首页 > 代码库 > Python 斐波那契数列练习

Python 斐波那契数列练习

# coding=gbk# 迭代法---1def fibonacci (n):    if n == 0 or n == 1:        return n    else :         a = 0        b = 1               for i in range (n-1) :            t = a            a = b            b = a + t        return b   number = eval (input ("请输入您要计算的斐波那契数列的项\n"))cc= fibonacci (number)print (cc)# 迭代法---2def fibonacci2 (n):    print ("n is "+str(n))    terms = [0,1]    i = 2    while i <= n :        terms.append(terms[i-1] + terms[i-2])        i = i + 1    return terms[n]number = eval (input ("请输入您要计算的斐波那契数列的项\n"))cc= fibonacci2 (number)print (cc)     # 递归法---1def fibonacci1 (n):    print (n is + str(n))    if n == 0 or n == 1 :        return n    else :            return fibonacci1 (n - 1) + fibonacci1 (n - 2)            number = eval (input ("请输入您要计算的斐波那契数列的项\n"))cc= fibonacci1 (number)print (cc)

上面的代码参考的有别人的,遇到的问题有:

1 Error: SyntaxError: Non-UTF-8 code starting with ‘\xb5‘

原因是因为代码中含有非UTF-8的字符,可以在代码第一行加入命令:

# coding=gbk

Python 斐波那契数列练习