Skip to content
C

Conditional Statements

How Python programs make decisions — if, if-else, if-elif-else, nested conditions, the ternary operator, and Python 3.10's match-case pattern matching.


Programs rarely do just one fixed thing — they need to make decisions. Should the user be let into the app? Is this number positive or negative? Did the student pass or fail? Conditional statements are how Python makes these decisions.


1. What are Conditional Statements?

What is it?

A conditional statement lets your program choose between different paths of action depending on whether something is True or False.

Definition: A conditional statement executes a block of code only if a specified condition is true.

Why do we use it?

Real-world logic is full of "if this, then that" situations:

  • If age is 18 or above, allow voting.
  • If password is correct, log the user in.
  • If marks are above 40, mark the student as "Pass."

Without conditionals, a program would just run every line the same way every time, regardless of the situation — which isn't how real software works.

How does it work?

Python checks the condition (an expression that evaluates to True or False). If it's True, the indented block underneath runs. If it's False, that block is skipped.


2. The if Statement

Syntax

python
if condition: # code that runs only if condition is True

Simple Example

python
age = 20 if age >= 18: print("You are eligible to vote")

Output:

You are eligible to vote

Explanation of the Code

  • age >= 18 is the condition — it evaluates to True since 20 >= 18.
  • Because the condition is True, the indented print() line runs.
  • If age were 15, nothing would print at all — the program would simply move on.

Real-World Example

Age verification on a voting or alcohol-purchase app: "If age >= 18, allow access."

Common Mistakes

  • Forgetting the colon : at the end of the if line.
  • Forgetting to indent the block under if — Python will raise an IndentationError.
  • Using = instead of == inside the condition.

Important Points

  • The condition must evaluate to a boolean (True/False).
  • Only the indented lines belong to the if block.
  • An if without a matching else simply does nothing when the condition is False.

Practice

  1. Write a program that prints "You can drive" if the age entered is 18 or above.

3. if-else

Syntax

python
if condition: # runs if condition is True else: # runs if condition is False

Simple Example

python
age = 15 if age >= 18: print("You are eligible to vote") else: print("You are not eligible to vote")

Output:

You are not eligible to vote

Explanation

  • Since 15 >= 18 is False, Python skips the if block and runs the else block instead.
  • Exactly one of the two blocks always runs — never both, never neither.

Real-World Example — Login Validation

python
correct_password = "python123" entered_password = input("Enter password: ") if entered_password == correct_password: print("Login successful") else: print("Incorrect password")

Common Mistakes

  • Adding a condition after else (else condition:) — else never takes a condition; elif does.
  • Misaligned indentation between the if and else blocks.

Important Points

  • else always pairs with the closest unmatched if.
  • Use if-else whenever there are exactly two possible outcomes.

Practice

  1. Write a program that checks if a number is even or odd and prints the appropriate message.

4. if-elif-else

What is it?

Used when there are more than two possible outcomes to check, one after another.

Syntax

python
if condition1: # block 1 elif condition2: # block 2 elif condition3: # block 3 else: # default block

Simple Example — Student Grades

python
marks = 72 if marks >= 90: grade = "A" elif marks >= 75: grade = "B" elif marks >= 60: grade = "C" elif marks >= 40: grade = "D" else: grade = "Fail" print("Grade:", grade)

Output:

Grade: C

Explanation of the Code

  • Python checks each condition from top to bottom.
  • marks >= 90 is False, so it moves on. marks >= 75 is also False.
  • marks >= 60 is True (72 >= 60), so grade = "C" runs, and Python stops checking the rest — it never looks at the remaining elif/else.

Real-World Example — Electricity Bill Slabs

python
units = 250 if units <= 100: bill = units * 3 elif units <= 200: bill = 100 * 3 + (units - 100) * 5 else: bill = 100 * 3 + 100 * 5 + (units - 200) * 8 print("Electricity Bill: Rs.", bill)

Output:

