I accidentally wrote my first
infinite loop in college (don’t worry, I’ll teach you how to avoid
that!). Conditional logic is like the brain of your program—it’s
how your code makes decisions, like choosing whether to print “Wear a
jacket!” or “Grab some sunglasses!” based on the weather. In
this guide, we’re going to dive into Python’s awesome tools for
decision-making: the classic if/elif/else statements, the snappy
conditional expression, and the super-cool match/case feature
(new in Python 3.10). Plus, we’ll unpack logical operators and
Python’s quirky “truthiness” concept. By the end,
you’ll be writing code that’s smart, readable, and totally
Pythonic. Let’s get started!
1. The Classic if/elif/else Statement: Your Code’s
Decision-Maker
The if statement is like the GPS of programming—it tells
your code where to go based on a condition. It’s super simple in Python,
and I promise, once you get the hang of it, you’ll be using it
everywhere!
How It Works
An if statement checks a condition (like “Is it
raining?”). If the condition is True, it runs a block of
code. The condition lives in the if line, followed by a colon
(:), and the code to run is indented below it. Think of
indentation as Python’s way of saying, “This stuff belongs
together!”
Here’s a quick example I used when I was learning Python to figure out if I could skip studying for a test:
# Checking if I aced my last test
score = 95
if score > 90:
print("Woohoo! I can chill tonight!")
# Output: Woohoo! I can chill tonight!
The condition (score > 90) is checked, and since it’s
True, the print statement runs. You can use any
comparison (like <, ==, or !=) or
even combine them with logical operators (we’ll get to those later).
Simple Example: Is It Snack Time?
Let’s say you’re hungry and want to know if it’s time for a snack:
# Checking if it’s snack time
hour = 15 # 3 PM
if hour >= 14 and hour <= 16:
print("Snack time! Grab some cookies!")
# Output: Snack time! Grab some cookies!
Adding Options with elif
Sometimes, you’ve got more than one choice. Like when I’m picking
what to wear based on the weather, I don’t just decide between
“hot” and “not hot”—there’s a whole range!
That’s where elif (short for “else if”) comes
in. It lets you check extra conditions if the first if fails.
Here’s an example to pick a study vibe based on your energy level:
# Choosing a study vibe
energy_level = 80
if energy_level >= 90:
print("Feeling epic! Crank up the music and code!")
elif energy_level >= 70:
print("Pretty good! Let’s study with some coffee.")
elif energy_level >= 50:
print("Kinda tired. Maybe a quick nap first?")
else:
print("Ugh, low battery. Time for a break!")
# Output: Pretty good! Let’s study with some coffee.
Each elif only runs if the stuff before it was
False. You can stack as many elifs as you want, but
only one block runs.
Simple Example: Picking a Study Spot
Here’s one I use to pick where to study based on the time of day:
# Choosing a study spot
time = 18 # 6 PM
if time < 12:
print("Morning vibes! Head to the library.")
elif time < 17:
print("Afternoon grind! Coffee shop it is.")
elif time < 20:
print("Evening focus! My desk with fairy lights.")
else:
print("Late night? Couch with snacks!")
# Output: Evening focus! My desk with fairy lights.
The Catch-All: else
The else is your backup plan—it runs if none of the
if or elif conditions are True.
It’s like saying, “If all else fails, do this.” You can only
have one else per if statement, and it goes at the
end.
The Indentation Rule
Python is super picky about indentation—it’s how it knows which
code belongs to an if block. Use four spaces (not tabs!) to
indent, and keep it consistent, or you’ll get an
IndentationError. I learned this the hard way when my first big
project crashed because I mixed spaces and tabs (yikes!).
If you need a placeholder (like when you’re planning code but not ready
to write it), use the pass statement. It’s like saying,
“I’ll fill this in later.”
# Placeholder for a future feature
def pick_study_playlist(mood):
if mood == "upbeat":
pass # I’ll add Spotify logic later!
else:
print("No playlist yet.")
2. The Compact Conditional Expression
Sometimes, an if/else block feels like overkill for a simple
choice. That’s where Python’s conditional expression (aka ternary
operator) comes in—it’s like a one-line if/else. I
love using these when I’m writing quick scripts to save time.
Syntax and Example
The syntax is: value_if_true if condition else value_if_false.
It’s like saying, “If this is true, pick this; otherwise, pick
that.”
Here’s one I use to decide if I’m coding or binge-watching:
# Quick decision for my evening
mood = "nerdy"
plan = "Code a game" if mood == "nerdy" else "Watch a sci-fi show"
print(plan)
# Output: Code a game
You can even sneak it into an f-string for extra cool points:
# Checking if I’m late for class
minutes_late = 5
message = f"You’re {'late' if minutes_late > 0 else 'on time'} for class!"
print(message)
# Output: You’re late for class!
Simple Example: Pass or Fail?
Here’s a quick way to label a test result:
# Labeling a test result
score = 65
result = "Pass" if score >= 60 else "Fail"
print(f"Your result: {result}")
# Output: Your result: Pass
The Readability Tightrope & Lazy Evaluation
Conditional expressions are awesome for short, simple choices, but don’t
go wild nesting them—it’s like trying to read a text message in a
funhouse mirror! Stick to if/elif/else for complex stuff.
Also, Python’s smart: it only evaluates the part of the expression it
needs (called “lazy evaluation”). So, if the condition is
True, it skips the else part entirely. This saves
time and prevents errors.
# Avoid nesting for readability
grade = 85
letter = "A" if grade >= 90 else ("B" if grade >= 80 else "C")
print(letter) # Output: B
# This works but is hard to read—use if/elif/else instead!
3. Structural Pattern Matching: The match/case Statement (Python
3.10+)
Okay, this one’s my favorite—Python’s
match/case statement (new in Python 3.10) is like a superpower
for handling complex choices. Think of it as a fancy if statement
that’s amazing for dealing with structured data, like lists or
dictionaries. I discovered this when I was building a game and needed to
handle different player commands.
The Core Idea
You give match a value (the “subject”), and each
case checks if it matches a pattern. The first matching pattern
runs its code, and then you’re done. It’s like a
choose-your-own-adventure book for your code!
Here’s an example for a chatbot I made for fun:
# Handling chatbot commands
command = "greet"
match command:
case "greet":
print("Hey there! Nice to see you!")
case "bye":
print("Catch you later!")
case "help":
print("Need help? I’m here!")
case _: # The wildcard catches everything else
print(f"Huh? I don’t know ‘{command}’.")
# Output: Hey there! Nice to see you!
The _ is like a “whatever” case—it catches
anything that doesn’t match the other cases.
Simple Example: Picking a Study Buddy
Imagine you’re choosing a study buddy based on their subject:
# Picking a study buddy
subject = "math"
match subject:
case "math":
print("Let’s study with Alex, the math whiz!")
case "python":
print("Emma’s your Python pal!")
case "history":
print("Study with Sam, the history buff!")
case _:
print("No study buddy for that subject yet.")
# Output: Let’s study with Alex, the math whiz!
Beyond Simple Literals: Advanced Patterns
match/case is like a Swiss Army knife—it can do way more
than just match words. Here are some cool tricks I use in my projects:
OR Patterns (|)
Combine multiple values for one action. I use this for my weekend planner:
# Planning my weekend
day = "Sunday"
match day:
case "Saturday" | "Sunday":
print("It’s chill time—movie marathon!")
case _:
print("Back to studying!")
# Output: It’s chill time—movie marathon!
Patterns with Type Checking
Check the type of data. I used this when grading assignments with mixed inputs:
# Checking input type
answer = 42
match answer:
case int():
print("You gave me a number!")
case str():
print("That’s a string!")
case _:
print("What even is that?")
# Output: You gave me a number!
Conditions on Patterns (if guard)
Add an extra condition with an if. I use this to filter valid
game scores:
# Checking a game score
score = 150
match score:
case int() if score > 100:
print(f"Wow, {score} is a high score!")
case int():
print(f"{score} is okay, keep playing!")
case _:
print("That’s not a score!")
# Output: Wow, 150 is a high score!
Capture Patterns
Grab a value and use it. I love this for parsing user names:
# Greeting a user
username = "Luna"
match username:
case str(name):
print(f"Yo, {name}! What’s up?")
case _:
print("Gimme a real name!")
# Output: Yo, Luna! What’s up?
Sequence Patterns
Break apart lists or tuples. I used this for a game’s movement commands:
# Handling game moves
move = ["go", "north"]
match move:
case ["go", direction]:
print(f"Moving {direction}!")
case ["stop"]:
print("Holding position!")
case _:
print("Unknown move!")
# Output: Moving north!
Mapping Patterns
Check dictionaries, like for a to-do list app I built:
# Checking a to-do item
task = {"type": "study", "hours": 2}
match task:
case {"type": "study", "hours": hours}:
print(f"Study for {hours} hours—let’s do this!")
case {"type": "break"}:
print("Time to relax!")
case _:
print("What’s that task?")
# Output: Study for 2 hours—let’s do this!
match/case is a game-changer for making your code clean and
expressive, especially when you’re juggling complex data like game
commands or app settings.
The Underlying Logic: Operators and Truthiness
Conditions are the heart of all this decision-making, and they’re built
with operators that give you True or False.
Let’s break it down!
1. Comparison Operators
These compare two values:
==(equals)!=(not equals)<(less than)>(greater than)<=(less than or equal to)>=(greater than or equal to)
Example: 5 < 10 is True. I use these to check if
I’m running late:
# Am I late?
current_time = 9
if current_time > 8:
print("Hurry up, class started!")
# Output: Hurry up, class started!
2. Logical Operators
Combine conditions with:
-
not: FlipsTruetoFalse(or vice versa). -
and:Trueif both sides areTrue. -
or:Trueif at least one side isTrue.
I use these to decide if I can skip a chore:
# Can I skip dishes?
dishes_done = False
room_clean = False
if not dishes_done and not room_clean:
print("Gotta clean something first!")
# Output: Gotta clean something first!
Python checks operators in order (like math: parentheses first, then
not, and, or). You can use parentheses
to make it clear, like (x > 5) and (y < 10).
Python also lets you chain comparisons, like 1 < x < 10,
which is super handy for ranges:
# Checking if I’m in study mode
hour = 14
if 9 <= hour <= 17:
print("Study mode: ON!")
# Output: Study mode: ON!
Truthiness: Python’s Quirky Logic
In Python, almost anything can act like True or
False. “Falsy” things are like empty or zero stuff,
and everything else is “truthy.” Here’s what’s falsy:
None0(integer)0.0(float)False0 + 0j(complex)""(empty string)[](empty list)()(empty tuple){}(empty dictionary)set()(empty set)
I use this to check if my to-do list is empty:
# Checking my to-do list
tasks = []
if not tasks:
print("No tasks! Time to celebrate!")
# Output: No tasks! Time to celebrate!
Watch Out! Don’t use if not my_var to
check for None—it’ll catch other falsy stuff like
0 or []. Use if my_var is None instead.
# Checking for None
my_var = 0
if my_var is None:
print("It’s None!")
else:
print("Not None, just falsy.")
# Output: Not None, just falsy.
Lazy Evaluation
Python’s and and or are lazy—they stop
as soon as they know the answer. If A in A and B is
False, Python skips B. This saved me once when
checking a list index:
# Avoiding an error
my_list = []
index = 0
if len(my_list) > index and my_list[index] == 5:
print("Found a 5!")
else:
print("List is too short or no 5.")
# Output: List is too short or no 5.
If len(my_list) > index is False, Python
doesn’t try to access my_list[index], avoiding a crash.
Wrapping Up: You’ve Got This!
Python’s conditional tools are like your code’s
superpower—they let your programs make smart choices. Whether
you’re using if/elif/else for simple decisions, conditional
expressions for quick one-liners, or match/case for fancy data
handling, you’re now equipped to write code that’s clear and
clever. Keep practicing, experiment with your own projects (maybe a study
planner or a game?), and you’ll be a Python decision-making pro in no
time. I’m rooting for you!
Quiz Time! Test Your Skills
- What’s the output of this code?
x = 8
if x > 5:
x = 3
print(x)
a) 8
b) 3
c) 5
d) Error
-
Which is falsy in Python?
a) " " (a space)
b) [] (empty list)
c) 1
d) True -
Why use a conditional expression?
a) It’s faster thanif/else.
b) It handles multipleelifconditions.
c) It’s concise for simpleif/elsechoices.
d) It’s required for loops. -
What does the
_wildcard do inmatch/case?
a) Matches the underscore character.
b) Catches any unmatched value.
c) Raises an error if no match.
d) Binds the value to_. -
What’s “short-circuiting” in
A and B?
a) IfAisTrue, skipB.
b) IfAisFalse, skipB.
c) Always evaluate both.
d) EvaluateBfirst. -
What does this
matchstatement print?
action = ["jump", "high"]
match action:
case ["jump", height]:
print(f"Jumping {height}!")
case ["run", *rest]:
print(f"Running with {rest}")
case _:
print("Unknown action")
a) Jumping high!
b) Running with ['high']
c) Unknown action
d)
Syntax error
-
How do you check if a username isn’t “admin” or “guest”?
a)if username != "admin" or username != "guest":
b)if not (username == "admin" and username == "guest"):
c)if username != "admin" and username != "guest":
d)if username not in ["admin", "guest"]:(Fix the logic from a) -
What’s the “arrow anti-pattern”?
a) Too many lambdas.
b) Nestedifstatements drifting right.
c) Long functions.
d) Usinggoto(not in Python).
Answer Key
-
b) 3
Explanation:x > 5isTrue, sox = 3runs, andprint(x)shows3. -
b) []
Explanation: Empty lists are falsy. A space,1, andTrueare truthy. -
c) It’s concise for simple
if/elsechoices
Explanation: It’s great for one-line decisions, not for complex logic. -
b) Catches any unmatched value
Explanation:_is a catch-all for anything not matched. -
b) If
AisFalse, skipB
Explanation:andstops if the first part isFalse. -
a) Jumping high!
Explanation:["jump", "high"]matches the first case, capturing “high”. -
c)
if username != "admin" and username != "guest":
Explanation: Useandto check both conditions. Optiondis also good but fixesa’s logic error. -
b) Nested
ifstatements drifting right
Explanation: Deep nesting makes code hard to read.
Frequently Asked Questions (FAQ)
Q1: Is there a switch/case in Python like in other
languages?
A1: Not exactly, but Python 3.10’s match/case is
even better! It’s like a super-powered switch that can
handle lists, dictionaries, and more. Before 3.10, we used
if/elif/else for everything.
Q2: What’s the “Zen of Python” and how does it relate to
conditionals?
A2: The “Zen of Python” (type import this in
Python to see it!) is a list of principles for writing great code. It loves
simplicity and readability, which is why Python’s
if statements and indentation make your code look clean and
clear.
Q3: Should I use if/elif/else or
match/case?
A3: Use if/elif/else for simple stuff, like checking
numbers or strings. Go for match/case when you’re dealing
with complex data, like game commands or JSON from an API—it’s way
cleaner!
Q4: Can a while loop have an else?
A4: Yup! The else runs if the loop finishes normally (not
with a break). It’s great for things like “I searched
the list and found nothing.”
Q5: What’s the difference between == and
is?
A5: == checks if values are the same (like
5 == 5). is checks if they’re the same object
in memory. Use is for None, like
if x is None.
Q6: Can match/case check number ranges?
A6:
Not directly, but use an if guard:
match number:
case int(x) if 1 <= x <= 10:
print("Between 1 and 10!")
Q7: Why does Python use indentation instead of braces?
A7: It forces your code to look neat, so everyone’s code is easy
to read. I used to hate it, but now I love how clean my code looks!
Glossary of Key Terms
-
and operator: Returns
Trueif both sides areTrue. Stops early if the first isFalse. -
assert statement: Checks a condition and crashes with an
error if
False. Great for debugging. -
Assignment expression (
:=): The “walrus operator” assigns and uses a value in one go (Python 3.8+). - break statement: Jumps out of a loop early.
-
case statement: Part of
match, defines a pattern to check. -
Chained comparisons: Stuff like
1 < x < 10—short and sweet! - continue statement: Skips to the next loop iteration.
-
Control structure: Code that controls flow, like
ifor loops. -
Conditional expression: One-liner like
x if y else z. -
Conditional: Code that runs based on a
True/Falsecheck. -
else branch: Runs if no
iforelifconditions areTrue. - elif branch: Checks another condition if earlier ones fail.
-
Evaluation order: How Python decides what to calculate
first (parentheses, then
not,and,or). -
Exception handling: Using
try/exceptto manage errors. - for loop: Loops over a list, string, or other iterable.
-
if statement: Runs code if a condition is
True. - Indentation: Spaces to group code blocks—Python’s signature move.
- lambda: A tiny, nameless function.
-
Lazy evaluation: Only calculating what’s needed, like
skipping
BinA and BifAisFalse. -
Logical operator:
and,or,notfor combining conditions. - match statement: Checks a value against patterns (Python 3.10+).
-
not operator: Flips
TruetoFalseor vice versa. - Operator precedence: Rules for what gets calculated first.
-
or operator:
Trueif either side isTrue. Stops if the first isTrue. - pass statement: A do-nothing placeholder.
-
Relational operator: Compares values, like
<or==. - Short-circuit evaluation: Same as lazy evaluation.
-
Structural pattern matching:
match/casefor fancy conditionals. -
Truthiness: How Python decides if something’s
TrueorFalse. -
Wildcard pattern (
_): Catches any unmatched value inmatch/case. -
while loop: Loops while a condition is
True. - yield statement: Makes a function return values one at a time (for generators).
