Exceptions, Typing and Performance Tips
Harry
· 14 Sep 2026
· 2 views
Advertisement
Handling Errors
try:
result = 10 / int(input("Number: "))
except ValueError:
print("That was not a number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print(f"Result: {result}")
finally:
print("Done")Raising Your Own Exceptions
def withdraw(balance, amount):
if amount > balance:
raise ValueError("Insufficient funds")
return balance - amountType Hints
Type hints document intent and let tools (mypy, IDEs) catch mistakes early.
from typing import List, Optional
def total(prices: List[float], discount: Optional[float] = None) -> float:
t = sum(prices)
return t * (1 - discount) if discount else tPerformance Tips
- Prefer comprehensions and built-ins (
sum,max,any) over manual loops. - Use
inon sets/dicts for O(1) membership checks instead of lists. - Profile with
cProfilebefore optimising; measure, don't guess. - Mind the GIL: use
multiprocessingfor CPU-bound work, threads for I/O. - Avoid big string concatenation; use
str.join().
Key Points
try/except/else/finallymakes handling errors explicit.- Type hints +
typingimprove clarity and tool support. - Profile first; the standard library is already well optimised.