3.8 Homework and Popcorn Hacks
3.8 Homework and Popcorn Hacks
Popcorn Hack 1
counter = 5 # Initialize the counter variable
while 1 <= counter <= 5: # Loop while the counter is between 1 and 5 (including 5)
print("Hello") # Print "Hello"
counter -= 1 # Decrement the counter by 1
Hello
Hello
Hello
Hello
Hello
Popcorn Hack 2
# Define the names
first_name = "Anvay"
middle_name = "Varin"
last_name = "Vahia"
# Repeat the entire sequence 4 times by initializing a repeat count
repeat_count = 0
while repeat_count < 4:
# Print the first name one time
print(first_name)
# Print the middle name two times
middle_count = 0
while middle_count < 2:
print(middle_name)
middle_count += 1
# Print the last name three times
last_count = 0
while last_count < 3:
print(last_name)
last_count += 1
print() # Print a blank line
# Increment the repeat count
repeat_count += 1
Anvay
Varin
Varin
Vahia
Vahia
Vahia
Anvay
Varin
Varin
Vahia
Vahia
Vahia
Anvay
Varin
Varin
Vahia
Vahia
Vahia
Anvay
Varin
Varin
Vahia
Vahia
Vahia
Popcorn Hack 3
myname = "Anvay" # Initialize the string variable myname
for letter in myname: # Loop through each letter in the string
print(letter) # Print the letter
A
n
v
a
y
Popcorn Hack 4
# Create a dictionary
fruit_dict = {
"apple": "red",
"banana": "yellow",
"cherry": "red",
"date": "brown",
"fig": "purple",
"grape": "purple"
}
# Iterate through each key and value in the dictionary
for key, value in fruit_dict.items():
# Print the key, value, and a custom message
print(f"The color of {key} is {value}.")
The color of apple is red.
The color of banana is yellow.
The color of cherry is red.
The color of date is brown.
The color of fig is purple.
The color of grape is purple.
Homework Hacks
Hack #1 While loops
password = input("Enter your password: ") # Prompt the user to enter a password
while password != "secret": # Loop while the password is incorrect
print("Incorrect password. Try again.") # Print an error message
password = input("Enter your password: ") # Prompt the user to enter a password again
print("Password accepted.") # Print a success message
Incorrect password. Try again.
Incorrect password. Try again.
Incorrect password. Try again.
Incorrect password. Try again.
Incorrect password. Try again.
Password accepted.
Hack #2 For loops
usersName = input("Enter your name: ") # Prompt the user to enter their name
for letter in usersName: # Loop through each letter in the input
print(letter) # Print the letter
A
n
v
a
y
Hack #3 For loops with lists
fruitList = ["apple", "banana", "cherry", "date", "fig", "grape"] # Create a list of fruits
for fruit in fruitList: # Loop through each fruit in the list
print(fruit) # Print the fruit
apple
banana
cherry
date
fig
grape