Functions in Python

Functions are set of instructions to perform a specific task. A function is a block of code which only runs when it is called. You can pass data, known as parameters/argument, into a function. It also called as method.


Below is the syntax of functions in python. In the below example you will get more clarity about the function syntax.

Define Function

def function_name([arg1,…,argn]): 
    [return value] 

Call Function
variable_name = function_name([val1,…,valn])

Note: Anything enclosed in [ ] (square bracket) is optional

Function can we call from any program, class or from another functions also.


This is simple example of function, where calculate_sum function is performing the task of sum of two numbers/ passing arguments data1 and data2 and returning final result in value result_sum.

Python Functions Example



Returning from a function

Let’s see how we can use values returned from a function.

Python return from a function

In the above screen display the different cases of return value from a function. It’s depend on your task in case your task required to return value then return one result value from function then assign this value to some variable where you call this function.

In case, you need return multiple value you can use reference type variable like array or you can also change value in passing argument if these are reference type and can be access out side the function. You will get more detail of reference variable in next topic Argument passing in Python.