This guide shows you how to generate four random numbers in Python using the built-in random module. You’ll learn several methods—integers, floats, and unique numbers—and how to avoid common pitfalls. No extra installations are needed; Python’s standard library has everything you require.
What You’ll Need
- Python 3.x installed on your computer (any recent version works).
- A text editor or Python IDE (like IDLE, VS Code, or PyCharm).
- Basic familiarity with running Python scripts.
Step-by-Step
-
Open a Python script or interactive shell.
Create a new file (e.g.,
random_numbers.py) or open a Python REPL to follow along. -
Import the random module.
At the top of your script, add:
import randomThis gives you access to all random functions.
-
Generate four random integers between 1 and 100.
Use
random.randint(a, b)to get integers in the inclusive range. Call it four times and store the results in a list:numbers = [random.randint(1, 100) for _ in range(4)] print(numbers)This creates a list of four distinct calls; duplicates are possible because each call is independent.
-
Generate four random floats between 0 and 1.
Use
random.random()which returns a float in [0.0, 1.0):floats = [random.random() for _ in range(4)] print(floats)For a different range, multiply and add:
random.random() * 10 + 5gives [5.0, 15.0). -
Generate four unique random integers from a range.
Use
random.sample(population, k)to pick k unique items without repetition:unique_numbers = random.sample(range(1, 101), 4) print(unique_numbers)This guarantees four different numbers. The population must have at least 4 items.
-
Generate four random numbers from a normal distribution.
Use
random.gauss(mu, sigma)for Gaussian-distributed floats:gaussians = [random.gauss(0, 1) for _ in range(4)] print(gaussians)This is useful for simulations and statistical sampling.
-
Run your script.
Execute the file with
python random_numbers.pyin your terminal, or press Run in your IDE. You’ll see the four numbers printed.
Common Mistakes
- Forgetting to import random – causes a
NameError. - Using
random.randrangeincorrectly – remember it excludes the stop value:random.randrange(1, 5)gives 1–4, not 5. - Assuming
random.sampleallows duplicates – it doesn’t; if you need duplicates, userandom.choicein a loop. - Using
random.seedincorrectly – seeding with the same value gives the same sequence, which may surprise you if you expect true randomness.
Tips
- Set a seed for reproducibility – call
random.seed(42)before generating to get the same numbers every run, useful for testing. - Use list comprehensions – they are concise and faster than a for loop with
append. - For cryptographic security, use the
secretsmodule instead ofrandom(e.g.,secrets.randbelow(100)). - If you need a fixed number of floats in a range, use
random.uniform(a, b).
Troubleshooting
Problem: I get a ValueError: sample larger than population.
Solution: Your range is too small. For random.sample(range(1, 5), 4), the range has only 4 values (1,2,3,4) – that works, but if you ask for 5, it fails. Ensure the population size is at least k.
Problem: The numbers are the same every time I run the script.
Solution: You likely called random.seed() with a fixed value. Remove the seed or change it to get different results.
Problem: I get a TypeError when using random.randint with floats.
Solution: randint expects integers. Use random.uniform for floats.
Problem: My list contains the same number repeated.
Solution: That’s normal with independent calls. If you need uniqueness, use random.sample.
Frequently Asked Questions
Q: How do I generate 4 random numbers without duplicates?
A: Use random.sample(range(start, stop+1), 4). For example, random.sample(range(1, 101), 4) gives 4 unique integers from 1 to 100.
Q: Can I generate 4 random numbers as a tuple?
A: Yes, just wrap the list in tuple(): tuple(random.randint(1, 10) for _ in range(4)).
Q: What’s the difference between random.randint and random.randrange?
A: randint(a, b) includes both endpoints; randrange(a, b) excludes b. For example, randint(1, 3) can be 1,2,3; randrange(1, 3) can be 1 or 2.
Q: Is there a way to generate 4 random numbers that sum to a specific value?
A: Yes, generate three random numbers and calculate the fourth as the remainder. For instance, for a sum of 100, generate a, b, c randomly, then set d = 100 - (a+b+c). Ensure the remainder is within your desired range.
Q: How can I make the random numbers reproducible?
A: Call random.seed(42) (or any integer) before generating. The same seed will produce the same sequence every time.
Q: Can I generate 4 random numbers from a specific list?
A: Yes, use random.choices(my_list, k=4) for sampling with replacement, or random.sample(my_list, 4) for without replacement (if the list has at least 4 items).
Related
- Data Entry Jobs From Home for Students: Real Guide
- Google Sheets Remove Dropdown From Column
- Random Number 1-3: How to Generate One
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Shortcuts for Naming a Range and Managing NamesIn Excel for Microsoft 365 on Windows, press Ctrl+F3 to open Name Manager, then choose New to name…
- How to Insert an Image in Excel (Step-by-Step)To insert an image in Excel for Microsoft 365 on Windows, select the worksheet, choose Insert > Pictures…
- How to Make Columns in Word the Same Width in Any DocumentTo make newspaper-style columns in Word equal width, open Layout > Columns > More Columns, choose how many…
- Excel Insert Row Greyed Out? Causes and FixesIn Excel for Microsoft 365 on Windows, Insert Row is usually greyed out because the worksheet is protected,…
- How to Split a Large CSV FileWhen a CSV file grows to hundreds of thousands of rows, it becomes slow to open in Excel,…
- Accept Track Changes in Word: A Step-by-Step GuideTo accept tracked changes in Word, open the document, go to Review, and use the Accept menu to…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.