Coding Tutorials

Python if, elif and else: make decisions in code

Flat illustration of a fork in a path with two signs, for Python if and else decisions

A condition in Python lets a program run one block of code and skip another, based on a test that is true or false. The if statement holds the test, and the indented block under it runs only when the test is true. When the test is false, Python moves past that block and keeps going with the next lines.

Elif adds more tests in order, and else covers every case the earlier tests did not catch. Together, they form a chain where at most one block runs. That chain is the core of decisions in code, from checking a password length to choosing a message based on a score. The rest of this guide builds that chain step by step, with examples you can change and rerun.

A first decision with if and else

The example below checks an age and prints a different message for each outcome. Change the age value, save, and run the file again to see the other branch run. That small change is the fastest way to feel how a condition works, because the output changes while the code stays almost the same.

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

The test age >= 18 compares the stored age with 18 and gives a true or false result. The colon at the end of the if line tells Python that a block follows, and the indented print line is that block. The else line has no test and no colon problem to solve: it simply says what to do when the if test is false. Without the else, a false test would print nothing, which is fine when silence is the right result, but not when the user needs a message.

Comparison operators are the tools for building tests. The table below lists the ones used most often, with a short reading of each. The official Python docs list these under comparisons, and they work for numbers and for other types where an ordering or equality makes sense.

OperatorMeaningExample test
==Equal toscore == 100
!=Not equal toname != "guest"
>Greater thanage > 18
<Less thantemperature < 0
>=Greater than or equal toage >= 18
<=Less than or equal toscore <= 50

Add more choices with elif

A single if and else handles two outcomes. Elif handles a third, a fourth, and more, without nesting a new if inside the else block. Python checks the tests from top to bottom. The first test that is true wins, its block runs, and the rest of the chain is skipped. That order matters, because a broad test placed first can hide a narrower test placed later.

score = 72
if score >= 90:
    print("Excellent")
elif score >= 70:
    print("Good")
elif score >= 50:
    print("Pass")
else:
    print("Needs more work")

With a score of 72, the first test fails, the second test passes, and the message is Good. The later tests are not checked at all, even though 72 is also greater than or equal to 50. That is why the tests are written from the highest boundary down. If the order were reversed, with the lowest boundary first, every passing score would match the first test and the higher messages would never appear.

Combine tests with and, or and not

Sometimes one test is not enough. A login check might need a name and a password, a discount might need a member flag or a high total, and a warning might need a value that is not in range. Python provides and, or, and not for those cases. With and, every part must be true. With or, at least one part must be true. With not, a true test becomes false, and a false test becomes true.

is_member = True
total = 40
if is_member and total >= 30:
    print("Discount applies")
if is_member or total >= 100:
    print("Free delivery check passed")
if not is_member:
    print("Guest checkout")

Read a combined test aloud before you trust it. If the sentence sounds confusing, split it into named variables first, so each part has a clear name. For example, store has_discount as the result of a combined test, then test that name in the if line. That extra line costs nothing at run time in a beginner program, and it makes the decision far easier to read a week later.

Conditions also work inside other blocks, and they work with values stored in variables and data types from the earlier guide. A condition can test text, numbers, and true or false flags, and it can sit inside a loop so the decision is repeated for each item. When a decision needs to be reused in many places, moving it into a function keeps the test in one place and the call sites short.

Common mistakes to watch for

Missing the colon at the end of an if, elif, or else line is the most common syntax mistake with conditions. Python reports it as a syntax error, and the fix is to add the colon. A missing colon is easy to spot once you know to look for it, because the line reads like a complete sentence without the mark that tells Python a block follows.

Using one equals sign in a test instead of two is a different kind of mistake. A single equals sign assigns a value, so writing if score = 100 does not test anything, and Python reports a syntax error for that line in a condition. The fix is to use two equals signs for comparison. That distinction was introduced in the variables guide, and conditions are where it starts to bite in practice.

Inconsistent indentation breaks a condition even when the tests are right. Lines in the same block must use the same indentation, and the else line must line up with the if line it belongs to. If an else line is indented too far, Python treats it as part of the previous block, and the program either fails or behaves in a way that looks unrelated to the change you just made. Keep indentation consistent, and use spaces throughout a file.

Writing overlapping tests in the wrong order is a logic mistake, not a syntax mistake, so Python will not report it. The program runs, but it gives the wrong message for some values. The fix is to test boundary values one by one, as described in the checklist above, and to reorder the tests so the most specific or highest boundary comes first. A test table on paper, with one row per boundary, catches this error faster than staring at the code.

Limits of this guide

This guide covers if, elif, and else with comparisons and simple combinations. It does not cover pattern matching, which is a newer Python feature for matching structured values, or the conditional expression that fits a short choice on one line. Both have their place, but they are not needed to make clear decisions, and they can hide logic when used too early. This guide also does not cover how to validate user input in depth, which needs its own treatment of text input, conversion, and error handling.

Worked example: a ticket price by age

