0

Suppose I input n=5, how do i get the first 5 numbers as the output and not 10?

    #fibonacci sequence
n=int(input('Enter number of numbers: '))
a=1
b=0
for i in range(1,n+1):
    a=a+b
    b=a+b
    print(a)
    print(b)
Rachana
  • 11
  • 2

3 Answers3

1

The way you are adding a and b in the for loop is wrong. If you use print twice it will print twice per loop.

n=int(input('Enter number of numbers: '))
a=1
b=0
for i in range(1,n+1):
    a, b = a + b, a
    print(a)
Prudhvi
  • 1,095
  • 1
  • 7
  • 18
0

Try this out:

n = int(input('Enter number of numbers: '))
def fib(n):
    curr, next_ = 1, 1
    for _ in range(n):
        yield curr
        curr, next_ = next_, curr + next_
print(list(fib(n)))
ErdoganOnal
  • 800
  • 6
  • 13
0
n=int(input('Enter number of numbers: '))
a=1
b=0
for i in range(1,n+1):
    a, b = a + b, a
    print(a)

The problem with your approach is you go with step 2 each time. For example on one iteration you go from a=5, b=3 to a=13, b=8. So there is 2 * 5 outputs.

V. Ayrat
  • 2,499
  • 9
  • 10