Why doesn't this very simple function work? I get NameError: name 'x' is not defined
def myfunc2():
x=5
return x
myfunc2()
print(x)
You've declared and defined x
inside of myfunc2
but not outside of it, so x
is not defined outside of myfunc2
.
If you'd like to access the value of x
outside of myfunc2
, you can do something like:
a = myfunc2()
print(a) # 5
I'd suggest reading up on variable scope in Python .
The x in myfunc2 is declared as a local. In order for this script to work, you can declare x as global:
def myfunc2():
global x
x = 5
return x
myfunc2()
print(x)
>>>5
Hope this helps.
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.