Generating two random numbers in Python is a common task for simulations, games, sampling, or any program that needs a bit of unpredictability. Python’s built-in random module provides several functions to produce random integers, floats, or even pick from a list. This guide walks you through the simplest methods, explains the differences, and helps you avoid common pitfalls.
What You’ll Need
- Python 3 installed on your computer (any recent version works; the examples use Python 3.8+).
- A text editor or Python IDE (like IDLE, VS Code, PyCharm) or an interactive Python shell.
- No extra packages are required—the
randommodule is part of Python’s standard library.
Step-by-Step
- Open a Python environment – Start your Python interpreter, or create a new
.pyfile in your editor. - Import the random module – At the top of your script, type
import random. This gives you access to all the random functions. - Generate two random integers – Use
random.randint(a, b)to get a random integer betweenaandb(inclusive). For example:import random num1 = random.randint(1, 100) num2 = random.randint(1, 100) print(num1, num2)This prints two integers, each between 1 and 100. If you want them to be different, you can add a loop to regenerate if they match.
- Generate two random floats – Use
random.random()for a float between 0.0 and 1.0, orrandom.uniform(a, b)for a float in a specific range:f1 = random.random() f2 = random.uniform(10.5, 20.5) print(f1, f2)random.random()returns a value like 0.374, whilerandom.uniform(10.5, 20.5)gives something like 15.234. - Generate two numbers from a list – If you need to pick two distinct items from a list, use
random.sample(population, k):colors = ['red', 'green', 'blue', 'yellow'] two_colors = random.sample(colors, 2) print(two_colors)This returns a list of two unique elements. If you don’t mind duplicates, use
random.choice()twice. - Generate two numbers with a seed (optional) – For reproducible results, set a seed before generating:
random.seed(42) a = random.randint(1, 10) b = random.randint(1, 10) print(a, b)The same seed will always produce the same two numbers, which is useful for testing.
- Run your code – Execute the script. You’ll see two random numbers printed to the console.
Common Mistakes
- Forgetting to import random – Calling
random.randint()without importing raises aNameError. - Using the wrong function –
random.random()returns a float between 0 and 1, not an integer. For integers, userandintorrandrange. - Confusing inclusive vs exclusive –
randint(1, 10)includes 10, butrandrange(1, 10)does not. Check your bounds carefully. - Assuming the two numbers are unique – Unless you use
random.sample()or add a check, the two numbers can be equal. If you need distinct values, handle that explicitly. - Using
randomas a variable name – If you name a variablerandom, it shadows the module and breaks subsequent calls.
Tips
- Use
random.randrange(start, stop, step)for more control, e.g., even numbers only:random.randrange(0, 101, 2). - For cryptographic security (e.g., passwords), use
secretsmodule instead ofrandom. Therandommodule is not suitable for security-sensitive purposes. - Store the two numbers in variables rather than printing directly, so you can use them later in calculations.
- If you need many pairs, consider using a list comprehension:
[(random.randint(1, 6), random.randint(1, 6)) for _ in range(10)]. - Set a seed for debugging – When you set a seed, you get the same sequence every run, making it easier to reproduce bugs.
Troubleshooting
- NameError: name ‘random’ is not defined – Add
import randomat the top of your script. - ValueError: empty range for randrange() – This happens if you call
randrange(10, 10)orrandint(10, 10)incorrectly (start equals stop). Ensure start is less than stop. - TypeError: ‘float’ object cannot be interpreted as an integer –
randintandrandrangerequire integer arguments. If you have floats, convert them withint()first. - Numbers are the same when you need different ones – Use
random.sample()if you’re picking from a list, or write a loop that regenerates until they differ. - Random numbers are the same every run – This is normal if you set a seed. Remove the
random.seed()line to get different numbers each time. - ImportError: No module named ‘random’ – Very unlikely, but ensure your Python installation is correct. Reinstall Python if needed.
Frequently Asked Questions
- Can I generate two random numbers without importing a module? – No, Python’s standard library does not include a built-in random function without importing
random. You could write your own pseudo-random generator, but it’s not recommended. - How do I generate two random numbers that are different from each other? – Use
random.sample(range(1, 101), 2)to get two unique integers, or use a loop to regenerate if they match. - What’s the difference between
random.randintandrandom.randrange? –randint(a, b)returns an integer between a and b inclusive.randrange(a, b)returns an integer from a to b-1 (exclusive). Userandrangewhen you want to exclude the upper bound. - Can I generate random numbers with a specific distribution, like normal? – Yes, use
random.gauss(mu, sigma)for a normal distribution, orrandom.expovariate(lambda)for exponential. These return floats. - Is the
randommodule safe for password generation? – No, it’s not cryptographically secure. Use thesecretsmodule for passwords, tokens, or any security-sensitive data. - How do I generate two random numbers in a single line? – You can use tuple unpacking:
a, b = random.randint(1, 10), random.randint(1, 10).
Related
- 5 Random Numbers: How to Pick Them Fairly
- Google Sheets Split One Cell Into Two: How-To
- Entry Level Data Management Jobs: What They Are
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Shortcut to Shut Down PC: Fastest WaysThe absolute fastest way to shut down a Windows PC is to press Alt + F4 on the…
- Remove Duplicates in Excel: Keyboard ShortcutIn Excel for Microsoft 365 on Windows, select a cell in your data and press Alt, then A,…
- Excel Cell Width in Inches: What the Number Really MeansExcel does not measure column width directly in inches: its width setting is based on the number of…
- Google Sheets Look for Duplicates? Find Them FastYes. In Google Sheets, use Format > Conditional formatting to highlight duplicate values, or Data > Data cleanup…
- How to Hide Page Breaks in Excel and Keep Print LayoutTo hide page-break lines in Excel for Microsoft 365 on Windows, open File > Options > Advanced, find…
- Excel Data Validation Must Be a Date? No—Here’s HowNo, Excel data validation does not have to be a date. You can restrict entries to whole numbers,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.