目录
形参和实参
形参用于定义, 实参用于调用
def printMax(a,b):
"""比较两个函数的大小,输出较大值"""
if a > b:
print(a,'较大值')
else:
print(b,'较大值')
#调用自定义函数,比较两个数大小
printMax(19,2)
printMax(19,100)
'''
执行结果
19 较大值
100 较大值
上面的printMax函数中,在定义时写的printMax(a,b),a和b称为"形式参数",
简称"形参";也就是说,形式参数实在定义函数时使用的;形式参数的命名只要符合
"标识符"命名规则即可;
在调用函数时,传递的参数称为"实际参数",简称"实参";上面代码中,
printMax(19,2),19和2就是实际参数
'''
输出:
D:\wwwroot\pyiteam\venv\Scripts\python.exe D:/wwwroot/pyiteam/mypy01.py
19 较大值
100 较大值
文档字符串
文档字符串(函数的注释)
程序的可读性最重要, 一般建议在函数体开始的部分附上函数定义说明, 这就是”文档字符串”, 也有人称为”函数的注释”; 我们通过三个单引号或者三个双引号来实现, 中间可以加入多行文字进行说明;
我们调用函数help(函数名.__doc__)可以打印输出函数的文档字符串;
def printTest(n):
'''传入n,输出n*3'''
print(n*3)
help(printTest.__doc__)
printTest(3) #传入3,打印出9
输出:
D:\wwwroot\pyiteam\venv\Scripts\python.exe D:/wwwroot/pyiteam/mypy01.py
No Python documentation found for '传入n,输出n*3'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.
9
Process finished with exit code 0
函数的返回值
return 返回值要点:
- 如果函数体中包含return语句,则结束函数执行并返回值;
- 如果函数体中不包含return语句,则返回None值;;
- 要返回多个返回值,使用列表,元组,字典,集合将多个值”存起来”即可;
def printTest(n):
return n
print(123)#return上一步已经结束,这一步不会打印出来
a = printTest(3) #有return,相当于拿到这个值,可以给其他变量赋值
print(a)
def printTest1():
2>1
print(printTest1()) #函数体重不包含return语句,返回None值
def test03(x,y,z):
return [x*3,y*2,z*5]
print(test03(2,7,1))
输出:
D:\wwwroot\pyiteam\venv\Scripts\python.exe D:/wwwroot/pyiteam/mypy01.py
3
None
[6, 14, 5]
Process finished with exit code 0