Search code examples
pythonfunctionpython-3.6python-exec

exec function not working properly in python 3.6


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.


Solution

  • The problem is that you need to specify the scope when you use exec inside a function.

    If you change it to:

    exec("%s=%d" %(string,turn), None, globals())
    

    It works as expected because you have no local variables (you declared them global) so you pass in the global scope as local scope to exec so it knows about tile1 and turn.


    However, it's misusing exec, you shouldn't use it that way!