The if-else statement in Python is a conditional control flow structure that allows a program to execute a block of code only if a specified condition evaluates to True, and optionally execute an alternative block if it's False. Python uses the 'elif' keyword (a contraction of 'else if') for additional conditions, and relies entirely on indentation, not curly braces, to define which statements belong to each block.
Python If-Else Statements
Think of an if-else statement like deciding what to wear based on the weather. 'If it's raining, wear a raincoat; elif it's sunny, wear sunglasses; else, just wear a regular jacket.' Your program checks conditions in exactly this same top-to-bottom order, and executes only the code block belonging to the very first condition that turns out to be true, skipping all the rest entirely.
Consider a food delivery app's dynamic pricing script written in Python for a backend service. The script checks: if the order total is above a certain amount, apply free delivery; elif the customer has an active subscription, apply a discounted delivery fee; else, charge the standard delivery fee. This exact if-elif-else pattern, using Python's clean indentation-based syntax, is extremely common in real backend logic, configuration scripts, and automation tools built with Python across companies of every size.
Programs need the ability to behave differently depending on varying data or conditions — a script that always does the exact same thing regardless of input has very limited real-world usefulness. If-elif-else statements provide this essential decision-making capability, letting Python programs validate input, apply business rules, and respond dynamically to different situations, which is foundational to virtually every non-trivial program, from simple scripts to large-scale automation and web backend systems.
- Simple if Statement: Executes an indented block of code only if a single condition evaluates to True; if False, the block is simply skipped entirely with no alternative action.
- if-else Statement: Provides exactly two paths: one indented block executes if the condition is True, and a different indented block (under 'else') executes if it's False.
- if-elif-else Ladder: Chains multiple conditions using 'elif' to check several mutually exclusive cases in sequence, executing only the block for the first condition found to be True, with an optional final 'else' as a catch-all.
- Conditional Expression (Ternary Operator): A concise, single-line alternative to a simple if-else, using the syntax 'value_if_true if condition else value_if_false', allowing a conditional value assignment in one line.
- Inconsistent Indentation Within the Same Block: Mixing different indentation levels (e.g., 4 spaces for one line and 2 spaces for the next line within what should be the same block) causes an 'IndentationError: unindent does not match any outer indentation level'. Every line within the same logical if/elif/else block must use exactly consistent indentation.
- Forgetting the Colon (:) After if/elif/else: Writing 'if score >= 90' without the trailing colon results in a 'SyntaxError: expected ':''. Every block-introducing statement in Python — if, elif, else, for, while, def, class — must always end with a colon before its indented body begins.
- Using 'elseif' Instead of 'elif': Developers coming from languages like C, JavaScript, or PHP sometimes instinctively write 'elseif' (one word) instead of Python's correct 'elif' keyword, resulting in a 'NameError: name 'elseif' is not defined' or a 'SyntaxError', since Python does not recognize 'elseif' as valid syntax at all.
- Incorrect Ordering in an if-elif-else Ladder for Ranges: Writing conditions from lowest to highest (e.g., checking 'score >= 60' before 'score >= 90') causes higher grade thresholds to never be reached, since a score of 95 would incorrectly match the very first True condition ('>= 60') and stop there. Ranges checked with '>=' in an elif ladder must be ordered from highest/most restrictive to lowest/least restrictive.
- Use 4 Spaces for Indentation Consistently: Follow PEP 8's recommendation of exactly 4 spaces per indentation level (not tabs, and not a different number of spaces), and configure your code editor to automatically insert spaces when pressing Tab, ensuring consistent formatting across your entire codebase and avoiding IndentationErrors.
- Order elif Conditions from Most to Least Specific: When checking numeric ranges with '>=' or '<=', always order conditions from the highest/most restrictive threshold down to the lowest, ensuring each value is correctly categorized into the first matching, appropriate range in the ladder.
- Use Conditional Expressions Only for Simple, Single-Value Assignments: Reserve Python's conditional (ternary) expression for simple, single-condition value assignments where readability remains high (e.g., 'status = "Adult" if age >= 18 else "Minor"'); avoid nesting multiple conditional expressions together, as this quickly becomes hard to read, and a standard if-elif-else block should be used instead for anything beyond a single simple condition.
- Use Python's Chained Comparisons for Range Checks: When checking whether a value falls within a specific range, use Python's native chained comparison syntax (e.g., 'if 18 <= age <= 65:') instead of the more verbose 'if age >= 18 and age <= 65:', producing cleaner, more mathematically intuitive conditional code.
Python's if-elif-else statements provide essential decision-making capability, relying entirely on indentation rather than curly braces to define code blocks, with the 'elif' keyword chaining multiple conditions cleanly. Python also offers a concise conditional expression for simple single-value assignments based on a condition. Mastering consistent indentation, the correct ordering of elif conditions for range checks, and knowing when to use a conditional expression versus a full if-elif-else block are essential skills for writing correct, idiomatic Python control flow.