if, elif, and else statements
These statements let your program make decisions based on conditions — they’re the core of control flow in Python.
Basic Syntax
if condition:
# code block if condition is True
elif another_condition:
# code block if elif is True
else:
# code block if none are True
- Each condition is checked in order
- Indentation (typically 4 spaces) defines code blocks
- You can have one if, zero or more elif, and zero or one else
Simple Example:
temperature = 25
if temperature > 30:
print(“It’s hot outside.”)
elif temperature >= 20:
print(“It’s a nice day.”)
else:
print(“It’s cold outside.”)
Output: “It’s a nice day.”
Flow Explanation:
- If the if condition is True, it runs that block and skips the rest.
- If the if is False, Python checks the elif (if any).
- If none of the conditions are True, the else block runs.
Real-Life Example: Age Check
age = int(input(“Enter your age: “))
if age < 13:
print(“You are a child.”)
elif age < 18:
print(“You are a teenager.”)
else:
print(“You are an adult.”)
Nesting if Statements
You can nest conditions inside others:
score = 85
if score >= 50:
print(“You passed!”)
if score >= 80:
print(“Great job!”)
else:
print(“You failed.”)
Common Mistakes to Avoid
Mistake | Fix |
---|---|
Missing colon : |
Add a colon at end of conditionif x == 5 → if x == 5: |
Improper indentation | Use consistent 4-space indentationprint("Hello") → print("Hello") |
Using = instead of == |
= is assignment, == is comparisonif x = 5: → if x == 5: |
Forgetting to cast input() to int |
Use int(input()) if comparing numbersage = input() → age = int(input()) |
Quick Quiz
What will this print?
x = 10
if x > 20:
print(“A”)
elif x > 5:
print(“B”)
else:
print(“C”)
Answer: “B”
Summary Table:
Statement | Purpose |
---|---|
if |
Starts a conditional check |
elif |
Checks another condition if the previous if or elif fails |
else |
Runs if no if or elif conditions are met |
Truthy and falsy values
In Python, every value has an inherent Boolean value — either True or False — even if it’s not literally the TrueorFalse` Boolean type.
These values are evaluated when used in conditions, such as in if statements.
What are “Truthy” and “Falsy”?
- Truthy: A value that evaluates to True when used in a Boolean context.
- Falsy: A value that evaluates to False.
Example:
if “hello”:
print(“This is truthy.”)
Output: This is truthy.
- Because a non-empty string (“hello”) is considered truthy.
Falsy Values in Python
These values are considered False in Boolean contexts:
Type | Falsy Value |
---|---|
Boolean | False |
NoneType | None |
Numeric | 0 , 0.0 , 0j |
Sequence/Collection | '' (empty string),[] (empty list),() (empty tuple),{} (empty dict),set() (empty set) |
Custom object | Any object with __bool__() or __len__() returning False |
# All of these evaluate as False
if not “”:
print(“Empty string is falsy”)
if not 0:
print(“Zero is falsy”)
if not None:
print(“None is falsy”)
if not []:
print(“Empty list is falsy”)
Truthy Values in Python
Everything else not listed as falsy is truthy.
Examples:
“hello” # non-empty string
42 # any non-zero number
[1, 2, 3] # non-empty list
{“a”: 1} # non-empty dictionary
True # obviously!
These will all make if statements run:
if [1, 2, 3]:
print(“Truthy list!”)
if “Python”:
print(“Truthy string!”)
Boolean Context Examples:
x = []
if x:
print(“List has items.”)
else:
print(“List is empty.”)
Output: List is empty.
Using bool() to Check Value Truthiness
You can test how Python evaluates any value using bool():
print(bool(0)) # False
print(bool(“Hi”)) # True
print(bool([])) # False
print(bool([0])) # True (non-empty list!)
Summary:
Value Type | Truthy Example | Falsy Example |
---|---|---|
String | "Python" |
"" |
Number | 42 |
0 |
List | [1, 2] |
[] |
Dictionary | {"a": 1} |
{} |
Boolean | True |
False |
NoneType | — | None |
Nested conditionals
What Are Nested Conditionals?
- A nested conditional is when you place an if, elif, or else inside another if block.
- This lets you check multiple layers of logic, like decision trees.
Basic Syntax:
if condition1:
if condition2:
# Runs if both condition1 AND condition2 are True
else:
# Runs if condition1 is True but condition2 is False
else:
# Runs if condition1 is False
Simple Example:
age = 20
has_ticket = True
if age >= 18:
if has_ticket:
print(“You can enter the event.”)
else:
print(“You need a ticket to enter.”)
else:
print(“You must be 18 or older to enter.”)
Output:
You can enter the event.
Why Use Nested Conditionals?
- When one condition depends on another
- To create multi-level decision structures
- When you want to check a second condition only if the first is True
Example: Student Grading System
grade = 85
if grade >= 50:
if grade >= 90:
print(“A+”)
elif grade >= 80:
print(“A”)
else:
print(“Pass”)
else:
print(“Fail”)
Output:
A
Alternative: Combine Conditions with and
You can sometimes flatten nested conditionals by using and:
if age >= 18 and has_ticket:
print(“You can enter.”)
elif age >= 18:
print(“Get a ticket.”)
else:
print(“You’re too young.”)
Both versions are valid — use nesting for clarity when conditions are hierarchical.
Common Mistakes to Avoid
Mistake | How to Fix |
---|---|
Misaligned indentation | Use consistent 4-space indentation |
Too many nested levels | Try combining conditions with and |
Forgetting outer condition | Make sure inner if runs inside the outer |
Summary:
- Use nested conditionals when one check depends on another.
- Can be useful for multi-step logic (e.g. eligibility checks).
- Don’t over-nest — too many levels can make code harder to read.
Practice Idea
Prompt:
Ask the user for:
- their age
- if they’re a student
- Then decide:
- If they can get a discount
- If they’re allowed access
Want me to write this as an exercise with solution or a quiz-style challenge?
match (Python 3.10+)
What is match?
The match statement in Python is used for pattern matching. It works like a switch statement in other languages — but with added power for complex data matching like objects, tuples, and more.
Introduced in Python 3.10, it allows cleaner, more readable conditionals.
Basic Syntax
match variable:
case pattern1:
# do something
case pattern2:
# do something else
case _:
# default case (like else)
Example 1: Simple Value Matching
status_code = 404
match status_code:
case 200:
print(“OK”)
case 404:
print(“Not Found”)
case 500:
print(“Server Error”)
case _:
print(“Unknown status”)
Output:
Not Found
The Underscore _
The _ case is a wildcard — it matches anything not matched before. Think of it like else.
Example 2: Match with Variables (Capture)
- You can also capture values from patterns:
command = (“move”, “left”)
match command:
case (“move”, direction):
print(f”Moving {direction}”)
case (“stop”,):
print(“Stopping”)
Output:
Moving left
Example 3: Match with Multiple Options
fruit = “apple”
match fruit:
case “apple” | “banana”:
print(“It’s a fruit we have.”)
case “kiwi”:
print(“Out of stock.”)
case _:
print(“Unknown item.”)
Output:
It’s a fruit we have.
Example 4: Matching with Conditions (if Guards)
x = 10
match x:
case x if x > 0:
print(“Positive number”)
case x if x < 0:
print(“Negative number”)
case _:
print(“Zero”)
When to Use match
Use match when:
- You’re matching discrete values (like switch-case)
- You need to check data shapes, like tuples or lists
- You want cleaner alternatives to long if-elif-else chains
Advanced Example: Matching Lists
data = [1, 2, 3]
match data:
case [1, 2, 3]:
print(“Exact match”)
case [1, *rest]:
print(f”Starts with 1, rest is {rest}”)
case _:
print(“No match”)
Summary:
Concept | Keyword or Usage |
---|---|
Start pattern matching | match |
Match specific case | case value: |
Default case | case _: |
OR / multiple options | case "a" | "b": |
Use with tuples/lists | case (a, b): or case [x, y, z]: |
Conditional guard | case x if x > 0: |
Bonus Idea
Would you like:
- Practice problems (e.g. color picker, command handler)?
- A side-by-side comparison with if/elif?
- A quiz or mini project using match?
- Let me know how you’d like to expand on this!