python can declare global variable in local scope?
It works:
def main():
# do some... for files varible
for file in files:
result = func(file)
print result
I can't understand. Somebody tell me why result
can be seen outside the for
loop.
Thanks you.
for
statements do not start a new scope. Only modules, class declarations, and function definitions start a new scope.
I don't see a global variable declaration.
result
is a local variable, as is
file
.
Are you talking about
files
?
That looks like a global variable, but I don't see it declared locally.
Update based on @DSM's helpful comment:
If you are talking about result
as being declared locally inside the for
-loop, it doesn't work that way in Python, the for
-loop doesn't create a local scope.
If you a function uses assignment =
or augemnted assignemnt (ie +=
) then the variable is considered local
by default. However, if you want to make the assignments global
use the global
keyword.
foo = 2
def bar():
foo = 3 # foo is locally defined here
def car():
global foo
foo = 4 # foo is globally reassigned here
bar() # foo is still 2
car() # foo is now 4
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.