Multiply/divide
- Python course
- Beginner
- Lesson 21/116
- 6 min
Add multiply, divide and zero check.
Multiplication and division
Now we'll add multiplication and division to the calculator. These functions use the same structure:
def multiply(x, y):
return x * y
def divide(x, y):
return x / yMultiplication uses *, division uses /. The division result is always a float: 10 / 5 gives 2.0.
Division has one problem: if the second number is zero, you get ZeroDivisionError. To prevent this we'll learn if and try/except in the next lesson.
Zero check (if)
Division by zero raises an error. The first way to prevent this is to check with if:
def divide(x, y):
if y == 0:
return 0
return x / yThe if y == 0: line runs the indented block when y is zero. == is an equality comparison. We'll cover if in detail in a separate group.
Practice Add multiplication and division
The previous functions are ready. Now add the multiply(x, y) and divide(x, y) functions (divide should have an if y == 0: return 0 check). Then print print(multiply(a, b)) and print(divide(a, b)).
Starter code
# Calculator - define two numbers
a = 10
b = 5
print(a, b)
def add(x, y):
return x + y
def subtract(x, y):
return x - y
print(add(a, b))
print(subtract(a, b))
# Add multiplication and division functionsSample solution
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return 0
return x / y
print(multiply(a, b))
print(divide(a, b))Expected output
10 5 15 5 50 2.0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the result of 10 / 5?
- 2
- 5
- 2.0 Correct answer
- It raises an error
Explanation: Division always returns a float: 2.0.
2 Complete the multiply function
def multiply(x, y):
return x ____ y
def multiply(x, y):
return x * y
Explanation: Multiplication uses the * operator.
3 Match the operators
| Term | Meaning |
|---|---|
+ |
Addition |
- |
Subtraction |
* |
Multiplication |
/ |
Division |