1.递归 object--对象
递归(recursion):
函数自身调用自身
2.求1~100的和
def count(num):# n + (n-1) + ... + 1if num == 1:return 1return num + (count(num - 1))print(count(100))
3.求Fibonacci
0 1 1 2 3 5 8 13 21 34 55 ..., 0+1=1 1+1=2 1+2=3 3+2=5 5+3=8
方法一:
def fib(n):a, b = 0, 1while a < n:print(a, end=' ')a, b = b, a+bprint() fib(1000) # 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
方法二:
递归求fib
def fib(n):if n == 1:return 0if n == 2:return 1return fib(n - 1) + fib(n - 2)print(fib(5))
第5项是3