Conditionals

Conditionals help control the flow of a program by deciding which code to execute based on a true or false condition.

1. Basic IF Statement:
IF (condition) { }
  • The code inside the brackets runs only if the condition is true. If the condition is false, nothing happens.
2. IF-ELSE Statement:
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

  1. Add a variable that represents temperature.
  2. Use an ‘if’ statement to print “It’s a hot day” if the temperature is greater than or equal to 30 degrees.
  3. 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

  1. Add a variable called is_logged_in and set it to False.
  2. Use an if statement to print “Welcome back!” if is_logged_in is True.
  3. 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

  1. Make a function to randomize ages between 1 and 100 using random.randint.
  2. Assign the randomized ages to variables age1 and age2.
  3. Print the values of the ages.
  4. 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