MGU Computer Science Series — Programming with Python
Part II: Control Flow and Program Logic
Booleans · Comparisons · Logic · Decisions
Chapter 5 of 30
5
MGU Computer Science Series  ·  Programming with Python  ·  Library Textbook Edition

Chapter 5:
Booleans, Comparisons,
and Decisions

The logical foundation of every decision a Python program can make — Boolean values, comparison operators, logical operators, and the discipline of designing a condition before you write one

■ Part II of VII ■

■ 10 Sections  •  Chapter 5 of 30 ■

Builds on Chapters 1–4 — prepares directly for if, elif, and else in Chapter 6

Chapter Introduction and Learning Objectives

Every useful program eventually has to make a choice. Should it approve the login or reject it? Is the temperature above the danger threshold? Did the user enter a valid age? To answer questions like these, programs need a way to evaluate conditions and produce a result that means either yes or no. Python gives you that tool through Boolean values and comparison operators.

This chapter introduces the logical foundation that powers every decision a Python program can make. You will learn what Boolean values are, how comparison operators produce them, how logical operators combine them, and how to design reliable decision conditions. This chapter prepares you for Chapter 6, where you will use these ideas inside if, elif, and else statements to control which parts of your program actually run.

Opening Question

How does a program decide whether a student passed a test, whether a password is strong enough, or whether a transaction looks suspicious? In every case, the program is not "deciding" the way a person does — it is evaluating an expression that reduces a real-world question down to exactly one of two values: True or False. By the end of this chapter, you will understand exactly how that reduction works, and you will be able to design conditions that capture what you actually mean.

10Sections
12Key Terms
6Comparison Ops
30Total Chapters

Learning Objectives

By the end of this chapter, you should be able to:

  1. 1Explain why programs need decisions and what role a condition plays in making one.
  2. 2Define the bool type and identify its only two possible values.
  3. 3Use all six comparison operators to produce Boolean results from numbers and strings.
  4. 4Distinguish clearly between the assignment operator = and the equality operator ==.
  5. 5Write range checks using both chained comparisons and and-based comparisons.
  6. 6Combine Boolean values using and, or, and not.
  7. 7Read and write compound conditions clearly, using parentheses and meaningful names.
  8. 8Construct and interpret truth tables for and, or, and not.
  9. 9Apply a five-step process for designing a decision rule from a plain-English description.
  10. 10Identify and correct the most common Boolean mistakes beginners make in Python.

Sections at a Glance

Sections 5.1 – 5.4
The Foundation: Booleans, Comparisons, and the = vs == Distinction
bool · Comparison Operators · Equality · Assignment

Why Programs Need Decisions

Most programs you write will not just run the same instructions every time. They will need to respond to different situations — different inputs, different data, different states — and behave differently as a result.

Think about how this works in everyday life:

  • If it is raining, bring an umbrella. Otherwise, leave it at home.
  • If a student scored 90 or above, the grade is an A. If they scored 80 or above, the grade is a B.
  • If the user enters the correct password, allow access. Otherwise, show an error.
  • If a number is negative, reject it. If it is zero, warn the user. If it is positive, continue.

Each of those situations involves a condition — a question that has a yes-or-no answer — and a decision about what to do depending on the answer.

Programs make decisions using conditions, and conditions produce Boolean values: either True or False. Before you can write decision-making code, you need to understand how Python evaluates conditions and what makes a condition True or False.

Looking Ahead

This chapter teaches you the foundation. The decisions themselves — the if statements — come in Chapter 6.

Boolean Values

Python has a data type called bool, short for Boolean. A Boolean value can only be one of two things:

True False

Notice that both are capitalized. Python is case-sensitive. true and false (lowercase) are not Boolean values in Python — they are simply undefined names that will cause a NameError if you use them.

You can assign Boolean values to variables just like any other value:

is_raining = True has_permission = False account_active = True

You can check the type of a Boolean value:

print(type(True)) # <class 'bool'> print(type(False)) # <class 'bool'>

Boolean values may seem simple — just two possible values — but they are the foundation of all decision-making in programs. Every condition a program evaluates eventually produces either True or False, and the program uses that result to decide what to do next.

