3

I have tried this code :

for i in range(10)
    print(line, i)

print(line, i)

and the program executed without error, so why is i declared even after the for statement, it must no longer exist.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
KarimS
  • 3,812
  • 9
  • 41
  • 64

2 Answers2

1

Yes, your iteration variable isn’t deleted when the loop is finished. As the documentation puts it: „Names in the target list are not deleted when the loop is finished”.

This has to do with variable scopes. As has been pointed out, the variable i exists within the scope of the function you’re in. A loop does not create an extra scope in python.

Leon Weber
  • 723
  • 6
  • 14
0

The scope is within a function, not a loop. A little different than other programming languages.

Choppin Broccoli
  • 3,048
  • 2
  • 21
  • 28