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

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

Notice that when we use an even number of sides, the alter-
nating shapes form separate legs of the spiral, as shown at the
top in Figure 5-6. But when the number of sides is odd, each leg
of the spiral alternates with the even (rosette) shape and the odd
(polygon) shape. With color and some thought, you can make this
program draw a design like the one in Figure 5-1. The if-else
statements add another dimension to our programming toolkit.

elif Statements


There’s one more useful add-on to an if statement: the elif clause.
No, that’s not one of Santa’s helpers! An elif is a way to string
together if-else statements when you need to check for more
than two possible outcomes. The keyword elif is short for “else if.”
Think about letter grades in school: if you score 98 percent on an
exam, the teacher might assign a grade of A or A+ depending on
the grading scale. But if you score lower, there’s not just one grade
(there are more options than A or F, thank goodness). Instead,
there are several possible grades your teacher might use: A, B, C,
D, or F.
This is a case where an elif statement or a set of elif state-
ments can help. Let’s take the example of a 10-point grading scale,
where 90 or above is an A, 80–89 is a B, and so on. If your score
is 95, we can print the letter grade A and skip all other options.
Similarly, if you earned an 85, we don’t need to test further than
a B. The if-elif-else construct helps us do this in a straight forward
way. Try running the following program, WhatsMyGrade.py, and
entering different values between 0 and 100.

WhatsMyGrade.py

u grade = eval(input("Enter your number grade (0-100): "))
v if grade >= 90:
print("You got an A! :) ")
w elif grade >= 80:
print("You got a B!")
x elif grade >= 70:
print("You got a C.")
y elif grade >= 60:
print("You got a D...")
z else:
print("You got an F. :( ")
Free download pdf