Booleans as Numbers

Python treats True and False as special cases of integers: True equals 1 and False equals 0. You will occasionally see this come up in arithmetic. For now, just know that this relationship exists — it will make more sense when you encounter it in later chapters.

print(True + True) # 2 print(False + 1) # 1
Study Note

You do not need to use Booleans as numbers in most programs. This is just useful background knowledge.

Comparison Operators

You rarely type True or False directly into a decision condition. Instead, you write an expression that Python evaluates to produce True or False. The most common way to do this is with a comparison operator.

Python's comparison operators compare two values and produce a Boolean result.

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
<Less than3 < 10True
>Greater than10 > 20False
<=Less than or equal to5 <= 5True
>=Greater than or equal to4 >= 7False

Try these in the Python shell to see the results:

>>> 10 == 10 True >>> 10 == 9 False >>> 7 != 3 True >>> 5 > 5 False >>> 5 >= 5 True >>> 3 < 0 False

Each comparison is an expression. Python evaluates the expression and produces a Boolean value. You can store that result in a variable:

score = 87 passed = score >= 60 print(passed) # True

Or you can use a comparison directly in a print() statement to see the result:

temperature = 104 print(temperature > 100) # True

Comparisons Work on Strings Too

Python can compare strings using the same operators. For equality, this is especially useful:

answer = "yes" print(answer == "yes") # True print(answer == "no") # False print(answer != "maybe") # True

String comparisons using <, >, <=, and >= compare alphabetical order (technically, Unicode code point order), which can be useful but also surprising. For now, focus on == and != with strings, since those are most commonly used in beginner programs.

print("apple" < "banana") # True print("zebra" > "ant") # True

Equality and Assignment Are Different

One of the most common beginner mistakes in Python — and in nearly every programming language — is confusing the equality operator with the assignment operator.

SymbolPurposeExample
=Assignmentx = 10
==Equality checkx == 10

Assignment (=) stores a value in a variable. It does not produce True or False. It is a statement that changes program state.

Equality (==) compares two values and produces True or False. It does not change anything.

Look at the difference:

x = 10 # Assignment: x now stores the value 10 x == 10 # Equality: produces True, but doesn't do anything with it print(x == 10) # True print(x == 5) # False

If you write = when you meant == inside a condition, Python will usually give you a SyntaxError because you cannot assign a value inside most comparison contexts. This error is Python protecting you from a common mistake.

Code Example — Common Mistake
# This is a mistake — do not do this if x = 10: # SyntaxError print("ten")

The correct version uses ==:

if x == 10: # Correct equality check print("ten")
Study Habit

Developing the habit of reading = as "gets" and == as "equals?" will help you avoid this mistake.

Sections 5.5 – 5.8
Building Logic: Ranges, Logical Operators, Compound Conditions, and Truth Tables
Chained Comparisons · and / or / not · Truth Tables

Less Than, Greater Than, and Ranges

Numeric comparisons are especially common in programs that work with ages, scores, temperatures, quantities, prices, and similar values. Let's look at some realistic examples.

Simple Comparisons

age = 17 print(age >= 18) # False — not yet an adult print(age < 18) # True — still a minor speed = 72 print(speed > 65) # True — over the speed limit print(speed <= 65) # False

Testing Whether a Value Is in a Range

Python supports chained comparisons, which let you test a range naturally:

score = 75 print(60 <= score <= 100) # True — score is between 60 and 100 print(0 <= score < 60) # False — score is not below 60

This is a feature unique to Python among common programming languages. It reads almost like natural language: "is score between 60 and 100, inclusive?"

You can also write range checks using and (covered in section 5.6), which is more common when you first learn Boolean logic:

score = 75 print(score >= 60 and score <= 100) # True — equivalent to above

Both forms work. The chained form is more readable when the condition is a simple range.

Boundary Values

Pay careful attention to whether your comparisons are strict (<, >) or inclusive (<=, >=). Boundaries are a common source of logic errors.

For example, if passing is defined as 60 or above:

