Home » Tutorials » How to Generate Random Data in Python

How to Generate Random Data in Python

Generating random data can be a lot of fun and incredibly useful! Whether you’re whipping up some test data, adding a bit of randomness to your tasks, or just exploring the unpredictable side of programming, you’ll find endless possibilities. It’s amazing how a few lines of Python code can create such diverse and interesting results. Picture this: with just a click of a button, you can generate random numbers, quirky strings, or even secure cryptographic bytes. It’s like having a mini-magic trick up your sleeve, all thanks to Python!

In today’s article, we’ll explore how to generate random data in Python. Creating a graphical user interface with tkinter, you’ll be able to generate random integers, floats, strings, and more with just a click of a button. I’ll be your guide as we build a simple yet powerful application that really shows off what Python can do. So, let’s get started!

Table of Contents

Necessary Libraries

For the code to function properly, you should install the tkinter library via the terminal or your command prompt:

$ pip install tk

Imports

As usual, we gather our tools to build our program. First, we use our go-to library, tkinter, which creates a graphical user interface to make this program user-friendly. From this library, we import messagebox to display messages with our random results. Next, we import the random module, which provides many pseudo-random number functions.

We also import the os module to interact with the operating system, and the string module to easily access all the letters we’ll use for generating random strings. Finally, we import the secrets module to generate cryptographically strong random numbers.

import tkinter as tk
from tkinter import messagebox
import random
import os
import string
import secrets

Functions for Generating Random Data

Now that we have our tools ready, it’s time to create the functions that will perform the tasks we want our code to do. Without further ado, let’s jump straight into it:

generate_randint Function

For the first function, think of it like rolling a dice that gives you any number between 1 and 500 using random.randint(). This function will display the result to the user by calling the show_result() function. All of this happens at the click of a button that we will create later.

def generate_randint():
   result = random.randint(1, 500)
   show_result("Random Integer", result)

generate_randrange Function

As for this function, it will generate a random number between 0 and 500, incrementing by 5. When you trigger this function by clicking a button, it will use random.randrange() to generate a random number like 5, 10, or 15. This number will be displayed to you using the show_result() function.

def generate_randrange():
   result = random.randrange(0, 500, 5)
   show_result("Random Integer from Range", result)

generate_choice Function

If you’re indecisive about how to start your conversation, this function uses random.choice() to pick a random greeting from a list. It then calls the show_result() function to display the result for you. All you need to do is click the button that triggers it.

def generate_choice():
   result = random.choice(["hello", "hi", "welcome", "bye", "see you"])
   show_result("Random Choice", result)

random_choices Function

Are you interested in creating a mini lottery ticket? If you are, this function uses random.choices() to randomly pick 5 numbers between 0 and 1000. It then displays them for you using the show_result() function.

def generate_choices():
   result = random.choices(range(1000), k=5)
   show_result("Random Choices", result)

generate_randfloat Functions

Not much to deliberate on this. Just as the name suggests, these functions give you floating-point numbers using the random module. The first function gives you a float between 0 and 1.

def generate_randfloat_0_1():
   result = random.random()
   show_result("Random Float (0.0 - 1.0)", result)

The second function gives you a Float between 5 and 10 in a uniform range.

def generate_randfloat_5_10():
   result = random.uniform(5, 10)
   show_result("Random Float (5.0 - 10.0)", result)

shuffle_list Function

This one is pretty self-explanatory. It uses the random module to randomly shuffle a list you create and then displays the result using the show_result() function. In this case, the list consists of ten numbers from 0 to 9.

def shuffle_list():
   l = list(range(10))
   random.shuffle(l)
   show_result("Shuffled List", l)

generate_randstring Function

Now, if you wish to create a random password or just a random string of 16 letters (which you can change), then this function is for you. It uses the random module with ASCII letters to form random strings of 16 characters and displays them with the show_result() function.

def generate_randstring():
   result = ''.join(random.sample(string.ascii_letters, 16))
   show_result("Random String (16 characters)", result)

Generating Cryptographic Random Bytes

If you want to mix randomness with security, then cryptographic functions are the answer. Our first one uses the os module, specifically the operating system’s random number generator, which is very secure, to generate 16 cryptographic random bytes.

def generate_randbytes_os():
   result = os.urandom(16)
   show_result("Cryptographic Random Bytes (os.urandom)", result)

If that isn’t to your liking, you can always use secrets.token_bytes(), which is even more secure since it uses the most secure source of randomness provided by the operating system.

def generate_randbytes_secrets():
   result = secrets.token_bytes(16)
   show_result("Cryptographic Random Bytes (secrets.token_bytes)", result)

And if you want the same level of security as secrets.token_bytes() but need a base64 encoded URL-safe string, you can use secrets.token_urlsafe().

def generate_randstring_crypto():
   result = secrets.token_urlsafe(16)
   show_result("Cryptographic Random String (secrets.token_urlsafe)", result)

Also if you want to generate a random integer up to a specific bit and with the same level of security as the previous two functions, you can use the secrets.randbits() function.

