Find Longest Word
Choose the longest whitespace-separated word with max and key=len. Students compare word lengths rather than alphabetic values and handle a tie or empty input.
1# Take string input2s = input("Enter a string: ")34# Find longest word5words = s.split()6if len(words) > 0:7 longest = max(words, key=len)8 print(f"Longest word: {longest}")9else:10 print("No words found")
Output
Enter a string: Hello World Programming Longest word: Programming
In this one
- Compare lengths with key
- Handle tied maxima
- Guard empty collections
How it works
- 1
Split the entered text.
- 2
If nonempty, call max(words, key=len).
- 3
Print that token or the no-words message.
Edge cases
What if two words tie?
What if two words tie?
The first longest token is chosen.
What if there are no words?
What if there are no words?
No words found is printed.
What's going on
After split, max(words, key=len) chooses a token by its length. Without key=len, max would compare string ordering instead.
The nonempty check avoids max on an empty sequence. If several words share the longest length, the first encountered maximum is returned. Punctuation remains in tokens and contributes to their measured length; this program does not clean dictionary words.
What if two words tie? The first longest token is chosen.
What if there are no words? No words found is printed.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does key=len change?
Pick an answer to check it.
Question 2
What if two words tie?
Pick an answer to check it.
Questions people ask
What if two words tie?
The first longest token is chosen.
What if there are no words?
No words found is printed.
What does key=len change?
The basis of comparison to token length.
๐Related Content
- ๐
Phase 5 - Learn Concepts
Review Phase 5 concepts and explanations
- ๐
Phase 5 - Quiz
Test your Phase 5 understanding with quiz questions
- ๐ป
Phase 5 - All Practice Problems
Explore all practice problems for Phase 5
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum