Reputation: 83
The following Fibonacci function doesn't work:
def fib():
n = int(input("Nth term "))
if n == 0:
return 0
elif n == 1:
return 1
else:
return (fib(n-1) + fib(n-2))
print(fib())
But this exponent function does
def hj():
num1 = int(input("Enter your number: "))
num2 = int(input("enter another number: "))
return num1**num2
print(hj())
What could be the reason as to why a of the same form works for one application but doesn't for the other?
Upvotes: 0
Views: 57
Reputation: 1415
In your code fib()
has no parameters, but you are calling you function like this which is wrong in that case fib(n-1)
and You should not taking user input inside a recursive function:
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
n = int(input("Nth term "))
print(fib(n))
Upvotes: 1
Reputation: 1421
You're asking for user input every time fib()
gets called. Lift it out of the function.
Also fib()
has no parameters, but you try to call fib(n-1)
Refactor to:
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return (fib(n-1) + fib(n-2))
n = int(input("Nth term "))
print(fib(n))
Upvotes: 1