Numbers

int and float, two kinds of division, remainder and rounding.

Python has two main numeric types. int is whole numbers of any size: 2 ** 100 is computed exactly. float is numbers with a fractional part, written with a dot: 3.5. In big numbers you can add underscores for readability: 1_000_000.

There are two kinds of division. The / operator always gives a float: 6 / 3 is 2.0. The // operator divides and rounds down to a whole number, and % gives the remainder:

print(17 // 5)   # 3
print(17 % 5)    # 2
print(-7 // 2)   # -4

Note -7 // 2: the result is -4, because rounding goes down, towards minus infinity, not towards zero.

The remainder is handy for "is the number even" (n % 2 == 0) and "how many are left after packing into boxes". ** raises to a power.

Fractions are stored in binary, so many decimal fractions are only approximated. The famous example: 0.1 + 0.2 gives 0.30000000000000004, and the comparison 0.1 + 0.2 == 0.3 is false. This is not a Python bug, the format works this way in every language. Money is counted in whole cents or with the decimal module, and fractional results are compared with a tolerance.

round(x, 2) rounds to two decimal places. Halves are rounded to the nearest even number: round(2.5) gives 2, while round(3.5) gives 4. This keeps errors from piling up in long calculations.

A string is turned into a number with int("42") and float("3.5"). If the string is not a number, you get a ValueError. abs, min and max return the absolute value, the minimum and the maximum.

Practice

  1. Quotient and remainder

    What does the program print?

    print(7 // 2, 7 % 2)
    
  2. Precision of fractions

    Why does the expression 0.1 + 0.2 == 0.3 give False in Python?

    • The binary format stores these fractions approximately
    • Adding fractions in Python has a bug
    • == cannot be used with numbers
    • You have to write 0.10 + 0.20
  3. What is left after packing

    Write a function leftover(total, size). It returns how many items are left if total items are packed into boxes that hold size each. Incomplete boxes do not count. The function template is ready: replace 0 with the right expression. Functions are covered in detail in the module "Functions".