Functions

This lesson will introduce functions in Python.

Function

A function in a programming language is a reusable block of code that will be executed when called. You can pass data to it and it can return data as well.

Think of a function as a box that performs a task. We give it an input and it returns an output. We don’t need to write the code again for different inputs, we could just call the function again.

Until now, we have only been using print and len. Both of these are functions. They perform a specific predetermined task. These are called built-in functions as they come with the Python language. Similarly, there are many other functions that come built-in.

Let’s say we want to find the minimum of two numbers.

Press + to interact
num1 = 10
num2 = 40
# code to check minimum number
if num1 < num2:
minimum = num1
else:
minimum = num2
print(minimum)
num1 = 250
num2 = 120
# code to check minimum number
if num1 < num2:
minimum = num1
else:
minimum = num2
print(minimum)
num1 = 100
num2 = 100
# code to check minimum number
if num1 < num2:
minimum = num1
else:
minimum = num2
print(minimum)

For every new pair of integers, we need to write the if-else statement again. This could become much simpler if we had a function to perform the necessary steps for calculating the minimum. The good news is that Python already has the min function:

Press + to interact
# find minimum using function
minimum = min(10,40)
print(minimum)
# find minimum using function
minimum = min(250,120)
print(minimum)
# find minimum using function
minimum = min(100, 100)
print(minimum)
# It even works with multiple arguments
minimum = min(100,120,34,56)
print(minimum)

We use the min function just like we use ...

Access this course and 1400+ top-rated courses and projects.