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.
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
age = 16
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
You are a minor
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
is_raining = 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
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 getpass # Module to get the user's name
import sys # Module to access system-related information
# Function to ask a multiple-choice question and get a response
def question_multiple_choice(prompt, options, correct_option):
# Print the question and options
print("Question: " + prompt)
for i, option in enumerate(options, start=97): # Use ASCII values a=97, b=98, ...
print(chr(i) + ") " + option)
# Get user input as the response
response = input("Your answer (a, b, c, or d): ").lower()
if response == correct_option:
print("Correct!")
return 1
else:
print("Incorrect. The correct answer is " + correct_option + ".")
return 0
# Define the number of questions and initialize the correct answers counter
questions = 5
correct = 0
# Personalized greeting message
# Collect the student's name
user_name = input("Enter your name: ")
print('Hello, ' + user_name + " running " + sys.executable)
print("You will be asked " + str(questions) + " questions.")
answer = input("Are you ready to take a test?")
# Question 1: Boolean Basics
# Ask a multiple-choice question about Boolean values and check the response
options_1 = ["True", "False"]
correct_option_1 = "a"
correct += question_multiple_choice("What are the possible values of a Boolean in Python?", options_1, correct_option_1)
# Question 2: Boolean Expressions
# Ask a multiple-choice question about Boolean expressions and their importance in programming
options_2 = ["To represent truth values", "To perform arithmetic operations", "To format text", "To store lists"]
correct_option_2 = "a"
correct += question_multiple_choice("Why are Boolean expressions important in programming?", options_2, correct_option_2)
# Question 3: Conditional Statements
# Ask a multiple-choice question about the purpose of conditional (if-else) statements in programming
options_3 = ["To control program flow", "To declare variables", "To perform calculations", "To print output"]
correct_option_3 = "a"
correct += question_multiple_choice("What is the purpose of conditional (if-else) statements in programming?", options_3, correct_option_3)
# Question 4: Relational Operators
# Ask a multiple-choice question about common relational operators in programming and provide examples
options_4 = ["<, >, ==", "&&, ||, !", "++, --", "+, -"]
correct_option_4 = "a"
correct += question_multiple_choice("Name some common relational operators in programming and provide an example.", options_4, correct_option_4)
# Question 5: Logical Operators
# Ask a multiple-choice question about the use of logical operators in programming and provide examples
options_5 = ["To combine boolean expressions", "To perform mathematical operations", "To format text", "To declare variables"]
correct_option_5 = "a"
correct += question_multiple_choice("Explain the use of logical operators in programming and provide an example.", options_5, correct_option_5)
# Display the final score
# Calculate the percentage of correct answers and provide feedback
percentage_correct = (correct / questions) * 100
print(user_name + ", you scored " + str(correct) + "/" + str(questions) + " (" + str(percentage_correct) + "%)")
Hello, ethan running /opt/homebrew/opt/python@3.11/bin/python3.11
You will be asked 5 questions.
Question: What are the possible values of a Boolean in Python?
a) True
b) False
Correct!
Question: Why are Boolean expressions important in programming?
a) To represent truth values
b) To perform arithmetic operations
c) To format text
d) To store lists
Correct!
Question: What is the purpose of conditional (if-else) statements in programming?
a) To control program flow
b) To declare variables
c) To perform calculations
d) To print output
Incorrect. The correct answer is a.
Question: Name some common relational operators in programming and provide an example.
a) <, >, ==
b) &&, ||, !
c) ++, --
d) +, -
Correct!
Question: Explain the use of logical operators in programming and provide an example.
a) To combine boolean expressions
b) To perform mathematical operations
c) To format text
d) To declare variables
Correct!
ethan, you scored 4/5 (80.0%)