Python tutorials  /  Python If-Else Statements
Chapter 5 · Python

Python If-Else Statements

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.

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.
if condition: # executes if condition is True elif another_condition: # executes if another_condition is True else: # executes if all above conditions are False # Conditional expression: result = value_if_true if condition else value_if_false
A beginner needs to write a Python program that categorizes a student's exam score into a letter grade (A, B, C, or F) based on different score ranges, using an if-elif-else ladder, and also wants to see how the same pass/fail check could be written more concisely using a conditional expression.
Grading System Using if-elif-else Ladder
This example checks a student's score against multiple thresholds in sequence to determine the appropriate letter grade, demonstrating Python's indentation-based if-elif-else structure.
Python
score = 82 if score >= 90: grade = "A" elif score >= 75: grade = "B" elif score >= 60: grade = "C" else: grade = "F" print("Score:", score) print("Grade:", grade)
Score: 82 Grade: B
Python evaluates each condition from top to bottom, in order. Since 'score' (82) is not >= 90, the first condition is False, so Python checks the next 'elif'. Since 82 >= 75 is True, 'grade' is set to "B", and Python immediately skips every remaining 'elif' and 'else' block, even though 82 also technically satisfies the '>= 60' condition further down. Notice there are no curly braces anywhere — indentation alone defines exactly which lines belong to each conditional block.
Concise Pass/Fail Check Using a Conditional Expression
This example rewrites a simple pass/fail decision using Python's conditional (ternary) expression, assigning a result string in a single, compact line instead of a full multi-line if-else block.
Python
score = 55 result = "Passed" if score >= 40 else "Failed" print("Result:", result)
Result: Passed
The conditional expression 'value_if_true if condition else value_if_false' is evaluated as a single expression that produces a value, here directly assigned to 'result'. Since 'score >= 40' evaluates to True, the expression evaluates to "Passed"; had the condition been False, it would have evaluated to "Failed" instead. This is functionally equivalent to a full 4-line if-else block but is much more compact for simple, single-value conditional assignments.
  • 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.
How does Python determine which lines of code belong to an if, elif, or else block, given that it doesn't use curly braces?
Python uses INDENTATION (whitespace at the beginning of a line) to determine block membership, rather than curly braces like Java or C. Every line that is indented at the same consistent level immediately following an 'if condition:', 'elif condition:', or 'else:' statement is considered part of that specific block. The block ends as soon as Python encounters a line indented back to a shallower level (or one at the same level as the original if/elif/else). This makes correct, consistent indentation not just a style preference in Python, but an actual functional requirement enforced by the language itself — inconsistent indentation causes an 'IndentationError' at parse time, since the interpreter can no longer reliably determine which block a given line belongs to.
What is Python's conditional expression (often called a ternary operator), and when is it appropriate to use versus a full if-else block?
Python's conditional expression uses the syntax 'value_if_true if condition else value_if_false', evaluating to one of two possible values based on a single boolean condition, all within a single expression that can be directly assigned to a variable or passed as an argument. It is appropriate for simple, single-condition cases where you need to conditionally choose between exactly two possible VALUES (e.g., 'label = "Even" if num % 2 == 0 else "Odd"'), keeping the code concise and readable. A full multi-line if-elif-else block is more appropriate when more than two outcomes are needed, when each branch needs to execute multiple statements (not just produce a single value), or when nesting would otherwise be required, since chaining or nesting multiple conditional expressions together quickly harms readability compared to an equivalent, clearer if-elif-else structure.
What is the output of the following code, and why, considering Python's specific elif ladder evaluation order? score = 95 if score >= 60: result = "Pass" elif score >= 90: result = "Pass with Distinction" else: result = "Fail" print(result)
The output will be "Pass", NOT "Pass with Distinction", even though a score of 95 would also satisfy the second condition. This happens because Python's if-elif-else ladder evaluates conditions strictly in the order they're written, from top to bottom, and executes the block for the FIRST condition found to be True, immediately skipping all subsequent elif/else blocks without even evaluating their conditions. Since 'score >= 60' (95 >= 60) is checked first and is already True, Python assigns 'result = "Pass"' and never even reaches the 'elif score >= 90:' check at all — this demonstrates why more restrictive/higher thresholds must always be placed BEFORE broader/lower ones in a range-checking elif ladder.
Write a Python program that checks if a given number is positive, negative, or zero, and prints the appropriate message using an if-elif-else ladder.
number = -7 if number > 0: print("Positive") elif number < 0: print("Negative") else: print("Zero") # Output: # Negative
Identify the bug in the following code and explain what error it will cause when run: age = 20 if age >= 18 print("Adult") else: print("Minor")
The bug is a missing colon ':' at the end of the 'if age >= 18' line. Python requires every block-introducing statement (if, elif, else, for, while, def, class) to end with a colon before its indented body. Running this code as-is produces a 'SyntaxError: expected ':''. The fix is to add the missing colon: 'if age >= 18:'.
Using a conditional expression, write a single line of Python code that assigns the string "Even" to a variable 'result' if a given integer 'num' is even, or "Odd" if it is odd.
num = 17 result = "Even" if num % 2 == 0 else "Odd" print(result) # Output: # Odd # This uses the modulus operator (%) to check the remainder when 'num' is divided by 2. If the remainder is 0, the number is even; otherwise, it's odd. Python's conditional expression then assigns the appropriate string directly based on this boolean check, all within a single, concise line.

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.

© 2026 CompileX. Maintained by Aditya Kumar Sharma.