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.
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources