Q.Identify the correct output of the following code snippet: game="Olympic2024" print(game.index("C")) (A) 0 (B) 6 (C) -1 (D) ValueError
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →The index() method searches for the first occurrence of a substring and returns its position (0-indexed). Since "C" does not exist in "Olympic2024", Python raises a ValueError.
Why index() behaves this way
The index() method in Python strings searches for the first occurrence of a substring and returns its zero-based position. The crucial detail: if the substring is not found, index() does not return -1 or 0 — it raises a ValueError exception and halts execution.
This is different from the find() method, which returns -1 when the substring is absent. The designers of Python made index() strict: if you ask for the position of something that doesn't exist, that's an error condition worth stopping for.
Step-by-step trace
-
Initialize the string
game = "Olympic2024"creates a string with characters at positions:Position 0 1 2 3 4 5 6 7 8 9 10 Character O l y m p i c 2 0 2 4 -
Search for
"C"The method
game.index("C")looks for the uppercase letter"C"in the string. -
Case-sensitive comparison
Python strings are case-sensitive. The string contains a lowercase
"c"at position 6, but"C"(uppercase) does not appear anywhere. -
Exception raised
Because
"C"is not found, Python raises:
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.