Skip to the content.

Group Lesson 2 Homework

Popcorn and Homework Hacks

Section 1 Homework

Popcorn Hacks

%%js

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

// Accessing a value
console.log("Fruit with key 2:", myDictionary[2]); // Output: fruit
<IPython.core.display.Javascript object>
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, 50)
        num2 = random.randint(1, 50)
        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 2 + 10?
Invalid input, please enter a number or 'q' to quit.
What is 1 + 10?
Thanks for playing! Your final score is 0.

# Function to convert temperatures
def temperature_converter():
    try:
        # Prompt the user for the temperature
        temperature = float(input("Enter the temperature: "))
        
        # Ask the user for the conversion type
        conversion_type = input("Convert to Celsius or Fahrenheit? ").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.")

# Call the temperature converter function
temperature_converter()
20.0°F is equal to -6.67°C
%%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>

Homework Hacks

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)
  total_cost += item_price

print("Total Cost:", total_cost)
print("What you bought:", shopping_list)
Total Cost: 3.0
What you bought: ['dog', 'cat']
cup = 48 #the conversion is in teaspoons for 1 cup
tablespoon = 3 #the conversion is in teaspoons for 1 tablespoon

while True:
    ingredient = input("Enter name of ingredient or type 'done' to quit:")

    if ingredient.lower() == "done":
        break

    quantity = int(input("Enter the quantity of the ingredient: "))
    unit = input("Enter the unit of the ingredient: ")

    if unit.strip().lower() == "cup":
        print(f"The number of teaspoons of {ingredient} is", quantity*cup)

    if unit.strip().lower() == "tablespoon":
        print(f"The number of teaspoons of {ingredient} is", quantity*tablespoon)
The number of teaspoons of cat is 96
The number of teaspoons of dog is 96

Lesson 3.4

Popcorn Hacks

%%js


let favoriteMovie = "No favorite";
let favoriteSport = "Basketball";
let favoriteFood = "Pasta";


// Concatenation
let concatenatedMessage = "My favorite movie is " + favoriteMovie + ". I love playing " + favoriteSport + " and my favorite food is " + favoriteFood + ".";


// Interpolation
let interpolatedMessage = `My favorite movie is ${favoriteMovie}. I love playing ${favoriteSport} and my favorite food is ${favoriteFood}.`;
<IPython.core.display.Javascript object>
%%js


// Define string
let phrase = "A journey of a thousand miles begins with a single step";


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


// Output
console.log(partOne);  // Output: journey
console.log(partTwo);  // Output: miles
console.log(remainder); // Output: begins with a single step
<IPython.core.display.Javascript object>
def remove_vowels(input_str):
    vowels = "aeiouAEIOU"
    result = ''.join([char for char in input_str if char not in vowels])
    return result

sentence = "Python enjoy learning I!"
print(remove_vowels(sentence))

Pythn njy lrnng !
def reverse_words(input_str):
    words = input_str.split()
    reversed_words = " ".join(words[::-1])
    return reversed_words

sentence = "This is not reversed!"
print(reverse_words(sentence))
reversed! not is This

Homework Hacks

%%js

let firstName = 'Nikhil';
let lastName = 'Maturi';

console.log(`Hello, ${firstName} ${lastName}`);
<IPython.core.display.Javascript object>
string = input("Enter something:")

inverted_string = []
for letter in string:
  inverted_string.append(letter)
result = ''.join(inverted_string[::-1])

if result == string:
  print("palindrome")
else:
  print("Not palindrome :(")
palindrome