In this tutorial, we will learn how to generate a 4-digit random number in Python. You may need to generate random numbers for various reasons, such as creating a one-time password (OTP), building a simple game, or testing purposes. We will use the built-in random module in Python for this task.
Step 1: Importing the random module
First, we need to import the random module in our Python code. To do this, use the following line:
1 |
import random |
Step 2: Generating a 4-digit random number
Next, we will use the randint() function from the random module to generate a four-digit random number. The randint() function takes two arguments: the start and end range (inclusive) of the random number. In our case, we want a random number between 1000 and 9999.
1 |
random_number = random.randint(1000, 9999) |
Step 3: Displaying the random number
Finally, we can display the generated random number using the print() function:
1 |
print("Your 4-digit random number is:", random_number) |
Full Code
1 2 3 4 |
import random random_number = random.randint(1000, 9999) print("Your 4-digit random number is:", random_number) |
Output
Your 4-digit random number is: 5823
Keep in mind that the output will vary each time you run the code since it’s generating a random number.
Conclusion
In this tutorial, we successfully learned how to generate a 4-digit random number using Python’s built-in random module. This technique can be easily adapted for other digit lengths or ranges by altering the arguments passed to the randint() function.