Python Numbers

Summary: in this tutorial, you’ll learn about Python numbers and how to use them in programs.

Python supports integers, floats, and complex numbers. This tutorial discusses only integers and floats.

Integers

The integers are numbers such as -1, 0, 1, 2, and 3, .. and they have type int.

You can use Math operators like +, -, *, and / to form expressions that include integers. For example:

>>> 20 + 10
30
>>> 20 - 10
10
>>> 20 * 10
200
>>> 20 / 10
2.0
Code language: Python (python)

To calculate exponents, you use two multiplication symbols (**). For example:

>>> 3**3
27Code language: Python (python)

To modify the order of operations, you use the parentheses (). For example:

>>> 20 / (10 + 10)
1.0Code language: Python (python)

Floats

Any number with a decimal point is a floating-point number. The term float means that the decimal point can appear at any position in a number.

In general, you can use floats like integers. For example:

>>> 0.5 + 0.5
1.0
>>> 0.5 - 0.5
0.0
>>> 0.5 / 0.5
1.0
>>> 0.5 * 0.5
0.25Code language: Python (python)

The division of two integers always returns a float:

>>> 20 / 10
2.0Code language: Python (python)

If you mix an integer and a float in any arithmetic operation, the result is a float:

>>> 1 + 2.0
3.0Code language: Python (python)

Due to the internal representation of floats, Python will try to represent the result as precisely as possible. However, you may get the result that you would not expect. For example:

>>> 0.1 + 0.2
0.30000000000000004Code language: Python (python)

Just keep this in mind when you perform calculations with floats. And you’ll learn how to handle situations like this in later tutorials.

Underscores in numbers

When a number is large, it’ll become difficult to read. For example:

count = 10000000000Code language: Python (python)

To make the long numbers more readable, you can group digits using underscores, like this:

count = 10_000_000_000Code language: Python (python)

When storing these values, Python just ignores the underscores. It does so when displaying the numbers with underscores on the screen:

count = 10_000_000_000
print(count)Code language: Python (python)

Output:

10000000000Code language: Python (python)

The underscores also work for both integers and floats.

Note that the underscores in numbers have been available since Python 3.6

Summary

  • Python supports common numeric types including integers, floats, and complex numbers.
  • Use the underscores to group numbers for the large numbers.
Did you find this tutorial helpful ?