Arithmetic
Operators are symbols like + that do math. Python has operators for the usual calculations, plus one for powers and two kinds of division:
| Operator | Operation | Example result |
|---|---|---|
+ | Addition | 7 + 2 gives 9 |
- | Subtraction | 7 - 2 gives 5 |
* | Multiplication | 7 * 2 gives 14 |
** | Exponentiation | 7 ** 2 gives 49 |
/ | True division | 7 / 2 gives 3.5 |
// | Floor division | 7 // 2 gives 3 |
% | Remainder | 7 % 2 gives 1 |
first = 20
second = 6
difference = first - second
product = first * second
quotient = first / second
remainder = first % second
print("Difference:", difference)
print("Product:", product)
print("Quotient:", quotient)
print("Remainder:", remainder)
Output:
Difference: 14
Product: 120
Quotient: 3.3333333333333335
Remainder: 2
Each result is stored in its own variable. The / operator does true division, which gives the full answer with decimals. It always returns a float. Here the quotient is 3.3333333333333335. The % operator gives the remainder. Three 6s make 18, so 2 is left over from 20.
Floor division, powers, and order
print(20 // 6)
print(2 ** 3)
print(2 + 3 * 4)
print((2 + 3) * 4)
Output:
3
8
14
20
// divides and throws away the remainder. It tells you how many full groups of 6 fit into 20, which is 3. ** raises 2 to the power 3, which means 2 * 2 * 2.
The last two lines show precedence, the order in which Python does the operations. Python multiplies before it adds, so 2 + 3 * 4 gives 14. Parentheses change the order, so (2 + 3) * 4 gives 20.
In the exercise, calculate an order total with multiplication and addition.