1

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
  • 107,083
  • 22
  • 201
  • 376
KarimS
  • 3,520
  • 7
  • 38
  • 60

2 Answers2

0

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

Choppin Broccoli
  • 3,020
  • 2
  • 18
  • 28
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
  • 703
  • 6
  • 14