HelpContactFor teachers and institutes
>_StemPy Lab
Mock TestsClasses

>_StemPy Lab

Learn. Solve. Code the solutions. Test yourself.

Live examsFree mock exams, timed and rankedEveryone starts together, and your score and rank come the moment it ends.See the exams →
Live examsInternational live exams are comingTell us which exam you want first. Timed practice papers are open now.See what is coming →

Learn

  • Physics
  • Chemistry
  • Mathematics
  • Biology
  • Python Programming
  • Statistics & Data Science
  • Computer Science
  • Space Science and Astronomy
  • Earth and Environmental Science
  • Classes
  • Groups

Practice

  • Problems
  • Quizzes
  • Mock Tests
  • Prepare for an Exam
  • Question Sets
  • Exams
  • Certificates
  • Python Labs
  • AI Practice Generator
  • Student-Created Tests

Community

  • Discussions
  • Resources
  • Notes
  • Glossary
  • Blog

Account

  • Log in
© 2026 senLearn. All rights reserved.HelpFor SchoolsAboutContactPrivacy PolicyTerms of UseRefund Policy
  1. Python Programming
  2. /Python Essentials
  3. /Errors and Exceptions

Errors and Exceptions

Python Programming · High School (9–10) · 2 courses, 27 worked problems, 68 practice questions

Every programmer makes mistakes, and Python reports them clearly. A syntax error, such as a missing bracket, stops the program before it runs. An exception happens while the program runs, such as ZeroDivisionError when you divide by zero or ValueError when int() gets text. The traceback tells you the type of error and the line where it happened. With try and except, a program can catch an exception and respond, for example by asking the user to type a number again. You can also raise your own exception when a value makes no sense.

With practice you will be able to

  • Read a traceback to find the type and line of an error
  • Catch an exception with try and except
  • Raise an exception when a function gets a bad value

On the syllabus of

  • CBSE / State Class 12
  • Python Certification
  • A-Level

Lessons

  • Three Essentials ProjectsCan you crack a Caesar code without knowing the shift?High School (9–10)
  • When Things Go Wrong: try and exceptWhat should a program do when you type a letter for your age? Which line names the error?High School (9–10)

Practice questions

Choose an answer, then check it. Each one shows a full explanation.

A loop collects the third letter of each word in a list. A word that is too short adds a question mark instead, and the except block ends with continue. thirds = "" for w in ["python", "go", "c", "java"]: try: thirds += w[2] except IndexError: thirds += "?" continue thirds += "." print(thirds) What is the output?

The helper middle picks the character at the halfway index of its argument. Three calls follow, and each answer is shown with a space after it. def middle(s): return s[len(s) // 2] print(middle("abc"), end=" ") print(middle("ab"), end=" ") print(middle("")) What is the result of running this code?

This program should print 3 zero bad. It stops with TypeError on the third call instead. def safe_div(a, b): try: return a // b except ZeroDivisionError: return "zero" print(safe_div(9, 3), safe_div(1, 0), safe_div("6", 2)) Which change makes the program print exactly 3 zero bad?

A program reads an age from the keyboard and raises its own error for a negative age. The user types -5. msg = "" try: age = int(input()) if age < 0: raise ValueError msg = "age " + str(age) except ValueError: msg = "bad" finally: msg += "!" print(msg) What does the program print?

A program removes names from a list. One of the names is not in the list. names = ["Ali", "Bea", "Cal"] for target in ["Bea", "Dev"]: try: names.remove(target) print(target, "out", end="; ") except ValueError: print(target, "not found", end="; ") print(len(names)) What does the program print?

A function raises an error when it is given an empty list. Three calls are made inside one try block. def mean(v): if len(v) == 0: raise ValueError("no data") return sum(v) / len(v) try: print(mean((2, 4)), end=" ") print(mean([]), end=" ") print(mean([1])) except ValueError as e: print(e) What does the program print?

A function reads from a box, which may be a dictionary, a list or a tuple. Its first except names the family LookupError, and its second names Exception. def fetch(box, k): try: return box[k] except LookupError: return "missing" except Exception: return "bad" print(fetch({"x": 1}, "y"), fetch([1, 2], -3), fetch((5, 6), "0")) What does the program print?

One function calls another. The inner one reads past the end of a list, and neither function has a try. def inner(items): print("in", end=" ") return items[3] def outer(items): v = inner(items) print("out", end=" ") return v try: print(outer([1, 2, 3])) except IndexError: print("caught") What does the program print?

A function adds results to a list that it is given. Part way through, one of the results fails, and the caller handles the error. def fill(target, values): for v in values: target.append(10 // v) return len(target) data = [] try: n = fill(data, [5, 2, 0, 1]) except ZeroDivisionError: n = -1 print(n, data) What does the program print?

A program has two exception classes of its own, one inheriting from the other. class AppError(Exception): pass class SaveError(AppError): pass def save(n): if n < 0: raise SaveError("negative") return n for n in (2, -1): try: print(save(n), end=" ") except AppError as e: print(type(e).__name__, e) except SaveError: print("save") What does the program print?

All 68 practice questions on Errors and Exceptions →

Worked problems

Each one has a hint, the key idea and a full worked solution.

  • Write three small functions square(n), double(n) and negate(n), and a dictionary operations that…Medium
  • Choose a project: a program that keeps the scores of a quiz game and shows who is winning…Easy
  • Write a function above_mean(marks) for a dictionary of name and mark…Medium
  • Write a function percent(part, total) that gives part / total * 100…Medium
  • For each job, say whether you would look before you leap (an if) or try and catch (try and except)…Easy
  • The data reader below reports each bad line with a message…Medium
  • Say which error each line gives, before you run it.Easy
  • Write add(name, number) for the contact book…Easy
  • The book has asha and ravi. What happens with contacts["zoya"]? …Easy
  • The book is {"meera": "99887", "asha": "98765", "ravi": "91234", "kabir": "90000"}…Medium
  • Count the letters of balloon with a dictionary…Medium
  • In a long English secret, the most common letter is x…Medium

All 27 worked problems on Errors and Exceptions →

Python labs

  • Contact book tools
  • Guess the shift
  • Marks report tools
  • Run the commands
  • Project: the command menu
  • Plan and test: a unit converter

Related topics

  • Python Essentials
  • Dictionaries
  • Tuples and Sets
  • Modules and Libraries
  • Searching and Sorting
  • Recursion
  • Text Processing
  • Essentials Projects