One-sentence summary
A function lets us give a name to a piece of code that does a job, so we can run that job again and again with a single line whenever we need it.
Why does it matter?
As a program grows, we often need to do the same job in more than one place. You calculate the area of a rectangle here, then somewhere else, then again. Writing the same lines over and over is tiring and easy to get wrong: you fix one copy and forget the other.
Functions solve this. We write a job once, give it a name, and then run the whole job again just by saying that name. Our code gets shorter, easier to read, and if there is a mistake we only have to fix it in one place. Functions are the most basic tool for the idea of "do not repeat yourself" in programming.
What is a function?
You can picture a function like a ready-made recipe attached to a button. You write the recipe once; then, whenever you like, you press the button and the recipe runs.
In Python a function is defined with the keyword def. def is short for "define."
def say_hello():
print("Hello!")
print("Today we are writing code.")
Here say_hello is the name of the function, the () parentheses show it is a function, and the : at the end of the line marks the start of a block. The two lines inside are written 4 spaces to the right. This shift to the right is called indentation, and Python requires it: indented lines are the body of the function, the work it does when it runs.
Notice something: running the code above prints nothing. That is because we only defined the function; we have not called it yet. To run a function we write its name followed by parentheses:
def say_hello():
print("Hello!")
print("Today we are writing code.")
say_hello()
say_hello()
This program prints "Hello!" and "Today we are writing code." twice. We wrote the recipe once and called it twice. That is the power of a function.
Parameters and return
The function above does the same thing every time. But usually we want to give a function some information and let it work based on that. The information we pass into a function is called a parameter.
Parameters: giving the function information
We write parameters inside the parentheses. Let us write a function that calculates the area of a rectangle. Since area = width × height, we give the function two pieces of information:
def print_area(width, height):
area = width * height
print("Area:", area)
print_area(5, 3)
print_area(10, 2)
Here width and height are parameters. When we call print_area(5, 3), width becomes 5 and height becomes 3, and the screen shows Area: 15. The second call prints Area: 20. The same function produced different results from different values.
return: giving the result back
print_area shows the result on the screen but does not give it back to us. Often we want to return the result instead of printing it, so we can use it in another step. For that we use return. return means "send the value I calculated back to wherever the function was called."
def calculate_area(width, height):
return width * height
first = calculate_area(5, 3)
second = calculate_area(10, 2)
print("Total area:", first + second)
Here calculate_area(5, 3) gives us back the value 15, and we store it in the variable first. In the same way second becomes 20. Then we add the two results and print Total area: 35.
Do not forget the difference between print and return: print only shows something on the screen, while return gives the value back to be used in the program. When a return runs, the function stops right there.
Reusing code and local variables
Now let us write a function that tells us whether a number is even. A number is even if it divides by 2 with nothing left over. We check this with % 2 == 0 (% gives the remainder).
A function that returns true or false
def is_even(number):
if number % 2 == 0:
return True
else:
return False
print(is_even(4))
print(is_even(7))
This program prints True first, then False. The is_even function works like answering "yes" or "no" to a question. Now we can use this function again and again for every number in a list:
numbers = [3, 8, 11, 20, 15]
for number in numbers:
if is_even(number):
print(number, "is even")
else:
print(number, "is odd")
We wrote the function once and called it five times inside the loop. The code stays short and clear.
What is a local variable?
Variables we create inside a function live only inside that function. These are called local variables. When the function ends, these variables disappear and we cannot reach them from outside.
def calculate_area(width, height):
area = width * height
return area
print(calculate_area(4, 6))
print(area) # ERROR: area is not defined here
The area variable here lives inside the calculate_area function. Outside the function, writing print(area) makes Python raise an error, because area is not defined there. This is actually a good thing: each function works with its own boxes and does not accidentally break another function's variables.
Mini practice
Write a function that tells whether a student's grade is a pass or a fail.
- Define a function called
passedthat takes agradeparameter. - Return
Trueif the grade is 50 or higher, andFalseotherwise. - Call the function with a few different grades and print the result.
A hint to get started:
def passed(grade):
if grade >= 50:
return True
else:
return False
print(passed(75))
print(passed(40))
After you write your own solution, try this: put the grades in a list and check them all one by one with a loop.
Common mistakes
Forgetting to call the function
Writing a function with def does not run it. To make a function run, you have to write its name followed by parentheses.
def say_hello():
print("Hello!")
say_hello # wrong: the function does not run
say_hello() # right: the function runs
Using only print instead of return
If you are going to use the result somewhere else, print is not enough; you have to give the value back with return. print only writes to the screen and leaves no value behind.
Getting the number of parameters wrong
If a function expects two parameters, you must call it with two values. If you give too few or too many, Python raises an error.
def calculate_area(width, height):
return width * height
calculate_area(5) # ERROR: height was not given
Trying to reach a local variable from outside
A variable inside a function is not defined outside it. If you want to use that value outside, return it with return.
Safety note
Functions will not harm your computer, but you should not run every piece of code you find online without thinking. Only run code that you wrote yourself or that your teacher or parent trusts. Also, do not put personal information such as your name, address, or school inside your code, and do not share such details with others.
Lesson summary
- A function gives a name to a job so we can run it again whenever we want.
- Functions are defined with
defand called by writingname(). - Parameters are the information we pass into a function from outside.
returngives back the value a function calculated;printonly writes to the screen.- Local variables created inside a function live only inside that function.
Review questions
- Which keyword do we use to define a function in Python?
- Is defining a function enough to run it? What do we need to do to run it?
- What is a parameter?
- What is the main difference between
printandreturn? - What does a local variable mean?
Answers
- We define it with the
defkeyword. For example,def say_hello():starts a function. - No, it is not enough. Defining is like writing the recipe; to run it we have to write the function's name followed by parentheses, that is, call it:
say_hello(). - A parameter is information we pass into a function from outside. The function works based on this information. For example, in
calculate_area(width, height),widthandheightare parameters. printonly shows a value on the screen; it leaves no result behind.returngives the value back to wherever the function was called, so we can store it in a variable or use it in another step.- A local variable is a variable created inside a function that lives only inside that function. When the function ends it disappears, and it cannot be reached from outside.
Source and verification note
For “Functions”, verification focuses on whether the relationship between What is a function? and Parameters: giving the function information remains consistent across examples. Code examples follow Python 3 syntax. Small differences may appear between environments, so examples should first be tested in a safe online editor or a local development setup.
Next lesson
Reading Error Messages: When Python raises an error, we learn to read the message calmly and find the type of error and the line where it happened.