3.1 and 3.4 Popcorn and Homework Hacks
Yash's Submission for 3.1 and 3.4 Homework
Variables
Popcorn Hack #1
%%js
//ADDED MY OWN FRUITS
var myDictionary = {
1: "apple",
2: "banana",
3: "orange"
};
// Accessing a value
console.log("Fruit with key 2:", myDictionary[2]); // Output: fruit
<IPython.core.display.Javascript object>
Popcorn Hack 2
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:
# Generate two random numbers and choose a random operator
num1 = random.randint(1, 20)
num2 = random.randint(1, 20)
op = random.choice(operators)
# Calculate the correct answer based on the operator
if op == '+':
answer = num1 + num2
elif op == '-':
answer = num1 - num2
elif op == '/':
answer = num1 / num2
else:
answer = num1 * num2
# Ask the player the question
print(f"What is {num1} {op} {num2}?")
player_input = input("Your answer (or type 'q' to quit): ")
# Check if the player wants to quit
if player_input.lower() == 'q':
break
# Check if the answer is correct
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}.")
# Start the game
play_game()
Welcome to the Math Quiz Game!
Answer as many questions as you can. Type 'q' to quit anytime.
What is 14 + 8?
Invalid input, please enter a number or 'q' to quit.
What is 8 * 2?
Correct!
What is 15 + 12?
Correct!
What is 3 - 15?
Thanks for playing! Your final score is 2.
Popcorn Hack 3
def temperature_converter():
temperature = float(input("Enter the temperature: "))
conversion_type = input("Convert to Celsius or Fahrenheit? [C/F]")
if conversion_type == "C":
celsius = (temperature - 32) * (5 / 9)
print(f"{temperature}°F is equal to {celsius:.2f}°C")
elif conversion_type == "F":
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'.")
temperature_converter()
55.0°F is equal to 12.78°C
Python Homework Hack
shopping_list = []
total_cost = 0.0
while True:
item_name = input("Enter the item name (or 'done' to finish): ")
if item_name.lower() == 'done':
break
item_price = float(input("Enter the price of the item: "))
shopping_list.append((item_name, item_price))
total_cost += item_price
print("\nYour shopping list:")
for item in shopping_list:
print(f"{item[0]} - ${item[1]:.2f}")
print(f"\nTotal cost: ${total_cost:.2f}")
Your shopping list:
Taco shells - $7.50
Black Beans - $3.50
Lettuce - $6.25
Shredded Cheese - $7.99
Salsa - $4.99
Total cost: $30.23
Javascript Homework Hack
%%js
// THIS TOOK ME A WHILE TO FIGURE OUT
const cupToTablespoon = 16;
const cupToTeaspoon = 48;
const tablespoonToTeaspoon = 3;
let ingredients = [];
let result = '';
while (true) {
let ingredientName = prompt("Enter the ingredient name (or 'done' to finish): ");
if (ingredientName === 'done') {
break;
}
let quantity = parseFloat(prompt(`Enter the quantity for ${ingredientName}: `));
let currentUnit = prompt("Enter the current unit (cup, tablespoon, teaspoon): ")
let targetUnit = prompt("Enter the unit to convert to (cup, tablespoon, teaspoon): ")
let convertedQuantity;
if (currentUnit === "cup" && targetUnit === "tablespoon") {
convertedQuantity = quantity * cupToTablespoon;
} else if (currentUnit === "cup" && targetUnit === "teaspoon") {
convertedQuantity = quantity * cupToTeaspoon;
} else if (currentUnit === "tablespoon" && targetUnit === "cup") {
convertedQuantity = quantity / cupToTablespoon;
} else if (currentUnit === "tablespoon" && targetUnit === "teaspoon") {
convertedQuantity = quantity * tablespoonToTeaspoon;
} else if (currentUnit === "teaspoon" && targetUnit === "cup") {
convertedQuantity = quantity / cupToTeaspoon;
} else if (currentUnit === "teaspoon" && targetUnit === "tablespoon") {
convertedQuantity = quantity / tablespoonToTeaspoon;
}
result += `${quantity} ${currentUnit} of ${ingredientName} is equal to ${convertedQuantity.toFixed(2)} ${targetUnit}.\n`;
}
console.log(result);
<IPython.core.display.Javascript object>
Strings
Popcorn Hack 1
%%js
// BONUS - I ADDED PROMPTS TO GET USER INPUT
let myfavoritemovie = prompt("Enter your favorite movie: ");
let myfavoritesport = prompt("Enter your favorite sport: ");
let myfavoritefood = prompt("Enter your favorite food: ");
// Concatenation
let concatenatedMessage = "My favorite movie is " + myfavoritemovie + ". I love playing " + myfavoritesport + " and my favorite food is " + myfavoritefood + ".";
// Interpolation
let interpolatedMessage = `My favorite movie is ${myfavoritemovie}. I love playing ${myfavoritesport} and my favorite food is ${myfavoritefood}.`;
// I ADDED OUTPUT
console.log(concatenatedMessage);
console.log(interpolatedMessage);
<IPython.core.display.Javascript object>
Popcorn Hack 2
%%javascript
//INPUT
let sentence = "Genius is 1% inspiration and 99% perspiration.";
let wordGenius = sentence.slice(0, 6);
let wordMiles = sentence.slice(-33, -22);
let fromBegins = sentence.slice(28);
//OUTPUT
console.log(`Extracted word: ${wordGenius}`);
console.log(`Extracted word: ${wordMiles}`);
console.log(`Extracted from '99%' to the end: ${fromBegins}`);
<IPython.core.display.Javascript object>
Popcorn Hack 3
def remove_vowels(input_str):
vowels = "aeiouAEIOU"
result = ''.join([char for char in input_str if char not in vowels])
return result
sentence = "Yash Parikh"
print(remove_vowels(sentence))
Ysh Prkh
Popcorn Hack 4
#BONUS - I REMADE IT IN A DIFFERENT WAY
def reverse_word_order(sentence):
words = sentence.split()
reversed_words = words[::-1]
reversed_sentence = ' '.join(reversed_words)
return reversed_sentence
input_sentence = "Python programming is fun"
print(reverse_word_order(input_sentence))
fun is programming Python
Javascript Homework Hack
%%javascript
let firstName = prompt("Enter your first name:");
let lastName = prompt("Enter your last name:");
let greetingMessage = `Hello, ${firstName} ${lastName}!`;
console.log(greetingMessage);
<IPython.core.display.Javascript object>
Python Homework Hack
def is_palindrome(input_string):
cleaned_string = input_string.replace(" ", "").lower()
return cleaned_string == cleaned_string[::-1]
input_string = input("Enter a word or phrase to check if it's a palindrome: ")
if is_palindrome(input_string):
print("It's a palindrome!")
else:
print("It's not a palindrome.")
It's a palindrome!