randint picks any whole number between two limits. Sometimes you want
something narrower: only even numbers, only odd numbers, only multiples of
five. The random module has a third tool for that, and you already know how
it thinks, because it works like range.
So far every program has imported the whole module and then written random.
in front of each tool. There is a second way to write the import, which brings
in one tool by name:
from random import randrange
After that line the tool is called randrange on its own, with no random.
in front of it. Both ways work. The first brings in the whole module; the
second brings in just the one tool, so it is shorter to use but nothing else
from the module is available.
Use one or the other for each tool. After from random import randrange, the
name random has not been imported at all, so random.randrange(...) fails
with a NameError. After import random, a bare randrange(...) fails in the
same way.
randrange takes the same three numbers as range: a start, a stop and a
step. It works out every value that range would count through, and picks one
of them at random.
from random import randrange
my_number = randrange(0, 10, 2)
print(my_number)
range(0, 10, 2) would count 0, 2, 4, 6, 8, so randrange(0, 10, 2) picks one
of those five numbers. It never picks an odd number, because the step jumps
over them, and it never picks 10, because the stop value is never reached.
This is the one real difference from randint. random.randint(0, 10) can
pick 10; randrange(0, 10) cannot, because like range it stops before
its stop value. randrange(0, 11) is what picks from 0 to 10.
| Code | Possible results |
|---|---|
random.randint(1, 6) |
1, 2, 3, 4, 5, 6 |
random.choice([1, 2, 3, 4, 5, 6]) |
1, 2, 3, 4, 5, 6 |
randrange(1, 7) |
1, 2, 3, 4, 5, 6 |
randrange(0, 10, 2) |
0, 2, 4, 6, 8 |
randrange(5, 30, 5) |
5, 10, 15, 20, 25 |
The first three rows are three ways of rolling the same dice. Which one to use
is mostly a matter of which reads most clearly: randint when you think in
lowest and highest, choice when the options are already in a list, and
randrange when you need a step.
from random import randrange print(randrange(5, 30, 5))
Run it a few times and check every result against the last row of the table.
Make sure that you check for the following things:
from random import randrange
with a bare randrange(...), or import random with random.randrange(...).str() before it is joined onto text with a
+.