VMware ESXi and vSphere Cluster Management

Python Arithmetic Operators

Learn Python arithmetic operators: addition, subtraction, multiplication, division, modulus, powers, floor division, precedence, and numeric results.

Python arithmetic operators let you perform mathematical calculations in code. You can use them with literal numbers such as 8 and 3.5, or with variables that store numeric values.

An arithmetic operator is a symbol that performs a mathematical operation on one or more values. An operand is a value or expression acted on by an operator. In 8 + 7, 8 is the left-hand operand, 7 is the right-hand operand, and + is the operator.

An expression is code that Python evaluates to produce a value. For example, both of these expressions calculate a result:

8 + 7
price * quantity

The first expression uses literal numbers. The second uses variables.

Python arithmetic operators

OperatorNameWhat it doesExample expressionExample result
+AdditionAdds values8 + 715
-SubtractionSubtracts the right operand from the left operand14 - 95
*MultiplicationMultiplies values6 * 530
/True divisionDivides the left operand by the right operand15 / 43.75
%ModulusReturns the remainder after division17 % 52
**ExponentiationRaises a base to a power2 ** 532
//Floor divisionReturns the quotient rounded down toward negative infinity17 // 53

Addition with +

The addition operator combines numeric values. The result of 8 + 7 is 15.

hours = 6
extra_hours = 2
total_hours = hours + extra_hours
print(total_hours)  # 8

Both operands can be expressions, variables, integers, or floats, provided the values can be added together.

Subtraction with -

Subtraction takes the value on the right away from the value on the left. Operand order matters:

14 - 9  # 5
9 - 14  # -5

Reversing the operands changes the result because subtraction is not commutative.

Multiplication with *

The multiplication operator multiplies numeric values:

boxes = 4
items_per_box = 6
total_items = boxes * items_per_box
print(total_items)  # 24

A single asterisk means multiplication. It is different from exponentiation, which raises a number to a power and uses two asterisks:

2 * 5   # 10
2 ** 5  # 32

True division with /

True division divides the left operand by the right operand. In Python 3, the / operator produces a float, even when the mathematical result is a whole number.

15 / 4  # 3.75
12 / 3  # 4.0

The right operand is the divisor. It cannot be zero. A zero divisor raises ZeroDivisionError.

10 / 0  # ZeroDivisionError

Modulus with %

The modulus operator returns the remainder left after division. A remainder is the amount that remains after forming complete groups.

For 17 % 5, five fits into seventeen three times. Three groups account for 3 * 5 = 15, leaving 2:

17 % 5  # 2
# 17 == (3 * 5) + 2

The divisor for % also cannot be zero. Otherwise Python raises ZeroDivisionError.

Common modulus uses

  • Test whether an integer is even: number % 2 == 0.
  • Test whether an integer is odd: number % 2 == 1 for nonnegative integers.
  • Perform an action at regular intervals: item_number % 3 == 0 identifies every third item.
24 % 2  # 0, so 24 is even
25 % 2  # 1, so 25 is odd

item_number = 6
if item_number % 3 == 0:
    print("Every third item")

With negative operands, modulus follows Python's floor-division rule. Therefore, reason about % together with // rather than assuming that it always behaves like truncation toward zero.

Exponentiation with **

Exponentiation raises a base to a power. In 2 ** 5, 2 is the base and 5 is the exponent:

2 ** 5  # 32

This means multiplying five factors of two: 2 * 2 * 2 * 2 * 2. Do not confuse ** with *: 2 * 5 is 10, while 2 ** 5 is 32.

Floor division with //

Floor division returns a quotient rounded down toward negative infinity. It does not always truncate toward zero.

17 / 5   # 3.4
17 // 5  # 3

-17 / 5   # -3.4
-17 // 5  # -4

The negative result is -4 because -4 is the next whole number down from -3.4. This differs from truncation toward zero, which would produce -3.

The result type depends on the operand types. Two integers usually produce an integer floor-division result, while a calculation involving a float produces a float:

17 // 5    # 3
17.0 // 5  # 3.0

Division, floor division, and modulus together

For a nonzero divisor b, Python's division and remainder operations follow this identity:

a == (a // b) * b + (a % b)

For example, with a = 29 and b = 6:

29 // 6  # 4
29 % 6   # 5

29 == (29 // 6) * 6 + (29 % 6)
29 == 4 * 6 + 5
29 == 29

Floor division tells you how many complete groups fit. Modulus tells you how many items remain. This makes them useful together for tasks such as dividing attendees into groups:

attendees = 29
group_size = 6
full_groups = attendees // group_size
remaining = attendees % group_size

print(full_groups)  # 4
print(remaining)   # 5
ExpressionMeaningResult type or value behaviorTypical use
a / bTrue divisionProduces a float in Python 3Calculations requiring a fractional quotient
a // bFloor divisionRounds the quotient down toward negative infinity; type depends on operandsComplete groups or a floor quotient
a % bModulusReturns the remainder associated with Python's floor-division ruleEven/odd tests, cycles, and leftovers

Expression evaluation and precedence

Operator precedence is the set of rules that determines which operations Python evaluates first. Parentheses group part of an expression and explicitly control its order.

2 + 3 * 4      # 14
(2 + 3) * 4    # 20

Without parentheses, multiplication happens before addition. With parentheses, the addition happens first.

PriorityOperatorsEvaluation notes
HighestParenthesized expressionsEvaluate the grouped expression first
Next**Exponentiation; it associates from the right
Next*, /, //, %These arithmetic operators share a precedence level and are generally evaluated left to right
Lowest+, -These operators are generally evaluated left to right

Most operators at the same arithmetic precedence are evaluated left to right:

20 / 5 * 2  # (20 / 5) * 2, which is 8.0

Exponentiation is the important exception in this group: it associates from the right.

2 ** 3 ** 2       # 2 ** (3 ** 2), which is 512
(2 ** 3) ** 2     # 64

Use parentheses when the intended grouping is important or when they make the expression easier to read.

Numeric types and arithmetic results

An integer is a whole-number numeric type, such as 4 or -17. A float can represent decimal values, such as 3.5 or -0.25.

whole = 8       # int
fraction = 2.5  # float

whole + fraction  # 10.5
8 / 2             # 4.0

Mixed integer-and-float calculations commonly produce a float. The value used for a calculation is separate from how it is displayed. For example, 12 / 3 produces the float 4.0; formatting the output as 4 would change its presentation, not the underlying division operation.

Try operators in the Python shell

The interactive Python shell lets you enter an expression and immediately inspect its result. Start it with the python command:

python
>>> 17 % 5
2
>>> 17 // 5
3
>>> 17 / 5
3.4
>>> 2 ** 5
32

You can also place the same expressions in a script and use print() to display their results.

Using the standard-library math module

The core arithmetic operators handle common calculations. For specialized mathematical functions, Python's standard library includes the math module. For example, math.sqrt() calculates a square root:

import math

math.sqrt(81)  # 9.0

Functions such as square roots and some rounding-related operations are better expressed with library functions than by combining basic operators. Learn the operators first, then use math when a named mathematical function fits the task.

Troubleshooting arithmetic expressions

Why does division include .0?

The / operator performs true division in Python 3 and returns a float. Use / when a fractional result is appropriate. Use // only when you specifically want floor division.

Why does % not calculate a percentage?

In an arithmetic expression, % means modulus: it returns a remainder. To calculate a percentage, use division and multiplication, such as part / whole * 100, when whole is nonzero.

Why is negative floor division unexpected?

// rounds down toward negative infinity, not toward zero. For example, -17 // 5 is -4. If truncation toward zero is specifically required for a numeric value, int(value) has that behavior for floats, but it is not a replacement for floor division in every calculation.

How do I prevent division by zero?

Check the divisor before using /, //, or %:

divisor = 0
if divisor != 0:
    result = 10 / divisor
else:
    print("Choose a nonzero divisor")

Without a guard or other error handling, a zero divisor raises ZeroDivisionError.

Why is the total not grouped as expected?

Python may have applied operator precedence, evaluating multiplication, division, floor division, modulus, or exponentiation before addition or subtraction. Add parentheses to state the intended order:

subtotal = (price * quantity) + shipping

Why did a power calculation multiply instead?

A single asterisk, *, means multiplication. Use two asterisks, **, for exponentiation.

Key points

  • Arithmetic operators combine operands to produce calculated values.
  • +, -, and * perform addition, subtraction, and multiplication.
  • / performs true division and returns a float in Python 3.
  • % returns a remainder and is useful for even/odd tests and repeating intervals.
  • ** raises a base to a power; it is not multiplication.
  • // performs floor division, rounding toward negative infinity.
  • For nonzero b, a == (a // b) * b + (a % b).
  • Use parentheses to make evaluation order explicit.

For related lessons, continue with arithmetic operators and then explore assignment, comparison, and logical operators.