How to Generate Random Four‑Digit Numbers in Python with random.randint and More
This tutorial explains how to use Python's random module—including randint, randrange, and alternative methods with string.digits and choice—to generate random four‑digit numbers, complete with code examples and sample outputs.
Python provides the built‑in random module for generating random numbers, which can be useful for passwords, security pins, and other applications requiring numbers of specific length.
Using random.randint() Method
The randint(start, end) function returns an integer between the given start and end values, inclusive.
import random
randomNumber = random.randint(1000, 9999)
print(randomNumber)Running this code prints a random four‑digit number each time.
Using random.randrange() Method
The randrange(start, end) function works similarly to randint, returning a random integer from start (inclusive) to end (exclusive).
import random
randomNumber = random.randrange(1000, 9999)
print(randomNumber)Each execution also yields a random four‑digit number.
Other Ways to Generate Random Numbers in Python
Beyond randint and randrange, you can combine the string module, random.choice, and a for loop to build a random four‑digit string.
from random import choice
import string
numbers = string.digits
randomNumber = ''.join(choice(numbers) for _ in range(4))
print(randomNumber)Summary
This article introduced Python's random module and demonstrated how to generate random four‑digit numbers using randint, randrange, and a combination of string.digits, choice, and join. While list comprehensions and loops are possible, randint and randrange remain the simplest approaches.
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.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
