☰

Python Numbers

Python Numbers Tutorial With Examples

Look at the last bill you paid. It has whole numbers, such as the quantity of items, and decimals, such as the price and the tax. Any program that works with money, marks, distances, temperatures or measurements has to store numbers like these and do sums on them. Python makes this easy, but it stores different kinds of numbers in different ways, and knowing which is which saves you from confusing bugs.

Python has three main number types: int for whole numbers, float for numbers with a decimal point, and complex for numbers with a real and an imaginary part. You do not have to declare the type. Python looks at the value and decides. You can check the type at any time and convert from one type to another, but as you will see, not every conversion is allowed.

In this tutorial, we go through int, float and complex with real output from Python 3.13. We then cover how to check a type, how type conversion works, and why converting a complex number to int or float fails. We add the number functions you will use every day, the fact that True and False are numbers too, and the decimal and fractions modules for exact maths. We finish with the common mistakes, a quick reference and the complete script.

Types of Python Numbers

When you store a number in a variable, Python gives it one of three types, based on how you write it.

The three Python number types
Type What it holds Example Typical use
int Whole numbers, positive or negative, no decimal point 10, -5, 0 Counts, ages, quantities
float Numbers with a decimal point 14.942, 2.5e3 Prices, measurements
complex A real part and an imaginary part 12+5j Engineering, signal work

Int in Python

An int is a whole number with no decimal part. It can be positive, negative or zero.

python
w = 10
print(w)
print(type(w))
output
10
<class 'int'>

Python has no fixed limit on how big an int can get. It is limited only by the memory of your computer. Most languages overflow at some point, but Python does not:

python
big = 2 ** 100
print(big)
print(type(big))
output
1267650600228229401496703205376
<class 'int'>

Readable Big Numbers and Other Number Systems

You can put underscores inside a large number to make it easy to read. Python ignores them. You can also write an int in binary, octal or hexadecimal, and convert back with the bin, oct and hex functions.

python
print(1_000_000)
print(0b1010, 0o17, 0xFF)
print(bin(10), oct(15), hex(255))
output
1000000
10 15 255
0b1010 0o17 0xff

Float in Python

A float is a number with a decimal point. Use it for prices, weights, distances and anything that is not always a whole number.

python
q = 14.942
print(q)
print(type(q))
output
14.942
<class 'float'>

For very large or very small numbers, you can use scientific notation. The letter e means times ten to the power of.

python
print(1.5e3, 2.5e-3)
output
1500.0 0.0025

Why 0.1 + 0.2 Is Not Exactly 0.3

Floats are stored in binary, and some decimals cannot be stored exactly in binary, in the same way one third cannot be written exactly in decimal. This is true in almost every programming language, not just Python.

python
print(0.1 + 0.2)
print(round(0.1 + 0.2, 2))
output
0.30000000000000004
0.3

The error is tiny, but it matters when you compare floats with the equals operator. Round the result, or use math.isclose, which returns True for 0.1 + 0.2 and 0.3.

python
import math
print(0.1 + 0.2 == 0.3)
print(math.isclose(0.1 + 0.2, 0.3))
output
False
True

Complex Numbers in Python

A complex number has a real part and an imaginary part. In Python the imaginary part is written with the letter j, not i as in most maths books.

python
c = 12 + 5j
print(c)
print(type(c))
output
(12+5j)
<class 'complex'>

Python stores a complex number as two floats. You can read each part, and Python can do the maths on complex numbers directly:

python
c = 12 + 5j
print(c.real, c.imag)
print(c.conjugate())
print(abs(3 + 4j))
print((2 + 3j) * (1 - 1j))
output
12.0 5.0
(12-5j)
5.0
(5+1j)

Notice that the real and imaginary parts print as 12.0 and 5.0, floats, even though we typed whole numbers. The abs of a complex number is its size, so abs(3 + 4j) is 5.0. Most beginners will not need complex numbers often, but they show up in physics, electronics and signal processing.

How to Check the Type of a Number?

Use the type function to see what Python thinks a value is. Use isinstance when you want a yes or no answer inside an if statement.

python
x = 122
print(type(x))
print(isinstance(5, int), isinstance(5.0, int))
output
<class 'int'>
True False

Type Conversion in Python?

You can change a number from one type to another using the functions int, float, complex and str. This is called type conversion, or casting. Two of the four conversions below fail when given a complex number, so we show the error too.

int(): Convert to a Whole Number

python
print(int(2.6), int(-2.6), int("42"))
output
2 -2 42

Converting a float to an int cuts off the decimal part. It does not round. So 2.6 becomes 2 and minus 2.6 becomes minus 2. Now a complex number:

python
y = 5 + 6j
try:
    int(y)
except TypeError as error:
    print("TypeError:", error)
output
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'complex'

A complex number has no single whole number value, so Python refuses. If you only need one part, use int(y.real).

float(): Convert to a Decimal Number

python
print(float(2), float("3.14"))
output
2.0 3.14
python
y = 5 + 6j
try:
    float(y)
except TypeError as error:
    print("TypeError:", error)
output
TypeError: float() argument must be a string or a real number, not 'complex'

The same rule applies. Use y.real or y.imag to get a float out of a complex number.

complex(): Convert to a Complex Number

python
print(complex(2.6), complex(2, 3))
output
(2.6+0j) (2+3j)

With one number, complex gives a number with an imaginary part of zero. With two numbers, they become the real and imaginary parts.

str(): Convert to Text

python
print(str(2.6), str(5 + 6j))
output
2.6 (5+6j)

The result looks the same on screen, but it is now text and not a number. You cannot do maths on it until you convert it back.

Converting Text That Looks Like a Float

