I’m trying to learn code with Programiz; the challenge is to find and print the numbers in a Fibonacci sequence that are less than the number you input. Here is the code, and so far it works for inputting 5 and 6. With both of those inputs, it stops at 3 and 5, respectivly, in the sequence, but any number higher than that and it keeps going. I can’t figure out why. I tried to follow the loop manually. If I input 7, it should loop 6 times (the range is 1, 7, but it stops at 7).
> loop 1=print t1(1), result=t1(1)+t2(1), t1=t2(1), t2=result(2)
> loop 2=print t1(1), result=t1(1)+t2(2), t1=t2(2), t2=result(3)
> loop 3=print t1(2), result=t1(2)+t2(3), t1=t2(3), t2=result(5)
> loop 4=print t1(3), result=t1(3)+t2(5), t1=t2(5), t2=result(8)
> loop 5=print t1(5), result=t1(5)+t2(8), t1=t2(8), t2=result(13)
shouldnt it stop here because t1=8 which is greater than n(7), closing the while loop
n = int(input())
t1 = 1
t2 = 1
result = 0
while t1<n:
for num in range (1,n):
print(t1)
result=t1+t2
t1=t2
t2=result
Sorry for the long question, I just figured I should explain my thought process on troubleshooting it, if anyone can help it would be appreciated.
Jack is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
Your inner loop doesn’t have any constraint except to iterate from 1
to n-1
.
If you input 7
, that inner loop will run six times, even if that means t1
ends up larger than n
.
Consider if we input 12
. 89
is much larger than 12
but we keep going well past it. In fact, predictably, we see 11 iterations.
>>> t1 = 1
>>> t2 = 1
>>> result = 0
>>> while t1<n:
... for num in range (1,n):
... print(t1)
... result=t1+t2
... t1=t2
... t2=result
...
1
1
2
3
5
8
13
21
34
55
89
A very simple fix would be to include a conditional break from the inner loop.
n = int(input())
t1 = 1
t2 = 1
result = 0
while t1 < n:
for num in range(1, n):
if t1 >= n: break
print(t1)
result = t1 + t2
t1, t2 = t2, result