Defining Functions
In this lesson, you will learn to write your own functions. Let's start with a problem: we need the areas of three rectangles. The area of a rectangle is its width times its height, so we could write:
width1 = 5
height1 = 6
area1 = width1 * height1
print(area1)
width2 = 10
height2 = 5
area2 = width2 * height2
print(area2)
width3 = 1
height3 = 5
area3 = width3 * height3
print(area3)This prints:
30
50
5It works, but we wrote the same four lines three times, and only the numbers changed. Imagine a hundred rectangles! And if we found a mistake in the calculation, we would have to fix it in a hundred places.
Programmers try not to repeat code. Instead, they write the repeated part once, give it a name and then use it wherever they need it. Such a named piece of code is called a function.
You have already used functions that come with Python, such as print(), len(), str() or sum(). Now you will write your own. Creating a function is called defining it:
def say_hello():
print("Hello!")
print("Have a nice day!")A function definition has these parts:
- The keyword
def(short for define), which tells Python that a function follows. - The name of the function, here
say_hello. It follows the same rules as variable names: no spaces, and names made of several words are written in snake_case. Choose a name that says what the function does, such assay_helloorprint_area. - Parentheses
(). They are empty for now; you will soon find out what goes in them. - A colon
:at the end of the line, just like afteriforfor. - The indented block of code below the first line, called the body of the function. It holds the commands the function runs. The body ends where the indentation ends.
When you run this code, nothing is printed. That's not a mistake! A definition only tells Python what the function should do, like a recipe written down in a cookbook: nobody has cooked anything yet. In the next exercise, you will make the function run.
Watch out for the colon and the indentation. Without the colon, the program ends with the error SyntaxError: expected ':'. When the body isn't indented, you get IndentationError: expected an indented block after function definition on line 1.
Instructions
Create a function named first_function whose body prints This is my first function!. Then run the program: nothing is printed yet, and that's how it should be.