Fall 2024 - P4
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
CSP Period 4 Unit 3.6.1 Conditionals in Python
In this lesson, students will learn how to use if-else statements in Python to make decisions in their code. They will discover how to use if to check if something is true, else for what happens if it's not true, and elif for more choices. Students will also learn how to combine conditions using and, or, and not. By the end of the lesson, they will be able to write simple programs that make decisions based on different situations.
Conditionals
Conditionals help control the flow of a program by deciding which code to execute based on a true or false condition.
IF (condition) { }
- The code inside the brackets runs only if the condition is true. If the condition is false, nothing happens.
IF (condition) { } ELSE { }
- The code in the first set of brackets runs if the condition is true. If the condition is false, the code in the second set of brackets runs instead.
Basic Example
- Add a variable that represents temperature.
- Use an ‘if’ statement to print “It’s a hot day” if the temperature is greater than or equal to 30 degrees.
- Use an ‘else’ statement to print “It’s a cold day” otherwise.
# Step 1: Add a variable that represents temperature
temperature = 50 # You can change this value to test different conditions
# Step 2: Check if it’s a hot day
if temperature >= 80:
print("It's a hot day")
# Step 3: Otherwise, print it's a cold day
else:
print("It's a cold day")
It's a cold day
Popcorn Hack #1
What would happen if you added more temperature ranges (like ‘warm’ for temperatures between 60 and 79 degrees)? How would you modify the code to implement this feature?”
Example with Booleans
- Add a variable called is_logged_in and set it to False.
- Use an if statement to print “Welcome back!” if is_logged_in is True.
- Use an else statement to print “Please log in.” if it is False.
# Step 1: Create a variable called is_logged_in
is_logged_in = False # You can change this to True to test the other condition
# Step 2: Check if the user is logged in
if is_logged_in:
print("Welcome back!")
# Step 3: Otherwise, prompt the user to log in
else:
print("Please log in.")
Please log in.
Popcorn Hack #2
How would you modify the code to include a message for a successful login attempt? What additional condition would you need to implement this?
Example using Random
- Make a function to randomize ages between 1 and 100 using random.randint.
- Assign the randomized ages to variables age1 and age2.
- Print the values of the ages.
- Print the relationship between the ages: age1 is older than, the same age as, or younger than age2.
import random
def randomize_ages():
# Step 1: Randomize ages between 1 and 100
age1 = random.randint(1, 100)
age2 = random.randint(1, 100)
# Step 2: Print the values of the ages
print(f"Person 1's age: {age1}")
print(f"Person 2's age: {age2}")
# Step 3: Print the relationship of the ages
if age1 > age2:
print("Person 1 is older than Person 2.")
elif age1 < age2:
print("Person 1 is younger than Person 2.")
else:
print("Person 1 is the same age as Person 2.")
# Call the function
randomize_ages()
Person 1's age: 29
Person 2's age: 82
Person 1 is younger than Person 2.
Popcorn Hack #3
How could you modify the function to include a check for whether either person is considered a minor (under 18)?
Quiz Time!
# Import necessary modules
import getpass
import sys
# Function to ask a question and get a response
def question_with_response(prompt):
answer = input(prompt)
return answer
# Define the number of questions and initialize the correct answers counter
questions = 5
correct = 0
# Personalized greeting message
user_name = question_with_response("Enter your name: ")
print('Hello, ' + user_name + "! You are running " + sys.executable)
ready = question_with_response("Are you ready to take a quiz on Python conditionals? (yes/no): ")
# Question 1: Boolean Basics
response1 = question_with_response("What are the one of the two possible values of a Boolean? (true/false): ")
if response1.lower() in ['true', 'false']:
correct += 1
print("Correct!")
else:
print("Incorrect. The correct answers are 'true' or 'false'.")
# Question 2: Boolean Expressions
response2 = question_with_response("Why are Boolean expressions important in programming? ")
if "true" in response2.lower() or "false" in response2.lower():
correct += 1
print("Correct!")
else:
print("Incorrect. Boolean expressions are essential for making decisions in code.")
# Question 3: Conditional Statements
response3 = question_with_response("What is the purpose of conditional statements in programming? ")
if "make decisions" in response3.lower() or "control flow" in response3.lower():
correct += 1
print("Correct!")
else:
print("Incorrect. They are used to control the flow of the program.")
# Question 4: Relational Operators
response4 = question_with_response("Name a common relational operator in programming. ")
if response4 in ['>', '<', '>=', '<=', '==', '!=']:
correct += 1
print("Correct!")
else:
print("Incorrect. Examples include '>', '<', '=='.")
# Question 5: Logical Operators
response5 = question_with_response("What are the two common logical operators? ")
if response5 in ['and', 'or', 'not']:
correct += 1
print("Correct!")
else:
print("Incorrect. Common logical operators are 'and', 'or', and 'not'.")
# Final score
print(user_name + ", you scored " + str(correct) + "/" + str(questions))
Hello, vibha! You are running /home/vibha/nighthawk/sprint_2/venv/bin/python
Incorrect. The correct answers are 'true' or 'false'.
Incorrect. Boolean expressions are essential for making decisions in code.
Correct!
Correct!
Correct!
vibha, you scored 3/5