Python Functions

In Python programming, a function is a block of statements that perform a specific task. It is really useful when we are to write the same code repeatedly in a program. Python uses the keyword “def” to define a function. It is important to use proper indentation to define functions like declaring conditions, loops etc.

We may pass data, called parameters, into a function. A function may also return data as a result. Python provides many in-built functions like print(), but it also provides the liberty to create our own functions. 

The following example shows how to create and call a simple user-defined function: 

# Function Definition
def function():
print("Learning Python is a fun!")

# Function Call
function()

Output:

Learning Python is a fun!
 

Parameter passing in a function

We can send any types of parameter to a function (e.g. number, string, list, tuple, dictionary etc.), and they will be considered as the same type inside the function.

See the example below which uses a list as the parameter to a function: 

# Function Definition
def function(countries):
for element in countries:
print(element)

# A sample list of countries
countries = ["India", "Australia", "England", "New Zealand"]

# Function Call
function(countries)

Output:

India
Australia
England
New Zealand

 

Functions return values

A function may return a value using the return statement. See the code below:

# Function Definition
def function(a, b):
return a + b

# Two sample numbers
x = 12.3
y = 23.2

# Function Call
z = function(x, y)
print("SUM:", z)

Output:

SUM: 35.5