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很强大!


呵呵


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