赋值变量Python的Eval/Exec

2024-09-29 17:47:47 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码旨在将阶乘转换为它的乘积。E、 g."4!"-->;"(4*3*2*1)"。由于exec(codeToRun)行,此代码无法工作。但是,如果我用codeToRun代替exec(codeToRun),那么它就完美地工作了,那么{}为什么不能工作呢?在

不起作用↓

def checkSpecialChars(char, stringToCheck, codeToRun):
    while char in stringToCheck:
        currentString=""
        for i in range(len(stringToCheck)):
            if stringToCheck[i]==char:
                try:
                    eval(codeToRun)
                except:
                    exec(codeToRun)
                    print(stringToCheck)
                currentString=""
                break
            if stringToCheck[i].isdigit():
                currentString+=stringToCheck[i]
            else:
                currentString=""
    return stringToCheck

有效↓

^{pr2}$

编辑1 阶乘的数目可以多于一个,每个阶乘中的位数也可以超过一个。在

Input: "11!/10!"

Expected Output: "(11*10*9*8*7*6*5*4*3*2*1)/(10*9*8*7*6*5*4*3*2*1)"

编辑2 我添加了一个输出字符串的print语句,如两段代码所示。现在,当我运行程序并输入4!时,程序会暂停(好像它是一个无限循环)。然后我按CTRL+C退出程序,它决定输出4!。然后每次我按CTRL+C时都会发生这种情况,因此该行必须在运行,因为print语句出现了,但它仍然位于4!。在


Tags: 代码ingt程序编辑if语句exec
1条回答
网友
1楼 · 发布于 2024-09-29 17:47:47

让我们快速浏览一下文档:

Help on built-in function exec in module builtins:

exec(source, globals=None, locals=None, /) Execute the given source in the context of globals and locals.

The source may be a string representing one or more Python statements
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.

以及

Help on built-in function locals in module builtins:

locals() Return a dictionary containing the current scope's local variables.

NOTE: Whether or not updates to this dictionary will affect name lookups in
the local scope and vice-versa is *implementation dependent* and not
covered by any backwards compatibility guarantees.

最后一句话似乎能解释你的烦恼。在

更具体地说,您使用一个参数调用exec,因此它将在globals()之上的locals()默认环境中执行。重要的是要认识到,这些并不一定与实际的全局和局部范围相同,但理论上可能是代理或副本或其他任何东西。现在,例如,如果您指定一个变量,这些字典中的一个会相应地更新。locals文档中的注释说明,无法保证此更新将传播到实际的本地范围。我想这就是你的程序不起作用的原因。在

如何解决这个问题:

基于以上一个简单的解决方法是

(1)与你自己订立一份合同,codeToRun分配给stringToCheck。在

(2)保留对传递给execlocals()实例的引用

(3)使用此选项显式设置stringToCheck

所以你的except块看起来有点像

    l = locals()
    exec(codeToRun, globals(), l)
    stringToCheck = l['stringToCheck']

相关问题 更多 >

    热门问题