Chapter Three · Choosing a Path

Making Decisions

Until now every line of a program ran, in order, every time. This chapter gives programs the ability to choose: to ask a yes-or-no question and run different lines depending on the answer. It ends with the skill that makes every later chapter easier: reading an error message from the bottom up.

A program that cannot choose is a recipe with no "if the sauce is too thick, add water". Real rules are full of conditions: free delivery over a certain amount, a discount for members, a warning when a value looks wrong. This chapter turns sentences like those into Python.

It starts with the questions themselves: comparisons, which answer True or False. Then if, elif and else, which run a block of lines only when the answer is right, and indentation, which in Python is part of the grammar. Then combining questions with and, or and not. Then a realistic rule with several conditions, written twice to show which version survives the next change. And last, the field guide to the error messages you have already started to meet.

Every decision has this shape
Is it raining?→yes: take an umbrella
If not: is it cold?→yes: take a coat
Neither→go as you are

Topics in This Chapter