Functions
This lesson will introduce functions in Python.
We'll cover the following...
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.
num1 = 10num2 = 40# code to check minimum numberif num1 < num2:minimum = num1else:minimum = num2print(minimum)num1 = 250num2 = 120# code to check minimum numberif num1 < num2:minimum = num1else:minimum = num2print(minimum)num1 = 100num2 = 100# code to check minimum numberif num1 < num2:minimum = num1else:minimum = num2print(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:
# find minimum using functionminimum = min(10,40)print(minimum)# find minimum using functionminimum = min(250,120)print(minimum)# find minimum using functionminimum = min(100, 100)print(minimum)# It even works with multiple argumentsminimum = min(100,120,34,56)print(minimum)
We use the min
function just like we use ...