Python comes with a rich set of built-in libraries. Two of the most commonly used modules for handling probabilities and system timings are random and time.
The random module provides tools to generate pseudo-random numbers and make random selections from collections.
Returns a random floating-point number in the range [0.0, 1.0).
Input:
import random
# Generate a float between 0.0 and 1.0
print("Random float:", random.random())Output:
Random float: 0.3745401188473625
Returns a random integer
Input:
# Roll a 6-sided die
die_roll = random.randint(1, 6)
print("Die roll:", die_roll)Output:
Die roll: 5
Returns a random element from a non-empty sequence (like a list or tuple).
Input:
fruits = ["apple", "banana", "cherry", "date"]
picked_fruit = random.choice(fruits)
print("Randomly picked fruit:", picked_fruit)Output:
Randomly picked fruit: banana
Shuffles the elements of a list in place (mutates the list).
Input:
cards = ["Ace", "King", "Queen", "Jack"]
random.shuffle(cards)
print("Shuffled cards:", cards)Output:
Shuffled cards: ['Queen', 'Jack', 'Ace', 'King']
Returns a random floating-point number
Input:
# Generate a float between 12.0 and 20.0
print("Random uniform float:", random.uniform(12, 20))Output:
Random uniform float: 15.823489
Returns a list of size k containing elements chosen from the sequence, with replacement (meaning elements can repeat).
Input:
colors = ["red", "blue", "green"]
# Choose 5 colors (elements can be duplicated!)
picked_colors = random.choices(colors, k=5)
print("Choices output:", picked_colors)Output:
Choices output: ['blue', 'red', 'blue', 'green', 'blue']
The time module provides functions for working with time-related tasks.
Returns the current system time in seconds since the Epoch (January 1, 1970, 00:00:00 UTC).
Input:
import time
epoch_time = time.time()
print("Seconds since Epoch:", epoch_time)Output:
Seconds since Epoch: 1782555600.0
Suspends execution of the current thread for the given number of seconds.
Input:
print("Starting...")
time.sleep(2) # Pauses execution for exactly 2 seconds
print("Completed after 2 seconds delay!")Output:
Starting...
Completed after 2 seconds delay!
If you want to measure exactly how long a block of code takes to run (benchmarking), do NOT use time.time(). It has low resolution and can be affected by system clock adjustments.
Instead, use time.perf_counter(), which provides a high-resolution, monotonic timer (a clock that never goes backwards).
Input:
start_time = time.perf_counter()
# Let's run a loop to benchmark it
sum_val = 0
for i in range(1000000):
sum_val += i
end_time = time.perf_counter()
execution_time = end_time - start_time
print(f"Loop completed in: {execution_time:.6f} seconds")Output:
Loop completed in: 0.053412 seconds
Let's combine random selections (random.choices()), shuffling (random.shuffle()), and integer generation (random.randint()) to construct a secure password generator.
- Prompts the user to enter their name.
- Selects 4 random letters from their name.
- Selects 2 random special characters from a list.
- Shuffles the combined set of characters to make it unpredictable.
- Capitalizes the first letter of the shuffled characters.
- Appends a random 5-digit security number (between
11111and99999) to form the final password.
Input:
import random
# 1. Input name
name = "python"
spe_chars = ['!', '@', '#', '^', '&', '*']
# 2. Gather components
sample1 = random.choices(name, k=4) + random.choices(spe_chars, k=2)
# 3. Shuffle components in-place
random.shuffle(sample1)
# 4. Join and title-case (capitalize first letter)
shuffled_str = ''.join(sample1).title()
# 5. Append random 5-digit number
password = shuffled_str + str(random.randint(11111, 99999))
print("Generated Password:", password)Output:
Generated Password: Y!Pt*h24589