Artificial Intelligence & Data Science is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Decision control statements

Decision control statements in Python: if, if–else, if–elif–else, nested if, conditional expressions, truthiness, comparisons, logical operators, short-circuiting, and basic flowcharting.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Decision control statements let a program choose different actions based on conditions, just like an engineer chooses different calculations or procedures depending on sensor readings, test results, or user choices. You need them to validate inputs, branch safety logic, select algorithms, and handle exceptional cases in automation, data processing, and embedded systems.

Key ideas

  • Definition: A block (suite) of statements is a group of one or more Python statements that share the same indentation level and execute together when their controlling statement (like if) is selected.

  • Definition: An if statement executes its block if and only if its condition is truthy; otherwise it skips that block. Exact statement: If condition C is truthy, then the indented suite S executes once; if C is falsy, S is skipped.

  • Definition: An if–else statement selects exactly one of two mutually exclusive suites: the if-suite executes if the condition is truthy; otherwise the else-suite executes. Assumption: the condition is evaluated exactly once and the other suite is skipped.

  • Definition: An if–elif–else (if-elif ladder) is a multi-way selection that tests conditions in order from top to bottom; the first condition that is truthy selects its suite and all remaining clauses are skipped. If no condition is truthy, the optional else-suite executes. Law of selection for ladder: At most one suite executes; if no condition is truthy and else is absent, no suite executes; if else is present and no condition is truthy, the else-suite executes.

  • Definition: A nested if is an if statement placed inside another if (or elif/else) suite, allowing hierarchical decisions. Assumption: inner conditions are evaluated only if the outer condition’s path is taken.

  • Definition: A conditional expression (ternary operator) is an expression form that selects between two values based on a condition, without starting a new indented block. It returns the first expression if the condition is truthy; otherwise it returns the second expression.

  • Definition: A comparison operator compares two values and returns a Boolean. Python supports >, >=, <, <=, ==, != and also chaining (a < b < c). Assumption: comparisons may call type-specific methods; some heterogeneous comparisons raise TypeError in Python 3 (e.g., 3 < "4").

  • Definition: A logical operator combines Boolean values: and, or, not. Exact evaluation rule (short-circuit):

    • For A and B, evaluate A; if A is falsy, result is A; otherwise evaluate B and result is B.
    • For A or B, evaluate A; if A is truthy, result is A; otherwise evaluate B and result is B.
    • not A returns True if A is falsy; otherwise False. These operators return one of their operands (not coerced to True/False), but in if conditions any non-Boolean result is used by its truth value. Operator precedence among logical operators is: not > and > or; use parentheses to make intent explicit.
  • Definition: Truthiness is the implicit Boolean value used by Python in conditions. Exact rule: False, None, numeric zero of any type (0, 0.0, 0j), and empty sequences/collections ("", (), [], {}, set(), range(0)) are falsy; all other objects are truthy unless a class defines bool or len to return 0/False.

  • Definition: A pass statement is a null operation—it does nothing and is used as a syntactic placeholder where a statement is required by Python’s grammar.

  • Flow of control diagrams to draw in exams:

    1. Simple if: Draw a diamond labeled “Condition C?”. From the bottom point of the diamond, draw two arrows: one labeled “True” going to a rectangle labeled “Execute S”; one labeled “False” going to a bypass arrow that skips S. Both arrows join to a single flow line labeled “Next”.
    2. if–else: Draw a diamond “C?”. From it, two arrows: “True” to rectangle “Suite S1”; “False” to rectangle “Suite S2”. After both rectangles, join into one flow line “Next”.
    3. if–elif–else ladder: Draw a diamond “C1?”. The “True” arrow goes to rectangle “S1” then to “Next”. The “False” arrow goes to a second diamond “C2?” and repeat. The final “False” arrow goes to rectangle “Else S” (if present). All suites join to “Next”. Label diamonds C1, C2, …, and rectangles S1, S2, …, Else.
    4. Nested if: Draw outer diamond “C_outer?”. “True” arrow goes to second diamond “Cinner?” leading to rectangles “Sinner-True” and “Sinner-False”; “False” arrow of outer diamond goes to rectangle “Souter-False (optional)”. Join all to “Next”.
  • Good practice principles often expected in answers:

    • Guard conditions first: write the most restrictive or error-detecting condition early to fail fast.
    • Mutually exclusive ranges: ensure numeric intervals do not overlap and cover required cases; use <= and < carefully.
    • Use chained comparisons for readability: a <= x < b.
    • Keep indentation consistent (spaces, typically 4 per level) and end each header line (if/elif/else) with a colon.
  • Note on version: The match–case statement (structural pattern matching) is also a decision construct introduced in Python 3.10; if your syllabus includes it, treat it as a multi-way decision specialized for patterns. If not, you can solve all typical first-year problems with if/elif/else.

