π Step 6: Define get_player_guess function
- This function opens the file
words.txtand reads all the words into a list, where each word is stripped of whitespace and converted to lowercase.
- The function then repeatedly prompts the user to enter a guess using a
while Trueloop. The user input should also be converted to lowercase.
π Note
- The words from the file and the userβs input are converted to lowercase to ensure consistency when comparing values during validation.
- This prevents mismatches (e.g., βHElloβ vs βhelloβ), allowing valid words to be recognised regardless of how the user types them.
- The guess is validated using the following conditions:
- The guess must be exactly 5 letters long
- The guess must contain only alphabetic characters
- The guess must exist in the list of valid words
- If the guess does not meet any of the conditions, print an appropriate error message and the user is prompted again.
- Once a valid guess is entered, the function returns the guess in lowercase.
π‘ Hint
- You need to read words from a file called
words.txt. Think about how to open a file safely in Python.
Note: when you open a file you need to make sure to close it.
βΉοΈ
- You can use a
with open(...)statement so the file is automatically closed after reading.
- Once the file is open, you can loop through each line in the file to access the words.
βΉοΈ
- Words may include extra whitespace or newline characters. Use
.strip()to clean each word
- Convert each word to lowercase using
.lower()
- Store the cleaned words in a list using a list comprehension
βΉοΈ
- You can chain methods/operations as long as each method/operation works on the object type returned by the previous one:
"hello world".split()[0].upper():.split()works on str,"hello world", returns a list["hello", "world"]β[0]works on list, returns a str,"hello"β.upper()works on str, returns str
- Basic list comprehension format:
new_list = [expression for item in iterable]
- To check if the number of letters is not 5 β
len(...) != 5 - To check if the guess is not alphabetic β
.isalpha() - To check if the guess is not a valid word β
not in
β Checker
Define get_player_guess function
Type or paste your code and run.