Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

More Options: elif

With if and else, a program chooses between two options. Often there are more. A soccer match, for example, ends in one of three ways: the home team wins, the away team wins, or it's a draw. For more options, add elif branches, each with a condition of its own. elif is short for “else if”:

home_goals = 3
away_goals = 2
if home_goals > away_goals:
    print("The home team won!")
elif home_goals < away_goals:
    print("The away team won!")
else:
    print("It's a draw!")

This prints:

The home team won!

The program checks the conditions from top to bottom and runs the block of the first true one. It skips the rest of the branches, even if some of the later conditions are true too. Only if no condition is true does the else block run. You can add as many elif branches as you need, always between the if and the else. The else at the end is optional: without it, nothing runs when no condition is true.

Since the first true condition wins, the order of the conditions matters:

points = 95
if points >= 50:
    print("Passed")
elif points >= 90:
    print("Excellent")

This prints:

Passed

95 points is an excellent result, but the first condition, points >= 50, is already true, so the program never gets to the second one. Put the stricter condition first: points >= 90, then points >= 50.

Instructions

  1. 1

    15 °C isn't weather for a winter coat. Between the if block and else, add an elif branch with the condition temperature > 10 that prints Wear a jacket.

  2. 2

    Add one more elif branch with the condition temperature > 18 that prints Wear a sweater, and change temperature to 20. The program should print Wear a sweater. If it prints Wear a jacket, the condition temperature > 10 comes first and catches 20 degrees too: move the new branch above it.

Back

8/15

  1. 1. The if Statement
  2. 2. Blocks of Code
  3. 3. The else Branch
  4. 4. Quiz: if and else
  5. 5. Comparison Operators
  6. 6. Quiz: Arranging a Condition
  7. 7. Boolean Values
  8. 8. More Options: elif
  9. 9. Quiz: elif
  10. 10. Logical Operators: and
  11. 11. Quiz: and
  12. 12. Logical Operators: or
  13. 13. Logical Operators: not
  14. 14. Nested Conditions
  15. 15. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.