Print First Word
Print the first whitespace-separated word safely with Python. Students use split before indexing and handle blank or space-only responses without an IndexError.
1# Take string input2s = input("Enter a string: ")34# Get first word5words = s.split()6if len(words) > 0:7 print(f"First word: {words[0]}")8else:9 print("No words found")
Output
Enter a string: Hello World Programming First word: Hello
In this one
- Split before indexing
- Discard empty whitespace pieces
- Guard the first token
How it works
- 1
Create words with s.split().
- 2
Check that words is nonempty.
- 3
Print words[0] or No words found.
Edge cases
What does only whitespace produce?
What does only whitespace produce?
No words found.
Are leading spaces kept in the first word?
Are leading spaces kept in the first word?
No. split discards separating whitespace.
What's going on
split without arguments creates nonempty tokens separated by whitespace. The length check ensures there is at least one before words[0] is used.
Leading spaces do not become an empty first word. For red blue, the selected token is red. Punctuation remains attached, so hello, keeps its comma. Blank and whitespace-only responses take the No words found branch.
What does only whitespace produce? No words found.
Are leading spaces kept in the first word? No. split discards separating whitespace.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which index selects the first token?
Pick an answer to check it.
Question 2
What does only whitespace produce?
Pick an answer to check it.
Questions people ask
What does only whitespace produce?
No words found.
Are leading spaces kept in the first word?
No. split discards separating whitespace.
Which index selects the first token?
0.
๐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