def generate_randbits_crypto():
   result = secrets.randbits(16)
   show_result("Cryptographic Random Bits (16 bits)", result)

show_result Function

This is the function that all the previous functions call to display the results to you in a message box using messagebox.showinfo().

def show_result(title, result):
   messagebox.showinfo(title, f"{title}: {result}")

Defining Main Function

Now this is the part where we create our main window, set its title, and define its geometry. We also create buttons for each random-generating function and link each button to its appropriate function. Then, we add root.mainloop() to start the main event loop, ensuring that the main window keeps running and remains responsive to the user until they exit.

Finally, we ensure that this function is triggered only if this script is run directly and not imported as a module.

def main():
   root = tk.Tk()
   root.title("Random Generator - The Pycodes")
   root.geometry("500x500")


   buttons = [
       ("Generate Random Integer (1 to 500)", generate_randint),
       ("Generate Random Integer from Range (0 to 500 step 5)", generate_randrange),
       ("Generate Random Choice from List", generate_choice),
       ("Generate five Random Choices from 0 to 1000", generate_choices),
       ("Generate Random Float (0.0 - 1.0)", generate_randfloat_0_1),
       ("Generate Random Float (5.0 - 10.0)", generate_randfloat_5_10),
       ("Shuffle List (0 to 9)", shuffle_list),
       ("Generate Random String (16 characters)", generate_randstring),
       ("Generate Cryptographic Random Bytes (os.urandom)", generate_randbytes_os),
       ("Generate Cryptographic Random Bytes (secrets.token_bytes)", generate_randbytes_secrets),
       ("Generate Cryptographic Random String (secrets.token_urlsafe)", generate_randstring_crypto),
       ("Generate Cryptographic Random Bits (16 bits)", generate_randbits_crypto),
   ]


   for text, command in buttons:
       button = tk.Button(root, text=text, command=command)
       button.pack(pady=5)


   root.mainloop()


if __name__ == "__main__":
   main()

Example

I have run this code on Windows as shown below:

Also on Linux system:

Full Code

import tkinter as tk
from tkinter import messagebox
import random
import os
import string
import secrets


def generate_randint():
   result = random.randint(1, 500)
   show_result("Random Integer", result)


def generate_randrange():
   result = random.randrange(0, 500, 5)
   show_result("Random Integer from Range", result)


def generate_choice():
   result = random.choice(["hello", "hi", "welcome", "bye", "see you"])
   show_result("Random Choice", result)


def generate_choices():
   result = random.choices(range(1000), k=5)
   show_result("Random Choices", result)


def generate_randfloat_0_1():
   result = random.random()
   show_result("Random Float (0.0 - 1.0)", result)


def generate_randfloat_5_10():
   result = random.uniform(5, 10)
   show_result("Random Float (5.0 - 10.0)", result)


def shuffle_list():
   l = list(range(10))
   random.shuffle(l)
   show_result("Shuffled List", l)


def generate_randstring():
   result = ''.join(random.sample(string.ascii_letters, 16))
   show_result("Random String (16 characters)", result)


def generate_randbytes_os():
   result = os.urandom(16)
   show_result("Cryptographic Random Bytes (os.urandom)", result)


def generate_randbytes_secrets():
   result = secrets.token_bytes(16)
   show_result("Cryptographic Random Bytes (secrets.token_bytes)", result)


def generate_randstring_crypto():
   result = secrets.token_urlsafe(16)
   show_result("Cryptographic Random String (secrets.token_urlsafe)", result)


def generate_randbits_crypto():
   result = secrets.randbits(16)
   show_result("Cryptographic Random Bits (16 bits)", result)


def show_result(title, result):
   messagebox.showinfo(title, f"{title}: {result}")


def main():
   root = tk.Tk()
   root.title("Random Generator - The Pycodes")
   root.geometry("500x500")


   buttons = [
       ("Generate Random Integer (1 to 500)", generate_randint),
       ("Generate Random Integer from Range (0 to 500 step 5)", generate_randrange),
       ("Generate Random Choice from List", generate_choice),
       ("Generate five Random Choices from 0 to 1000", generate_choices),
       ("Generate Random Float (0.0 - 1.0)", generate_randfloat_0_1),
       ("Generate Random Float (5.0 - 10.0)", generate_randfloat_5_10),
       ("Shuffle List (0 to 9)", shuffle_list),
       ("Generate Random String (16 characters)", generate_randstring),
       ("Generate Cryptographic Random Bytes (os.urandom)", generate_randbytes_os),
       ("Generate Cryptographic Random Bytes (secrets.token_bytes)", generate_randbytes_secrets),
       ("Generate Cryptographic Random String (secrets.token_urlsafe)", generate_randstring_crypto),
       ("Generate Cryptographic Random Bits (16 bits)", generate_randbits_crypto),
   ]


   for text, command in buttons:
       button = tk.Button(root, text=text, command=command)
       button.pack(pady=5)


   root.mainloop()


if __name__ == "__main__":
   main()

Happy Coding!

Subscribe for Top Free Python Tutorials!

Receive the best directly.  Elevate Your Coding Journey!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
×