+ 1

whille loop in Python

what is the difference between these two codes? i = 1 while i <= 5: print(i) i += 1 print("finish") ---> 1 2 3 4 5 finished i = 1 while i <= 5: i += 1     print(i) print("finish") ---> 2 3 4 5 6 finished why in first one 6 is not printed though we wrote <=5. so then 5 can be i, too. we should have another 5 + 1 that produces 6 and why in the second one 6 is written though we limited it saying <=5? I am really confused

16th Dec 2022, 6:46 PM
Kasra
Kasra - avatar
3 ответов
+ 1
The difference is the order between the increment and the output. The loops run from 1 to 5. In the last iteration, i is incremented to 6, so the loop exits. In the first one, it prints 5, increments to 6, then exits. In the second one, it increments to 6, prints 6, then exits. The while exit condition is tested right before each iteration, not in the code block inside the loop.
16th Dec 2022, 8:30 PM
Emerson Prado
Emerson Prado - avatar
0
In first case you first check i and after print i In secon case you first increase i and after print i
16th Dec 2022, 8:33 PM
Danila Khaminets
Danila Khaminets - avatar
0
Best to visualise what is happening in both instances so from i=5 Loop 1: Is i <= 5? Yes Print value {5} i = 6 Is i <= 5? No Print finished Loop 2: Is i <= 5? Yes i = 6 Print value {6} Is i <= 5? No Print finished This is also the reason that the second loop starts at 2 instead of 1 as i is incremented before the value is printed to the console. Hope this helps.
16th Dec 2022, 9:59 PM
Anthony Carnovale