liveBook · Manning

Else clause

As explained in Python How-To

An else clause is an optional part of a Python try...except statement that runs when the protected try clause completes without raising an exception.

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

How Python How-To covers it

How deep it goes
Explains clause order and execution through successful and failed conversions, while recommending a short try clause.
Examples
Uses task-string conversion: a valid urgency creates a Task, while an invalid number is handled and returns None.
What it assumes
Builds on basic try...except handling and integer conversion rather than teaching either from zero.
What you can do after
Practice/perform it by placing task creation in else after successful integer conversion.
How it connects
Connects try and except clauses, ValueError, and the contrasting finally clause.

Also explained in

Compare how 5 books explain else clause →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.