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
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.
© 2024 OneMinuteCode. All rights reserved.