What is the random.getrandbits() method in Python?

Overview

The random.getrandbits() method is used to return a random number in the specified size, in bits.

Syntax

random.getrandbits(n)

Parameters

The random.getrandbits() method requires a parameter value, n, that specifies the size (in bits) of the random number to be generated.

How to use the random.getrandbits() method

Let’s generate a random integer with a bit size of 4.

import random
print(random.getrandbits(4))

Explanation

  • Line 1: We import the random module.
  • Line 3: We use the random.getrandbits() method to generate a random number with a bit size of 4.

Free Resources