My Notes
Python Conditional Statements - The Complete Breakdown
Python Conditional Statements — The Complete Breakdown
So what even is a conditional?
Your code runs top to bottom, line by line. Every line executes. That's fine for simple scripts — but real programs need to make decisions. Should I let this user in? Is this score passing? Did the file exist or not?
A conditional says: "check this condition — if it's true, run this block. If it's not, go somewhere else." It's how your code stops being a dumb script and starts actually thinking.
Python uses three keywords for this: if, elif, and else.
The basic structure
if condition:
# runs if condition is True
elif another_condition:
# runs if the first was False but this is True
else:
# runs if everything above was False
Only one block ever runs. Python checks from top to bottom, finds the first True condition, runs that block, and skips the rest. Once a match is found, it's done.
if alone — the simplest case
score = 85
if score >= 70:
print("You passed.")
Output:
You passed.
If score were 50, nothing would print at all. There's no else here — if the condition is False, Python just moves on.
if + else — two paths
score = 55
if score >= 70:
print("You passed.")
else:
print("You failed.")
Output:
You failed.
Now there's always an outcome. Either the condition is true and you pass, or it's false and you fail. No middle ground, no silence.
if + elif + else — multiple paths
elif is short for "else if." It gives you more branches.
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
Output:
Grade: B
Python hits score >= 90 — False. Moves to score >= 80 — True. Prints "Grade: B" and stops. The remaining elif and else never even get checked.
You can have as many elif blocks as you want. There's no limit.
The comparison operators — how conditions are built
These are what go inside your if statements.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | equal to | 5 == 5 | True |
!= | not equal to | 5 != 3 | True |
> | greater than | 10 > 7 | True |
< | less than | 3 < 8 | True |
>= | greater than or equal | 5 >= 5 | True |
<= | less than or equal | 4 <= 3 | False |
The most important one to get right: == checks equality, = assigns a value. Using = inside an if condition is the single most common beginner bug.
x = 10
if x == 10: # correct — checking if x equals 10
print("yes")
if x = 10: # SyntaxError — this is assignment, not comparison
print("yes")
Combining conditions — and, or, not
and — both conditions must be true
age = 20
has_permission = True
if age >= 18 and has_permission:
print("Access granted.")
Output:
Access granted.
Both age >= 18 and has_permission must be True. If either is False, the whole condition is False.
or — at least one condition must be true
is_admin = False
is_owner = True
if is_admin or is_owner:
print("You can edit this.")
Output:
You can edit this.
Only one needs to be True. If both are False, then it's False.
not — flip the result
is_banned = False
if not is_banned:
print("Welcome.")
Output:
Welcome.
not inverts the boolean. not False becomes True, so the block runs.
Combining all three
age = 17
is_admin = False
has_parent_approval = True
if (age >= 18 or has_parent_approval) and not is_admin:
print("Entry allowed.")
else:
print("Entry denied.")
Output:
Entry allowed.
Use parentheses to control what gets evaluated together — same as math. Python evaluates the parenthesised part first.
Checking booleans directly
You don't need to write == True or == False. Python lets you use the variable directly.
is_logged_in = True
# the verbose way — works but unnecessary
if is_logged_in == True:
print("Hello.")
# the clean way — preferred
if is_logged_in:
print("Hello.")
Both do the same thing. The second is what real Python code looks like.
For False:
if not is_logged_in:
print("Please log in.")
Much cleaner than if is_logged_in == False.
Checking if something is None
Always use is for None checks, not ==.
result = None
if result is None:
print("No result yet.")
if result is not None:
print(f"Got: {result}")
Output:
No result yet.
is checks identity — whether two things are literally the same object in memory. None is a singleton in Python, so is None is the correct and more reliable way to check for it.
Checking membership — in and not in
in checks if a value exists inside a list, string, or other collection.
skills = ["python", "security", "ctf"]
if "python" in skills:
print("Python skill found.")
if "java" not in skills:
print("Java not in list.")
Output:
Python skill found.
Java not in list.
Works on strings too:
email = "kalyan@northeastern.edu"
if "@" in email:
print("Valid email format.")
Output:
Valid email format.
Nested conditionals — if inside if
You can put conditionals inside conditionals. Each level needs proper indentation.
age = 20
has_id = True
if age >= 18:
if has_id:
print("Entry allowed.")
else:
print("Need ID to enter.")
else:
print("Must be 18 or older.")
Output:
Entry allowed.
But don't nest too deep — it gets hard to read fast. Three levels of nesting is usually a sign you should restructure with and/or instead.
The shortcut — ternary (one-line if/else)
Python has a one-liner version for simple if/else assignments.
The long way:
score = 85
if score >= 70:
result = "pass"
else:
result = "fail"
The one-liner:
result = "pass" if score >= 70 else "fail"
print(result)
Output:
pass
Pattern: value_if_true if condition else value_if_false. Only use this for simple cases — if the logic is complex, write it out fully.
match — Python's version of switch (Python 3.10+)
If you come from other languages, you might know switch statements. Python 3.10 added match as its equivalent.
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
case _ is the catch-all — like else. If nothing matches, it runs.
This is cleaner than a long chain of elif when you're checking one variable against many specific values. But it only works on Python 3.10 or newer — if/elif/else works everywhere.
All the scenarios — which to use when
Simple yes/no decision → if + else
if is_authenticated:
show_dashboard()
else:
redirect_to_login()
Multiple outcomes on one value → if + elif + else
if severity == "critical":
alert_immediately()
elif severity == "high":
log_and_notify()
elif severity == "low":
log_only()
else:
ignore()
Two conditions that must both be true → and
if file_exists and has_read_permission:
open_file()
Either condition is enough → or
if is_admin or is_superuser:
grant_access()
Flip a condition → not
if not is_blocked:
allow_request()
Check membership → in
if ip_address in whitelist:
allow()
One specific variable vs many values → match (Python 3.10+)
match command:
case "start": start()
case "stop": stop()
case "reset": reset()
case _: print("Unknown command")
Quick one-line assignment → ternary
label = "admin" if is_admin else "user"
The decision table
| Situation | Use |
|---|---|
| One condition, two outcomes | if + else |
| Multiple conditions, multiple outcomes | if + elif + else |
| Both things must be true | and |
| At least one must be true | or |
| Invert a condition | not |
| Check if item exists in a collection | in / not in |
| Check for None | is None / is not None |
| One variable vs many specific values | match (3.10+) |
| Quick inline decision | ternary (x if condition else y) |
The one-line summary
if checks a condition and runs a block if it's true. elif gives you more branches. else catches everything that didn't match. Combine conditions with and, or, and not. Use == to compare — never =. Master these and your code can make any decision you throw at it.