【问题标题】:exec function not working properly in python 3.6exec 函数在 python 3.6 中无法正常工作
【发布时间】:2017-09-23 09:44:41
【问题描述】:

我写的代码

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)

我想问一下如何更正此代码以获得预期的输出。另外,我不能使用列表和字典。

【问题讨论】:

  • 你必须打印“string”,因为它现在是“title1”
  • 你能不能用代码解释一下,因为我不明白你的答案

标签: python function python-3.6 python-exec


【解决方案1】:

问题是在函数内部使用exec时需要指定作用域。

如果你把它改成:

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

它按预期工作,因为您没有 local 变量(您将它们声明为 global),因此您将全局范围作为 local 范围传递给 exec,因此它知道 tile1turn .


但是,它误用了exec,你不应该那样使用它!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    • 1970-01-01
    • 2019-03-05
    • 2012-02-04
    • 2012-08-05
    • 2017-08-08
    • 1970-01-01
    相关资源
    最近更新 更多