VMware ESXi and vSphere Cluster Management

Python if, elif, and else Statements

Learn how Python if, elif, and else statements choose among multiple outcomes using conditions, comparisons, indentation, menus, and nested decisions.

A conditional statement is a control-flow construct that runs code based on whether a condition is true or false. Python uses the Boolean values True and False to make these decisions.

A two-way decision uses if and else: one block runs when a condition is true, and the fallback block runs when it is false. A multi-way decision uses if, one or more elif clauses, and an optional else to choose among several alternatives.

Purpose of if, elif, and else

The if clause is the first branch. An elif clause, short for “else if,” adds another condition between the initial if and the optional final else. Use an if-elif-else chain when a program should select one outcome from several possible outcomes.

temperature = 28

if temperature >= 30:
    print("It is hot.")
elif temperature >= 20:
    print("It is mild.")
else:
    print("It is cool.")

In this example, the program selects one message. It does not run every block whose condition might eventually be true.

Basic syntax and structure

The general pattern contains one required if clause, zero or more elif clauses, and one optional final else clause.

if condition:
    statements
elif another_condition:
    statements
else:
    statements
  • At least one if clause is required.
  • You can repeat elif as many times as needed.
  • The else clause is optional and must be last.
  • Each clause header ends with a colon (:).
  • Statements belonging to a branch must be indented.

A code block is a group of statements that belongs to a branch. Python uses consistent indentation to mark the boundary of each block. Four spaces is the usual style.

Clause | Required or optional | When it is evaluated | When its block runs

if | Required | First, before all other branches | When its condition is True

elif | Optional; zero or more | In order, after earlier conditions are False | When its condition is True and no earlier branch matched

else | Optional; at most one | After all if and elif conditions are false | When no preceding condition matched

Evaluation order

Python tests conditions from top to bottom. The first condition that evaluates to True controls the result. Python executes that branch's block, then skips the remaining elif conditions and the else block.

number = 7

if number < 0:
    print("Negative")
elif number < 10:
    print("A single digit")
elif number < 100:
    print("Two digits")
else:
    print("At least three digits")

The second condition is true for 7, so the program prints A single digit. The later conditions are not tested after that match.

The else block is a catch-all branch. It runs only when every preceding if and elif condition is false. An if-elif chain is also valid without an else; in that case, nothing in the chain runs if no condition matches.

Using comparisons in conditions

A condition is an expression that produces a Boolean result, either True or False. Conditions commonly use comparison operators.

Operator | Meaning | Example

== | Equal to | choice == 1

!= | Not equal to | status != "done"

< | Less than | score < 50

> | Greater than | age > 18

<= | Less than or equal to | items <= 10

>= | Greater than or equal to | score >= 90

Do not confuse == with =. The single equals sign assigns a value to a variable. The double equals sign compares two values.

choice = 2       # Assignment: store 2 in choice

if choice == 2:  # Comparison: check whether choice is 2
    print("Option two selected")

Interactive numbered vehicle menu

This example displays five choices, reads a selection with input(), converts the text to an integer with int(), and maps each valid number to a vehicle message.

print("Vehicle menu")
print("1. Bicycle")
print("2. Bus")
print("3. Car")
print("4. Train")
print("5. Boat")

selection = int(input("Select an option: "))

if selection == 1:
    print("You selected a bicycle.")
elif selection == 2:
    print("You selected a bus.")
elif selection == 3:
    print("You selected a car.")
elif selection == 4:
    print("You selected a train.")
elif selection == 5:
    print("You selected a boat.")
else:
    print("Invalid vehicle selection.")

The expression input("Select an option: ") returns text. int() converts numeric text such as "3" into the integer 3, allowing numeric comparisons.

A representative run might look like this:

Vehicle menu
1. Bicycle
2. Bus
3. Car
4. Train
5. Boat
Select an option: 4
You selected a train.

User input | Matching branch | Program result

1 | selection == 1 | Prints that a bicycle was selected

2 | selection == 2 | Prints that a bus was selected

3 | selection == 3 | Prints that a car was selected

4 | selection == 4 | Prints that a train was selected

5 | selection == 5 | Prints that a boat was selected

0, 6, or another out-of-range integer | else | Prints an invalid-selection message

Why condition order matters

Because Python stops at the first match, conditions must be ordered intentionally. This is especially important when tests overlap.

score = 87

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

The highest threshold is tested first. A score of 95 also satisfies score >= 80, but it must reach the A branch first. If the >= 80 test came first, every score of 80 or higher would receive a B.

  • Put higher thresholds before lower thresholds.
  • Put narrow or specific tests before broad tests when they overlap.
  • Keep related alternatives in one conditional chain.
  • Use clear output messages so each branch's purpose is easy to understand.
  • Avoid overlapping conditions unless their order is deliberate.

Nested conditional statements

A nested if statement is an if statement placed inside the code block of another conditional. Nesting is useful when a second decision depends on a successful first decision.

has_account = True
password_correct = False

if has_account:
    print("Account found.")
    if password_correct:
        print("Access granted.")
    else:
        print("Incorrect password.")
else:
    print("No account found.")

When has_account is false, Python skips the nested password check because that check is relevant only after an account is found. Notice that the nested branches are indented farther than the outer branch.

Use nesting when the dependency is real, but avoid unnecessary nesting. Sometimes a single chain or a combined Boolean condition communicates the decision more clearly.

Common errors and troubleshooting

Using assignment instead of comparison

Writing if selection = 1: causes a syntax error because = assigns values. Use if selection == 1: to test equality.

Inconsistent indentation

An IndentationError, or code executing in an unexpected branch, usually means statements in a block are not indented consistently. Indent every statement belonging to the same branch by the same amount.

if ready:
    print("Starting")
    print("Running")

Missing a colon

Every if, elif, and else header needs a trailing colon. For example: else:.

A later branch never runs

An earlier condition may already be matching, or a broad condition may appear before a more specific one. Review the top-to-bottom order and place the most specific or highest-priority tests first.

An else belongs to the wrong if

Align else with the if to which it belongs. In nested code, indentation determines that relationship.

if logged_in:
    if is_admin:
        print("Admin area")
    else:
        print("Regular user area")
else:
    print("Please log in")

Non-numeric menu input

If a user enters a word such as three, int() raises ValueError because the text is not an integer. For robust programs, validate the text before conversion or handle the conversion with try and except.

try:
    selection = int(input("Select an option: "))
except ValueError:
    print("Please enter a whole number.")

Key points

  • if starts a conditional chain and is required.
  • elif adds alternative conditions and is evaluated only after earlier tests are false.
  • else is an optional fallback that runs when no condition matches.
  • Only the first matching branch in an if-elif-else chain runs.
  • Use == for comparison and = for assignment.
  • Colons and consistent indentation are required for correct Python syntax.
  • Order overlapping conditions carefully because earlier branches take precedence.