Print Last Word
Print the last whitespace-separated word with Python. Students combine split, an empty-input guard, and negative indexing while retaining attached punctuation.
1# Take string input2s = input("Enter a string: ")34# Get last word5words = s.split()6if len(words) > 0:7 print(f"Last word: {words[-1]}")8else:9 print("No words found")
Output
Enter a string: Hello World Programming Last word: Programming
In this one
- Use negative token indexes
- Ignore trailing separators
- Guard an empty token list
How it works
- 1
Split s into words.
- 2
If any token exists, select words[-1].
- 3
Otherwise print the no-words message.
Edge cases
What happens for an empty response?
What happens for an empty response?
No words found is printed.
Does one word work?
Does one word work?
Yes. It is both the first and last token.
What's going on
words = s.split() drops extra whitespace and produces a list of tokens. words[-1] selects its last entry only after checking it exists.
For red blue, the result is blue. Trailing spaces do not produce an extra empty token. This is token selection rather than character selection, so the last word can contain many characters and attached punctuation.
What happens for an empty response? No words found is printed.
Does one word work? Yes. It is both the first and last token.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does words[-1] select?
Pick an answer to check it.
Question 2
What happens for an empty response?
Pick an answer to check it.
Questions people ask
What happens for an empty response?
No words found is printed.
Does one word work?
Yes. It is both the first and last token.
What does words[-1] select?
The final token.
๐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