函数
1. 无参函数的定义
def functionname([function args]):
"""函数的注释"""
function body
return[表达式]
- 函数名应该符合标识符标准
- 以数字、字幕、下划线组成
- 不能以数字开头
- 不能和关键字重名
- 函数体应该保持4个空格的缩进
- 函数的注释应该写在函数定义的下方一行
- 函数的定义上方应该保证两行空格(PEB8规范)
- return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None
- 函数的参数分为以下四种:
1.必需参数
2.关键字参数
3.默认参数
4.不定长参数
demo
# 计算面积函数
def area(width, height):
return width * height
def print_welcome(name):
print("Welcome", name)
print_welcome("Runoob")
w = 4
h = 5
print("width =", w, " height =", h, " area =", area(w, h))
result
Welcome Runoob
width = 4 height = 5 area = 20
2. 关键字参数
关键字参数就是在调用函数时使用关键字传入参数的值,使用关键字参数允许函数调用时参数的顺序与声明时不一致,因为 Python 解释器能够用参数名匹配参数值。
#!/usr/bin/python3
#可写函数说明
def printinfo( name, age ):
"打印任何传入的字符串"
print ("名字: ", name)
print ("年龄: ", age)
return
#调用printinfo函数
printinfo( age=50, name="runoob" )
名字: runoob
年龄: 50
3. 默认参数
调用函数时,如果没有传递参数,则会使用默认参数。以下实例中如果没有传入 age 参数,则使用默认值。
def studentinfo(name, age=18):
"""
student info
:param name:
:param age:
:return:
"""
print("name = ", name, ",age = ", age)
return
studentinfo("david", 20)
studentinfo("ben")
result
name = david ,age = 20
name = ben ,age = 18
4. 可变参数
在Python函数中,还可以定义可变参数。顾名思义,可变参数就是传入的参数个数是可变的,可以是1个、2个到任意个,还可以是0个。
可变参数的格式:
def functionname[*agrs]
"""function notes """
function body
return [*function return ]
传入的任意个参数会被组装成tuple。也可以将tuple前加*后传入。
def arbitrary_arguements(*args):
"""
变长参数
:param args:
:return:
"""
for s in args:
print(s)
return
arbitrary_arguements("a", "b")
arbitrary_arguements("c", "d", "e")
result:
a
b
c
d
e
网友评论