Back to Blog
Python

Python If Statement: Syntax and Practical Usage

python if statement: Learn how the Python if statement works: core syntax, elif chains, truthiness, ternary expressions, common pitfalls, and short-circuit evaluation.

PythonConditionalsControl FlowBoolean LogicCode Quality
A branching path diagram illustrating the Python if statement's conditional execution flow.

The python if statement is the primary tool for conditional execution in Python. It evaluates a boolean expression and runs a block of code only when that expression is true. The syntax is deliberately minimal: the keyword if, a condition, a colon, and an indented block.

The Core Syntax of the Python If Statement

A basic if statement requires three elements: the if keyword, a condition, and a colon. The block that follows must be indented consistently, usually with four spaces. Python treats indentation as the block boundary, so there is no then keyword and no braces.

temperature = 28 if temperature > 25: print("It is warm outside.")

The condition can be any expression that Python can convert to a boolean. Comparison operators (==, !=, <, >, <=, >=), membership tests (in), identity checks (is), and logical combinations (and, or, not) all work here. When the condition evaluates to True, the indented block runs. When it evaluates to False, Python skips the block and continues with the first statement at the original indentation level.

Chaining Conditions With elif and else

When a decision has more than two outcomes, elif and else extend the statement. Python evaluates the conditions in order and runs the block belonging to the first condition that is true. Once one block runs, the rest of the chain is skipped.

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

The else block is optional and runs when none of the preceding conditions are true. elif is a contraction of "else if"; you can chain as many as needed. Order matters because Python stops at the first true condition. A condition that would also match a later elif never gets evaluated, so arrange the chain from the most specific case to the most general.

How Python Evaluates Truthiness

An if condition does not need to be a literal True or False. Python applies its truthiness rules to any object. The following values are falsy: False, None, 0, 0.0, empty strings (""), empty containers ([], (), {}, set()), and objects whose __bool__() or __len__() returns a false value. Everything else is truthy.

items = [] if items: print(f"Processing {len(items)} items.") else: print("No items to process.")

This pattern is idiomatic: checking an empty list with if items: is clearer than if len(items) > 0:. The same applies to strings, dictionaries, and sets. For custom classes, defining __bool__() lets you control how instances behave in conditions. Without __bool__(), Python falls back to __len__(), and if neither is defined, the object is always truthy.

Conditional Expressions for Simple Branching

For a single value assignment based on a condition, a conditional expression, often called the ternary operator, is more compact than an if/else block:

status = "active" if user.is_active else "inactive"

The expression evaluates the condition, then returns the value on the left of if when true, or the value on the right of else when false. Both branches are expressions, not statements, so they must produce values.

Conditional expressions are best for short, readable assignments. When the branches require multiple statements or complex logic, a regular if/else block remains the better choice. Nesting conditional expressions is legal but quickly becomes unreadable; avoid it.

Common Mistakes That Break if Statements

A frequent error is using a single = instead of == in a condition. Python raises a SyntaxError when it detects an assignment in a condition, which prevents the classic C-style bug, but the error message can still confuse developers who are new to the language.

# This raises a SyntaxError if value = 10: print("value is 10")

Another common issue is inconsistent indentation. Python requires the entire block to use the same indentation level. Mixing tabs and spaces, or using a different number of spaces on different lines, produces an IndentationError. Most editors handle this automatically, but it remains a source of failure when code is copied between environments.

Operator precedence also causes subtle bugs. The expression if not a == b: evaluates a == b first and then negates it, which is usually what the author intended. But if not a and b: parses as (not a) and b, not not (a and b). When the intent is ambiguous, add parentheses to make the grouping explicit.

Short-Circuit Evaluation and Condition Ordering

The and and or operators in a condition short-circuit: Python stops evaluating as soon as the result is determined. With and, if the left operand is falsy, the right operand never runs. With or, if the left operand is truthy, the right operand never runs.

if user is not None and user.is_admin: grant_access()

This behavior is useful for guarding against None before accessing attributes. It also has performance implications. When a condition combines multiple checks, place the cheapest or most likely-to-fail check first. That way, expensive operations are skipped when an earlier check already decides the outcome.

# Expensive check runs only when the cheap check passes if cache_key in cache and cache[cache_key].is_valid(): return cache[cache_key]

The order of conditions should reflect both the cost of evaluation and the probability of each outcome. A condition that is almost always false should come first in an and chain, because it prevents the remaining checks from running.

When a match Statement Replaces an if/elif Chain

Python 3.10 introduced the match statement for structural pattern matching. It is not a general replacement for if, but it handles certain patterns more cleanly than a long if/elif chain.

match command: case "start": start_service() case "stop": stop_service() case _: print("Unknown command.")

A match statement is appropriate when the comparison is against literal values, when you need to unpack structured data, or when you want to bind parts of the matched value to names. For numeric comparisons, range checks, or conditions that combine multiple variables, an if/elif chain remains the clearer choice. The two constructs serve different purposes; choosing between them depends on whether the decision is about the shape and value of a single subject or about an arbitrary boolean expression.

python if statement: Practical Usage and Code Examples | RYUSLOG DEV