Python学习入门基础教程(learning Python)--2.3.3Python函数型参详解
2013-08-23 21:57
961 查看
本节讨论Python下函数型参的预设值问题。 Python在设计函数时,可以给型参预设缺省值,当用户调用函数时可以不输入实参。如果用户不想使用缺省预设值则需要给型参一一赋值,可以给某些型参赋值或不按型参顺序用表达式给型参赋值,说起来有些绕,我们看看例子好了![python]view plaincopy#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行),程序运行结果如下。[python]view plaincopyprototype: 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很强大!
呵呵
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行),程序运行结果如下。[python]view plaincopyprototype: 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很强大!
呵呵
相关文章推荐
- Python学习入门基础教程(learning Python)--2.3.3Python函数型参详解
- Python学习入门基础教程(learning Python)--2.3.4Python函数返回值
- Python学习入门基础教程(learning Python)--3.3.1 Python下的布尔表达式
- Python学习入门基础教程(learning Python)--5.2 Python读文件基础
- Python学习入门基础教程(learning Python)--8.1 字典数据添加与删除
- Python学习入门基础教程(learning Python)--1.2Python输入输出与处理 .
- Python学习入门基础教程(learning Python)--2.3.5Python返回多个值问题
- Python学习入门基础教程(learning Python)--3.3.1 Python下的布尔表达式
- Python学习入门基础教程(learning Python)--2 Python简单函数设计 .
- Python学习入门基础教程(learning Python)--5.6 Python读文件操作高级
- Python学习入门基础教程(learning Python)--3 Python分支结构和布尔逻辑
- Python学习入门基础教程(learning Python)--6.4 Python的list与函数
- Python学习入门基础教程(learning Python)--1.2.1 Python输出语句print基本使用 .
- Python学习入门基础教程(learning Python)--2.1 Python下自定义函数 .
- Python学习入门基础教程(learning Python)--2.2.1 Python下的变量解析
- Python学习入门基础教程(learning Python)--5.1 Python下文件处理基本过程
- Python学习入门基础教程(learning Python)--3.3.3 Python逻辑关系表达式
- Python学习入门基础教程(learning Python)--3.2 if-else分支语句
- Python学习入门基础教程(learning Python)--2.2 Python下的变量基础
- Python学习入门基础教程(learning Python)--3.1Python的if分支语句