简体   繁体   English

递归的“try except”块中的变量减速 function

[英]Variable decleration in a 'try except' block of a recursive function

I want to declare a variable in an except block to use that variable i the try block, all in a recursive funktion.我想在 except 块中声明一个变量以在 try 块中使用该变量,所有这些都在递归函数中。
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.它应该尝试打印 l,正确地跳转到 Name-exception,在那里声明变量,递归调用 function,现在应该能够打印声明的变量。 But it keeps jumping in the except block??但它一直在 except 块中跳跃? Any way to achive that?有什么方法可以实现吗?

The variable l only exists locally within the except block.变量 l 仅存在于 except 块中。 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.这将确保它可以在以下递归调用中访问。

Because the l = 1 never got executed before print(l) in any of the individual function calls.因为l = 1从未在任何单独的 function 调用中的print(l)之前执行过。 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. function 调用自身不会使递归调用可以访问其中定义的任何变量,例如,无需将它们作为参数传递给递归调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM