Skip to main content
Albero Academy

if / elif / else

Make decisions with conditional branches and understand truthiness.

Flow Control11 min

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:

a single branch
temperature = 38
if temperature > 37.5:
print("You have a fever")
print("Rest and hydrate") # same indent = same block
print("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:

a chain of conditions
score = 72
if 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 valuesEverything else is truthy
FalseNon-zero numbers
NoneNon-empty strings
0Non-empty lists/dicts/sets
"" [] {}Most objects
idiomatic truthiness
items = []
if items: # reads as "if there are any items"
print("has items")
else:
print("empty") # this runs — [] is falsy
name = input("Name: ")
if not name: # empty string is falsy
print("Name is required")

The ternary expression

For a simple either/or value, the one-line conditional expression is cleaner than a full if/else:

value if condition else value
age = 20
status = "adult" if age >= 18 else "minor"
# Combine conditions with and / or / not
if age >= 18 and has_id:
print("entry allowed")

Key takeaways

  1. 01if / elif / else choose one branch; the first matching condition wins, then the rest are skipped.
  2. 02Order elif conditions from most specific to least, or an earlier branch will steal matches.
  3. 03A colon plus indentation (not braces) defines each block body.
  4. 04Truthiness: 0, "", [], {}, None and False are falsy; everything else is truthy — so if items: means "non-empty".
  5. 05The ternary "a if cond else b" is a concise one-line conditional value.

Finished this chapter?

Mark it complete to track your progress through Python.