函数
def fun(parm…):
语句
返回值
eg
def arr(num):
fbi=[0,1]
for i in range(num-2):
fbi.append(fbi[-1]+fbi[-2])
return fbi
#参数,值传递
>>> def add(n):
n=n+1
>>>
>>> n=10
>>> add(n)
>>> n
10
#类似与C语言的指针
>>> def a(names):
names[0]="dog"
>>> name=['pig','pp']
>>> name
['pig', 'pp']
>>> a(name)
>>> name
['dog', 'pp']
>>>
#函数参数的关键参数
def printhello(str1,str2):
print(str1,str2)
printhello(str1='f',str2='x')
printhello(str2='x',str1='f')
def printhello1(str1='x',str2='1'):
print(str1,str2)
printhello1()
#收集参数
def printhello2(str1='x',*str2):
print(str1,str2)
printhello2('x',2,3,4);
>>x (2, 3, 4)
def printhello3(str1='x',**str2):
print(str1,str2)
printhello3('xx',x=1,y=2)
>>xx {'y': 2, 'x': 1}
#翻转收集参数
def add(x,y):
return (x+y)
parm=(1,2)
print(add(*parm))
>>3
def printparm(**parm):
print(parm)
printparm(x=1,y=2,z=3)
>>{'x': 1, 'y': 2, 'z': 3}
#变量的作用域
x =1;
def add1(y):
global x
x=x+1
return x
print(add1(2))
#递归
def X(n):
if n==1:
return 1
else:
return n*X(n-1)
print(X(5))
>>120
#
本文详细介绍了Python中函数的定义与使用,包括不同类型的参数传递方式:如值传递、引用传递,以及关键参数、收集参数等高级用法,并通过实例展示了递归函数的应用。

被折叠的 条评论
为什么被折叠?



