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

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

The lower() function changed the capital Y and capital S in Yes,
Sir to lowercase, leaving the rest of the string unchanged.
We can use lower() on the user’s input so that no matter which
they enter, Y or y, the condition in our if statement will be True:


if answer.lower() == 'y':


Now, if a user enters either Y or y, our program checks to see if
the lowercase version of their answer is y. But if we want to check
for the full word Yes, we need a compound if statement.
Compound if statements are like compound sentences: “I’m
going to the store, and I’m going to buy some groceries.” Compound
if statements are useful when we want to do a bit more than just
test whether one condition is true. We might want to test if this
condition and another condition are both true. We might test if
this condition or another condition is true. And we might want to
see if the condition is not true. We do this in everyday life, too. We
say, “If it’s cold and raining, I’ll wear my heavy raincoat,” “If it’s
windy or cold, I’ll wear a jacket,” or “If it’s not raining, I’ll wear my
favorite shoes.”
When we build a compound if statement, we use one of the
logical operators shown in Table 5-2.


Table 5-2: Logical Operators


Logical
operator

Usage Result

and if(condition1 and condition2): True only if both
condition1 and condition2
are True
or if(condition1 or condition2): True if either of
condition1 or condition2
are True
not if not(condition): True only if the condition
is False

We can use the or operator to check if the user entered y or yes;
either one will do.


answer = input("Do you want to see a spiral? y/n:").lower()
if answer == 'y' or answer == 'yes': # Checks for either 'y' or 'yes'

Free download pdf