If Else in Python: The Complete Guide to Conditional Statements
Every useful program eventually has to make a decision. Should the user be let in or shown an error? Is the cart empty or full? Has the file finished downloading? In Python, the tool for making those decisions is the conditional statement — the family of `if`, `if/else`, and `if/elif/else` constructs that run a block of code only when a condition is `True`.
If you are searching for if else python or how the if statement works, this guide covers the whole picture: the syntax, the operators that go inside conditions, truthiness, the ternary expression, the modern `match` statement, and — most importantly — the indentation rule that trips up nearly every beginner and quietly makes Python one of the most readable languages in existence.
Key Takeaways
• An `if` statement runs a block of code only when its condition evaluates to `True`; `else` handles every other case, and `elif` adds extra branches in between.
• Indentation is syntax, not style. Python uses whitespace — not braces `{}` — to decide which lines belong to a block. Four spaces per level is the convention.
• Conditions are built from comparison operators (`==`, `!=`, `<`, `>`) and logical operators (`and`, `or`, `not`).
• Truthiness lets you write `if x:` directly — empty containers, `0`, `””`, and `None` are *falsy*; almost everything else is *truthy*.
• The three classic beginner errors are using `=` instead of `==`, forgetting the colon `:`, and inconsistent indentation.
What does a conditional statement actually do in Python?
A conditional statement evaluates an expression that resolves to either `True` or `False`, then decides whether to run an indented block of code based on that result. That is the entire concept. The condition is the question; the block is what happens when the answer is yes.
“`python temperature = 38
if temperature > 37.5: print(“You have a fever.”) print(“Consider resting today.”)
print(“Done checking.”) “`
Output:
“` You have a fever. Consider resting today. Done checking. “`
The two `print` lines inside the `if` ran because `38 > 37.5` is `True`. The final `print` is not indented, so it sits outside the `if` and runs no matter what. Change `temperature` to `36` and the first two lines vanish from the output — only `Done checking.` remains.
How do you write a basic if statement in Python?
The anatomy of an `if` statement is small but exact:
“`python if condition:
do_something() “`
Three things are mandatory, and missing any one of them is an error:
- The keyword `if`.
- A colon `:` at the end of the line.
- An indented block beneath it.
Here is a working example with no `else` at all — an `if` is perfectly valid on its own:
“`python balance = 250
if balance < 0: print("Account overdrawn!")
print(“Balance check complete.”) “`
Output:
“` Balance check complete. “`
Because `250 < 0` is `False`, the `print("Account overdrawn!")` line is skipped entirely. Notice there is no `else` — Python simply does nothing and moves on.
The whitespace is load-bearing. Most languages use braces `{ }` to mark which lines belong to an `if`. Python made a deliberate, opinionated choice: it uses the *actual indentation* of your code as the syntax. This is the language’s quiet superpower. Because the visual structure of the code and its logical structure are forced to be identical, you literally cannot write an `if`-block whose indentation lies about what it controls. That is why Python written by any author tends to look the same and read clearly — the formatting *is* the program. It is also why the two most common beginner errors are indentation-related: an `IndentationError`, or code that silently runs outside the `if` because it was indented one space wrong. And it is why mixing tabs and spaces produces baffling bugs — to Python, they are different characters marking different block levels. The mental shift is this: in Python, the indentation is the block. Line your code up consistently — spaces, four per level by convention — and your `if/elif/else` structure becomes correct and self-documenting at the same time. The whitespace you might ignore in another language is doing real work here.
How does if/else work in Python?
An `else` block catches everything the `if` condition did *not* catch. There is no condition on `else` — it is the fallback for “in all other cases.”
“`python age = 16
if age >= 18: print(“You can vote.”) else: print(“You are too young to vote.”) “`
Output:
“` You are too young to vote. “`
Exactly one of the two branches always runs — never both, never neither. The `if` and its matching `else` must be aligned at the same indentation level, and each owns its own indented block below it.
How do you handle multiple conditions with if/elif/else?
When you have more than two possible outcomes, `elif` (short for “else if”) lets you chain conditions. Python checks them top to bottom and runs the block for the *first* condition that is `True` — then skips the rest entirely.
“`python score = 82
if score >= 90: grade = “A” elif score >= 80: grade = “B” elif score >= 70: grade = “C” elif score >= 60: grade = “D” else: grade = “F”
print(f”Your grade is {grade}.”) “`
Output:
“` Your grade is B. “`
Because `82 >= 90` is `False` but `82 >= 80` is `True`, Python assigns `”B”` and never even evaluates the `C`, `D`, or `else` branches. Order matters: if you had put `score >= 60` first, every passing score would be graded `”D”`. Always arrange conditions from most specific to least specific.
Here is a quick reference for which form to reach for:
| Conditional form | Use it when | Example shape |
|---|---|---|
| `if` alone | You want to do something *only* when a condition is true | `if user.is_admin:` |
| `if` / `else` | There are exactly two outcomes | `if logged_in:` … `else:` |
| `if` / `elif` / `else` | There are three or more mutually exclusive cases | grade bands, menu choices |
| Ternary expression | You are choosing one *value* between two options | `status = “on” if flag else “off”` |
| `match` statement | You are matching one value against many fixed patterns | command/HTTP-status dispatch |
What operators go inside a Python condition?
Conditions are built from two kinds of operators: comparison operators that compare two values, and logical operators that combine multiple conditions.
The comparison operators () each return a boolean:
“`python print(5 == 5) # True — equal to print(5 != 3) # True — not equal to print(7 > 10) # False — greater than print(7 < 10) # True — less than print(7 >= 7) # True — greater than or equal print(7 <= 6) # False — less than or equal ```
The logical operators — `and`, `or`, `not` — combine boolean values. (For the full set including arithmetic and bitwise operators, see .)
“`python age = 25 has_ticket = True
if age >= 18 and has_ticket: print(“Welcome to the show.”)
if not has_ticket: print(“Please buy a ticket.”) else: print(“Enjoy!”) “`
Output:
“` Welcome to the show. Enjoy! “`
- `and` is `True` only when both sides are true.
- `or` is `True` when at least one side is true.
- `not` flips a boolean to its opposite.
Python also lets you *chain* comparisons in a way most languages do not, which reads almost like math:
“`python temperature = 22
if 18 <= temperature <= 25: print("Room temperature is comfortable.") ```
Output:
“` Room temperature is comfortable. “`
`18 <= temperature <= 25` is genuinely equivalent to `18 <= temperature and temperature <= 25`, just cleaner.
When should you nest if statements — and when should you flatten them?
You can place an `if` inside another `if`. This is nesting, and it is sometimes the clearest way to express a multi-step check.
“`python user_logged_in = True is_admin = False
if user_logged_in: if is_admin: print(“Showing admin dashboard.”) else: print(“Showing user dashboard.”) else: print(“Please log in.”) “`
Output:
“` Showing user dashboard. “`
But deep nesting quickly becomes hard to read — every level adds another four spaces of indentation, pushing your real logic further to the right (the so-called “arrow anti-pattern”). Often you can flatten nested conditions by combining them with `and`, or by returning early:
“`python def get_dashboard(user_logged_in, is_admin): if not user_logged_in: return “Please log in.” if is_admin: return “Showing admin dashboard.” return “Showing user dashboard.”
print(get_dashboard(True, False)) “`
Output:
“` Showing user dashboard. “`
Same logic, no nesting, much easier to follow. As a rule of thumb: if you find yourself three levels deep, look for a way to flatten.
What is truthiness, and why can you write `if x:`?
Python does not require your condition to be an explicit comparison. Any value can be tested for truthiness directly. The rule: a value is falsy if it represents “nothing,” and truthy otherwise.
Falsy values include: `False`, `None`, `0`, `0.0`, `””` (empty string), `[]` (empty list), `{}` (empty dict), and `()` (empty tuple). Almost everything else is truthy.
“`python items = []
if items: print(f”You have {len(items)} item(s).”) else: print(“Your cart is empty.”)
name = “Ravi”
if name: print(f”Hello, {name}!”) “`
Output:
“` Your cart is empty. Hello, Ravi! “`
Writing `if items:` is more idiomatic — and more readable — than `if len(items) > 0:`. This truthiness rule is the same one that powers conditions inside , where `while` checks the same way.
How do you write a one-line if/else (the ternary expression)?
When you only need to choose between two *values*, a full `if/else` block is overkill. Python’s conditional expression (often called the ternary operator) does it on one line. The shape is `value_if_true if condition else value_if_false`.
“`python age = 20
status = “adult” if age >= 18 else “minor” print(status) “`
Output:
“` adult “`
It reads almost like English: “status is ‘adult’ if age is at least 18, else ‘minor’.” Use it for simple value selection. If the logic is complex or has side effects, prefer a normal `if/else` block — squeezing too much onto one line hurts readability rather than helping it.
What are the most common if/else mistakes in Python?
Three errors account for the overwhelming majority of beginner frustration. All three are easy to fix once you can recognise them.
1. Using `=` instead of `==`. A single `=` *assigns*; a double `==` *compares*. Inside a condition you almost always want `==`. Helpfully, modern Python raises a `SyntaxError` if you write `if x = 5:`, so this fails loudly rather than silently.
“`python x = 5
if x == 5: print(“x is five”) “`
Output:
“` x is five “`
2. Forgetting the colon `:`. Every `if`, `elif`, and `else` line must end with a colon. Leave it off and Python stops with a `SyntaxError`.
“`python
if x > 0: print(“positive”) “`
3. Inconsistent indentation. This is the big one. The block under an `if` must be indented, and every line in that block must be indented the *same* amount. Mixing four spaces with two, or spaces with tabs, raises an `IndentationError` or — worse — silently changes which lines belong to the block.
“`python if x > 0: print(“this is inside the if”) print(“so is this”) print(“this is always printed”) “`
Pick four spaces per level, configure your editor to insert spaces when you press Tab, and stay consistent. Your `if/elif/else` structure will then be correct *and* self-documenting.
Build and run your Python logic on infrastructure you control with DarazHost
Conditionals are where your program’s logic comes alive — and you want a stable place to write, test, and run that logic without fighting your environment. DarazHost VPS and dedicated servers give developers a real, controllable Python environment: install the exact Python version you need, manage your own dependencies, and run your code on guaranteed resources with full root access. It is the dependable home your Python work deserves, backed by 24/7 support. When your `if/elif/else` logic is ready to ship, it runs on infrastructure that behaves the same in production as it did on your machine. Explore hosting built for developers who want a real environment they control.
Is there a modern alternative for many branches? Meet `match`
When you find yourself writing a long `if/elif/elif/elif` chain that compares one value against many fixed options, Python’s structural pattern matching — the `match` statement, available since Python 3.10 — is often cleaner.
“`python status_code = 404
match status_code: case 200: print(“OK”) case 301 | 302: print(“Redirect”) case 404: print(“Not Found”) case _: print(“Unknown status”) “`
Output:
“` Not Found “`
The `case _:` line is the wildcard — it acts like `else`, catching anything not matched above. `match` does not replace `if/else`; for boolean tests and ranges, `if` is still the right tool. But for dispatching on one value across many discrete cases, `match` reads beautifully. If you are still finding your footing with the fundamentals, the guide is a good companion to this one.
Frequently asked questions
What is the difference between `if` and `elif` in Python? `if` begins a conditional chain and is always evaluated first. `elif` (else-if) adds an additional condition that is checked *only* if all preceding `if`/`elif` conditions were `False`. You can have many `elif` branches, but only one `if` and at most one `else` per chain.
Why does Python use indentation instead of curly braces? It is a deliberate design choice to force readable code. Because indentation *is* the block delimiter, the visual layout of Python code always matches its logical structure — you cannot mislead a reader with formatting that disagrees with the actual block boundaries. The convention is four spaces per level; avoid mixing tabs and spaces.
Can I write an `if` statement without an `else`? Yes. An `if` is complete on its own. If the condition is `False` and there is no `else`, Python simply skips the block and continues. `else` is only needed when you have a specific fallback action.
What is the difference between `==` and `=` in a condition? `==` compares two values and returns `True` or `False` — that is what belongs in a condition. `=` assigns a value to a variable. Writing `if x = 5:` raises a `SyntaxError` in Python, which prevents a whole class of bugs that plague other languages.
When should I use a ternary expression instead of an `if/else` block? Use the ternary form (`a if cond else b`) when you are choosing between two *values* and the logic is simple enough to read on one line. For anything involving multiple statements, side effects, or complex conditions, a full `if/else` block is clearer.