您好,登錄后才能下訂單哦!
多類型傳值:
def fun(x,y):
return x +y
print fun(3,5)
8
print fun(*t)
3
def fun(x,y,z):
return x + y + z
t1 = (1,2,3)
fun(*t1)
6
fun(*(2,4,5))
11
fun(1,*t)
4
print t
(1, 2)
fun(x=1,y=3,z=5)
9
>>> dic = {'x':1,'y':3,'z':6}
>>> fun(**dic)
10
冗余參數(shù):
>>> def fun(x,*args,**kwargs):
... print x
... print args
... print kwargs
...
>>> fun(1)
1
()
{}
>>> fun(1,2)
1
(2,)
{}
>>> fun(1,2,3)
1
(2, 3)
{}
>>> t
(1, 2)
>>> fun(1,2,3,'a',[1,2],*t,a=3,**{'t':11,'p':22})
1
(2, 3, 'a', [1, 2], 1, 2)
{'a': 3, 'p': 22, 't': 11}
遞歸的注意事項:
必須有最后的默認(rèn)結(jié)果:
if n == 0
遞歸參數(shù)必須向默認(rèn)結(jié)果收斂的:
factorial(n-1)
階乘腳本:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Feng Xiaoqing
# jiecheng.py
# ======================
def factorial(n):
sum = 0
for i in range(1,n+1):
sum += i
return sum
print factorial(100)
另外一種方法:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
print factorial(5)
求1-100相加的和:
def factorial(n):
if n == 0:
return 0
else:
return n + factorial(n-1)
print factorial(100)
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。