Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

eval SyntaxError: invalid syntax in python

Tags:

python

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?

like image 888
showkey Avatar asked Mar 21 '14 12:03

showkey


People also ask

How do I fix SyntaxError invalid syntax in Python?

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.

Why eval is not working in Python?

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.

What does eval () do in Python?

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.


1 Answers

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'
like image 58
suhailvs Avatar answered Oct 03 '22 18:10

suhailvs