Python Forum

Full Version: Storing whole functions in variables
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
When i print y, why does it say none? instead of returning the value from the function called
x = 1

def edr(x):
    x+2
    print(x)
#Here i try to understand variables to store an function in a variable
y = edr(x)
#It says none and i thought it would  either call the function or get the value of x
print(y)
First, you're not storing the function in the variable, you're storing its return value. You need an explicit return statement in named functions, since there isn't one, the function implicitly returns None.
I understand now, thanks
You can use a lambda expression to bind a function and an argument to be called later.
x = 1

def edr(x):
    return x + 2

y = lambda: edr(x)

print(edr, y, y(), edr(x))
Output:
<function edr at 0x00000193D86AF0D0> <function <lambda> at 0x00000193D8B94160> 3 3
edr without the () is a function.
y is a lambda expression that will call the function edr with the argument x.
y() evaluates the lambda expression (calls the function) and returns the result.
edr(x) calls the function edr() with the argument x.