How do you create a task only after its urgency has been converted successfully? Put the conversion in a short try clause, handle ValueError in except, and put task creation in else. The else clause runs only when the try clause finishes without raising an exception. section 12.4.1 section 12.6
Create a task after a successful conversion
from collections import namedtuple Task = namedtuple("Task", "title, urgency") def process_task(text): title, urgency_str = text.split(",") try: urgency = int(urgency_str) except ValueError: return None else: return Task(title, urgency) print(process_task("Laundry,3")) # Task(title='Laundry', urgency=3) print(process_task("Laundry,3#")) # None The invalid number reaches except, so task creation is skipped. Keeping it in else also avoids using urgency when conversion has not assigned it. section 12.4 section 12.4.1
An else clause follows the except clause; it is optional. Keep only the operation that may raise the handled exception in try, then use else for work that depends on its success. A finally clause has a different purpose: it runs whether or not try raises an exception. section 12.4.1 section 12.6
Python also permits else on for and while loops, but that is a different pattern: loop else runs when no break occurs. Avoid confusing the two uses. section 5.4.3 section 5.4.4




