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(),
Since you are writing a generator, why not use two yields, to save doing the extra shuffle?
.....
Python is a dynamically typed language. the type of a variable is determined at runtime and it can vary as the execution is in progress. Here at first, you have declared a to hold an integer type and later you have assigned a function to it and so its type now became a function.
you are trying to apply 'a' as an argument to range() function which expects an int arg but you have in effect provided a function variable as argument.
the corrected code should be
this will work
You are giving
a
too many meanings:vs.
You won't run into the problem (as often) if you give your variables more descriptive names (3 different uses of the name
a
in 10 lines of code!):and change
range(a)
torange(amount)
.Also you can try the closed form solution (no guarantees for very large values of n due to rounding/overflow errors):
i like this version: