Python · Course navigation

Python arithmetic and operators

Calculate totals and distinguish division from floor division.

On this page
Before you start

Variables and numeric values.

  • Calculate totals and distinguish division from floor division.
  • Predict the sample output and explain the state changes.
  • Complete the practice task and check the boundary cases.

The concept

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.

Code example

Python
price = 12
quantity = 3
total = price * quantity
print(total)
print(7 / 2, 7 // 2, 7 % 2)
assert -7 // 2 == -4
Output
36
3.5 3 1

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1price = 12
2quantity = 3
3total = price * quantity
4print(total)
5print(7 / 2, 7 // 2, 7 % 2)
6assert -7 // 2 == -4

Follow 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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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

Behind the scenes

How Python processes this code

Python runs this source through its interpreter. It creates objects for values and resolves names as each statement runs.

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.

Further reading