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
-
Why do you think it's working incorrectly? Have you debugged this program? Have you checked the values of number1?DarknessPlusPlus– DarknessPlusPlus2020年11月28日 15:08:26 +00:00Commented Nov 28, 2020 at 15:08
-
Yes, I provided the numbers I get: they are more than 4000000 and the program does not stopillymarev– illymarev2020年11月28日 15:12:31 +00:00Commented Nov 28, 2020 at 15:12
-
At the last iteration of the loop, number1 is at value: 2 178 309 and number2 is at: 3 524 578. These values are less than 4 000 000. Plus, you are only asking the value named nunber1 to be less than 4 million.DarknessPlusPlus– DarknessPlusPlus2020年11月28日 15:14:13 +00:00Commented Nov 28, 2020 at 15:14
-
1This is because the condition of the loop is just evaluated before the loop is repeated, but that is after the values are printed. It's not that the loop condition is guaranteed to be kept in every place in the loop body, but just at the start of the loop. So you just need to change your code, that the printing comes before the changeing of the values, or you wrap an if statement around the print code.jottbe– jottbe2020年11月28日 15:17:07 +00:00Commented Nov 28, 2020 at 15:17
-
I voted you up because you are new... but next time try to give more information and Expected output at least..adir abargil– adir abargil2020年11月28日 15:37:03 +00:00Commented Nov 28, 2020 at 15:37
3 Answers 3
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)
Comments
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
2 Comments
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.
1 Comment
do ... while! Better approach :)