Intro to Computer Science / Unit 4: Programming Basics in Python
4.3 Arithmetic Operators
Notes
Python can do math with these operators:
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ - * | add, subtract, multiply | 4 * 3 | 12 |
/ | division (always a float) | 7 / 2 | 3.5 |
// | floor division | 7 // 2 | 3 |
% | remainder (modulus) | 7 % 2 | 1 |
** | exponent | 2 ** 3 | 8 |
- Order of operations: parentheses, then
**, then*///%, then+-. 10 / 2gives5.0, a float, not5.n % 2 == 0is a common test for an even number.
Practice
What does
print(17 % 5) display?17 divided by 5 is 3 remainder 2, and % gives the remainder.
What does
print(2 + 3 * 4) display?Multiplication comes first: 3 * 4 = 12, then 2 + 12 = 14.
What does
print(10 // 4) display?Floor division gives the whole-number part of 2.5, which is 2.
Ready for more? Take the Unit 4 test.