PYTHON BASICS • LESSON 18
Errors, Debugging & Exception Basics
Learn how to understand Python errors, find bugs, debug your programs, and handle common runtime problems usingtry andexcept.
1. What Is an Error?
An error occurs when Python cannot execute your code as intended. Errors are normal when learning programming. The important skill is learning how to read the error and locate the problem.
print("Hello"
The closing parenthesis is missing, so Python cannot correctly understand the statement.
CHECK YOUR UNDERSTANDING
What is a useful first step when debugging Python code?
2. Syntax Errors
A syntax error occurs when Python code does not follow the language's syntax rules.
if 10 > 5
print("Yes")The colon after the condition is missing.
CHECK YOUR UNDERSTANDING
Which problem exists in the code above?
Complete the syntax: if 10 > 5___
3. Runtime Errors
A runtime error happens while the program is running. The syntax may be valid, but an operation cannot be completed.
number = 10 print(number / 0)
Python cannot divide a number by zero, so this produces aZeroDivisionError.
CHECK YOUR UNDERSTANDING
Which error occurs when Python tries to divide a number by zero?
4. NameError
A NameError can occur when Python tries to use a variable or name that has not been defined.
sales = 50000 print(total_sales)
total_sales was never defined.
CHECK YOUR UNDERSTANDING
Why does print(total_sales) fail in the example?
5. TypeError
A TypeError can occur when an operation is performed on incompatible types.
age = 20 print(age + " years")
Here Python is asked to add an integer and a string.
CHECK YOUR UNDERSTANDING
Which error can occur in age + ' years'?
6. IndexError
IndexError can occur when you try to access a list position that does not exist.
sales = [100, 200, 300] print(sales[5])
CHECK YOUR UNDERSTANDING
Why does sales[5] fail?
7. Logical Errors
A logical error is different. The program runs, but it produces the wrong result because the logic is incorrect.
price = 100 quantity = 5 total = price + quantity print(total)
The code runs, but the calculation should use multiplication, not addition.
CHECK YOUR UNDERSTANDING
What is the logical mistake in the example?
8. A Simple Debugging Process
- Read the error message.
- Look at the line number.
- Understand what Python expected.
- Check variable names and values.
- Test a smaller part of the program.
- Fix the problem and run the code again.
CHECK YOUR UNDERSTANDING
Which should you generally do first when an error appears?
9. Handling Errors with try and except
Sometimes we expect that an operation might fail. Python allows us to handle certain runtime errors with try andexcept.
try:
number = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")Python attempts the code inside try. If the specified exception occurs, the except block runs.
CHECK YOUR UNDERSTANDING
Which block handles the specified exception?
The code that might produce an exception is commonly placed inside a ___ block.
10. Handling Different Exceptions
try:
value = int("abc")
except ValueError:
print("Invalid number")int("abc") cannot convert the text to an integer, so Python raises a ValueError.
CHECK YOUR UNDERSTANDING
Which exception is appropriate for int("abc")?
11. Debugging Data Analytics Code
Debugging becomes especially important when processing business data. A small error in a calculation can produce incorrect analytical results.
def revenue(price, quantity):
return price * quantity
sales = revenue(5000, 4)
print(sales)Before trusting the result, check the inputs, calculation, and expected output.
CHECK YOUR UNDERSTANDING
What should revenue(5000, 4) return?
DEBUGGING CHALLENGE
Find the Bug
def profit(revenue, cost):
return revenue + cost
result = profit(100000, 70000)
print(result)The program runs, but the calculation is wrong. Profit should be revenue minus cost.
CHECK YOUR UNDERSTANDING
Which line should be corrected?
Profit is usually calculated as revenue ___ cost.
MINI CHALLENGE
Safe Division
You are analyzing a conversion rate and want to avoid a crash if the number of visitors is zero.
try:
conversion_rate = 100 / 0
except ZeroDivisionError:
print("No visitors")Which block handles the division problem?
CHECK YOUR UNDERSTANDING
Which block handles the division problem?
FINAL CHALLENGE
Build a Safe Sales Calculator
A data analyst wants to calculate average sales. If the number of transactions is zero, the program should display a message instead of crashing.
try:
total_sales = 500000
transactions = 0
average = total_sales / transactions
print(average)
except ZeroDivisionError:
print("No transactions available")CHECK YOUR UNDERSTANDING
What will the program print?
Lesson 18 Recap
- ✓ Syntax errors break Python's syntax rules.
- ✓ Runtime errors occur while the program runs.
- ✓ Logical errors produce incorrect results.
- ✓ NameError can occur when a name is undefined.
- ✓ TypeError can occur with incompatible types.
- ✓ IndexError can occur with an invalid list index.
- ✓ try contains code that might raise an exception.
- ✓ except can handle a matching exception.
- ✓ Debugging is essential when working with real data.