Formulas

Executes the indented suite if condition is truthy.

  • if condition: suite else: suite Two-way selection between suites.

  • if condition1: suite1 elif condition2: suite2 elif condition3: suite3 else: suite_else Multi-way selection, first true condition wins; else is optional.

  • `if outer_condition: if inner_condition: inner_suite else: inner_else_suite

else: outer_else_suite` Nested if for hierarchical checks.

  • result = expr_if_true if condition else expr_if_false Conditional expression (ternary) that chooses a value.

  • if a < b < c: Comparison chaining for ordered, non-overlapping checks.

  • if (x >= low) and (x <= high): Logical operators and, or, not combine conditions; parentheses improve clarity.

  • if not items: Truthiness check for emptiness or zero.

  • pass Placeholder in empty suites.

  • Optional (Python 3.10+): match value: case pattern1: suite1 case pattern2: suite2 case _: default_suite Structural pattern matching for multi-way selection by pattern.

Worked examples

Example 1: Classify marks into grades using if–elif–else and guard conditions Complete program:

# Grade classifier: maps percentage to letter grade
# Assumptions: 0 <= marks <= 100

def grade_for(marks):
    # Guard invalid input first
    if marks < 0 or marks > 100:
        return "Invalid"
    if marks >= 90:
        return "O"   # Outstanding
    elif marks >= 80:
        return "A+"
    elif marks >= 70:
        return "A"
    elif marks >= 60:
        return "B+"
    elif marks >= 50:
        return "B"
    elif marks >= 40:
        return "C"
    else:
        return "F"   # Fail

# I/O
marks = float(input("Enter percentage (0–100): "))
print("Grade:", grade_for(marks))

Sample input and exact output 1: Input Enter percentage (0–100): 86 Output Grade: A+

Sample input and exact output 2 (invalid): Input Enter percentage (0–100): 120 Output Grade: Invalid

Why it demonstrates decisions: ordered conditions, mutually exclusive ranges, early validation using if and or.

Example 2: Leap year checker with nested if and logical operators A year is a leap year if it is divisible by 4, except years divisible by 100, unless they are also divisible by 400.

Complete program:

year = int(input("Enter a year (e.g., 2024): "))

if year % 4 != 0:
    print("Common year")
else:
    if year % 100 != 0:
        print("Leap year")
    else:
        if year % 400 == 0:
            print("Leap year")
        else:
            print("Common year")

Equivalent concise version using logical operators:

year = int(input("Enter a year (e.g., 2024): "))
if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):
    print("Leap year")
else:
    print("Common year")

Sample inputs and exact outputs:

  • Input Enter a year (e.g., 2024): 2024 Output Leap year

  • Input Enter a year (e.g., 2024): 1900 Output Common year

  • Input Enter a year (e.g., 2024): 2000 Output Leap year

Why it demonstrates decisions: nested if vs combined logical conditions, strict evaluation order, modulus tests.

Example 3: Electricity bill calculator using an if–elif ladder Suppose the tariff is defined as:

  • First 100 units at ₹5.00 per unit
  • Next 100 units (101–200) at ₹7.00 per unit
  • Beyond 200 units at ₹10.00 per unit
  • Fixed charge ₹50 added to every bill

Complete program:

units = int(input("Enter units consumed: "))

if units < 0:
    print("Invalid units")
