print(‘-------------无参函数--------------‘)
示范一:
def bar():
print(‘from bar‘)
def foo():
bar()
print(‘from foo‘)
foo() #from bar from foo
示范二:
def foo():
bar()
print(‘from foo‘)
def bar():
print(‘from bar‘)
foo() #from bar from foo
有参函数
def func(x,y):
print(x,y)
func(1,2) #1 2
空函数
def func(x,y):
pass
def interactive():
name=input(‘username>>>:‘)
age=input(‘age>>>:‘)
msg=‘名字:{} 年龄:{}‘.format(name,age)
print(msg)
interactive()
def add(x,y):
res=x+y
return res
res=add(20,34)
print(res) #54
def auth_user():
pass
def log_in():
pass
def ls():
pass #构思代码
def add(x,y):
res=x+y
return res
res=add(20,30)
print(res)
res=add(1,23)*10
print(res) #240
res=add(add(1,2),10)
print(res) #13
def func(x,y):
return
func()
def func(x,y):
return x
res=func(10,20)
print(res)
def func(x,y):
return 10,‘aa‘,[1,2]
res=func()
print(res,type(res))
def func(x,y):
print(x,y)
func(1,2)
def func(x,y):
print(x,y)
func(1,2)#1 2
a=1
b=2
func(a,b)#1 2
func(int(‘1‘),2) #1 2
def func(x,y):
print(x,y)
func(1,2) # 1 2
func(1,23,3) #报错 多一个
func(1,) #报错 少一个
def func(x,y):
print(x,y)
func(y=2,x=1) #1 2
func(1,y=2) #1 2
func(1,2,y=3)
func(1,2,y=3,x=3)
def func(x,y=2):
print(x,y)
func(x=1) # 1 2
func(x=1,y=9) # 1 9
def register(name,age,gender=‘男‘):
print(name,age,gender)
register(‘三炮‘,18)
register(‘二炮‘,18)
register(‘大炮‘,18)
register(‘村花‘,18,‘女‘)
>>>三炮 18 男
二炮 18 男
大炮 18 男
村花 18 女
def func(x,y=2):
pass
m=2
def func(x,y=m):
print(x,y)
func(1) # 1 2
m=2
def func(x,y=m):
print(x,y)
func(1)#1 2
m=[11,]
def func(x,y=m):
print(x,y)
m.append(333)
func(1) #1 [11, 333]
def func(x,y,z,l=None):
if l is None:
l=[]
l.append(x)
l.append(y)
l.append(z)
print(l)
func(1,2,3)
new_l=[111,222]
func(1,2,3,new_l)
def func(x,y,*z):
print(x,y,z)
func(1,2,3,4,5,6,7)#1 2 (3, 4, 5, 6, 7)
def my_sum(*args):
res=0
for item in args:
res+=item
return res
res=my_sum(1,2,3,4,)
print(res) #10
def func(x,y,z):
print(x,y,z)
func(*[1,2,3])#1 2 3
func(*[1,2]) #报错
l=[1,2,3]
func(*l) #1 2 3
def func(x,y,*args):
print(x,y,args)
func(1,2,[3,4,5,6]) #1 2 ([3, 4, 5, 6],)
func(1,2,3,4,5,6)
func(*‘hello‘) #h e (‘l‘, ‘l‘, ‘o‘)
def func(x,y,**kwargs):
print(x,y,kwargs)
func(1,y=2,a=1,b=2,c=3)#1 2 {‘a‘: 1, ‘b‘: 2, ‘c‘: 3}
def func(x,y,z):
print(x,y,z)
func(*{‘x‘:1,‘y‘:2,‘z‘:3}) #x y z
func(**{‘x‘:1,‘y‘:2,‘z‘:3}) #1 2 3
func(**{‘x‘:1,‘y‘:2}) #报错
func(**{‘x‘:1,‘a‘:4,‘y‘:2,‘z‘:3}) 报错
def func(x,y,**kwargs):
print(x,y,kwargs)
func(x=1,a=4,y=2,z=3) #1 2 {‘a‘: 4, ‘z‘: 3}
func(**{‘x‘:1,‘a‘:4,‘y‘:2,‘z‘:3}) #1 2 {‘a‘: 4, ‘z‘: 3}
def func(*args,**kwargs):
print(args)
print(kwargs)
func(1,2,3,4,5,6,7,8,x=1,y=2)
>>>(1, 2, 3, 4, 5, 6, 7, 8)
{‘x‘: 1, ‘y‘: 2}
def index(x,y,z,bbb):
print(‘index>>>‘,x,y,z,bbb)
def wrapper(a,b,c,d):
index(a,b,c,d)
wrapper(1,2,3,4) #index>>> 1 2 3 4
原文:https://www.cnblogs.com/www-521/p/13124175.html