Python functions
Jakob Jenkov |
Python functions are blocks of Python instructions which can be executed as a block from various points in your Python code - as if the code inside the function was located at the place where the function is called from. Executing a function is also referred to as "calling" a function.
Declaring a Function in Python
You declare a Python using the def
keyword followed by the function name and any parameters
the function should take. Here is an example of declaring a function in Python:
def my_function(p1, p2): print("param 1:", p1, " and param 2: ", 2)
This example declares a function name my_function which takes two parameters named p1 and p2. The value of these parameters are then printed the console.
If you do not want your function to take any parameters, just omit the parameter names inside the parentheses, like this:
def my_function2(): print("This function takes no parameters")
Calling a Function in Python
Calling a function in Python is done simply by writing its name followed by parentheses inside which you pass the values of the parameters the function takes. Here is an example of calling a function in Python:
my_function("p1 value", "p2 value") my_function2()
The above example calls both of the functions declared in the earlier sections in this Python function tutorial.
Returning a Value From a Python Function
A Python function can return value which can be assigned to a variable, used as part of an expression (e.g. calculation), or used as parameter in another function call. Here is an example of a Python function that returns a value:
def my_function3(a, b): return a + b sum = my_function3(2, 4) print(sum)
As you can see, the function my_function3() returns the sum of the two parameter values it receives when called. The value returned is assigned to a Python variable, which is subsequently printed.
Tweet | |
Jakob Jenkov |