Functions in Python


In the Python programming language, we have two types of functions. They are built-in (also known as pre-defined) functions and, user-defined functions (functions that we create).

What is a function?

A function is a titled block of code that contains a statement(s) related to a specific task. All the statements in a function must be related to a task so that when we call the function, we will call it to perform some specific task.
A function in Python has both a function definition and a function call. Function definition means creating the function or defining the function. Function-call means invoking the function in order to execute the statements defined in it.
A function definition is Function Heading + Function Body.
The Function heading consists of a def keyword, the name of the function, optional input parameters that the function takes, and it ends with a semi-colon.
The function body is nothing but all those statement(s) that we want to relate to a specific task we want to achieve when the function is called.
Here is the general syntax when defining a function:
  1. def <fnName>([<Input_Parameters>]): #This is known as function heading  
  2.     statement-1 #Body of the function  
  3.     statement-2  
  4.     ...  
  5.     ...  
  6.     statement-n  

What is a Function call?

Calling or invoking the function in order to execute the code inside the function. It is always recommended to define the function first before calling the function. A function, therefore, must be first defined and then called. Once defined, a function can be called any number of times we want. A function that is defined will not be called automatically, we must call the function.
General Syntax of a function call
Python being a case-sensitive programming language, we must use the same exact name we have used to define the function otherwise, it will result in an error.
As part of a function, we use the "return" keyword to return a value of the result from a function. Always place the return statement as the last statement. However, in Python, it is not mandatory that a function returns or contains a return statement. Therefore we can have/define a function without any return statement as well. A function using a return statement by default can return only one value. However, we have many options for dealing with situations when we want functions to return more than one value (multiple values).


It is highly recommended to use/define functions in situations in which we have repetitive tasks. Therefore we can say that in Python functions provide an approach for a high level of code reusability. Furthermore, functions are a better design for the maintenance of code.