今日内容大纲
1.函数的初识
2.函数的返回值
3.函数的参数
1.函数的初识
def关键字 空格 函数名(与变量命名要求相同): 英文的冒号
函数体
执行函数 :函数名 +()
函数是以功能为导向的,
def login():
pass
def register():
pass
2.函数的返回值
return: 1)函数中遇到return 结束函数,下面代码不执行。
2)将函数里面的值返回给函数的执行者(调用者)。
第一种情况:
只有return,返回None
第二种情况:
return None
第三种情况:
return 单个值(返回的值与单个值的类型相同)
第四种情况:
return 多个值 以元组的形式返回给函数的调用者。
补充:
什么是None?
所有的空集合,空列表,空字典.... --->None
例1:函数中遇到return 结束函数,下面代码不执行
def tes():
print(111)
print(222)
return #遇到return终止函数执行
print(333)
tes()
执行结果:
111
222
例2:只有return,返回None
def tes():
return
print(tes())
执行结果:
None
例3:return None
def tes():
return None
print(tes())
执行结果:
None
例4:return 单个值(返回的值与单个值的类型相同)
def tes():
return 11
print(tes(),type(tes()))
执行结果:
11 <class 'int'>
例5:return 多个值 以元组的形式返回给函数的调用者
def tes():
return 11, "afda", [11, 22, 33], (111,"asb",),{"name":"alex"}
print(tes(),type(tes()))
执行结果:
(11, 'afda', [11, 22, 33], (111, 'asb'), {'name': 'alex'}) <class 'tuple'>
例6:写一个功能与 len()函数形同的函数
def my_len(data):
"""计算数据的长度"""
count = 0
for i in data:
count += 1
return count
li = [11, 22, 33, 44, 55, 66, 77]
print(my_len(li))
s = "agjkgjk"
print(my_len(s))
3.函数的参数
3.1 实参角度
位置参数
一一对应,实参形参数量相等
关键字参数
一一对应,实参形参数量相等,实参顺序可变
混合参数 (位置参数,关键字参数)
关键字参数必须在位置参数后面
例1:位置参数,需要一一对应,实参形参数量相等
def tes(a, b, c):#形参
return a, b, c
print(tes(11, 22, 33))#实参
例2:关键字参数,一一对应,实参形参数量相等,实参顺序可变
def tes(a, b, c):
return a, b, c
print(tes(a = 11, c = 22, b = 33))
例3:混合传参,关键字参数必须在位置参数后面
def tes(a, b, c):
return a, b, c
print(tes(11, 22, c = 33))
def tes(a, b, c):
return a, b, c
print(tes(11, c = 33,b = 44))
def tes(a, b, c):
return a, b, c
print(tes(11, 33,b = 44)) #报错,原因:b有多个值传入
补充:三元运算符
例4:比较两个数大小,将大数返回
def max(x, y):
if x > y:
return x
else:
return y
print(max(100, 99))
运用三元运算:x if x > y else y
def max(x, y):return x if x > y else y
print(max(100, 99))
3.2 形参角度
位置参数
一一对应,实参形参数量相等
默认参数
默认参数必须放在形参的位置参数后面
默认参数不传值则为默认值,传值则覆盖默认值。
动态参数
例1:位置参数, 一一对应,实参形参数量相等
def tes(a, b, c):
return a, b, c
print(tes(11, 33, 44))
例2:默认参数必须放在形参的位置参数后面,默认参数不传值则为默认值
def tes(a, b, c = 44):
return a, b, c
print(tes(11, 33))
执行结果:
(11, 33, 44)
例3:默认参数必须放在形参的位置参数后面,默认参数传值则覆盖默认值。
def tes(a, b, c = 44):
return a, b, c
print(tes(11, 33, 66))
执行结果:
(11, 33, 66)
例4:往文件追加模式,调用函数,录入用户姓名,性别
def personal_info(x,y = "男"):
with open("用户信息",encoding="utf-8",mode="a") as f1:
f1.write("姓名:{} 性别:{}\n".format(x, y))
while True:
s1 = input("请输入姓名:(q/Q退出)").strip()
if s1.upper() == "Q":
break
s2 = input("请输入性别:(q/Q退出)").strip()
if s2.upper() == "Q":break
elif s2 == "":personal_info(s1)
else:personal_info(s1,s2)