-1

Why does "3" get printed out in this code block's output:

Input:

n = range(4)

for num in n:
    print(num - 1)
else:
    print(num)

Output:

-1 
0
1
2
3

From my understanding, "3" should not be printed since:

  1. num will never equal "4" since n are the literals 0 through 3 (not inclusive of 4),
  2. when num equals its highest literal, which is "3", it will print "2".

I've read the question about the else statement in for and while loops in Python, but I do not see an iteration where "4" is called in the for loop hence triggering the any usage of the else statement since num stops at 3.

Thank you.

  • 4
    The `else` is executed because no `break` was encountered in the loop. – khelwood Dec 27 '20 at 17:07
  • @khelwood Aw I see it now. Thank you! – Elvis Presley Dec 27 '20 at 17:21
  • 2
    From the [docs](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops): *"Loop statements may have an `else` clause; it is executed when the loop terminates through exhaustion of the iterable (with `for`) or when the condition becomes false (with `while`), __but not when the loop is terminated by a `break` statement__."* – Tomerikoo Dec 29 '20 at 08:49

1 Answers1

2

This gives us a sequence:

n = range(4)
0
1
2
3

This prints out the first four numbers:

for num in n:
    print(num - 1)
-1
0
1
2

And finally this prints out the final value of num:

else:
    print(num)
4
Hugo
  • 27,885
  • 8
  • 82
  • 98
  • Yes, I realized that after the first comment but I appreciate this comment as it's very clearly written out. Initially, I believed the life span of num ended when for loop ended; therefore, it would num would not proceed to the else statement. – Elvis Presley Dec 29 '20 at 16:47