在A'中的变量切除术,试试除外'递归功能的块

发布于 2025-01-26 11:46:06 字数 286 浏览 2 评论 0原文

我想在块中以除块以外的一个变量i try块,在递归funktion中使用该变量。
这样:

def rec():
    try:
        print(l)
        return
    except NameError:
        l = 1
        rec()

它变成了Infite循环,但是为什么呢?它应该尝试打印L,正确地跳到名称外,声明那里的变量,递归调用该函数,现在应该能够打印声明的变量。但是除了块之外,它一直在跳入吗? 有什么方法可以实现吗?

I want to declare a variable in an except block to use that variable i the try block, all in a recursive funktion.
Like that:

def rec():
    try:
        print(l)
        return
    except NameError:
        l = 1
        rec()

It becomes an infite loop, but why? It should try to print l, jump rightfully to the Name-exception, declare the variable there, call the function recursivly and should now be able to print the declared variable. But it keeps jumping in the except block?!
Any way to achive that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

灯角 2025-02-02 11:46:07

变量L仅在块除外。
如果您想这样做,则可以添加该行:

global l

这将确保在以下递归调用中访问它。

The variable l only exists locally within the except block.
If you want to do it this way you can add the line:

global l

This will make sure it is accessible in the following recursive call.

甚是思念 2025-02-02 11:46:07

因为l = 1在任何单个函数调用中都从未在print(l)之前执行。期望它能正常工作就像期望这样做:

a = 1
def test():
    print(a)

呼叫本身的函数不会使其在其中定义的任何变量都可以访问递归调用,例如,没有将它们作为参数传递到递归调用中。

Because the l = 1 never got executed before print(l) in any of the individual function calls. Expecting it to work would be like expecting this to work:

a = 1
def test():
    print(a)

A function calling itself does not make any of the variables defined in it accessible to the recursive call without, for example, passing them as parameters into the recursive call.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文