Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 149 ยท Data Types

Numbers

Work with Python numbers - int, float and complex, arithmetic, rounding rules, why 0.1 + 0.2 isn't 0.3, and exact math with the decimal and fractions modules.

Numbers are at the heart of most programs: prices, scores, distances, timestamps, pixel positions. Python has three built-in number types, int, float and complex, plus two modules in the standard library for when you need exact results: decimal and fractions.

This lesson shows how each type behaves, how to round correctly, and the one fact about decimal numbers that every programmer has to learn sooner or later: computers can't store 0.1 exactly.

Integers: int

An int is a whole number, positive or negative, with no decimal point. Unlike many languages, Python integers have no size limit: they grow as large as your memory allows.

Python Integers of any size

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Underscores inside numbers (8_100_000_000) are ignored by Python and make long numbers readable. The format code :, adds thousands separators when printing; String Formatting has more.

You can also write integers in other bases, which is common when working with colors, file permissions or bit flags:

Python Binary, octal and hexadecimal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Floating-point numbers: float

A float is a number with a fractional part. Any number written with a decimal point or an exponent is a float:

Python
price = 19.99
ratio = 0.5
whole_but_float = 3.0       # still a float
avogadro = 6.022e23         # 6.022 ร— 10ยฒยณ
tiny = 1.5e-9               # 0.0000000015

Floats are fast and good enough for measurements, science and graphics. They have about 15โ€“17 significant digits of precision and a huge but limited range. Python also has special float values for infinity and "not a number": float("inf") and float("nan").

The 0.1 + 0.2 surprise

Run this and look closely at the first line:

Python Floating-point precision

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The result is 0.30000000000000004, and the comparison is False. This isn't a Python bug; every mainstream language does the same. Floats are stored in binary, and just as 1/3 can't be written exactly in decimal (0.3333...), 1/10 can't be written exactly in binary. The computer stores the nearest value it can, and tiny errors appear when you combine them.

Two rules follow:

  • Don't compare floats with ==. Use math.isclose(a, b) or check that the difference is smaller than some tolerance.
  • Round when displaying, not while calculating. Use format codes like :.2f for output.

Money needs exact math. Adding up prices as floats can be off by a cent. Store money as integer cents (1999 for $19.99), or use the decimal module shown below.

Arithmetic

Python's arithmetic operators work on all number types:

Operator Meaning Example Result
+ add 7 + 2 9
- subtract 7 - 2 5
* multiply 7 * 2 14
/ divide 7 / 2 3.5
// floor division 7 // 2 3
% remainder (modulo) 7 % 2 1
** power 7 ** 2 49

Two rules about result types are worth memorizing:

  • / always returns a float, even when the division is exact: 6 / 3 is 2.0.
  • Mixing an int and a float gives a float: 2 + 0.5 is 2.5.

The operators, their precedence, and tricky cases like // with negative numbers get a full lesson in Arithmetic Operators.

Built-in number functions

Python Handy built-ins

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The math module adds square roots, trigonometry, logarithms and constants such as math.pi. It gets its own lesson in math and random.

Rounding

There are several ways to turn a float into a whole number, and they disagree on negative numbers and halves. Choose deliberately:

Python Rounding compared

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

  • int(x) and math.trunc(x) chop off the fractional part, moving toward zero.
  • math.floor(x) goes down to the next whole number; math.ceil(x) goes up.
  • round(x) goes to the nearest whole number. On an exact half, it picks the even neighbor: round(2.5) is 2, round(3.5) is 4. This is called banker's rounding, and it avoids a bias toward larger numbers when you round many values.
  • round(x, n) rounds to n decimal places. A negative n rounds to tens, hundreds and so on.

Because of binary storage, round(2.675, 2) gives 2.67, not 2.68: the stored value is really a hair below 2.675. When the exact decimal result matters, use decimal.

Complex numbers

Python supports complex numbers directly. The imaginary part is written with a j suffix:

Python
z = 3 + 4j
print(z.real, z.imag)   # 3.0 4.0
print(abs(z))           # 5.0, the distance from zero
print(z * 1j)           # (-4+3j)

You won't need them for everyday programming, but they're there for electrical engineering, signal processing and math. The cmath module has complex versions of the math functions.

Exact decimals: the decimal module

decimal.Decimal stores numbers in base 10, exactly as you write them, so 0.1 really is 0.1. Always create Decimals from strings: creating one from a float copies the float's error.

Python Decimal for money

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

quantize(Decimal("0.01")) rounds to cents, and rounding=ROUND_HALF_UP picks the "halves go up" rule people expect on receipts. Decimals are slower than floats, so use them where exactness matters (money, accounting) rather than everywhere.

Exact fractions: the fractions module

fractions.Fraction stores a numerator and a denominator, so values like 1/3 stay exact through any number of operations:

Python Fractions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Fractions are handy for recipes, music timing, probability and anywhere you'd naturally write a ratio.

Converting between number types

Python
int("42")       # 42 (text to int)
float("3.5")    # 3.5
int(9.99)       # 9 (truncates!)
float(7)        # 7.0
str(2.5)        # '2.5'

int() and float() raise a ValueError on text that isn't a valid number. Type Conversion covers the edge cases.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does 10 / 2 return?

    The / operator always returns a float. Use // for integer (floor) division.
  2. 2. What is round(4.5)?

    round() uses banker's rounding. Exact halves go to the nearest even number, so 4.5 becomes 4 and 5.5 becomes 6.
  3. 3. Why is 0.1 + 0.2 == 0.3 False?

    Floats are binary approximations. Compare them with math.isclose() instead of ==, or use Decimal for exact decimal math.
  4. 4. Which line creates an exact decimal value of 0.1?

    Create Decimals from strings. Decimal(0.1) copies the float's binary error.
  5. 5. What does int(-3.8) return?

    int() truncates toward zero. Use math.floor() to round down to -4.

Summary

  • int: whole numbers of unlimited size. Underscores make long literals readable; 0b, 0o, 0x write other bases.
  • float: numbers with a fractional part, about 15โ€“17 significant digits. They're binary approximations, so compare with math.isclose(), not ==.
  • / always returns a float; mixing int and float gives a float.
  • int() truncates, math.floor()/math.ceil() go down/up, and round() uses banker's rounding on halves.
  • complex numbers use a j suffix.
  • Use Decimal (created from strings) for money and exact decimal math, and Fraction for exact ratios.

Next: Strings, where you'll learn how Python stores and works with text.