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 requires you to consider how Python interprets each command line. For ease, I listed the lines in the code above, ok?
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 worth 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. As at this time i is worth 6, the result is i = 6 - 3, so i = 3. This value is printed on the next line, as expected.
The execution then returns to line (2). The current value of i is 3 (which incidentally was the last printed). Since i > 0 (because 3 > 0) is true, the processing enters the loop again. The line (3) does the subtraction again, causing i to be set to 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 in fact 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 sequentially, 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. :)
Really, I was wrong to say that it is wrong. I should have said that it is outside the recommendations.
– Denis Callau