Python Random getrandbits() Method with Examples

In Python, the random module is used to generate random numbers. This is not truly random; rather, it is used to generate pseudo-random numbers. This implies that these numbers can be determined at random.

random getrandbits() Method in Python:

getrandbits() method returns an integer of the specified size (in bits).

Syntax:

random.getrandbits(num)

Parameters:

num: This is Required. A number indicating the size of the returned integer in bits.

Examples:

Example1:

Input:

Given number(size) = 6

Output:

The random integer =  56

Example2:

Input:

Given number(size) = 10

Output:

The random integer = 59

Random getrandbits() Method with Examples in Python

Method #1: Using Built-in Functions (Static Input)

Approach:

  • Import random module using the import keyword.
  • Give the number(size) as static input and store it in a variable.
  • Pass the given number as an argument to the random.getrandbits() method that returns an integer of the given size in bits.
  • Store it in another variable.
  • Print an integer with a size of a given number of bits.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the number(size) as static input and store it in a variable.
gvn_numb = 6
# Pass the given number as an argument to the random.getrandbits() method that
# returns an integer of the given size in bits.
# Store it in another variable.
rslt = random.getrandbits(gvn_numb)
# Print an integer with a size of a given number of bits.
print("The random integer = ", rslt)

Output:

The random integer =  56

Method #2: Using Built-in Functions (User Input)

Approach:

  • Import random module using the import keyword.
  • Give the number(size) as user input using the int(input()) function and store it in a variable.
  • Pass the given number as an argument to the random.getrandbits() method that returns an integer of the given size in bits.
  • Store it in another variable.
  • Print an integer with a size of a given number of bits.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the number as user input using the int(input()) function and
# store it in a variable.
gvn_numb = int(input("Enter some random number = "))
# Pass the given number as an argument to the random.getrandbits() method that
# returns an integer of the given size in bits.
# Store it in another variable.
rslt = random.getrandbits(gvn_numb)
# Print an integer with a size of a given number of bits.
print("The random integer = ", rslt)

Output:

Enter some random number = 10
The random integer = 59