randint() is a function from Python’s built-in random module. It generates a random integer between two given integer values. The returned number includes both the starting and ending values of the range. It is commonly used in games, simulations, testing and anywhere random integer selection is required.
Example: This example generates a random number between 1 and 5.
import random
n = random.randint(1, 5)
print(n)
Output
2
Explanation: random.randint(1, 5) returns a random integer from 1 to 5 (both included).
Syntax
randint(start, end)
Parameters:
- start: Integer value where the range begins.
- end: Integer value where the range ends.
Both parameters must be integers.
Examples
Example 1: This example generates a random number between -5 and -1. It demonstrates that randint() also works with negative integers.
import random
r = random.randint(-5, -1)
print(r)
Output
-2
Explanation: random.randint(-5, -1) returns a random integer from -5 to -1, including both endpoints.
Example 2: This program generates five random numbers between 1 and 100. It uses a loop to call randint() multiple times.
import random
for _ in range(5):
print(random.randint(1, 100))
Output
31 90 55 97 56
Explanation: random.randint(1, 100) is executed inside the for loop, producing a new random integer in each iteration.
Example 3: This program generates a 4-digit One-Time Password (OTP). Such random numbers are commonly used in login verification systems.
import random
otp = random.randint(1000, 9999)
print(otp)
Output
5497