python学习-循环
1.正序循环
def xunhuan(i):
if i<10:
print(i)
else:
return
xunhuan(i+1)
if __name__=="__main__":
xunhuan(1)
2.倒叙循环
def xunhuan(i):
if i<10:
xunhuan(i+1)
print(i)
else:
return
if __name__=="__main__":
xunhuan(1)
3.九九乘法表
def jiujiu(n):
if n<10:
for i in range(1,n+1):
print ("%d*%d=%d"%(i,n,i*n),end="\t")
print()
jiujiu(n+1)
if __name__=="__main__":
jiujiu(1)
非递归版本
def jiujiu():
for k in range(1,10):
for i in range(1,k+1):
print ("%d*%d=%d"%(i,k,i*k),end="\t")
print()
if __name__=="__main__":
jiujiu()
4.斐波那契数列
def f(n):
if n>1:
return f(n-1)+f(n-2)
else:
return 1
if __name__=="__main__":
for i in range(0,10):
print(f(i))
非递归版
def f(n):
if n>1:
a=1
b=1
fibN=0
for i in range(2,n+1):
fibN=a+b
a=b
b=fibN
return fibN
else:
return 1
if __name__=="__main__":
for i in range(0,10):
print(f(i))
5.舍罕王赏麦
def f(n):
if n>1:
sum,k=f(n-1)
k=k*2
sum=sum+k
return sum,k
else:
return 1,1
if __name__=="__main__":
print(f(64))
|