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 14 is 1110110000001111 
which has 16 bits)

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output :

10
49195

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

10
0
1
14
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.