python-3.xfor-loopwhile-loop

Loop with 'for'


This is a Python 3 question for loops using 'for'

Why does the print(num-1) still execute at range 4? In my mind when range is 4 it should skip print(num-1) and go straight to else: print(num).

for num in range(4):
    print(num - 1)
else:
    print(num)

The correct output is: -1 0 1 2 3 My question is why it should not be: -1 0 1 2 4

Thank you.

I tried using while:

num = 0
while num != 4:
    print(num - 1)
    num += 1
else:
    print(num)

I got what I was expecting: -1 0 1 2 4


Solution

  • The range(4) generates values: 0, 1, 2, 3.

    The loop iterates over each of these values and assigns them to num.

    Inside the loop, print(num - 1) runs for each value of num.

    Step-by-step execution:

    num print(num - 1) Output
    0 -1
    1 0
    2 1
    3 2

    Once the loop completes, the else block executes.

    The value of num remains 3 from the last iteration.

    So print(num) outputs 3.

    Thus, the final output is:

    -1 0 1 2 3