I want to execute some Python code, typed at runtime, so I get the string and call
exec(pp, globals(), locals())
where pp is the string. It works fine, except for recursive calls, e. g., for example, this code is OK:
def horse():
robot.step()
robot.step()
robot.turn(-1)
robot.step()
while True:
horse()
But this one is not:
def horse():
robot.step()
robot.step()
robot.turn(-1)
robot.step()
horse()
horse()
NameError: global name 'horse' is not defined
Is there a way to run recursive code as well?
UPDATE
a = """\
def rec(n):
if n > 10:
return
print n
return rec(n+1)
rec(5)"""
exec(a)
Works if put on the top-level. But if moved inside a function:
def fn1():
a = """\
def rec(n):
if n > 10:
return
print n
return rec(n+1)
rec(5)"""
exec(a)
fn1()
the same error occurs: NameError: global name 'rec' is not defined