Skip to the content.

3.10 Homework and Popcorn hacks

Popcorn Hacks

Hack #1

%%js


let aList = [];

while (true) {

    let userInput = prompt("Enter an item you want (or 'q' to quit):");

    if (userInput === 'q') {
        break;
    }

    aList.push(userInput);
}

console.log(aList)

Hack #2

%%js

let aList = []

while (true) {
    let userInput = prompt("Enter an item you want (or 'q' to quit):")

    if (user_input === 'q') {
        break;
    }

    aList.push(userInput)
}

console.log(aList[2])

Hack #3

myFavoriteFoods = ["Ribeye", "Alaskan Black Cod", "Filet Mignon", "Fish Tacos", "pizza"]

myFavoriteFoods.append("Cheesburgers")

myFavoriteFoods.append("Tri-tip sandwich")

print(myFavoriteFoods.length)

Hack #3 in Javascript (for bonus)

%%js

let myFavoriteFoods = ["Ribeye", "Alaskan Black Cod", "Filet Mignon", "Fish Tacos", "pizza"];

myFavoriteFoods.push("Cheesburgers");

myFavoriteFoods.push("Tri-tip sandwich");

console.log(myFavoriteFoods.length);

Hack #4

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

totalOfEvenNumbers = 0

for num in nums:

    if (num % 2 == 0): # checking if even
         
        totalOfEvenNumbers += num

Hack #4 in Javascript (for bonus)

%%js

const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

let totalOfEvenNumbers = 0;

for (const num of nums) {
    if (num % 2 === 0) { // checking if even
        totalOfEvenNumbers += num;
    }
}

Hack #5

fruits = ["apple", "banana", "orange"]
index = 0

for fruit in fruits:
    if (fruit == "banana"):
        print("there is a banana in index", index)
    index += 1
there is a banana in index  1

Hack #5 in Javascript (for bonus)

%%js

const fruits = ["apple", "banana", "orange"];
let index = 0;

for (const fruit of fruits) {
    if (fruit === "banana") {
        console.log("there is a banana in index", index);
    }
    index += 1;
}

Homework Hacks

Hack #1

# Create a list of numbers
numbers = [10, 20, 30, 40, 50]

# Print the second element in the list
print(numbers[1])  # Indexing starts from 0, so 1 refers to the second element

Hack #2

%%js

// Create an array of numbers
let numbers = [10, 20, 30, 40, 50];

// Log the second element in the array
console.log(numbers[1]);  // Indexing starts from 0, so 1 refers to the second element

Hack #3

# To-do list application

def show_menu():
    print("\n--- To-Do List Menu ---")
    print("1. View to-do list")
    print("2. Add item to to-do list")
    print("3. Remove item from to-do list")
    print("4. Exit")

def view_list(todo_list):
    if not todo_list:
        print("Your to-do list is empty.")
    else:
        print("\nYour to-do list:")
        for i, item in enumerate(todo_list, 1):
            print(f"{i}. {item}")

def add_item(todo_list):
    item = input("Enter the task you want to add: ")
    todo_list.append(item)
    print(f"'{item}' has been added to your to-do list.")

def remove_item(todo_list):
    view_list(todo_list)
    if todo_list:
        try:
            item_number = int(input("\nEnter the number of the task you want to remove: "))
            removed_item = todo_list.pop(item_number - 1)
            print(f"'{removed_item}' has been removed from your to-do list.")
        except (ValueError, IndexError):
            print("Invalid input. Please enter a valid number.")

def main():
    todo_list = []
    
    while True:
        show_menu()
        choice = input("\nEnter your choice (1-4): ")
        
        if choice == '1':
            view_list(todo_list)
        elif choice == '2':
            add_item(todo_list)
        elif choice == '3':
            remove_item(todo_list)
        elif choice == '4':
            print("Goodbye!")
            break
        else:
            print("Invalid choice. Please enter a number between 1 and 4.")

if __name__ == "__main__":
    main()

Hack #4

%%js

// Workout tracker application

let workoutLog = [];

function showMenu() {
    console.log("\n--- Workout Tracker Menu ---");
    console.log("1. View workout log");
    console.log("2. Add workout");
    console.log("3. Exit");
}

function viewWorkouts() {
    if (workoutLog.length === 0) {
        console.log("Your workout log is empty.");
    } else {
        console.log("\nYour workout log:");
        workoutLog.forEach((workout, index) => {
            console.log(`${index + 1}. Type: ${workout.type}, Duration: ${workout.duration} mins, Calories: ${workout.calories} kcal`);
        });
    }
}

function addWorkout() {
    const type = prompt("Enter the workout type (e.g., Running, Swimming, etc.):");
    const duration = parseFloat(prompt("Enter the duration of the workout in minutes:"));
    const calories = parseFloat(prompt("Enter the calories burned during the workout:"));

    if (isNaN(duration) || isNaN(calories)) {
        console.log("Invalid input. Please enter valid numbers for duration and calories.");
        return;
    }

    const workout = {
        type: type,
        duration: duration,
        calories: calories
    };

    workoutLog.push(workout);
    console.log("Workout added successfully!");
}

function main() {
    while (true) {
        showMenu();
        const choice = prompt("Enter your choice (1-3):");

        if (choice === '1') {
            viewWorkouts();
        } else if (choice === '2') {
            addWorkout();
        } else if (choice === '3') {
            console.log("Goodbye!");
            break;
        } else {
            console.log("Invalid choice. Please enter a number between 1 and 3.");
        }
    }
}

main();