Why can a variable be accessible outside the loop in Python?

Consider the following example:

for iter in xrange(10):
   myvar = iter

print myvar
# 9

Does this myvarclearly go beyond the cycle? But it is still available. If it is Perl, it will cause an error.

What is the reason for such a function in Python? It's unhealthy? Which is better to declare a variable before a loop?

+4
source share
2 answers

There is no new scope created by the for loop (Ruby also behaves the same). This may be surprising if you come from a language that creates new areas for blocks.

I do not consider it harmful if you know the rules.

If your functions and methods are so large that you have tracking issues, your functions and methods are too large.

+5

, :

my_var = 0
my_var = 1
my_var = 2
...
my_var = 9

print my_var

, , my_var /.

-1

Source: https://habr.com/ru/post/1615343/


All Articles