A very common error is passing the text "3.7" straight to int. Python raises a ValueError. Convert to float first, then to int.

python
try:
    int("3.7")
except ValueError as e:
    print("ValueError:", e)
print(int(float("3.7")))
output
ValueError: invalid literal for int() with base 10: '3.7'
3

Useful Number Functions

These built in functions work on numbers, and you will use them almost every day.

Useful number functions
Function What it does Example and result
abs(x) Removes the minus sign abs(-7) gives 7
pow(x, y) x to the power y pow(2, 5) gives 32
round(x, n) Rounds to n decimals round(3.14159, 2) gives 3.14
divmod(a, b) Quotient and remainder together divmod(17, 5) gives (3, 2)
max, min, sum Largest, smallest, total sum([1, 2, 3]) gives 6
math.floor(x) Rounds down math.floor(2.7) gives 2
math.ceil(x) Rounds up math.ceil(2.1) gives 3
math.sqrt(x) Square root math.sqrt(16) gives 4.0
python
import math
print(abs(-7), pow(2, 5), round(3.14159, 2))
print(divmod(17, 5))
print(math.floor(2.7), math.ceil(2.1), math.sqrt(16))
print(round(2.5), round(3.5))
output
7 32 3.14
(3, 2)
2 3 4.0
2 4

Look at the last line. The round function gives 2 for 2.5 and 4 for 3.5. Python rounds a number that sits exactly halfway to the nearest even number. This is called banker’s rounding, and it surprises people who expect 2.5 to become 3.

Booleans Are Numbers Too

In Python, True and False are a subtype of int. True behaves as 1 and False as 0. That is why the three types are not quite the whole story.

python
print(isinstance(True, int))
print(True + True)
print(int(True), float(False))
output
True
2
1 0.0

Exact Maths With Decimal and Fractions

When you cannot accept the small float error, for example in money calculations, Python has two modules that give exact answers. Pass the number as text to Decimal, so that it never goes through a float.

python
from decimal import Decimal
from fractions import Fraction
print(Decimal("0.1") + Decimal("0.2"))
print(Fraction(1, 3) + Fraction(1, 6))
output
0.3
1/2

Use Decimal for money and Fraction when you need exact ratios. Both are slower than float, so use them only where exactness matters.

Common Mistakes with Python Numbers

  • Expecting int to round. int(2.6) gives 2, because it cuts off the decimal. Use round if you want 3.
  • Converting complex to int or float. It raises a TypeError. Use the real or imag part.
  • Passing “3.7” text straight to int. It raises a ValueError. Convert to float first.
  • Comparing floats with the equals operator. 0.1 + 0.2 is not exactly 0.3. Use math.isclose.
  • Forgetting that division gives a float. 10 divided by 5 gives 2.0, not 2. Use floor division for a whole number.
  • Doing maths on text. The text "5" is not the number 5. Convert it first.

Quick Reference

Python number types quick reference
Type Created by Check or convert
int w = 10 type(w), int(“42”), int(2.6)
float q = 14.942 type(q), float(2), float(“3.14”)
complex c = 12 + 5j type(c), c.real, c.imag, complex(2, 3)
text s = str(2.6) str(5 + 6j)

Complete Script to Run Yourself

Here is the script that produces every output on this page. Copy it into a file, run it with Python 3, and compare the results.

python
import math
from decimal import Decimal
from fractions import Fraction

# Int, float, complex
w = 10
q = 14.942
c = 12 + 5j
print(w, q, c)
print(type(w), type(q), type(c))
x = 122
print(type(x))

# Int has no fixed limit
big = 2 ** 100
print(big)
print(type(big))
print(1_000_000)

# Other number systems
print(0b1010, 0o17, 0xFF)
print(bin(10), oct(15), hex(255))

# Float
print(1.5e3, 2.5e-3)
print(0.1 + 0.2)
print(round(0.1 + 0.2, 2))
print(math.isclose(0.1 + 0.2, 0.3))
print(Decimal("0.1") + Decimal("0.2"))
print(Fraction(1, 3) + Fraction(1, 6))

# Complex
print(c.real, c.imag)
print(c.conjugate())
print(abs(3 + 4j))
print((2 + 3j) * (1 - 1j))

# Conversion
print(int(2.6), int(-2.6), int("42"))
print(float(2), float("3.14"))
print(complex(2.6), complex(2, 3))
print(str(2.6), str(5 + 6j))
print(int(True), float(False))
for func in (int, float):
    try:
        func(5 + 6j)
    except TypeError as e:
        print(func.__name__, "TypeError:", e)
try:
    int("3.7")
except ValueError as e:
    print("ValueError:", e)
print(int(float("3.7")))
print(int("1010", 2), int("ff", 16))

# Useful functions
print(abs(-7), pow(2, 5), round(3.14159, 2), round(2.5), round(3.5))
print(divmod(17, 5))
print(max(4, 9, 2), min(4, 9, 2), sum([1, 2, 3]))
print(math.floor(2.7), math.ceil(2.1), math.sqrt(16))
print(isinstance(5, int), isinstance(True, int), isinstance(5.0, int))
print(True + True)
print(10 / 4, 10 // 4, 10 % 4, 10 / 5)

 

Numbers look simple, but a few small facts decide whether your program is right: int cuts and does not round, complex cannot become int or float, floats carry a tiny error, and True is the number 1. Run the script above, change the values and read the errors, and you will remember these rules far better than by reading them. Then move on to Python strings and lists, where numbers are used as positions and counts.

Popular Tags:

online python course for beginners online python programming course online python training course online training courses for python Python Numbers tutorial Python: Data Types - Numbers (Integers & Floats) Understanding Numeric Data in Python Programming