# python 函数②

157人阅读 评论(0)

fact(n) = n! = 1 * 2 * 3 * ... * (n-1) * n = (n-1)! * n = fact(n-1) * n

def fact(n):
if n==1:
return 1
return n * fact(n - 1)

>>> fact(1)
1
>>> fact(5)
120

===> fact(5)
===> 5 * fact(4)
===> 5 * (4 * fact(3))
===> 5 * (4 * (3 * fact(2)))
===> 5 * (4 * (3 * (2 * fact(1))))
===> 5 * (4 * (3 * (2 * 1)))
===> 5 * (4 * (3 * 2))
===> 5 * (4 * 6)
===> 5 * 24
===> 120

def power(x, n):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
print power(2,3)#ok
print power(2）#error

# OK:
def fn1(a, b=1, c=2):
pass
# Error:
def fn2(a=1, b):
pass

### 任务

?不会了怎么办

def greet(name='world'):
print 'Hello, ' + name + '.'
greet()
greet('Bart')
Hello, world.
Hello, Bart.

def fn(*args):
print args

>>> fn()
()
>>> fn('a')
('a',)
>>> fn('a', 'b')
('a', 'b')
>>> fn('a', 'b', 'c')
('a', 'b', 'c')

def average(*args):
...

>>> average()
0
>>> average(1, 2)
1.5
>>> average(1, 2, 2, 3, 4)
2.4

### 任务

?不会了怎么办

def average(*args):
sum = 0.0
if len(args) == 0:
return sum
for x in args:
sum = sum + x
return sum / len(args)
print average()
print average(1, 2)
print average(1, 2, 2, 3, 4)

或者

def average(*args):

if len(args)!=0:
return sum(args)*1.0/len(args)
else:
return 0.0

0
0

个人资料
• 访问：28634次
• 积分：1306
• 等级：
• 排名：千里之外
• 原创：80篇
• 转载：41篇
• 译文：13篇
• 评论：0条
阅读排行
最新评论