Python Glossary Русский

Python 3.6+secretsfunction

secrets.randbelow()

random numbers

Returns a cryptographically strong random integer in the range [0, n); n itself is excluded.

Syntax

secrets.randbelow(exclusive_upper_bound) -> int

The upper bound is excluded, like range(), unlike random.randint(a, b) which includes both ends. There is no lower bound: for [a, b] write a + randbelow(b - a + 1). An n of zero or less raises ValueError. It fits one-time codes: f'{secrets.randbelow(10**6):06d}'.

Examples

import secrets
n = secrets.randbelow(10)
print(0 <= n < 10)  # → True
code = f'{secrets.randbelow(10**6):06d}'
print(len(code))  # → 6
secrets.randbelow(0)  # → ValueError: Upper bound must be positive.

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy