Validate Words That the User Guesses
00:00 Validate the Words That the User Guesses. While you won’t check the user’s guesses against the word list, you should do some validation and alert the user if they’re doing something wrong. In this section, you’ll improve the user feedback that you provide when the user makes their guesses. Currently, you are using the code seen on-screen to handle user input to improve the handling of guesses. You’ll start by refactoring this into a separate function.
Console includes an
.input() method that mirrors the
input() function but allows you to add Rich formatting to the input prompt. While you don’t take advantage of this feature, it’s nice to use
console here as well for consistency.
previous_guesses as a parameter because soon you’ll use it to check that the user isn’t repeating a guess. Before implementing any checks, though, update
main() to call the new function.
warning style that you defined earlier, you print a message to the user informing them they’ve already guessed the word. To let the user make a new guess, you call
guess_word() one more time and return that guess.
02:11 For example, the time it takes to call the function is negligible compared to the time it takes the user to enter their guess. Since all your words are five letters long, you should also check that all the guesses are five letters long.
02:33 This test follows the same structure as the previous one. You check whether there are five letters in the guess, and if not, you print a warning and let the user guess again. Finally, you can guide the users to use only the letters in the English alphabet.
You use the walrus operator inside
any() to collect an example of a character that’s invalid. If there’s an invalid letter in the user’s guess, then you report it with
console.print() as usual and give the user another attempt. The use of the walrus operator inside of
any() is powerful, but it may not be obvious why it works.
03:35 Run the game and try to provoke your code by making different kinds of errors. Do you get helpful feedback when you guess four-letter words or include numbers in your guesses? While the core game is the same as before, your program is now more solid and will guide the user if they make any mistakes. You’ve done a great job implementing your Wordle clone, but before ending this course, you’ll tweak your code here and there by smoothing out a few sharp edges.
Become a Member to join the conversation.