我写的代码
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
,你不应该那样使用它!
关于python - exec 函数在 python 3.6 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46378216/