Electricity Bill: Rs. 1150

Real-World Example — Menu Selection

python
print("1. Coffee - Rs.50") print("2. Tea - Rs.30") print("3. Juice - Rs.60") choice = int(input("Enter your choice: ")) if choice == 1: print("You ordered Coffee") elif choice == 2: print("You ordered Tea") elif choice == 3: print("You ordered Juice") else: print("Invalid choice")

Common Mistakes

  • Writing overlapping conditions in the wrong order — e.g., checking marks >= 40 before marks >= 60, which would wrongly grade a 72 as a "D" (because the first matching condition wins and stops the chain). Always order conditions from most specific / highest value to least.
  • Forgetting the final else to catch unexpected values.

Important Points

  • Only one block in an if-elif-else chain ever runs — the first one whose condition is True.
  • Order matters — always arrange conditions logically (usually highest to lowest, or most specific to most general).

Practice

  1. Write a grading program using your own grade boundaries.
  2. Write a menu-based program with at least 4 options and a message for invalid input.

5. Nested Conditions

What is it?

A nested condition is an if statement placed inside another if (or else) block — used when a decision depends on more than one level of checking.

Simple Example

python
age = 20 has_id = True if age >= 18: if has_id: print("Entry allowed") else: print("ID required for entry") else: print("Entry not allowed - underage")

Output:

Entry allowed

Explanation of the Code

  • The outer if checks age first.
  • Only if the outer condition is True does Python even look at the inner if has_id: check.
  • This models real logic: age is checked first; ID is only relevant if the person is already old enough.

Real-World Example

A movie ticket booking system might check: is the movie rated correctly for the age group? If yes, is a valid ID also provided? Both conditions must be checked in sequence.

Common Mistakes

  • Over-nesting (5+ levels deep), which makes code hard to read. Often, combining conditions with and is cleaner:
python
if age >= 18 and has_id: print("Entry allowed")
  • Incorrect indentation between nested levels — easy to lose track of which block belongs to which if.

Important Points

  • Nested conditions are useful, but too much nesting hurts readability — prefer and/or when the logic allows it.
  • Each nested level needs its own consistent indentation (usually 4 more spaces per level).

Practice

  1. Write a nested condition that checks if a number is positive, and if so, whether it's even or odd.

6. The Ternary (Conditional) Operator

What is it?

A shorter, one-line way of writing simple if-else logic, when you just need to assign one of two values based on a condition.

Syntax

python
value = true_result if condition else false_result

Simple Example

python
age = 20 status = "Adult" if age >= 18 else "Minor" print(status)

Output:

Adult

Explanation

  • This is exactly equivalent to writing a full if-else block, just condensed to one line.
  • Read it as: "give me true_result if the condition is true, else give me false_result."

Real-World Example

python
marks = 35 result = "Pass" if marks >= 40 else "Fail" print(result)

Common Mistakes

  • Trying to cram complex, multi-condition logic into a ternary expression, making it unreadable. If it doesn't fit cleanly on one line, use a regular if-else instead.

Important Points

  • Best used for simple, single-condition value assignments.
  • Not meant to replace if-elif-else chains with many branches.

Practice

  1. Use a ternary operator to assign "Even" or "Odd" to a variable based on a number.

7. match-case (Structural Pattern Matching)

What is it?

Introduced in Python 3.10, match-case is Python's version of a "switch statement" found in other languages — a cleaner way to compare one value against several possible patterns.

Syntax

python
match value: case pattern1: # code case pattern2: # code case _: # default case (like "else")

Simple Example — Menu Selection

python
choice = 2 match choice: case 1: print("You ordered Coffee") case 2: print("You ordered Tea") case 3: print("You ordered Juice") case _: print("Invalid choice")

Output:

You ordered Tea

Explanation of the Code

  • match choice: starts the comparison.
  • Python checks choice against each case in order and runs the first matching block.
  • case _: is the default — it matches anything not caught by earlier cases (similar to else).

