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

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.

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

    Create words with s.split().

  2. 2

    Check that words is nonempty.

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