Generating Four-Digit Random Numbers in Python for Security Applications
Random Number Generation Using randint()
The random module provides the randint() function wich generates integers within specified bounds inclusively. To create a four-digit number ranging from 1000 to 9999:
import random
security_code = random.randint(1000, 9999)
print("Generated security code:", security_code)
Alternative Approach with randrange()
Similar to randint(), the randrange() method produces pseudo-random values. How ever, its uper limit is exclusive:
import random
temporary_pin = random.randrange(1000, 10000)
print("Temporary PIN generated:", temporary_pin)
String-Based Generation Technique
A more flexible approach combines character selection with string operations. This method constructs numeric strings digit by digit:
from random import choice
import string
digit_pool = string.digits
verification_code = ''.join(choice(digit_pool) for _ in range(4))
print("Verification code created:", verification_code)
This technique offers greater control over character composition and can be easily modified for different length requirements.