# This fails if file doesn't existwith open('missing.txt', 'r') as f: content = f.read()
Fix:
import os# Check firstif os.path.exists('data.txt'): with open('data.txt', 'r') as f: content = f.read()else: print("File not found")# Or use try-excepttry: with open('data.txt', 'r') as f: content = f.read()except FileNotFoundError: content = "" # Default value
# These cause ValueErrorint("hello") # Can't convert to numberint("12.5") # int() doesn't accept decimalslist.remove("x") # Item not in list
Fix:
# Validate user inputtry: age = int(input("Age: "))except ValueError: print("Please enter a number")# Convert carefullyfloat_str = "12.5"number = int(float(float_str)) # Convert to float first
user = {"name": "Alice", "age": 25}print(user["email"]) # KeyError - no email key
Fix:
# Check if key existsif "email" in user: print(user["email"])# Use get() with defaultemail = user.get("email", "no-email@example.com")# Or handle the errortry: print(user["email"])except KeyError: print("Email not found")
# Wrong - changes list size during iterationnumbers = [1, 2, 3, 4, 5]for num in numbers: if num % 2 == 0: numbers.remove(num) # Dangerous!# Right - create new listodd_numbers = [n for n in numbers if n % 2 != 0]
Mutable default arguments
# Wrong - same list for all calls!def add_item(item, items=[]): items.append(item) return items# Right - create new list each timedef add_item(item, items=None): if items is None: items = [] items.append(item) return items