x=1
def hi(y):
exec("global " + y)
exec(y + "+=1")
hi("x")
print(x)
I'd like the globally defined x to be incremented by 1, but the output I get is still 1. How can I correct this?
x=1
def hi(y):
exec("global " + y)
exec(y + "+=1")
hi("x")
print(x)
I'd like the globally defined x to be incremented by 1, but the output I get is still 1. How can I correct this?
You can access globals by a special keyword, wait for it: globals
:)
def hi(var):
globals()[var] += 1
Avoid exec like the plague (till you know what problems it introduces or in 5 years, which ever is later)
single letter variable names is a no-no for future readability sake. (it might just be for a demo but I'm saying...)
check out this link for scoping rules (with good examples for globals in further posts)
Hope the person passing in 'x'
doesn't change it to a invalid variable name like hi(12345)
.