Thursday, September 4, 2025
HomeLanguagesrandom.getrandbits() in Python

random.getrandbits() in Python

random module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined.

random.getrandbits()

The getrandbits() method of the random module is used to return an integer with a specified number of bits. The number of bits required in the result is passed as an parameter in the method. Examples :

Input : getrandbits(4)
Output : 14
(the binary equivalent of 14 is 1110 which has 4 bits)

Input : getrandbits(16)
Output : 60431
(the binary equivalent of 60431 is 1110110000001111 
which has 16 bits)

Example 1: 

Python3




# import the random module
import random
 
# a random number with 4 bits
print(random.getrandbits(4))
 
# a random number with 16 bits
print(random.getrandbits(16))


Output : 

10
49195

Example 2: 

Python3




# import the random module
import random
 
# 5 random number with 4 bits
for i in range(4):
    print(random.getrandbits(4))


Output:

10
0
1
14
RELATED ARTICLES

Most Popular

Dominic
32261 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6695 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS