You asked why in the code below:
(1) i = 6
(2) while (i > 0):
(3) i = i - 3;
(4) print (i)
The output is 3 and 0 and not only 3. The answer is simple, but it requires you to consider how Python interprets each command line. For ease, I listed the lines in the above code, okay?
The first line executed is (1). It simply assigns the value 6 to the variable i. The second line executed is (2). It checks if i > 0, and since i is 6 (at this time), this is true and Python allows execution to enter the loop. Thus, the next line executed is (3), which causes i to receive i - 3. Since at this point i is 6, the result is i = 6 - 3, then i = 3. This value is printed on the next line , as expected.
Execution then returns to row (2). The current value of i is 3 (which, incidentally, was the last printed). Since i > 0 (because 3 > 0) is true, the processing re-enters the loop. Line (3) subtracts again, so that i becomes 0 (since it does i = 3 - 3). Line (4) then prints the current value of i, which is 0.
Finally the execution returns to the line (2), but this time the processing does not enter the loop because the condition is no longer true.
Try running this code:
i = 6
while True:
i = i - 3
if(i > 0):
print (i)
else:
break
Note that in this code the condition of the loop is actually always true (after all, it is fixed True
), and the correct condition (its original condition) was moved into the loop in a if
. Analyze with this new code how the computer processes line by line in a sequential way, following the current value of the variable in each step (this procedure usually - or used to be called " table test "). It will help you understand how "logic" influences problem solving. :)