PythonPython Operators and ExpressionsPython arithmetic operators
What are arithmetic operators?
Question 42 of 88 · Updated
On this page
- 1. Arithmetic operators at a glance
- 2. True division versus floor division
- 3. Modulo and the quotient-remainder identity
- 4. Exponentiation and modular powers
- 5. Grouping powers and unary signs
- 6. Operand types determine arithmetic behavior
- 7. Choose the appropriate numeric representation
- 8. Practical example: calculate the number of pages
- 9. Practical example: convert seconds to hours, minutes and seconds
- 10. Practical example: circular positions and divisibility
- 11. Modulo versus other remainder functions
- 12. Common arithmetic errors
- Frequently asked questions
- What is the difference between / and //?
- Why is -7 % 3 equal to 2?
- Does % calculate a percentage?
- Is ^ exponentiation?
- Are arithmetic operations always constant-time?
- Interview-ready answer
- Official references
Arithmetic operators perform numerical calculations on operands. Python provides addition, subtraction, multiplication, true division, floor division, modulo and exponentiation. It also defines matrix multiplication syntax for types that support it. The exact behavior and result type depend on the operands.
This lesson builds on the general operator overview and focuses on arithmetic behavior, particularly quotient and remainder calculations, numeric precision, exponentiation and practical integer algorithms.
1. Arithmetic operators at a glance#
| Operator | Operation | Example | Result |
|---|---|---|---|
+ | Addition | 7 + 3 | 10 |
- | Subtraction | 7 - 3 | 4 |
* | Multiplication | 7 * 3 | 21 |
/ | True division | 7 / 2 | 3.5 |
// | Floor division | 7 // 2 | 3 |
% | Modulo | 7 % 2 | 1 |
** | Exponentiation | 2 ** 10 | 1024 |
@ | Matrix multiplication | A @ B | Depends on the operand types |
The plus and minus signs also have unary forms, which operate on a single operand.
PYTHONprint(+7, -7, 7+3, 7-3, 7*3)
Output:
7 -7 10 4 21The matrix multiplication operator was introduced in Python 3.5. Ordinary built-in scalar integers and floats do not implement it. Matrix and array libraries or custom classes may support it. Its meaning is not the same as ordinary multiplication, and its result depends on the shape and contract of the operands.
2. True division versus floor division#
PYTHONprint(7/2, 7//2, 7//2.0, -7//2, int(-7/2))
Output:
3.5 3 3.0 -4 -3The true division operator / produces a floating-point result for ordinary integer operands. Floor division // with integer operands returns the integer floor of the mathematical quotient. When a float participates in this built-in floor division, the result is a float, such as 3.0.
The distinction matters for negative values. The mathematical quotient -7/2 is -3.5; its floor is -4, whereas truncation toward zero gives -3.
Do not implement exact integer floor division by converting the result of / to int. Besides rounding in the wrong direction for negative nonintegral quotients, using a float intermediate can lose precision or exceed the floating-point range for large integers.
For integer operands and nonzero divisors, // produces the exact floor quotient. Floating-point floor division is subject to finite-precision effects. The preceding integer-versus-float lesson discusses these representation limits in detail.
3. Modulo and the quotient-remainder identity#
For integers a and nonzero b, Python defines quotient q and remainder r through the following relationship:
- q = a // b
- r = a % b
- a = q * b + r
A nonzero remainder has the same sign as the divisor b, and its absolute value is strictly smaller than the absolute value of b.
The built-in divmod(a, b) returns the quotient and remainder as a pair.
PYTHONfor a,b in [(7,3),(-7,3),(7,-3),(-7,-3)]: q,r=divmod(a,b) print(a,b,q,r,q*b+r==a)
Output:
7 3 2 1 True
-7 3 -3 2 True
7 -3 -3 -2 True
-7 -3 2 -1 True| Dividend a | Divisor b | a // b | a % b | Reconstruction |
|---|---|---|---|---|
| 7 | 3 | 2 | 1 | 2*3 + 1 = 7 |
| -7 | 3 | -3 | 2 | -3*3 + 2 = -7 |
| 7 | -3 | -3 | -2 | -3*(-3) - 2 = 7 |
| -7 | -3 | 2 | -1 | 2*(-3) - 1 = -7 |
For a positive divisor b, the remainder is in the range from zero through b - 1. This is why modulo is useful for circular indexes and periodic schedules.
Python's remainder rule differs from truncating-remainder conventions used in some other languages. Do not assume that the result for negative operands will match code translated from another language.
The identity above is exact for integers. Floating-point modulo, floor division and divmod can involve rounding effects, so exact real-number identities need not hold in machine arithmetic.
4. Exponentiation and modular powers#
The operator ** raises a base to a power. For ordinary integer operands and a nonnegative integer exponent, it produces an exact integer result, subject to resource constraints.
PYTHONprint(2**10, 2**-3, pow(7,5,13), pow(3,-1,11))
Output:
1024 0.125 11 4The negative exponent in 2-3 produces a float for these integer operands. The three-argument built-in pow computes modular exponentiation when supplied valid integer operands. In particular, pow(7, 5, 13) computes the same mathematical remainder as (75) % 13 without needing to construct the entire unreduced power.
Since Python 3.8, the three-argument integer form supports negative exponents when the modular inverse exists. Here pow(3, -1, 11) returns 4 because 3*4 has remainder 1 modulo 11. If no inverse exists, such as pow(2, -1, 4), it raises ValueError.
Modular exponentiation is useful in number-theoretic algorithms. Do not assume Python's built-in pow provides constant-time execution or other cryptographic side-channel guarantees.
For very large powers, computational cost and output size can grow rapidly. Arbitrary-precision integer support is not a promise of unlimited memory or constant-time exponentiation.
5. Grouping powers and unary signs#
PYTHONprint(2**3**2, (-2)**2, -2**2, 2**-2)
Output:
512 4 -4 0.25The first expression groups as 2(32), not (23)2. Parentheses around a negative base change the grouping. Exponentiation binds more tightly than a unary minus to its left, but permits a unary expression on its right.
The broader precedence and associativity topics will examine expression grammar in detail. For everyday arithmetic, use parentheses when they clarify the intended calculation.
6. Operand types determine arithmetic behavior#
PYTHONprint(2+0.5, (2+3j)*2, "ha"*3, [1]*0)
Output:
2.5 (4+6j) hahaha []The first operation uses floating-point arithmetic, the second uses complex arithmetic, and the last two perform sequence repetition rather than numerical multiplication.
Addition can also concatenate compatible sequences. However, a numerical addition expression such as 2 + "3" does not automatically parse the string as a number.
Operator support differs by numeric type. Built-in complex numbers support addition, subtraction, multiplication, true division and exponentiation but not floor division or modulo. Standard-library Decimal and Fraction implement their own arithmetic semantics; they should not be assumed to support every mixed-type operation.
7. Choose the appropriate numeric representation#
PYTHONfrom decimal import Decimal from fractions import Fraction print(Decimal("0.1")+Decimal("0.2"), Fraction(1,3)+Fraction(1,6))
Output:
0.3 1/2Integers represent exact whole quantities. Floats are suitable for many approximate numerical computations. Decimal provides decimal arithmetic with a configurable context, and Fraction represents rational numbers using integer components.
The Decimal example starts from strings to avoid importing a pre-existing binary floating-point approximation. Decimal arithmetic may still round according to its context. Fraction preserves exact rational values but can require growing integer numerators and denominators.
Choose a representation based on the problem's semantics. For financial software, define currency units and rounding rules explicitly. For physical measurements, choose an appropriate precision and tolerance rather than assuming every float result must be exactly equal to a decimal target.
8. Practical example: calculate the number of pages#
A pagination function must account for a partially filled final page. Dividing the number of items by page size and rounding a float can introduce unnecessary precision problems.
PYTHONdef pages(n,size): if n<0 or size<=0: raise ValueError("invalid input") q,r=divmod(n,size) return q+bool(r) print([pages(n,10) for n in (0,1,10,11,25)])
Output:
[0, 1, 1, 2, 3]The function assumes integer item counts and page sizes. It returns zero pages for zero items. For 25 items and page size 10, the quotient is 2 and remainder is 5, so the result is 3.
A production interface should validate the input types and relevant range limits. An application may intentionally choose a different zero-item pagination convention.
For nonnegative n and strictly positive size, the expression (n + size - 1) // size is another exact integer solution. divmod is useful when the remainder is also needed.
The calculation uses a bounded number of integer operations and local variables. This is O(1) under a fixed-size arithmetic model, but arbitrary-precision integer operations depend on the sizes of the operands.
9. Practical example: convert seconds to hours, minutes and seconds#
PYTHONdef split_seconds(total): hours,rem=divmod(total,3600) minutes,seconds=divmod(rem,60) return hours,minutes,seconds print(split_seconds(3661))
Output:
(1, 1, 1)The function is intended for nonnegative integral durations. It first extracts whole hours, then splits the remaining seconds into minutes and seconds. For 3661 seconds, the result is 1 hour, 1 minute and 1 second.
This example shows how quotient and remainder operations naturally decompose a quantity into larger and smaller units without floating-point conversions.
10. Practical example: circular positions and divisibility#
PYTHONprint((23+5)%24, (2-5)%24) print([n for n in range(1,7) if n%2==0])
Output:
4 21
[2, 4, 6]The first expression wraps 28 back into the range of a 24-hour clock. The second wraps a negative position into the same range. The final expression selects even integers.
For a positive integer cycle length m, x % m normalizes an integer position to the interval from zero to m - 1. In real date-and-time applications, use suitable datetime and timezone handling; simple modulo does not account for calendar changes or daylight-saving transitions.
For n candidate values, the filtering example uses O(n) modulo tests under a bounded-size integer cost model, and O(k) additional list storage for k selected elements.
11. Modulo versus other remainder functions#
The standard-library math module provides fmod and remainder, which follow different remainder conventions.
PYTHONimport math print(-7%3, math.fmod(-7,3), math.remainder(7,4))
Output:
2 -1.0 -1.0For the finite values in this example:
- Python integer % uses the floor-division remainder rule.
- math.fmod returns a floating-point remainder with the sign of the dividend when nonzero.
- math.remainder follows the IEEE 754 remainder convention, based on the nearest integer quotient with ties to even.
These are not interchangeable functions. Choose the one required by the mathematical or numerical algorithm.
12. Common arithmetic errors#
The following independent tests illustrate invalid or unsupported operations.
| Expression | Expected exception | Reason |
|---|---|---|
1/0 | ZeroDivisionError | Division by zero |
1//0 | ZeroDivisionError | Floor division by zero |
1%0 | ZeroDivisionError | Modulo by zero |
2+"3" | TypeError | Incompatible operands |
1@2 | TypeError | Scalar integers do not implement matrix multiplication |
pow(2,-1,4) | ValueError | Modular inverse does not exist |
0**-1 | ZeroDivisionError | Negative power of zero |
(1+2j)//2 | TypeError | Complex floor division is unsupported |
Handle expected exceptions at the relevant boundary. Validate divisors, operand types and application-specific limits. Avoid catching every exception simply to hide an arithmetic problem.
Frequently asked questions#
What is the difference between / and //?#
For ordinary integer operands, / returns a float representing true division, while // returns the exact integer floor quotient. Floor division is not truncation toward zero.
Why is -7 % 3 equal to 2?#
The floor quotient is -3. The remainder must satisfy -7 = (-3)*3 + 2, so the remainder is 2.
Does % calculate a percentage?#
No. In ordinary numeric arithmetic it calculates a remainder. To calculate 15 percent of 200, use 200 * 15 / 100, with an appropriate numeric representation and rounding policy.
Is ^ exponentiation?#
No. For ordinary integers, ^ is bitwise XOR. Use ** for exponentiation.
Are arithmetic operations always constant-time?#
No. Operation costs depend on operand sizes, numeric representations, sequence lengths and any custom implementation. Large integer arithmetic is not constant-time in the general case.
Interview-ready answer#
Python arithmetic operators include + for addition, - for subtraction, * for multiplication, / for true division, // for floor division, % for modulo and ** for exponentiation. The @ operator supports matrix multiplication for compatible types. For integers with nonzero divisors, a = (a // b)*b + a % b, and divmod returns both parts. Floor division rounds toward negative infinity, so negative operands require care. Operand types determine the operation's actual semantics and result type. Use exact integer arithmetic for discrete counts, choose appropriate representations for decimal or approximate values, and account for zero division, precision and resource constraints.
Official references#
- Python Language Reference — Binary arithmetic operations
- Python Language Reference — The power operator
- Python Standard Library — Numeric types
- Python Standard Library — divmod
- Python Standard Library — pow
- Python Standard Library — math
- Python Standard Library — decimal
- PEP 465 — A dedicated infix operator for matrix multiplication
Verification note: Eleven independent output-based examples and eight expected-exception tests passed on CPython 3.13.5. The Mermaid quotient-remainder flowchart was manually reviewed for syntax and mathematical accuracy. The local Mermaid package and CLI were unavailable, so parser-level validation and live-site rendering were not performed. Official reference links are supplied under the authorized offline research exception; live documentation and the Supabase changelog were not checked.
References
- 1.Python Language Reference — Binary arithmetic operationsdocs.python.org
- 2.Python Standard Library — Numeric typesdocs.python.org
- 3.Python Standard Library — divmoddocs.python.org
- 4.Python Standard Library — mathdocs.python.org
- 5.Python Standard Library — decimaldocs.python.org
- 6.
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design