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 followi
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
a = int(raw_input('Give amount: '))
def fib():
a, b = 0, 1
while 1:
yield a
a, b = b, a + b
b = fib()
b.next()
for i in range(a):
print b.next(),
this will work
You are giving a
too many meanings:
a = int(raw_input('Give amount: '))
vs.
a = fib()
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!):
amount = int(raw_input('Give amount: '))
and change range(a)
to range(amount)
.
def Fib(n):
i=a=0
b=1
while i<n:
print (a)
i=i+1
c=a+b
a=b
b=c
Fib(input("Please Enter the number to get fibonacci series of the Number : "))
To get the fibonacci numbers till any number (100 in this case) with generator, you can do this.
def getFibonacci():
a, b = 0, 1
while True:
yield b
b = a + b
a = b - a
for num in getFibonacci():
if num > 100:
break
print(num)
Below are two solution for fiboncci generation:
def fib_generator(num):
'''
this will works as generator function and take yield into account.
'''
assert num > 0
a, b = 1, 1
while num > 0:
yield a
a, b = b, a+b
num -= 1
times = int(input('Enter the number for fib generaton: '))
fib_gen = fib_generator(times)
while(times > 0):
print(next(fib_gen))
times = times - 1
def fib_series(num):
'''
it collects entires series and then print it.
'''
assert num > 0
series = []
a, b = 1, 1
while num > 0:
series.append(a)
a, b = b, a+b
num -= 1
print(series)
times = int(input('Enter the number for fib generaton: '))
fib_series(times)