Why doesn't this function give me an answer?
Question:
This is the code that I am running. No problem is coming up, but it doesn’t give me an answer either. I can’t find the problem.
def fibonacci(n):
if n <= 0:
return False
elif n == 1 or n == 2:
return 1
else:
count = 1
n1, n2 = 1, 1
while count <= n:
n1 = n2
newn = n2+n1
if n == count:
return newn
else:
count += 1
fibonacci(3)
Answers:
You have to use print
on a function call to see that function’s return unless you are calling the function from inside the REPL.
Using your example code, make this change:
print(fibonacci(3))
There are two other issues that I see:
The first is you start count at 1 even though
elif n == 1 or n == 2:
return 1
accounts for the first and second fibonacci number
The second is n1
and n2
are never updated
To address these, you can update your code like this
def fibonacci(n):
if n <= 0:
return False
elif n == 1 or n == 2:
return 1
else:
count = 3 # if you're in this part of the code, you must be at the 3rd fibonacci number
n1, n2 = 1, 1
while count <= n:
newn = n2+n1
if n == count:
return newn
else:
count += 1
n1 = n2
n2 = newn
for i in range(11):
print(i, fibonacci(i))
Output:
0 False
1 1
2 1
3 2
4 3
5 5
6 8
7 13
8 21
9 34
10 55
This is the code that I am running. No problem is coming up, but it doesn’t give me an answer either. I can’t find the problem.
def fibonacci(n):
if n <= 0:
return False
elif n == 1 or n == 2:
return 1
else:
count = 1
n1, n2 = 1, 1
while count <= n:
n1 = n2
newn = n2+n1
if n == count:
return newn
else:
count += 1
fibonacci(3)
You have to use print
on a function call to see that function’s return unless you are calling the function from inside the REPL.
Using your example code, make this change:
print(fibonacci(3))
There are two other issues that I see:
The first is you start count at 1 even though
elif n == 1 or n == 2:
return 1
accounts for the first and second fibonacci number
The second is n1
and n2
are never updated
To address these, you can update your code like this
def fibonacci(n):
if n <= 0:
return False
elif n == 1 or n == 2:
return 1
else:
count = 3 # if you're in this part of the code, you must be at the 3rd fibonacci number
n1, n2 = 1, 1
while count <= n:
newn = n2+n1
if n == count:
return newn
else:
count += 1
n1 = n2
n2 = newn
for i in range(11):
print(i, fibonacci(i))
Output:
0 False
1 1
2 1
3 2
4 3
5 5
6 8
7 13
8 21
9 34
10 55