Real-World Example

match-case is great for menu systems, command interpreters, or handling different types of API responses ("success", "error", "pending").

python
status = "error" match status: case "success": print("Operation completed") case "error": print("Something went wrong") case "pending": print("Still processing") case _: print("Unknown status")

Common Mistakes

  • Forgetting the default case _:, which means unmatched values simply do nothing.
  • Using match-case for very simple two-way decisions where a normal if-else would be clearer.

Important Points

  • match-case requires Python 3.10 or newer.
  • case _: is the catch-all default pattern.
  • It's often cleaner than a long if-elif chain when comparing one variable against many fixed values.

Practice

  1. Rewrite the menu selection example from Section 4 using match-case instead of if-elif-else.

Comparison Table — Choosing the Right Conditional Tool

SituationBest Tool
One simple checkif
Exactly two outcomesif-else
Many possible outcomes (ranges)if-elif-else
Assigning one of two values in one lineTernary operator
Comparing one variable against many fixed valuesmatch-case
Decision depends on more than one separate checkNested if or and/or

Common Beginner Mistakes — Summary

  • Using = instead of == inside conditions.
  • Forgetting the colon : after if, elif, else.
  • Wrong indentation, causing IndentationError.
  • Ordering elif conditions incorrectly (e.g., checking a lower threshold before a higher one).
  • Over-nesting if statements instead of using and/or.

Cheat Sheet — Conditional Statements

python
if condition: ... elif condition2: ... else: ... # Nested if condition1: if condition2: ... # Ternary value = a if condition else b # match-case (Python 3.10+) match value: case pattern: ... case _: ...

Interview Questions

Q1. What is the difference between `if-else` and `if-elif-else`? Answer: if-else handles exactly two possible outcomes. if-elif-else handles multiple possible outcomes, checked in order, where only the first matching condition's block runs.

Q2. What happens if none of the conditions in an `if-elif-else` chain are true and there is no `else`? Answer: Nothing runs — the program simply continues to the next line after the chain.

Q3. What is the ternary operator used for? Answer: A compact one-line way to assign one of two values based on a condition, equivalent to a simple if-else.

Q4. What is `match-case` and when was it introduced? Answer: It's Python's structural pattern matching feature (similar to switch-case in other languages), introduced in Python 3.10, used to compare a value against multiple patterns cleanly.

Q5. Can you use `and`/`or` instead of nested `if` statements? Answer: Yes — for simple combined conditions, if age >= 18 and has_id: is often cleaner and more readable than nesting two separate if blocks.


Practice Questions

Beginner

  1. Write a program that checks if a number is positive, negative, or zero.
  2. Write a program to check if a person is eligible to vote (age >= 18).
  3. Write a program that checks if a character entered is a vowel.
  4. Write a program that checks if a year is a leap year.
  5. Write a program using the ternary operator to find the larger of two numbers.

Intermediate

  1. Write a program that takes marks and prints a grade using if-elif-else (A/B/C/D/Fail).
  2. Write a login system that checks both username and password using nested conditions.
  3. Write a program that calculates an electricity bill using slab-based elif conditions.
  4. Write a program that classifies a triangle as equilateral, isosceles, or scalene based on three side lengths.
  5. Write a menu-driven program using match-case with at least 4 options.

Challenge

  1. Write a program that checks if a number is divisible by both 3 and 5, only 3, only 5, or neither — using appropriate conditions.
  2. Build a simple traffic light simulator: given a color ("red", "yellow", "green") using match-case, print the correct action ("Stop", "Get Ready", "Go").
  3. Write a BMI calculator that takes height and weight, calculates BMI, and prints the category (Underweight/Normal/Overweight/Obese) using if-elif-else.

Mock Test

  • Conditional Statements - Quick Test

    10 questions covering if / if-else / if-elif-else, nested conditions, the ternary operator, and match-case.

    10 questions · 10 min · Easy
    Start Mock Test

Coding Problems