Hack 1, 3.8.1: popcorn
# Popcorn Hack: Divisibility by 3
# Create an empty list
nums = []
# Get user input for how many numbers they want to add
num_of_inputs = int(input("How many numbers do you want to add to the list? "))
# Use a loop to get inputs and append them to the list
for _ in range(num_of_inputs):
number = int(input("Enter a number: "))
nums.append(number)
# Use a for loop to iterate through the list and check divisibility by 3
print("Numbers divisible by 3:")
for num in nums:
if num % 3 == 0: # Nested if statement to check divisibility by 3
print(num)
Numbers divisible by 3:
Hack 2, 3.8.8: homeowrk
# Part 1: Iterating through the list and applying rules
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
continue # Skip number 3
if num == 5:
break # Stop the loop completely at 5
print(num) # Print the number if it's not skipped or breaking the loop
# Part 2: Error handling in loops
elements = [1, 2, 0, "three", 4, "five", 5]
for elem in elements:
try:
# Attempt to divide 10 by each element
result = 10 / elem
print(f"10 divided by {elem} is {result}")
except ZeroDivisionError:
print("Division by zero.")
except TypeError:
print("Type error.") # Handle if it's not a number (e.g., a string)
1
2
4
10 divided by 1 is 10.0
10 divided by 2 is 5.0
Division by zero.
Type error.
10 divided by 4 is 2.5
Type error.
10 divided by 5 is 2.0
Hack 3, 3.8.7: homework
# Exercise 1 and 2 combined
# Exercise 1: Loop through a list of colors
colors = ["red", "blue", "green", "yellow"]
for color in colors:
print(color) # Display each color
# Exercise 2: Loop through a dictionary of fruits and their quantities
fruits = {"apple": 3, "banana": 5, "cherry": 7} # Number of each type of fruit
for fruit, quantity in fruits.items():
print(fruit, ":", quantity) # Display each fruit and its corresponding quantity
red
blue
green
yellow
apple : 3
banana : 5
cherry : 7