0

Shouldn't line 5 error because y is not defined? to me it should be out of scope but still outputs with y=100. Does python push the variable scope up a level? or is there a slow garbage collector? or some third thing?

i = 0
for x in range(100):
    for y in range(100):
        i += y
    print(x, y)

Expected output:

NameError: name 'y' is not defined

Actual output:

0 99

1 99

2 99

3 99

4 99

5 99...

Community
  • 1
  • 1

1 Answers1

0

No, it should not be an error, the docs explicitly call out the behaviour (paraphrased and emphasised below):

for_stmt ::= "for" target_list "in" expression_list ...

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.

Community
  • 1
  • 1
paxdiablo
  • 772,407
  • 210
  • 1,477
  • 1,841