Summary | 3.1 | 3.2 | 3.3 | 3.4 | 3.5 | 3.6 | 3.7 | 3.10 | Relevancy |
Homeworks and Popcorn Hacks for Lessons
Homeworks and Hacks for Lesson 3.1
Lesson 3.1 Popcorn Hacks and Homework
Popcorn Hack #1
Javascript Version
%%js
var myDictionary = {
1: "grape",
2: "strawberry",
3: "pineapple"
};
console.log("Fruit with key 2:", myDictionary[2]);
<IPython.core.display.Javascript object>
Python Version
myDictionary = {
1: "blueberry",
2: "raspberry",
3: "apple"
}
print("Fruit with key 2:", myDictionary[2])
Fruit with key 2: raspberry
Popcorn Hack #2
Python Version
import random
def play_game():
score = 0
operators = ['+', '-', '*']
print("Welcome to the Math Quiz Game!")
print("Answer as many questions as you can. Type 'q' to quit anytime.\n")
while True:
num1 = random.randint(1, 20)
num2 = random.randint(1, 20)
op = random.choice(operators)
if op == '+':
answer = num1 + num2
elif op == '-':
answer = num1 - num2
elif op == '*':
answer = num1 * num2
else:
answer = num1 / num2
print(f"What is {num1} {op} {num2}?")
player_input = input("Your answer (or type 'q' to quit): ")
if player_input.lower() == 'q':
break
try:
player_answer = int(player_input)
if player_answer == answer:
print("Correct!")
score += 1
else:
print(f"Oops! The correct answer was {answer}.")
except ValueError:
print("Invalid input, please enter a number or 'q' to quit.")
print(f"Thanks for playing! Your final score is {score}.")
play_game()
Welcome to the Math Quiz Game!
Answer as many questions as you can. Type 'q' to quit anytime.
What is 13 + 2?
Correct!
What is 9 * 15?
Thanks for playing! Your final score is 1.
Popcorn Hack #3
Javascript Version
%%js
let temperature = parseFloat(prompt("Enter the temperature:"));
let conversionType = prompt("Convert to (C)elsius or (F)ahrenheit?").toUpperCase();
if (conversionType === "C") {
let celsius = (temperature - 32) * (5 / 9);
console.log(`${temperature}°F is equal to ${celsius.toFixed(2)}°C`);
} else if (conversionType === "F") {
let fahrenheit = (temperature * (9 / 5)) + 32;
console.log(`${temperature}°C is equal to ${fahrenheit.toFixed(2)}°F`);
} else {
console.log("Invalid conversion type entered.");
}
<IPython.core.display.Javascript object>
Python Version
def temperature_converter():
try:
temperature = float(input("Enter the temperature: "))
conversion_type = input("Convert to Celsius or Fahrenheit? ").strip().upper()
if conversion_type == "C":
pass
# TODO: Convert Fahrenheit to Celsius
# celsius = (temperature - 32) * (5 / 9)
# print(f"{temperature}°F is equal to {celsius:.2f}°C")
elif conversion_type == "F":
pass
# TODO: Convert Celsius to Fahrenheit
# fahrenheit = (temperature * (9 / 5)) + 32
# print(f"{temperature}°C is equal to {fahrenheit:.2f}°F")
else:
print("Invalid conversion type entered. Please enter 'C' or 'F'.")
except ValueError:
print("Invalid input. Please enter a numeric temperature value.")
temperature_converter()
Homework Lesson 3.1
Python Homework: Shooping List Calculator
def shopping_list_calculator():
shopping_list = []
total_cost = 0.0
while True:
item = input("Enter item name (or type 'done' to finish): ").strip()
if item.lower() == 'done':
break
try:
price = float(input(f"Enter the price of {item}: $").strip())
shopping_list.append((item, price))
except ValueError:
print("Invalid input. Please enter a valid price.")
for item, price in shopping_list:
total_cost += price
print("\n--- Shopping List ---")
for item, price in shopping_list:
print(f"{item}: ${price:.2f}")
print(f"\nTotal cost: ${total_cost:.2f}")
shopping_list_calculator()
--- Shopping List ---
cake: $3.00
Total cost: $3.00
Javascript Homework: Recipe Ingredient Converter
%%js
const conversionRates = {
"cupsToTablespoons": 16,
"tablespoonsToTeaspoons": 3,
"cupsToTeaspoons": 48
};
function recipeConverter() {
let ingredients = [];
while (true) {
let ingredient = prompt("Enter the ingredient name (or type 'done' to finish): ");
if (ingredient.toLowerCase() === 'done') break;
let quantity = parseFloat(prompt(`Enter the quantity of ${ingredient}: `));
let currentUnit = prompt(`Enter the current unit (cups, tablespoons, teaspoons): `).toLowerCase();
let desiredUnit = prompt(`Convert ${ingredient} to (cups, tablespoons, teaspoons): `).toLowerCase();
let convertedQuantity;
if (currentUnit === "cups" && desiredUnit === "tablespoons") {
convertedQuantity = quantity * conversionRates.cupsToTablespoons;
} else if (currentUnit === "tablespoons" && desiredUnit === "teaspoons") {
convertedQuantity = quantity * conversionRates.tablespoonsToTeaspoons;
} else if (currentUnit === "cups" && desiredUnit === "teaspoons") {
convertedQuantity = quantity * conversionRates.cupsToTeaspoons;
} else if (currentUnit === desiredUnit) {
convertedQuantity = quantity;
} else {
alert("Invalid conversion units! Please try again.");
continue;
}
ingredients.push({
name: ingredient,
originalQuantity: `${quantity} ${currentUnit}`,
convertedQuantity: `${convertedQuantity} ${desiredUnit}`
});
}
console.log("\n--- Recipe Ingredient Conversions ---");
ingredients.forEach(item => {
console.log(`${item.name}: ${item.originalQuantity} -> ${item.convertedQuantity}`);
});
}
recipeConverter();
<IPython.core.display.Javascript object>