+ 7

PYTHON WHILE LOOP [ SOLVED ]

tracker = 0 while tracker <= 2: tracker += 1 print(tracker) Output : 1, 2, 3 Now my question is why it count 3 ? Anyone explain please .

9th Feb 2021, 11:18 PM
zeitu đŸ‡”đŸ‡ž
zeitu đŸ‡”đŸ‡ž - avatar
8 Respostas
+ 9
Let's jump to the point where 2 is printed, so tracker is 2. Next the condition (tracker <= 2) is checked and 2 <= 2 is true. Then tracker is incremented to 3, and 3 is printed. Then condition 3 <= 2 is false and execution ends
9th Feb 2021, 11:29 PM
Benjamin JĂŒrgens
Benjamin JĂŒrgens - avatar
+ 5
When tracker is 2, the loop still considers the statement true and goes again. This then is why tracker can increase to three and output it. All you have to do is remove the equal sign in the condition or put the print statement after the increment.
9th Feb 2021, 11:24 PM
Gabriel
Gabriel - avatar
+ 4
10th Feb 2021, 8:38 AM
zeitu đŸ‡”đŸ‡ž
zeitu đŸ‡”đŸ‡ž - avatar
+ 2
tracker <=2 and goes thru the loop again
10th Feb 2021, 12:19 AM
Lardaneo
Lardaneo - avatar
+ 2
Technically its just because your print(tracker) is placed after the increment instruction. Put the print(tracker) before tracker += 1 and see
11th Feb 2021, 11:30 AM
Elon
Elon - avatar
+ 1
Why cause <=. Less than or equal to.
10th Feb 2021, 12:43 AM
Ireneo language
+ 1
The tracker variable is incremented before printing, hence it also prints 3!
11th Feb 2021, 3:37 PM
Charuta Dessai
0
2=2 positive loops one more time 3=2 negative breaks and program ends in 3
10th Feb 2021, 12:42 AM
Ireneo language