Wednesday, January 13, 2021

Functions in Python With Examples

In this post we’ll see what are functions, what are the advantages of creating functions, how to define functions in Python and how to execute functions in Python and return result, if any.

What are functions

A function is a block of code that is usually written to perform a specific functionality. A function is executed only when you call it and you can pass data to a function (known as function parameters) and return a result from a function.

Advantages of using functions

  1. Functions help you in writing modular code as you can write different functions for different functionality. So. Functions help you in dividing application into smaller chunks.
  2. Functions help in making your code reusable as you can call functions when required and use them in different applications too.
  3. Functions also avoid repetition of code as the functionality which is required at several places can be written as a separate function and that function can be called as and when required.
  4. Functions make your code easy to maintain as any extra functionality can be written as an extra function without disturbing the existing code base.
  5. Functions make it easy to debug code, since different functions are written for different tasks so it easy to pin-point which function has a problem.

Python function syntax

In Python there are many inbuilt functions for performing various tasks like print() to display output, len() which returns the length (the number of items) of an object. But user can also define ‘user defined functions’ for performing specific tasks.

Syntax for defining a function in Python is as given below-

def function_name(param1, param2, ..) :
 """function doc string"""
 function suite
  1. For defining a function ‘def’ keyword is used followed by the function name.
  2. Function name is followed by a parenthesis where you specify the parameters for passing values to a function. Note that parameters are optional. In case there are no parameters then you have an empty parenthesis after function name.
  3. After parentheses there is a colon (:) which marks the end of function header and beginning of function body (indented code block also known as function suite).
  4. There is also an optional doc string that describes what a function does.
  5. There is also an optional return statement to return a value from a function.

Example of creating function in Python

In the example a function sum is created with two parameters. In the function those two parameters are added and the added value is returned.

def sum(a, b):
  """This function adds the passed values"""
  sum = a + b
  return sum

Calling a function in Python

To execute a function you have to call it. You can call a function using its name passing values for the parameters if there are parameters.

def sum(a, b):
  """This function adds the passed values"""
  sum = a + b
  return sum

# calling function
result = sum(5, 6)
print('Sum is', result)

Output

Sum is 11

Indentation in Python function

Indentation which means the spaces in the beginning of the code are very important in Python.

Python doesn't use curly braces ({}) to indicate start and end of the block of code that is done by indentation of code. Since function is also a block of code so that has to follow the same rules of indentation in Python. In the above function definition you can see that the code lines that form the function are having the same level of indentation.

Return value from a function

Using return statement a function in Python can return a value. If there is no value to be returned from a function then you don’t need to write a return statement in your function. If there is no return statement in a function then a Python function returns ‘None’ implicitly.

If a function just performs some action rather than calculating and returning a result, such functions are also known as procedures.

Here is the sum function rewritten so that result is printed with in the function itself and no value is returned from the function.

def sum(a, b):
  """This function adds the passed values"""
  result = a + b
  print('Sum is', result)

# calling function
print(sum(5, 6))

Output

Sum is 11
None

As you can see now trying to print the returned value displays ‘None’ as that is the value returned for a void function in Python.

That's all for this topic Functions in Python With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Global Keyword in Python With Examples
  2. Namespace And Variable Scope in Python
  3. Local, Nonlocal And Global Variables in Python
  4. Passing Object of The Class as Parameter in Python
  5. pass Statement in Python

You may also like-

  1. Multiple Inheritance in Python
  2. Python String split() Method
  3. User-defined Exceptions in Python
  4. Python Program to Find Factorial of a Number
  5. Java BufferedWriter Class With Examples
  6. How to Reverse a Doubly Linked List in Java
  7. How to Create Immutable Class in Java
  8. Spring Boot StandAlone (Console Based) Application Example