Questions about Python exec

Asked 2 years ago, Updated 2 years ago, 115 views

In Python, we made a calculation using exec and eval in the for statement

lists = ["a=1", "b=2", "c=a+b"]
returned_list = []
for x in lists:
    exec(x)
    returned_list.append(eval(x))
print(returned_list)

If I write it like this, SyntaxError: invalid syntax comes out. We can use similar code in Shell, but can't we use eval in the function?

How can I solve this problem? I want to run a grammatical string that specifies the variables in the list, and create a function that uses that string.

python-3.x exec

2022-09-20 17:40

1 Answers

I'm not sure exactly what you're trying to implement, but there are differences between exec() and val().

In other words, in the case of exec(), both exec('a=1') and exec('1+2') are possible, but in the case of exec(), running eval('a=1') will cause a sync error.

I think you can pay attention to that part and modify it.


2022-09-20 17:40

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.