Computer Programming 1 (Python) • Control Flow

Compound Conditions — I can evaluate compound conditions using and/or/not and predict outcomes at my level.

Combine simple true-or-false checks into powerful decision logic using Python's and, or, and not operators.

A Python coding terminal with a program flow and laptop.
Inside this lesson 10 sections 5 questions 8 figures

SECTION 1

Historical Context & Motivation

Every time you unlock your phone, you satisfy a compound condition: the device checks that the entered passcode matches and that too many failed attempts have not occurred. The idea of combining simple true-or-false statements into richer decisions is far older than smartphones — it stretches back to the foundations of mathematical logic itself. Understanding this history helps you appreciate why Python's and, or, and not keywords work the way they do.

1847 • George Boole's Boolean Algebra

English mathematician George Boole published The Mathematical Analysis of Logic, creating an algebra of two values — True and False — combined with AND, OR, and NOT operations.

1938 • Claude Shannon's Switching Circuits

Claude Shannon showed that Boole's algebra could model electrical switching circuits, laying the groundwork for every digital computer that followed.

1972 • The C Programming Language

Dennis Ritchie's C language used symbolic operators (&&, ||, !) for compound conditions. Most modern languages inherited this pattern.

1991 • Python Is Born

Guido van Rossum released Python, choosing the readable English words and, or, and not instead of cryptic symbols, making compound conditions easier to read and write.

A single if statement can only test one condition at a time. But real-world programs routinely need to ask questions like "Is the user old enough and do they have a valid ID?" or "Is the temperature too high or too low?" This is the gap that compound conditions fill — they let you merge multiple Boolean checks into a single, elegant expression.

SECTION 2

Core Principles & Definitions

Before you start chaining conditions together, you need a clear mental model of what each logical operator does. A compound condition is any Boolean expression that joins two or more simple conditions using and, or, or not. Each operator follows precise rules, and knowing those rules lets you predict the outcome of any expression without running the code.

1

and — Both Must Be True

The expression A and B evaluates to True only when both A and B are True. If either one is False, the whole expression is False.
2

or — At Least One True

The expression A or B evaluates to True when at least one of A or B is True. It is only False when both are False.
3

not — Flip the Value

The expression not A flips True to False and False to True. It is the only unary logical operator — it acts on a single operand.
4

Operator Precedence

Python evaluates not first, then and, then or. Use parentheses to override this order and make your intent crystal clear.
✦

KEY TAKEAWAY

Think of and like a strict teacher who requires every assignment turned in before you pass. Think of or like a lenient teacher who passes you if any assignment is done. And not is like flipping your answer sheet upside down — every True becomes False and vice versa.

SECTION 3

Visual Explanation — Truth Tables

A truth table is the most powerful tool for predicting the output of a compound condition. It lists every possible combination of inputs (True or False for each operand) and shows what the whole expression evaluates to. The diagram below presents truth tables for all three Python logical operators side by side.

A and BABResultTrueTrueTrueTrueFalseFalseFalseTrueFalseFalseFalseFalseA or BABResultTrueTrueTrueTrueFalseTrueFalseTrueTrueFalseFalseFalsenot AAResultTrueFalseFalseTrueOperator Precedence (Highest → Lowest)EVALUATED FIRSTnotEVALUATED SECONDandEVALUATED LASTorExample: not True or False and True→ (not True) or (False and True)→ False or False → False
The top row shows truth tables for and, or, and not. Green results indicate True; red results indicate False. The bottom panel shows how Python evaluates operators from highest to lowest precedence.

Notice the key pattern in the truth tables: and produces only one True row (both inputs must be True), while or produces only one False row (both inputs must be False). This symmetry is worth memorizing — it makes mental evaluation much faster.

SECTION 4

How Python Evaluates Compound Conditions

Python uses a clever optimization called short-circuit evaluation. This means the interpreter stops evaluating a compound condition as soon as it knows the final result. Understanding short-circuiting helps you write more efficient code and avoid errors like dividing by zero inside a condition.

SHORT-CIRCUIT RULE FOR AND

AandB→ifAisFalse,returnAimmediately(Bisneverevaluated)A and B → if A is False, return A immediately (B is never evaluated)

Since and requires both sides to be True, a False on the left makes the whole expression False — no need to check the right side.

SHORT-CIRCUIT RULE FOR OR

