Skip to content
Advertisement

Two while Loop Statements showing different results

I am new to python and struggling with 2 simple sets of code in which there is while loop used with a little difference (atleast in my opinion). These code should print ‘i’ while it is less than 6 but one set of code is printing ‘1 2 3 4 5 6’ and the other is printing ‘0 1 2 3 4 5’. I’m not sure why there is the difference. Any help will be much appreciated. Code is below:

this code is printing: ‘1 2 3 4 5 6’:

i=0
while i<6:
 i+=1
 print(i)

this code is printing: ‘0 1 2 3 4 5’:

i=0
while i<6:
 print(i)
 i+=1

Advertisement

Answer

In the first example, you are incrementing i before you print the value:

enter image description here

In the second example, however, you print the value of i first, and then increment it. That means, in the very first iteration, 0 is printed first instead of 1. Similarly, the last iteration will print a 5 since the value of i is incremented to 6 afterwards, and the while loop breaks.

enter image description here

Hopefully this helped! Please let me know if you have any further questions or need any clarification :)

Advertisement