|
Correctly formatted (two spaces preceding each line, one blank line before the first code line, no extra lines needed between code lines): def loop():
for number in range(10):
fixed_number = number
def inner():
return fixed_number
yield inner
The output: eagerly = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
lazily = [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
It doesn't work because of the way Python's variables are scoped. Your fixed_number variable is still shared across all instances of inner. Python doesn't have any sort of block scoping like you seem to think it has. |