Python Coding Exercise #26: Random Number Between Two Numbers
Part of the series Python Practice Exercise — part 26
Before you start: Know input() and int() · Know what a module is
The question
Write a program that enters two numbers and generates a random number between those two numbers. Use the
randintfunction from therandommodule.
Because the answer is random, it changes every time you run the program. Here are two example runs (yours will print different numbers):
Number 1: 1
Number 2: 10
7
Number 1: 1
Number 2: 10
3
My Solution
import random
number1 = int(input("Number 1: "))
number2 = int(input("Number 2: "))
final_number = random.randint(number1, number2)
print(final_number)
How My Solution Works
1. Import the random module
import random
The random module is a collection of tools for generating random values. import random brings in the whole module, and you use its tools by writing random. before the name, as in random.randint(...). (Another module, math, was used the same way in Exercise #22.)
You can also import just the function you need:
from random import randint
final_number = randint(number1, number2)
It does the same job. With this style, you call randint by its plain name, without random. in front.
2. Read the two limits
int(input(...)) is used twice, so each answer is converted to a whole number. These are the lower and upper limits.
3. Pick a random number
random.randint(number1, number2) returns a random integer from number1 to number2. The result is stored in final_number and printed.
Both ends are included
An important detail: randint can return either end of the range. random.randint(1, 6) can give 1, 2, 3, 4, 5 or 6, just like rolling a dice. Generating 10,000 numbers with randint(1, 6) produces all six values from 1 to 6, including both ends.
This is different from range() (see Built-in Functions in Python) and from the similar function randrange(), which stop before the last number:
| Function | Example | Possible results |
|---|---|---|
random.randint(1, 6) | includes both ends | 1, 2, 3, 4, 5, 6 |
random.randrange(1, 6) | stops before 6 | 1, 2, 3, 4, 5 |
If the two numbers are the same, there is only one choice, so randint(7, 7) always gives 7. Negative limits work too: randint(-5, 5) returns a number from -5 to 5.
Things to notice
The numbers must be in order. randint expects the smaller number first. If the user types the larger one first, the program stops with an error:
Number 1: 10
Number 2: 1
ValueError: empty range in randint(10, 1)
(The exact wording of this message differs slightly between Python versions, but it’s always a ValueError.)
You can make the program work whichever order the user types the numbers in, using min() and max() from Exercise #23:
import random
number1 = int(input("Number 1: "))
number2 = int(input("Number 2: "))
final_number = random.randint(min(number1, number2), max(number1, number2))
print(final_number)
Now typing 10 and then 1 works exactly like typing 1 and then 10. The exercise doesn’t ask for this, but it makes the program friendlier.
The numbers aren’t truly random. Python generates pseudo-random numbers, which come from a formula that looks random. That’s why you can make them repeatable by setting a seed before generating. Starting from the same seed gives the same sequence every time, which is handy for testing:
import random
random.seed(42)
first = [random.randint(1, 100) for _ in range(5)]
random.seed(42)
second = [random.randint(1, 100) for _ in range(5)]
print(first == second) # True
Don’t name your own file random.py. If a file in your project is called random.py, Python imports that instead of its own random module, and import random stops working as expected. The same goes for a file called math.py.
Other useful tools in the random module
| Function | What it does |
|---|---|
random.randint(a, b) | a random whole number from a to b, including both |
random.randrange(a, b) | a random whole number from a up to, but not including, b |
random.random() | a random decimal number from 0 up to, but not including, 1 |
random.uniform(a, b) | a random decimal number between a and b |
Key takeaways
- The
randommodule generates random values.import randomlets you use it, andfrom random import randintimports just one function. random.randint(a, b)returns a whole number fromatoband includes both ends.randrange(a, b)stops beforeb, likerange().randintneeds the smaller number first. Otherwise it raises aValueError. Usemin()andmax()to make the order not matter.- Python’s random numbers are pseudo-random. A seed makes them repeatable.
- Don’t give your own files the same name as a Python module.
✦ This is part of my Python Practice Exercise series, where I work through exercises while learning Python and explain each answer in plain language. ✦
Practice Source: This exercise is taken from Ultimate Python Programming: Learn Python with 650+ Programs, 900+ Practice Questions, and 5 Projects by Deepali Srivastava, published by BPB Publications. I’m working through the exercises as part of my Python learning journey and documenting my answers and explanations here.