Skip to content

Error Types

Recognizing Python's Common Errors


Errors vs Exceptions

  • Syntax Error: Code is written incorrectly and cannot run
  • Exception: Errors that occur at runtime

Common Syntax Errors

1. Indentation Error

python
#  IndentationError
def greet():
print("Hello")  # Missing indentation

#  Correct
def greet():
    print("Hello")

2. Missing Colon

python
#  SyntaxError
if age > 18  # Missing colon
    print("Adult")

#  Correct
if age > 18:
    print("Adult")

3. Unmatched Parentheses

python
#  SyntaxError
result = (1 + 2  # Missing closing parenthesis

#  Correct
result = (1 + 2)

Common Runtime Exceptions

1. NameError: Undefined Variable

python
print(age)  # NameError: name 'age' is not defined

# Correct: Define before using
age = 25
print(age)

2. TypeError: Type Error

python
# Example 1: Operations on different types
result = "25" + 5  # TypeError: can only concatenate str

# Correct
result = int("25") + 5  # 30

# Example 2: Incorrect parameter type
def greet(name):
    print(f"Hello, {name}")

greet(123)  # Runs, but not recommended

3. ValueError: Value Error

python
# Example 1: Type conversion fails
age = int("abc")  # ValueError: invalid literal

# Example 2: List method can't find value
lst = [1, 2, 3]
lst.remove(5)  # ValueError: 5 not in list

4. IndexError: Index Out of Range

python
ages = [25, 30, 35]
print(ages[5])  # IndexError: list index out of range

# Correct
if len(ages) > 5:
    print(ages[5])

5. KeyError: Dictionary Key Doesn't Exist

python
student = {'name': 'Alice', 'age': 25}
print(student['major'])  # KeyError: 'major'

# Correct approach
print(student.get('major', 'Unknown'))  # Unknown

6. FileNotFoundError: File Doesn't Exist

python
with open('non_existent.txt', 'r') as f:  # FileNotFoundError
    content = f.read()

# Correct: Check first
from pathlib import Path
if Path('file.txt').exists():
    with open('file.txt', 'r') as f:
        content = f.read()

7. ZeroDivisionError: Division by Zero

python
result = 10 / 0  # ZeroDivisionError

# Correct
if denominator != 0:
    result = numerator / denominator

8. AttributeError: Attribute Doesn't Exist

python
lst = [1, 2, 3]
lst.append(4)      #  List has append
lst.push(5)        #  AttributeError: 'list' object has no attribute 'push'

Common Errors in Social Science Scenarios

Scenario 1: Data Cleaning

python
# Reading survey data
data = [
    {'id': 1, 'age': '25', 'income': '50000'},
    {'id': 2, 'age': 'N/A', 'income': '75000'},
    {'id': 3, 'age': '35', 'income': 'unknown'}
]

#  Direct conversion will error
for resp in data:
    age = int(resp['age'])  # ValueError at id=2

Scenario 2: File Reading

python
#  File may not exist
df = pd.read_csv('survey_2024.csv')  # FileNotFoundError

#  Column name may be misspelled
mean_income = df['imcome'].mean()  # KeyError: 'imcome'

Scenario 3: API Calls

python
import requests

#  Network may be down
response = requests.get('https://api.example.com/data')
data = response.json()  # May fail

Viewing Error Messages

python
# Complete error message example
ages = [25, 30, 35]
print(ages[5])

# Output:
# Traceback (most recent call last):
#   File "script.py", line 2, in <module>
#     print(ages[5])
# IndexError: list index out of range

Interpretation:

  • Traceback: Error tracking
  • File "script.py", line 2: Error location
  • IndexError: Error type
  • list index out of range: Error description

Preventing Errors

1. Using Type Hints

python
def calculate_mean(data: list) -> float:
    """Calculate mean"""
    return sum(data) / len(data)

2. Input Validation

python
def calculate_tax(income):
    if not isinstance(income, (int, float)):
        raise TypeError("Income must be a number")
    if income < 0:
        raise ValueError("Income cannot be negative")
    return income * 0.25

3. Using Safe Methods

python
#  Unsafe
value = dict[key]

#  Safe
value = dict.get(key, default_value)

Practice Questions

python
# Find the error type in the following code

# 1.
result = "25" + 5

# 2.
ages = [25, 30, 35]
print(ages[3])

# 3.
def greet()
    print("Hello")

# 4.
student = {'name': 'Alice'}
print(student['age'])

# 5.
value = int("abc")

Next Steps

Next section learns how to use try-except to catch and handle these errors.

Continue!

Released under the MIT License. Content © Author.