Home > Enterprise >  Variable decleration in a 'try except' block of a recursive function
Variable decleration in a 'try except' block of a recursive function

Time:05-06

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?

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

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