if, elif, else Conditions in Python

If, elif and else are used in Python so that our program runs different code according to different conditions. If a condition is True then do one thing, else do another thing - this is their job.

1. if Statement

If is the most basic condition. It checks whether the given condition is True or not. If it is True then the code inside it will run, else it will be skipped.

Condition is a boolean expression which answers in True or False. In Python, the code coming after if is indented (i.e. written by giving 4 spaces or tabs), so that Python knows that this code is part of the same condition.

Syntax:

if condition:
    # This code will run if the condition is True

Example:

age = 20

if age >= 18:
    print("You are old enough to vote.")

2. else Statement

else means - if the above if becomes False, then run this code.

It always comes after if, it cannot be written alone.

Syntax:

if condition:
    # If the condition is True, then this code will run
else:
    # If the condition is False, then this code will run

Example:

age = 16

if age >= 18:
    print("You are old enough to vote.")
else:
    print("You are not old enough to vote.")

In the above example, age >= 18 is False, so the else code will run.

3. elif Statement

elif means - else if.

It is useful when more than one condition has to be checked.

Python will first check the if, if it is False then it will go to the first elif, then the next, and as soon as any is found True, the rest of the conditions will not be checked.

You can put as many elifs as you want.

Syntax:

if condition1:
    # code if condition1 is True
elif condition2:
    # code if condition2 is True
else:
    # code if all the above conditions are False

Example:

score = 85

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

If score >= 90 is False, then Python goes to the next elif. score >= 80 is True, so "Grade: B" is printed and the rest of the conditions are not checked.

4. Important Things and Tips

  • Take care of indentation: Use space/tab properly in Python. If there is any mistake, IndentationError will come.
  • Understand Boolean Expressions: The result of condition is always True or False. You can make complex condition by combining comparison operators (==, !=, <, >, <=, >=) and logical operators (and, or, not).
  • Order matters: Keep the order of elifs correct. Python checks from top to bottom, and as soon as the first one is found to be True, the rest are skipped.
  • Take care of readability: Write the code neatly and understandably. Use parentheses () in complex conditions so that the reader understands what you are checking.

Next Lesson: Python Nested Conditions

Scroll to Top