all Python 3randomfunction
random.getrandbits
bits and bytes
An integer of k random bits (0 <= result < 2**k); it draws on the core generator, so it is reproducible under a fixed seed.
Syntax
random.getrandbits(k)
The engine underneath is the Mersenne Twister: observe enough output and its internal state can be reconstructed, so passwords, tokens and keys belong to secrets.randbits() or os.urandom() instead. A negative k raises ValueError, while k=0 is legal and always yields 0.
Examples
# Python 3.9+
import random
random.seed(0)
print(random.getrandbits(8)) # → 216
print(0 <= random.getrandbits(4) < 16) # → True
print(len(f'{random.getrandbits(128):032x}')) # → 32
print(random.getrandbits(0)) # → 0
print(random.getrandbits(-1)) # → ValueError
See also
Open in the full glossarydocs.python.orgReport an inaccuracy