A ticket price example shows how elif chains handle several ranges in order. The program below starts with an age, then walks down the branches until one test passes. Only the first passing branch runs, which matters when the ranges overlap in wording, because the order of the branches decides the result for ages on a boundary.

age = 15
if age < 12:
    price = 5
elif age < 18:
    price = 8
else:
    price = 12
print("Price:", price)

Trace the example with age 15. The first test asks whether 15 is less than 12, which is false, so that branch is skipped. The second test asks whether 15 is less than 18, which is true, so price becomes 8 and the rest of the chain is skipped. Changing age to 11 or 20 and tracing again is a good exercise, because it shows how the same code picks a different branch for each input.

Boundary values deserve a deliberate test. Try age 12 and age 18 in the example and check the price each time. Those are the values where one branch stops applying and the next starts, and they are the values where a wrong comparison, such as using less than instead of less than or equal to, first shows up. Testing boundaries is a habit that carries into every later program.

Compare conditions in a table

Conditions use comparison operators to test values, and each operator has a plain meaning. The table below lists the common ones, with a short example for each. Reading the table slowly helps, because two operators cause most beginner errors. One is the difference between = for assignment and == for comparison, and the other is the difference between a single comparison and a chained test.

OperatorMeaningExample
==Equal toage == 18
!=Not equal toage != 18
<Less thanage < 18
<=Less than or equal toage <= 18
>Greater thanage > 18
>=Greater than or equal toage >= 18

Using = inside a condition is a common mistake, because Python reads it as an attempt to assign a value, which is not allowed in that spot, and it reports a syntax error. The fix is to use == when the question is whether two values are equal. Writing the comparison out loud before typing it helps. Say "is age equal to 18" and the double equals sign follows naturally.

Chained comparisons are a Python shorthand worth knowing once the basics are firm. Writing 12 <= age < 18 tests both ends of a range in one line, and it reads like the range it describes. It is not required for beginner code, and a pair of tests joined with and gives the same result, so either form is fine as long as the range logic is clear.

Nested decisions and when to flatten them

A decision inside another decision is called nesting, and it appears when a second question only matters after the first answer is known. The example below first checks whether a member flag is true, and only then checks the age, because the member discount only applies to members. Nesting matches that logic directly, and it keeps the inner test from running for people it does not apply to.

is_member = True
age = 20
if is_member:
    if age >= 18:
        print("Member adult price")
    else:
        print("Member young price")
else:
    print("Standard price")

Deep nesting gets hard to read fast, because each level pushes the code further right and the reader must hold several tests in mind at once. When a nested block grows past two levels, it is often clearer to combine tests with and, or to move the inner block into a function with a clear name. That move does not change the logic, and it gives the reader a named step instead of a deeper indent.

A practical way to check nested code is to list the paths through it. For the example above, the paths are member adult, member young, and standard. Walk one path at a time with a concrete value for each variable, and confirm the printed message matches the path. If a path cannot be reached with any values, that branch may be dead code, and removing it makes the program easier to trust.

Truthiness: values that act as true or false

Python lets a condition test a value directly, without comparing it to True or False. An empty string, an empty list, and the number zero count as false in that test, while a non-empty string, a non-empty list, and any non-zero number count as true. That rule is called truthiness, and it is used for short checks such as whether a list holds any items at all.

items = ["pen", "book"]
if items:
    print("There are items to show")
else:
    print("The list is empty")

Truthiness is handy, yet it can hide intent when the value might be zero for a real reason. A count of zero is a real answer, and treating it as false can make a program skip a step it should run. When the question is really about a number, compare the number directly, for example count == 0, so the reader sees the exact test being made.

For the same reason, comparing a value to True with == is rarely needed. Writing if is_member is clearer than writing if is_member == True, because the variable already holds a true or false value. The shorter form also avoids a subtle trap, where a value that counts as true in a direct test is not equal to True under ==, even though both forms feel similar at first glance.

Frequently asked questions

How many elif blocks can one if have?

As many as the decision needs. Python checks them in order and runs the first block whose test is true, then skips the rest. Keep the list short enough to read, and use a table or a function if the list keeps growing.

Can a condition test more than one thing?

Yes, with and and or. With and, every part must be true. With or, at least one part must be true. Brackets help when a test mixes and and or, because they make the intended grouping clear.

Is else always needed?

No. An if on its own is fine when nothing special should happen in the other case. Add else only when the other case needs its own action, such as a message or a fallback value.

What is the difference between = and == in a condition?

A single = assigns a value to a name, while == tests whether two values are equal. Using = inside an if line causes a syntax error, because assignment is not allowed in that spot, so == is the form to use for a comparison.

Can I test a range in one condition?

Yes, a chained comparison such as 12 <= age < 18 tests both ends of a range in one line. A pair of tests joined with and gives the same result, so either form works as long as the range logic is clear.

How deep should nested if blocks go?

Two levels are usually easy to follow, while deeper nesting gets hard to read and to test. When a block grows deeper, combining tests with and or moving the inner block into a function keeps the logic visible.

Sources