If-Else Conditional Statements In Python — PBA Institute Tutorial
Chapter 03 · Python Programming Series
12 min read Beginner

Decision Making With If-Else

Decision-making is the heart of any program. The if, elif and else keywords let your script choose between different paths depending on conditions — checking ages, comparing scores, validating data or branching workflows. Master these and your programs stop being linear and start being smart.

Overview

🧭

Branching Logic

Pick the right action based on values, user input or computation results.

🔁

Multi-Way Choice

Combine elif branches to handle any number of cases.

📐

Clean Indentation

Python's whitespace rule produces visually clear decision blocks.

Short-Circuit Eval

and/or stop as soon as the result is decided — fast and safe.

✍️

Ternary Style

Write compact conditional assignments in a single, expressive line.

Syntax

  • Conditions are any expression that evaluates to True or False.
  • The colon : marks the end of a header line; the indented block below is the body.
  • elif stands for else if and can be chained as many times as needed.
  • Indentation is part of the syntax — use 4 spaces consistently.
If-Else — Syntax
if condition:
    # runs when condition is True
elif another_condition:
    # runs when the first is False but this one is True
else:
    # runs when none of the above is True

Detailed Explanation

  • Boolean conditions: Any expression Python can interpret as truthy or falsy works. 0, 0.0, None, empty strings/lists/dicts are falsy; everything else is truthy.
  • if statement: Use if when you have a single check and no alternative branch. The body runs only when the condition is True.
  • if-else statement: else handles the opposite case. Exactly one of the two branches will always run.
  • if-elif-else ladder: When you have more than two possibilities (grade A/B/C/D/F, traffic-light states, menu choices), chain elif blocks. The first true condition wins; the rest are skipped.
  • Nested if: Place an if inside another if to build multi-stage checks (e.g. login succeeded → user is admin → show admin panel). Keep nesting shallow for readability.
  • Ternary operator: Python supports a one-line conditional: value = a if condition else b. Great for assignments but avoid nesting ternaries.

Code Examples

Example 1 — Even or Odd
n = int(input("Number: "))
if n % 2 == 0:
    print(n, "is even")
else:
    print(n, "is odd")
Output Number: 7
7 is odd
Example 2 — Largest of Three Numbers
a, b, c = 10, 25, 18
if a >= b and a >= c:
    print("Largest:", a)
elif b >= a and b >= c:
    print("Largest:", b)
else:
    print("Largest:", c)
Output Largest: 25
Example 3 — Grade Calculator
marks = 76
if marks >= 90:
    grade = "A"
elif marks >= 75:
    grade = "B"
elif marks >= 60:
    grade = "C"
elif marks >= 40:
    grade = "D"
else:
    grade = "F"
print("Grade:", grade)
Output Grade: B
Example 4 — Leap Year Check (Nested if)
y = 2024
if y % 4 == 0:
    if y % 100 == 0:
        if y % 400 == 0:
            print("Leap year")
        else:
            print("Not a leap year")
    else:
        print("Leap year")
else:
    print("Not a leap year")
Output Leap year
Example 5 — Ticket Price (Ternary)
age = 16
price = 100 if age >= 18 else 50
print("Ticket price:", price)
Output Ticket price: 50
Example 6 — Password Strength
pwd = "Hello@123"
if len(pwd) < 8:
    print("Too short")
elif pwd.isalpha() or pwd.isdigit():
    print("Weak password")
else:
    print("Strong password")
Output Strong password

Real-World Use Cases

Traffic Signals

Decide vehicle action — Stop, Go or Slow — from the light colour.

Grading Systems

Convert numeric marks to grades A/B/C/D/F automatically.

Authentication

Allow or deny access based on username and password checks.

Discount Engines

Apply different discount rules depending on cart total or user tier.

Weather Apps

Suggest clothing or activities based on temperature ranges.

Form Validation

Reject invalid email, age or pin-code entries before saving them.

Notes & Pro Tips

  • Indent every block exactly 4 spaces — mixing tabs and spaces raises IndentationError.
  • Use == for equality comparison, not = (which is assignment).
  • Combine conditions with and, or, not — Python short-circuits them.
  • Always include an else branch when results must cover all cases.
  • Prefer elif over deeply nested ifs — it reads top-to-bottom like English.
  • Use parentheses to clarify complex boolean expressions even when not strictly required.

Common Mistakes

  • Using = instead of ==: if x = 5 is a syntax error in conditions.
  • Forgetting the colon: if x > 0 without : raises SyntaxError.
  • Wrong indentation: Python uses indentation to mark blocks; misaligned lines change the meaning.
  • Comparing strings as numbers: "10" > "9" is False (lexicographic compare).
  • Mutable default-style logic: writing if list: works, but if list == []: is clearer for empties.
  • Deep nesting: beyond 2–3 levels, refactor into functions or use elif ladders.

Practice Problems

  • Problem 1: Read a number and print whether it is positive, negative or zero.
  • Problem 2: Accept three sides and decide if they form an equilateral, isosceles or scalene triangle.
  • Problem 3: Take a year and determine if it is a leap year using a single boolean expression.
  • Problem 4: Build a simple calculator: ask two numbers and an operator (+, -, *, /) and print the result.
  • Problem 5: Read marks for five subjects, compute the percentage, and print the final grade.
  • Problem 6: Ask the user for a character and determine if it is a vowel, consonant, digit, or special symbol.

Interview Questions

  • Q1. Explain the difference between if, if-else and if-elif-else.
  • Q2. Does Python support switch-case? How do you achieve similar behaviour?
  • Q3. What is short-circuit evaluation in Python's and / or operators?
  • Q4. Write a ternary expression to assign "adult" or "minor" based on age.
  • Q5. How does Python decide truthiness for objects like empty lists or zero?
  • Q6. What happens if two conditions in an if-elif chain are both true at the same time?

Frequently Asked Questions

  • Q1: Does Python have a switch statement?
    Classic Python did not have one. Python 3.10 introduced match-case, but for most decision logic an if-elif-else chain is idiomatic.
  • Q2: Can I omit the else block?
    Yes — else and elif are both optional. Use them only when you need alternative paths.
  • Q3: What is the ternary operator in Python?
    It is a one-line conditional: result = a if condition else b. Useful for compact assignments.
  • Q4: How many elif blocks can I have?
    There is no hard limit, but if you have more than 4–5 elifs consider a dictionary lookup or polymorphism.
  • Q5: Why is indentation so strict in Python?
    Python uses indentation as the block syntax — there are no braces. Consistent indentation keeps code readable and parsing unambiguous.
  • Q6: Can I nest if statements?
    Yes, but limit nesting to 2–3 levels. Beyond that, refactor with elif or helper functions for clarity.

Summary

Conditional statements are the toolkit you use to give your programs intelligence. if handles single decisions, else covers the opposite case, and elif extends the logic to as many branches as you need. Combined with boolean operators and the ternary expression, these few keywords are enough to model virtually any business rule, validation routine or game logic. Write clean, well-indented blocks and your decisions will be both correct and readable.

Continue Learning

Previous

Go to Previous Chapter

Next

Go to Next Chapter