yego.me
💡 Stop wasting time. Read Youtube instead of watch. Download Chrome Extension

Dealing cards with functions | Intro to CS - Python | Khan Academy


4m read
·Nov 10, 2024

Let's design a program with functions and nested function calls. We want to build a program that lets the user play several different car games. That means every game is going to need to share functionality for dealing a deck of playing cards.

The first thing that comes to mind is that I'll probably want a function that can draw a random card from the deck. I'm thinking I probably want to represent a card as a string, so this might return something like "Queen of Hearts." For now, I'm going to go ahead and stick that in as a placeholder return value.

The other task I can see wanting to perform over and over again is drawing a hand of cards. Different games use different hand sizes, so I'll want this to be generalizable. The function should take, as a parameter, the number of cards in the hand.

Okay, so how should this function work? I guess really what I want is to draw a number of cards equal to that parameter. Maybe I accumulate all of those card strings into one giant string and then return that at the end. That sounds like a good use case for a loop. On each iteration, I draw a card and then I concatenate that card to our hand.

Before we get ahead of ourselves, let's test out what we did so far by calling draw hand. To be safe, let's test it out with a few different arguments.

Oh, okay, um, that's a little hard to read. What if instead I put each card on a separate line? In Python, we can achieve this with a new line character, which is just a backslash followed by "n." Instead of displaying this as it appears, Python interprets this essentially as us hitting the enter key.

So now with my hand nicely formatted, I feel confident that my draw hand function works. But I don't want my hand to be full of Queens every time, so it's time to go back in and fill in our draw card function. A playing card consists of two pieces: the suit and the rank.

To draw a random card, then, I want to pick a random suit and random rank, which sounds like two different tasks, which means two different functions. Let's start out with the suit, since that only has four options, and we'll import the random module at the top of the file.

Okay, well, we want this function to return either hearts, diamonds, spades, or clubs with equal likelihood. So we'll generate a random number between 1 and 4 and based on that number choose which suit to return. Then we can go back to the draw card function and replace that hardcoded "hearts" with a call to get suit.

When I run those draw hand function calls now, I get all different kinds of Queens. The last thing we need to add is a get rank function. A playing card can have a rank of Ace, 2 through 10, or Jack, Queen, King. That means in total there are 13 possible ranks, so we'll generate a number between 1 and 13.

If we get one, we'll return the rank Ace; if we get 11, we'll return Jack; if we get 12, Queen; and 13, King. Any other rank, like 8, is just represented by its number, so we can return num. Now, just like before, let's go back to draw a card and call get rank.

What does this stack trace mean? When we read stack traces that involve function calls, we generally want to focus on the bottom because that is what will tell us what the actual error is and what line it came from. The rest of the stack trace just tells us the path of execution the computer took to reach that line.

So it started by executing draw hand, which then called draw a card, which then had the error. This type error tells us that we're adding an integer and a string, so get rank must be returning an integer. Somehow these cases are definitely returning a string, but down here when we return num, num is an integer.

As a general rule, a function should be consistent about which data type it returns. Always that way, callers can know what to expect. So since get rank needs to return a string in the Ace, Jack, Queen, King case, we also want to cast num to a string before we return it.

There's one last feature we want to add. Some of our card games don't use face cards, that is, Ace, Jack, Queen, King, because face cards can either be enabled or disabled. We can support this option with a Boolean parameter. If we don't want face cards, we can just generate a random number between 2 and 10 instead. That way we're excluding the options 1, 11, 12, and 13.

Now when I call get rank inside draw a card, I'll need to pass that parameter. But how do I know if it should be true or false? Well, I don't know. I want to let the caller decide, so draw a card will also take that parameter and pass it through to get rank, and then that extends to draw hand as well.

Oops, and now I need to update my calls to draw hand to take in that extra argument. Now that it's all working, what are the limitations of this approach? Well, the deck I modeled here isn't actually hateful. It's possible my hand has two Ace of Spades.

Depending on our use case, this might actually be a feature because some games use multiple decks or don't want players to count cards. But in other games where the rules strictly assume exactly one of each card, this might be a bug. For this collection of games, I actually think the simplification is pretty nice, but it might not be for someone else's use case.

More Articles

View All
To, two, and too | Frequently confused words | Usage | Grammar
Hello grammarians! Today we’re going to talk about the confusion that happens between these three homophones: these three words that sound exactly the same. The preposition “to,” the number “two,” and the adverb “too.” Now, these words all sound very sim…
Warm up to the second partial derivative test
So, in single variable calculus, if you have a function f of x and you want to find the maximum or the minimum of this function, what you do is you find its derivative and you set that equal to zero. Graphically, this has the interpretation that, you know…
Java Lesson 6
Hey guys, this is Maids in1 with Java lesson six. In this Java lesson, we’re going to be learning a few new things that are majorly important concepts that I haven’t really brought through to you guys. The first one of these concepts is methods, voids, o…
15 Signs You’re Pre-Rich
Some of you aren’t broke, right? You’re just on the way to becoming rich. Let’s call you pre-rich. Your time hasn’t come yet, but you might share some of these early signs that one day, probably soon, your reality will match your potential. Here are 15 si…
Why your $1 is REALLY worth $5 (Real Estate Investing Mind Trick)
This is also why when you’re investing in real estate, how you should look at every one dollar is actually being worth five dollars. Because this is how much it’s actually truly worth. So this is something I catch myself doing all the time and I thought I…
Gods, Monotheism, and Ideologies All Failed. But the Human Brain Could Still Succeed. | Joscha Bach
JOSCHA BACH: I think that religion probably got us from the first million individuals—and we had been at a million individuals for a very long time in history—to the first one hundred million. And then this monotheistic religion, we got to something like …