Boolean Logic (AND, OR, NOT) and Compound Conditions
Combine multiple checks into clear compound decisions using AND, OR, and NOT operators, leverage short-circuit evaluation safely, and simplify complex conditions with De Morgan's laws.
In This Article
- Combine individual boolean expressions using AND, OR, and NOT operators in blocks, Python, and C++.
- Use truth tables to verify exactly when compound conditions evaluate to true or false.
- Rely on short-circuit evaluation to guard array bounds or null checks safely.
- Avoid the classic beginner trap of writing 'if x == 3 or 4' and apply De Morgan's laws to simplify negations.
Making Decisions with Multiple Rules
Real-world rules rarely depend on a single isolated check. Consider the rule for opening a boss door in an adventure game: the player must stand next to the door, and the player must hold either the Master Key or at least three Silver Keys, and the player must not be under a freeze curse. Writing that logic using deeply nested if statements inside if statements quickly turns into an unreadable "arrow code" pyramid drifting off the right edge of your screen.
Named after nineteenth-century mathematician George Boole, Boolean logic lets you combine simple true/false comparisons into expressive compound conditions using three fundamental logical operators: AND, OR, and NOT.
The Three Core Logical Operators and Their Truth Tables
Before combining three or four checks at once, you must know the exact rules for each operator when given two boolean inputs, A and B:
- Logical AND (
andin Python,&&in C++): Evaluates totrueonly when bothAis true andBis true. If either side is false, the entireANDexpression is false. Think of it as a strict checklist where every requirement is mandatory. - Logical OR (
orin Python,||in C++): Evaluates totruewhen at least one side is true (eitherAis true, orBis true, or both are true). In programming,ORis inclusive: having both a coupon and a VIP pass still lets you in! AnORexpression is only false when both inputs are false. - Logical NOT (
notin Python,!in C++): A unary operator that takes a single boolean input and flips its truth value:not truebecomesfalse, andnot falsebecomestrue.
Visual Block Logic
IF (hp > 0) AND (has_gold_key OR coins >= 50):
open_treasure_chest()
IF NOT is_paused:
update_game_timer()
Python
if hp > 0 and (has_gold_key or coins >= 50):
open_treasure_chest()
if not is_paused:
update_game_timer()
C++
if (hp > 0 && (hasGoldKey || coins >= 50)) {
openTreasureChest();
}
if (!isPaused) {
updateGameTimer();
}
Operator Precedence: Why Parentheses Matter
Just as multiplication happens before addition in arithmetic (2 + 3 * 4 evaluates 3 * 4 first), boolean operators have a built-in precedence order: NOT binds tightest, followed by AND, followed by OR. Look at the chest condition above: hp > 0 and (has_gold_key or coins >= 50). Without the parentheses around the or clause, the computer would group (hp > 0 and has_gold_key) or (coins >= 50)—meaning a player with 0 health could still open the chest as long as they had 50 coins! Whenever you mix AND and OR in the same condition, always add explicit parentheses to make your intended grouping unambiguous.
Short-Circuit Evaluation: Why Left-to-Right Order Matters
Both Python and C++ evaluate compound boolean expressions from left to right and stop as soon as the final outcome is guaranteed—a behavior known as short-circuit evaluation:
- In
A and B, ifAevaluates tofalse, the whole expression must befalseregardless of whatBis. Therefore, the computer skips evaluatingBaltogether! - In
A or B, ifAevaluates totrue, the whole expression must betrue. Therefore, the computer skips evaluatingB!
Far from being just a minor speed optimization, short-circuit evaluation is a critical safety technique. Suppose you want to check whether tile grid[index] contains a wall, but index might be negative or past the end of the list. If you write:
if index >= 0 and index < len(grid) and grid[index] == "WALL":
Because the bounds checks come first on the left, if index is -1, the first check is False, the and expression immediately short-circuits, and grid[-1] (or an out-of-bounds crash in C++) is never executed!
and / && operator so invalid operations on the right are safely short-circuited.The Classic Beginner Trap: if x == 3 or 4:
In everyday English, we say "if the dice roll is 3 or 4, you win." Translating that word-for-word into Python or C++ produces a notorious silent bug:
# BUGGY CODE - DO NOT DO THIS:
if roll == 3 or 4:
print("You win!")
Why does this print "You win!" even when roll is 1? Because the or operator joins two independent complete expressions: (roll == 3) on the left, and (4) on the right. When roll is 1, roll == 3 is False. Next, Python and C++ evaluate the right-hand expression 4 as a boolean—and in both languages, any non-zero number is considered truthy (True)! Thus False or True always evaluates to True. You must spell out both comparisons explicitly:
Visual Block Logic
IF (roll == 3) OR (roll == 4):
say("You win!")
Python
if roll == 3 or roll == 4:
print("You win!")
# Or: if roll in (3, 4):
C++
if (roll == 3 || roll == 4) {
std::cout << "You win!
";
}
De Morgan's Laws: Simplifying Negated Conditions
When writing a while loop or guarding against invalid inputs, you often need the exact opposite of a compound condition. Augustus De Morgan formulated two laws that show how distributing a NOT across parentheses flips the operator inside:
not (A and B)is logically identical to(not A) or (not B).not (A or B)is logically identical to(not A) and (not B).
For example, "continue the game while it is NOT the case that (time is up OR health is zero)" translates cleanly via De Morgan's second law into: "continue while (time is NOT up) AND (health is NOT zero)." Both forms always produce the exact same truth table; choose whichever reads more naturally for your problem.
Cleaning Up Complex Conditions with Named Booleans
When an if condition grows to combine four or five comparisons, even properly parenthesized logic becomes slow for a human to read. A great habit in both Python and C++ is to store intermediate sub-conditions in descriptive boolean variables right before the if statement:
bool is_within_bounds = (r >= 0 && r < rows && c >= 0 && c < cols);
bool has_unlock_item = (has_master_key || silver_keys >= 3);
if (is_within_bounds && has_unlock_item && !is_frozen) {
unlockDoor(r, c);
}
Breaking a compound decision into named boolean variables costs zero extra performance in modern compilers, makes debugger inspection effortless, and reads almost like plain English.
Practice Exercise: Valid Grid Coordinate Checker
A robot is moving on a rectangular board with rows = 8 (valid rows 0 through 7) and cols = 10 (valid columns 0 through 9). Additionally, square (3, 4) contains a lava pit that the robot cannot step onto.
- Write a function
is_safe_tile(r, c)in Python and C++ that returnstrueif and only if(r, c)is inside the board boundaries and is not the lava pit at(3, 4). - Use De Morgan's law to rewrite the negation
!(r == 3 && c == 4)without using the outer!operator.
CodeCracker