How to Generate Random 4‑Digit Numbers in Python with randint, randrange, and More
This article explains how to use Python's built‑in random module—specifically randint() and randrange()—to generate random four‑digit numbers, and also demonstrates alternative approaches using string.digits, choice(), and join(), complete with code snippets and sample outputs.
Python provides the built‑in random module for generating random numbers, offering functions such as seed(), randrange(), randint(), choice(), choices(), and shuffle().
Using random.randint() method
The randint() function returns a random integer within a specified inclusive range. randint(range1, range2) Import the module and generate a four‑digit number by setting the range from 1000 to 9999.
import random
randomNumber = random.randint(1000, 9999)
print(randomNumber)Sample output:
Using random.randrange() method
The randrange() function works similarly to randint(), requiring a start and end value. randrange(range1, range2) Example code:
import random
randomNumber = random.randrange(1000, 9999)
print(randomNumber)Sample output:
Other methods to generate random numbers in Python
Beyond randint() and randrange(), you can create a random four‑digit string using string.digits, choice(), and join().
from random import choice
import string
numbers = string.digits
randomNumber = ''.join(choice(numbers) for _ in range(4))
print(randomNumber)Full example:
#Python小白学习交流群:153708845
from random import choice
import string
numbers = string.digits
randomNumber = ''.join(choice(numbers) for _ in range(4))
print(randomNumber)Sample output:
Summary
The article introduced Python's random module and demonstrated how to generate a random four‑digit number using randint() and randrange(). It also covered an alternative approach employing string.digits, choice(), and join(). While list comprehensions and loops can create such numbers, randint() and randrange() remain the simplest solutions.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Raymond Ops
Linux ops automation, cloud-native, Kubernetes, SRE, DevOps, Python, Golang and related tech discussions.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
