How to Generate Random 4-Digit Numbers in Python?

In this tutorial, I will explain how to generate random 4-digit numbers in Python. As a Python developer developing a game project for my New York clients, I encountered a scenario where I needed to generate random 4-digit numbers. I will explain how to achieve this task efficiently with examples.

Methods

Let us see some important methods to achieve this task.

Read How to Check if a Python String Contains Only Numbers?

Use Python’s random Module

Python’s built-in random module provides several functions to generate random numbers. Let’s explore how to use it to create random 4-digit numbers.

1. Basic Random Number Generation

To generate a random 4-digit number, you can use the randint function. Here’s a simple example:

import random

def generate_random_number():
    return random.randint(1000, 9999)

print(generate_random_number())

Output:

1895

I have executed the above example code and added the screenshot below.

Generate Random 4-Digit Numbers in Python

This function generates a random integer between 1000 and 9999, inclusive. Each time you run the script, it will produce a different 4-digit number.

Check out How to Calculate the Number of Days Between Two Dates in Python?

2. Generate Multiple Random Numbers

If you need to generate a list of random 4-digit numbers, you can use a loop. Here’s how you can do it:

import random

def generate_multiple_random_numbers(count):
    random_numbers = [random.randint(1000, 9999) for _ in range(count)]
    return random_numbers

print(generate_multiple_random_numbers(5))

Output:

[8460, 6347, 3809, 7643, 7326]

I have executed the above example code and added the screenshot below.

How to Generate Random 4-Digit Numbers in Python

This script generates a list of five random 4-digit numbers. You can adjust the count parameter to generate as many numbers as you need.

Read How to Get a Week Number from Date in Python?

3. Ensure Uniqueness

In some applications, it’s crucial that the generated numbers are unique. To ensure uniqueness, you can use a set to store the numbers and check for duplicates:

import random

def generate_unique_random_numbers(count):
    random_numbers = set()
    while len(random_numbers) < count:
        random_numbers.add(random.randint(1000, 9999))
    return list(random_numbers)

print(generate_unique_random_numbers(5))

Output:

[4224, 7249, 1332, 3797, 5817]

I have executed the above example code and added the screenshot below.

Generate Random 4-Digit Numbers in Python Ensure Uniqueness

This function will generate a list of unique random 4-digit numbers. The use of a set ensures that no duplicates are added.

Read How to Subtract Number of Days from a Date in Python?

Advanced Techniques with secrets Module

For security-sensitive applications, the secrets module is recommended over the random module because it provides functions that generate cryptographically secure random numbers.

1. Use secrets to Secure Random Numbers

Here’s how you can generate a random 4-digit number using the secrets module:

import secrets

def generate_secure_random_number():
    return secrets.randbelow(9000) + 1000

print(generate_secure_random_number())

The randbelow function generates a random number between 0 and 8999, and adding 1000 ensures it’s a 4-digit number.

Check out How to Get the Day of the Week from a Date in Python?

2. Generate Multiple Secure Random Numbers

Similar to the random module, you can generate multiple secure random numbers using a loop:

import secrets

def generate_multiple_secure_random_numbers(count):
    random_numbers = [secrets.randbelow(9000) + 1000 for _ in range(count)]
    return random_numbers

print(generate_multiple_secure_random_numbers(5))

This script generates a list of secure random 4-digit numbers.

Read How to Extract Day Number of the Year from a Date in Python?

Example: Generate OTPs

One common use case for random 4-digit numbers is generating One-Time Passwords (OTPs). Here’s a practical example that simulates sending OTPs to users in the USA:

import random

def send_otp(phone_number):
    otp = random.randint(1000, 9999)
    print(f"Sending OTP {otp} to phone number {phone_number}")

# Example usage
send_otp("+1-202-555-0173")
send_otp("+1-303-555-0147")

In this example, the send_otp function generates a random 4-digit OTP and prints a message simulating sending the OTP to a user’s phone number.

Check out Difference Between Class and Instance Variables in Python

Conclusion

In this tutorial, I explained how to generate random 4-digit numbers in Python. I discussed Python's random module, basic random number generation, and generating multiple random numbers. We also discussed some advanced techniques of the secrets module with example.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.