Python arithmetic and operators
Calculate totals and distinguish division from floor division.
price = 12
quantity = 3
total = price * quantity
print(total)
print(7 / 2, 7 // 2, 7 % 2)
assert -7 // 2 == -436 3.5 3 1
Explanation
Operators combine values into expressions. Multiplication and division bind more tightly than addition; parentheses make an intended grouping explicit.
For integers, / produces a floating-point quotient, // floors the quotient, and % gives a remainder. Flooring a negative quotient moves toward negative infinity, not toward zero.
Explore the dry run
price = 12quantity = 3total = price * quantityprint(total)print(7 / 2, 7 // 2, 7 % 2)assert -7 // 2 == -4Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Bind the unit price. | price = 12 | — | |
| Bind the item count. | quantity = 3 | — | |
| Multiply 12 by 3. | total = 36 | — | |
| Print the computed total. | total = 36 | 36 | |
| Calculate the quotient, floor quotient, and remainder. | total = 36 | 36 3.5 3 1 | |
| Check negative floor division; a successful assertion prints nothing. | total = 36 | 36 3.5 3 1 |
Cost and common mistakes
A fixed number of operations for this bounded example; large Python integers have size-dependent arithmetic costs.
- Dividing by zero raises ZeroDivisionError.
- Binary floating-point cannot represent every decimal exactly; use decimal arithmetic where exact decimal rounding is required.
Try it yourself
Predict 17 // 5 and 17 % 5 before running them.
Reveal answer and reasoning
The quotient is 3 and the remainder is 2: 17 = 3 * 5 + 2.