Add/subtract
- Python course
- Beginner
- Lesson 20/116
- 6 min
Write add and subtract functions.
Defining functions (def)
In this lesson we'll introduce the function concept. A function is a reusable block of code. It is defined with def:
def add(x, y):
return x + yThe def add(x, y) line names the function and its parameters. The indented block is the body. return sends the result out.
You call the function as add(3, 5); the result is 8. We'll cover functions in detail later.
Addition and subtraction
We'll add addition and subtraction functions to the calculator. Each takes two parameters and returns a number:
def add(x, y):
return x + y
def subtract(x, y):
return x - yWhen calling, we pass values to the parameters: add(10, 5) returns 15, subtract(10, 5) returns 5.
Practice Add addition and subtraction
From the previous lesson a = 10 and b = 5 are already defined. Now add the add(x, y) and subtract(x, y) functions. Then print print(add(a, b)) and print(subtract(a, b)).
Starter code
# Calculator - define two numbers
a = 10
b = 5
print(a, b)
# Add addition and subtraction functionsSample solution
def add(x, y):
return x + y
def subtract(x, y):
return x - y
print(add(a, b))
print(subtract(a, b))Expected output
10 5 15 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the function body
def add(x, y):
____ x + y
def add(x, y):
return x + y
Explanation: return sends the result out of the function.
2 What does add(3, 4) return for def add(x, y): return x + y?
- 34
- 7 Correct answer
- 3
- It raises an error
Explanation: add(3, 4) returns 3 + 4 = 7.
3 Match the function concepts
| Term | Meaning |
|---|---|
def |
Function definition |
return |
Returning a result |
add(3, 5) |
Function call |
x, y |
Parameters |