eval
can handle only a single Python expression, and no statement (simple or compound).
Your string contains multiple expressions and statements. You'd have to use exec
instead:
program = '''\
self.move()
self.turnRight()
if x > 0:
self.turnLeft()
else:
self.turnRight()
'''
exec program
If you were to use a conditional expression you can make it 3 separate expressions:
program = ['self.move()', 'self.turnRight()',
'self.turnLeft() if x > 0 else self.turnRight']
for line in program:
eval(program)
Note that it is always a better idea to implement a more specific language rather than re-use Python and eval
or exec
; you'll create more problems than you'll solve, especially when it comes to security.