Python學習入門基礎教程(learning Python)--2.3.3Python函數型參詳解

本節討論Python下函數型參的預設值問題。

   Python在設計函數時,可以給型參預設缺省值,當用戶調用函數時可以不輸入實參。如果用戶不想使用缺省預設值則需要給型參一一賦值,可以給某些型參賦值或不按型參順序用表達式給型參賦值,說起來有些繞,我們看看例子好了!

  1. #define function: area with two args

  2. def area(width = 10, height = 10):  

  3.     z = width * height  

  4. print(z)  

  5. #define fucntion: main

  6. def main():  

  7. #call function area

  8. print("prototype: area(width = 10, height = 10):")  

  9. print("area()")  

  10.     area()  

  11. print("area(20)")  

  12.     area(20)  

  13. print("area(width = 20)")  

  14.     area(width = 20)  

  15. print("area(height = 30)")  

  16.     area(height = 30)  

  17. print("area(20, 30)")  

  18.     area(20, 30)  

  19. print("area(height = 30, width = 30)")  

  20.     area(height = 30, width = 30)  

  21. #entry of programme

  22. main()  

代碼第2~4行是採用預設型參值的方式定義了一個函數area。好處是在函數調用時可以不輸入實參(第11行),用戶函數調用時可以依據自己的需求修改或者說傳入型參(第13行改變了width的值,而height的值仍使用預設值)(第19行,修改width的值爲20,height的值爲30),當然也可以不按型參順序賦值(第21行),程序運行結果如下。

  1. prototype: area(width = 10, height = 10):  

  2. area()  

  3. 100

  4. area(20)  

  5. 200

  6. area(width = 20)  

  7. 200

  8. area(height = 30)  

  9. 300

  10. area(20, 30)  

  11. 600

  12. area(height = 30, width = 30)  

  13. 900

    Python很強大!


呵呵


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章