score = 60 print(score > 60) # False — exactly 60 does NOT pass (strict) print(score >= 60) # True — exactly 60 DOES pass (inclusive)
Watch the Boundary

When you design a condition, ask yourself: should the boundary value be included or excluded? This single question prevents one of the most frequent logic errors in beginner programs.

Logical Operators: and, or, and not

Single comparisons can only test one thing at a time. Often you need to combine conditions: a user must be at least 18 and must have a valid account. A temperature warning should trigger if it is too hot or too cold. A value is valid only if it is not negative.

Python provides three logical operators for combining Boolean values:

OperatorMeaningExample
andBoth conditions must be Truea and b
orAt least one condition must be Truea or b
notInverts a Boolean valuenot a

The and Operator

and produces True only when both conditions are True. If either condition is False, the result is False.

age = 20 has_id = True print(age >= 18 and has_id) # True — both conditions are met age = 16 print(age >= 18 and has_id) # False — age condition fails

Think of and as a strict gate: both keys are required.

The or Operator

or produces True when at least one condition is True. It only produces False when both conditions are False.

temperature = 38 print(temperature < 0 or temperature > 35) # True — too hot temperature = 20 print(temperature < 0 or temperature > 35) # False — comfortable range

Think of or as a flexible gate: either key will open it.

The not Operator

not flips a Boolean value. not True is False, and not False is True.

is_logged_in = False print(not is_logged_in) # True — the user is NOT logged in account_locked = True print(not account_locked) # False — account IS locked

not is useful when you want to check whether something is absent, disabled, or missing.

Combining Logical Operators

You can combine multiple logical operators in one expression. Use parentheses to make the grouping clear:

age = 25 income = 45000 has_criminal_record = False eligible = (age >= 18) and (income >= 30000) and (not has_criminal_record) print(eligible) # True
Style Tip

Without parentheses, Python uses operator precedence to decide the order of evaluation. Parentheses make your intent clear and prevent errors.

Compound Conditions

A compound condition is a Boolean expression that combines multiple comparisons using logical operators. You have already seen several examples. This section focuses on reading and writing them carefully.

Reading Compound Conditions

When you read a compound condition, work through it piece by piece:

score = 82 grade = "B" print(score >= 80 and score < 90 and grade == "B")
Code Tracing
Stepping through a compound condition
  • Piece 1score >= 80 → 82 >= 80 → True
  • Piece 2score < 90 → 82 < 90 → True
  • Piece 3grade == "B" → "B" == "B" → True
  • CombineTrue and True and True → True
x = 5 print(x < 0 or x > 10)
Code Tracing
Stepping through an or condition
  • Piece 1x < 0 → 5 < 0 → False
  • Piece 2x > 10 → 5 > 10 → False
  • CombineFalse or False → False

Writing Compound Conditions Clearly

Long conditions can become hard to read. A few habits help.

Use parentheses to group sub-conditions:

# Harder to read result = score >= 80 and score < 90 or grade == "A" # Clearer with parentheses result = (score >= 80 and score < 90) or (grade == "A")

Break very long conditions across lines:

eligible = ( age >= 18 and income >= 30000 and not has_criminal_record )

Give the condition a meaningful name:

in_passing_range = score >= 60 and score <= 100 has_access = is_logged_in and not account_locked

Naming a condition makes later code much easier to read:

if in_passing_range: print("Congratulations, you passed.")

Truth Tables at an Introductory Level

A truth table is a systematic way of showing all possible combinations of Boolean inputs and their outputs. Truth tables are used in logic, digital electronics, and programming to understand exactly how Boolean operators behave.

Truth Table for and

ABA and B
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

and only produces True in one case: when both inputs are True.

Truth Table for or

ABA or B
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

or only produces False in one case: when both inputs are False.

Truth Table for not

Anot A
TrueFalse
FalseTrue

not simply flips the value.

Using Truth Tables to Reason About Conditions

Truth tables help you think through what a condition does before you test it in a program. If you are designing a rule like "a user can log in if they are active and not banned," you can map it out:

