🐍 Python Indentation Rules - Cheat Sheet
🎯 Golden Rules
- Use 4 spaces (not tabs)
- Be consistent throughout your file
- Every code block must be indented
- Same level = same indentation
📏 Basic Indentation Pattern
# Level 0 (no indentation)
def my_function():
# Level 1 (4 spaces)
if condition:
# Level 2 (8 spaces)
for item in list:
# Level 3 (12 spaces)
print("Deep inside")
# Back to Level 2 (8 spaces)
print("Back out one level")
# Back to Level 1 (4 spaces)
print("Function level")
# Back to Level 0
print("Top level")
🔧 Code Blocks That Require Indentation
Functions
def function_name():
# Must indent here
return "something"
If Statements
if condition:
# Must indent here
elif other_condition:
# Must indent here
else:
# Must indent here
Loops
for item in items:
# Must indent here
while condition:
# Must indent here
Try/Except
try:
# Must indent here
except Exception as e:
# Must indent here
finally:
# Must indent here
Classes
class MyClass:
# Must indent here
def method(self):
# Must indent here (8 spaces total)
❌ Common Errors
Missing Indentation
WRONG ❌
def my_function():
print("This will fail!")
CORRECT ✅
def my_function():
print("This works!")
Inconsistent Indentation
WRONG ❌
def my_function():
print("4 spaces")
print("6 spaces - Error!")
CORRECT ✅
def my_function():
print("4 spaces")
print("4 spaces - Good!")
Missing Colon
WRONG ❌
def my_function()
print("Missing colon above")
CORRECT ✅
def my_function():
print("Colon added!")
🎨 Real-World Examples
Flask Route
@app.route("/endpoint", methods=["POST"])
def my_route():
data = request.form.get("data")
if data:
try:
result = process_data(data)
return "Success", 200
except Exception as e:
print(f"Error: {e}")
return "Error", 500
else:
return "No data", 400
Database Operations
def save_to_database(data):
try:
conn = psycopg2.connect(DATABASE_URL)
cur = conn.cursor()
cur.execute("INSERT INTO table VALUES (%s)", (data,))
conn.commit()
print("✅ Saved successfully")
except Exception as e:
print(f"❌ Database error: {e}")
finally:
if conn:
conn.close()
🛠️ Debugging Tips
Check Syntax
python3 -m py_compile filename.py
Common Error Messages
IndentationError: expected an indented block
Fix: Add 4 spaces after ":"
IndentationError: unindent does not match any outer indentation level
Fix: Check your spacing is consistent
SyntaxError: invalid syntax (pointing to a line)
Fix: Check the line above for missing ":"
📐 Visual Guide
def function(): ← Colon required
if condition: ← 4 spaces + colon
for item: ← 8 spaces + colon
try: ← 12 spaces + colon
code ← 16 spaces
except: ← 12 spaces + colon
error ← 16 spaces
end_for ← 8 spaces
end_if ← 4 spaces
end_function ← 0 spaces
💡 Pro Tips
- Use a good editor (VS Code, PyCharm) that shows indentation
- Configure your editor to show spaces/tabs
- Set tab key to insert 4 spaces
- Use consistent indentation throughout entire project
- When in doubt, count the spaces: 0, 4, 8, 12, 16...
🚨 Emergency Fix
If you get indentation errors:
- Find the error line from the traceback
- Check the line above for missing ":"
- Count spaces - should be multiples of 4
- Make sure all lines at same level have same spacing
- Test with:
python3 -m py_compile filename.py