As per the language reference (emphasis mine):
The for-loop makes assignments to the variables(s) in the target list. This overwrites all previous assignments to those variables including those made in the suite of the for-loop:
[…]
Names in the target list are not deleted when the loop is finished, but if the sequence is empty, they will not have been assigned to at all by the loop.
So while you are iterating over the range of numbers from 0 to 6, those values are assigned to x
in each iteration. So in the first iteration, you get x = 0
, in the second it’s x = 1
, and so on until x = 5
(which is the last number that’s in the range).
Then when the for loop ends, as specified, the variable x
is not deleted, so x
is still around and still has that value 5
that it was assigned to in the final iteration.
Finally, since you seemed surprised that x
is just 5 in the end (and not 0, 1, 2, 3, 4, 5
), note that in each iteration, x
has only a single value. The print(x)
inside the for loop is just executed 6 times with x
having a different value each time. That does not result in the output you stated though; it’s still one number per line. Your code is essentially the same as the following without loops:
# the for loop does this:
x = 0
print(x)
x = 1
print(x)
x = 2
print(x)
x = 3
print(x)
x = 4
print(x)
x = 5
print(x)
# and this follows the loop:
print(x)