Python函数2

空函数

1
2
def nop():
pass

函数参数

默认参数

1
2
3
4
5
6
7
8
9
10
11
def involution(x,n=2):
s=1
while n>0:
n=n-1
s=s*x
return s

print(involution(6))
print(involution(5,3))
##output:36
##output:125

可变参数

1
2
3
4
5
6
7
8
9
10
def calc(*numbers):
s=0
for n in numbers:
s=s+n*n
return sum

print(calc(1,2,3))
print(calc(1,3,5,7))
##output:14
##output:84

任意数相加

1
2
3
4
5
6
7
8
def calc(*numbers):
sum=0
for i in numbers:
sum=sum+i
return sum

print(calc(1,2,3,4,5))
##output:15

平均数

1
2
3
4
5
6
7
8
9
10
def calc(*numbers):
sum=0
for n in numbers:
sum=sum+n
if len(numbers)>0:
avg=sum/len(numbers)
return avg

print(calc(1,2,3,4,5))
##output:3.0

匿名函数

lambda x: x*x (关键字lambda表示匿名函数,冒号前的x表示函数参数,后边是表达式)

1
2
3
4
5
6
7
f1=lambda x:x*x
print(f1(5))
##output:25

f2=lambda x,y,z:x+y+z
print(f2(4,5,6))
##output:15