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.
try and exceptChoose 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?
Each one has a hint, the key idea and a full worked solution.