0%

Chapter 5

Making Decisions

Meet Boolean Values

A program that always follows the same instructions can still be useful. A program becomes much more responsive when it can ask a question about its current data and choose what to do next.

Python represents the answer to a yes-or-no question with a . There are exactly two Boolean values:

True
False

The type is called bool, short for Boolean. The name honors George Boole, whose work helped formalize logic with two possible values.

Boolean values in variables

You can store a Boolean value in a just like a or number:

Try it

The output is:

True
False

The capital letters matter. Python’s Boolean values are written as True and False, not true and false.

Quotation marks matter too. True is a Boolean value, while "True" is a string containing four characters.

You can ask type() to show the difference:

Try it

The first value has type bool. The second has type str.

Comparisons produce Boolean values

Most Boolean values in a program come from questions about other data. Python calls these questions comparisons.

Consider this :

temperature < 20

It asks whether the current value of temperature is less than 20. Python evaluates the expression and produces either True or False.

Run it with two different temperatures:

Try it

The first comparison produces True. The second produces False.

A comparison does not print by itself. In this example, print() makes the resulting Boolean value visible. You can also store the result:

Try it

Python evaluates age < 30 first, then assigns the resulting Boolean value to is_under_30.

Which value has the bool type?

What does this code print?

available_places = 3
print(available_places < 2)

Values that guide decisions

A Boolean value records one of two possibilities: yes or no, on or off, true or false. In the next lessons, you will learn the comparison that produce these values and then use them to control which instructions Python runs.

For this lesson, keep the central idea in view: a comparison is an expression, and its result is a Boolean value.

Task

Run the examples and complete both quizzes. Before moving on, make sure you can explain:

  • why True and "True" have different ;

  • why the same comparison can produce a different result when a changes;

  • why a comparison is an with a .