Reading history

Python if, elif and else Statements (With Examples)

4 min read 2 views

Learn Python if, elif and else: how conditions are checked, indentation, and/or/not, truthy values, the one-line if expression and common mistakes.

Programs make decisions all the time: show a warning if the battery is low, give a discount if the cart is big enough, refuse a login if the password is wrong. In Python you make these decisions with if, elif and else. This lesson shows how each one works, how to combine conditions, and the one-line form of if/else.

In this lesson you will learn

  • How if, elif and else choose which block runs
  • Why indentation matters in Python
  • How to combine conditions with and, or and not
  • The one-line conditional expression
  • Which values Python treats as true or false

The if, elif and else Chain

Python checks each condition from top to bottom. It runs the block under the first condition that is true and skips the rest. If none is true, the else block runs. Both elif and else are optional.

temperature = 31

if temperature >= 35:
    print("Heat alert: stay indoors")
elif temperature >= 28:
    print("Warm day: carry water")
elif temperature >= 15:
    print("Pleasant weather")
else:
    print("Cold: take a jacket")

print("Check finished")

Output

Warm day: carry water
Check finished

The temperature is 31. The first test (>= 35) is false, the second (>= 28) is true, so Python prints “Warm day” and jumps past the whole chain. The third test is true too, but it is never checked. That is why the order of elif branches matters: put the strictest test first.

Indentation is the syntax

Python has no curly braces. The lines that belong to an if are the ones indented under it (four spaces is the standard). Each condition line ends with a colon. Forgetting the colon or mixing indentation causes a SyntaxError or IndentationError.

Combining Conditions, Truthiness and One-Line if

age = 20
has_ticket = True
balance = 0

# and / or / not combine conditions
if age >= 18 and has_ticket:
    print("Entry allowed")

if not balance:
    print("Balance is zero, which counts as False")

# conditional expression (one-line if/else)
status = "adult" if age >= 18 else "minor"
print("Status:", status)

# nested if
marks = 72
if marks >= 40:
    if marks >= 80:
        print("Passed with distinction")
    else:
        print("Passed")
else:
    print("Failed")

Output

Entry allowed
Balance is zero, which counts as False
Status: adult
Passed
  • and is true only when both sides are true; or is true when at least one is; not flips a value.
  • Truthiness: 0, 0.0, "", [], {} and None count as false. Almost everything else counts as true. So if not balance: means “if the balance is zero”.
  • Conditional expression: value_if_true if condition else value_if_false picks one of two values in a single line. Use it for short choices only.
  • Nested if: an if inside another if. Keep nesting shallow; two levels is usually the limit before code gets hard to read.

Comparison Operators Used in Conditions

OperatorMeaningExample
==equal tox == 5
!=not equal toname != ""
<, >, <=, >=less / greaterage >= 18
inis a member of"a" in "cat"
isis the same objectx is None

Python also allows chained comparisons such as 18 <= age < 60, which reads exactly like maths.

Common Mistakes

  1. Using = instead of ==. if x = 5: is a syntax error; comparison needs two equals signs.
  2. Writing if x == 1 or 2:. This is always true because 2 on its own is truthy. Write if x == 1 or x == 2: or if x in (1, 2):.
  3. Using else if. Python spells it elif.
  4. Wrong branch order. If >= 15 came before >= 35, a heat alert would never print.

Practice Exercises

Exercise 1. Print “even” or “odd” for a number n using a one-line conditional expression.

Show answer
n = 7
print("even" if n % 2 == 0 else "odd")   # odd

Exercise 2. A year is a leap year if it is divisible by 4 but not by 100, unless it is also divisible by 400. Write the condition.

Show answer
year = 2024
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
    print("Leap year")
else:
    print("Not a leap year")

Frequently Asked Questions

Does Python have a switch statement?

Since Python 3.10 there is match/case, which handles pattern matching. For simple value checks, an if/elif chain or a dictionary lookup is still the most common choice.

How many elif blocks can I use?

As many as you need. Only the first true branch runs, and there is at most one else, which must come last.

Can an if block be empty?

No. If you need a placeholder, write pass inside the block.

Summary

  • if / elif / else run the first block whose condition is true.
  • Indentation defines the block, and each condition line ends with a colon.
  • and, or and not combine conditions; empty and zero values are false.
  • a if cond else b chooses between two values in one line.

Next, learn to repeat code with the Python for loop.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *