0
i don't understand this peace of code in while loop in python
i = 1 while i <=5: i += 1 # on top of print statement print(i) # gives results items in range(2, 7) #while this code below; i = 1 while i <=5: print(i) i += 1 # below print statement # gives results items in range(1, 6) # WHY IS THAT..?
2 Answers
+ 1
In the first loop value of <i> is incremented by one before it is printed, therefore;
1,2,3,4,5 becomes â
2,3,4,5,6
In the second loop value of <i> is printed first, then incremented, and that's why it outputs 1 ~ 5.
Hth, cmiiw
+ 1
When you don't understand the functioning of a loop, try to imagine (or write) the behavior you expect step by step. It often helps clarifying things.
Here in your first piece of code :
- i is initialized to 1 outside the loop
- inside the loop, i is incremented (+=1) BEFORE being printed, so the first value to be printed will be 1+1, 2
- the loop continues until it reaches 6 (because then i<=5 is false). So the last value entering the loop is i=5. It is incremented, so the value of i now is 6, and then printed (so 6 is printed). i=6 so the loop stops
In your second piece of code :
- i is initialized to 1 outside the loop
- inside the loop, i is printed (so 1 is printed as first value) AND THEN is incremented. So the next value in the loop will be 2.
- The loop continues until i reaches 6, so the last value to enter the loop is 5. It is printed (so 5 is printed). Then it is incremented, so the value of i is now 6. The loop ends.
Does that answer your question ?