AorB→ifAisTrue,returnAimmediately(Bisneverevaluated)A or B → if A is True, return A immediately (B is never evaluated)

Since or only needs one True, a True on the left makes the whole expression True — the right side is skipped.

DE MORGAN'S LAWS

not(AandB)≡(notA)or(notB)∣not(AorB)≡(notA)and(notB)not (A and B) ≡ (not A) or (not B) | not (A or B) ≡ (not A) and (not B)

These two equivalences let you distribute not across compound conditions. When not moves inside the parentheses, and flips to or and vice versa.

💡

Why Short-Circuiting Matters

Consider x != 0 and 10 / x > 2. If x is 0, the left side is False, so Python never evaluates 10 / x — avoiding a ZeroDivisionError. This is a common Python pattern you'll see in real projects.

SECTION 5

Common Compound Condition Patterns

Certain compound condition patterns appear so frequently in Python programs that they deserve special attention. Recognizing these patterns will save you debugging time and help you write cleaner code. The diagram below illustrates a decision flowchart that uses all three logical operators together.

Decision Flowchart: Can a User Ride the Roller Coaster?START: User wants to rideheight >= 48and age >= 8TrueFalsenothas_heart_conditionTrueFalsehas_ticket orhas_season_passTrueFalse✅ RIDE APPROVED❌ DENIED❌ DENIED❌ DENIEDheight >= 48 and age >= 8 and not has_heart_condition and (has_ticket or has_season_pass)
This flowchart models a roller coaster eligibility check. Each diamond tests one part of a compound condition. The full expression at the bottom combines and, or, and not into a single compound condition.
PatternPython CodeWhen to Use
Range checklow <= x and x <= highTesting whether a value falls within a range (e.g., valid test scores between 0 and 100).
Membership checkx == 'a' or x == 'b' or x == 'c'Checking if a value matches any item from a small set of options.
Guard clausex != 0 and y / x > 5Preventing an error by verifying safety before performing a risky operation.
Negated groupnot (a or b)Ensuring that none of the conditions in a group are true.

Common compound condition patterns in Python

SECTION 6

Worked Example — Evaluating a Compound Condition

Let's walk through the process of evaluating a compound condition by hand. Suppose we have the following Python variables and expression:

ℹ

Given Code

age = 16 has_permit = True has_violations = False can_drive = age >= 16 and has_permit and not has_violations

Evaluating can_drive Step by Step

  1. 1

    Step 1 — Substitute Values

    Replace each variable with its current value in the expression: 16 >= 16 and True and not False
  2. 2

    Step 2 — Evaluate Comparison Operators First

    Comparison operators like >= have higher precedence than logical operators. 16 >= 16 evaluates to True. The expression becomes: True and True and not False
    True and True and not False
  3. 3

    Step 3 — Evaluate not (Highest Logical Precedence)

    The not operator is evaluated before and. not False flips to True. The expression becomes: True and True and True
    True and True and True
  4. 4

    Step 4 — Evaluate and (Left to Right)

    Python evaluates and from left to right. True and True gives True. Then True and True gives True.
    Final result: can_drive = True

The user is 16 (old enough), has a permit, and has no violations, so can_drive is True. Now consider what happens if has_violations were True: then not True would give False, making the entire and chain False. This illustrates how a single False in an and chain kills the whole expression.

SECTION 7

Strengths & Common Pitfalls

StrengthCommon Pitfall
Compound conditions reduce nested if-statements, making code flatter and easier to read.Chaining too many operators in one line creates an unreadable "mega-condition." Break long expressions across lines or use intermediate variables.
Short-circuit evaluation provides built-in safety against errors like division by zero.Relying on short-circuiting without understanding it can hide bugs. If the right side has a needed side effect, it may never execute.
De Morgan's Laws let you simplify complex negated conditions.Forgetting to flip the operator when distributing not — writing not (A and B) as (not A and not B) instead of (not A or not B).
Python's English keywords (and, or, not) are more readable than symbols used in other languages.Confusing the English word "or" (which can mean exclusive or) with Python's or (which is inclusive — both can be True).

Strengths vs. Common Pitfalls of Compound Conditions

✦

KEY TAKEAWAY

When you find yourself nesting if statements three or more levels deep, step back and ask: can I flatten this into a single compound condition? Cleaner code is easier to debug and easier for your future self to read.

SECTION 8

Connection to Advanced Topics

