Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assignment within exec in python

I am trying to build calculator using PyQt5 and I get string which I need to evaluate and assign it to a variable so that I can Pass that variable to widgets as an answer . So far I can evaluate the expression but can't assing it . How can I do that ? so far I have following code:-

# 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 .....

When I try to run it without global, it runs without error but x remains 0 and If I ran it like this I get this error:-

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

I am very new to python So can't figure out whats going on

like image 898
orayan Avatar asked May 17 '18 11:05

orayan


People also ask

What does exec () do in Python?

Python's built-in exec() function allows you to execute arbitrary Python code from a string or compiled code input.

How do you pass arguments to exec in Python?

to pass arguments to exec() you need to pass dict as an argument for globals/locals not set .

What is the assignment in Python?

An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.

What can I use instead of exec in Python?

The globals() and locals() functions returns the current global and local dictionary, respectively, which may be useful to pass around for use by eval() or execfile().


1 Answers

global x = 5

is not valid python code.

If you want to assign to a global variable x, you should write

global x
x = 5

Try changing your code as

global x
eqn1 = "{0} = {1}".format("x",eqn)
x = 0
exec(eqn1, globals())

To modify global variables with exec, you need to use globals() function.

EDIT: Add globals() function.

like image 123
eozd Avatar answered Oct 03 '22 17:10

eozd