Why is Python’s eval() rejecting this multiline string, and how can I fix it?

eval evaluates stuff like 5+3

exec executes stuff like for ...

>>> eval("for x in range(3):print x")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for x in range(3):print x
      ^
SyntaxError: invalid syntax
>>> exec("for x in range(3):print x")
0
1
2
>>> eval('5+3')
8

Leave a Comment