First If

Home / Guides

If Else Statement: How to Make Your Code Choose a Path

An if statement lets your code skip. An if else statement lets it choose — and a program that always picks one of two paths has no silent gap for bugs to hide in.

An if statement lets you skip code. An if else statement lets you choose. The difference sounds small and it is not: a lone if leaves a gap where nothing happens, and a gap is where bugs live. Once you add else, the program has no silent third option — it does one thing or the other, every single time.

python
if temperature > 25:
    print("Wear shorts.")
else:
    print("Bring a jacket.")

Two paths, one decision, no gaps. Whatever the temperature is, one of those lines runs and the other does not.

What else actually does

else means "in every other case". It takes no condition, because it is not a question — it is the catch-all that runs when the if's condition came out false. It is attached to the if above it, and it belongs to the same block level.

That is why else is optional but rarely accidental. Leaving it off says: doing nothing is a valid outcome here. Sometimes that is true, as when you check whether a value exists before using it. But when the program must always produce an answer for the user, an if without an else means there is a state where the user gets silence.

A real example: the login screen

python
entered = input("Password: ")

if entered == saved_password:
    print("Welcome back.")
    show_dashboard()
else:
    print("That password does not match.")
    attempts = attempts + 1

Both branches do work. The true branch opens the app; the false branch tells the person what happened and counts the failure. Now imagine the same program with else removed: a wrong password would produce no message at all and the screen would sit there. The user would assume it froze. That is what a missing else feels like from the outside.

Three paths and more: the else if chain

Most real rules have more than two outcomes. Grades are the classic example — scores map onto letters:

python
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"

Python spells it elif; JavaScript, Java, C#, PHP and Go spell it else if; Ruby spells it elsif. Same idea everywhere: test another condition, but only if everything above failed.

Order is logic, not style. Each branch is only tested when every branch above it was false. If you move the >= 70 check to the top, a score of 95 matches it first and everyone gets a C. The chain reads top to bottom, first match wins, and the rest is skipped.

Because the first match wins, you can write the conditions loosely. In the example above, the >= 80 branch does not need to say "and less than 90" — everything below 90 has already failed the first test. That is the useful, non-obvious trick of an else if chain: each test only has to rule out what is left.

Nested ifs, and why you should flatten them

You can put an if statement inside another one. It works, it is legal, and it is usually a sign that the code is about to become hard to read:

python
if user_is_logged_in:
    if account_is_active:
        if has_permission:
            show_admin_panel()

Three levels deep and the reader is holding three conditions in their head at once. The version below says the same thing and can be read in one pass — this pattern is called a guard clause:

python
if not user_is_logged_in:
    return
if not account_is_active:
    return
if not has_permission:
    return

show_admin_panel()

Each check bails out early, so by the time you reach the interesting line, every requirement has already been confirmed. When you find yourself nesting, ask whether the conditions could sit side by side instead. Usually they can.

The one-line form, and when to avoid it

Most languages offer a compact if/else that produces a value instead of running a block. Python calls it a conditional expression, everything else calls it the ternary operator:

javascript
const label = age >= 18 ? "adult" : "minor";

Use it when both outcomes are short and the whole line still fits your eye. Do not use it when either outcome is a function call with side effects, and never nest one inside another — a nested ternary is the single most reliable way to make a line of code unreadable.

Combining conditions instead of nesting

Two conditions that must both be true belong in one condition, joined by and:

python
if age >= 18 and country == "US":
    show_us_adult_offer()

Two conditions where either will do belong with or. And when a combination gets long, name it:

python
free_shipping_eligible = total > 50 or customer_is_member

if free_shipping_eligible:
    apply_free_shipping()

That intermediate variable is not busywork. It names the rule, it can be printed when the rule misbehaves, and it can be tested on its own.

How each language spells if/else

LanguageSpellingBlock
Pythonif / elif / elseindentation + colon
JavaScriptif / else if / elseparentheses + braces
Java, C#, PHPif / else if / elseparentheses + braces
Rubyif / elsif / elseend
Goif / else if / elseno parentheses, braces required

Notice that only the punctuation moves. The decision — which condition, which order, which fallback — is identical in every column. Learn the thinking once and the syntax becomes a lookup.

Mistakes worth knowing before you make them

  1. The unreachable branch. if score >= 60 ... elif score >= 80 — the second can never run, because 80s already passed the first test. Write chains from the narrowest condition to the widest, or the other way round, but never out of order.
  2. The inverted else. When both branches are one line, it is easy to swap them. Print something distinctive in each branch while you test, then delete the prints.
  3. Two elses. An if has one else. If you find yourself wanting a second, you wanted else if.
  4. Missing the default case. An if/else if chain with no final else silently does nothing for the values it does not expect — which is how "status: undefined" ends up on a customer's screen. End the chain with an else that handles the unexpected.
  5. Comparing strings carelessly. "Yes", "yes" and "YES " are three different strings. Normalise the input once, before the comparison.

Practice

  1. Write a ticket price rule: under 5 is free, 5 to 17 is 8, 18 to 64 is 15, 65 and over is 10. Test with 4, 5, 17, 18, 64, 65 and 90. Every one of those numbers should produce the price you expect — this is how you find out that > and >= are not the same word.
  2. Write a login that prints a different message for the right password, the wrong password, and an empty field.
  3. Take the three-level nested example above and rewrite it with guard clauses. Compare line counts and notice which version you would rather debug at 6pm.

The takeaway

An if statement asks a question. An if/else statement answers it. Add else whenever the user deserves to be told something either way, order your else if branches from narrow to wide, and flatten nesting before it flattens you.

Common questions

Is else required?

No. else is optional. Leave it off when doing nothing is a correct outcome, and add it when the program must always pick one of two paths.

What is the difference between else if and else?

else if checks another condition, so the chain keeps testing until one matches. else catches everything that is left, with no condition at all.

Can I use more than one else?

No. A single if statement has one else at most. For a third path you use else if, which can appear as many times as you need.

Why does my else if never run?

Usually because an earlier branch already matched. Conditions are tested from top to bottom and the first true one wins, so the order of the branches is part of the logic.

Ask a question

Not sure why your if never runs? Send it over.

Your message comes straight to the person who writes the guides. We answer real questions.

Powered by LunaNineAI.com

This is a demo version of this site.

Contact us to claim this site.