简体   繁体   中英

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.
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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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