Code I wrote
tile1=0; player1=1; turn=player1
def s():
global tile1,turn,player1
print("Before",tile1)
string='tile' + '1' # I am getting 1 by some function that's why I need to create variable string
exec("%s=%d" %(string,turn))
print("After",tile1)
s()
Output what I expected
Before 0
After 1
Output what i got
Before 0
After 0
If I write the code without the function , it gives the expected output
tile1=0; player1=1; turn=player1
print("Before",tile1)
string='tile' + '1'
exec("%s=%d" %(string,turn))
print("After",tile1)
I want to ask how to correct this code so that I get the expected output. Also, I am not allowed to use list and dictionary.
The problem is that you need to specify the scope when you use
execinside a function.If you change it to:
It works as expected because you have no
localvariables (you declared themglobal) so you pass in the global scope aslocalscope toexecso it knows abouttile1andturn.However, it's misusing
exec, you shouldn't use it that way!