Calling Functions in Python
After writing a function, it’s defined, not executed. To execute we should call it explicitly. The function runs after having been executed. A part of a program that is calling our function is named a caller. Of course, to execute a function and run, we write its name with parentheses accepting a list of arguments.
function_name(arguments_list)
Defining the function sum():
def sum(a,b,c):
return a+b+c
Calling the function sum():
>>>sum(23,56,89)
168
During execution, a calling program is stopped and waiting for the moment when our function finishes its work, and the control comes back to the caller again.
Defining the first function printing “Hello!”:
def druk():
print(“Hello!”)
Defining the second function calling the function druk():
def drul():
druk()
The function drul() is the caller for the function druk(). Let’s call drul():
>>> drul()
Hello!
>>>
Or we can write in other order:
def drul():
druk()
def druk():
print(“Hello!”)
We get the same:
>>> drul()
Hello!
>>>
Even if there aren’t any arguments, we must use parentheses with the name of our function to execute it. In this case, they will be empty. A function must be defined before its calling. But we can refer to a function before its defining.
We can check if an object is callable using the built function callable():
callable(object)
>>>callable(print)
True
The function returns True if the object is callable or False if the object isn’t callable. It is in Python 3.x.x because in Python 2.x.x the function callable returns 1 (True) or 0 (False).
Callable objects in Python:
— functions built-in
— functions defined by a user
— methods of built-in objects
— class objects
— class methods