Reputation: 427
Codes:
def get_wordlen():
wordfamily_lst = []
while True:
try:
word_len = int(input('\nPlease enter length of the word you wish to guess: '))
input_File = open('dic.txt', 'r').read().split()
for word in input_File:
if len(word) == word_len:
wordfamily_lst.append(word)
else:
print("Sorry, there's no word of that length")
continue
except ValueError:
print('Please enter a numeric value for word length')
continue
return word_len, wordfamily_lst
wordlen, wordfamilylst = get_wordlen()
print(wordlen,wordfamilylst)
How can i modify my "else" statement to safeguard against user input of word length that the txt. file does not contain. Right now, my codes will display the print statement for EVERY word that doesn't match with the user input of word length.
I'd like just one print statement and loop back to the top of the while loop.
Please give me some suggestions.
Upvotes: 0
Views: 46
Reputation: 12092
You could modify your try
block as:
word_len = int(input('\nPlease enter length of the word you wish to guess: '))
input_File = open('dic.txt', 'r').read().split()
wordfamily_lst = []
for word in input_File:
if len(word) == word_len:
wordfamily_lst.append(word)
if not wordfamily_lst:
print("Sorry, there's no word of that length")
continue
for word in input_File:
will execute for all words in the file
appending the word to wordfamily_lst
only if the lengths match.wordfamily_lst = []
inside the while
block, the if not wordfamily_lst:
will make sure the error is
printed only if the input word is not present in the file.On a related note, it would be a good idea to move the code to read the file outside the while True:
block, read all the words in the file into a list once and compare the user input with this new list.
To summarize, this is what I mean:
def get_wordlen():
input_file_words = open('dic.txt', 'r').read().split()
while True:
try:
word_len = int(input('\nPlease enter length of the word you wish to guess: '))
wordfamily_lst = []
for word in input_file_words:
if len(word) == word_len:
wordfamily_lst.append(word)
if not wordfamily_lst:
print("Sorry, there's no word of that length")
continue
except ValueError:
print('Please enter a numeric value for word length')
continue
return word_len, wordfamily_lst
wordlen, wordfamilylst = get_wordlen()
print(wordlen,wordfamilylst)
Upvotes: 1