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
randommodule 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.
<code>randint(range1, range2)</code>Import the module and generate a four‑digit number by setting the range from 1000 to 9999.
<code>import random
randomNumber = random.randint(1000, 9999)
print(randomNumber)</code>Sample output:
Using random.randrange() method
The
randrange()function works similarly to
randint(), requiring a start and end value.
<code>randrange(range1, range2)</code>Example code:
<code>import random
randomNumber = random.randrange(1000, 9999)
print(randomNumber)</code>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().
<code>from random import choice
import string
numbers = string.digits
randomNumber = ''.join(choice(numbers) for _ in range(4))
print(randomNumber)</code>Full example:
<code>#Python小白学习交流群:153708845
from random import choice
import string
numbers = string.digits
randomNumber = ''.join(choice(numbers) for _ in range(4))
print(randomNumber)</code>Sample output:
Summary
The article introduced Python's
randommodule 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.
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.