October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk2 min

How to Generate Random 4-Digit Numbers in Python

Use randint for an ordinary 1000–9999 integer, secrets for security-sensitive values, and a zero-padded string when a code may begin with zero.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For an ordinary four-digit integer, use random.randint(1000, 9999). If the value is a login or verification code that must be hard to predict, use Python’s secrets module instead. And if the first digit may be zero, treat the result as a four-character string—not a four-digit integer.

Generate a random integer from 1000 to 9999

Python’s random.randint(a, b) includes both endpoints, so this returns an integer from 1000 through 9999:

import random

number = random.randint(1000, 9999)
print(number)

This is suitable for ordinary examples, games, and simulations. The Python 3.14 random documentation defines randint(a, b) as returning a value where a <= N <= b.

Generate a four-character code that can start with zero

A four-digit integer cannot begin with zero: converting 0042 to an integer produces 42. If all four positions matter, generate from 0 through 9999 and format the result as text with four digits:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import random

code = f"{random.randrange(10_000):04d}"
print(code)

The format specifier :04d pads the value with leading zeroes when needed. The result is a string, so a value such as 0042 keeps all four characters.

Use a security-focused generator for authentication codes

For an OTP, password-reset code, or other security-sensitive value, use secrets, not random. Python’s documentation warns that the pseudo-random generators in random should not be used for security purposes. The Python 3.12 secrets documentation recommends the module for cryptographically strong values and defines randbelow(n) as returning a value below the exclusive upper bound n.

For a security-sensitive four-digit integer from 1000 through 9999:

import secrets

number = secrets.randbelow(9000) + 1000
print(number)

For a four-character security code that may start with zero:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import secrets

code = f"{secrets.randbelow(10_000):04d}"
print(code)

These examples generate a value; they do not by themselves implement an authentication system. A real login or reset flow also needs appropriate controls for code expiry, attempt limits, delivery, and verification.

Choose the range that matches the result you need

Requirement Code Possible values Result type
Ordinary four-digit integer random.randint(1000, 9999) 1000–9999, inclusive Integer
Ordinary four-character code, including a leading zero f"{random.randrange(10_000):04d}" 0000–9999 String
Security-sensitive four-digit integer secrets.randbelow(9000) + 1000 1000–9999 Integer
Security-sensitive four-character code, including a leading zero f"{secrets.randbelow(10_000):04d}" 0000–9999 String
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Keep range arguments as integers

Pass integer bounds to randrange. Since Python 3.12, it no longer automatically converts non-integer arguments, such as floats, into integers; see the version notes in the official random documentation.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

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

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.