Lesson 46 min read
Conditionals
Teach your code to make decisions like a choose-your-own-adventure book
If, Elif, Else — The Decision Trio
Imagine you're a bouncer at a club. You check a condition ("Are you on the list?") and decide what happens next. That's exactly what if does in Python.
The structure is simple:
if— Check the first condition. If it'sTrue, run this block.elif— "Else if" — only checked when the previous condition wasFalse. You can have as many as you want.else— The catch-all. Runs when nothing above wasTrue.
Indentation matters! Python uses 4 spaces (not curly braces) to define code blocks. Everything indented under an if belongs to that branch.
Basic Conditionals
Truthy & Falsy Values
In Python, you don't always need an explicit True or False. Every value has a "truthiness" to it:
Falsy (treated as False):
False,None,0,0.0- Empty things:
"",[],{},(),set()
Truthy (treated as True):
- Everything else! Non-zero numbers, non-empty strings, non-empty lists, etc.
This is super handy for checking if something is empty or exists.
Truthy/Falsy & Ternary Expressions
Nested Conditions & Combining Logic
You can put if statements inside other if statements — but be careful not to go too deep! If you're nesting more than 2 or 3 levels, it's usually a sign you should refactor with and/or or use a function.
Nested Conditions & Combined Logic
Note: Pro tip: Avoid deep nesting by flipping conditions. Instead of
if valid: (big block of code), try if not valid: print("error"); return. This is called a guard clause and it keeps your code flat and readable.