is_activeis_bannedis_active and not is_banned
TrueTrueFalse
TrueFalseTrue
FalseTrueFalse
FalseFalseFalse

Only one combination allows login: active and not banned. The table makes this clear immediately.

Section 5.9 – 5.10
Putting It Together: Designing Rules and Avoiding Mistakes
A Five-Step Design Process · Common Pitfalls

Designing Decision Rules

Writing correct Boolean conditions requires more than knowing the operators. It requires thinking carefully about what you actually want the program to decide.

Here is a process for designing a condition.

Design Process
Five steps from plain English to a working condition
  • Step 1State the rule in plain English. Write out the decision in natural language before writing any code. Be specific. For example: "A student passes if their score is 60 or above." "A password is strong if it has at least 8 characters and contains a digit." "A transaction is suspicious if it is over 10,000 or it comes from a flagged account."
  • Step 2Identify the variables involved. What information does the program have? What values are you comparing? For example: score (a number), password (a string and its length), transaction amount and account status (numbers and Booleans).
  • Step 3Translate each part into a comparison. For example: score >= 60; len(password) >= 8 (and checking for a digit — more on this later); amount > 10000 or account_flagged.
  • Step 4Combine comparisons using logical operators. For example: score >= 60 (just one comparison here); len(password) >= 8 and has_digit; amount > 10000 or account_flagged.
  • Step 5Test your condition mentally against examples. Pick a few example values and evaluate the condition by hand before trusting the code.

Example: "Pass if score >= 60"

Scorescore >= 60ExpectedMatch?
75TruePass✓
60TruePass✓
59FalseFail✓
0FalseFail✓
Why This Matters

Testing your condition against expected inputs before running the program is an early form of test-case thinking. It will save you from many logic errors.

Common Boolean Mistakes

Boolean expressions are small but they carry a lot of logic. Several mistakes appear over and over in beginner Python programs.

Mistake 1: Using = Instead of ==

# WRONG if x = 10: # SyntaxError # CORRECT if x == 10:

Mistake 2: Comparing to True or False Unnecessarily

# REDUNDANT — works but is noisy if is_valid == True: print("valid") # BETTER — simpler and more readable if is_valid: print("valid")

Similarly:

# REDUNDANT if is_valid == False: # BETTER if not is_valid:

Python conditions do not need to be compared against True or False. A Boolean variable already is a Boolean.

Mistake 3: Misplacing not

# WRONG — checks if score is "not 60" and then uses and not score == 60 and score < 80 # ambiguous # BETTER — use parentheses to make intent clear (not (score == 60)) and score < 80 # or more naturally: score != 60 and score < 80

Mistake 4: Trying to Write Range Checks the Wrong Way

# WRONG — this does not check a range in most languages, but in Python # it actually works, but beginners often write it wrong like this: 60 <= score <= 100 # This IS valid Python and works correctly # This is wrong: score >= 60 and <= 100 # SyntaxError — missing second operand

Always include the variable on both sides when not using Python's chained comparison:

score >= 60 and score <= 100 # Correct

Mistake 5: Forgetting or Requires Both Sides to Be Full Comparisons

# WRONG — reads naturally in English, but Python doesn't parse it this way if score == 90 or 95: # This doesn't check score == 95 # CORRECT if score == 90 or score == 95:
Why This Is Dangerous

The expression score == 90 or 95 is evaluated as (score == 90) or (95). Since 95 is a non-zero number, Python treats it as True. So this condition is always True, regardless of the score — a hidden logic bug.

Mistake 6: Confusing and with or

Read conditions carefully:

  • "Accept if the user is an admin or a moderator."
  • "Reject if the user is banned and their account is expired."

Getting and and or backwards will produce the opposite of what you intend. Use a truth table or mental test cases to verify.

Chapter Summary

Key Terms

