Exercises
Debugging
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Print the first and last lines of the traceback rather than letting it crash.
Python
import traceback
def broken():
return [1, 2, 3][10]
# catch it and print the first and last traceback lines
traceback.format_exc() gives the whole thing as a string.
import traceback
def broken():
return [1, 2, 3][10]
try:
broken()
except IndexError:
lines = traceback.format_exc().strip().splitlines()
print(lines[0])
print(lines[-1])Exercise 2Passed
The comparison fails for a reason you cannot see. Print the repr to reveal it.
Python
value = "42 "
print(value == "42")
# now show what value really is
repr() shows quotes and whitespace.
value = "42 "
print(value == "42")
print(repr(value))Exercise 3Passed
Use an f-string with = so each line names the variable it prints.
Python
total = 0
for n in [1, 2, 3]:
total += n
# print n and total, each labelled
f"{n=}" prints the expression and its value.
total = 0
for n in [1, 2, 3]:
total += n
print(f"{n=} {total=}")