Python迭代斐波纳契语

时间:2018-09-02 01:08:06

标签: python fibonacci

听,我知道有关于此的一千篇文章,而我花了三个小时来研究它们。我知道此代码无法正常工作很简单,但我无法弄清楚。当它运行时,我只希望它返回第n个项。我是python的新手,也许有一些我不明白的逻辑。所以当我这样做时:

n = int(input("What Fibonacci number would you like to find? "))

def fib(n):
    i = 0
    present = 1
    previous = 0

    while i < n:
        nextterm = present + previous
        present = previous
        previous = nextterm
        i = i + 1
        print nextterm

print(fib(n))

我明白了:

1
1
2
3
5
None

当我这样做时:

n = int(input("What Fibonacci number would you like to find? "))

def fib(n):
    i = 0
    present = 1
    previous = 0

    while i < n:
        nextterm = present + previous
        present = previous
        previous = nextterm
        i = i + 1
        return nextterm

print(fib(n))

我刚得到“ 1”

我花了很多时间在这上面,我很困惑。有人请修理我!

4 个答案:

答案 0 :(得分:2)

您只是忘了返回值:

n = int(input("What Fibonacci number would you like to find? "))

def fib(n):
    i = 0
    nextterm = 1
    present = 1
    previous = 0

    while i < n:
        nextterm = present + previous
        present = previous
        previous = nextterm
        i = i + 1
        #print nextterm

    return nextterm

print(fib(n))

答案 1 :(得分:0)

在第一种情况下,您没有返回任何内容,因此当您print(fib(n))时,由于python没有找到任何return语句,因此它返回None,这是您看到的最后一个打印内容,其他则是循环内的那些。在第二种情况下,您在return循环内有while语句,因此当它执行第一次迭代时,它将返回1,超出框架,并且不执行其他任何迭代,因此它只会打印'1'

答案 2 :(得分:0)

因为return仅返回一次,所以第一次返回就完成了,

更清晰的示例:

 def f():
     return 'good'
     return 'bad'

现在:

print(f())

返回:

'good'

另一方面,这也是一种解决方法:

n = int(input("What Fibonacci number would you like to find? "))

def fib(n):
    l=[]
    i = 0
    present = 1
    previous = 0

    while i < n:
        nextterm = present + previous
        present = previous
        previous = nextterm
        i = i + 1
        l.append(nextterm)
    return '\n'.join(str(i) for i in l)
print(fib(n))

或者print,但不执行其他打印:

n = int(input("What Fibonacci number would you like to find? "))

def fib(n):
    i = 0
    present = 1
    previous = 0

    while i < n:
        nextterm = present + previous
        present = previous
        previous = nextterm
        i = i + 1
        print(nextterm)
fib(n)

答案 3 :(得分:-1)

def fibonacci():
    num = int(input("How many numbers that generates?:"))
    i = 1
    if num == 0:
        fib = []
    elif num == 1:
        fib = [1]
    elif num == 2:
        fib = [1,1]
    elif num > 2:
        fib = [1,1]
        while i < (num - 1):
            fib.append(fib[i] + fib[i-1])
            i += 1
    return fib
print(fibonacci())