Add Validation and User Feedback
Add Validation and User Feedback. In the previous part of the course, you added Rich and rewrote your game to use color for a better user experience. In this step, you’ll make your game more user-friendly by adding features that can guide your users if they do something unexpected. In theory, you can use any text file as a word list, but if that word list doesn’t contain any five-letter words, then
get_random_word() will fail. But what message will your users see?
You are seeing a traceback and an
IndexError. Without any other content, your users may not realize that the problem is in the word list. It’s hard to recover from not having any valid words in the word list, but you can at least provide a more explicit and actionable error message.
use the walrus operator (
:=) to create the list of valid words and check that it contains at least one word. When you use the walrus operator, you are writing an assignment expression, which does the assignment as part of an expression. In this case, you assign the list of words to
words as before. However, you are now immediately using the list in the
if test to check that it’s not empty. If the list is empty, then you print a warning in the
else clause, explicitly describing the problem.
Now you are shielding your users from seeing the traceback. Instead, you provide actionable feedback that they can use to fix the problem. Note also that you add
style="warning" to the call to
02:54 You could require that the guess is also in your existing word list. However, if you’re playing with a limited word list, this can get frustrating for users, as they end up needing to first figure out which words are actually in the word list.
03:08 A better option might be to use a second comprehensive word list when checking if a guess is valid. The most important part is that any reasonable word should be considered as valid. Without a broad dictionary available, it’s probably a better user experience to allow any combination of five letters.
03:26 In this course, you won’t tackle adding a second such word list for validating guesses, but feel free to give it a go. It’s a good exercise to try. In the next section of the course, you’ll look at validation of the user’s guesses.
Become a Member to join the conversation.