结合使用exec()和递归函数 [英] Using exec() with recursive functions

查看:73
本文介绍了结合使用exec()和递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行一些在运行时键入的Python代码,所以我得到了字符串并调用

I want to execute some Python code, typed at runtime, so I get the string and call

exec(pp,globals(),locals())

exec(pp, globals(), locals())

其中 pp 是字符串.它可以正常工作,但递归调用除外.例如,此代码可以:

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()

但是这个不是:

def horse():
    robot.step()
    robot.step()
    robot.turn(-1)
    robot.step()
    horse()

horse()

NameError:全局名称"horse"不是 定义

NameError: global name 'horse' is not defined

是否还可以运行递归代码?

Is there a way to run recursive code as well?

更新

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()

发生相同的错误:NameError:未定义全局名称'rec'

the same error occurs: NameError: global name 'rec' is not defined

推荐答案

它对我有用:

a = """\
def rec(n):
    if n > 10:
        return
    print n
    return rec(n+1)

rec(5)"""

exec(a)
5
6
7
8
9
10

我只能说您的代码中可能有一个错误.

All I can say is that there is probably a bug in your code.

修改

你在这里

def fn1():
    glob = {}
    a = """\
def rec(n):
    if n > 10:
        return
    print n
    return rec(n+1)

rec(5)"""
    exec(a, glob)

fn1()

这篇关于结合使用exec()和递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