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(),
Here, we store the number of terms in nterms . We initialize the first term to 0 and the second term to 1. If the number of terms is more than 2, we use a while loop to find the next term in the sequence by adding the preceding two terms. We then interchange the variables (update it) and continue on with the process.
# Python program to display the Fibonacci sequence def recur_fibo(n): if n <= 1: return n else: return(recur_fibo(n-1) + recur_fibo(n-2)) nterms = 10 # check if the number of terms is valid if nterms <= 0: print("Plese enter a positive integer") else: print("Fibonacci sequence:") for i in range(nterms): print( ...
We have to find the nth Fibonacci term by defining a recursive function. So, if the input is like n = 8, then the output will be 13 as first few Fibonacci terms are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34... otherwise, return solve(n - 1) + solve(n - 2)
I would use this method:
Python 2
a = int(raw_input('Give amount: ')) def fib(n): a, b = 0, 1 for _ in xrange(n): yield a a, b = b, a + b print list(fib(a))
Python 3
a = int(input('Give amount: ')) def fib(n): a, b = 0, 1 for _ in range(n): yield a a, b = b, a + b print(list(fib(a)))
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With