CSCI 127 Joy and Beauty of Data · Unit 1: Data types · on Exam 1
1.4 Selection: if, elif, else
Study notes for Selection: if, elif, else in CSCI 127 Joy and Beauty of Data at Montana State University: the big ideas, code you should know, a worked example, common mistakes and an exam tip. The same topic has endless practice questions and flashcards in StudyCat.
Big ideas
if condition:runs a block when the condition is true;eliftests another condition only if the earlier ones failed;elsecatches everything else. Only one branch of a chain runs.- Comparisons:
== != < <= > >=. Combine withand,or,not;andbinds tighter thanor, so use parentheses when mixing. - Chained comparisons read like math:
0 <= x < 10. - Every value has a truth value:
0,0.0,"",[]andNoneare false; everything else is true. - Nested ifs work, but flat
elifchains are easier to read. Put the most specific test first when ranges overlap.
Code you should know
Letter grade with elif
score = int(input("Score? "))
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(grade)Output
B
Boolean logic
age = 20
has_id = False
print(age >= 18 and has_id)
print(age >= 18 or has_id)
print(not has_id)
print(15 <= age < 65)
print(bool(0), bool(""), bool("no"), bool([]))Output
False True True True False False True False
Even, odd, FizzBuzz
for n in range(1, 16):
if n % 15 == 0:
print("FizzBuzz")
elif n % 3 == 0:
print("Fizz")
elif n % 5 == 0:
print("Buzz")
else:
print(n)Output
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz (one per line)
Worked example
What prints for
x = 7?if x > 5:
print("big")
if x > 6:
print("bigger")
else:
print("small")Show the solution
big then bigger. The two ifs are separate statements, so both tests run; the else belongs only to the second one and is skipped.Common mistakes
- Testing
score >= 70beforescore >= 90in a chain, so an A gets a C. - Writing
if x == 1 or 2:, which is always true. You needx == 1 or x == 2. - Using
=in a condition. - Forgetting that separate
ifs all run while anif/elifchain runs one branch.
Exam tipWhen a problem gives ranges, write the tests from the top of the scale down (or the bottom up) so each
elif only has to check one edge.Keep going in StudyCat
StudyCat is free for Montana State students: an endless quizzer with worked explanations, one-question lessons, flashcards, exam prep checklists, the class calendar with every deadline, a grade calculator and a study board for CSCI 127.