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

南笙酒味 提交于 2019-12-01 18:32:17

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

I don't believe it's harmful as long as you know the rules.

If your functions and methods are so large that you have trouble keeping track, then your functions and methods are too large.

Think of it as if you're doing this:

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

print my_var

This is basically what the iteration will look like, there is no reason why my_var would not be accessible from within your current method / scope.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!