Errors and Debugging
This is a free course. Log in to run the code exercises and track your progress.
Errors and Debugging
A program can go wrong in three ways:
- Syntax errors break the rules of the language: a missing colon, an unclosed bracket, wrong indentation. Python refuses to run the program at all and points at the line.
- Runtime errors (exceptions) happen while the program is running: dividing by zero (
ZeroDivisionError), converting"abc"withint()(ValueError), using an undefined name (NameError), adding a number to a string (TypeError). The program stops at that line. - Logical errors give a wrong answer without any message, such as
avg = a + b / 2instead of(a + b) / 2. Only testing with known answers finds them.
Debugging means finding and fixing these errors: read the error message (its last line names the error and the line number), print intermediate values, and test with inputs whose answer you already know.
A preview of Class 12: a runtime error can be handled so the program does not crash.
try:
print(10 / int(input()))
except ZeroDivisionError:
print("Cannot divide by zero")
This program should print the average of two integers read from one line, with one decimal, but it has a logical error. Fix it.
a, b = map(int, input().split())
avg = a + b / 2
print(f"{avg:.1f}")Log in to edit and run this code.