Lesson 9 of 10
Python supports all the arithmetic you'd expect, plus a couple of operators unique to programming languages.
| Operator | Meaning | Example | Result |
| --- | --- | --- | --- |
| + | Addition | 5 + 2 | 7 |
| - | Subtraction | 5 - 2 | 3 |
| * | Multiplication | 5 * 2 | 10 |
| / | Division (always returns a float) | 5 / 2 | 2.5 |
| // | Floor division (rounds down to an int) | 5 // 2 | 2 |
| % | Modulo (remainder) | 5 % 2 | 1 |
| ** | Exponent (power) | 5 ** 2 | 25 |
print(5 + 2)
print(5 / 2)
print(5 // 2)
print(5 % 2)
print(5 ** 2)
Floor division vs. regular division
/ always gives you a float, even when the numbers divide evenly. // rounds the result down
to the nearest whole number. This distinction matters a lot once you start working with things
like pagination or splitting items into groups.
print(10 / 3)
print(10 // 3)
Modulo — a surprisingly useful operator
% gives you the remainder of a division. It's the standard way to check things like "is this
number even?" (an even number has a remainder of 0 when divided by 2).
print(7 % 2)
print(8 % 2)
Operator precedence
Just like in math class, Python evaluates some operators before others. ** runs first, then
*, /, //, % (left to right), then + and - (left to right). Parentheses () always
run first and can be used to force a specific order.
print(2 + 3 * 4)
print((2 + 3) * 4)
print(2 ** 3 + 1)
Try it yourself
Given the numbers 17 and 5, print the result of dividing them with /, //, and %.
Checkpoint
/always returns a float;//floors to an int;%gives the remainder.**is exponentiation.- Precedence: parentheses, then
**, then* / // %, then+ -.
Questions about this lesson
Log in to ask a question.