Search code examples
pythonfunctionparametersgloballocal

Python function argument can't be used as a variable in a child function


Here's the problem I try to solve:

I have a first function, to which I put in arguments. Then, later on, I have a second function, from which I want to call, as a variable, the said argument of the parent function. So it goes like:

def parent_function(argument=x):
 
    if statement:
        child_function()
 
    else:
        ...
 
    return result


def child_function():
 
    x = x + 5
 
    return x

If I run such a code, I get an error in the child function saying name 'x' is not defined.

However, if I fix my code to make x global in the parent function, like this:

def parent_function(argument=x):

    global x

    if statement:
        child_function()
 
    else:
        ...
 
    return result


def child_function():
 
    x = x + 5
 
    return x
 
 

I get the error name 'x' is parameter and global

I need to import both functions in another file and I can't "dismantle" the child function inside the parent function.

Thanks very much for any help !


Solution

  • Don't use global Variables. Every function needs it's own arguments:

    def parent_function(x):
        if statement:
            x = child_function(x)
        else:
            ...
        return result
    
    
    def child_function(x):
        x = x + 5
        return x