Introduction to Functions
In this chapter, we will get acquainted with functions in Python. Imagine that you need to calculate the area of three rectangles. For that, we need their width and height and multiply them. We could do this with the following code:
width1 = 5
height1 = 6
area1 = width * height
print(area1) # Outputs 30
width2 = 10
height2 = 5
area2 = width * height
print(area2) # Outputs 50
width3 = 1
height3 = 5
area3 = width * height
print(area3) # Outputs 5
This is tedious and you can surely imagine that calculating the area of 100 rectangles this way is madness.
In programming, we generally try to avoid repeating the same code multiple times. Instead, we can group the repeating part of the code and reuse it. We achieve this using functions. A function is a reusable piece of code that solves a specific problem.
Instructions
When you are ready, proceed to the next exercise!
Start programming for free
1/7