To generate a random number between a range in Python, use the random.randint(a, b) function for integers (inclusive of both endpoints) or random.uniform(a, b) for floating-point numbers (inclusive of the lower bound, exclusive of the upper bound in most implementations). For example, random.randint(1, 10) returns an integer from 1 to 10, while random.uniform(1.0, 10.0) returns a float between 1.0 and just under 10.0.
Why Random Numbers Matter in Python
Random number generation is a core feature in Python, used in simulations, games, statistical sampling, cryptography, and machine learning. The standard library provides the random module, which is sufficient for most non-security-sensitive tasks. For cryptographic applications, Python offers the secrets module, which uses a stronger source of randomness. Understanding the difference between these two modules is essential for choosing the right tool for your project.
How the random Module Works
The random module uses a pseudo-random number generator (PRNG) called the Mersenne Twister. It is deterministic: given the same seed, it produces the same sequence of numbers. This is useful for reproducible experiments. You can set the seed with random.seed(42) to get the same sequence every run. The module provides several functions for generating numbers within a range:
random.randint(a, b)– returns an integer N such that a <= N <= b.random.randrange(start, stop[, step])– returns an integer from the range start to stop (exclusive) with an optional step.random.uniform(a, b)– returns a float N such that a <= N < b (though b may be included due to rounding).random.random()– returns a float in [0.0, 1.0). Combine with multiplication and addition to scale.
For example, to simulate a dice roll (1 to 6), use random.randint(1, 6). To generate a random float between 5.0 and 7.5, use random.uniform(5.0, 7.5).
Choosing Between randint, randrange, and uniform
Your choice depends on the type of number you need and whether the upper bound is inclusive. If you need an integer and want the upper bound included, use randint. If you prefer the Python-style exclusive upper bound (like range()), use randrange. For example, random.randrange(0, 10) returns 0 to 9, while random.randint(0, 10) returns 0 to 10. For floats, uniform is the direct choice, but you can also achieve the same with random.random() * (b - a) + a. The latter gives you explicit control over the scaling and is often used when you need to avoid the slight rounding that uniform might have.
Common Problems and Misconceptions
One common mistake is using random.randrange(1, 10) expecting 10 to be included. It is not; you need randrange(1, 11). Another misconception is that random.uniform(0, 1) can return 1.0. In practice, due to floating-point rounding, it rarely does, but the documentation states that the upper bound may or may not be included. If you need a strictly exclusive upper bound, use random.random() and scale it. Also, beginners often forget to import the module: import random is required. Finally, do not use random for security-sensitive tasks like generating passwords or tokens; use secrets instead.
Generating Random Numbers in NumPy
For scientific computing, NumPy offers a more powerful random module. The function numpy.random.randint(low, high, size=None) generates an array of random integers from low (inclusive) to high (exclusive). For floats, numpy.random.uniform(low, high, size=None) works similarly. These functions are faster and support vectorized operations, making them ideal for large datasets. Note that NumPy’s randint uses an exclusive upper bound, unlike Python’s random.randint. This is a common source of confusion when switching between the two.
Performance and Reproducibility
Generating a single random number is fast, but if you need millions, consider using NumPy for speed. For reproducibility, always set a seed. In the random module, use random.seed(42). In NumPy, use numpy.random.seed(42) (though the newer recommended approach is to use a Generator object, e.g., rng = numpy.random.default_rng(42)). This ensures that your results can be replicated in debugging or sharing research.
Security: When to Use the secrets Module
If you are generating random numbers for passwords, tokens, or any security-related purpose, the random module is not suitable because its PRNG is predictable. Instead, use the secrets module, which draws from the operating system’s secure random source. For example, to generate a random integer between 1 and 100 securely, use secrets.randbelow(100) + 1. To get a secure random float, you can use secrets.randbits(53) / (1 << 53) to mimic random.random() but securely. Always favor secrets for anything that could be exploited.
Frequently Asked Questions
How do I generate a random integer between 1 and 100 inclusive?
Use random.randint(1, 100). This includes both 1 and 100. If you need exclusive, use random.randrange(1, 101).
How do I generate a random float between 0 and 1?
Use random.random() which returns a float in [0.0, 1.0). For a different range, scale it: random.random() * (max - min) + min.
Why does random.randint sometimes return the same number repeatedly?
That is expected in random sequences. If you need to avoid repeats, you can use random.sample(range(a, b+1), k) to get k unique numbers.
Can I generate a random number from a normal distribution?
Yes, use random.gauss(mu, sigma) for a single value, or numpy.random.normal(mu, sigma, size) for an array.
Is random.uniform truly uniform?
Yes, in theory, but due to floating-point precision, the distribution is approximately uniform. For most purposes, it is sufficient.
How do I generate a random even number between two values?
Use random.randrange(start, stop, 2) with start and stop adjusted to even numbers. For example, to get an even number between 2 and 10 inclusive, use random.randrange(2, 11, 2).
Related
- Undo in Laptop Shortcut: Keys for Windows and Mac
- Google Sheets Savings Tracker Template: How to Use One
- Random 7 Digit Number: 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
- How to Use SUMIF in Google Sheets for Quick TotalsTo total values that match one condition in Google Sheets, enter =SUMIF(A2:A7,"Travel",B2:B7) in an empty cell, assuming categories…
- Excel Regression Line: Add, Format, and Interpret ItYes. In Excel for Microsoft 365 on Windows, create or select an XY scatter chart, then choose Chart…
- Excel CHAR Numbers for Bullet Points: Which to Use?In Excel for Microsoft 365 on Windows, CHAR(149) returns a bullet character in the Windows character set; for…
- How to Insert a Line in Word: Borders and Shapes GuideTo insert a line in a Word document, type three hyphens (—) on a blank line and press…
- Schedule Repeat Emails in Outlook: Options and StepsOutlook can schedule an individual email to send later, but it does not have a built-in option to…
- How to Screen Record a PowerPoint Presentation with AudioTo record a PowerPoint presentation with narration, open the deck and choose Record > From Beginning in PowerPoint…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.