Why doesn't the variable url change?
def test():
url = "Start"
def change():
global url
url = "End"
change()
print(url)
return url
test()
And yes, it needs to be a function within a function. That way the rest of my code is more simple. Thanks for your help!
Global variables are those defined at the top-level scope of a module, not just any variable defined outside the scope of a function. The variable defined in test
is a nonlocal variable from change
's perspective, not a global variable.
Use the nonlocal
keyword instead:
def test():
url = "Start"
def change():
nonlocal url
url = "End"
change()
print(url)
return url
nonlocal
causes the assignment to take place in the closest enclosing scope where url
is defined. (If no such local scope exists, the nonlocal
declaration is a syntax error. A definition in the global scope does not count, in contrast with free variables who are looked up in the closest enclosing scope, whether local or global.)
In your original function, change
really does set (or even create) a global variable named url
. For example:
def test():
url = "Start"
def change():
global url
url = "End"
change()
print(url)
return url
try:
print(url)
except NameError:
print("'url' not yet defined")
test() # Outputs "Start"
print(url) # Outputs "End"
The solution is to use the nonlocal
keyword
def test():
url = "Start"
def change():
nonlocal url
url = "End"
change()
print(url)
return url
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.