I want to assign :
x0='123'
x1='123'
x2='123'
x3='123'
x4='123'
x5='123'
x6='123'
x7='123'
x8='123'
x9='123'
I write the code to express that i can get the output of a string 123
when input x1
or x8
.
for i in range(0,10):
eval("x"+str(i)+"='123'")
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<string>", line 1
x0='123'
^
SyntaxError: invalid syntax
How i can do that way?
You can clear up this invalid syntax in Python by switching out the semicolon for a colon. Here, once again, the error message is very helpful in telling you exactly what is wrong with the line.
The reason it fails is that the functions you import from the math module are not local variables inside the function; they are global. So when you read locals() and insert into the dict, it inserts None for every single one. You would see this if you removed the get(key, None) and just accessed locals()[key] directly.
Python's eval() allows you to evaluate arbitrary Python expressions from a string-based or compiled-code-based input. This function can be handy when you're trying to dynamically evaluate Python expressions from any input that comes as a string or a compiled code object.
For dynamic execution of statements use the exec
function:
>>> exec('y = 3')
>>> y
3
eval
usage: eval(expression)
.
The expression
argument is parsed and evaluated as a Python expression.
e.g.:
>>> s = 3
>>> eval('s == 3')
True
>>> eval('s + 1')
4
>>> eval('s')
3
>>> eval('str(s) + "test"')
'3test'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With