Skip to the content.

Homework and Popcorn Hacks for 3.1 & 3.4

Homework for 3.4 teachings

Popcorn Hack #1

%%js


let favoriteMovie = "Cars";
let favoriteSport = "Soccer";
let petName = "monkey";


let concatenatedMessage = "My favorite movie is " + favoriteMovie + ". I love playing " + favoriteSport + " and my pet's name is " + petName + ".";


let interpolatedMessage = `My favorite movie is ${favoriteMovie}. I love playing ${favoriteSport} and my pet's name is ${petName}.`;
<IPython.core.display.Javascript object>

Popcorn Hack #2

%%js


let phrase = "siuuuuuuuuuuuuuuuuuuuuuuuuuu";


let partOne = phrase.slice(1, 6);
let partTwo = phrase.slice(-15, -20);
let remainder = phrase.slice(22);


console.log(partOne);  // Output: journey
console.log(partTwo);  // Output: miles
console.log(remainder); // Output: begins with a single step
<IPython.core.display.Javascript object>

Popcorn Hack #3

def name_vowels(input_str):
    vowels = "i"
    result = ''.join([char for char in input_str if char not in vowels])
    return result

sentence = "Python is confusing"
print(name_vowels(sentence))

Python s confusng
def reverse_words(input_str):
    words = input_str.split()
    reversed_words = " ".join(words[::-1])
    return reversed_words

sentence = "hello world"
print(reverse_words(sentence))
world hello

Python Shopping lists

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("\nShopping List:")
for item, price in shopping_list:
    print(f"{item}: ${price:.2f}")
print(f"Total cost: ${total_cost:.2f}")

Shopping List:
chicken: $12.00
eggs: $10.00
milk: $8.00
bread: $9.00
Total cost: $39.00

JavaScript: Recipe Ingredient Converter

%%js

const conversionRates = {
    cupsToTablespoons: 16,
    tablespoonsToTeaspoons: 3,
    cupsToTeaspoons: 48
};

let ingredients = [];

while (true) {
    let ingredient = prompt("Enter the ingredient name (or 'done' to finish):");
    if (ingredient.toLowerCase() === 'done') break;

    let quantity = parseFloat(prompt("Enter the quantity of the ingredient:"));
    let unit = prompt("Enter the unit (cups, tablespoons, teaspoons):");
    let targetUnit = prompt("Enter the unit to convert to (tablespoons, teaspoons):");

    let convertedQuantity;
    if (unit === "cups" && targetUnit === "tablespoons") {
        convertedQuantity = quantity * conversionRates.cupsToTablespoons;
    } else if (unit === "cups" && targetUnit === "teaspoons") {
        convertedQuantity = quantity * conversionRates.cupsToTeaspoons;
    } else if (unit === "tablespoons" && targetUnit === "teaspoons") {
        convertedQuantity = quantity * conversionRates.tablespoonsToTeaspoons;
    } else {
        alert("Invalid conversion units.");
        continue;
    }

    ingredients.push({ ingredient, quantity, unit, convertedQuantity, targetUnit });
}

ingredients.forEach(item => {
    console.log(`${item.quantity} ${item.unit} of ${item.ingredient} = ${item.convertedQuantity} ${item.targetUnit}`);
});

<IPython.core.display.Javascript object>

3.1 hw and popcorn hacks

Popcorn Hack 1

%%js


// Create a dictionary (object) in JavaScript
var myDictionary = {
    1: "1",
    2: "2",
    3: "3"
};

// Accessing a value
console.log("1 with key 2:", myDictionary[2]); // Output: fruit
<IPython.core.display.Javascript object>

Pocorn 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(5, 50)
        num2 = random.randint(5, 50)
        op = random.choice(operators)

        # Calculate the correct answer based on the operator
        if 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 12 / 13?
Oops! The correct answer was 156.
What is 13 * 17?
Oops! The correct answer was 221.
What is 39 + 5?
Oops! The correct answer was 44.
What is 39 + 33?
Thanks for playing! Your final score is 0.

Popcorn Hack 3

%%js

// 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.");
}
<IPython.core.display.Javascript object>
def temperature_converter():
    try:
        temperature = float(input("Enter the temperature: "))
        conversion_type = input("Convert to Celsius (C) or Fahrenheit (F)? ").strip().upper()

        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'.")

    except ValueError:
        print("Invalid input. Please enter a numeric temperature value.")

temperature_converter()
55.0°C is equal to 131.00°F