Skip to content Skip to sidebar Skip to footer

Refer A Global Variable That Has Same Name As The Local Variable In Python

I am new to python, how can we refer a global variable that has the same name as local one. spam = 'global spam' def scope_test(): spam = 'local spam' print(spam) # ac

Solution 1:

It's something not recommended, I am answering it for the sake if you're curious to ask/do it:

Python 3.5.2>>> spam = 'global spam'>>> defscope_test(): 
..     spam = 'local spam' 
..     print(spam) 
..     # access global spam and print or assign to the local spam 
..     print(globals()['spam']) 
..     spam = globals()['spam'] 
..     print(spam) 
..     
>>> scope_test()

The output:

local spam
global spam
global spam

Post a Comment for "Refer A Global Variable That Has Same Name As The Local Variable In Python"