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
pythonif condition: # code that runs only if condition is True
Simple Example
pythonage = 20 if age >= 18: print("You are eligible to vote")
Output:
You are eligible to voteExplanation of the Code
age >= 18is the condition — it evaluates toTruesince20 >= 18.- Because the condition is
True, the indentedprint()line runs. - If
agewere15, 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 theifline. - Forgetting to indent the block under
if— Python will raise anIndentationError. - Using
=instead of==inside the condition.
Important Points
- The condition must evaluate to a boolean (
True/False). - Only the indented lines belong to the
ifblock. - An
ifwithout a matchingelsesimply does nothing when the condition isFalse.
Practice
- Write a program that prints "You can drive" if the age entered is 18 or above.
3. if-else
Syntax
pythonif condition: # runs if condition is True else: # runs if condition is False
Simple Example
pythonage = 15 if age >= 18: print("You are eligible to vote") else: print("You are not eligible to vote")
Output:
You are not eligible to voteExplanation
- Since
15 >= 18isFalse, Python skips theifblock and runs theelseblock instead. - Exactly one of the two blocks always runs — never both, never neither.
Real-World Example — Login Validation
pythoncorrect_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:) —elsenever takes a condition;elifdoes. - Misaligned indentation between the
ifandelseblocks.
Important Points
elsealways pairs with the closest unmatchedif.- Use
if-elsewhenever there are exactly two possible outcomes.
Practice
- 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
pythonif condition1: # block 1 elif condition2: # block 2 elif condition3: # block 3 else: # default block
Simple Example — Student Grades
pythonmarks = 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: CExplanation of the Code
- Python checks each condition from top to bottom.
marks >= 90isFalse, so it moves on.marks >= 75is alsoFalse.marks >= 60isTrue(72 >= 60), sograde = "C"runs, and Python stops checking the rest — it never looks at the remainingelif/else.
Real-World Example — Electricity Bill Slabs
pythonunits = 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. 1150Real-World Example — Menu Selection
pythonprint("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 >= 40beforemarks >= 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
elseto catch unexpected values.
Important Points
- Only one block in an
if-elif-elsechain ever runs — the first one whose condition isTrue. - Order matters — always arrange conditions logically (usually highest to lowest, or most specific to most general).
Practice
- Write a grading program using your own grade boundaries.
- 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
pythonage = 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 allowedExplanation of the Code
- The outer
ifchecks age first. - Only if the outer condition is
Truedoes Python even look at the innerif 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
andis cleaner:
pythonif 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/orwhen the logic allows it. - Each nested level needs its own consistent indentation (usually 4 more spaces per level).
Practice
- 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
pythonvalue = true_result if condition else false_result
Simple Example
pythonage = 20 status = "Adult" if age >= 18 else "Minor" print(status)
Output:
AdultExplanation
- This is exactly equivalent to writing a full
if-elseblock, just condensed to one line. - Read it as: "give me
true_resultif the condition is true, else give mefalse_result."
Real-World Example
pythonmarks = 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-elseinstead.
Important Points
- Best used for simple, single-condition value assignments.
- Not meant to replace
if-elif-elsechains with many branches.
Practice
- 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
pythonmatch value: case pattern1: # code case pattern2: # code case _: # default case (like "else")
Simple Example — Menu Selection
pythonchoice = 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 TeaExplanation of the Code
match choice:starts the comparison.- Python checks
choiceagainst eachcasein order and runs the first matching block. case _:is the default — it matches anything not caught by earlier cases (similar toelse).
Real-World Example
match-case is great for menu systems, command interpreters, or handling different types of API responses ("success", "error", "pending").
pythonstatus = "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-casefor very simple two-way decisions where a normalif-elsewould be clearer.
Important Points
match-caserequires Python 3.10 or newer.case _:is the catch-all default pattern.- It's often cleaner than a long
if-elifchain when comparing one variable against many fixed values.
Practice
- Rewrite the menu selection example from Section 4 using
match-caseinstead ofif-elif-else.
Comparison Table — Choosing the Right Conditional Tool
| Situation | Best Tool |
|---|---|
| One simple check | if |
| Exactly two outcomes | if-else |
| Many possible outcomes (ranges) | if-elif-else |
| Assigning one of two values in one line | Ternary operator |
| Comparing one variable against many fixed values | match-case |
| Decision depends on more than one separate check | Nested if or and/or |
Common Beginner Mistakes — Summary
- Using
=instead of==inside conditions. - Forgetting the colon
:afterif,elif,else. - Wrong indentation, causing
IndentationError. - Ordering
elifconditions incorrectly (e.g., checking a lower threshold before a higher one). - Over-nesting
ifstatements instead of usingand/or.
Cheat Sheet — Conditional Statements
pythonif 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
- Write a program that checks if a number is positive, negative, or zero.
- Write a program to check if a person is eligible to vote (age >= 18).
- Write a program that checks if a character entered is a vowel.
- Write a program that checks if a year is a leap year.
- Write a program using the ternary operator to find the larger of two numbers.
Intermediate
- Write a program that takes marks and prints a grade using
if-elif-else(A/B/C/D/Fail). - Write a login system that checks both username and password using nested conditions.
- Write a program that calculates an electricity bill using slab-based
elifconditions. - Write a program that classifies a triangle as equilateral, isosceles, or scalene based on three side lengths.
- Write a menu-driven program using
match-casewith at least 4 options.
Challenge
- Write a program that checks if a number is divisible by both 3 and 5, only 3, only 5, or neither — using appropriate conditions.
- Build a simple traffic light simulator: given a color ("red", "yellow", "green") using
match-case, print the correct action ("Stop", "Get Ready", "Go"). - Write a BMI calculator that takes height and weight, calculates BMI, and prints the category (Underweight/Normal/Overweight/Obese) using
if-elif-else.