Boolean
A data type with exactly two possible values: True or False.
bool
Python's built-in Boolean type.
Comparison operator
An operator that compares two values and produces a Boolean result: ==, !=, <, >, <=, >=.
Equality operator (==)
Compares two values to determine whether they are equal. Produces True or False.
Assignment operator (=)
Stores a value in a variable. Does not produce a Boolean.
Logical operator
An operator that combines Boolean values: and, or, not.
and
A logical operator that produces True only when both operands are True.
or
A logical operator that produces True when at least one operand is True.
not
A logical operator that inverts a Boolean value.
Compound condition
A Boolean expression that combines multiple comparisons using logical operators.
Chained comparison
A Python expression that tests a range using two comparison operators together, such as 60 <= score <= 100.
Truth table
A table showing all possible input combinations for a Boolean expression and their corresponding output.
Condition
A Boolean expression used to represent a yes-or-no question that a program evaluates.
PracticeBoolean Practice

Evaluate each expression and predict whether it produces True or False. Then check your answer by running it in the Python shell.

# 1 10 == 10 # 2 10 == 10.0 # 3 "hello" == "Hello" # 4 7 != 3 # 5 5 > 5 # 6 5 >= 5 # 7 0 < -1 # 8 100 <= 100 # 9 not True # 10 not False # 11 True and False # 12 True or False # 13 False or False # 14 not (5 > 3) # 15 (3 < 5) and (10 > 7)
PracticeComparison Practice

For each situation, write a Python comparison expression that produces True when the condition is satisfied.

  1. A student's score is at least 90.
  2. A temperature is below freezing (below 0 degrees Celsius).
  3. A username is not equal to "admin".
  4. A file size is exactly 1024 bytes.
  5. An age is between 13 and 17, inclusive.
  6. A price is greater than 0 but not more than 500.
  7. A password has more than 7 characters. (Hint: use len())
  8. A value is not equal to 0.
  9. A year is greater than 2000.
  10. A speed is at or above 60 but strictly below 80.
PracticeTruth Table Practice

Complete the following truth tables.

Table 1: Fill in the result of A and B

ABA and B
TrueTrue 
TrueFalse 
FalseTrue 
FalseFalse 

Table 2: Fill in the result of A or B

ABA or B
TrueTrue 
TrueFalse 
FalseTrue 
FalseFalse 

Table 3: Complete with A = True, B = False

ExpressionValue
not A 
not B 
A and not B 
not A or B 
not (A and B) 
not A and not B 
PracticeCondition Design Questions

For each decision rule, write a Python Boolean expression. Do not write an if statement yet — just write the expression.

  1. A user can vote if they are 18 or older.
  2. An item is on sale if its original price is over 100 and it is marked as discounted.
  3. A number is outside the range 1 to 10 (not including 1 or 10).
  4. A student passes if their score is at least 60, or if they have a documented exemption.
  5. A login attempt is valid if the username equals "admin" and the password equals "secure123".
  6. A package ships for free if the order total is at least 50 or the customer is a premium member.
  7. A sensor reading is abnormal if it is below 10 or above 90.
  8. A character in a game can attack if they have health greater than 0 and at least 1 action point.
PracticePredict the Output

Study each code block. Predict exactly what it prints. Then verify by running it.

Block 1
x = 15 print(x > 10) print(x < 20) print(x > 10 and x < 20)
Block 2
score = 59 passing = score >= 60 print(passing) print(not passing)
Block 3
a = True b = False print(a and b) print(a or b) print(not a or b) print(not (a or b))
Block 4
name = "Alice" print(name == "alice") print(name == "Alice") print(name != "Bob")
Block 5
temperature = 0 cold = temperature <= 0 hot = temperature >= 30 extreme = cold or hot print(cold) print(hot) print(extreme)
DebuggingCommon Errors

Each code block contains at least one error. Identify the error, explain what is wrong, and write the corrected version.

Problem 1
score = 75 if score = 75: print("Score is 75")
Problem 2
age = 20 if age == 18 or 19 or 20: print("Young adult")
Problem 3
x = 5 print(x >= 1 and <= 10)
Problem 4
is_active = True if is_active == True: print("Active")

(This runs correctly but contains a style problem. What is it, and how would you improve it?)

Problem 5
logged_in = False if not logged_in == False: print("Please log in.")

(This may not produce a SyntaxError, but the logic is confusing. Rewrite it clearly.)

PracticeShort Programming Tasks

