In this article, you will learn in depth about Python functions, their types, syntax, structure and other components. You will also learn about the scope of the variables used in functions.
A function in any programming language is a single comprehensive unit (self-contained block) containing a block of code that performs a specific task.
This means function performs the same task when called, which avoids the need of rewriting the same code again and again.
Functions help in the simplification of complex programs by breaking it into modules.
Imagine you are developing an application in Python and you need to write a huge amount of code for it. In that application, you need to compare values and find the maximum value many times in the program.
Now if you write code to compare value and find maximum one at every need step in the program, the code will be too huge making it extremely difficult to manage and debug.
To address such complexity and make the program more manageable, Python allows you to give a name to a block of statements, allowing you to run that block using the specified name anywhere in your program and any number of times. That name is called function and you can call it anywhere instead of writing the block of codes repeatedly. Besides, functions also make the code reusable.
There are two types of functions in Python.
These are the built-in functions of Python with pre-defined functionalities.
As the name goes, these are the functions defined by the users as per the requirement at different stages.We define our own functionalities and give a name to these functions.User-defined function with return type has return statements to return values after calculation whereas, function with non-return type has no return statement.
You will discover more about these later in this tutorial.
As seen in above diagram, a Python function consists of function definition where the functionality of a function is defined. Function definition as seen above consists of a function name, function arguments, docstring, code statements, and the return statement.
Once a function is defined, we need to call the function in the main program to execute the function. For that, there is function call statement.
Let’s go through each keyword, expressions, and statements used in the function.
Let’s look at the syntax of function definition in Python and explain it bits by bits afterward.
def function_name (arg 1, arg2,...):
"""docstring"""
statement(s)
return [expression]
def
followed by the function name
.(:)
.Defining a function means giving the function a name, specifying the parameters and defining the operation of function with code statements.
Once a function is defined, we need to call the function wherever and whenever we need to execute it. To call a function, we simply need to write the function and supply corresponding arguments for the parameters we included in the function definition.
Here is the basic syntax of a function call in Python.
function_name(arg1, arg2,...)
As we saw in the function definition, the first statement of the body function is a documentation string called doctsring, which explains in brief about the function and its operation. In Python, string literals are used for documenting modules.
We can access the docstring by __doc__
attribute. For example function_name.__doc__
.
Note: The doc attribute has two underscores(__)
before and after. Using single underscore (_)
will raise an error.
Here is the example to show how we can access the docstring in Python functions.
def Hello():
""" Hello World """
print ('Hi')
print ("The doctsring of the function Hello is: "+ Hello.__doc__)
Output:
This script will generate following output.
The docstring of the function Hello is: Hello World
The return statement ends the execution of the function and returns the value of expression following the keyword return
to the caller.
return [expression]
If the return expression has no expression or if there is no return
statement in the function, a special value 'None'
is returned.
The return
statement in a function is used to return a single value or a single object, be it an integer or a floating point number.
But what if we wanted to return multiple values from a function with the return
statement.
So let’s see how we can achieve this.
How to return multiple values using the return statement?
Multiple return
statements are not allowed in Python functions. So, the only way to return multiple values from a function is by returning lists or tuples which can have multiple integers or any other data type. This is the indirect way of returning multiple values.
Here is the example illustrating the concept of returning multiple values from a function. We will return a tuple containing multiple values.
def add(a,b,c,d):
x = a + b
y = c + d
return (x,y)
As shown in above example, we can return multiple values using tuples or lists or dictionaries. But it becomes problematic if the number values to be returned is huge.
Now that we know about function definition, function call, docstring, and the return statement.
let’s go through one example to illustrate all the concepts. We will learn in depth about function parameters or arguments in the next article.
In this example, we will depict both return type and non-return type user defined function to find the sum of two numbers.
#return type function
def add_r(a, b):
""" return type function to find sum """
x = a + b
return x
#non return type function
def add_n(a, b):
""" non return type function to return sum """
x = a + b
print (x)
#call the return type function and print
print (add_r(2,3))
#call the non return type function
add_n(2,3)
Output
5
5
The program works perfectly fine as we expect, but one can get confused with the use of the same variable a
, b
, and x
in both the functions.
Well, the thing is, the scope of the variable defined or declared inside a function is limited to that function only. We cannot use the variable outside of the function it is defined in because the variable doesn’t exist beyond that function.
Let’s learn in detail about the scope and the lifetime of a variable in the Python functions.
The scope of a variable determines its accessibility and availability in different portions of a program. Their availability depends on where they are defined. Similarly, life is a period in which the variable is stored in the memory.
Depending on the scope and the lifetime, there are two kinds of variables in Python.
Here are some of the points to list out the difference between global and local variable for their proper understanding.
def function_name(args):
.............
global x #declaring global variable inside a function
.............