Python NumPy random.bytes() Function

The random module is part of the NumPy library. This module includes the functions for generating random numbers. This module includes some basic random data generating methods, as well as permutation and distribution functions and random generator functions.

NumPy random.bytes() Function:

The NumPy random.bytes() function returns a string containing the number of random bytes given.

Syntax:

numpy.random.bytes(length)

Parameters

length: This is Required. It Specifies the number of random bytes.

Return Value:

It returns a string with the given length.

NumPy random.bytes() Function in Python

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

Example1

Approach:

  • Import numpy module using the import keyword.
  • Give the length as static input and store it in a variable.
  • Pass the above-given length as an argument to the random.bytes() of numpy module to get a string with the given length of random bytes.
  • Store it in a variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np  
# Give the length as static input and store it in a variable.
gvn_len = 6
# Pass the above given length as an argument to the random.bytes() of numpy
# module to get a string with the given length of random bytes.
# Store it in a variable.
rslt=np.random.bytes(gvn_len)  
# Print the above result
rslt

Output:

b'\xb3\t\x02d"\xaa'

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

Approach:

  • Import numpy module using the import keyword.
  • Give the length as user input using the int(input()) function and store it in a variable.
  • Pass the above-given length as an argument to the random.bytes() of numpy module to get a string with the given length of random bytes.
  • Store it in a variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np  
# Give the length as user input using the int(input()) function 
# and store it in a variable.
gvn_len = int(input("Enter some random number = "))
# Pass the above given length as an argument to the random.bytes() of numpy
# module to get a string with the given length of random bytes.
# Store it in a variable.
rslt=np.random.bytes(gvn_len)  
# Print the above result
rslt

Output:

Enter some random number = 8
b'\x84!\x18\xc0\xbb\x1c<S'