Loop Variable Scope
Concepts covered: Iteration
A loop variable in Python is an ordinary variable. The for loop assigns to it on every pass, and the loop ending does not delete it or reset it. Whatever value it was given last is still there, and code after the loop can read it. This is useful, and it is also a source of surprises when you expect the variable to vanish.
for i in range(3):
print("inside", i)
print("after", i)
total = 0
for n in [4, 9, 2]:
total = total + n
print("last n", n, "total", total)
count = 10
while count < 13:
count = count + 1
print("count", count)inside 0 inside 1 inside 2 after 2 last n 2 total 15 count 13
| Loop | Last assignment to the variable | Value after the loop |
|---|---|---|
| for i in range(3) | i = 2 on the third pass | 2 |
| for n in [4, 9, 2] | n = 2 on the third pass | 2 |
| while count < 13 | count = 13 inside the body | 13 |
The first loop's last assignment was i = 2, so "after 2" prints. The second loop's last item was 2, so n is 2 while total holds the full sum of 15. The while loop reads differently: count is a variable the body increments, and its final value is the first one that made count < 13 False. That is why it reads 13. When a while loop ends because its check fails, the counter holds the value that failed it; if a break ends the loop, the counter keeps whatever the body last assigned.
break leaves the variable on the found item
When break fires, the loop variable holds the item of the pass that triggered it, because no later pass happens to overwrite it. A search loop can hand its result to the code after it this way: the loop variable is the thing that was found.
for n in [3, 8, 5, 12, 6]:
if n > 9:
break
print(n)Output:
12
Values 3, 8 and 5 fail the if, and 12 passes it. The break fires while n is 12, so 6 is never assigned and the print shows 12. Without the break, the loop would run to the end and the same print would show 6, the last item.
A loop that never runs
If the sequence is empty, the body runs 0 times and the loop variable is never assigned. Reading it afterwards raises a NameError if no earlier line created it, the same error you get from any variable that was never assigned. If an earlier line did create it, it keeps that earlier value, because the loop never touched it.
for item in []:
print(item)
print(item)item = "nothing"
for item in []:
print("inside")
print(item)Output:
nothing
Reusing a name
Loops that use the same variable name share 1 variable. After the second loop, the name holds the second loop's last value, and the first loop's final value is gone. Distinct names such as price and name, or row and col, show at a glance which loop last wrote to a variable, and they keep a later loop from quietly overwriting a value you still need.
What does this program print?
n = 1
while n * n < 50:
n = n + 1
print(n)- 7
- 8
- 49
- 64
Predicting a for variable after a break means finding the first item, in list order, that passes the if, and stopping there. Later items are never assigned, even ones that would also pass. Over [2, 15, 30] with a break on n > 10, n ends at 15, and 30 never reaches the variable.
When a printed value belongs to the wrong loop, look for a name that 2 loops share. The second loop's assignments land in the same variable, so once it ends, the first loop's value is gone. Giving each loop a variable named for its own data, such as name and score, keeps both values.
About this lesson
This section is part of the Loops: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.