python中exec中的赋值

ora*_*yan 6 python variable-assignment python-exec

我正在尝试使用 PyQt5 构建计算器,我得到了需要评估的字符串并将其分配给一个变量,以便我可以将该变量作为答案传递给小部件。到目前为止,我可以评估表达式但不能评估它。我怎样才能做到这一点 ?到目前为止,我有以下代码:-

# this functions gets called when Enter is pressed
def etrp(self):
    eqn =  self.sender().text()                  #I get string like '23+4'
    eqn1 = "{0} = {1}".format("global x",eqn)    #I make it x = 23+4
    x = 0
    exec(eqn1)                                   # I get error here
    print(x)
    #some code .....
Run Code Online (Sandbox Code Playgroud)

当我尝试在没有全局的情况下运行它时,它运行没有错误,但 x 仍然为 0,如果我像这样运行它,我会收到此错误:-

qt5ct: using qt5ct plugin
global x = 12+32
Traceback (most recent call last):
  File "/home/orayan/Development/Python/Calculator/calculator.py", line 11, in etrp
    exec(eqn1)
  File "<string>", line 1
    global x = 12+32
             ^
SyntaxError: invalid syntax
[1]    19185 abort (core dumped)  ./main.py
Run Code Online (Sandbox Code Playgroud)

我对python很陌生所以不知道发生了什么

eoz*_*ozd 4

global x = 5
Run Code Online (Sandbox Code Playgroud)

不是有效的 python 代码。

如果你想分配给一个全局变量x,你应该写

global x
x = 5
Run Code Online (Sandbox Code Playgroud)

尝试将您的代码更改为

global x
eqn1 = "{0} = {1}".format("x",eqn)
x = 0
exec(eqn1, globals())
Run Code Online (Sandbox Code Playgroud)

要使用 exec 修改全局变量,需要使用globals()函数。

编辑:添加 globals() 函数。