Python's random Module for Beginners! How to Generate Random Values with Copy-and-Paste Code
To run Python from the command prompt or PowerShell on your PC, you need to download and install Python.
If you havenβt installed it yet, please refer to the article Setting Up Python and Development Environment to install Python.
Hi there! Have you ever wanted to add a bit of dynamism or unpredictability to your website? For example, changing the displayed image every time someone visits, showing random recommended articles, or generating lots of dummy data during development.
To achieve this "randomness," Python provides a very convenient standard library called the random module. Since it's a standard library, no additional installation is needed if you have Python, making it a reliable ally for web creators.
In this article, we'll thoroughly explain how to use Python's random module, from basics to applications, with plenty of sample code, so even beginner web creators can start using it right away. All sample code is designed to work perfectly with just a copy-and-paste. By "just trying it out," you can experience the fun and convenience of random number generation!
Preparation: Importing the random Module
First things first, to use the features of the random module, you need to import it at the beginning of your Python script. It's very simple; you just need to write the following line.
import random
# From this point on, you can use the features of the random module.
print("The random module has been imported!")
Now you're ready to call various functions within the module using the format random.function_name(). Let's take a look at some of the most common functions one by one.
Part 1: Generating Random Integers (randint, randrange)
One of the most frequently used features is generating a random integer within a specified range. This is very useful in many situations where you need a random integer, like "a number from 1 to 6 (a die roll π²)" or "a test score from 100 to 200."
Get an integer in a specified range: random.randint()
random.randint(a, b) returns a random integer between the two numbers `a` and `b` passed as arguments. An important point is that this range is inclusive of both a and b (greater than or equal to a and less than or equal to b).
Example: A random integer from 1 to 6 (a die roll)
import random
# Generate a random integer from 1 to 6 (inclusive)
dice_roll = random.randint(1, 6)
print(f"The die roll is: {dice_roll}")
Use it like range(): random.randrange()
random.randrange() also generates integers, but it works just like Python's standard range() function. For this reason, it might feel more intuitive to programmers.
randrange(stop): An integer from 0 up to, but not including, stop.randrange(start, stop): An integer from start up to, but not including, stop.randrange(start, stop, step): An integer from the range start to stop, with an interval of step.
Unlike randint(a, b), note that the endpoint value (stop) is not included in the range.
Example: A random integer from 0 to 9 (10 is not included)
import random
# Generate a random integer from 0 up to (but not including) 10
# Same logic as range(10)
number = random.randrange(10)
print(f"A random number from 0 to 9: {number}")
The true power of randrange() is shown when you want to generate random numbers with a specific step (interval). For example, you can specify "only even numbers" or "only multiples of 5."
Example: A random multiple of 5 from 10 to 100
import random
# Start at 10, up to (but not including) 101, with a step of 5
# Candidates are 10, 15, 20, ..., 100
multiple_of_five = random.randrange(10, 101, 5)
print(f"A random multiple of 5 from 10 to 100: {multiple_of_five}")
Part 2: Choosing Elements from a List (choice, choices, sample)
This is a very useful feature for situations like "displaying one random article from a list of recommended articles" or "displaying a few banner images selected from multiple ones" on a website. It extracts elements from a collection (sequence) like a list or tuple.
Choose just one: random.choice()
random.choice(seq) picks just one random element from a sequence such as a list or tuple. It's a simple and very easy-to-use function.
Example: Picking a fortune from a fortune-telling slip
import random
fortunes = ["Great Blessing", "Middle Blessing", "Small Blessing", "Blessing", "Curse", "Great Curse"]
# Pick one random element from the list
result = random.choice(fortunes)
print(f"Your fortune for today is... {result}!")
Choose multiple with replacement: random.choices()
random.choices(population, k=n) picks multiple elements from a list. The important point is that it allows duplicates (sampling with replacement). This means an element that has been chosen once can be chosen again. You specify the number of elements to pick with k.
Example: A simulation of flipping a coin 10 times (Heads and Tails are chosen with replacement)
import random
coin_sides = ["Heads", "Tails"]
# Choose 10 times from coin_sides with replacement (k=10)
results = random.choices(coin_sides, k=10)
print(f"Coin flip results: {results}")
print(f"Number of Heads: {results.count('Heads')}")
print(f"Number of Tails: {results.count('Tails')}")
Furthermore, choices() allows you to specify weights, which can change the probability of each element being chosen. This is very useful for situations where you want to manipulate probabilities, such as in a game's gacha feature.
Example: A simulation of a gacha system where high-rarity items are less likely to appear
import random
items = ["Super Rare SSR+", "SSR", "SR", "R", "N"]
# Probability: 0.5%, 3%, 15%, 30%, 51.5% corresponding weights
weights = [0.5, 3, 15, 30, 51.5]
# Draw 10 times considering the weights
gacha_results = random.choices(items, weights=weights, k=10)
print(f"10-pull gacha results: {gacha_results}")
Choose multiple without replacement: random.sample()
random.sample(population, k) picks multiple elements from a list without duplicates (sampling without replacement). It's ideal for situations like "drawing 3 winners from a list of participants without duplicates" or "ensuring that displayed related articles do not overlap."
Example: Drawing 2 winners from 5 users
import random
users = ["UserA", "UserB", "UserC", "UserD", "UserE"]
# Choose 2 people from the users list without duplicates (k=2)
winners = random.sample(users, k=2)
print(f"Congratulations to the winners!: {winners}")
Part 3: Shuffling the Order of a List (shuffle)
If you want to randomly reorder the elements of an existing list, use random.shuffle(x).
As a point of caution, shuffle() does not return a new list but modifies the original list directly (in-place operation). Therefore, if you want to keep the original order, you should use it after copying the list.
Example: Shuffling a deck of cards
import random
cards = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
print(f"Before shuffling: {cards}")
# Randomly reorder the cards list itself
random.shuffle(cards)
print(f"After shuffling: {cards}")
If you want to get a "new" shuffled list while keeping the original list, it's easy to use the aforementioned random.sample(). If you specify the total number of elements in the list for k, you will get a new, shuffled list as a result.
Example: Get a shuffled list while keeping the original list
import random
original_list = [1, 2, 3, 4, 5]
# Sample as many items as the length of the original list
shuffled_list = random.sample(original_list, k=len(original_list))
print(f"Original list (unchanged): {original_list}")
print(f"New shuffled list: {shuffled_list}")
Part 4: Generating Random Floating-Point Numbers (random, uniform)
You can generate not only integers but also random numbers that include a decimal point (floating-point numbers). This can be used for animation parameters or for calculating ratios in A/B testing.
A value between 0.0 and 1.0: random.random()
random.random() is the most basic function for generating decimals, returning a random floating-point number that is greater than or equal to 0.0 and less than 1.0 ($0.0 \le N < 1.0$). It requires no arguments.
Example: Generating a random floating-point number
import random
value = random.random()
print(f"Generated value: {value}")
# Example of displaying "Success!" with a 70% probability
if value < 0.7:
print("Success with a 70% probability!")
else:
print("Too bad, failure...")
A decimal in a specified range: random.uniform()
If you want a decimal within a specific range, use random.uniform(a, b). This returns a random floating-point number that is greater than or equal to a and less than or equal to b ($a \le N \le b$).
Example: Generating a random decimal from -1.0 to 1.0
import random
# Generate a random decimal from -1.0 to 1.0
random_float = random.uniform(-1.0, 1.0)
print(f"Generated decimal: {random_float}")
# If you want to display it with 3 decimal places
print(f"With 3 decimal places: {random_float:.3f}")
Applications: Practical Samples for Web Production
From here, we'll introduce more practical examples that web creators might use in actual development, combining the basic functions we've learned so far.
Application 1: Generating Random Passwords or ID Strings
This is useful when you want to generate initial passwords for test users or temporary session IDs. Here, we introduce a smart way to write this by combining random.choice() with string manipulation and list comprehensions.
import random
import string
# Define the candidate characters
# string.ascii_letters are all English letters (a-z, A-Z)
# string.digits are numbers (0-9)
# string.punctuation are symbols (!"#$%&...)
characters = string.ascii_letters + string.digits + string.punctuation
print(f"Partial candidate characters: {characters[:20]}...")
# Specify the password length
length = 16
# Generate a random string of the specified length using a list comprehension
# "".join(list) concatenates the elements of a list into a single string
random_password = "".join(random.choice(characters) for _ in range(length))
print(f"Generated random string: {random_password}")
Application 2: Generating HTML with Random Elements using Python
Python is also active on the web server side. Here, we introduce code that dynamically generates an HTML file with random content. This is useful when you want to efficiently create prototypes or test data for a website.
The following Python code generates a simple HTML file with a different background color and a different message each time it is run.
Python code: Generating random HTML
import random
# 1. Generate a random color code
# Convert an integer from 0 to 16777215 (FFFFFF) to a hexadecimal number
bg_color = f"#{random.randint(0, 0xFFFFFF):06x}"
# 2. Select a random message and icon
messages = [
("Welcome to the world of Python!", "π"),
("The random module is handy, isn't it?", "π"),
("Web design is fun!", "π¨"),
("It's a great day for coding today.", "π»")
]
message, icon = random.choice(messages)
# 3. Create the HTML structure with an f-string
html_content = f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Randomly Generated Page</title>
<style>
body {{
background-color: {bg_color};
color: #333;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
text-align: center;
padding-top: 100px;
transition: background-color 0.5s ease;
}}
.container {{
background-color: rgba(255, 255, 255, 0.8);
padding: 2em 3em;
border-radius: 12px;
display: inline-block;
box-shadow: 0 8px 20px rgba(0,0,0,0.15);
backdrop-filter: blur(10px);
}}
h1 {{
font-size: 2.5rem;
}}
</style>
</head>
<body>
<div class="container">
<h1>{icon} {message}</h1>
<p>The background color of this page is <strong>{bg_color}</strong>.</p>
</div>
</body>
</html>
"""
# 4. Save the generated HTML to a file named "random_page.html"
with open("random_page.html", "w", encoding="utf-8") as f:
f.write(html_content)
print("`random_page.html` has been generated. Please open it in a browser to check.")
When you run the Python script above, a file named `random_page.html` will be created in the same directory as the script. If you open this file in a browser, a page with a different design should be displayed each time. Please give it a try.
Points to Note and Advanced Usage
Reproducibility of Random Numbers: random.seed()
The random numbers generated by the random module are actually not completely random, but are pseudo-random numbers generated by a specific calculation (algorithm). The starting point for this calculation is a value called the "seed."
Normally, the seed is automatically set from an unpredictable value such as the current time, so a different sequence of random numbers is generated each time it is run. However, for debugging or testing, you may want to generate "random, but the same sequence of random values every time." This is achieved with random.seed().
If you give a specific number (seed value) to random.seed(), the sequence of random numbers generated thereafter will be completely fixed. No matter how many times you run it, the same random numbers will appear in the same order from the same seed value.
import random
# Set the seed value to 42
random.seed(42)
print("--- Running with seed value 42 ---")
print(random.randint(1, 100))
print(random.choice(["A", "B", "C"]))
print(random.random())
print("\n--- Running again with seed value 42 ---")
# If you set the seed to the same value again, the random number sequence will be reset and you will get exactly the same result
random.seed(42)
print(random.randint(1, 100))
print(random.choice(["A", "B", "C"]))
print(random.random())
γMost ImportantγUse the secrets Module for Security Purposes
Warning: This is a very important point.
The random module we have introduced so far is sufficient for statistical randomness and general use, but its algorithm is publicly known, and the random numbers it generates are predictable, so it is not cryptographically secure.
In other words, you should not use the random module for security-critical features in web applications, such as:
- Generating user passwords or reset tokens
- Session IDs or authentication tokens
- Generating API keys
- Any other secret values that should not be guessed by a third party
For these purposes, you must use the dedicated module for generating cryptographically secure random numbers, secrets, which has been added to the standard library since Python 3.6.
The usage of the secrets module is very similar to that of the random module, but it uses the most secure source of randomness provided by the OS, making it extremely difficult for a third party to predict.
Example: Generating a secure token with the secrets module
import secrets
import string
# --- Generate a secure URL-safe token (32 bytes) ---
# Can be used for password reset URLs, etc.
url_safe_token = secrets.token_urlsafe(32)
print(f"Secure URL-safe token: {url_safe_token}")
# --- Example of generating a secure password (16 characters) ---
# Use alphanumeric characters and symbols as candidate characters
alphabet = string.ascii_letters + string.digits + string.punctuation
# Use secrets.choice() to securely choose characters
secure_password = ''.join(secrets.choice(alphabet) for i in range(16))
print(f"Example of a secure password: {secure_password}")
Summary
In this article, we have explained in detail everything from the basics of random number generation using Python's random module to practical application examples in web production and important security precautions.
Finally, let's review the main functions once more.
- Integers:
random.randint(a, b)(inclusive of a, b),random.randrange(start, stop)(exclusive of stop) - Element Selection:
random.choice(seq)(one),random.choices(seq, k=n)(n items with replacement),random.sample(seq, k=n)(n items without replacement) - Reordering:
random.shuffle(x)(modifies the original list directly) - Decimals:
random.random()(0.0 to 1.0),random.uniform(a, b)(in the range a to b) - Reproducibility:
random.seed(value)(fixes the random number sequence) - Security: Always use the
secretsmodule for passwords and tokens!
By mastering these functions, you can easily create test data in web development or add a little surprise and interactivity to the user experience. Please copy and paste the code we have introduced and make the random generation feature your own by actually running it!
π Next Steps
Once you're comfortable with data manipulation in Python, let's try tackling "regular expressions," a powerful tool for string manipulation. It will make searching and replacing complex text data much easier.
Next article: Using the re Module for String Searching and Replacement with Regular Expressions