Exceptions & Files · Question 4 · Easy

A dictionary of marks is asked for a name that was never stored. Which exception is raised?

marks = {"Anil": 70}
print(marks["Sunil"])
  1. IndexError
  2. NameError
  3. KeyError
  4. ValueError
Answer and explanation

Answer: C. KeyError

Explanation: Looking up a missing key with square brackets raises KeyError. IndexError is for positions in a list or tuple that are out of range.

Previous: In a try statement, when does the code inside the finally block run? · Next: A file report.txt already has some text in it. What happens to that text when…

Practise exceptions & files

Try a fresh set of exceptions & files questions with an explanation after every answer, free and without signing up: Exceptions & Files practice. Or sit a full placement mock test.

More exceptions & files questions

More python practice

Built-ins & Standard Library · Variables, Types & Operators · Python Strings · Lists & Tuples · Dictionaries & Sets · Conditions & Loops · Functions & Scope · Comprehensions & Generators

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge