Nighthawk Pages

Homeworks and Popcorn Hacks for Lessons

All homeworks for Lessons

Popcorn Hacks for 3.1

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:
        num1 = random.randint(1, 20)
        num2 = random.randint(1, 20)
        op = random.choice(operators)
        
        if op == '+':
            answer = num1 + num2
        elif 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("Wrong! Please enter a number or 'q' to quit.")

    print(f"Goodbye! 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 20 - 8?
Correct!
What is 14 / 2?
Correct!
What is 2 / 8?
Oops! The correct answer was 0.25.
What is 9 + 8?
Correct!
What is 2 + 20?
Oops! The correct answer was 22.
What is 1 / 15?
Goodbye! Your final score is 3.
%%javascript

var myDictionary = {
    1: "cherry",
    2: "grapes",
    3: "blueberry"
};

console.log("Fruit with key 2:", myDictionary[2]); 

<IPython.core.display.Javascript object>
%%javascript

function convertTemperature() {
    let temperature = parseFloat(prompt("Enter the temperature:"));
    let conversionType = prompt("Choose the conversion type: 'C to F' or 'F to C'").toLowerCase();
    
    let convertedTemp;
    if (conversionType === "c to f") {
        convertedTemp = (temperature * 9/5) + 32;
        console.log(`${temperature}°C is ${convertedTemp.toFixed(2)}°F`);
    } else if (conversionType === "f to c") {
        convertedTemp = (temperature - 32) * 5/9;
        console.log(`${temperature}°F is ${convertedTemp.toFixed(2)}°C`);
    } else {
        console.log("Invalid conversion type");
    }
}

convertTemperature();
UsageError: Cell magic `%%` not found.
def convert_temperature():
    temperature = float(input("Enter the temperature: "))
    conversion_type = input("Choose the conversion type: 'C to F' or 'F to C': ").lower()
    
    if conversion_type == "c to f":
        converted_temp = (temperature * 9/5) + 32
        print(f"{temperature}°C is {converted_temp:.2f}°F")
    elif conversion_type == "f to c":
        converted_temp = (temperature - 32) * 5/9
        print(f"{temperature}°F is {converted_temp:.2f}°C")
    else:
        print("Invalid conversion type")

convert_temperature()
Invalid conversion type

Popcorn Hacks for 3.4

%javascript

let favoriteMovie = "The Grinch";
let favoriteSport = "basketball";
let petName = "Coco";


let concatenatedMessage = "My favorite sport is " + favoriteSport + ". I love my dog " + petName + ".";


let interpolatedMessage = `My favorite sport is ${favoriteSport} and my dog is ${petName}.`;


console.log(concatenatedMessage);
console.log(interpolatedMessage);
  Cell In[31], line 3
    let favoriteMovie = "The Grinch";
        ^
SyntaxError: invalid syntax
%%js



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


let partOne = phrase.slice(2, 9);       // Extracts "journey"
let partTwo = phrase.slice(-26, -20);   // Extracts "miles" using negative index
let remainder = phrase.slice(31);       // Extracts from "begins" to the end

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_myname(input_str):
    name = "prajnaPRAJNA"
    result = ''.join([char for char in input_str if char not in name])
    return result

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

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

sentence = "My favorite pets are cats"
print(reverse_words(sentence))


I eoy leig ytho!
cats are pets favorite My
shopping_list = []
total_cost = 0

while True:
    item_name = input("Enter the name of grocery(or type 'done' to finish): ")
    
    if item_name.lower() == 'done':
        break
    
    try:
        item_price = float(input(f"What is the price of {item_name}: $"))
    except ValueError:
        print("Invalid price. Enter a valid number.")
        continue
    
    shopping_list.append({"name": item_name, "price": item_price})
    
    total_cost += item_price

print("\nYour Shopping List:")
for item in shopping_list:
    print(f"{item['name']}: ${item['price']:.2f}")

print(f"\nTotal cost: ${total_cost:.2f}")

Invalid price. Enter a valid number.

Your Shopping List:
tomatoes: $2.00
potato: $4.00

Total cost: $6.00

Homework for 3.1

%%javascript


const conversionRates = {
    cup_to_tablespoons: 16,
    tablespoon_to_teaspoons: 3,
    cup_to_teaspoons: 48
};


let ingredients = [];

while (true) {
    let ingredientName = prompt("Enter the name of the ingredient (or type 'done' to finish):");
    
    if (ingredientName.toLowerCase() === "done") {
        break;
    }
    
    let quantity = parseFloat(prompt(`Enter the quantity for ${ingredientName}:`));
    if (isNaN(quantity)) {
        alert("Invalid quantity. Please enter a number.");
        continue;
    }
    
    let currentUnit = prompt("Enter the current unit (cups, tablespoons, teaspoons):").toLowerCase();
    if (["cups", "tablespoons", "teaspoons"].indexOf(currentUnit) === -1) {
        alert("Invalid unit. Please enter 'cups', 'tablespoons', or 'teaspoons'.");
        continue;
    }
    
    let desiredUnit = prompt("Enter the desired unit to convert to (cups, tablespoons, teaspoons):").toLowerCase();
    if (["cups", "tablespoons", "teaspoons"].indexOf(desiredUnit) === -1) {
        alert("Invalid unit. Please enter 'cups', 'tablespoons', or 'teaspoons'.");
        continue;
    }
    
    
    let convertedQuantity;
    
    if (currentUnit === "cups") {
        if (desiredUnit === "tablespoons") {
            convertedQuantity = quantity * conversionRates.cup_to_tablespoons;
        } else if (desiredUnit === "teaspoons") {
            convertedQuantity = quantity * conversionRates.cup_to_teaspoons;
        } else {
            convertedQuantity = quantity; 
        }
    } else if (currentUnit === "tablespoons") {
        if (desiredUnit === "cups") {
            convertedQuantity = quantity / conversionRates.cup_to_tablespoons;
        } else if (desiredUnit === "teaspoons") {
            convertedQuantity = quantity * conversionRates.tablespoon_to_teaspoons;
        } else {
            convertedQuantity = quantity; 
        }
    } else if (currentUnit === "teaspoons") {
        if (desiredUnit === "cups") {
            convertedQuantity = quantity / conversionRates.cup_to_teaspoons;
        } else if (desiredUnit === "tablespoons") {
            convertedQuantity = quantity / conversionRates.tablespoon_to_teaspoons;
        } else {
            convertedQuantity = quantity;  
        }
    }
    
   
    ingredients.push({
        name: ingredientName,
        originalQuantity: quantity,
        originalUnit: currentUnit,
        convertedQuantity: convertedQuantity,
        convertedUnit: desiredUnit
    });
}


console.log("\nConverted Ingredients:");
ingredients.forEach(ingredient => {
    console.log(`${ingredient.name}: ${ingredient.originalQuantity} ${ingredient.originalUnit} = ${ingredient.convertedQuantity.toFixed(2)} ${ingredient.convertedUnit}`);
});
<IPython.core.display.Javascript object>

Homework for 3.4

%%javascript

let firstName = "Prajna";
let lastName = "Raj";

let greetingConcatenation = "Hello, I'm " + firstName + " " + lastName + "!";
console.log(greetingConcatenation); 

<IPython.core.display.Javascript object>
def is_palindrome(input_string):
    cleaned_string = input_string.replace(" ", "").lower()
    if cleaned_string == cleaned_string[::-1]:
        return True
    else:
        return False


user_input = input("Enter a word or phrase: ")
if is_palindrome(user_input):
    print(f"'{user_input}' is a palindrome!")
else:
    print(f"'{user_input}' is not a palindrome.")

'racecar' is a palindrome!
Scroll to top