Teach Your Kids To Code: A Parent-friendly Guide to Python Programming

(vip2019) #1
Conditions (What If?) 81

Figure 5-2: If you answer y to the question in
IfSpiral.py, you’ll see a spiral like this one.

If you enter a character other than a lowercase y—or more than
one character—the program prints Okay, we're done! and ends.

Meet the Booleans


Boolean expressions, or conditional expressions, are important pro-
gramming tools: the computer’s ability to make decisions depends
on its ability to evaluate Boolean expressions to True or False.
We have to use the computer’s language to tell it the condition
we’d like to test. The syntax of a conditional expression in Python
is this:

expression1 conditional_operator expression2

Each expression can be a variable, a value, or another expres-
sion. In IfSpiral.py, answer == 'y' was a conditional expression, with
answer as the first expression and 'y' as the second. The conditional
operator was ==, to check if answer was equal to 'y'. There are many
other conditional operators in Python besides ==. Let’s learn about
some of them.

Comparison Operators


The most common conditional operators are comparison operators,
which let you test two values to see how they compare to each
other. Is one of the values bigger or smaller than the other? Are
Free download pdf