The randrange() function in Python's random module is used to generate a random number within a specified range. It allows defining a start, stop, and an optional step value to control the selection of numbers. Unlike randint(), which includes the upper limit, randrange() excludes the stop value. Example:
Python
import random
print("0-100:", random.randrange(100))
print("50-100:", random.randrange(50, 100))
print("50-100 (step 5):", random.randrange(50, 100, 5))
Output0-100: 48
50-100: 61
50-100 (step 5): 50
Explanation: The first call picks a random number between 0 and 99. The second call selects a random number between 50 and 99. The third call chooses a random number between 50 and 99, but only from numbers that are multiples of 5 (like 50, 55, 60, etc.).
Syntax of randrange()
random.randrange(start, stop, step)
Parameter:
- start (optional): The starting number of the range. Default is 0.
- stop (required): The upper limit (exclusive) for the generated number.
- step (optional): The step size. Default is 1 and cannot be zero (raises ValueError).
Return Value: This function returns a randomly selected number from the sequence [start, start+step, start+2*step, ..., stop). The stop value is never included.
Exceptions:
- Raises ValueError if stop <= start.
- Raises ValueError if non-integer values are provided as parameters.
Examples
Example 1: Generating Even or Odd Numbers
Python
import random
print("10-50:", random.randrange(10, 50, 2))
print("11-51:", random.randrange(11, 51, 2))
Output10-50: 34
11-51: 37
Explanation:
- The first call generates a random even number within [10, 12, 14, ..., 48].
- The second call generates a random odd number within [11, 13, 15, ..., 49].
Example 2: Simulating a dice roll
Python
import random
dice_roll = random.randrange(1, 7)
print(dice_roll)
Explanation: This function randomly selects an integer between 1 and 6, simulating a dice roll.
Example 3: Random selection from a list
Python
import random
a = [10, 20, 30, 40, 50]
random_idx = random.randrange(len(a))
print(a[random_idx])
Explanation: randrange(len(a)) selects a random index from 0 to 4. The corresponding value from a is then printed.
Handling Exceptions
Case 1: Non-integer Arguments
The randrange() function does not accept float values. Instead of allowing a crash, we can handle it gracefully.
Python
import random
start, stop, step = 14.5, 100, 1 # Example invalid input
try:
if not all(isinstance(i, int) for i in [start, stop, step]):
raise TypeError("All arguments must be integers.")
print(random.randrange(start, stop, step))
except TypeError as e:
print("Error:", e)
OutputError: All arguments must be integers.
Explanation: This function ensures start, stop, and step are integers using all(isinstance(i, int) for i in [start, stop, step]). If not, it raises a TypeError with a clear message. Upon valid input, random.randrange() generates a number. A try-except block catches TypeError and displays a user-friendly message.
Case 2: Invalid Range (start >= stop)
The start value must always be less than stop. Instead of allowing an error, we can handle it gracefully by swapping values if necessary.
Python
import random
start, stop, step = 500, 100, 1 # Example invalid input
try:
if start >= stop:
raise ValueError("Start value must be less than stop value.")
print(random.randrange(start, stop, step))
except ValueError as e:
print("Error:", e)
OutputError: Start value must be less than stop value.
Explanation: This function validates that start < stop to ensure a proper range. If not, it raises a ValueError with a clear message. When valid, random.randrange() generates a number. A try-except block catches the ValueError and provides a user-friendly error message.
Practical application: Simple game simulation
Random number generation is widely used in games. Below is an example of a simple game where two players roll a dice until one reaches a score of 100.
Python
import random
p1, p2, t = 0, 0, 0 # p1: Player 1 score, p2: Player 2 score, t: Turn counter
while True:
t += 1 # Increment turn count
r1, r2 = random.randrange(1, 11), random.randrange(1, 11) # r1: Player 1 roll, r2: Player 2 roll
p1 += r1 # Add roll value to Player 1's score
p2 += r2 # Add roll value to Player 2's score
print(f"Turn {t}: P1 = {p1}, P2 = {p2}") # Display scores
if p1 >= 100: # Check if Player 1 wins
print("P1 wins!")
break
if p2 >= 100: # Check if Player 2 wins
print("P2 wins!")
break
OutputTurn 1: Player 1 = 7, Player 2 = 9
Turn 2: Player 1 = 15, Player 2 = 10
Turn 3: Player 1 = 19, Player 2 = 15
Turn 4: Player 1 = 28, Player 2 = 25
Turn 5: Player 1 = 29, Player 2 = 34
Turn 6: Player 1 ...
Explanation: In this game, both players take turns rolling a number between 1 and 10, adding it to their scores. The game continues until one player reaches 100 points and wins.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice