Steve Smith Steve Smith - 1 month ago 6
Python Question

Why does "for num in range(5)" have any effect if num=10 prior to the loop?

I'm given the following program, and I've been asked to write down what it prints:

num = 10
for num in range(5):
print(num)
print(num)


My answer is:

10


My reasoning is that
num
has been defined to be
10
, so it can't be in the range
(0,5)
, so we can skip this loop. Then, we simply write down what
num
is: 10.

The answer is very different:

0
1
2
3
4
4


How on earth is this the case, and how could the last line possibly print 4, when
num
has been defined to be
10
at the start?

Answer

When you do:

for num in range(5):
    print(num)

The value you assigned to num via num = 10 is over ridden by the for loop. Within the loop, your num is varying from 0 to 4. And when the for loop ends, it holds the value as 4. Outside the loop when you do print num it prints 4 because it is holding that last assigned value within for.