Search code examples
pythonfunctionfunction-parameter

Use a variable created inside a function as function parameter


Suppose you have the following code to define this simple function:

def a(x,y,b):

    z=[x,y]

    c=b*2

    return c

I want to call this function with the value z[0] as input for parameter b. If I try to call the function in the following way:

a(x,y,z[0])

I get an error since the variable 'z' is defined inside the function and does not exists until the function runs.

I thought that when a function is called, python would simply replace the inserted inputs with the relative parameter inside the function to perform the desired calculation, independently from the pre-existence of an input variable. I mean, in my function for example, if I insert as input z[0] I would expect that python simply takes the digits z[0] and copy them in the function in place of b and perform the multiplication by taking the first element of the array z.

I make a step by step example with the desired output of the function to clarify the question: after defyining the above described function, I call it with these inputs

a(2,3,z[0])

here are the steps of execution of the function:

1) it computes the array z=[2,3]

2) it computes c=z[0]*2 ie c=2*2

3) it returns c=4

The step number 2) however doesn't takes place, since the variable z is created inside the function. I'm asking if there is a way to make the function "copy" the input digits z[0] inside the function in place of the parameter b during the execution of the function itself, so that python does not consider z[0] as a non existing variable, but as a simple piece of code to replace b with.


Solution

  • This is horrible, but I'm starting to think it's what you want. Don't do this though. Really.

    def a(x,y,b):
        z=[x,y]
        c=eval(b)*2
        return c
    
    r = a(2,3,'z[0]')
    print(r)
    

    If you're curious why this works, it's delaying the evaluation of the expression z[0] until after z is defined inside the function's scope, rather than failing to evaluate it in the caller's scope.