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
Mean and standard deviation versus median and IQR | AP Statistics | Khan Academy
So we have nine students who recently graduated from a small school that has a class size of nine, and they want to figure out what is the central tendency for salaries one year after graduation. They also want to have a sense of the spread around that ce…
Periodicity of algebraic models | Mathematics III | High School Math | Khan Academy
We’re told Divya is seated on a Ferris wheel at time T equals zero. The graph below shows her height H in meters T seconds after the ride starts. So at time equals zero, she looks like about two. What is this? This would be one and a half, so it looks lik…
How To Be 10x More Productive | The Ultimate Guide to Productivity
Productivity is effective movement. It’s running in the right direction for the longest distance. It’s about making the greatest progress towards your goals in the shortest amount of time. And the key to productivity can be boiled down to a simple equatio…
The CEO Who Pays Employees to De-Locate From the Bay
I haven’t started with questions from Twitter before, but I feel like they kind of covered some of the initial ones I wanted to go off with, uh-huh. So maybe we should just go with those. All right, so the first one was from Ben Thompson, and he asked fo…
Home Chandalar Home | Life Below Zero
[Music] On a clear day, you can see mountains all across the horizon. Down there, big mountains. Can’t see anything down there now. What about just getting over to the flats though? That might be a little tricky. Yeah, I can uh get over these next couple…
Calculating angle measures to verify congruence | Congruence | High school geometry | Khan Academy
We have four triangles depicted here, and they’ve told us that the triangles are not drawn to scale. We are asked which two triangles must be congruent, so pause this video and see if you can work this out on your own before we work through this together.…