0

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
  • 99,167
  • 19
  • 183
  • 334
karim
  • 3,138
  • 6
  • 33
  • 58

2 Answers2

0

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

Choppin Broccoli
  • 2,930
  • 2
  • 17
  • 27
0

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
  • 673
  • 6
  • 14