我写的代码
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之后
如果我不使用函数编写代码,它会给出预期的输出
^{pr2}$我想问一下如何更正这段代码,以便获得预期的输出。另外,我不允许使用列表和字典。在
问题是在函数中使用
exec
时需要指定作用域。在如果将其更改为:
它按预期工作,因为您没有}。在
local
变量(您声明了它们global
),所以您将全局范围作为local
作用域传递给exec
,因此它知道tile1
和{但是,这是在滥用
exec
,你不应该那样使用它!在相关问题 更多 >
编程相关推荐