Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

BeginnerPhase 5 - Category 3: Word OperationsExample 2 of 10
print-last-word.py
1# Take string input
2s = input("Enter a string: ")
3
4# Get last word
5words = 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. 1

    Split s into words.

  2. 2

    If any token exists, select words[-1].

  3. 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.