Python Functions

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.

Python Functions: Introduction


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.

Why do we need Python Functions?


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.

Types of functions in Python


There are two types of functions in Python.

  • Built-in FunctionsThese are the built-in functions of Python with pre-defined functionalities.
  • User-defined FunctionsAs 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.

How does a function work in Python?


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.

Python Functions: Definition

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]
  • A function definition in Python starts with the keyword def followed by the function name.
  • Depending on the operational requirement or user’s choice, a function may or may not have parameters inside the parentheses just after function name and it is followed by a colon (:).
  • After that is an optional statement – the documentation string of function or docstring followed by the indented block of codes or statements designated for the operation of the function.
  • The return statement is to exit the function and return the computed value, making the program flow to jump wherever the function is called.

Function call

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,...)

Docstring

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

The return statement ends the execution of the function and returns the value of expression following the keyword return to the caller.

Syntax of return statement

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.

Example to find a sum of two numbers using function in Python

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.

Scope and lifetime of the variable

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.

  • Local Variables
  • Global Variables

Local Variables vs Global Variables

Here are some of the points to list out the difference between global and local variable for their proper understanding.

  • Variables or parameters defined inside a function are called local variables as their scope is limited to the function only. On the contrary, Global variables are defined outside of the function.
  • Local variables can’t be used outside the function whereas a global variable can be used throughout the program anywhere as per requirement.
  • The lifetime of a local variable ends with the termination or the execution of a function, whereas the lifetime of a global variable ends with the termination of the entire program.
  • The variable defined inside a function can also be made global by using the global statement.
    def function_name(args):
      .............
      global x  #declaring global variable inside a function
      .............

     

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.