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

(vip2019) #1

94 Chapter 5


Now we’re testing if either of two conditions is True. If either
is True, the user gets to see the spiral. Notice that we write the
full conditional on either side of the or keyword: answer == 'y' or
answer == 'yes'. One common error for new programmers is try-
ing to shorten or conditions by leaving out the second answer ==. To
remember the right way to use an or statement, think about each
condition separately. If any of the conditions joined by an or evalu-
ates to True, the whole statement is true, but each condition has to
be complete for the statement to work.
A compound condition using and looks similar, but and requires
every condition in the statement to be true for the overall statement
to evaluate to True. For an example, let’s write a program to decide
what to wear based on the weather. Type W hatToWear.py in a new
window or download it from http://www.nostarch.com/teachkids/,
and run it:

WhatToWear.py

u rainy = input("How's the weather? Is it raining? (y/n)").lower()
v cold = input("Is it cold outside? (y/n)").lower()
w if (rainy == 'y' and cold == 'y'): # Rainy and cold, yuck!
print("You'd better wear a raincoat.")
x elif (rainy == 'y' and cold != 'y'): # Rainy, but warm
print("Carry an umbrella with you.")
y elif (rainy != 'y' and cold == 'y'): # Dry, but cold
print("Put on a jacket, it's cold out!")
z elif (rainy != 'y' and cold != 'y'): # Warm and sunny, yay!
print("Wear whatever you want, it's beautiful outside!")

At u, we ask the user whether it’s raining outside, and at v,
we ask if it’s cold or not. We also make sure the answers stored in
rainy and cold are lowercase by adding the lower() function to the
end of the input() functions on both lines. With these two condi-
tions (whether it’s rainy and whether it’s cold), we can help the
user decide what to wear. At w, the compound if statement checks
to see if it’s both rainy and cold; if it is, the program suggests a
raincoat. At x, the program checks to see if it’s both rainy and not
cold. For rainy but not cold weather, the program recommends an
umbrella. At y, we check to see if it’s not raining (rainy not equal
to 'y') but still cold, requiring a jacket. Finally, at z, if it’s not
raining and it’s not cold, wear whatever you want!
Free download pdf