Practice Question: For Loop

What is the output of the following code snippet?

Python
for x in range(3):
    print(x, end='')
    x = 3
Answer

The output is:

Python
012

Reassigning x inside the loop does not affect the iteration of the for-loop. This is because for x in range(3) gets each new value by calling next() on the range iterator, so changes to x inside the loop are ignored.

Back to collection