Python学习入门基础教程(learning Python)--2.3.3Python函数型参详解
本节讨论Python下函数型参的预设值问题。
Python在设计函数时,可以给型参预设缺省值,当用户调用函数时可以不输入实参。如果用户不想使用缺省预设值则需要给型参一一赋值,可以给某些型参赋值或不按型参顺序用表达式给型参赋值,说起来有些绕,我们看看例子好了!
#define function: area with two args
def area(width = 10, height = 10):
     z = width * height
     print(z)
#define fucntion: main 
def main():
     #call function area
     print("prototype: area(width = 10, height = 10):")
     print("area()")
     area()
     print("area(20)")
     area(20)
     print("area(width = 20)")
     area(width = 20)
     print("area(height = 30)")
     area(height = 30)
     print("area(20, 30)")
     area(20, 30)
     print("area(height = 30, width = 30)")
     area(height = 30, width = 30)
#entry of programme
main()
代码第2~4行是采用预设型参值的方式定义了一个函数area。好处是在函数调用时可以不输入实参(第11行),用户函数调用时可以依据自己的需求修改或者说传入型参(第13行改变了width的值,而height的值仍使用预设值)(第19行,修改width的值为20,height的值为30),当然也可以不按型参顺序赋值(第21行),程序运行结果如下。
prototype: area(width = 10, height = 10): area() 100 area(20) 200 area(width = 20) 200 area(height = 30) 300 area(20, 30) 600 area(height = 30, width = 30) 900
Python很强大!
呵呵
 
 
 
 
 
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号