0

I wrote a short code which outputs the first n numbers of the Fibonacci sequence where n is the value of the passed parameter and each number is printed in a new line. My problem is that the output isn't starting at 0, it starts at 1. How do I also get the 0 in the output?

def fibonacci(n):
    fib1 = 0
    fib2 = 1
    for x in range(0,n):
        print("%d\n" %(fib2), end = " ")
        next = fib1 + fib2 
        fib1 = fib2
        fib2 = next

So this is the output, why are the numbers after the first one moved in? output

666
  • 5
  • 1
  • 3

3 Answers3

0
def fibonacci(n):
    fib1 = 0
    fib2 = 1
    for x in range(0,n):
        print("%d\n" %(fib1), end = " ")
        next = fib1 + fib2 
        fib1 = fib2
        fib2 = next

Simple print fib1 instead of fib2 at line #5 How do you expect output 0 at start if you printed fib2 which is 1

Hisham___Pak
  • 1,472
  • 1
  • 11
  • 23
  • thank you, stupid mistake! lol But another question: why does my output write the 0 and the 1 straight among themselves but all following numbers moved into? – 666 Nov 03 '19 at 11:14
0

You can use:

def fibonacci(n):
    fib1 = 0
    fib2 = 1
    for x in range(0, n):
        print("%d" %(fib1))
        fib1, fib2 = fib2, fib1 + fib2

Alternatively, you can just switch the values of fib1 and fib2 without messing with your code any more.

peki
  • 669
  • 7
  • 24
0

as mentioned in other examples you can solve your problem .. I am sharing few more ways to do it.. shorter code

 def fibonacci_fun(n):
  a, b = 0, 1
  for x in range(2, n):
    print('%s' % a)
    a, b = b, a+b

 fibonacci_fun(n)

another way using while loop

def fibonacci(n):
  a, b = 0, 1
  while a <= n:
    print(a)
    a, b = b, a+b

fibonacci(n)
Jahanzeb Nawaz
  • 1,128
  • 12
  • 11