This article is especially suitable for students who have just learned the basic syntax of Python; even those with no background can easily get started!
In daily programming, we often need to generate random numbers—such as when developing a guessing game, a lottery program, or creating test data for data analysis. Today, we will teach you how to play with random numbers in Python in the most straightforward way!
🔑 Summoning the “Random Number Generator”
Python has a powerful toolbox called <span>random</span>, which can be summoned with just one line of code:
import random # Summon our random number tool
🎲 Generating a Single Random Number (Super Simple)
Want to generate an integer? Try this:
import random
# Generate a random integer between 1 and 10 (inclusive)
dice = random.randint(1, 10)
print("Random dice roll:", dice) # Output could be: 7
Want a random number with decimals:
import random
# Generate a random float between 0.0 and 1.0
percent = random.random()
print("Task completion: {:.1f}%".format(percent*100))
# Example output: Task completion: 73.8%
Tip:
<span>{:.1f}</span>can keep the decimal to one place for a more aesthetically pleasing output.
📋 Creating a List of Random Numbers (Advanced)
Scenario Simulation: A teacher needs to randomly assign grades to 10 students (50-100 points).
import random
# Create an empty grade list
score_list = []
for i in range(10):
# Generate a random grade
score = random.randint(50, 100)
# Add to the grade list
score_list.append(score)
print("Class grade list:", score_list)
# Example output: [78, 92, 65, 88, 73, 95, 81, 69, 85, 77]
Float version (suitable for generating temperature, price, etc.):
import random
# Generate 5 temperature data points between 35.0 and 40.0
temperature_list = []
for i in range(5):
# Generate random temperature, keeping one decimal place
temp = round(random.uniform(35.0, 40.0), 1)
temperature_list.append(temp)
print("Temperature records:", temperature_list, "℃")
# Example output: [36.7, 37.2, 38.5, 36.2, 37.8] ℃
Key Notes:
<span>round(x, 1)</span>can keep the decimal to one place.
<span>uniform(a, b)</span>is specifically for generating floats within a range.
🎯 Simple Lottery Program
import random
# List of employees participating in the lottery
employees = ["Zhang San", "Li Si", "Wang Wu", "Zhao Liu", "Qian Qi"]
# Randomly select 3 lucky winners
winners = []
for _ in range(3):
lucky_index = random.randint(0, len(employees)-1)
winners.append(employees[lucky_index])
print("Winners list:", winners)
💡 Tips
1. Fixing Random Results (super useful for debugging):
import random
random.seed(42) # Set random seed
print(random.randint(1,100)) # Always outputs 82
2. More Concise Syntax (using list comprehensions):
import random
# Generate 10 random numbers in one line
rand_list = [random.randint(1,100) for _ in range(10)]
print(rand_list)
3. Important Reminder:
The built-in
<span>random</span>module in Python is not suitable for generating passwords or other security scenarios; for such needs, use the more specialized<span>secrets</span>module.
✏️ Hands-On Practice
Try generating a list containing 20 elements, each being a two-digit random integer (10-99). After completing, you can try to:
- Calculate the average of the list
- Find the maximum and minimum values
- Develop a simple guessing game
The best way to learn programming is through hands-on practice! If you encounter any issues, feel free to leave a comment for discussion~