Conditionals let a program choose what to do. Based on whether a condition is true or false, different blocks of code run — this is how software makes decisions, from "is the user logged in?" to "which grade does this score earn?".
The if statement
An if runs its block only when the condition is true. Python uses a colon and indentation (four spaces) to mark the body — there are no curly braces:
temperature = 38if temperature > 37.5:print("You have a fever")print("Rest and hydrate") # same indent = same blockprint("Take care") # not indented → always runs
elif and else
Add elif (else-if) branches for more conditions, and a final else for "none of the above". Python checks them top to bottom and runs the first that matches, then skips the rest:
score = 72if score >= 75:grade = "Distinction"elif score >= 40:grade = "Pass"else:grade = "Fail"print(grade) # Pass — the first matching branch wins
Truthiness
Any value can be tested in a boolean context, not just True/False. Python treats these as falsy:
| Falsy values | Everything else is truthy |
|---|---|
False | Non-zero numbers |
None | Non-empty strings |
0 | Non-empty lists/dicts/sets |
"" [] {} | Most objects |
items = []if items: # reads as "if there are any items"print("has items")else:print("empty") # this runs — [] is falsyname = input("Name: ")if not name: # empty string is falsyprint("Name is required")
The ternary expression
For a simple either/or value, the one-line conditional expression is cleaner than a full if/else:
age = 20status = "adult" if age >= 18 else "minor"# Combine conditions with and / or / notif age >= 18 and has_id:print("entry allowed")
Key takeaways
- 01if / elif / else choose one branch; the first matching condition wins, then the rest are skipped.
- 02Order elif conditions from most specific to least, or an earlier branch will steal matches.
- 03A colon plus indentation (not braces) defines each block body.
- 04Truthiness: 0, "", [], {}, None and False are falsy; everything else is truthy — so if items: means "non-empty".
- 05The ternary "a if cond else b" is a concise one-line conditional value.
