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

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

Figure 5-4: I’m old enough to drive in the United States, but my five-year-old
son isn’t.

The only catch is that the last if statement at y feels redun-
dant. If the user is old enough at w, we shouldn’t need to test to
see if they’re too young, because we already know they’re not. And
if the user i sn’t old enough at w, we shouldn’t need to test to see if
they’re too young at y, because we already know they are. If only
Python had a way of getting rid of that unnecessary code... well,
it just so happens that Python does have a shorter, faster way to
handle situations like this one.

else Statements


Often we want our program to do one thing if a condition evaluates
to True and something else if the condition evaluates to False. This
is so common, in fact, that we have a shortcut, the else statement,
that allows us to test if the condition is true without having to per-
form another test to see if it’s false. The else statement can only be
used after an if statement, not by itself, so we sometimes refer to
the two together as an if-else. The syntax looks like this:

if condition:
indented statement(s)
else:
other indented statement(s)

If the condition in an if statement is true, the indented state-
ments under the if are executed, and the else and all its statements
are skipped. If the condition in the if statement is false, the program
skips directly to the else’s other indented statements and runs those.
We can rewrite OldEnough.py with an else statement to
remove the extra conditional test (your_age < driving_age). This not
Free download pdf