Skip to content
CodeKruPro

Predict the output · Python

Numbers and arithmetic

Integer division, remainders, overflow, decimals and rounding.

Learn: Predicting what Python arithmetic prints7 minute read

Python arithmetic looks friendly, but interviewers like it because several rules differ from Java and from school maths. Testers meet these rules when they check totals, averages, rounding in reports and IDs read from text. A question here usually hides one rule: which kind of division, which way rounding goes, or how floats are stored. Here are the rules, basics first.

The number types you need

int holds whole numbers of any size. float holds numbers with a fraction, stored in 64-bit binary like Java's double. bool holds True or False and, as you will see, is a kind of int.

Rule 1: / always gives a float, // floors

In Python 3, / is true division and always returns a float, even when the result is whole: 8 / 2 is 4.0. // is floor division: it rounds down, toward the smaller number (minus infinity), not toward zero. So -9 // 4 is -3, while Java's -9 / 4 gives -2. The remainder % takes the sign of the right operand, which keeps (a // b) * b + a % b equal to a. For example, -9 // 4 is -3 and -9 % 4 is 3, and -3 * 4 + 3 is -9 again. divmod(a, b) returns both parts as a tuple, a fixed group of values such as (-3, 3).

int() on a float behaves differently: it cuts toward zero, so int(-2.7) is -2.

Rule 2: round() sends halves to the nearest even number

round(2.5) is 2 and round(3.5) is 4. Exact halves go to the nearest even number, which avoids pushing totals upward when many values are rounded. Values that are not exact halves round as usual. Because floats are binary, a value that looks like a half may not be one: 2.675 is stored a little below 2.675, so round(2.675, 2) is 2.67. The same half-to-even rule applies in f-strings such as f"{2.5:.0f}".

print(9 / 4, 9 // 4, -9 // 4, -9 % 4)
print(8 / 2)
print(int(-2.7), round(2.5), round(3.5))
2.25 2 -3 3
4.0
-2 2 4

Rule 3: ints never overflow

A Python int grows as large as memory allows. 2 ** 70 (2 to the power 70) prints every digit, and there is no separate long type. A question that expects a wrapped negative number, as in Java, has no such answer in Python.

Rule 4: floats are approximations

0.1 has no exact binary form, so it is stored as the nearest possible value. The small errors show up in sums: 0.1 + 0.2 prints 0.30000000000000004, so 0.1 + 0.2 == 0.3 is False. Changing the order of additions can change the last digit. Use math.isclose to compare, and the decimal module (a ready-made set of tools that you import) for money.

Rule 5: bool is a kind of int

True and False behave as 1 and 0 in arithmetic, because bool is a subclass of int (a special kind of int). True + True is 2, and sum() over booleans counts the true ones. It also means 1, 1.0 and True are equal and count as the same dictionary (dict) key.

print(2 ** 70)
print(0.1 + 0.2)
print(True + True)
1180591620717411303424
0.30000000000000004
2

Rule 6: dividing by zero always raises

Unlike Java, Python raises ZeroDivisionError for floats too: 1.0 / 0 raises an error that stops the program. Python does have infinity and NaN ("not a number"), but you create them on purpose with float("inf") and float("nan"). NaN is not equal to anything, itself included; test for it with math.isnan.

Rule 7: conversions are strict about text

int("42") works, and so does int(" 42 "), because surrounding whitespace is allowed. int("4.2") raises ValueError, the error for text that is not a valid whole number; use float first. A second argument is the base: int("ff", 16) is 255.

How to answer in an interview

Name the operator and the rule, then give the value. "// floors toward minus infinity, so -7 // 2 is -4, not -3 as in Java." For float questions, say the stored value is approximate and name the fix: math.isclose in assertions (the checks in test code), Decimal for money. Comparing with Java when the two languages differ is a quick way to show depth.

Common mistakes

  • Expecting 6 / 2 to print 3.
  • Rounding -7 // 2 toward zero.
  • Expecting round(2.5) to be 3.
  • Comparing floats with == in tests.
  • Expecting 1.0 / 0 to give infinity.

Recap

/ always gives a float and // floors, with the remainder following the divisor's sign. round sends halves to even. Ints never overflow, floats are approximate, bool is an int, and any division by zero raises an error.

10 questions0/10 solved

Not startedNot startedIn progressIn progressSolvedSolvedPro+Pro+

The first 2 questions of each topic are free. Pro+ opens every question.

Back to the plan