8. Principles of Defensive Programming
Defensive programming is about anticipating failure. Write code assuming every dependency, input, or file might fail or be malicious.
Example
def read_number(prompt):
try:
value = int(input(prompt))
if value < 0:
raise ValueError("Number must be positive.")
return value
except ValueError as e:
print("Error:", e)
return 0 # Safe fallback
✅ Lesson: Handle failures predictably and safely rather than assuming everything will work.