Functions in Python
Video Tutorial
Overview
A function in Python is a collection of connected statements that performs a single task. Functions help in the division of our program into smaller, modular portions. Functions help our program become more ordered and controllable as it grows in size. It also eliminates repetition and makes the code reusable.
Scope
- In this article, we will learn about functions in Python.
- Then, we will look into different types of functions.
- We will also look at the syntax and working of functions in Python.
- Then, we will understand how to call functions in Python and whether functions are passed by value or passed by reference in Python.
- We will then also understand what arguments and parameters are and categorize functions on the basis of parameters and return type.
- Then, we will learn about a few different types of functions.
- We will also learn about the scope of variables in functions in Python.
- At last, we will know the advantages of using functions in Python.
What are Functions in Python?
Functions are modular blocks of code designed to perform specific tasks. They enhance code efficiency and clarity by reducing code repetition and enabling code reuse.
A function can be related to the process of making tea. If you were to make tea for the first time, your parents would have defined the steps to make it. The next time they want to drink tea, they’ll call out to you directly by saying ‘Make Tea’.
Similarly, in the case of functions, you first define the sequence of steps that you would like to carry out to achieve a certain task. Later, you can call out the Function by its name, and these steps will be performed.
Types of Functions in Python
Functions in Python can be of 2 types:
-
User-defined:
Output:
-
Built-in:
These are already defined within Python, and thus a user need not define them again. They can be directly used in a program or application. E.g., abs() is used to find the absolute value of a number.
Output:
Rules for Naming Functions in Python
If you were asked to name the process by which plants use sunlight to synthesize nutrients from CO2 and water, you wouldn’t say digestion. Similarly, a function should be named based on the task that it performs. Shorter and easy-to-understand ones are always preferred.
- They must begin with a letter or an underscore.
- They should be lowercase.
- They can consist of numbers but shouldn’t start with one.
- They can be of any length.
- They shouldn’t be a keyword in python, i.e. be reserved for any purpose. To improve readability and to maintain conventions, separate words by underscores. Ensure that you give function names that define the purpose of the Function. Use camelCase only in case that is the current style of the program.
Syntax of Python Functions
Output:
The function definition consists of the name, the parameters needed, the steps that will be carried out by the Function, and returning values, if any.
Syntax:
The components of a python function definition are:
1. Keyword def:
In python, the keyword def is used to define a function. It marks the beginning of the function definition.
2. Name of the Function:
function_name is a unique identifier that is considered the name of the Function.
3. Parameters:
These are the values passed to the Function. 0 or more parameters can be included in the parentheses.
4. Colon(:): The:
represent the start of the indented function block.
5. docstring:
The optional docstring or document string is used to define what the Function does.
6. Statements:
These include the sequence of tasks that the Function is to perform. It can also use the pass keyword in case of no statements. These statements are usually indented at the same level (usually 2 or 4 spaces).
7. Return Statement:
The optional return statement symbolizes the return of values from the Function to the calling code.
Example of a function in Python
A Simple function to print Hello World on the screen.
How Does a Python Function Work?
A python function consists of 2 parts: Function definition and function call. To create a function in Python, you have to first define the Function, giving it a name, parameters, statements, etc., and then call it separately in the program using its names and parameters, if any.
How to Call a Function in Python?
A function in Python is called by using its name followed by parentheses. In case parameters are present, these are included in the parentheses.
Example: To call the Function named hello, simply type the following:
Output:
Are Functions in Python Passed by Reference or Passed by Value?
Passing is the process of providing arguments (parameters) to a function. In general, parameters in functions can be passed in 2 ways: pass by reference or pass by value. In the pass-by-value, a copy of the parameter’s value is stored in the memory, and all changes are done to that. Hence, these changes aren’t reflected in the parameter in the function call. However, in pass-by reference, a copy of the address of the actual parameter is stored; thus, changes inside the Function will be reflected back in the program.
Example:
Output:
Example:
Output:
Consider the following example where i is passed from main() to inc(). The inc() function serves the purpose of incrementing the value being sent from main by 1. id() is a built-in function in Python that gives memory addresses of objects being passed.
Output:
From the above example, we can draw the following conclusion:
- The address of i remains constant.
- The initial address of n is equal to that of i.
- The address of n changes on reassignment of value
Although the fact that the incrementing doesn’t reflect in the main() suggests that the Python code uses a pass-by-value mechanism, the 2nd conclusion clearly proves that this isn’t a case of pass-by-value. Thus, we can say that Python uses a mechanism that is different from a pass-by-value or pass-by-reference.
Unlike languages that use pass by value or pass by reference, python uses a mechanism known as “Pass by Object Reference”. Here, the name (aka object reference) is passed. A variable is assumed to consist of an object. Objects in python are of 2 types: Mutable and Immutable. An immutable object is one whose values cannot be changed once created. E.g., Strings, tuple. A Mutable object is one whose values can be changed. E.g., Sets, List. If the object under consideration is mutable, the object modifications will persist and will not in the case of immutable objects.
Example: Function that helps to implement a change in value using functions.
Output:
Types of Arguments in Python
Functions with arguments/parameters are called parameterized functions. To call these functions, the number and order of arguments should be as given in the function definition.
A function can have 1 or more parameters. A function in python can accept up to 255 parameters.
The arguments/parameters used in the python function definition are called formal arguments or formal parameters while the ones in the function call are called local arguments or local parameters. The name is based on their location in the program.
Function parameters can have their type defined along with them, as given in the example:
Output:
Example: Function with Single Parameter
Output:
Example: Function with Multiple Parameters
Output:
There are four major types of arguments:
- Required arguments
- Keyword arguments
- Default arguments
- Variable-length arguments
Required Arguments
In such functions, the exact number of arguments are required to be passed in the order in which it is defined in the Function.
Example:
Output:
Hello Anna
Output:
In the above example, the hello() function requires exactly one argument (name) to be passed in the function call, without which it will give an error.
Keyword Arguments(**kwargs)
Usually, when you call a function using arguments, these are passed to the function definition in the order in which they are passed in. For example:
In the example above, fname takes the value Murthy and lname takes the value Sunny. There might be times when you don’t know the order in which the arguments are present in the Function and thus want to use them in the function call in a different order. This is exactly where Keyword Arguments come in. Using keyword arguments, a function can be called by providing parameter values in any order, as long as the parameter names are mentioned along with them.
Example:
Output:
What if you don’t know the number of arguments being passed? Functions can have single parameters prefixed with ** to map a variable number of keyword arguments in different order.
Output:
Default Arguments
The formal parameters can be assigned default values as a failsafe, in case a local value isn’t passed. In such cases, the default value will be used inside the Function.
Example:
Output:
Variable-Length Arguments
Not always will you know the number of arguments that can be passed to the Function. If the number of arguments passed is unknown, you can add an asterisk (*) before the parameter in the function definition.
Example:
Output:
Categorizing Functions in Python based on Parameters and Return Value
Based on Function Definition, a function can be categorized into 4 types:
a) Without parameters, without return statement
Syntax:
Example:
Output:
b) With Parameters, without return statement
Syntax:
Example:
Output:
c) Without parameters, with the return statement
Syntax:
Example:
Output:
d) With parameters, with return statement
Syntax:
Example:
Output:
Recursive Functions in Python
Recursion is the process in which a function calls itself. Recursive functions are used mostly for sequence generation and are used to make the code look clean and elegant.
Example of a function to calculate the sum of n consecutive natural numbers recursively:
Output:
Anonymous Functions in Python
An anonymous in python is a function that is defined without a name. Unlike functions defined using the def keyword, these are defined using the lambda keyword and are hence called lambda functions. They can have 0 or more arguments but only one return value.
Syntax:
Example:
The above example as a normally defined function could be written as:
Output:
Scope of Variables in Python
Global Variables
Any variable declared outside the Function is called a global variable. Such a variable has global scope, i.e., it is accessible everywhere, whether inside or outside of the Function.
Example:
Output:
Local Variables
A variable declared inside the Function’s body is called a local variable. Such a variable is said to have a local scope, i.e., it is only accessible within the Function and not outside.
Example:
Output:
Example: Global and Local Variables with the Same Name
Output:
Pass Statement
Empty functions are used as a means of time delay. Since functions cannot be empty, the pass statement can be used to avoid errors caused by a lack of statements.
Example:
Advantages of Functions in Python
Helps in increasing modularity of code – Python functions help divide the code into smaller problems and solve them individually, thus making it easier to code.
Minimizes Redundancy – Python functions help you save the effort of rewriting the whole code. All you got to do is call the Function once it is defined.
Maximes Code Reusability – Once defined, the python Function can be called as many times as needed, thus enhancing code reusability.
Improves Clarity of Code – As the large program is divided into sections with the help of functions, it helps in increasing the readability of code, at the same time ensuring easy debugging.
::: section{.summary}
Conclusion
Let's recall functions in Python in a nutshell:
- Functions are used to reduce repetition and make the code more modular.
- Python neither uses pass by value nor pass by reference mechanism, but it uses pass by object reference sort of mechanism.
- We can pass up to 255 parameters in a function in Python.
- Scope of a variable in a function can be changed from local to global by using the global keyword.
- Pass statement can be used to write an empty function.
:::