【问题标题】:Python exec() returns None [duplicate]Python exec()返回无[重复]
【发布时间】:2018-06-12 12:47:15
【问题描述】:

使用 exec() 执行字符串时,返回 None。

tree_1= '''def tree():
  input_user = input('elektriciteit | Y&N')
  if input_user == 'Y':
    return 1800000
  else:
    input_user = input('accelerator | Y&N')
    if input_user == 'Y':
      return 2170701
    else:
      return 2170705
tree()'''


output = exec(tree_1)
print(output)

如何将返回值保存到变量中。评估不工作。

【问题讨论】:

  • exec,当以这种方式调用时,将在当前上下文中运行——如果您将tree()''' 更改为result = tree()''',您可以只使用print(result)。不过,我不是这种方法的忠实拥护者。
  • 是的;这就是exec 所做的。你为什么首先使用exec
  • "Eval 不工作" - 但你没有使用eval,你使用的是exec正在工作)。
  • 上周它起作用了,现在我来到这部分代码,我得到了“无”返回。也许是 python 版本?

标签: python


【解决方案1】:

刚刚找到答案。

tree_1= '''def tree():
  input_user = input('elektriciteit | Y&N')
  if input_user == 'Y':
    return 1800000
  else:
    input_user = input('accelerator | Y&N')
    if input_user == 'Y':
      return 2170701
    else:
      return 2170705
result = tree()'''

exec(tree_1)

global result
print(result)

【讨论】:

    猜你喜欢
    • 2020-05-12
    • 2022-10-02
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 2016-12-13
    • 2021-11-26
    相关资源
    最近更新 更多