Kahibaro
Discord Login Register

if, elif, else

The Basic `if` Statement

In this chapter, you’ll focus on how to use if, elif, and else to control which parts of your code run.

A basic if statement checks a condition and runs a block of code only if that condition is True.

age = 20
if age >= 18:
    print("You are an adult.")

How it works:

You can have any number of lines inside the if block:

age = 20
if age >= 18:
    print("You are an adult.")
    print("You can enter the website.")
    print("Enjoy your stay!")

All three print lines run only if age >= 18 is True.

Adding an `else` Block

else is used when you want to run alternative code if the if condition is False.

age = 15
if age >= 18:
    print("You are an adult.")
else:
    print("You are not an adult.")

How it works:

More realistic example:

temperature = 30
if temperature > 25:
    print("It's warm outside.")
else:
    print("It's not very warm today.")

Multiple Choices with `elif`

Sometimes there are more than two possibilities.
That’s what elif is for: “else if”.

Basic pattern:

if condition1:
    # code if condition1 is True
elif condition2:
    # code if condition2 is True and condition1 was False
elif condition3:
    # code if condition3 is True and all above were False
else:
    # code if none of the conditions were True

Example: grading system

score = 72
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")

Important details:

In the example above:

When to Use `if`, `elif`, and `else`

Some common patterns:

`if` only

Use if alone when you only care about one situation and don’t need an “otherwise”.

age = 19
if age >= 18:
    print("You can vote.")

If the condition is False, nothing happens.

`if` + `else`

Use if + else when there are two exclusive options.

number = 3
if number % 2 == 0:
    print("Even")
else:
    print("Odd")

This guarantees one of the two messages is printed.

`if` + `elif` (+ `else`)

Use if + elif when you have several possible categories.

hour = 14
if hour < 12:
    print("Good morning")
elif hour < 18:
    print("Good afternoon")
else:
    print("Good evening")

Here:

Execution Order and “First Match” Rule

With ifelifelse chains, remember:

  1. Conditions are checked in order, from top to bottom.
  2. The first condition that is True is chosen.
  3. After that block runs, the rest of the chain is ignored.

Example:

x = 10
if x > 0:
    print("Positive")
elif x > 5:
    print("Greater than 5")

Even though x > 5 is True, you will only see:

Positive

Because:

To make the second condition work as intended, you’d have to reorder them:

x = 10
if x > 5:
    print("Greater than 5")
elif x > 0:
    print("Positive")

Now the output is:

Greater than 5

Attaching `else` to the Right `if`

An else (and elif) always belongs to the nearest previous if that doesn’t already have an else.

Correct example:

age = 17
if age >= 18:
    print("Adult")
else:
    print("Minor")

Incorrect structure (common confusion):

# This is valid Python, but maybe not what you intended:
age = 17
if age >= 18:
    if age >= 21:
        print("You can drink alcohol (in some countries).")
else:
    print("You are under 18.")

Here, the else is paired with the inner if age >= 21, not the outer one.
So "You are under 18." only runs if age >= 18 is True and age >= 21 is False.

In other words:

You usually want this instead:

age = 17
if age >= 18:
    if age >= 21:
        print("You can drink alcohol (in some countries).")
    else:
        print("You are an adult, but cannot drink alcohol yet.")
else:
    print("You are under 18.")

Notice how indentation makes it clear which else belongs to which if.

Writing Clear Conditions

You can often simplify and clarify your if / elif / else blocks.

Avoid overlapping conditions

Example with overlapping:

score = 85
if score >= 70:
    print("Pass")
elif score >= 80:
    print("Good")

Here, "Good" will never print, because if score >= 80, then score >= 70 is also True, and the first condition already matches.

Better:

score = 85
if score >= 80:
    print("Good")
elif score >= 70:
    print("Pass")

Use `elif` instead of multiple separate `if`s (when appropriate)

Sometimes beginners write:

temperature = 10
if temperature < 0:
    print("Freezing")
if temperature < 15:
    print("Cold")
if temperature < 25:
    print("Mild")

If temperature = 10, all three messages except "Freezing" will print, which might not be what you want.

To choose exactly one category, use elif and else:

temperature = 10
if temperature < 0:
    print("Freezing")
elif temperature < 15:
    print("Cold")
elif temperature < 25:
    print("Mild")
else:
    print("Warm")

Now only one message is printed.

Common Pitfalls with `if` / `elif` / `else`

1. Forgetting the colon `:`

Every if, elif, and else line must end with :.

if age >= 18:
    print("Adult")
elif age >= 13:
    print("Teen")
else:
    print("Child")

If you miss a colon, you’ll get a SyntaxError.

2. Mixing up `==` and `=`

Incorrect:

if x = 10:   # Error!
    print("x is 10")

Correct:

x = 10
if x == 10:
    print("x is 10")

3. Indentation mistakes

Blocks under if, elif, and else must be consistently indented.

Incorrect:

age = 20
if age >= 18:
print("Adult")   # Not indented → error

Correct:

age = 20
if age >= 18:
    print("Adult")

Or with multiple lines:

age = 20
if age >= 18:
    print("Adult")
    print("Welcome!")

All lines in the block must be indented the same amount.

Small Practice Ideas

Here are a few small programs you can try to write using if, elif, and else:

  1. Day of the week greeting
    • Ask the user to enter a number from 1 to 7.
    • If 1 → print "Monday", if 2 → "Tuesday", …, if 7 → "Sunday".
    • Use if / elif / else to handle it.
  2. Ticket price based on age
    • If age < 3 → "Free".
    • If age is 3–12 → "Child ticket".
    • If age is 13–64 → "Adult ticket".
    • If age is 65 or older → "Senior ticket".
  3. Simple login check
    • Store a correct password in a variable.
    • Ask the user to input a password.
    • If it matches → "Access granted", else → "Access denied".

As you practice, pay attention to:

Views: 16

Comments

Please login to add a comment.

Don't have an account? Register now!