def safe_divide(a, b): try: result = a / b except ZeroDivisionError: print("Cannot divide by zero") return None except TypeError: print("Please provide numbers") return None else: print("Division successful") return result finally: print("Execution finished") # always runs print(safe_divide(10, 2)) # 5.0 Always use context managers for resources.
@classmethod def total_accounts(cls) -> int: return cls._total_accounts acc = BankAccount("Elena", 1000) acc.deposit(500) print(acc.balance) # 1500 print(BankAccount.total_accounts()) # 1 5. Error Handling – Fail Gracefully try/except/else/finally – the else runs only if no exception occurred. in python code
class BankAccount: """A simple bank account.""" _total_accounts = 0 # class variable def __init__(self, owner: str, balance: float = 0.0): self.owner = owner self._balance = balance BankAccount._total_accounts += 1 def safe_divide(a, b): try: result = a /
def greet(name: str, excited: bool = False) -> str: """Return a greeting.""" message = f"Hello, name" return message.upper() + "!!!" if excited else message print(greet("Maria", excited=True)) # HELLO, MARIA!!! def log(level, *messages, **metadata): print(f"[level.upper()]", *messages, metadata) log("info", "User login", "IP 192.168.1.1", user="alice") [INFO] User login IP 192.168.1.1 'user': 'alice' 4. Classes – Modeling in Python Code Python classes are straightforward. No need for getters/setters (use @property when needed). class BankAccount: """A simple bank account
# Write with open("data.txt", "w") as f: f.write("Hello, Python\n") with open("data.txt", "r") as f: content = f.read() print(content) 7. Pythonic Patterns & Idioms Swap variables a, b = b, a # no temp variable needed Check for emptiness if not items: # instead of if len(items) == 0 print("Empty") Use enumerate for index for i, value in enumerate(["a", "b", "c"]): print(i, value) # 0 a, 1 b, 2 c Use zip to iterate over multiple sequences names = ["Anna", "Bob"] scores = [95, 87] for name, score in zip(names, scores): print(f"name: score") 8. Modern Python Features (3.8+) Walrus operator := (assignment inside expression) # Without walrus data = input("Enter: ") while data != "quit": print(f"You said data") data = input("Enter: ") With walrus while (data := input("Enter: ")) != "quit": print(f"You said data") Structural Pattern Matching ( match / case ) def handle_command(cmd): match cmd.split(): case ["quit"]: return "Goodbye" case ["hello", name]: return f"Hello, name" case ["add", x, y] if x.isdigit() and y.isdigit(): return int(x) + int(y) case _: return "Unknown command" 9. Writing Testable Python Code Use unittest or pytest . Example with built-in doctest :
# Ugly (C-style loop) i = 0 while i < len(items): print(items[i]) i += 1 for item in items: print(item) 2. Core Structures Expressed in Python Code Lists & List Comprehensions # Creating and transforming numbers = [1, 2, 3, 4] squares = [n**2 for n in numbers] # [1, 4, 9, 16] evens = [n for n in numbers if n % 2 == 0] # [2, 4] Dictionaries & Dict Comprehensions users = "alice": 25, "bob": 30 ages_plus_10 = name: age+10 for name, age in users.items() # 'alice': 35, 'bob': 40 Sets & Set Operations A = 1, 2, 3 B = 3, 4, 5 print(A | B) # union: 1,2,3,4,5 print(A & B) # intersection: 3 3. Functions – The Heart of Python Code Define behavior cleanly with type hints (Python 3.5+):
def deposit(self, amount: float) -> None: if amount <= 0: raise ValueError("Deposit must be positive") self._balance += amount