Scrollable Nav Bar

Python Conditional Statements : if elif & else

Conditional statements are the backbone of decision-making in any program. Whether you’re writing a small script to format filenames, building the logic for a web service, or implementing the rules inside a machine learning data pipeline, if/elif/else lets your code react to data and behave differently depending on the situation.

This tutorial is written for students, developers and professionals who want a clear, practical understanding of conditional statements in Python. I focus on readable examples, common pitfalls, and guidance you can use immediately in your projects. The article is reading‑focused (not a video script) and includes placeholders where you can add screenshots or outputs.


Who this is for & what you should know first

You should already be comfortable with variables, basic arithmetic and comparison operators (==, !=, <, >, <=, >=), loops such as for and while, and the modulo operator % (remainder). If those feel new, take a short refresher before continuing — conditional logic builds on them.

Tip: In Python, many values evaluate to False in a boolean context (e.g., 0, '', None, empty lists). Understanding truthy and falsy values will help you write concise conditions.


if Statement

An if statement runs a block of code only when its condition evaluates to True. At its core this is straightforward, but Python’s emphasis on readability means good formatting and clear conditions matter more than clever tricks.

Example:

age = 20
if age >= 18:
    print("You can vote")

A few practical notes:

  • Always follow the condition with a colon : and indent the block (4 spaces is the community standard).
  • Keep conditions simple. If the condition requires multiple logical operators, consider assigning parts of it to well-named variables so the if line reads like plain English.

[Add screenshot showing the if example and its output]


else

else provides a default action when the if condition is false. Use it when you want to guarantee one of two clear outcomes.

Example:

age = 16
if age >= 18:
    print("You can vote")
else:
    print("You cannot vote yet")

When deciding whether to include an else, ask: does every case need handling? If not, it’s okay to omit else and let the program simply continue when the condition is false.

[Add screenshot for if/else output]


elif

When your logic needs more than two branches, elif (short for “else if”) keeps the code linear and readable. An if/elif/else chain evaluates top-to-bottom and executes only the first branch whose condition is true.

Example:

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

Important principles:

  • Put the most specific or highest-priority checks near the top.
  • The else at the end is optional; if present, it must be last.
  • Only the first matching elif will execute — later elif blocks are skipped for that iteration.

[Add screenshot of grade assignment example and output]


A careful walk through FizzBuzz

FizzBuzz asks you to print numbers 1–100 but replace multiples of 3 with Fizz, multiples of 5 with Buzz, and multiples of 15 with FizzBuzz. The subtlety is that numbers divisible by 15 are also divisible by 3 and 5, so order determines the result.

Clean version using elif:

for n in range(1, 101):
    if n % 15 == 0:
        print("FizzBuzz")
    elif n % 3 == 0:
        print("Fizz")
    elif n % 5 == 0:
        print("Buzz")
    else:
        print(n)

Why check % 15 first? If you check % 3 before % 15, the % 3 branch will capture numbers like 15 and you’ll never reach the FizzBuzz branch. Thinking about mutually exclusive vs overlapping conditions is key to writing correct elif chains.

[Add sample FizzBuzz output]


if vs if/elif/else chain

There is a functional difference between:

  • An if/elif/else chain (only one branch runs), and
  • Separate if statements placed sequentially (several can run).

Example where both apply:

for n in range(1, 21):
    if n % 3 == 0:
        print("Fizz")
    if n % 2 == 0:
        print("It is even!")

For n = 6, both lines print. Use separate if statements when multiple independent rules may apply; use elif when choices are mutually exclusive.

[Add output showing both messages for some numbers]


One-line conditional expressions

Python’s conditional expression is handy for assigning a value based on a condition in a single line:

result = "Fizz" if n % 3 == 0 else n

This is great for short, clear transformations (e.g., choosing a label). Avoid chaining many ternary expressions because the readability cost rises fast.

[Add screenshot showing ternary expression usage]


When to prefer readability over brevity

A concise one-liner can look clever, but clarity matters more. Use these rules of thumb:

  • If a condition needs a comment to explain it, refactor.
  • If you find yourself nesting if blocks more than two levels deep, extract helper functions.
  • Name boolean sub-expressions: is_eligible = age >= 18 and paid_membership — then if is_eligible: reads like a sentence.

Common pitfalls and how to avoid them

Wrong order of checks: As in FizzBuzz, wrong order breaks logic. Reorder to check higher-priority or stricter conditions first.

Using elif without if: Syntax error — elif always follows an if.

Over-nesting: Hard to maintain — prefer small functions.

Boolean confusion: Remember Python truthiness rules; if items: checks that items is non-empty.


Exercises

  1. Print 1–50, labels for multiples of 4 (Quad), 6 (Hex) and 12 (QuadHex). (Hint: check % 12 first.)
  2. Convert a numeric score into grades A–F using if/elif/else. (Hint: test boundary values like 89, 90.)
  3. Re-implement exercise 2 using a helper function def letter_grade(score): and keep your if lines short.

Summary and Takeaways

if, elif, and else let your code branch and respond to data. Focus on correct order, clear conditions, and readability. Use one-line conditionals sparingly, prefer named sub-expressions, and factor complex logic into helpers.