coding180 icon
Coding180
The elif statement: using multiple conditions: Examples and exercises

The elif statement: using multiple conditions: Examples and exercises

Home > Tutorials > Python for beginners > Python Conditional Looping


As a beginner learning Python, you'll quickly discover that programming is all about making decisions. And in order to make informed choices, you need to be able to evaluate multiple conditions at once. That's where the elif statement comes in!

What is the Elif Statement?

The elif statement is short for "else if." It's used in Python to check multiple conditions in a specific order. If the first condition is not met, the elif statement moves on to the next condition, and so on, until a condition is met or the end of the statement is reached.

Here's an example:

x = 5

if x < 2:
    print("x is less than 2")
elif x < 5:
    print("x is less than 5")
else:
    print("x is greater than or equal to 5")

In this example, we're using the if statement to check if x is less than 2. If that condition is not met, the elif statement checks if x is less than 5. If that condition is also not met, the else statement runs, which means that x must be greater than or equal to 5.

Using Multiple Elif Statements

You can use as many elif statements as you need to check different conditions. Here's an example:

score = 90

if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
elif score >= 60:
    print("D")
else:
    print("F")

In this example, we're checking a student's score and using elif statements to assign a letter grade. Notice how we're checking the conditions in descending order, starting with the highest grade.

Exercises

Now that you understand how to use the elif statement, it's time to practice! Here are some exercises for you to try:

  1. Write a program that checks if a number is positive, negative, or zero.
  2. Write a program that checks whether a year is a leap year or not.
  3. Write a program that asks the user for their age and tells them which age group they belong to (child, teenager, adult, senior).

Remember to use the elif statement to check multiple conditions!

Conclusion

The elif statement is an important tool in Python programming that allows you to evaluate multiple conditions in a specific order. By mastering the elif statement, you'll be able to make more informed decisions in your code. Keep practicing with the exercises above, and soon you'll be writing complex programs like a pro!


user

Robort Gabriel

Lagos, Nigeria

Freelance Web Developer, Native Android Developer, and Coding Tutor.

Skills
  • UI / UX
  • JavaScript
  • Python
  • PHP
  • Kotlin
  • Java
  • Bootrap
  • Android
  • Laravel