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.
<!-- Below is in CollegeBoard Pseudocode -->
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.
age = 21
# age = input("What is your age?") if want to prompt user for age
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”.
isRaining = True
if isRaining:
print("Bring an umbrella!")
else:
print("The weather is clear")
The weather is clear
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
import random
a = random.randint(0,100)
b = random.randint(0,100)
print("Variable a is " + str(a))
print("Variable b is " + str(b))
if a > b:
print("Variable a is greater than variable b")
elif a == b:
print("Variable a is equal to variable b")
else:
print("Variable a is less than variable b")
Variable a is 26
Variable b is 32
Variable a is less than variable 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.
# The quiz contains questions related to Boolean values, Boolean expressions,
# conditional statements, relational operators, and logical operators.
# Import necessary modules
import getpass # Module to get the user's name
import sys # Module to access system-related information
# Function to ask a question and get a response
def question_with_response(prompt):
# Print the question
print("Question: " + prompt)
# Get user input as the response
msg = input()
return msg
# 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 question about Boolean values and check the response
# Provide feedback based on the correctness of the response
question1 = question_with_response("What is one value Booleans can take?")
if question1.lower() == "true" or question1 == "false":
correct += 1
print("You answered question 1 correctly!")
else:
print("You did not answer question 1 correctly. The correct answer was either 'true' or 'false'.")
# Question 2: Boolean Expressions
# Ask a question about Boolean expressions and their importance in programming
# Provide feedback based on the correctness of the response
question2 = question_with_response("What is one Boolean expression?")
if question2 == ">" or question2 == "<" or question2 == "==" or question2 == "!=" or question2 == ">=" or question2 == "<=":
correct += 1
print("You answered question 2 correctly!")
else:
print("You did not answer question 2 correctly. The correct answer was >, <, ==, !=, >=, or <=.")
# Question 3: Conditional Statements
# Ask a question about the purpose of conditional (if-else) statements in programming
# Provide feedback based on the correctness of the response
question3 = question_with_response("Fill in the blank. Conditional statements can run __________ (9 letters) code lines depending on different conditions or Boolean expressions.")
if question3.lower() == "different":
correct += 1
print("You answered question 3 correctly!")
else:
print("You did not answer question 3 correctly. The correct answer was 'different'.")
# Question 4: Relational Operators
# Ask a question about common relational operators in programming and provide examples
# Provide feedback based on the correctness of the response
question4 = question_with_response("Variable a is equal to 10, and variable b is equal to 5. The code only contains 'if a _ b:' and has 'print('a is larger than b')' nested under it. If the console outputted 'a is larger than b', what should be in the blank?")
if question4 == ">":
correct += 1
print("You answered question 4 correctly!")
else:
print("You did not answer question 4 correctly. The correct answer was >.")
# Question 5: Logical Operators
# Ask a question about the use of logical operators in programming and provide examples
# Provide feedback based on the correctness of the response
question5 = question_with_response("Fill in the blank if the output is True and there are no repeat answers. 10 > 5 ___ 5 < 10, 10 > 5 ___ 7 > 3, ___ -1 >6. Format your answer like ___, ___, ___.")
if question5.lower() == "or, and, not":
correct += 1
print("You answered question 5 correctly!")
else:
print("You did not answer question 5 correctly. The correct answer was 'or, and, not'.")
# Question 6: If, elif, else
question6 = question_with_response("What are the two major conditional statements in python? What can be considered the combination of both of them? Hint, the first word is 2 letters and the second and third are 4 letters. Format your answer like __ ____, ____")
if question5.lower() == "if else, elif":
correct += 1
print("You answered question 6 correctly!")
else:
print("You did not answer question 6 correctly. The correct answer was 'if else, elif'.")
# Calculate the percentage of correct answers
percentageCorrect = (correct / questions) * 100
if percentageCorrect >= 90:
grade = "A"
elif percentageCorrect >= 80 and percentageCorrect < 90:
grade = "B"
elif percentageCorrect >= 70 and percentageCorrect < 80:
grade = "C"
elif percentageCorrect >= 60 and percentageCorrect < 70:
grade = "D"
else:
grade = "F"
# Display the final score and percentage
print(user_name + ", you scored " + str(correct) + "/" + str(questions) +"! This corresponds to an " + grade + "!")
Hello, test running /bin/python
You will be asked 5 questions.
Question: What is one value Booleans can take?
You answered question 1 correctly!
Question: What is one Boolean expression?
You answered question 2 correctly!
Question: Fill in the blank. Conditional statements can run __________ (9 letters) code lines depending on different conditions or Boolean expressions.
You answered question 3 correctly!
Question: Variable a is equal to 10, and variable b is equal to 5. The code only contains 'if a _ b:' and has 'print('a is larger than b')' nested under it. If the console outputted 'a is larger than b', what should be in the blank?
You answered question 4 correctly!
Question: Fill in the blank if the output is True and there are no repeat answers. 10 > 5 ___ 5 < 10, 10 > 5 ___ 7 > 3, ___ -1 >6. Format your answer like ___, ___, ___.
You did not answer question 5 correctly. The correct answer was 'or, and, not'.
Question: What are the two major conditional statements in python? What can be considered the combination of both of them? Hint, the first word is 2 letters and the second and third are 4 letters. Format your answer like __ ____, ____
You did not answer question 6 correctly. The correct answer was 'if else, elif'.
test, you scored 4/5! This corresponds to an B!