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

(vip2019) #1

92 Chapter 5


At u, we ask the user for a numeric grade from 0 to 100 with
an input() prompt, convert it to a number with the eval() func-
tion, and store it in the variable grade. At v, we compare the
user’s grade to the value 90 , the cutoff for a letter grade of A. If
the user entered a score of 90 or greater, Python will print You
got an A! :), skip the other elif and else statements, and continue
with the rest of the program. If the score is not 90 or greater, we
proceed to w to check for a grade of B. Again, if the score is 80 or
greater, the program prints the correct grade and skips past the
else statement. Otherwise, the elif statement at x checks for a C,
the elif statement at y checks for a D, and, finally, any score less
than 60 makes it all the way to z and results in the else state-
ment’s You got an F. :(.
We can use if-elif-else statements to test a variable across mul-
tiple ranges of values. Sometimes, though, we need to test multiple
variables. For example, when deciding what to wear for the day, we
want to know the temperature (warm or cold) and the weather (sun
or rain). To combine conditional statements, we need to learn a few
new tricks.

Complex Conditions: if, and, or, not


There are times when a single conditional statement isn’t enough.
What if we want to know if it’s warm and sunny or cold and rainy?
Think back to our first program in this chapter, in which we
answered y if we wanted to draw a spiral. The first two lines asked
for input and checked to see if that input was y:

answer = input("Do you want to see a spiral? y/n:")
if answer == 'y':

To see a spiral, the user has to enter y exactly; only this one
answer is accepted. Even something similar, like capital Y or the
word yes, doesn’t work because our if statement checks only for y.
One easy way to solve the Y versus y problem is to use the
lower() function, which makes strings all lowercase. You can try it
in IDLE:

>>> 'Yes, Sir'.lower()
'yes, sir'
Free download pdf