Clean Up the Game and Your Code
00:00 Clean Up the Game and Your Code. In the previous sections of the course, you improved the user experience by adding some messages that help the user if they do anything wrong. In this final step, you’ll add one more feature that can help the users, namely a list of all the letters and their status. But first, you’ll do some cleanup to make for more readable, maintainable dode.
00:24 Magic values usually make your code less readable. A magic value is a value, typically a number, that appears in your program without any context. As an example, consider the code seen on-screen.
What’s the meaning of
6 here? As you’re currently deeply immersed in your game, you may immediately point out that five is the number of letters in a word, and six refers to the number of guesses you get.
Let’s say you want to change the game a little, and guess at seven-letter words. Then you’d need to replace all instances of
5 that describe the number of letters with
7. This is both cumbersome and error prone, particularly if you have the same number referring to different things.
01:26 But note that Python doesn’t have any special support for constants. Technically, a constant is just a variable that doesn’t change its value, but it’s a convention in Python to use capital letters for the names of variables that are supposed to be constant.
01:56 With these in place, you can start to replace your magic values with these constants. On-screen, you can see the same line of code twice. Which one will be easy to understand when you come back to the code in a month’s time to make some changes?
02:11 The constants help you understand what the code is doing. Go ahead and add the constants throughout the code. On-screen, you’ll see the replacements being made, but it’s a good exercise to run through the code independently to see where you would replace them.
One way to check if you’ve replaced all occurrences of
5 is to change the value of
NUM_LETTERS. Does the program still work If you get eight guesses to figure out a six letter word? If not, then you’ve missed an occurrence. In the next section of the course, you’ll make some final changes to the game to improve the user experience.
Become a Member to join the conversation.