Skip to content

Python Numbers

Numbers are a fundamental and versatile data type in Python, enabling a wide range of mathematical operations and computations. In Python, numbers can be categorized into integers, floating-point numbers, and complex numbers. Let’s explore these numeric data types and how they can be utilized in Python.

Integers in Python are whole numbers, both positive and negative, without any decimal component. You can perform various arithmetic operations on integers, such as addition, subtraction, multiplication, and division.

numbers.py
a = 5
b = -10
result = a + b  # Result is -5

Python allows unlimited precision for integers, meaning they can be as large as your system’s memory allows.

bignum.py
big = 2 ** 100      # no overflow, Python handles huge integers
print(big)          # 1267650600228229401496703205376

Integers can be written in binary, octal, and hexadecimal using prefixes, and you can group digits with underscores for readability (the underscores are ignored by Python):

bases.py
binary = 0b1010      # binary  -> 10
octal = 0o17         # octal   -> 15
hexadecimal = 0xFF   # hex     -> 255
million = 1_000_000  # underscores aid reading -> 1000000
 
print(binary, octal, hexadecimal, million)
print(bin(10), oct(15), hex(255))   # convert back to base strings

Output:

command
C:\Users\Your Name> python bases.py
10 15 255 1000000
0b1010 0o17 0xff

Floating-point numbers represent real numbers with a decimal point or in exponential form. They are used to handle both integer and fractional values.

numbers.py
pi = 3.14159
radius = 2.5
area = pi * (radius ** 2)  # Calculating the area of a circle

While floating-point numbers are powerful for scientific and mathematical computations, they may introduce precision issues due to the binary representation of real numbers.

This surprises every beginner — floats are stored in binary, so some decimals cannot be represented exactly:

precision.py
print(0.1 + 0.2)            # 0.30000000000000004
print(0.1 + 0.2 == 0.3)     # False!

When exact decimal arithmetic matters (money, for example), use the decimal module:

decimal_money.py
from decimal import Decimal
 
price = Decimal("0.1") + Decimal("0.2")
print(price)                # 0.3  (exact)

Complex numbers have both a real and an imaginary part, represented as a + bj, where a and b are real numbers, and j is the imaginary unit.

numbers.py
z = 3 + 4j

You can perform operations like addition, subtraction, multiplication, and division on complex numbers.

numbers.py
w = 1 - 2j
result = z * w  # Result is (11-2j)

Python supports a wide range of operations on numeric data types. Here are some common examples:

  • Arithmetic Operations:

    numbers.py
    a = 10
    b = 3
    addition = a + b
    subtraction = a - b
    multiplication = a * b
    division = a / b
  • Exponential Operation:

    numbers.py
    square = 4 ** 2  # Result is 16
  • Modulo Operation:

    numbers.py
    remainder = 10 % 3  # Result is 1

In Python, you can compare numeric values using the following comparison operators:

numbers.py
a = 10
b = 5
print(a > b)  # True

You can convert numeric values from one data type to another using the following built-in functions:

  • int() - converts to an integer
  • float() - converts to a floating-point number
  • complex() - converts to a complex number
numbers.py
num_int = 10
num_float = float(num_int)  # Convert integer to float
num_complex = complex(num_int)  # Convert integer to complex
numbers.py
num_float = 10.5
num_int = int(num_float)  # Convert float to integer
num_complex = complex(num_float)  # Convert float to complex
numbers.py
num_complex = 3 + 4j
num_int = int(num_complex)  # Raises TypeError
num_float = float(num_complex)  # Raises TypeError
numbers.py
num_str = "42"
num_int = int(num_str)  # Convert string to integer
num_float = float(num_str)  # Convert string to float
num_complex = complex(num_str)  # Convert string to complex

Python’s math module provides a plethora of mathematical functions, including square root, logarithms, trigonometric functions, and more.

numbers.py
import math
sqrt_result = math.sqrt(25)  # Result is 5.0

Python’s random module provides functions for generating random numbers. For example, you can use the random() function to generate a random floating-point number between 0 and 1.

numbers.py
import random
print(random.random())  # Prints a random number between 0 and 1
print(random.randrange(1, 10))  # Prints a random integer between 1 and 10

You do not always need the math module. Python has several handy built-ins for numbers:

builtins.py
print(abs(-7))        # 7    -> absolute value
print(round(3.14159, 2))  # 3.14 -> round to 2 decimals
print(pow(2, 8))      # 256  -> 2 to the power 8
print(divmod(17, 5))  # (3, 2) -> quotient and remainder together
print(max(3, 9, 1))   # 9
print(min(3, 9, 1))   # 1

Operators like +=, -=, *=, /=, //=, %=, and **= update a variable in place — a shorthand that keeps code concise:

augmented.py
count = 10
count += 5     # same as: count = count + 5
count *= 2     # same as: count = count * 2
count //= 3    # floor division assignment
print(count)   # 10

Python groups all numeric values into three built-in types, each suited to a different kind of value.

diagram Python's numeric types mermaid
int, float, and complex are the three built-in numeric types, each handling a different kind of number.

Numbers in Python are a versatile and integral part of the language’s functionality. Whether you’re dealing with simple integer calculations or complex mathematical operations involving floating-point or complex numbers, Python provides a straightforward and expressive syntax. Understanding how to work with numbers is crucial for various applications, including scientific computing, data analysis, and algorithmic problem-solving.

As you continue your Python journey, explore the rich set of numeric operations and mathematical functions Python offers. Gain proficiency in leveraging numeric data types to solve diverse problems and unlock the full potential of numerical computing in Python.

For more in-depth tutorials and practical examples, check out our resources on Python Central Hub!


pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading