Teach Your Kids To Code: A Parent-friendly Guide to Python Programming

(vip2019) #1

120 Chapter 6


want to let the computer do the repetitive work. The suit names
(diamonds, hearts, clubs, spades) are going to be repeated 13 times
each, for the 13 cards in each suit. The face values (two through
ace) are going to be repeated 4 times each, because there are 4
suits. Worse, we’re typing the word of 52 times!
When we ran into repetition before, we used loops to make the
problem easier. If we wanted to generate the whole deck of cards,
a loop would do the job nicely. But we don’t need the whole deck to
play a single hand of War: we just need two cards, the computer’s
card and the player’s. If a loop won’t help us avoid repeating all
those suits and face values, we need to break the problem down
further.
In War, each player shows one card, and the higher card wins.
So as we’ve discussed, we need just 2 cards, not 52. Let’s start
with one card. A card name consists of a face value (two through
ace) and a suit name (clubs through spades). Those look like good
possibilities for lists of strings: one list for faces and one for suits.
Instead of using a list of 52 repeated entries for each separate
card, we pick a face value at random from the list of 13 possibili-
ties, then pick a suit name at random from the 4 possible choices.
This approach should let us generate any single card in the deck.
We replace our long array cards with two much shorter arrays,
suits and faces:

suits = ["clubs", "diamonds", "hearts", "spades"]
faces = ["two", "three", "four", "five", "six", "seven", "eight", "nine",
"ten", "jack", "queen", "king", "ace"]

We reduced 52 lines of code to about 3! That’s smart program-
ming. Now let’s see how to use these two arrays to deal a card.

d aling Cardse
We already know how to use
the random.choice() function
to pick an item at random
from a list. So to deal a card,
we simply use random.choice()
to pick a face value from a
list of faces and a suit name
from a list of suits. Once
Free download pdf