Generate Random 4 Digit Number in Python: Easy Guide
In this article
To generate a random 4-digit number in Python, use the random.randint(1000, 9999) function from the built-in random module. This ensures the resulting integer is always between 1,000 and 9,999 inclusive, guaranteeing exactly four digits. For cases where you need a 4-digit string that can start with zero (like a PIN), use random.choices or f-string formatting to preserve leading zeros.
What You'll Need
- A computer with Python installed (Python 3.x is recommended).
- A text editor or Integrated Development Environment (IDE) such as VS Code, PyCharm, or even a simple IDLE shell.
- Basic familiarity with how to run a Python script via the terminal or command prompt.
Step-by-Step
- Import the Random Module: Python does not load the random functionality by default to save memory. You must first import the
randommodule at the top of your script. Typeimport randomand press enter or save it in your .py file. This module contains several functions for generating pseudo-random numbers based on the Mersenne Twister algorithm. - Choose Your Logic: Integer vs. String: Decide if you need a mathematical number or a security-style code. If you need a number for a calculation, an integer is best. If you need a 4-digit PIN (where 0021 is valid), you must treat the output as a string.
- Generate a Strict 4-Digit Integer: To ensure the number is always four digits and never starts with zero, use the
randintfunction. Write the following line:number = random.randint(1000, 9999). Therandint(a, b)function returns a random integer N such that a <= N ≤ b. By setting the lower bound to 1000, you prevent the code from returning 1, 2, or 3-digit numbers. - Generate a 4-Digit PIN (with leading zeros): If your project requires a code that can be "0521",
randint(1000, 9999)will not work because integers cannot have leading zeros. Instead, userandom.randint(0, 9999)and format it. Write:pin = f"{random.randint(0, 9999):04d}". The:04dpart tells Python to format the integer as a decimal and pad it with zeros until it is 4 characters long. - Alternative Method Using random.choices: For a more manual approach to string generation, you can pick four individual digits. Write:
digits = "0123456789"followed bypin = "".join(random.choices(digits, k=4)). This method treats each position in the 4-digit sequence as an independent random choice from the string of available numbers. - Print and Verify the Result: To see your generated number, use the print function. Write
print(number)orprint(pin). Run your script multiple times to ensure the output varies and always adheres to the 4-digit constraint.
Common Mistakes
One of the most frequent errors is using random.randint(0, 9999) and expecting it to always produce four digits. If the random generator picks the number 42, the output will be 42, not 0042. This results in a 2-digit number, which can crash systems expecting a fixed-length input. Always use string formatting or a minimum bound of 1000 to avoid this.
Another common mistake is forgetting to import the random module. Beginners often try to call randint() directly, which results in a NameError: name 'randint' is not defined. You must either use import random and call random.randint(), or use from random import randint to call the function directly.
Some developers use random.random() and multiply it by 9999. This returns a floating-point number (a decimal), not an integer. While you can wrap this in int(), it is unnecessarily complex and can lead to off-by-one errors depending on how you handle the rounding and the upper boundary.
Tips
If you are generating these numbers for security purposes—such as password resets, temporary tokens, or encryption keys—do not use the random module. The random module is pseudo-random, meaning it is deterministic and could potentially be predicted by a sophisticated attacker. Instead, use the secrets module, which is designed for cryptographically strong random numbers. Replace random.randint(1000, 9999) with secrets.randbelow(9000) + 1000.
To make your code more reusable, wrap the logic in a function. For example, creating a function called generate_otp() allows you to call the logic anywhere in your application without rewriting the bounds and formatting logic every time. This ensures consistency across your entire codebase.
When working with large datasets or generating thousands of random numbers in a loop, consider using random.sample() or NumPy's random.randint() for significantly better performance. The standard library is fine for a few numbers, but NumPy is optimized for vectorization and speed.
Troubleshooting
If your code is producing the same "random" number every time you restart the program, check if you have manually set a seed using random.seed(). The seed initializes the random number generator; if the seed is the same, the sequence of numbers generated will be identical. Remove any random.seed(x) lines to allow Python to use the system time as the default seed.
If you encounter a TypeError, ensure you are passing integers to the randint function. Passing a string (e.g., random.randint("1000", "9999")) will cause the program to fail. The arguments must be whole numbers.
If the output is not exactly 4 digits, double-check your range. If you used random.randint(100, 9999), you will occasionally get 3-digit numbers. Ensure the lower bound is exactly 1000 for integers, or use the :04d formatting for strings to ensure leading zeros are preserved.
Frequently Asked Questions
Can I generate a 4-digit number without repeating any digits?
Yes. Instead of randint, use random.sample("0123456789", 4). This picks four unique digits from the string. You can then use "".join() to turn the resulting list into a single string.
What is the difference between random.randint and random.randrange?
randint(a, b) includes both the start (a) and the end (b) values. randrange(a, b) includes the start value but excludes the end value. To get a number up to 9999 using randrange, you would need to use random.randrange(1000, 10000).
How do I ensure the number doesn't start with zero?
The simplest way is to set the minimum value of your range to 1000. By using random.randint(1000, 9999), the smallest possible result is 1000, which guarantees the first digit is at least 1.
Is the random module thread-safe?
Yes, the random module functions are thread-safe. However, if you are using a shared random state across multiple threads and require absolute predictability for testing, you should create separate instances of random.Random() for each thread.
How can I generate a list of ten 4-digit numbers at once?
The most efficient way is using a list comprehension: [random.randint(1000, 9999) for _ in range(10)]. This creates a list by executing the randint function ten times in a single line of code.