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.
Cell In[1], line 3
<block of statements>
^
SyntaxError: invalid syntax
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
# Step 1: Add a variable that represents an age
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”.
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
import random
def randomize_numbers():
a = random.randint(0, 100)
b = random.randint(0, 100)
return a, b
a, b = randomize_numbers()
print(a)
print(b)
if a > b:
print("a is greater than b")
elif a == b:
print("a equals b")
else:
print("a is less than b")
91
62
a is greater 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.
##Homework
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, correct_answer):
# Print the question
print("Question: " + prompt)
# Get user input as the response
response = input("Your Answer: ")
if response.lower() == correct_answer.lower():
return True
else:
return False
# Leaderboard system
scores = {}
# Define the number of questions and initialize the correct answers counter
questions_count = 5
correct = 0
# Personalized greeting message
# Collect the student's name
user_name = input("Enter your name: ")
if user_name in scores:
print(f'Welcome back, {user_name}! Your previous score was {scores[user_name]}.')
print('Hello, ' + user_name + ". You will be asked " + str(questions_count) + " questions.")
answer = input("Are you ready to take a test? (yes/no) ")
if answer.lower() == 'yes':
# Question 1: Boolean Basics
if question_with_response("True or False: In Python, Boolean values can only be True or False.", "True"):
correct += 1
print("Correct!")
else:
print("Wrong. The correct answer is True.")
# Question 2: Boolean Expressions
if question_with_response("Which of the following evaluates to False? (a) 'True and False' (b) 'True or False'", "a"):
correct += 1
print("Correct!")
else:
print("Wrong. The correct answer is (a) 'True and False'.")
# Question 3: Conditional Statements
if question_with_response("What will be the output of the following code?\nif False:\n print('Hello')\nelse:\n print('World')", "World"):
correct += 1
print("Correct!")
else:
print("Wrong. The correct output is 'World'.")
# Question 4: Relational Operators
if question_with_response("Which of the following is a relational operator in Python? (a) && (b) <= (c) ||", "b"):
correct += 1
print("Correct!")
else:
print("Wrong. The correct answer is (b) <=.")
# Question 5: Logical Operators
if question_with_response("Which of the following is not a logical operator in Python? (a) and (b) or (c) not (d) &", "d"):
correct += 1
print("Correct!")
else:
print("Wrong. The correct answer is (d) &.")
# Display the final score
score = (correct / questions_count) * 100
print(f"{user_name}, you scored {correct}/{questions_count} which is {score:.2f}%")
# Update the score in leaderboard
scores[user_name] = score
print("\n---Leaderboard---")
sorted_scores = dict(sorted(scores.items(), key=lambda item: item[1], reverse=True))
for key, value in sorted_scores.items():
print(f"{key}: {value:.2f}%")
else:
print("Okay, maybe next time!")
Hello, Rayane. You will be asked 5 questions.
Question: True or False: In Python, Boolean values can only be True or False.
Correct!
Question: Which of the following evaluates to False? (a) 'True and False' (b) 'True or False'
Correct!
Question: What will be the output of the following code?
if False:
print('Hello')
else:
print('World')
Correct!
Question: Which of the following is a relational operator in Python? (a) && (b) <= (c) ||
Correct!
Question: Which of the following is not a logical operator in Python? (a) and (b) or (c) not (d) &
Correct!
Rayane, you scored 5/5 which is 100.00%
---Leaderboard---
Rayane: 100.00%