Skip to content

Python 3 - Numbers

Numbers are fundamental data types used to store numeric values. Python’s number types are immutable, meaning that operations resulting in a new numeric value actually create a new number object in memory.

Number objects are created simply by assigning a numeric literal to a variable:

count = 10 # Integer
price = 99.95 # Floating-point
complex_num = 3 + 4j # Complex number

You can remove the reference to a number object (making it eligible for garbage collection if no other references exist) using the del statement:

del price
del count, complex_num # Delete multiple variables

Python 3 supports three distinct numeric types:

  • int (Integer): Represents whole numbers (positive, negative, or zero) without a decimal point. Integers in Python 3 have arbitrary precision, meaning they can grow to accommodate any size, limited only by available memory. Unlike Python 2, there is no separate long type.
  • float (Floating-Point Number): Represents real numbers, including those with a decimal point. They can also be expressed in scientific notation using e or E (e.g., 2.5e2 means 2.5 x 102 = 250.0). Floats typically use the IEEE 754 standard for double-precision representation, which can sometimes lead to small precision inaccuracies.
  • complex (Complex Number): Represents numbers in the form a + bj, where a (real part) and b (imaginary part) are floats, and j (or J) represents the square root of -1. The imaginary part is optional (e.g., 5j). While less common in general programming, they are crucial in scientific and engineering domains.

Integers can also be represented in binary (0b), octal (0o), and hexadecimal (0x) formats:

binary_val = 0b1011 # Binary for 11
octal_val = 0o17 # Octal for 15
hex_val = 0xFF # Hexadecimal for 255
print(f"Binary 0b1011 is {binary_val}")
print(f"Octal 0o17 is {octal_val}")
print(f"Hex 0xFF is {hex_val}")
intfloatcomplex
100.03.14j
10015.2045.j
-786-21.99.322e-36j
03.23e+180.876j
99999999999999999-90.-0.6545+0J
0o20 # Octal 16-3.254e100(3+0j)
0x1A # Hex 267.02e-124.53e-7j

Complex number components can be accessed via attributes: z = 3+4j; z.real gives 3.0, z.imag gives 4.0.

Python automatically converts numbers between types during operations (e.g., int + float results in a float). However, you often need to explicitly convert between types using built-in functions:

  • int(x): Converts x to an integer. For floats, it truncates towards zero. For strings, the string must represent a whole number (optionally specify base like int('101', 2) for binary).
  • float(x): Converts x to a floating-point number. Works for integers and compatible strings.
  • complex(real [,imag]): Creates a complex number. real can be int, float, or string. imag must be numeric if provided.
  • str(x): Converts any object x (including numbers) to its string representation.
#!/usr/bin/env python3
num_int = 10
num_float = 3.14
num_str_int = "100"
num_str_float = "-4.5"
print(f"float({num_int}) = {float(num_int)}")
print(f"int({num_float}) = {int(num_float)}") # Truncates
print(f"int({num_str_int}) = {int(num_str_int)}")
print(f"float({num_str_float}) = {float(num_str_float)}")
print(f"complex({num_int}) = {complex(num_int)}")
print(f"complex({num_int}, {num_float}) = {complex(num_int, num_float)}")
# Conversion errors
# int("hello") # ValueError
# int("10.5") # ValueError

Python’s math module provides access to a wide range of mathematical functions. You need to import math first.

FunctionDescription
abs(x) (Built-in)Returns the absolute value of x (distance from zero).
math.ceil(x)Returns the ceiling of x (smallest integer >= x).
math.copysign(x, y)Returns x with the sign of y.
math.exp(x)Returns e raised to the power x (ex).
math.fabs(x)Returns the absolute value of x as a float.
math.floor(x)Returns the floor of x (largest integer <= x).
math.fmod(x, y)Returns the floating-point remainder of x/y. Generally preferred over % for floats.
math.log(x, [base])Returns the logarithm of x to the given base. Defaults to natural logarithm (base e) if base is omitted.
math.log10(x)Returns the base-10 logarithm of x.
math.log2(x)Returns the base-2 logarithm of x.
max(a, b, ...) (Built-in)Returns the largest of its arguments.
min(a, b, ...) (Built-in)Returns the smallest of its arguments.
math.modf(x)Returns the fractional and integer parts of x as a tuple (frac, int). Both have the same sign as x. Integer part is returned as a float.
pow(x, y) (Built-in)Returns x raised to the power y (x**y). More efficient than math.pow for integers.
math.pow(x, y)Returns x raised to the power y as a float.
round(x [, n]) (Built-in)x rounded to n digits after the decimal point. If n is omitted, rounds to the nearest integer. Uses “round half to even” strategy for ties (e.g., round(2.5) is 2, round(3.5) is 4).
math.sqrt(x)Returns the square root of x (for x >= 0).
math.trunc(x)Returns the truncated integer value of x (removes fractional part).

Random Number Functions (from random module)

Section titled “Random Number Functions (from random module)”

The random module provides functions for generating pseudo-random numbers, useful in simulations, games, testing, etc. import random is needed.

FunctionDescription
random.choice(seq)Returns a random element from a non-empty sequence (list, tuple, string).
random.choices(population, k=1)Returns a list of k elements chosen from the population with replacement.
random.randrange(start, stop [, step])Returns a randomly selected element from range(start, stop, step). Equivalent to choice(range(start, stop, step)) but more efficient.
random.randint(a, b)Returns a random integer N such that a <= N <= b.
random.random()Returns a random float r in the range [0.0, 1.0) (0.0 included, 1.0 excluded).
random.seed([a])Initializes the random number generator. Use the same seed a to get a reproducible sequence of random numbers. Called automatically with system sources if no seed is provided.
random.shuffle(lst)Randomizes the order of elements in a list lst in-place. Returns None.
random.uniform(a, b)Returns a random float r such that a <= r <= b or b <= r <= a.
random.sample(population, k)Returns a list of k unique elements chosen from the population sequence or set without replacement.

Trigonometric Functions (from math module)

Section titled “Trigonometric Functions (from math module)”

The math module also includes standard trigonometric functions. Angles are typically measured in radians.

FunctionDescription
math.acos(x)Returns the arc cosine of x in radians.
math.asin(x)Returns the arc sine of x in radians.
math.atan(x)Returns the arc tangent of x in radians.
math.atan2(y, x)Returns atan(y / x) in radians, considering the signs of x and y to determine the correct quadrant.
math.cos(x)Returns the cosine of x radians.
math.hypot(x, y)Returns the Euclidean norm, sqrt(x*x + y*y) (length of the hypotenuse).
math.sin(x)Returns the sine of x radians.
math.tan(x)Returns the tangent of x radians.
math.degrees(x)Converts angle x from radians to degrees.
math.radians(x)Converts angle x from degrees to radians.

The math module defines important mathematical constants:

ConstantDescription
math.piThe mathematical constant pi (approx. 3.14159…)
math.eThe mathematical constant e (approx. 2.71828…)
math.tauThe mathematical constant tau (2 * pi, approx. 6.28318…)
math.infFloating-point positive infinity.
math.nanFloating-point ‘Not a Number’.