Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 149 ยท Control Flow

if, elif and else

Make decisions in Python with if, elif and else. Learn how conditions and indentation work, how to avoid deep nesting, and when to use a conditional expression.

So far your programs have run every line from top to bottom. Real programs need to make choices: show an error if the password is too short, charge shipping unless the order is large, pick a greeting based on the time of day. The if statement is how Python makes those choices.

In this lesson you'll write if, elif and else blocks, see how Python decides which branch runs, learn to keep decision logic flat and readable, and meet the one-line conditional expression. Everything builds on the conditions you wrote in Comparison and Logical Operators.

The if statement

An if statement has a condition, a colon, and an indented block of code that runs only when the condition is truthy:

Python Your first if

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Change 31 to 20 and run it again. The two indented lines are skipped, but the last line still runs, because it isn't indented and so isn't part of the if block.

Three rules to get right:

  • The line ends with a colon :. Forgetting it is a SyntaxError.
  • The block is defined by indentation, four spaces per level by convention. Every line in the block must be indented by the same amount, as you learned in Syntax and Indentation.
  • The condition can be any expression. Python judges it by truthiness, so if items: means "if the list isn't empty".

else: the other path

else adds a block that runs when the condition is falsy. Exactly one of the two blocks runs, never both and never neither:

Python if and else

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

else has no condition of its own, and it lines up with its if, not with the block inside it.

elif: choosing among many options

When there are more than two possibilities, chain extra conditions with elif (short for "else if"). Python checks each condition from top to bottom and runs only the first block whose condition is true. If none match, the else block runs, if there is one.

Python Grading with elif

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With a score of 83, the first condition (>= 90) is false, the second (>= 80) is true, so grade becomes "B" and Python skips every remaining branch. That's why the elif score >= 70 line doesn't need to say and score < 80: you only reach it if the earlier checks failed.

Order matters, though. If you put score >= 60 first, every passing score would get a "D". Always list the most specific or strictest conditions first.

Tip: An if with several elifs is different from several separate if statements. Separate ifs are each checked independently, so more than one block can run. Use elif when the options exclude each other.

Combining conditions

Any expression from the operators chapter can be a condition. Combine checks with and, or and not, use chained comparisons, and test membership with in:

Python Real-world conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Each condition reads almost like a sentence. When a condition grows long, give its parts names: is_long_enough = len(password) >= 8 and then if is_long_enough and has_digit:.

Nested if statements

You can put an if inside another if. The inner one is only checked when the outer condition is true:

Python
if user_is_logged_in:
    if cart:
        print("Proceed to checkout")
    else:
        print("Your cart is empty")
else:
    print("Please sign in first")

One level of nesting is fine. Three or four levels become hard to follow. Two techniques help.

Combine conditions when the inner if has no else: if logged_in: if is_admin: is the same as if logged_in and is_admin:.

Return early inside functions. Handle the problem cases first and leave, so the main logic stays at the left margin:

Python Flattening with early returns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Each guard clause deals with one special case and returns. You'll write many functions like this after Functions and Return Values.

Conditional expressions

That cost = 4.99 if weight_kg <= 2 else 9.99 line is a conditional expression, sometimes called the ternary operator. It picks between two values in one line:

Python
value_if_true if condition else value_if_false

Because it's an expression, it produces a value you can assign, print or pass to a function:

Python Conditional expressions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Use conditional expressions for short, simple choices between two values. The last example chains two of them; it works, but it's at the limit of readability. Anything more complicated deserves a full if/elif/else.

Note: Both branches of a conditional expression must be values; you can't put a statement such as an assignment in them. And the else part is required.

Empty blocks with pass

A block can't be empty: Python requires at least one statement after the colon. When you want a branch that does nothing, perhaps while sketching out code, use pass:

Python
if order_total > 100:
    pass  # TODO: apply a discount
else:
    print("No discount")

Common mistakes

A few errors show up again and again in if statements:

  • Using = instead of ==. if total = 0: is a SyntaxError. Python's error message even suggests ==.
  • Mixed indentation. A block whose lines use different amounts of indentation raises IndentationError. Let your editor insert four spaces per level.
  • Comparing with True. if is_ready == True: works, but if is_ready: says the same thing more clearly.
  • Testing the wrong thing. if name == "Ann" or "Bob": is always true, as you saw in Comparison and Logical Operators. Write if name in ("Ann", "Bob"):.
  • Unreachable branches. In if x > 0: ... elif x > 10: ..., the second branch can never run, because anything above 10 is already above 0. Put the stricter test first.

When you're choosing among many specific values rather than ranges, a long elif chain can often be replaced by a dictionary lookup or by the match statement in the next lesson.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. With n = 15, what does this print? if n > 10: print("A") / elif n > 5: print("B") / else: print("C")

    Only the first true branch runs. n > 10 is true, so A prints and the elif is skipped.
  2. 2. What is missing from if total > 50 on its own line?

    An if line must end with a colon. Parentheses are optional and Python has no then keyword.
  3. 3. What does label = "even" if 7 % 2 == 0 else "odd" store?

    7 % 2 is 1, so the condition is False and the expression takes the else value.
  4. 4. How can you flatten if a: with a nested if b: that has no else?

    The inner block only runs when both are true, which is exactly a and b.

Summary

  • if condition: runs an indented block only when the condition is truthy.
  • else: runs when the condition is falsy; elif adds more conditions, and only the first true branch runs.
  • Order elif branches from most specific to least specific.
  • Keep nesting shallow by combining conditions with and and by returning early from functions.
  • a if condition else b is a conditional expression for short choices between two values.
  • Use pass for a block that intentionally does nothing.

Next: Pattern Matching with match, Python's structural way to branch on the shape and value of data.