liveBook · Manning

Conditional logic

As explained in Python How-To

Conditional logic is a programming technique that evaluates conditions to select among execution paths, actions, or result values.

When a task should run only under certain circumstances, use a condition to decide what happens. In Python, an if statement can guard an operation, while an if...else... statement can select between paths. Conditional expressions select a value instead. section 1.4.1 section 10.3.2

To collect titles of tasks with urgency greater than 3, test each task inside a loop. Only matching titles are appended; the resulting list is ['Homework', 'Museum']. section 5.2.4

filtered_titles0 = []
for task in tasks:
    if task.urgency > 3:
        filtered_titles0.append(task.title)
      
assert filtered_titles0 == ['Homework', 'Museum']

The if statement makes the filtering test explicit on its own line. section 5.2.4

A list comprehension can express the same filter as [expression for item in iterable if condition]. The condition follows the iterable; dictionary and set comprehensions can also use filtering conditions. section 5.2.4

filtered_titles1 = [task.title for task in tasks if task.urgency > 3]
 
assert filtered_titles0 == filtered_titles1

This comprehension produces the same titles as the loop. section 5.2.4

For a choice between two values, use value_when_true if condition else value_when_false. The Task constructor uses this form to assign an empty list when tags is None, or the supplied tags otherwise. section 10.3.2

class Task:
    def __init__(self, title, desc, tags = None):
        self.title = title
        self.desc = desc
        self.tags = [] if tags is None else tags    #1
 
    def __repr__(self):
        return f"Task({self.title!r}, {self.desc!r}, {self.tags})"
 
    def save_data(self):
        pass

The conditional expression assigns self.tags in the constructor. section 10.3.2

A condition can also stop a loop early. To find the first task with urgency 5, assign the task and break when the test succeeds. Initialize the result to None first so it has a value even when no task matches. section 5.4.1

Listing 5.7 Finding the urgent task by using break
first_urgent_task1 = None     #1
 
for task in tasks:
    if task.urgency == 5:
        first_urgent_task1 = task
        break
  
assert first_urgent_task0 == first_urgent_task1

The search ends at the first match rather than continuing through the remaining tasks. section 5.4.1

Choose the form that keeps the decision readable. A separate if statement can make the condition more visible than a filter call. If you are unsure how an if...else... statement interacts with scope, try changing a global variable inside it and inspect the result. section 5.3.6 section 10.4.5

How Python How-To covers it

How deep it goes
Defines conditional expressions and works through filtering and loop exit; leaves conditional scope as an investigation.
Examples
Uses task urgency filters, a tags default in a constructor, and a first-urgent-task search.
What it assumes
Assumes familiarity with loops and task objects in the filtering examples.
What you can do after
Apply conditional logic in Python to filter items, select a value, and terminate a loop on a match.
How it connects
Connects conditional logic to list comprehensions, iteration, break statements, and variable scope.

Also explained in

Compare how 22 books explain conditional logic →

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.