On 06/21/2016 09:50 PM, Elizabeth Weiss wrote:
> i=1
> while i<=5:
>    print(i)
>    i=i+1
> 
> The result is:
> 1
> 2
> 3
> 4
> 5
> 
> Why is one of the results 5 since i=i+1? Should the maximum result be 4 since 
> 4 +1=5? 
> 
> Thanks for your help!

If you trace the execution through in your mind it should be come clear.
 While always checks the expression first before running the body of the
loop.  If, during the loop body, i was 4, it is then incremented to 5.
Now the top of the while loop checks the expression and since i is 5,
5<=5 is true (5 is less than or equal to 5), so the body runs now, and
prints out the value and then increments i by 6, making it 6.  Now at
the top of the while loop, 6 is clearly not less than or equal to 5, so
the loop terminates there.  Hope this helps.

-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to