How to Generate 3 Random Numbers in Python
In this article
To generate three random numbers in Python, the quickest method is to import the random module and call random.random() three times, or use a list comprehension like [random.random() for _ in range(3)]. For integers within a range, use random.randint(1, 100) three times. This guide walks through each approach with clear steps, plus common pitfalls and troubleshooting so you get reliable results whether you need floats, integers, or unique values.
What You'll Need
- A working Python installation (version 3.6 or later is recommended; the examples use standard features available in all Python 3 versions).
- A text editor or IDE to write and run your code (IDLE, VS Code, PyCharm, or any editor you prefer).
- Basic familiarity with running a Python script or using the interactive interpreter.
No third-party packages are required—the random module is part of Python's standard library.
Step-by-Step
- Open your Python environment. You can use the interactive shell (type
pythonorpython3in your terminal) or create a new.pyfile in your editor. For a script, save it with a name likerandom_three.py. - Import the random module. At the top of your file or in the shell, type:
import random
This gives you access to all the random number functions. If you only need a few functions, you can also usefrom random import random, randint, but importing the whole module is clearer for beginners. - Decide what kind of random numbers you need. The three most common types are:
- Floating-point numbers between 0.0 and 1.0 (exclusive of 1.0): userandom.random().
- Integers within a specified inclusive range: userandom.randint(a, b).
- Floating-point numbers within a range: userandom.uniform(a, b).
Choose the one that fits your task. The steps below show each method. - Generate three random floats between 0 and 1. The simplest approach is a loop or list comprehension:
numbers = [random.random() for _ in range(3)]print(numbers)
This produces a list of three floats such as[0.123, 0.456, 0.789]. Each call torandom.random()returns a new value. - Generate three random integers within a range. Use
random.randintwith your desired minimum and maximum (both inclusive). For example, to get three integers between 1 and 100:numbers = [random.randint(1, 100) for _ in range(3)]print(numbers)
This might output[42, 17, 89]. Adjust the arguments as needed. - Generate three random floats within a custom range. Use
random.uniform(a, b)to get floats betweenaandb(inclusive of endpoints in most cases, but the distribution is continuous). Example for numbers between 10 and 20:numbers = [random.uniform(10, 20) for _ in range(3)]print(numbers) - Run your code. If you're using a script, save the file and run it from the terminal with
python random_three.py(orpython3on macOS/Linux). If you're in the interactive shell, just press Enter after each line. You should see a list of three numbers printed. - Verify the output. Check that you got exactly three numbers and that they fall within the expected range. For floats between 0 and 1, ensure no value is exactly 1.0 (which is possible but extremely rare). For integers, confirm they are within your min and max.
Common Mistakes
- Forgetting to import the module. Trying to call
random.random()withoutimport randomraises aNameError. Always import first. - Using
random.randintwith reversed arguments.random.randint(10, 1)raises aValueErrorbecause the first argument must be less than or equal to the second. Double-check your min and max order. - Assuming
random.random()includes 1.0. It returns values in the half-open interval [0.0, 1.0). If you need 1.0 included, userandom.uniform(0, 1)instead. - Generating numbers in a loop without storing them. If you write
for _ in range(3): random.random()without appending to a list, you lose the values. Use a list comprehension or append to a list. - Expecting unique numbers from
random.randint.randintcan repeat values. If you need three distinct numbers, userandom.sample(range(1, 101), 3). - Using the wrong function for the data type.
random.random()returns a float; if you need an integer, userandintorrandrange. Mixing them up leads to type errors later.
Tips
- Use
random.samplefor unique values. If you need three non-repeating numbers from a range,random.sample(range(1, 50), 3)is the cleanest way. It returns a list of three distinct integers. - Set a seed for reproducibility. Call
random.seed(42)before generating numbers to get the same sequence every time—useful for testing or debugging. - Use
random.choicesfor weighted picks. If you need three numbers with different probabilities,random.choiceswith aweightsparameter can help, though it's more advanced. - Consider
secretsfor security-sensitive use. Therandommodule is not cryptographically secure. For passwords or tokens, use thesecretsmodule instead. - Format output for readability. Use
round(num, 2)to limit decimals when printing floats, or f-strings likef"{num:.3f}". - Test with small ranges. When using
randint, try a small range like 1 to 3 to quickly see if your logic works before scaling up.
Troubleshooting
If your code doesn't work as expected, check these common issues:
- NameError: name 'random' is not defined. You forgot to import the module. Add
import randomat the top. - ValueError: empty range for randrange(). This happens when the range is invalid, e.g.,
random.randint(5, 5)is fine (returns 5), butrandom.randint(5, 4)is not. Ensure min ≤ max. - TypeError: 'module' object is not callable. You might have written
random()instead ofrandom.random(). The module itself is not callable; use the function. - Getting the same number every time. If you set a seed and don't change it, the sequence repeats. Remove the seed or change it for different results.
- Output is not a list of three. Check that your loop runs exactly three times. If using
range(3), it yields 0, 1, 2—three iterations. Off-by-one errors are common; verify with a print statement inside the loop. - Numbers outside expected range. Double-check the arguments to
randintoruniform. Rememberrandintincludes both endpoints, whileuniformmay include them depending on floating-point rounding.
If you're still stuck, simplify: try generating one random number first, then expand to three. Use print() to inspect intermediate values.
Frequently Asked Questions
How do I generate three random numbers without duplicates?
Use random.sample(range(start, end), 3) where the range contains at least three numbers. For example, random.sample(range(1, 11), 3) returns three unique integers between 1 and 10.
Can I generate three random numbers in a single line?
Yes, use a list comprehension: [random.random() for _ in range(3)]. This creates a list of three random floats in one line.
What's the difference between random.random() and random.uniform(0, 1)?
random.random() returns a float in [0.0, 1.0), never exactly 1.0. random.uniform(0, 1) can return 1.0 due to rounding, and allows any range, not just 0 to 1.
How do I get three random integers between 1 and 10?
Use [random.randint(1, 10) for _ in range(3)]. Each call returns an integer from 1 to 10 inclusive, and duplicates are possible.
Is the random module suitable for cryptography?
No, the random module is not cryptographically secure. For security-sensitive applications, use the secrets module, which is designed for generating secure random numbers.
How can I make the random numbers reproducible?
Set a seed before generating: random.seed(42). Then every run will produce the same sequence of numbers. This is useful for testing and debugging.