Python function is the group of related statements that perform the specific task. A function in any programming language is a block of organized, reusable code used to perform a single, related action. Functions provide better modularity for our application and code reusability.
In this article, you will learn about Python functions, what is a function in Python, and its syntax, components, and types of functions. Also, you’ll learn to create a function in Python.
What is Function in Python?
A function in Python is the group of related statements that perform a specific task. Functions help us to break our program into smaller and modular pieces.
As our program grows larger and larger, the functions make it more organized, manageable, and reusable. Furthermore, it avoids repetition and makes code reusable.
How to create a function in Python
To create a function in Python, use the def keyword. A function should have a uniquely identified name. In addition, it should have optional Parameters (arguments) through which we pass values to a function.
The def in Python is used to define a function and is placed before a function name provided by the user to create a user-defined function. A function is a logical unit of code with a sequence of statements indented under a name using a “def” keyword.
def function_name(parameters): """docstring""" statement(s)
Above shown is the function definition, which consists of the following components.
- Keyword def marks the start of the function header.
- Provide a function name to identify that function uniquely. Function naming follows the same conventions of writing the identifiers in the Python language.
- Parameters (arguments) are optional through which we pass values to the function.
- The colon (:) to mark the end of the function header.
- Optional documentation string or docstrings to describe what the function does in the program. It is a comment in the programming language.
- The function body contains one or more valid python statements. Statements must have the same indentation level (usually four spaces).
- The optional return statement returns the value from the function.
By default, the parameters have a positional behavior, and you need to inform them in the same order they were defined.
Example of Function in Python
See the following example of a Function body.
def GoT(char): """This function print chars to""" print(char) return
How to call a function in Python?
Defining the function only gives it a name, specifies the parameters to be included in the function, and structures the blocks of code.
Once you have defined the basic structure of Python, you can execute it by calling it from another function or directly from the Python prompt.
We type the function name with the appropriate parameters if we want to call the function. See the full code below.
# app.py def GoT(char): """This function print chars to""" print(char) return GoT("Jon snow")
See the output.
Pass by value vs. Pass by reference
All the parameters (arguments) in the Python language are passed by reference. It means that if you change what the parameter refers to within the function, the change is also reflected in the calling function. See the below code.
# app.py def apps(list): list.append(21) print("Values inside the function: ", list) return list = ['Facebook', 'Instagram', 'Messenager'] apps(list) print("Values outside the function: ", list)
So, here we are modifying the list inside the function and see if the outside function list is changed or not. See the below output.
So, in the above code, we are appending one item 21 inside the function, and still, the outside list is updated, which means it is passed by reference.
There is one more example where an argument is passed by reference, and the reference is being overwritten inside the called function. See the following code.
# app.py def apps(list): list =  print("Values inside the function: ", list) return list = ['Facebook', 'Instagram', 'Messenager'] apps(list) print("Values outside the function: ", list)
See the output.
The parameter list is local to the function apps. We are not modifying the existing list; we are assigning the new list, which is why changing the list within the function does not affect the list. The function accomplishes nothing.
Docstring in Python
The first string after the function header is called a docstring and is short for documentation string. Docstring is used to explain, in brief, what the function does. It might be a standard term if you are familiar with Laravel.
Although they are optional, proper documentation counts as the best programming practice. Unless you can remember what you had done with your code a month ago, otherwise always document your code.
The return statement
The return statement is used to exit the function and go back to the place from where it was called. The syntax of the return statement is following.
The return statement can contain an expression that gets evaluated, and the value is returned. If there is no expression in a statement or the return statement itself is not present inside the function, then a function will return the None object.
Scope and Lifetime of variables
The variable’s scope determines the portion of a program where you can access the particular identifier. There are two necessary scopes of variables in Python, which are the following.
- Global variables
- Local variables
The variable’s scope is the portion of a program where the variable is recognized. Parameters and variables defined inside the function are not visible from the outside world. Hence, they have a local scope.
A variable’s lifetime is the period throughout which the variable exists in the memory. The lifetime of variables inside the function is as long as the function executes.
All the variables in the program may not be accessible at all the locations in that program. It depends on where you have declared the variable.
Variables are destroyed once we return from the function. Hence, the function does not remember any value of a variable from its previous calls.
See the following code.
# app.py def movie(): endgame = 10 print("Value inside function:", endgame) endgame = 20 movie() print("Value outside function:", endgame)
See the output.
You can call the function by using the following types of formal arguments.
- Required arguments.
- Keyword arguments.
- Default arguments.
- Variable-length arguments.
The Anonymous or Lambda Functions
Lambda Functions are called anonymous because they are not declared conventionally using a def keyword. Instead, you can use the lambda keyword to create small anonymous functions.
Lambda forms can take any number of arguments but return just one value in the form of expression. Therefore, they cannot contain any commands or multiple expressions.
- An anonymous function cannot be the direct call to print because lambda requires an expression.
- Lambda functions have their local namespace and cannot access variables other than those in their parameter list and those in the global namespace.
Although it appears that lambda functions are the one-line version of the function, they are not equivalent to the inline statements in C or C++, whose purpose is bypassing function stack allocation during the invocation for performance reasons.
That’s it for def in Python.