Python: Generate a Random Integer in a Range
In this article
To generate a random integer within a range in Python, import the random module and call random.randint(a, b), which returns an integer from a to b inclusive. For example, random.randint(1, 10) returns a whole number between 1 and 10, with both endpoints possible. That one line is all you need for most cases; the rest of this guide covers the variations, the pitfalls, and what to do when the result is not what you expected.
What You'll Need
- A working Python installation (Python 3 is assumed throughout; the
randommodule is part of the standard library, so no extra install is required). - A way to run Python code: the interactive interpreter, a script file, or a notebook.
- Basic familiarity with importing modules and calling functions.
Step-by-Step
- Import the random module. At the top of your script or in your interpreter session, type
import random. This loads Python's built-in pseudo-random number generator. No pip install is needed becauserandomships with Python. - Decide your inclusive bounds.
random.randint(a, b)includes bothaandb. If you want a number from 1 to 6 like a die roll, the call israndom.randint(1, 6). If you want 0 through 9, userandom.randint(0, 9). Write down the lowest and highest values you actually want to see, because the inclusive behaviour is the most common source of off-by-one errors. - Call randint and store or print the result. For example:
number = random.randint(1, 100)thenprint(number). Each time you run the program you will get a different value (subject to the seeding note below). - Use randrange if you prefer an exclusive upper bound.
random.randrange(start, stop)returns a value fromstartup to but not includingstop. Sorandom.randrange(1, 7)behaves likerandom.randint(1, 6). This style matches Python'srange()function and is handy when your upper limit is naturally exclusive, such as choosing an index into a list of lengthn:random.randrange(len(my_list)). - Use choice for picking from a sequence. If your "range" is really a set of allowed values, such as
[10, 20, 30], userandom.choice([10, 20, 30]). It returns one element uniformly at random and avoids arithmetic mistakes. - Test the boundaries. Run your code several times and confirm you can see both the minimum and maximum values appear. With a small range like 1 to 3, a handful of runs should show all three outcomes. This catches the classic mistake of passing the wrong upper bound.
- Seed only when you need reproducibility. If you are writing tests or a tutorial where the same "random" output must appear every run, call
random.seed(42)(any fixed number) before generating. For normal programs, do not seed; Python seeds itself from the operating system at startup, which is what you want for genuine unpredictability. - For security-sensitive values, switch modules. The
randommodule is not cryptographically secure. If you are generating passwords, tokens, or anything an attacker might guess, use thesecretsmodule instead:import secretsthensecrets.randbelow(100)for 0 to 99, orsecrets.choice()for picking from a sequence. Thesecretsmodule is also in the standard library.
Common Mistakes
- Assuming the upper bound is excluded.
randintincludes both ends. People coming from other languages often expectrandint(1, 10)to stop at 9. It does not. If you want 1 to 9, writerandint(1, 9). - Swapping the arguments.
random.randint(10, 1)raises aValueErrorbecause the low bound must not exceed the high bound. Always pass the smaller number first. - Passing floats.
randintexpects integers.random.randint(1.0, 10.0)raises aValueError. Userandom.uniform(1.0, 10.0)if you actually want a float. - Re-seeding inside a loop. Calling
random.seed()before every draw can produce the same value repeatedly, especially with a fixed seed. Seed once at the start if you need it at all. - Using random for security. As noted above,
randomis fine for games and simulations but not for passwords or tokens. Usesecretsthere. - Forgetting to import. A
NameError: name 'random' is not definedalmost always means the import line is missing or misspelled.
Tips
- Use
random.randintwhen you think in inclusive terms (dice, card values, "a number from 1 to 100") andrandom.randrangewhen you think in slice terms (list indices, ranges that stop before the end). - For a quick one-off in the interpreter, you can run
python -c "import random; print(random.randint(1, 10))"from your shell. - If you need several unique integers from a range (like a lottery draw), use
random.sample(range(1, 50), 6). It returns a list of distinct values without repeats. - To shuffle a list in place, use
random.shuffle(my_list)rather than generating random indices yourself. - When debugging, print the bounds alongside the result so you can see exactly what was requested:
print(f"{low}-{high}: {value}").
Troubleshooting
If you see NameError: name 'random' is not defined, add import random at the top of the file. If you see ValueError: empty range for randrange() or a message about the low bound being greater than the high bound, check the order of your arguments and confirm the range is not empty (for example, randint(5, 5) is valid and always returns 5, but randint(5, 4) is not). If you get TypeError or ValueError about non-integer arguments, convert your values with int() or switch to random.uniform for floats. If the same number keeps appearing, look for a random.seed() call with a fixed value, or a seed set inside a loop. If results seem biased or predictable in a security context, replace random with secrets. If nothing runs at all, confirm you are using Python 3 by checking python --version; the examples here assume Python 3, and on some systems the command may be python3.
Frequently Asked Questions
Is random.randint inclusive of both endpoints?
Yes. random.randint(a, b) can return a, b, or anything in between. Use random.randrange(a, b) if you want the upper bound excluded.
How do I get a random integer that excludes the maximum?
Use random.randrange(low, high), which stops one short of high. For example, random.randrange(1, 10) returns 1 through 9.
Can I generate a random integer without importing anything?
No, the standard library's random functions live in the random module (or secrets for security use), so you must import one of them. There is no built-in function in the default namespace.
Why do I get the same number every time I run my script?
Most likely you are calling random.seed() with a fixed value, or seeding inside a loop. Remove the seed call, or seed only once at the start when reproducibility is intentional.
What is the difference between randint and randrange?
randint(a, b) includes both endpoints. randrange(start, stop) includes start but excludes stop, matching the behaviour of range(). Both return integers.
Should I use random or secrets for passwords?
Use secrets. The random module is designed for simulation and games, not for values that must resist guessing. secrets.randbelow(n) and secrets.choice() are the right tools for tokens and passwords.