Knowing how to generate random data using Python can be very useful in many cases. You might need to generate random data for Email OPT in your web application, or you might be working with cryptography using Python, where you need to generate a random UUID. Similarly, there are many applications where you need to generate random data using Python.
Generally, when it comes to generating random Data in Python, the first most library that comes to our mind is Python
module, but there are two other Standard modules in Python that can also be used to generate random data.
In this Python tutorial, I will walk you through the python Different code snippets to Generate random data in Python. So open your best Python IDE or Text editor and follow along.
Generate Random Numbers in Python
There are two modules in Python that can be used to generate random numbers.
For most of the cases, you will be using the Python
module to generate random numbers, but in case you wish to generate strong random numbers for the secret password, security token, and cryptography there, you should be using the Python
Generating random numbers with Python random module
In a random module, you get two methods
randrange(start, end, [steps])
to generate random numbers. The
will generate a random number greater than and equal to
and smaller than equal to
randrange(start, end, step)
method will generate a random number between start and end with the interval of specified steps.
import random #random number >=20, and <= 300 print(random.randint(20, 300)) #random number >=20, <300 and 20,30,...290 print(random.randrange(20, 300, 10))
Generating random numbers with the Python secrets module
Using the Python
method, we can generate a random number between o to n.
import secrets #random number o to 99 print(secrets.randbelow(100))
let's say you want to generate 4 digits random number for OTP in Python, for that you can use the Python
import random #4 digit opt otp = random.randint(1000, 9999) print("Your Four Digit OTP is:", otp)
Your Four Digit OTP is: 8901
Choose Random Data From the Elements
Let's say you have a Python list or any other sequence of elements, and you want to pick elements from the sequence. In that case, randomly, you can use the Python random or secrets module.
Randomly chooses or pick elements from a Python List or sequence using the
In the Python random module, we have two methods, namely
to pick random elements from the sequence. The
method picks a single random element from the sequence. and. The
pick k numbers of random elements from the sequence and return a list of k random picks.
import random cards = ["ace", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "J", "K", "Q"] #pick one print(random.choice(cards)) #pick 3 cards print(random.choices(cards, k =3))
ten ['three', 'five', 'six']
Randomly chooses or pick an element from a Python List or sequence using the secrets module
In the secrets module, we also get the choice() method to randomly select one element from a Python list or sequence.
import secrets cards = ["ace", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "J", "K", "Q"] #pick one print(secrets.choice(cards))
Selecting random elements from a sequence can be very useful. We can use it in many applications, such as generating random long secure passwords from letters.
Let's generate a 14-character-long random password in Python.
#Python program to generate random passwords
import string import secrets import random #"'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'" letters_digits = string.ascii_letters + string.digits #with random choices() passwords_random = "".join(random.choices(letters_digits, k=14) ) print("14 characters long Randomly Generated Password:", passwords_random) #with secrets choice passwords_secrets = "".join([secrets.choice(letters_digits) for _ in range(14)]) print("14 characters long Randomly Generated Password:", passwords_secrets)
14 characters long Randomly Generated Password: X6WrjhOYUmmmbI 14 characters long Randomly Generated Password: phx1opoYMj7QLg
Generate Random Floating Points Numbers
In the above example, we have only covered how to generate random Integer numbers. Let's say you want to generate random floating points or decimal points, or random numbers. Then what will we do?- the answer is simple we will use the random() method.
The random module provides a random() method that generates a random floating-point number between 0.0 and 1.0 whenever you call it.
import random print("Random Floating point number between 0.0 and 1.0 : ", random.random())
Output Random Floating point number between 0.0 and 1.0: 0.3365084727758496 From the output, you can see that the random() function only returns a randomly generated floating-point number between 0.0 to 1.0. In many cases, it might do the work for you, but there is a high chance that you want to generate a big floating-point number with fixed decimal point numbers.
To generate 1-digit floating point numbers, we will multiply the returned random() result by 10. To get a 2-digit floating-point number, will multiply the randomly generated floating-point number by 100 and so on. And to small the size of decimal points, we will round the numbers using the Python round function .
import random #random floating number num = random.random()*10000 print("Random Floating Number", round(num, 2))
Random Floating Number 6466.69
The random module also provides another method
that print a random floating number
start < = N <= end
import random #random floating number num = random.uniform(10, 10000) print("Random Floating Number", round(num, 2))
Random Floating Number 3299.03
Generate Random Data For Cryptography
Although the Python
module provides many methods to generate random data, but it is not secure and reliable, and in most cases, you will see that it returns similar random data. And when we talk about cryptography where we require such logic or modules which can generate random and unique data for us.
Luckily in Python, we have inbuilt Python standard
modules that can be used to generate random data in different formats. But in cryptography and security, you will be using the Python
module more than
, because it provides more methods to create random data.
Generate Random bytes data for Cryptographic use using Python
module, we get the
function that generates random bytes data of
size that is suitable for cryptographic use. The bytes data returned by the
function is Operating System specific.
import os size= 20 #random crypto-safe bytes data crypto_bytes = os.urandom(size) print("Random Bytes Data for Crypto: ", crypto_bytes)
Random Bytes Data for Crypto: b'^ ]l\x8b\x1c\x83m\x15\xd53f\xb3e\x14X\xfa\xfa\x08\xe6'
Generate Random bytes data for Cryptographic use using the Python
module provides more methods to generate secure random token data in different data type formats.
method returns a randomly generated integer with K random bits.
method returns a randomly generated Nbytes long Byte string token.
method returns a randomly generated Nbytes long Hexadecimal string token.
method returns a randomly generated Nbytes long Base64 encoded text.
import secrets N= 18 crypto_bytes = secrets.token_bytes(N) print("Random Secrets Token Bytes for Crypto:", crypto_bytes) crypto_rand_string = secrets.token_urlsafe(N) print("Random URL safe String for Crypto:", crypto_rand_string) crypto_hex = secrets.token_hex(N) print("Random Hexadecimal String for Crypto:", crypto_hex) crypto_int_bits = secrets.randbits(N) print("Random 18 bit Crypto Integer:",crypto_int_bits )
Random Secrets Token Bytes for Crypto: b'm\xf9j\xd7\xf0J$,e\x01yz\x07V\xe4H\xa6"' Random URL safe String for Crypto: pSizKJUs39ywa74dLCGesPU_ Random Hexadecimal String for Crypto: 96e5fb1e9db600e255ada174d030e563301b Random 18 bit Crypto Integer: 143815
In this Python tutorial, you learned how to generate random data in Python. The Python random module is a straightforward library that provides many methods to generate and play with random data. You can also use the random method to shuffle a sequence of elements, such as shuffling elements from a list, or if we talk about a real application shuffling a deck of cards .
Apart from the random module we have
modules in Python which can also be used to generate random data. The
module is generally used to generate Operating System Specific Crypto Bytes code, where we can use the secrets modules to generate secure random data.
People are also reading:
Leave a Comment on this Post