Intro to Logic and Computational Thinking
Master boolean logic, build truth tables, and create a Python guessing game.
Materials for this lesson
- Laptop (charged)
- Printed logic puzzle worksheet
Warm-Up: Two Truths and a Lie
Below are three groups of math statements. In each group, two are true and one is a lie. Can you spot the lie?
Group 1:
- A) Every even number greater than 2 can be written as the sum of two prime numbers.
- B) The square root of 144 is 14.
- C) A prime number has exactly two factors: 1 and itself.
Group 2:
- A) 0.999... (repeating forever) is exactly equal to 1.
- B) There are more even numbers than odd numbers.
- C) The number 1 is neither prime nor composite.
Group 3:
- A) If you flip a fair coin 100 times, you are guaranteed to get at least 40 heads.
- B) 2 is the only even prime number.
- C) The sum of the angles in any triangle is 180°.
Notice how figuring out the "lie" required you to evaluate each statement as true or false. That's the heart of today's lesson: boolean logic ā the math of true and false.
Core Lesson: Boolean Logic ā The Foundation of All Computing
True or False: The Simplest Data Type
Every computer on Earth, from your phone to a Mars rover, operates on one fundamental idea: things are either true or false, on or off, 1 or 0. This is called boolean logic, named after mathematician George Boole (1815ā1864).
A boolean value is either True or False. A boolean expression is any statement that evaluates to True or False. For example: 5 > 3 is True. 10 == 7 is False.
The Three Core Operators: AND, OR, NOT
These three operators are the building blocks of all logical reasoning ā in math, computer science, law, philosophy, and everyday life.
AND (both must be true)
"I'll go outside if it's warm AND it's not raining."
Both conditions must be true for the whole statement to be true.
| A | B | A AND B | |---|---|---------| | True | True | True | | True | False | False | | False | True | False | | False | False | False |
OR (at least one must be true)
"I'll have dessert if they have cake OR they have pie."
At least one condition must be true.
| A | B | A OR B | |---|---|--------| | True | True | True | | True | False | True | | False | True | True | | False | False | False |
NOT (flip the value)
"I'll go to the party if I'm NOT sick."
| A | NOT A | |---|-------| | True | False | | False | True |
What does (True AND False) OR (NOT False) evaluate to?
Boolean Logic in Python
Python uses the keywords and, or, and not (lowercase). Comparison operators produce boolean values:
# Comparison operators
print(5 > 3) # True
print(10 == 7) # False (== means "is equal to?")
print(10 != 7) # True (!= means "is not equal to?")
print(4 <= 4) # True (<= means "less than or equal to")
# Combining with and, or, not
age = 13
has_ticket = True
print(age >= 12 and has_ticket) # True ā both conditions met
print(age >= 18 or has_ticket) # True ā at least one condition met
print(not has_ticket) # False ā flips True to False
If / Elif / Else: Making Decisions
The real power comes when you use booleans to control what your program does:
temperature = 72
if temperature > 90:
print("It's scorching! Stay inside.")
elif temperature > 70:
print("Beautiful day! Go outside.")
elif temperature > 50:
print("A bit cool. Grab a jacket.")
else:
print("Bundle up! It's cold out there.")
How if/elif/else works:
- Python checks each condition from top to bottom
- It runs the code under the first condition that is
True - It skips everything else
elseis the "catch-all" ā it runs only if nothing above was true
In Python, what is the output of: print(not (True and False))
Boolean Logic & Logic Gates ā Crash Course Computer Science #3
Hands-On Lab: Build a Number Guessing Game
We're going to build a game where the computer picks a random number and you try to guess it. The computer gives hints after each guess.
Version 1: Basic Guessing Game
import random
# Computer picks a random number between 1 and 100
secret = random.randint(1, 100)
attempts = 0
print("=== Number Guessing Game ===")
print("I'm thinking of a number between 1 and 100.\n")
while True:
guess = int(input("Your guess: "))
attempts += 1
if guess < secret:
print("Too low! Try higher.")
elif guess > secret:
print("Too high! Try lower.")
else:
print(f"\nš You got it! The number was {secret}.")
print(f"It took you {attempts} attempts.")
break
Version 2: Add Difficulty Levels and a Guess Limit
import random
print("=== Number Guessing Game v2 ===")
print("Choose your difficulty:")
print("1. Easy (1-50, 10 guesses)")
print("2. Medium (1-100, 7 guesses)")
print("3. Hard (1-500, 9 guesses)")
print("4. Insane (1-1000, 10 guesses)")
choice = input("\nDifficulty (1-4): ")
if choice == "1":
high = 50
max_guesses = 10
elif choice == "2":
high = 100
max_guesses = 7
elif choice == "3":
high = 500
max_guesses = 9
elif choice == "4":
high = 1000
max_guesses = 10
else:
print("Invalid choice, defaulting to Medium.")
high = 100
max_guesses = 7
secret = random.randint(1, high)
attempts = 0
print(f"\nI'm thinking of a number between 1 and {high}.")
print(f"You have {max_guesses} guesses. Good luck!\n")
while attempts < max_guesses:
remaining = max_guesses - attempts
guess = int(input(f"[{remaining} left] Your guess: "))
attempts += 1
if guess < secret:
diff = secret - guess
if diff > high // 4:
print("Way too low!")
else:
print("Too low, but you're getting warm.")
elif guess > secret:
diff = guess - secret
if diff > high // 4:
print("Way too high!")
else:
print("Too high, but you're getting warm.")
else:
print(f"\nYou got it in {attempts} guesses! The number was {secret}.")
break
else:
print(f"\nOut of guesses! The number was {secret}.")
Version 3: The Computer Guesses YOUR Number
Flip the script! You think of a number, and the computer uses binary search to guess it ā the same strategy you should be using!
print("=== Reverse Guessing Game ===")
print("Think of a number between 1 and 1000.")
print("I'll try to guess it. Answer with:")
print(" 'h' = too high")
print(" 'l' = too low")
print(" 'y' = correct!\n")
input("Press Enter when you've picked your number...")
low = 1
high = 1000
attempts = 0
while low <= high:
guess = (low + high) // 2
attempts += 1
response = input(f"Attempt {attempts}: Is it {guess}? (h/l/y): ").lower()
if response == "y":
print(f"\nI got it in {attempts} attempts!")
print(f"With binary search, I can always find a number in 1-1000")
print(f"in at most 10 guesses (because 2^10 = 1024 > 1000).")
break
elif response == "h":
high = guess - 1
elif response == "l":
low = guess + 1
else:
print("Please enter 'h', 'l', or 'y'.")
attempts -= 1 # Don't count invalid input
if low > high:
print("Hmm, that's impossible. Did you change your number?")
Binary search is one of the most important algorithms in computer science. It works by cutting the search space in half each time. For a range of 1-1000, it needs at most 10 guesses because 2^10 = 1024. For 1 to 1,000,000, it needs at most 20 guesses. For all 8 billion people on Earth? Only 33 guesses.
Challenge: The Logic Puzzle
Five friends ā Alice, Bob, Carol, Dave, and Eve ā each have a different favorite color: red, blue, green, yellow, and purple. Use the clues to figure out who likes which color.
Clues:
- Alice does not like red or blue.
- Bob does not like green or yellow.
- Carol likes blue.
- Dave does not like red.
- The person who likes green has a name that comes before "D" alphabetically.
Bonus: Can you write a Python program that solves this logic puzzle by brute force? Hint: use itertools.permutations to try every possible assignment and check which ones satisfy all the clues.
Resources
- Crash Course: Boolean Logic & Logic Gates ā fantastic video on how boolean logic runs inside computers
- Khan Academy: Intro to Boolean Logic ā interactive exercises
- Python Booleans ā W3Schools ā Python reference for boolean values and comparisons
- Binary Search Algorithm ā CS Unplugged ā the guessing game algorithm, explained for everyone
- Replit ā online code editor
- Logic Puzzles ā Brainzilla ā more puzzles to sharpen your reasoning