Two while Loop Statements showing different results

Question:

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
Asked By: Bilal Anees

||

Answers:

The magic you are seeing is because of i+=1

This is essentially the same as i = i + 1

In English that says "Make i to be equal whatever i is right now plus 1"

Answered By: Christian Jensen

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 🙂

Answered By: Aniketh Malyala
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.