1、关于函数的调用,简单小例子:
>>> def fun():
print(test)
>>> test='ni hao ma ?'
>>> fun()
ni hao ma ?
>>> def fun(test):
print('输出内容为: ’,test)
>>> test1='ni hao ma ?'
>>> fun(test1)
输出内容为:ni hao ma ?
>>> fun('nihao')
nihao
>>> def fun(x,y=34):
if x==y:
print(x,"等于",y)
else:
if x>y:
print(x,"大于",y)
else:
print(x,"小于",y)
>>> fun(45)
45 大于 34
>>> fun(45,23)
45 大于 23
2、全局变量和局部变量
>>> x='你好吗?' x为全局变量,y为局部变量,通俗讲定义在函数外的变量叫全局变量,定义在函数内的叫局部变量
>>> def fun(y):
print(y,x)
>>> fun('李好)
李好 你好吗?
3、函数返回值的使用
>>> def fun(a,b):
return(a+b)
>>> z=fun(34,67)
>>> print(z)
101
4、关于return的用法:
>>> def fun(a,b):
if a>b:
return a
return b
>>> fun(34,45)
45
5、冗余参数处理
>>> def fun(a,b):
return a,b
>>> fun(34,56)
(34, 56)
>>> d={'a':34,'b':23}
>>> fun(**d)
(34, 23)
>>> def f(x,y):
if x==y:
print(x,"等于",y)
else:
print(x,"不等于",y)
>>> f(12,(12,34))
12 不等于 (12, 34)
>>> ni=(12,34)
>>> f(*ni)
12 不等于 34
>>> def f(x,*args,**kwargs):
print (x)
print(args)
print(kwargs)
>>> f(1)
1
()
{}
>>> f(1,2,34,5)
1
(2, 34, 5)
{}
>>> f(x=1,y=2)
1
()
{'y': 2}
>>> f(1,2,34,5,x=45,y=20)
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
f(1,2,34,5,x=45,y=20)
TypeError: f() got multiple values for argument 'x' #因为在传值1已经赋值给x,在执行x=45时需再次赋值,所以会报错,不能如此写