Compound conditions are your entry point into a much larger world of logic-driven programming. As you advance in Computer Science, the same Boolean logic you're learning now will reappear in several important contexts. The table below maps what you know now to what you'll encounter in future courses.

What You Know NowWhere It Leads
Combining conditions with and, or, notFormal Boolean algebra and logic gates in digital circuits (AP Computer Science, Discrete Math)
Short-circuit evaluationLazy evaluation in functional programming languages like Haskell and advanced Python features like generators
De Morgan's Laws for simplifying expressionsQuery optimization in databases (SQL WHERE clauses) and search engine filter logic
Truth tablesFormal verification and proof techniques in software engineering and cybersecurity

From Compound Conditions to Advanced Topics

You'll also encounter compound conditions inside while loops and list comprehensions soon. In those contexts, compound conditions control not just which code runs, but how many times it runs and which data it processes. Mastering compound conditions now gives you a solid foundation for every control-flow concept that follows.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

In your own words, explain why True or False and False evaluates to True. Which operator does Python evaluate first, and why does that matter?
Show answer
Python evaluates and before or because and has higher precedence. So the expression is grouped as True or (False and False). The inner part, False and False, yields False. Then True or False yields True because or only needs one True operand. Understanding precedence prevents you from misreading the expression as (True or False) and False, which would give False.

Question 2: BASIC CALCULATION

Given x = 5 and y = 10, evaluate the following expression step by step: x > 3 and y < 20 and not x == y
Show answer
First, substitute values: 5 > 3 and 10 < 20 and not 5 == 10. Evaluate comparisons: True and True and not False. Next, evaluate not False → True (not has highest precedence). Finally, evaluate left to right: True and True → True, then True and True → True. The final result is True.

Question 3: INTERMEDIATE

A movie theater gives a discount if a customer is under 13 or 65 and older, or if they have a membership card. Write a single compound condition that stores True in gets_discount. Variables available: age and has_membership. Then evaluate your expression when age = 30 and has_membership = False.
Show answer
The compound condition is: gets_discount = age < 13 or age >= 65 or has_membership. With age = 30 and has_membership = False, we substitute: 30 < 13 or 30 >= 65 or False → False or False or False → False. The 30-year-old without a membership does not get a discount. Note that if any one of these conditions were True, the or chain would produce True.

Question 4: APPLIED

A school attendance system flags a student for review if they have more than 5 unexcused absences and their grade is below 70, or if they have not completed any assignments. Write the compound condition and evaluate it for a student with absences = 7, grade = 82, and assignments_done = 12.
Show answer
The condition is: flagged = (absences > 5 and grade < 70) or assignments_done == 0. Parentheses make the grouping explicit. Substituting: (7 > 5 and 82 < 70) or 12 == 0 → (True and False) or False → False or False → False. The student is NOT flagged. Even though they have too many absences, their grade is above 70, so the first group is False. They've also completed assignments, so the second condition is False too.

Question 5: CRITICAL THINKING

Using De Morgan's Laws, rewrite the expression not (temperature > 100 or pressure > 50) without the outer not. Then explain in 2–3 sentences why both forms produce the same result. Finally, describe a scenario where the rewritten form might be more readable.
Show answer
Applying De Morgan's Law, not (A or B) becomes not A and not B. So the rewritten expression is: temperature <= 100 and pressure <= 50. Both forms produce the same result because negating an or requires both individual conditions to be false, which is exactly what and demands — both conditions must be true. The rewritten form reads naturally as "temperature is safe AND pressure is safe," which is more intuitive in a safety-monitoring program where you want to clearly state the acceptable ranges rather than negate the dangerous ones.

SUMMARY

Lesson Summary

Summary

In this lesson you learned how to build compound conditions using Python's three logical operators. The and operator requires both operands to be True. The or operator requires at least one operand to be True. The not operator flips a single Boolean value. Operator precedence dictates that not is evaluated first, then and, then or — and parentheses always override this order.

You also explored short-circuit evaluation, which allows Python to skip unnecessary checks and prevent runtime errors. De Morgan's Laws give you a reliable way to simplify negated compound conditions by flipping operators when distributing not. With truth tables as your reference tool and step-by-step evaluation as your method, you can now confidently predict the outcome of any compound condition you encounter in Python.

Varsity Tutors • Computer Programming 1 (Python) • Compound Conditions