3、函数的参数:
3、函数的参数:
实参角度:
(1)位置参数:
一一对应,实参形参数量相等
ps:
def tes(a, b, c): print(111) print(a, b, c) ret = tes(111, 'asdf', [1, 2, 3]) print(ret)
(2)关键字参数:
一一对应,实参形参数量相等,实参顺序可变
ps:
def func(x, y): print(x, y) func(y=100, x=7)
(3)混合参数:(位置参数,关键字参数)
关键字参数在位置参数的后面
ps:
def func(x, y, z): print(x, y, z) func(100, 90, z=7) #混合参数,位置参数必须在关键字参数的前面
形参角度:
(1)位置参数:
一一对应,实参形参数量相等
ps:
def func2(y, x): print(x, y) func2(1, 20)
(2)默认参数:
默认参数必须放在形参的位置参数后面
默认参数不传值则为默认值,传值则覆盖默认值
ps:
def func2(y, x, z=100): print(x, y, z) func2(1, 50, 300)
(3)动态参数:*args,**kwargs
# 用户传入到函数中的实参数量不定时,或者是为了以后拓展,
# 此时要用到动态参数*args,**kwargs(万能参数。)
# *args接收的是所有的位置参数。
# **kwargs接收的是所有的关键字参数。
# 位置参数,*args,默认参数, **kwargs
形参顺序:位置参数,*args,默认参数, **kwargs
def func2(a, b, *args, sex='男',age=20, **kwargs): print(a) print(b) print(args) print(sex) print(age) print(kwargs) func2(1, 2, 5, 6, 7, 8, 9,sex='男', x=6, y=5, name='alex')
def func3(*args,**kwargs): # 函数的定义 *用意是聚合。 print(args) print(kwargs) # *的魔性用法 l1 = [1, 2, 3,[4,5,6]] l2 = [11, 21, 32] s1 = 'fjskalgf' s2 = 'fjskrrrf' tu1 = (1, 2, 3) tu2 = (11, 22, 33) dic ={'name': 'alex'} dic1 ={'age': 1000} func3(*l1, **dic, **dic1) # 在函数的执行时,*的用意是打撒。
def func1(*args,**kwargs): # print(args) # (1, 2, 3) # print(*args) # print(*(1,2,3)) # print(kwargs) # {'name':'alex'} print(**kwargs) # print(name='alex') func1(*[1,2,3], **{'name':'alex'})
(1)
def my_len(a): #形式参数 count = 0 for i in a: count += 1 return count s1 = 'fkdshadslfs' l1 = [1, 2, 3, 4, 5] print(my_len(l1)) #实际参数 print(my_len(s1)) #实际参数
三元运算
x = 99 y = 100 c = x if x > y else y print(c)
(2)函数比大小
def max(x, y): return x if x > y else y print(max(100, 90))
ps:将员工姓名和性别录入到文件中
def input_information(name, sex='男'): with open('information1', encoding='utf-8', mode='a') as f1: f1.write('姓名:{}\t 性别:{}\n'.format(name, sex)) while True: msg = input('请输入员工的姓名,性别/Q或者q退出').strip() if msg.upper() == 'Q': break msg = msg.replace(',', ',') if ',' in msg: msg = msg.split(',') name, sex = msg input_information(name, sex) else: input_information(msg)

浙公网安备 33010602011771号