Boolean

  • A Boolean value is either true or false.
  • A Boolean expression produces a Boolean value (true or false) when evaluated.

Conditional ("if") statements

  • Affect the sequential flow of control by executing different statements based on the value of a Boolean expression.

xx xx xx

xx

IF (condition)
{
	<block of statements>
}

The code in <block of statements> is executed if the Boolean expression condition evaluates to true; no action is taken if condition evaluates to false.

IF (condition)
{
	<block of statements>
}
ELSE
{
	<second block of statements>
}

The code in the first <block of statements> is executed if the Boolean expression condition evaluates to true; otherwise, the code in <second block of statements> is executed.

Example: Calculate the sum of 2 numbers. If the sum is greater than 10, display 10; otherwise, display the sum.

num1 = INPUT
num2 = INPUT
sum = num1 + num2
IF (sum > 10)
{
	DISPLAY (10)
}
ELSE
{
	DISPLAY (sum)
}

Hack 1

  • Add a variable that represents an age.

  • Add an ‘if’ and ‘print’ function that says “You are an adult” if your age is greater than or equal to 18.

  • Make a function that prints “You are a minor” with the else function.

## YOUR CODE HERE
# A variable representing an age
age = 20  # You can change this value to test with different ages

# An 'if' statement to check if the age is greater than or equal to 18
if age >= 18:
    print("You are an adult")
else:
    print("You are a minor")

You are an adult

Relational operators:

  • Used to test the relationship between 2 variables, expressions, or values. These relational operators are used for comparisons and they evaluate to a Boolean value (true or false).

Ex. a == b evaluates to true if a and b are equal, otherwise evaluates to false

  • a == b (equals)
  • a != b (not equal to)
  • a > b (greater than)
  • a < b (less than)
  • a >= b (greater than or equal to)
  • a <= b (less than or equal to)

Example: The legal age to work in California is 14 years old. How would we write a Boolean expression to check if someone is at least 14 years old?

age >= 14

Example: Write a Boolean expression to check if the average of height1, height2, and height3 is at least 65 inches.

(height1 + height2 + height3) / 3 >= 65

Hack 2

  • Make a variable called ‘is_raining’ and set it to ‘True”.

  • Make an if statement that prints “Bring an umbrella!” if it is true

  • Make an else statement that says “The weather is clear”.

## YOUR CODE HERE
# A variable named 'is_raining' set to True
is_raining = True  # You can change this to False to test the other condition

# An 'if' statement to check if 'is_raining' is True
if is_raining:
    print("Bring an umbrella!")
else:
    print("The weather is clear.")

Bring an umbrella!

Logical operators:

Used to evaluate multiple conditions to produce a single Boolean value.

  • NOT evaluates to true if condition is false, otherwise evaluates to false
  • AND evaluates to true if both conditions are true, otherwise evaluates to false
  • OR evaluates to true if either condition is true or if both conditions are true, otherwise evaluates to false

Example: You win the game if you score at least 10 points and have 5 lives left or if you score at least 50 points and have more than 0 lives left. Write the Boolean expression for this scenario.

(score >= 10 AND lives == 5) OR (score == 50 AND lives > 0)

Relational and logical operators:

Example: These expressions are all different but will produce the same result.

  • age >= 16
  • age > 16 OR age == 16
  • NOT age < 16

Hack 3

  • Make a function to randomize numbers between 0 and 100 to be assigned to variables a and b using random.randint

  • Print the values of the variables

  • Print the relationship of the variables; a is more than, same as, or less than b

## YOUR CODE HERE
import random

# Function to randomize numbers between 0 and 100
def randomize_numbers():
    a = random.randint(0, 100)
    b = random.randint(0, 100)
    print(f"a: {a}")
    print(f"b: {b}")

    if a > b:
        print("a is more than b")
    elif a == b:
        print("a is the same as b")
    else:
        print("a is less than b")

# Call the function
randomize_numbers()

a: 51
b: 31
a is more than b

Homework

Criteria for above 90%:

  • Add more questions relating to Boolean rather than only one per topic (ideas: expand on conditional statements, relational/logical operators)
  • Add a way to organize the user scores (possibly some kind of leaderboard, keep track of high score vs. current score, etc. Get creative!)
  • Remember to test your code to make sure it functions correctly.
# Import necessary modules
import sys  # Module to access system-related information

# Function to ask a question and get a response
def question_with_response(prompt, correct_answer):
    print("Question: " + prompt)
    answer = input().strip().lower()
    if answer == correct_answer.lower():
        print("Correct!")
        return 1
    else:
        print("Incorrect. The correct answer is: " + correct_answer)
        return 0

# Keep track of user scores
scores = []

# Collect the student's name
user_name = input("Enter your name: ")
print('Hello, ' + user_name + " running " + sys.executable)

while True:
    print("You will be asked several questions.")
    answer = input("Are you ready to take a test? (yes/no) ").lower().strip()
    
    if answer == "no":
        print("Okay, goodbye!")
        break
    elif answer != "yes":
        print("Invalid response. Please answer with 'yes' or 'no'.")
        continue

    correct = 0

    # Question 1
    correct += question_with_response("True or False: Boolean values can only be True or False.", "True")

    # Question 2
    correct += question_with_response("Which operator is used to compare two values for equality? (==, =, ===, eq)", "==")

    # Question 3
    correct += question_with_response("Which keyword is used to create a conditional statement? (if, cond, when, check)", "if")

    # Question 4
    correct += question_with_response("Which operator is used to check if one value is greater than another? (>, <, >=, =>)", ">")

    # Question 5
    correct += question_with_response("Which logical operator is used to check if both conditions are true? (and, or, not, xor)", "and")

    # Display the score
    print(user_name + ", you scored " + str(correct) + "/5")
    
    # Add score to the scores list
    scores.append(correct)

    # Display leaderboard
    print("\nLeaderboard:")
    sorted_scores = sorted(scores, reverse=True)
    for i, score in enumerate(sorted_scores):
        print(f"{i+1}. {score}/5")
    
    # Ask if they want to take the test again
    answer = input("Do you want to take the test again? (yes/no) ").lower().strip()
    if answer != "yes":
        print("Thank you for participating!")
        break

Hello, Tim running /opt/homebrew/opt/python@3.11/bin/python3.11
You will be asked several questions.
Question: True or False: Boolean values can only be True or False.
Correct!
Question: Which operator is used to compare two values for equality? (==, =, ===, eq)
Correct!
Question: Which keyword is used to create a conditional statement? (if, cond, when, check)
Correct!
Question: Which operator is used to check if one value is greater than another? (>, <, >=, =>)
Incorrect. The correct answer is: >
Question: Which logical operator is used to check if both conditions are true? (and, or, not, xor)
Correct!
Tim, you scored 4/5

Leaderboard:
1. 4/5
You will be asked several questions.
Question: True or False: Boolean values can only be True or False.
Correct!
Question: Which operator is used to compare two values for equality? (==, =, ===, eq)
Correct!
Question: Which keyword is used to create a conditional statement? (if, cond, when, check)
Correct!
Question: Which operator is used to check if one value is greater than another? (>, <, >=, =>)
Correct!
Question: Which logical operator is used to check if both conditions are true? (and, or, not, xor)
Correct!
Tim, you scored 5/5

Leaderboard:
1. 5/5
2. 4/5
Thank you for participating!