StudyCatLearn / Practice / Excel
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

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

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.