[Solved] Why pass a variable to a function in Python? [closed]


Doing it the first way severely hampers the re-usability of your function.

Simple Example:

What if I wanted to see the outcome from of your function when y=3 when x is any of the numbers in [2, 4, 6]?

With the first example, you’d need:

def f():
    return x + y

results=[]
y = 3
x = 2
results.append(f())

x = 4
results.append(f())

x = 6
results.append(f())

# Or alternatively -- shorter but kind of redundant:
for num in [2, 4, 6]:
    x = num
    results.append(f())

With the 2nd option, you can just do this:

def f(x, y):
    return x + y

y = 3
x = [2, 4, 6]
results = [f(i,y) for i in x]

Now imagine that with much larger numbers of repetitions for use of f().

solved Why pass a variable to a function in Python? [closed]