acgtyrant acgtyrant - 5 months ago 10
Python Question

How to get a global variable in a function while the latter has a homonymic local variable?

a = 1
def b():
for c in range(10):
if c % 2 == 0:
a = c
else:
a = a
print(a)
b()


I want to "assgin global.a to b.a", but
a = a
does not work while it just assign the local
a
to local
a
. So how to access the global
a
and assign it to the
a
in
b
?

Do not change the name of
a
in
b
.

Answer

Use globals(). Though I do not recommend any of this, it can be done. Also, I can't even begin to imagine why you would want to as Daniel commented.

def b():
    for c in range(10):
        if c % 2 == 0:
            a = c
        else:
            a = globals()['a']
        print a