Home > Software design >  why last output also varies in this block of python code?
why last output also varies in this block of python code?

Time:11-02

I can understand first output of first example, that is 2 as the i = 1 makes value to 2 than print calls, I also understand the second example's first output that is 1 because print calls i then increment begins. But, what about the end, as we have already defined "while i < 6:" then why first example returns last output as 6 (why don't it breaks to 5) I'm a beginner so treat me like a kid and write the answer that is easy to understand. Thank you! :)

i = 1
while i < 6:
    i  = 1
    print(i)  # Print output after i increment, see the result
>> The output is -
2
3
4
5
6

i = 1
while i < 6:
    print(i)  # Print output before i increment, see the result
    i  = 1
>> The output is -
1
2
3
4
5

I was expecting the output should be limited to 5 but it returns to 6 (in first example)

CodePudding user response:

The while condition is only checked before each iteration, not after every statement inside the loop body. So on the last iteration, i == 5 and the condition i < 6 succeeds. It goes into the loop body, increments i to 6, and then prints that value.

CodePudding user response:

i = 1
while i < 6:# initially i value is 1.
    i  = 1 # here you are incrementing. i value becomes 2.
    print(i)  # print starts from 2 

in the last check  i value becomes 5 then it increments to 6 and prints.
so the output starts from 2 and goes till 6.
>> The output is -
2
3
4
5
6

i = 1
while i < 6:
    print(i)  # Print output before i increment, see the result
    i  = 1

here you print the i value first and increment later .
you print the i value first 
initially 1
then you print it . then you are incrementing it.
in the final check 5<6. it prints 5 and in the next increment as i value equals to 6. the while statement becomes false.
>> The output is -
1
2
3
4
5
  • Related