3.1 and 3.4 Popcorn Hacks

Popcorn Hack 1
%%js

var myDictionary = {
    1: "banana",
    2: "apple",
    3: "mango"
};

console.log("Fruit with key 2:", myDictionary[2]); 
<IPython.core.display.Javascript object>
<IPython.core.display.Javascript object>
Popcorn Hack 2
import random

def play_game():
    score = 0
    operators = ['+', '-', '*',]

    print("Math Quiz Game")
    print("Answer as many questions as possible. Type 'q' to quit anytime.\n")

    while True:
        num1 = random.randint(1, 30)
        num2 = random.randint(1, 30)
        op = random.choice(operators)

        if 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"Your final score is {score}.")

play_game()
Math Quiz Game
Answer as many questions as possible. Type 'q' to quit anytime.

What is 15 + 3?
Correct!
What is 8 * 17?
Oops! The correct answer was 136.
What is 22 * 20?
Oops! The correct answer was 440.
What is 1 * 17?
Oops! The correct answer was 17.
What is 13 - 18?
Oops! The correct answer was -5.
What is 20 - 29?
Your final score is 1.
Popcorn Hack 3
%%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>
<IPython.core.display.Javascript object>
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
       

        elif conversion_type == "F":
            pass
        
        else:
            print("Invalid conversion type entered. Please enter 'C' or 'F'.")

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

temperature_converter()

Popcorn Hack 4
%%js


let favoriteMovie = "Joker";
let favoriteSport = "soccer";
let petName = "Chump";


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>
<IPython.core.display.Javascript object>
Popcorn Hack 5
%%js


let phrase = "My journey is outrageous and I love running";



let partOne = phrase.slice(2, 8);
let partTwo = phrase.slice(-18, -12);
let remainder = phrase.slice(20);



console.log(partOne);  
console.log(partTwo);  
console.log(remainder); 
<IPython.core.display.Javascript object>
Popcorn Hack 6
def remove_vowels(input_str):
    vowels = "aeiouAEIOU"
    result = ''.join([char for char in input_str if char not in vowels])
    return result

sentence = "Coding is so fun and I love it!"
print(remove_vowels(sentence))
Cdng s s fn nd  lv t!
Popcorn Hack 7
def reverse_words(input_str):
    words = input_str.split()
    reversed_words = " ".join(words[::-1])
    return reversed_words

sentence = "I love playing sports in the winter with friends!"
print(reverse_words(sentence))
friends! with winter the in sports playing love I
Homework Hack 1

shopping_list = []


total_cost = 0

while True:
 
    item_name = input("Enter the name of the item (or 'done' to finish): ")
    
    if item_name.lower() == 'done':
        break


    try:
        item_price = float(input(f"Enter the price of {item_name}: "))
    except ValueError:
        print("Please enter a valid price.")
        continue

   
    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:
gum: $4.00
shirt: $12.00
milk: $6.00
banana: $1.50

Total Cost: $23.50
Homework Hack 2
%%js
const cupsToTablespoons = 16;
const tablespoonsToTeaspoons = 3;
const cupsToTeaspoons = 48;

let ingredients = [];
let continueInput = true;

while (continueInput) {
    let ingredientName = prompt("Enter the name of the ingredient (or type 'done' to finish):");
    if (ingredientName.toLowerCase() === 'done') {
        continueInput = false;
        break;
    }
    
    let quantity = parseFloat(prompt(`Enter the quantity of ${ingredientName}:`));
    let unit = prompt(`Enter the current unit for ${ingredientName} (cups, tablespoons, teaspoons):`).toLowerCase();
    
    let desiredUnit = prompt("Enter the unit you want to convert to (tablespoons, teaspoons):").toLowerCase();

    let convertedQuantity = quantity;
    
    if (unit === 'cups' && desiredUnit === 'tablespoons') {
        convertedQuantity = quantity * cupsToTablespoons;
    } else if (unit === 'cups' && desiredUnit === 'teaspoons') {
        convertedQuantity = quantity * cupsToTeaspoons;
    } else if (unit === 'tablespoons' && desiredUnit === 'teaspoons') {
        convertedQuantity = quantity * tablespoonsToTeaspoons;
    } else if (unit === desiredUnit) {
        convertedQuantity = quantity;
    } else {
        alert("Invalid unit conversion. Try again.");
        continue;
    }
    
    ingredients.push({
        name: ingredientName,
        originalQuantity: quantity,
        originalUnit: unit,
        convertedQuantity: convertedQuantity,
        convertedUnit: desiredUnit
    });
}

if (ingredients.length > 0) {
    console.log("Recipe Ingredient Conversion Results:");
    ingredients.forEach(ingredient => {
        console.log(`${ingredient.name}: ${ingredient.originalQuantity} ${ingredient.originalUnit} = ${ingredient.convertedQuantity} ${ingredient.convertedUnit}`);
    });
} else {
    console.log("No ingredients entered.");
}
<IPython.core.display.Javascript object>
Homework Hack 3
%%js
let firstName = prompt("Zach");
let lastName = prompt("Peltz");


let greetingConcatenation = "Hello, " + firstName + " " + lastName + "!";
console.log(greetingConcatenation); 
<IPython.core.display.Javascript object>
Homework Hack 4
def is_palindrome(s):

    s = s.replace(" ", "").lower()
    

    return s == s[::-1]


input_string = input("Enter a word or phrase: ")


if is_palindrome(input_string):
    print(f"'{input_string}' is a palindrome!")
else:
    print(f"'{input_string}' is not a palindrome.")
'doc note i dissent a fast never prevents a fatness i diet on cod' is a palindrome!