Write a small Python program for each task. Use input() where appropriate. Your program should print a Boolean result or a message based on a Boolean evaluation.

  1. Ask the user to enter a number. Print True if the number is positive, False if it is not.
  2. Ask the user to enter their age. Print whether they are eligible to vote (True if 18 or older, False otherwise).
  3. Ask the user to enter two numbers. Print True if the first number is larger than the second, False otherwise.
  4. Ask the user to enter a password. Print True if the password is longer than 7 characters, False if it is not. (Hint: use len())
  5. Ask the user to enter a temperature in Celsius. Print True if the temperature is "comfortable" (between 18 and 26, inclusive), False otherwise.
  6. Ask the user to enter a score from 0 to 100. Print True if the score is in the B range (80 to 89, inclusive), False otherwise.
  7. Ask the user to enter a username. Print True if the username is either "admin" or "root", False otherwise.
  8. Ask the user to enter a number. Print True if the number is even. (Hint: use the % operator — x % 2 == 0 is True when x is even.)
ReviewReview Questions

Conceptual Questions

  1. What are the only two possible values of a Python Boolean?
  2. Why does Python require Boolean values to be capitalized (True, False) rather than lowercase?
  3. What is the difference between = and == in Python? Give one example of each.
  4. What does a comparison operator do? Name all six comparison operators in Python.
  5. What does the and operator require to produce True?
  6. What does the or operator require to produce False?
  7. What does not do to a Boolean value?
  8. Explain in your own words why writing if score == 90 or 95: is a logic error.
  9. What is a compound condition? Give an example.
  10. What is a truth table and how is it useful when designing conditions?

Applied Questions

  1. Write a Boolean expression that is True when a variable n is divisible by both 3 and 5. (Hint: use %)
  2. Write a Boolean expression that is True when a string variable answer is neither "yes" nor "no".
  3. A product is discounted if its category is "clearance" or its price is over 200 and it has been in stock for more than 90 days. Write this as a Python Boolean expression using variables category, price, and days_in_stock. Make sure your parentheses express the correct logic.
  4. Explain the difference between 0 < x < 10 and x > 0 and x < 10 in Python. Do they produce the same result? Which is more readable?
  5. A programmer writes the condition not is_premium and not is_trial. Describe in plain English what kind of user this condition identifies.
Chapter 5 Checklist
Use this to confirm your understanding before moving to Chapter 6
Concepts
  • I can explain why programs need decisions and what a condition is.
  • I can name the two values of the bool type and explain why capitalization matters.
  • I can use all six comparison operators correctly on numbers and strings.
  • I can explain the difference between = and == and avoid confusing them.
  • I can write a range check using both chained comparisons and and-based comparisons.
  • I can explain the difference between strict and inclusive boundaries.
  • I can combine conditions using and, or, and not.
  • I can build and read a truth table for and, or, and not.
Applications
  • I can follow the five-step process to design a decision rule from a plain-English description.
  • I can test a Boolean condition against example values before trusting it.
  • I can identify and correct the six common Boolean mistakes covered in this chapter.
Study Habits
  • I trace compound conditions piece by piece rather than guessing the result.
  • I use parentheses and meaningful names to make conditions easier to read.
  • I check boundary values deliberately instead of assuming inclusivity or exclusivity.
Preview — Chapter 6
If, Elif, and Else

You now know how Python evaluates Boolean conditions. In Chapter 6, you will put that knowledge to work inside if, elif, and else statements — the structures that let a program choose which code to run based on a condition. You will learn how to write branches that handle multiple cases, how to avoid overlapping or missing conditions, how to trace which branch runs for different inputs, and how to design branching logic that is clear and correct. Chapter 6 is where decisions become code.

MGU Library Connection
  • Programming with Python — Appendix C: Python Syntax Quick Reference
  • Programming with Python — Appendix D: Common Python Error Messages
  • Companion resource: Boolean Logic Guide
  • Companion resource: Conditionals Flowchart
  • Next chapter: Chapter 6 — If, Elif, and Else
  • Prerequisite course: Computer Science Foundations, Chapter 1