Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

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.

00:36 What’s the meaning of 5 and 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.

00:48 But if you leave the code untouched for a few days, it may not be obvious when you come back to it. Another problem with magic values is that they’re hard to change.

00:58 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:14 A good practice is to replace magic values with properly named constants. For example, you can define NUM_LETTERS and then replace all occurrences of 5 with it.

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:41 Add a few descriptive constants to the top of the file.

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.

03:10 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.