Logic Building
# Take string input
s = input("Enter a string: ")
# Swap first and last word
words = s.split()
if len(words) >= 2:
words[0], words[-1] = words[-1], words[0]
result = " ".join(words)
print(f"After swap: {result}")
else:
print("Need at least 2 words")Output
Enter a string: Hello World Programming After swap: Programming World Hello
Swap first and last elements of word list.
Key Concepts:
- Split into words
- Swap words[0] and words[-1]
- Join back