randint picks a random number. Quite often what you want is not a number at
all: a random card from a deck, a random name from a class list, a random
colour for the next level. If those things are already stored in a list, the
random module can pick one of them for you.
The tool is choice. Its one argument is the list to pick from:
import random
die = [1, 2, 3, 4, 5, 6]
num = random.choice(die)
print(num)
random.choice(die) picks one item from die at random, and hands it back to
be stored in num. Every item in the list has the same chance of being picked.
That program is another dice roll, written a different way. randint(1, 6)
picks a number from 1 to 6, and choice picks one of the six items in the list,
which happen to be the numbers 1 to 6.
Where choice becomes more useful than randint is with a list of text:
import random
colours = ["red", "green", "blue", "yellow"]
colour = random.choice(colours)
print("The next level is " + colour)
Nothing in there is a number, so randint could not have done this on its own.
The item that comes back is whatever was in the list: text here, so it can be
joined onto other text with a + straight away, with no str() needed.
choice looks at the list and picks something from it, but it does not take
the item out. The list has the same items afterwards as before, which also
means the same item can be picked twice in a row:
import random colours = ["red", "green", "blue", "yellow"] print(random.choice(colours)) print(random.choice(colours)) print(random.choice(colours)) print(colours)
Run it a few times. Sooner or later the same colour comes up twice, and the last line always prints all four.
A picked item can be stored in a variable, and a variable can be added to a
list with append, as in the previous chapter. Put that inside a for loop and
the program can pick several items and keep all of them:
import random
colours = ["red", "green", "blue", "yellow"]
picked = []
for count in range(3):
colour = random.choice(colours)
picked.append(colour)
print(picked)
A pair of square brackets with nothing between them, [], is an empty
list: a list with no items in it yet. picked starts that way, grows by one
item every time round the loop, and is printed once, after the loop has
finished. It has to be created before the loop: create it inside, and it is
emptied again on every repetition.
Make sure that you check for the following things:
import random is the first line of the program.choice is written after random and a full stop: random.choice(...).choice is used.choice can be joined on with + as it is; only a
number needs str().