Data ProcessingPython Math and Random
Python is heavily used in data science, engineering, and game development. Naturally, it has a robust set of tools for handling mathematics and generating random data. Python provides a set of built-in math functions, as well as an extensive math module and a random module.
Built-in Math Functions
Python has a few mathematical functions that are available by default without importing any modules. These include finding the minimum, maximum, absolute value, and powers.
# min() and max() find the lowest and highest values in an iterable
x = min(5, 10, 25)
y = max(5, 10, 25)
print(f"Lowest: {x}, Highest: {y}")
# abs() returns the absolute (positive) value of a number
z = abs(-7.25)
print(f"Absolute: {z}")
# pow(x, y) returns the value of x to the power of y (same as x ** y)
p = pow(4, 3) # 4 * 4 * 4
print(f"Power: {p}")
OutputLowest: 5, Highest: 25
Absolute: 7.25
Power: 64
The Math Module
For more advanced mathematical operations like trigonometry, logarithms, and advanced rounding, you must import the built-in math module.
import math
# Square root
print(math.sqrt(64))
# Rounding strictly UP or DOWN
print(math.ceil(1.4)) # Rounds UP to 2
print(math.floor(1.9)) # Rounds DOWN to 1
# Mathematical constants
print(math.pi)
print(math.e)
Output8.0
2
1
3.141592653589793
2.718281828459045
The Random Module
Python does not have a native random() function, but it has a built-in module named random that can be used to make random numbers, select random choices, and shuffle data.
import random
# Generate a random integer between 1 and 10 (inclusive)
roll = random.randint(1, 10)
print(f"You rolled a {roll}")
# Generate a random float between 0.0 and 1.0
percent = random.random()
print(f"Random float: {percent}")
OutputYou rolled a 7
Random float: 0.6384729183
Random Choices and Shuffling
The random module is especially useful for interacting with lists. You can randomly select items or shuffle an existing list in place.
import random
fruits = ["apple", "banana", "cherry", "mango"]
# random.choice() picks exactly one item randomly
winner = random.choice(fruits)
print(f"The winner is: {winner}")
# random.shuffle() randomizes the order of the list IN PLACE
cards = ["Ace", "King", "Queen", "Jack"]
random.shuffle(cards)
print(f"Shuffled deck: {cards}")
OutputThe winner is: cherry
Shuffled deck: ['Queen', 'Ace', 'Jack', 'King']
💡Security Warning: The built-in random module generates pseudo-random numbers that are predictable. NEVER use the random module for security purposes like generating passwords, encryption keys, or session tokens. For cryptography, use Python's secrets module instead.