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

(vip2019) #1
Random Fun and Games: Go Ahead, Take a Chance! 121

we have a random face and a random suit, all we do to complete a
card name is add the word of between them (two of diamonds, for
example).
Notice that we might deal the same card twice or more in a
row using random.choice() this way. We’re not forcing the program to
check whether a card has already been dealt, so you might get two
aces of spades in a row, for example. The computer’s not cheating;
we’re just not telling it to deal from a single deck. It’s like this pro-
gram is dealing cards from an infinite deck, so it can keep dealing
forever without running out.


import random
suits = ["clubs", "diamonds", "hearts", "spades"]
faces = ["two", "three", "four", "five", "six", "seven", "eight", "nine",
"ten", "jack", "queen", "king", "ace"]
my_face = random.choice(faces)
my_suit = random.choice(suits)
print("I have the", my_face, "of", my_suit)


If you try running this code, you’ll get a new, random card
every time. To deal a second card, you’d use similar code, but you’d
store the random choices in variables called your_face and your_suit.
You’d change the print statement so it printed the name of this new
card. Now we’re getting closer to our game of War, but we need
some way to compare the computer’s card and the user’s card to
see who wins.


Counting Cards


There’s a reason we listed face card values in ascending order,
from two through ace. We want the cards’ faces list to be ordered
by value from lowest to highest so that we can compare cards
against each other and see which card in any pair has the higher
value. It’s important to determine which of two cards is higher,
since in War the higher card wins each hand.


Finding an Item in a List


Fortunately, because of the way lists and arrays work in Python, we
can determine where a value occurs in a list, and we can use that
information to decide whether one card is higher than another. The
position number of an item in a list or array is called the index of
that item. We usually refer to each item in an array by its index.

Free download pdf