Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
exec函数在python 3.6中工作不正常_Python_Function_Python 3.6_Python Exec - Fatal编程技术网

exec函数在python 3.6中工作不正常

exec函数在python 3.6中工作不正常,python,function,python-3.6,python-exec,Python,Function,Python 3.6,Python Exec,我写的代码 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("

我写的代码

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()
输出我期望的内容
在0之前
1之后

输出我得到的
在0之前
0以后

如果我在没有函数的情况下编写代码,它会给出预期的输出

tile1=0; player1=1; turn=player1
print("Before",tile1)
string='tile' + '1'                                  
exec("%s=%d" %(string,turn))
print("After",tile1)

我想询问如何更正此代码,以便获得预期的输出。此外,我不允许使用列表和字典。

问题是,在函数中使用
exec
时,需要指定范围

如果将其更改为:

exec("%s=%d" %(string,turn), None, globals())
它按预期工作,因为您没有
local
变量(您声明了它们
global
),所以您将全局范围作为
local
范围传递给
exec
,这样它就知道
tile1
turn



但是,它误用了exec,您不应该这样使用它

你必须打印“字符串”,因为现在是“标题1”,你能用代码解释一下吗?因为我不明白你的答案