Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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’:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading