Reputation: 256
I want the loop to stop when one of the numbers reaches 4 million. But it's working incorrectly. Could someone help me?
number1=0
number2=1
while number1<(4000000):
number1+=number2
number2+=number1
print(number1,number2)
Here are the numbers I get:
1 2
3 5
8 13
21 34
55 89
144 233
377 610
987 1597
2584 4181
6765 10946
17711 28657
46368 75025
121393 196418
317811 514229
832040 1346269
2178309 3524578
5702887 9227465
Upvotes: 1
Views: 367
Reputation: 31199
There are a lot of options to do it. The main problem is the logical sequence:
check -> increment -> print
Whenever you increment after check, the printed value is greater than the value used for comparison.
And another option in addition (not the best one):
number1 = 0
number2 = 1
while True:
number1 += number2
number2 += number1
if number1 <= (4000000):
print(number1, number2)
else:
break
You should use <=
instead of <
for a case when number1
exactly equals 4000000
. With <
, it will go to infinity loop.
Upvotes: 0
Reputation: 563
Be a pro about it. No need to restructure your code. Just skip the last iteration. This basically what we want to do.
number1=0
number2=1
while number1<(4000000):
print(number1,number2)
number1+=number2
number2+=number1
Upvotes: 0
Reputation: 473
It is working correctly - when number1 reaches 4 million it stops. If the issue is that numbers above 4 million are printed you could break an infinite loop instead:
while True:
number1+=number2
number2+=number1
if number1 > 4000000:
break
print(number1, number2)
Upvotes: 4