✦ For everyone, free.

Practical knowledge for real and everyday life

Home

Python Built-in Numeric Types

Python Built-in Numeric Types are core data types for handling numbers, including integers, floats, complex numbers, and booleans.

Python's built-in numeric types are the core object types used to represent integers, Boolean values, real-number approximations, and complex numbers. Each type has distinct representation, operations, conversion behavior, precision characteristics, and mathematical semantics that affect how numeric values are stored, manipulated, and interact in Python programs.


Foundations of Python Numeric Types

Python's principal built-in numeric types are int, bool, float, and complex. These types form a numeric hierarchy where numeric literals and operations produce objects of particular runtime types, each with specific behaviors:

  • int: Represents arbitrary-precision integers, including positive, negative, and zero values.
  • bool: A subtype of int with only two values, True and False, representing truth values.
  • float: Represents finite-precision floating-point approximations of real numbers, including special values like infinity and NaN.
  • complex: Represents complex numbers with real and imaginary parts stored as floats.

Numeric operations between these types follow Python's numeric model, often promoting operands to a common type to produce a meaningful result.

Common numeric operations include:

  • Arithmetic: Addition (+), subtraction (-), multiplication (*), division (/), floor division (//), remainder (%), and exponentiation (**).
  • Comparison: Equality (==), inequality (!=), less than (<), greater than (>), less than or equal (<=), greater than or equal (>=). Note: Complex numbers support only equality and inequality.
  • Conversion: Explicit conversion functions like int(), float(), bool(), and complex() convert between types where meaningful.
  • Sign operations: Unary plus (+x) and unary minus (-x).
  • Built-in numeric functions: abs(), round(), and others operate according to operand type.

The behavior and result type of these operations depend on the types of the operands involved. For example, adding an int and a float results in a float.

Python performs numeric coercion in mixed-type arithmetic by promoting operands to a broader numeric type when the operation is supported. The general coercion hierarchy is:

boolintfloatcomplex

For example, when adding an int and a float, the int is converted to float before addition; adding a float and a complex converts the float to complex.

TypeRepresentative LiteralConceptual DomainPrecision CharacteristicsMutabilityRepresentative OperationsImportant Limitations
int42, 0b1010, 0x2AAll integers (unbounded)Arbitrary precision (limited by memory)ImmutableArithmetic, bitwise ops, floor division, remainderNo fractional parts, no floating-point ops
boolTrue, FalseTruth valuesExactly two values, subclass of intImmutableLogical operations, arithmetic due to int subtypeShould represent logic, not used as integers
float3.14, 1e-3Real numbers (approximate)Fixed precision (binary floating-point)ImmutableArithmetic, comparisons, rounding, special valuesPrecision limits, rounding errors
complex1+2j, 3jComplex numbersReal and imaginary parts as floatsImmutableArithmetic, conjugation, magnitude, no orderingNo ordering operations (<, >, etc.)

Python Numeric Examples

# Representative literals and their types
print(type(42))          # <class 'int'>
print(type(True))        # <class 'bool'>
print(type(3.14))        # <class 'float'>
print(type(1+2j))        # <class 'complex'>

# Mixed-type arithmetic and resulting types
print(type(1 + 2.0))     # float, int promoted to float
print(type(True + 2))    # int, bool promoted to int
print(type(3.0 + 1j))    # complex, float promoted to complex

# Explicit conversions
print(int(3.7))          # 3 (truncation)
print(float(5))          # 5.0
print(bool(0))           # False
print(complex(2))        # (2+0j)
print(complex("1+2j"))   # (1+2j)

Python Integer Type

Python int objects represent arbitrary-precision integer values, limited only by available memory, not fixed-width machine integers. They include positive, negative, and zero values.

Integer literals can be written in several bases:

  • Decimal (base 10): 1234
  • Binary (base 2): 0b1010 or 0B1010
  • Octal (base 8): 0o755 or 0O755
  • Hexadecimal (base 16): 0x1A3F or 0X1A3F

Digit separators (_) may be used for readability: 1_000_000.

The source notation differs from the integer value represented; for example, 0xA represents decimal 10.

Integer arithmetic includes:

  • Addition, subtraction, multiplication, exponentiation (**)
  • Division / produces a float result
  • Floor division // gives an integer quotient rounded down
  • Remainder % yields the modulo result

Note that / and // differ: / produces floating-point division, // produces floor division.

Python supports bitwise operations on integers:

  • AND (&)
  • OR (|)
  • XOR (^)
  • NOT (~)
  • Left shift (<<)
  • Right shift (>>)

These operate on the binary representation of integers and differ from Boolean logical operations.


Integer Examples

# Large integers
big_int = 10**100
print(big_int)

# Various literal bases
print(0b1010)   # 10 decimal
print(0o755)    # 493 decimal
print(0x1A3F)   # 6719 decimal

# Arithmetic and division
print(7 + 3)    # 10
print(7 - 3)    # 4
print(7 * 3)    # 21
print(7 ** 3)   # 343
print(7 / 3)    # 2.3333333333333335 (float)
print(7 // 3)   # 2 (floor division int)
print(7 % 3)    # 1 (remainder)

# Negative floor division and remainder
print(-7 // 3)  # -3
print(-7 % 3)   # 2

# Bitwise operations
print(6 & 3)    # 2
print(6 | 3)    # 7
print(6 ^ 3)    # 5
print(~6)       # -7
print(1 << 4)   # 16
print(16 >> 2)  # 4

Integer Conversion

  • int() converts floats by truncation toward zero.
  • int() converts numeric strings in a given base: int("101", 2) == 5.
  • Invalid conversions raise ValueError.
print(int(3.7))          # 3
print(int(-3.7))         # -3
print(int("10", 16))     # 16
# int("10.5") would raise ValueError

Python Boolean Type

Python's bool type has exactly two values: True and False. It is a subclass of int, where True behaves like 1 and False like 0 in numeric contexts.

Truth-value testing distinguishes Boolean objects from truthiness of other values:

  • Zero numeric values are falsy (False in Boolean context).
  • Nonzero numeric values are truthy (True in Boolean context).
  • The function bool(value) returns a Boolean object, not just a truthy or falsy value.

Arithmetic operations are valid on Booleans due to their integer subtype relationship:

>>> True + 2
3
>>> False * 10
0

However, Booleans should normally represent logical state rather than act as disguised integers.


Boolean Examples

print(isinstance(True, int))     # True
print(True == 1)                 # True
print(False == 0)                # True

print(True + 5)                  # 6
print(False * 100)               # 0

print(bool(0))                   # False
print(bool(42))                  # True
print(bool([]))                  # False (empty container is falsy)

# Distinguishing Boolean from truthy values
print(type(bool(42)))            # <class 'bool'>
print(type(42))                  # <class 'int'>

Python Floating-Point Type

Python's float type represents finite floating-point approximations of real numbers, typically implemented as 64-bit binary IEEE-754 double precision values. It includes finite values and special values like positive infinity, negative infinity, and NaN (not a number).

Floating-point literals use decimal notation and optional exponent notation:

  • 3.14
  • 2.7e-3 (2.7 × 10⁻³)
  • 1e6

Conversions from integers and numeric strings produce the closest representable binary floating-point value—not exact decimal values.

Floating-point arithmetic includes ordinary operations and comparisons, but rounding errors, overflow, and underflow must be considered.


Floating-Point Examples

# Floating-point literals and exponent notation
print(3.14)            # 3.14
print(2.7e-3)          # 0.0027
print(float("1e6"))    # 1000000.0

# Arithmetic and comparison
print(1.0 + 2.0)       # 3.0
print(2.0 / 3.0)       # 0.6666666666666666
print(2.0 == 2)        # True (int promoted to float)

# Rounding and conversion
print(round(2.675, 2)) # 2.67 (due to binary floating-point representation)

# Large integers to float
print(float(10**20))   # 1e+20 (approximate)

# Small integers to float
print(float(0))        # 0.0
print(float(-5))       # -5.0

Floating-Point Representation and Precision in Python

Many decimal fractions cannot be exactly represented in finite binary floating-point form. Python stores the closest representable value, which may introduce small rounding errors.

Floating-point precision is limited to about 53 significant binary digits (approximately 15-17 decimal digits). Rounding errors accumulate in calculations, and cancellation or scale differences can magnify errors.

This representation error is distinct from mistakes in algorithms.


Floating-Point Precision Examples

print(0.1 + 0.2 == 0.3)         # False (surprising to many)
print(repr(0.1))                 # '0.10000000000000001'
print(sum([0.1]*10))             # 0.9999999999999999 (not exactly 1.0)

Approximate Floating-Point Comparison

Because of rounding errors, exact equality is often unsuitable for floating-point values. Instead, approximate comparisons use absolute and relative tolerances.

Python's math.isclose() provides this functionality, allowing problem-specific tolerance settings.

Comparing rounded display strings is not reliable.


Approximate Comparison Example

import math

a = 0.1 + 0.2
b = 0.3

print(a == b)                          # False
print(math.isclose(a, b))              # True by default tolerances

# Near zero, absolute tolerance matters
x = 1e-10
y = 0.0
print(math.isclose(x, y, abs_tol=1e-9))  # True
print(math.isclose(x, y, abs_tol=1e-11)) # False

Decimal value Representable float 1 Representable float 2 Selected approx. Rounded arithmetic result
Featureintfloat
RepresentationExact integer value, arbitrary precisionApproximate real number, binary floating-point
RangeUnbounded (memory-limited)Approx. ±1.8×10³⁰⁸
PrecisionExactLimited (~15-17 decimal digits)
Equality behaviorExact equalityApproximate equality issues
Overflow / sizeNo overflow, limited by memoryOverflow to ±inf, underflow to zero
Typical useCounting, indexing, exact mathReal-valued measurement, scientific computation
Numerical pitfallsNone (except memory limits)Rounding error, cancellation, representation error

Special Floating-Point Values in Python

Python float supports special values:

  • Positive infinity: float('inf') or math.inf
  • Negative infinity: float('-inf')
  • NaN (Not a Number): float('nan')

These values behave differently in arithmetic and comparisons:

  • Arithmetic with infinity follows extended real number rules.
  • Operations can produce infinity or NaN.
  • NaN is unordered: it does not compare equal to anything, including itself.

Use math.isnan(), math.isinf(), and math.isfinite() to classify float values explicitly.


Special Floating-Point Examples

import math

pos_inf = float('inf')
neg_inf = float('-inf')
nan_val = float('nan')

print(pos_inf > 1e308)            # True
print(neg_inf < -1e308)           # True
print(pos_inf + 1000)             # inf
print(neg_inf * 2)                # -inf
print(pos_inf / pos_inf)          # nan

print(nan_val == nan_val)         # False
print(math.isnan(nan_val))        # True
print(math.isinf(pos_inf))        # True
print(math.isfinite(1.0))         # True

Python Complex Type

Python's complex type represents complex numbers with real and imaginary parts stored as floating-point values.

  • Literal forms include numbers with a j suffix: 3 + 4j, 2j.
  • The constructor complex(real, imag) creates complex numbers.

Complex arithmetic includes addition, subtraction, multiplication, division, and exponentiation where meaningful.

Additional operations:

  • Conjugation: .conjugate()
  • Magnitude: abs()
  • Access to .real and .imag components

Complex numbers support equality and inequality but do not support ordering comparisons (<, >, <=, >=).


Complex Examples

z1 = 3 + 4j
z2 = complex(1, -1)

print(z1.real)          # 3.0
print(z1.imag)          # 4.0
print(z1 + z2)          # (4+3j)
print(z1 * z2)          # (7+1j)
print(abs(z1))          # 5.0 (magnitude)
print(z1.conjugate())   # (3-4j)

print(z1 == complex(3,4))     # True
print(z1 != z2)               # True

# Unsupported ordering comparison raises TypeError
try:
    print(z1 < z2)
except TypeError as e:
    print(e)                  # '<' not supported between instances of 'complex' and 'complex'

Solved Python Numeric Type Exercises

Exercise 1: Aggregating Mixed Numeric Measurements

Given a list of measurements containing both integers and floats, compute the sum and average. Avoid exact floating-point equality when checking if the average equals a target value.

import math

measurements = [10, 20.0, 30, 40.5, 50]

total = sum(measurements)   # Mixed int and float sum results in float
average = total / len(measurements)

target = 30.3

print(f"Total: {total}, Average: {average}")

# Avoid exact equality; use math.isclose with relative tolerance
if math.isclose(average, target, rel_tol=1e-9):
    print("Average matches target approximately.")
else:
    print("Average does not match target.")

Explanation:

  • measurements mix int and float.
  • sum() returns a float because of mixed types.
  • Division returns a float.
  • Exact equality for floats is avoided due to rounding errors.
  • math.isclose() uses a relative tolerance suitable for the scale of values.

Exercise 2: Classifying Numeric Values

Given a list of numeric values possibly including special floats and complex numbers, classify each as finite, infinite, NaN, real-valued, or complex, and perform valid type-appropriate operations.

import math

values = [1, 0.0, float('inf'), float('nan'), 3+4j, -5]

for v in values:
    if isinstance(v, complex):
        print(f"{v} is complex.")
        print(f"  Magnitude: {abs(v)}")
        # Ordering comparisons not valid
        try:
            _ = v < 0
        except TypeError:
            print("  Ordering comparison not supported for complex.")
    elif isinstance(v, float):
        if math.isnan(v):
            print(f"{v} is NaN.")
        elif math.isinf(v):
            print(f"{v} is infinite.")
        elif math.isfinite(v):
            print(f"{v} is finite float.")
    elif isinstance(v, int):
        print(f"{v} is integer.")
    else:
        print(f"{v} is of unknown numeric type.")

Explanation:

  • Uses isinstance to distinguish types.
  • Uses math module functions to classify floats.
  • Recognizes complex numbers and handles unsupported comparisons gracefully.
  • Demonstrates how numeric types require different handling.

This completes a foundational overview of Python's built-in numeric types, their behavior, precision, operations, and practical usage examples.