![]() |
VOOZH | about |
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:
0-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.).
random.randrange(start, stop, step)
Parameter:
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:
Example 1: Generating Even or Odd Numbers
10-50: 34 11-51: 37
Explanation:
Example 2: Simulating a dice roll
5
Explanation: This function randomly selects an integer between 1 and 6, simulating a dice roll.
Example 3: Random selection from a list
10
Explanation: randrange(len(a)) selects a random index from 0 to 4. The corresponding value from a is then printed.
Case 1: Non-integer Arguments
The randrange() function does not accept float values. Instead of allowing a crash, we can handle it gracefully.
Error: 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.
Error: 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.
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.
Turn 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.