I need to make a program that asks for the amount of Fibonacci numbers printed and then prints them like 0, 1, 1, 2... but I can't get it to work. My code looks the following:
a = int(raw_input('Give amount: '))
def fib():
a, b = 0, 1
while 1:
yield a
a, b = b, a + b
a = fib()
a.next()
0
for i in range(a):
print a.next(),
Simple way to print Fibonacci series till n number
I would use this method:
Python 2
Python 3
To get the fibonacci numbers till any number (100 in this case) with generator, you can do this.
I've build this a while ago:
No that
fab
will grow over time, so it isn't a perfect solution.You had the right idea and a very elegant solution, all you need to do fix is your swapping and adding statement of a and b. Your yield statement should go after your swap as well
a, b = b, a + b ####
should bea,b = a+b,a #####
Your
a
is a global name so-to-say.Whenever Python sees an
a
, it thinks you are talking about the above one. Calling it something else (elsewhere or here) should help.