Python Notes
HubHistory of Python - Complete Guide 2026Python Applications - Complete Guide 2026Python Features - Complete Guide 2026What is Python? - Complete Guide 2026Why Learn Python? - Complete Guide 2026Your First Python Program – Hello World & Beyond 2026How to Install Python on Windows, Mac & Linux – Complete Guide 2026Install VS Code for Python – Complete Setup Guide with Extensions 2026Python Environment Setup – Virtual Environments, pip & Project Structure 2026Python IDLE – Complete Guide for Beginners 2026Python CommentsPython Data TypesPython Input and OutputPython OperatorsPython SyntaxPython Strings BasicsPython Type CastingPython VariablesBreak, Continue and Pass in PythonElif Statement in PythonFor Loop in PythonIf-Else Statement in PythonIf Statement in PythonNested If in PythonPattern Programs in PythonWhile Loop in PythonDecorators in PythonFunction Arguments in PythonFunctions Basics in PythonGenerators in PythonLambda Functions in PythonRecursive Functions in PythonReturn Statement in PythonScope of Variables in PythonAbstraction in PythonClasses and Objects in PythonConstructors in PythonEncapsulation in PythonInheritance in PythonMagic Methods (Dunder Methods) in PythonMethod Overriding in PythonPolymorphism in PythonPython Comprehensions – List, Dict, Set & GeneratorPython Dictionaries – Key-Value StorePython Dictionary Methods – Complete ReferencePython List Methods – All Built-in MethodsPython Lists – Complete GuidePython Set Methods – Complete ReferencePython Sets – Unordered Unique CollectionsPython Tuples – Immutable SequencesPython Asynchronous Programming with asyncioPython Context ManagersAdvanced Python DecoratorsAdvanced Python GeneratorsPython Iterators - Advanced GuidePython Memory ManagementPython MultiprocessingPython MultithreadingCRUD Operations in Python DatabasesMySQL with Python (mysql-connector-python)ORM Introduction with SQLAlchemyPostgreSQL with Python (psycopg2)SQLite3 with PythonIntroduction to DjangoDjango Models and ORMDjango REST API with DRFDjango ViewsIntroduction to FlaskFlask RoutingFlask Templates with Jinja2Email Automation with PythonPDF Automation with PythonSelenium Web Automation with PythonTask Scheduler with PythonWeb Scraping with PythonData Analysis with PythonData Cleaning with PythonData Visualization ProjectData Visualization with MatplotlibNumPy IntroductionPandas IntroductionStatistical Visualization with SeabornClassification AlgorithmsClustering AlgorithmsIntroduction to Machine LearningMachine Learning Project: Churn PredictionModel Evaluation and SelectionRegression AlgorithmsSave pipeline (includes preprocessing + model)AI Assistant ProjectCalculator ProjectChatbot ProjectExpense Tracker ProjectFace Detection ProjectPassword Generator ProjectWeather App ProjectPython Coding Interview QuestionsPython OOP Interview Questions and AnswersPython Master CheatsheetPython Interview Questions and AnswersPython Best PracticesCommon Python Errors and SolutionsPython Debugging TechniquesPython Learning Resources
Master Python error handling by understanding the most common errors — SyntaxError, IndentationError, NameError, TypeError, AttributeError, ImportError, ValueError, KeyError, IndexError, and how to fix them.
Every Python developer encounters errors. Learning to read error messages and understand common pitfalls is one of the most valuable skills you can develop.
Reading a Traceback
Code example
Traceback (most recent call last):
File "app.py", line 15, in <module> ← Script, line number, context
result = divide(10, 0) ← Code that caused the chain
File "app.py", line 8, in divide ← Function where error occurred
return a / b ← Exact line
ZeroDivisionError: division by zero ← Exception type: messageReading strategy: Always read the last line first (the actual error), then trace upward through the call stack.
SyntaxError
Example
# ❌ SyntaxError: Missing colon
def greet(name)
print(f"Hello, {name}")
# ✅ Fix
def greet(name):
print(f"Hello, {name}")
# ❌ SyntaxError: Unmatched bracket
result = (1 + 2 * 3
value = result + 1 # Forgot to close parenthesis
# ✅ Fix
result = (1 + 2 * 3)
value = result + 1
# ❌ SyntaxError: Missing quote
message = "Hello World
print(message)
# ✅ Fix
message = "Hello World"
print(message)
# ❌ SyntaxError: Invalid assignment target
3 = x # Can't assign to a literal
# ✅ Fix
x = 3
# ❌ f-string with backslash (Python < 3.12)
# names = ['Alice', 'Bob']
# print(f"Names: {'\n'.join(names)}") # SyntaxError!
# ✅ Fix — assign first or use Python 3.12+
separator = '\n'
names = ['Alice', 'Bob']
print(f"Names: {separator.join(names)}")
IndentationError
python example
# ❌ IndentationError: Expected an indented block
def greet(name):
print(f"Hello, {name}") # Not indented!
# ✅ Fix
def greet(name):
print(f"Hello, {name}")
# ❌ IndentationError: Unexpected indent
x = 5
y = 10 # Indented but not inside a block
# ✅ Fix
x = 5
y = 10
# ❌ Mixing tabs and spaces
def calculate():
x = 1
y = 2 # Tab instead of spaces!
# ✅ Fix — use spaces consistently
def calculate():
x = 1
y = 2
# Pro tip: Configure your editor to show whitespace and convert tabs to spacesNameError
python example
# ❌ NameError: name 'x' is not defined
print(x) # x was never assigned
# ✅ Fix
x = 10
print(x)
# ❌ NameError: typo in variable name
user_name = "Alice"
print(usernmae) # Typo!
# ✅ Fix
print(user_name)
# ❌ NameError: using variable before assignment
def calculate():
result = initial + 5 # initial not yet defined
initial = 10
return result
# ✅ Fix
def calculate():
initial = 10
result = initial + 5
return result
# ❌ NameError: function not imported
response = requests.get("https://example.com") # requests not imported
# ✅ Fix
import requests
response = requests.get("https://example.com")
# ❌ Scope issue
def outer():
x = 10
def inner():
print(x + 5) # OK — can read from outer scope
x = 20 # UnboundLocalError! Can't assign to x from outer scope
# ✅ Fix using nonlocal
def outer():
x = 10
def inner():
nonlocal x
x = 20
inner()
print(x) # 20TypeError
Example
# ❌ TypeError: can only concatenate str (not "int") to str
name = "Alice"
age = 25
print("Name: " + name + ", Age: " + age) # age is int!
# ✅ Fix
print("Name: " + name + ", Age: " + str(age))
print(f"Name: {name}, Age: {age}") # Best approach
# ❌ TypeError: unsupported operand type(s)
result = "5" + 3 # Can't add str and int
# ✅ Fix
result = int("5") + 3 # 8
result = "5" + str(3) # "53"
# ❌ TypeError: object is not subscriptable
number = 42
print(number[0]) # Integers aren't subscriptable
# ✅ Fix — check type first
data = "hello"
print(data[0]) # 'h'
# ❌ TypeError: ... takes N positional arguments but M were given
def add(a, b):
return a + b
result = add(1, 2, 3) # 3 args but function expects 2
# ✅ Fix
result = add(1, 2) # or add(*args)
# ❌ TypeError: 'NoneType' object is not callable
def get_function():
pass # Returns None!
func = get_function()
func() # None is not callable!
# ✅ Fix
def get_function():
return lambda x: x * 2 # Return an actual function
# ❌ TypeError: 'int' object is not iterable
for i in 5: # Can't iterate over integer
print(i)
# ✅ Fix
for i in range(5):
print(i)
AttributeError
python example
# ❌ AttributeError: 'str' object has no attribute 'append'
name = "Alice"
name.append(" Smith") # append() is for lists!
# ✅ Fix
name = name + " Smith" # or
name = f"{name} Smith"
# ❌ AttributeError: 'NoneType' object has no attribute 'upper'
result = some_function() # Returns None
print(result.upper()) # None has no methods!
# ✅ Fix — check for None
result = some_function()
if result is not None:
print(result.upper())
# Or: print(result.upper() if result else "No result")
# ❌ AttributeError: module has no attribute
import math
math.sqroot(16) # It's math.sqrt, not sqroot!
# ✅ Fix
math.sqrt(16)
# Common misspellings
# list.lenght → list.length (wrong!) → len(list) ✅
# dict.has_key() → 'key' in dict ✅ (Python 3)
# string.count() ← this one IS correct
# pd.DataFrame.tostring() → pd.DataFrame.to_string() ✅ImportError / ModuleNotFoundError
python example
# ❌ ModuleNotFoundError: No module named 'numpy'
import numpy as np # Module not installed
# ✅ Fix — install it
# pip install numpy
import numpy as np
# ❌ ImportError: cannot import name 'DataFrame' from 'pandas'
from pandas import DataFrame # This actually works...
# But this won't:
from pandas import Dataframe # Case sensitive!
# ✅ Fix — check case
from pandas import DataFrame # Capital D and F
# ❌ Circular imports
# file a.py:
# from b import B
# file b.py:
# from a import A # Circular!
# ✅ Fix — restructure or use local imports
# In a.py:
def use_b():
from b import B # Import inside function, not at module level
return B()
# ❌ Wrong relative import
from .models import User # This only works inside a package!
# ✅ Fix — use absolute import when running as script
from mypackage.models import UserValueError
Example
# ❌ ValueError: invalid literal for int() with base 10
age = int("twenty-five") # Can't convert text to int
# ✅ Fix — validate input
raw = "twenty-five"
try:
age = int(raw)
except ValueError:
print(f"'{raw}' is not a valid integer")
age = 0
# ❌ ValueError: not enough values to unpack
a, b, c = [1, 2] # Only 2 values, need 3
# ✅ Fix
a, b = [1, 2] # Match number of variables to values
# Or:
a, b, c = [1, 2, 3]
# ❌ ValueError in Pandas
import pandas as pd
df = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
df['c'] = [5, 6, 7] # Series length doesn't match!
# ✅ Fix — matching lengths
df['c'] = [5, 6]
# ❌ ValueError: math domain error
import math
math.sqrt(-1) # No real sqrt of -1
# ✅ Fix
import cmath
result = cmath.sqrt(-1) # Complex result: 1j
KeyError
Example
# ❌ KeyError: 'age'
person = {"name": "Alice", "city": "NYC"}
print(person["age"]) # Key doesn't exist!
# ✅ Fix — use .get() with default
print(person.get("age", 0)) # Returns 0 if key missing
print(person.get("name")) # Returns None if key missing
# Or check first
if "age" in person:
print(person["age"])
# ❌ KeyError in nested dict
data = {"user": {"name": "Alice"}}
print(data["user"]["email"]) # Missing key!
# ✅ Fix — chained .get()
email = data.get("user", {}).get("email", "N/A")
print(email) # "N/A"
# ❌ KeyError when modifying dict during iteration
d = {"a": 1, "b": 2, "c": 3}
for key in d:
if d[key] < 2:
del d[key] # RuntimeError: dictionary changed size!
# ✅ Fix — iterate over a copy
for key in list(d.keys()):
if d[key] < 2:
del d[key]
IndexError
Example
# ❌ IndexError: list index out of range
my_list = [10, 20, 30]
print(my_list[3]) # Index 3 doesn't exist (0, 1, 2)
print(my_list[-4]) # Negative index too large
# ✅ Fix — check length
if len(my_list) > 3:
print(my_list[3])
print(my_list[-1]) # Last element: safe
# ❌ IndexError from off-by-one
nums = [1, 2, 3, 4, 5]
for i in range(len(nums) + 1): # Should be len(nums)
print(nums[i]) # Fails on last iteration
# ✅ Fix
for i in range(len(nums)):
print(nums[i])
# Better: iterate directly
for num in nums:
print(num)
# ❌ IndexError on empty sequence
my_list = []
first = my_list[0] # Empty list!
# ✅ Fix — check first
if my_list:
first = my_list[0]
else:
first = None
# Or: first = my_list[0] if my_list else None
FileNotFoundError
python example
# ❌ FileNotFoundError: No such file or directory
with open("data.csv") as f:
content = f.read()
# ✅ Fix — check if file exists
from pathlib import Path
file_path = Path("data.csv")
if file_path.exists():
with open(file_path) as f:
content = f.read()
else:
print(f"File not found: {file_path}")
# Or use try/except
try:
with open("data.csv") as f:
content = f.read()
except FileNotFoundError:
print("data.csv not found!")
content = ""Exception Handling Best Practices
Example
# ❌ Catching all exceptions (too broad)
try:
result = int(user_input)
except:
print("Error") # Hides the real problem!
# ❌ Still too broad
try:
result = int(user_input)
except Exception:
print("Error")
# ✅ Catch specific exceptions
try:
result = int(user_input)
except ValueError:
print("Please enter a valid number")
except TypeError:
print("Input must be a string or number")
# ✅ Multiple exception types
try:
file_data = json.load(open(path))
value = file_data["key"]
except FileNotFoundError:
print(f"File not found: {path}")
except json.JSONDecodeError:
print("Invalid JSON format")
except KeyError:
print("Missing required key")
except Exception as e:
# Catch-all for unexpected errors (log, don't hide)
logger.error(f"Unexpected error: {type(e).__name__}: {e}")
raise # Re-raise to propagate
# ✅ finally block — always runs
def process_file(path):
f = None
try:
f = open(path)
data = json.load(f)
return data
except FileNotFoundError:
return None
finally:
if f:
f.close() # Runs whether exception occurred or not
# ✅ Better: context manager (auto-closes)
def process_file(path):
try:
with open(path) as f:
return json.load(f)
except FileNotFoundError:
return None
# ✅ Custom exceptions
class InsufficientFundsError(ValueError):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(f"Insufficient funds: balance ${balance:.2f}, need ${amount:.2f}")
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(balance, amount)
return balance - amount
try:
new_balance = withdraw(100, 200)
except InsufficientFundsError as e:
print(f"Transaction failed: {e}")
print(f" Balance: ${e.balance}, Requested: ${e.amount}")
Quick Error Reference
| Error | Typical Cause | Quick Fix |
|---|---|---|
SyntaxError | Missing colon, bracket, quote | Check syntax carefully |
IndentationError | Wrong indentation | Use 4 spaces consistently |
NameError | Variable not defined | Check spelling, define before use |
TypeError | Wrong type in operation | Convert types, check .get() for None |
AttributeError | Wrong method/attribute name | Check docs, look for typos |
ImportError | Module not installed | pip install module_name |
ValueError | Wrong value for operation | Validate input |
KeyError | Key missing from dict | Use .get() with default |
IndexError | Index out of range | Check len(), use negative indexing |
FileNotFoundError | File doesn't exist | Check path, use Path.exists() |
ZeroDivisionError | Division by zero | Check divisor before dividing |
RecursionError | Infinite recursion | Add base case, increase sys.setrecursionlimit |
*Next: Debugging Techniques →*
Continue the lesson path
Study next in this module
01ResourcesPython Best PracticesMaster Python best practices and coding standards — PEP 8 style guide, clean code principles, naming conventions, documentation, type hints, logging, testing, virtual environments, and professional Python patterns.02ResourcesPython Debugging TechniquesMaster Python debugging — print debugging, pdb debugger, VS Code debugger, logging strategies, unit testing with pytest, profiling, and systematic debugging workflows for finding and fixing bugs quickly.03ResourcesPython Learning ResourcesCurated list of the best Python learning resources — official documentation, books, online courses, YouTube channels, practice platforms, communities, cheat sheets, and a structured 6-month learning roadmap.04Advanced PythonPython Asynchronous Programming with asyncioDeep dive into Python async/await, asyncio event loop, coroutines, tasks, async generators, aiohttp, and real-world asynchronous patterns with Hindi explanations.