Conditional Logic
Beginner · 18 min read · ▶ live playground · ✦ checkpoint
Your program can already remember values, calculate with them, and print answers. Now it gets to choose. Conditional logic is code that lets a program pick what to do next based on a yes-or-no test, and it turns Python from a straight recipe into a tiny decision maker.
Questions Python can answer
An expression is code that produces a value; a Boolean expression is an expression that produces True or False. Think of it as a yes-or-no question written in Python: "Is this score high enough?" "Did the password match?" "Is the cart empty?"
A comparison operator is a symbol that compares two values and returns True or False. You already know arithmetic operators like + and *; comparisons are the operators programs use when they need a decision.
score = 82
print(score >= 70)
print(score == 100)
print(score != 0)TrueFalseTrue
The comparison operators you will reach for most are:
==asks "are these equal?"!=asks "are these different?"<asks "is the left side less than the right side?"<=asks "is the left side less than or equal to the right side?">asks "is the left side greater than the right side?">=asks "is the left side greater than or equal to the right side?"
Read those lines aloud:
score >= 70asks whetherscoreis at least 70.score == 100asks whetherscoreis equal to 100.score != 0asks whetherscoreis not equal to 0.
The double equals == matters. A single = assigns a name, like score = 82. A double == asks a question, like score == 82.
Branching with if, elif, and else
A statement is a complete instruction Python can run; control flow is the order Python runs those statements in. Until now, that order has been top to bottom. An if statement adds a branch, a path of code Python may take, like a sign at a fork in the path: "If this is true, go this way."
A condition is the expression after if or elif that Python tests for truthiness. A Boolean expression is one common kind of condition. A block is the indented group of lines that belongs to the line above it. Indentation means spaces at the start of a line, and Python uses those spaces as structure, not decoration.
score = 82
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "Not yet"
print(f"Score: {score}")
print(f"Grade: {grade}")Score: 82Grade: B
Python checks the branches in order. The first true branch runs, then the whole chain is done. For score = 82, score >= 90 is false, score >= 80 is true, and Python never checks the later elif.
Use else for the fallback path. It has no condition because it means "nothing above matched."
Try it — tune the grade rules
Change score and attendance, then run the program again. Watch how only one branch in each chain gets picked.
Truthiness: values as quick answers
Truthiness is Python's rule for treating a non-Boolean value as true or false in a condition. It is like glancing at a container and asking, "Is there anything here?"
For the values you know so far, blank or zero-like values count as false: False, 0, 0.0, "", and None. Present values count as true: True, nonzero numbers, and non-empty strings.
nickname = ""
backup_name = "Sam"
if nickname:
print(f"Welcome, {nickname}")
else:
print(f"Welcome, {backup_name}")
cart_total = 0
if cart_total:
print("Ready to checkout")
else:
print("Your cart is empty")Welcome, SamYour cart is empty
You could write if nickname != "":, and sometimes that is clearer. Truthiness shines when the meaning is natural: "if there is a nickname" or "if there is a total."
Combining decisions
A logical operator is a keyword that combines or flips Boolean expressions. The three you use constantly are and, or, and not.
Think of a door checklist. and means every required item must pass. or means at least one acceptable item can pass. not flips the answer.
age = 17
has_ticket = True
with_adult = True
can_enter = has_ticket and (age >= 18 or with_adult)
print(can_enter)
account_locked = False
print(not account_locked)TrueTrue
Parentheses are your friend here. Python has precedence rules for and, or, and not, but readable decision code should not make people remember them. Mark the part you mean to group, the same way you used parentheses to highlight arithmetic earlier.
Nesting: a question inside a question
Nesting means putting one block inside another block. It is a follow-up question: first ask whether the work is A-level, then, only inside that path, ask whether it was late.
score = 91
late_work = True
if score >= 90:
if late_work:
print("A-level work, but late")
else:
print("A-level work, on time")
else:
print("Keep practicing")A-level work, but late
Nesting is useful when the inner question only matters after the outer question passes. If two conditions are really part of the same question, and often reads better than an extra level of indentation.
Conditional expressions
A conditional expression is a one-line expression that chooses between two values. It is also called a ternary expression, which means it has three parts: value if true, condition, value if false.
Use it when the choice is small enough to read in one breath, like a tiny two-label printer.
temperature = 38
message = "drink water" if temperature >= 35 else "enjoy the walk"
print(message)drink water
Do not force a whole story into this shape. If the branches need several statements, use if, elif, and else. The conditional expression is for choosing a value, not for hiding a full decision tree on one line.
Checkpoint
Answer all three to mark this lesson complete
You can now make a program choose a path instead of marching straight down the page. Next, pattern matching gives you a cleaner tool for some multi-way choices, especially when one value can have several clear shapes.