How do I print a fibonacci sequence to the nth number in Python?

前端 未结 7 1612
忘了有多久
忘了有多久 2020-12-31 22:24

I have a homework assignment that I\'m stumped on. I\'m trying to write a program that outputs the fibonacci sequence up the nth number. Here\'s what I have so far:

7条回答
  •  粉色の甜心
    2020-12-31 22:42

    for a recursive solution:

    def fib(n):
        if n == 0:
            return 0
        elif n == 1:
            return 1
        else:
            return fib(n-1) + fib(n-2)
    x=input('which fibonnaci number do you want?')
    print fib(x)
    

    explanation: if n is 0, then ofcourse the '0th' term is 0, and the 1st term is one. From here, you know that the next numbers will be the sum of the previous 2. That is what's inferred by the line after the else.

提交回复
热议问题