Python random.getrandbits()

Python random.getrandbits()

The random module is used to generate random numbers in Python. These are not actually random numbers, but rather pseudo-random numbers. This means that these randomly generated numbers can be determined.

random.getrandbits()

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

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:

# 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:

# 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

Leave a Reply

Your email address will not be published. Required fields are marked *