Skip to Content
Learning Python, 6th Edition
book

Learning Python, 6th Edition

by Mark Lutz
February 2025
Intermediate to advanced
1172 pages
42h 20m
English
O'Reilly Media, Inc.
Book available
Content preview from Learning Python, 6th Edition

Chapter 12. if and match Selections

This chapter presents Python’s two statements used for selecting from alternative actions based on test results:

if/elif/else
The main selection workhorse in most programs, capable of coding arbitrary logic
match/case
A tool for narrower multiple-choice selection, with advanced matching operations

Because this is our first in-depth look at compound statements—statements that embed other statements—we will also explore the general concepts behind the Python statement syntax model here in more detail than we did in the introduction in Chapter 10. Because the if statement introduces the notion of tests, this chapter will also deal with Boolean expressions, cover the “ternary” if expression, and fill in some details on truth tests in general.

if Statements

In simple terms, the Python if statement selects actions to perform. Along with its if expression counterpart, it’s the primary selection tool in Python and represents much of the logic a Python program possesses. It’s also our first compound statement. Like all such statements, the if statement may contain other statements, including other ifs. In fact, Python lets you combine statements in a program both sequentially (so that they execute one after another), and in an arbitrarily nested fashion (so that they execute only under certain conditions, such as selections and loops).

General Format

The Python if is typical of if statements in most procedural languages. It takes the form of an ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Head First Python, 3rd Edition

Head First Python, 3rd Edition

Paul Barry

Publisher Resources

ISBN: 9781098171292Errata PageSupplemental Content