Homework and Popcorn Hacks for Lessons 3.1
Variables
A variable acts as a storage for data. Defining variables in both python and javascript have a similar procedures other than the fact that for javascript you have to define the variable by using statements such as let and var, while for python you can directly state a value for a variable.
Popcorn Hacks
%%js
// Create a dictionary (object) in JavaScript with unique values
var myDictionary = {
1: "Orange",
2: "mango",
3: "Strawberry"
};
// Accessing a value
console.log("Fruit with key 2:", myDictionary[2]); // Output: mango
<IPython.core.display.Javascript object>
3.1 was mainly about what variables and the different types, which is specifically used in my hack with a dictionary containing lists matching keys to values, so in this popcorn hack, the numbers to the fruit values.
import random
import time
def play_game():
score = 0
correct_streak = 0
multiplier = 1 # Multiplier for score based on streaks
time_limit = 10 # Base time limit in seconds
# Difficulty levels: Easy, Medium, Hard
print("Choose your difficulty level:")
print("1: Easy (numbers between 1-10)")
print("2: Medium (numbers between 1-20)")
print("3: Hard (numbers between 1-50)")
while True:
difficulty = input("Enter difficulty (1, 2, or 3): ")
if difficulty in ['1', '2', '3']:
break
print("Invalid choice. Please select 1, 2, or 3.")
if difficulty == '1':
num_range = 10
elif difficulty == '2':
num_range = 20
else:
num_range = 50
while True:
# Generate two random numbers based on difficulty level
num1 = random.randint(1, num_range)
num2 = random.randint(1, num_range)
# Randomly choose an operator: +, -, *, /
operator = random.choice(['+', '-', '*', '/'])
# Calculate the correct answer
if operator == '+':
correct_answer = num1 + num2
elif operator == '-':
correct_answer = num1 - num2
elif operator == '*':
correct_answer = num1 * num2
else: # operator == '/'
if num2 != 0:
correct_answer = round(num1 / num2, 2) # Rounded to 2 decimal places
else:
continue # Skip division by zero
# Display the question and start the timer
print(f"\nWhat is {num1} {operator} {num2}? (Type 'q' to quit)")
start_time = time.time()
# Show countdown timer
while True:
remaining_time = time_limit - (time.time() - start_time)
if remaining_time <= 0:
print(f"\nTime's up! You exceeded the {time_limit} seconds limit.")
correct_streak = 0
multiplier = 1
break
print(f"Time left: {round(remaining_time, 1)}s", end="\r")
player_input = input("\nYour answer: ")
# Allow the player to quit by typing 'q'
if player_input.lower() == 'q':
print(f"\nGame over! Your final score is: {score}")
return
try:
if float(player_input) == correct_answer:
custom_messages = ["Great job!", "You're on fire! 🔥", "Keep it up!", "Math genius! 🌟"]
print(random.choice(custom_messages))
correct_streak += 1
if correct_streak % 3 == 0:
multiplier += 1
print(f"Streak bonus! Multiplier now: x{multiplier}")
score += (1 * multiplier)
break
else:
print(f"Oops! The correct answer was {correct_answer}.")
correct_streak = 0
multiplier = 1
break
except ValueError:
print("Please enter a valid number or 'q' to quit.")
# End of game, display final score
print(f"\nGame over! Your final score is: {score}")
# Start the game
play_game()
This next popcorn hack is a math quiz, which I not only incorporated the different variables taught in this lesson but also added loops. In my code one example of when I used variables is score as I set the value to 0. In this code that represents that initially the score starts at zero, but by using mathemtical expressions such as, correct_answer = num1 + num2, the score will gradually increase based on how many the user gets correct.
// Temperature Converter in JavaScript
let temperature = parseFloat(prompt("Enter the temperature:"));
let conversionType = prompt("Convert to (C)elsius or (F)ahrenheit?").toUpperCase();
if (conversionType === "C") {
// Convert Fahrenheit to Celsius
let celsius = (temperature - 32) * (5 / 9);
console.log(`${temperature}°F is equal to ${celsius.toFixed(2)}°C`);
} else if (conversionType === "F") {
// Convert Celsius to Fahrenheit
let fahrenheit = (temperature * (9 / 5)) + 32;
console.log(`${temperature}°C is equal to ${fahrenheit.toFixed(2)}°F`);
} else {
console.log("Invalid conversion type entered.");
}
I used many coding concepts in this popcorn hack such as variables, which is shown in the code like ‘let termperature’ which stores the users temerature they inputed. I also used conditional statements such as if/ elif/else to check if the user chose to convert to Celsius or Farenheit, depending on that it will change its conversion. I also used mathematical operations such as toFixed as it ensures that the result of the temperature is displayed with two decimal places.
# Unique Temperature Converter in Python
# Function to convert temperatures
def temperature_converter():
try:
# Prompt the user for the temperature with a detailed message
temperature = float(input("🌡️ Enter the temperature value you'd like to convert: "))
# Ask the user for the conversion type with better clarity
conversion_type = input("🔄 Would you like to convert to (C)elsius or (F)ahrenheit? ").strip().upper()
if conversion_type == "C":
# Convert Fahrenheit to Celsius
celsius = (temperature - 32) * (5 / 9)
print(f"✅ Success! {temperature}°F is equal to {celsius:.2f}°C.")
# Check for extreme temperatures
if celsius < -273.15:
print("⚠️ Warning: This temperature is below absolute zero!")
elif conversion_type == "F":
# Convert Celsius to Fahrenheit
fahrenheit = (temperature * (9 / 5)) + 32
print(f"✅ Success! {temperature}°C is equal to {fahrenheit:.2f}°F.")
# Warn for unrealistically high or low temperatures
if fahrenheit > 1000:
print("⚠️ Caution: This seems like an extremely high temperature!")
elif fahrenheit < -459.67:
print("⚠️ Warning: This temperature is below absolute zero!")
else:
print("❌ Error: Invalid conversion type entered. Please enter 'C' for Celsius or 'F' for Fahrenheit.")
except ValueError:
print("❌ Error: Invalid input. Please enter a numeric temperature value.")
# Call the temperature converter function
temperature_converter()
This is the last popcorn hack for 3.1 which allows users to convert temperatures from Celcius and Farenheit. I used if/elif/else statements so the system can decide on converting to Farenheit or Celsius. In this case if the user chooses ‘C’ then the system will convert the degrees from farenheit to celsius, vice versa for choosing ‘F’. I also included a warning system to ensure that the users are typing in the corrent temperature, such as if the user were to have entered a degree above 1000, then it would print saying it was an exteremly high temperature, which is shown using an if statement like the following : ‘ if fahrenheit > 1000: print(“⚠️ Caution: This seems like an extremely high temperature!”)’ But overall the program works by first asking the user the temperature and how they would want to convert it. Based on that the system uses the mathematical expressions I coded to convert the degrees, unless the user provides an unrealistic degree amount.
Homework Hacks
# Initialize an empty shopping list and total cost
shopping_list = []
total_cost = 0.0
# Step 2: User Input for Shopping List
print("Welcome to your Shopping List! 🎉")
print("You can add items to your shopping list. Type 'done' when you are finished.\n")
while True:
# Get the name of the item
item_name = input("Enter the name of the item (or type 'done' to finish): ").strip()
# Check if the user wants to finish
if item_name.lower() == 'done':
break
# Get the price of the item
try:
item_price = float(input(f"Enter the price of {item_name}: $"))
except ValueError:
print("Invalid input. Please enter a numeric value for the price.")
continue # Skip this iteration if price is invalid
# Add the item and its price to the shopping list
shopping_list.append((item_name, item_price))
# Update the total cost
total_cost += item_price
print(f"Added {item_name} for ${item_price:.2f}.\n")
# Step 3: Display the shopping list and total cost
print("\nYour Shopping List:")
for item, price in shopping_list:
print(f"- {item}: ${price:.2f}")
print(f"\nTotal Cost: ${total_cost:.2f}")
This Python program is a shopping list, in which users can input items and their corresponding prices.
The system then calculates and displays the total cost of the items.
I set the initial value of the <code>shopping_list</code> variable as <code>[]</code>, as that is the
beginning of their list when they haven't added anything yet. After the user inputs values, the value of
the variable will gradually increase.
I also used conditionals such as <code>if item_name.lower() == 'done':</code>, which represents that when
the user is finished with their shopping list, they will enter 'done', which stops the calculation of the
prices of products.
I used a while loop in this homework hack as well, to continuously prompt the user to add their
grocery items until they finish.
// Step 1: Initialize Conversion Rates
const conversionRates = {
cupsToTablespoons: 16,
cupsToTeaspoons: 48,
tablespoonsToTeaspoons: 3,
};
// Function to convert the quantity based on the unit
function convertIngredient(quantity, unit, toUnit) {
let convertedQuantity;
if (unit === "cups") {
if (toUnit === "tablespoons") {
convertedQuantity = quantity * conversionRates.cupsToTablespoons;
} else if (toUnit === "teaspoons") {
convertedQuantity = quantity * conversionRates.cupsToTeaspoons;
}
} else if (unit === "tablespoons") {
if (toUnit === "cups") {
convertedQuantity = quantity / conversionRates.cupsToTablespoons;
} else if (toUnit === "teaspoons") {
convertedQuantity = quantity * conversionRates.tablespoonsToTeaspoons;
}
} else if (unit === "teaspoons") {
if (toUnit === "cups") {
convertedQuantity = quantity / conversionRates.cupsToTeaspoons;
} else if (toUnit === "tablespoons") {
convertedQuantity = quantity / conversionRates.tablespoonsToTeaspoons;
}
}
return convertedQuantity;
}
// Step 2: Input for Ingredients
console.log("Welcome to the Recipe Ingredient Converter! 🎉");
let ingredients = [];
while (true) {
let ingredientName = prompt("Enter the name of the ingredient (or type 'done' to finish):");
if (ingredientName.toLowerCase() === "done") {
break; // Exit the loop if the user is done
}
let quantity = parseFloat(prompt(`Enter the quantity of ${ingredientName}:`));
let currentUnit = prompt("Enter the current unit (cups, tablespoons, teaspoons):").toLowerCase();
let desiredUnit = prompt("Enter the desired unit to convert to (cups, tablespoons, teaspoons):").toLowerCase();
// Perform the conversion
let convertedQuantity = convertIngredient(quantity, currentUnit, desiredUnit);
// Step 4: Display the Converted Results
if (convertedQuantity !== undefined) {
console.log(`${quantity} ${currentUnit} of ${ingredientName} is equal to ${convertedQuantity.toFixed(2)} ${desiredUnit}.`);
} else {
console.log("Invalid unit conversion. Please check your inputs.");
}
// Store ingredient data
ingredients.push({
name: ingredientName,
quantity: quantity,
currentUnit: currentUnit,
convertedQuantity: convertedQuantity,
desiredUnit: desiredUnit
});
}
// Display all converted results at once
console.log("\nConverted Ingredients Summary:");
ingredients.forEach(ingredient => {
console.log(`${ingredient.quantity} ${ingredient.currentUnit} of ${ingredient.name} is equal to ${ingredient.convertedQuantity?.toFixed(2) || 'N/A'} ${ingredient.desiredUnit}.`);
});
This second homework hack is a recipe ingrediant converter allowing the user to input ingredients with their quantities in one unit, ex : cups or tablespoons, and then convert them to another unit, ex : teaspoons. First, I set up a dictionary (conversionRates), then stored the values of conversions inside of them, with variables, ‘cupsToTeaspoons: 48’. Then I used the convertingrediant function which takes the quantity, current unit, and wanted unit as input and performs the conversion based on the conversion rates given. They continously will get prompted by entering their ingrediants until they enter stop as shown ‘while (true) { let ingredientName = prompt(“Enter the name of the ingredient (or type ‘done’ to finish):”);
if (ingredientName.toLowerCase() === "done") {
break; // Exit the loop if the user is done
} }' Then after the user enters done a summary of all the ingrediants will appear in the console, 'console.log("\nConverted Ingredients Summary:"); ingredients.forEach(ingredient => {
console.log(`${ingredient.quantity} ${ingredient.currentUnit} of ${ingredient.name} is equal to ${ingredient.convertedQuantity?.toFixed(2) || 'N/A'} ${ingredient.desiredUnit}.`); });'