All lessons

Making decisions · step 10 of 22

elif, and, or, not

9 minMore than two paths, and conditions that combine.

More than two paths

elif ("else if") checks another condition when the earlier ones were false. Python tests them in order and runs the first match it finds.

score = 87
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"
print(grade)      # B

Order matters. With >= 80 written first, a score of 95 would be graded B — always write the strictest condition first.

Combining conditions

and needs both sides true, or needs one of them, not flips a boolean.

age = 20
has_id = True
if age >= 18 and has_id:
    print("Welcome in")

Reading your conditions out loud — "18 or over and has ID" — is the fastest way to check they say what you mean.

Remember this

  • elif adds more branches, checked in order
  • Put the strictest condition first
  • and / or / not combine conditions

Quick quiz

Three questions. 3 correct answers and you have the idea — you can retry as often as you like.

  1. 1. What runs when none of the if/elif conditions match?

  2. 2. If `if score >= 80` is written before `if score >= 90`, where does 95 land?

  3. 3. What does `not (5 > 3)` give?

Answer all three to check them.

Now write it yourself

0/2 passed
1

Practice 1

`score` is set for you. Print a letter grade: `A` for 90 or more, `B` for 80+, `C` for 70+, otherwise `F`.

practice_1.py

Given for you

score = 87
2

Practice 2

`age` and `has_ticket` are set for you. Print `Enter` when the person is 18 or older AND has a ticket, otherwise print `Not yet`.

practice_2.py

Given for you

age = 20
has_ticket = True

Finish with two of three quiz answers correct and every exercise passing, and this lesson is marked complete.