else:
    if units <= 100:
        energy = units * 5.0
    elif units <= 200:
        energy = 100 * 5.0 + (units - 100) * 7.0
    else:
        energy = 100 * 5.0 + 100 * 7.0 + (units - 200) * 10.0

    total = energy + 50.0
    print(f"Energy charge: ₹{energy:.2f}")
    print(f"Fixed charge: ₹50.00")
    print(f"Total bill: ₹{total:.2f}")

Sample input and exact output 1: Input Enter units consumed: 75 Output Energy charge: ₹375.00 Fixed charge: ₹50.00 Total bill: ₹425.00

Check: 75×5 = 375; 375 + 50 = 425.

Sample input and exact output 2: Input Enter units consumed: 150 Output Energy charge: ₹850.00 Fixed charge: ₹50.00 Total bill: ₹900.00

Check: 100×5 = 500; next 50×7 = 350; 500+350=850; +50=900.

Sample input and exact output 3: Input Enter units consumed: 275 Output Energy charge: ₹1950.00 Fixed charge: ₹50.00 Total bill: ₹2000.00

Check: 100×5 = 500; 100×7 = 700; 75×10 = 750; energy = 1950; +50 = 2000. Note: The program prints without thousands separator unless locale/format specified; if you need commas, adapt the format (e.g., format with comma). For the exact output above, if using f"{value:.2f}", it will actually show 1950.00 and 2000.00; to show commas use f"{value:,.2f}". We include a corrected run below.

Corrected run with comma formatting enabled:

units = 275
if units <= 100:
    energy = units * 5.0
elif units <= 200:
    energy = 100 * 5.0 + (units - 100) * 7.0
else:
    energy = 100 * 5.0 + 100 * 7.0 + (units - 200) * 10.0
print(f"Energy charge: ₹{energy:,.2f}")
print("Fixed charge: ₹50.00")
print(f"Total bill: ₹{energy + 50:,.2f}")

Exact output for units = 275 (no input line): Energy charge: ₹1,950.00 Fixed charge: ₹50.00 Total bill: ₹2,000.00

Why it demonstrates decisions: a classic tariff slab uses mutually exclusive ranges and precise boundary conditions with elif.

Common mistakes

  • Inconsistent indentation (mixing tabs and spaces) or wrong indentation so that statements fall outside the intended block.
  • Overlapping or missing numeric ranges in elif ladders (e.g., using < in one and <= in the next, creating gaps or overlaps).
  • Checking equality of floating-point numbers directly (if x == 0.1:), which can fail due to representation; prefer tolerance checks or range conditions if relevant to the problem.
  • Using bitwise operators (&, |) instead of logical operators (and, or) in conditions; these behave differently and can produce wrong results.
  • Misusing truthiness: testing if items == True instead of simply if items: for non-empty checks; or forgetting that empty strings/lists are falsy.
  • Placing a general condition before a specific one, making later branches unreachable (e.g., if x >= 0 then elif x > 10 will never run).
  • Expecting and/or to return strictly True/False; they return an operand. In if conditions this is fine, but in expressions it can surprise (e.g., result = name or "Guest").
  • Ignoring short-circuit side effects: writing if f() and g(): and assuming g() always runs; g() will not run if f() is falsy.

For your exam

  • Diagrams: draw clear flowcharts for simple if, if–else, and if–elif–else with labels (Condition, True, False, Suite/Action, Next). Keep arrows clean and join points clear.
  • Programs: typical tasks include grading, triangle classification by sides/angles, leap year, tariff/billing slabs, input validation, menu selection. For full marks include: input prompts, correct boundary conditions, correct elif order, sample run(s) with exact outputs, and comments where helpful.
  • Reasoning questions: explain why a certain elif branch is unreachable; show correction. Prove correctness for ranges by splitting the real line into disjoint intervals and mapping each to exactly one branch.
  • Version awareness: if match–case is included in your syllabus, be ready to write a small example and explain underscore (_) as the wildcard default case.

Quick check

  1. Write one Python line using a conditional expression to set fee to 0 if age < 5, otherwise 100.
  2. For x = 7, which branch executes? if x > 10: A elif x > 5: B else: C
  3. Is the condition if data: True when data = []? Why?

Answers: 1) fee = 0 if age < 5 else 100 2) B 3) No; [] is empty and therefore falsy under Python’s truthiness rules.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?