Write a function longest_word that asks the user for words and returns the longest word entered by the user. It should stop when the user hits return without typing a word. If multiple words have the same maximum length, return the first word entered by the user. If the user quits before entering any words, return “No words were entered”. This function should use a searching loop. (Hint: remember that the len function returns the length of a string.)
def longest_word():
word = input("enter a word")
if word == "":
return "No words were entered"
max = 0
while len(word) > max :
max = len(word)
new_word = input("enter a word")
if len(new_word) <= len(word):
print(word)
else:
print(new_word)
longest_word()
I understand that I need to iterate the while loop until the user enters without typing any words, but I do not know how to write the corresponding code.
CodePudding user response:
The logic of your code had some flaws.
- You need to run the while loop until the input is
""
or an empty string and thelen(word)>max
needs to be inside an if statement. This is because the input value decides whether to break the loop or continue it, the difference in lengths just determines the result. - The returned word should be the longest one(only). But the block:
if len(new_word) <= len(word):
print(word)
else:
print(new_word)
Prints every entered word that is longer than the previous one. 3. You need to change the value of the previous word or the longest word every time a longer word is entered so that it is updated, not just the value of the length.
The code might look like:
def longest_word():
word = input("enter a word")
if word == "":
return "No words were entered"
max = 0 # This variable is not exactly required
longest = word # this variable stores the longest word(currently)
new_word = None # This assignment is for checking for empty strings
while new_word != "" :
max = len(word)
new_word = input("enter a word")
if len(new_word) >= len(longest): # If the entered word is longer, change
# value of the longest word
longest = new_word
print(longest) # Print the longest word.
longest_word()
This is not necessary but avoid naming variables the same as keywords as it often causes a confusion
CodePudding user response:
Some key points of what this function needs to do:
- It needs to
return
the longest word, notprint
it. - It needs to keep track of the longest word seen so far (so it can
return
it when it's done). Keeping track of the length of the longest word is not sufficient.
Here's how I might write it:
def longest_word():
longest = ""
while True:
word = input("enter a word")
if not word:
return longest or "No words were entered"
if len(word) > len(longest):
longest = word
Note that the return
line immediately ends the loop once no word
is entered, and the or
statement handles the case where nothing was entered prior to that point.
The remaining if
statement ensures that longest
is the longest word seen so far.