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)
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)
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)))
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.