Let's say I have a function
def x(): print(20)
Now I want to assign the function to a variable called y
, so that if I use the y
it calls the function x
again. if i simply do the assignment y = x()
, it returns None
.
we put the function in a variable if inside the function block we use the return method: var multiplyTwo = function (a) { return a * 2; }; if we simply call this function, nothing will be printed, although nothing is wrong with the writing of the function itself.
In C++, assigning a function to a variable and using that variable for calling the function as many times as the user wants, increases the code reusability. Below is the syntax for the same: Syntax: C++
File scope variables can only be initialised with constant expressions. A function call isn't one.
It is possible to use a function expression and assign it to a regular variable, e.g. const factorial = function(n) {...} . But the function declaration function factorial(n) is compact (no need for const and = ). An important property of the function declaration is its hoisting mechanism.
You simply don't call the function.
>>>def x(): >>> print(20) >>>y = x >>>y() 20
The brackets tell python that you are calling the function, so when you put them there, it calls the function and assigns y
the value returned by x
(which in this case is None
).
When you assign a function to a variable you don't use the () but simply the name of the function.
In your case given def x(): ...
, and variable silly_var
you would do something like this:
silly_var = x
and then you can call the function either with
x()
or
silly_var()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With