Swap First and Last Word
Swap the first and last words in Python while retaining middle-word order. Students split text, require two tokens, and rebuild the result with single spaces.
1# Take string input2s = input("Enter a string: ")34# Swap first and last word5words = s.split()6if len(words) >= 2:7 words[0], words[-1] = words[-1], words[0]8 result = " ".join(words)9 print(f"After swap: {result}")10else:11 print("Need at least 2 words")
Output
Enter a string: Hello World Programming After swap: Programming World Hello
In this one
- Swap token endpoints
- Require two words
- Preserve middle order
How it works
- 1
Split text and require at least two tokens.
- 2
Exchange words[0] and words[-1] together.
- 3
Join and print the result.
Edge cases
What if only one word is entered?
What if only one word is entered?
Need at least 2 words is printed.
Are middle words reversed?
Are middle words reversed?
No. Only the two endpoints swap.
What's going on
The code requires at least two words before assigning the endpoints together. Both original endpoint values are read before either is replaced.
With red blue green, the result is green blue red; longer inputs retain their middle tokens unchanged. join normalizes separators to single spaces. Zero or one token reaches the message branch rather than pretending a meaningful two-word swap occurred.
What if only one word is entered? Need at least 2 words is printed.
Are middle words reversed? No. Only the two endpoints swap.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why use paired assignment?
Pick an answer to check it.
Question 2
What if only one word is entered?
Pick an answer to check it.
Questions people ask
What if only one word is entered?
Need at least 2 words is printed.
Are middle words reversed?
No. Only the two endpoints swap.
Why use paired assignment?
To preserve both old endpoint values before writing.
๐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