Generate random integers between two bounds in Python

Use randint for inclusive integer bounds, randrange for an exclusive stop, and secrets for security-sensitive randomness.

Best practices
Generate random integers between two bounds in Python illustration

random.randint(x, y) returns an integer including both endpoints. For example, random.randint(1, 10) can return either 1 or 10.

Compare the interval rules

import random

random.randint(1, 10)        # 1 through 10, inclusive
random.randrange(1, 11)      # Stop value 11 is excluded
random.choice(range(1, 11))  # Select from the same ten values

Use integer bounds and make sure the interval is nonempty. For a stepped range, randrange also accepts a step, such as random.randrange(0, 11, 2) for even numbers from 0 through 10.

Use secrets for security-sensitive values

The random module is intended for simulation and similar work, not passwords, verification codes, or authentication tokens.

import secrets

value = secrets.randbelow(10) + 1  # 1 through 10

For inclusive integer bounds x <= y, use secrets.randbelow(y - x + 1) + x. A cryptographically secure generator does not make a tiny output range hard to guess; choose a range and expiry policy appropriate to the application.

Reproduce a test sequence

rng = random.Random(42)
value = rng.randint(1, 100)

A dedicated generator avoids changing the module’s shared random state. Reusing the seed and call sequence reproduces a run in the same environment; do not assume every helper algorithm has identical output across Python versions. Calling randint repeatedly advances the sequence rather than returning the first seeded value every time.

FAQ

Does randint(0, 1) choose between two values?

Yes. Its possible results are 0 and 1, with equal probability.

How do I generate a floating-point value?

Use random.uniform(x, y). Floating-point rounding means the upper endpoint may or may not be included; it does not have the same exact endpoint rule as integer randint.

See Python random-number generators, Python secrets module.

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting