Skip to the content.

Homeworks 3.10A

Popcorn Hack: 3.10.1 Hack 1 Javascript

Use a_list.append(user_input) to append each item.

Use a for loop to print out each item in the list at the end.

Exercise: Build a Shopping List with JavaScript

In this exercise, you will create a simple shopping list application that allows users to add items to a list and display them at the end.

%%js  
// Create an empty array to hold the shopping list
let aList = [];

// Add predefined items to the list
aList.push("strawberries");
aList.push("table");
aList.push("milk");
aList.push("bread");

// Function to display the entire shopping list
function showList() {
    if (aList.length > 0) {
        console.log("Your shopping list contains:");
        for (let i = 0; i < aList.length; i++) {
            console.log((i + 1) + ". " + aList[i]);  // Display the list items
        }
    } else {
        console.log("Your shopping list is empty.");
    }
}

// Display the list after adding items
showList();

<IPython.core.display.Javascript object>

Popcorn Hack 2 Python: Accessing and Deleting Elements

Create a list/array named aList.

Input items into the list/array. After the user is done adding items, display the second element (if it exists) in the list/array.

After adding items to the list/array, delete the second element (if it exists) and display the updated list/array.

# Create a list with some random elements
a_list = ["apple", "banana", "grape", "car", "pencil"]

# Display the second element if it exists
if len(a_list) > 1:
    print("Second element:", a_list[1])
else:
    print("There is no second element in the list.")

# Delete the second element if it exists and display the updated list
if len(a_list) > 1:
    del a_list[1]
    print("Updated list after deleting the second element:", a_list)
else:
    print("No second element to delete. Here's the list:", a_list)

Second element: banana
Updated list after deleting the second element: ['apple', 'grape', 'car', 'pencil']

Popcorn Hack 3 Javascript: Assigning Values to a List and Finding Its Length

Create a list of your five favorite foods.

Add two more items to your list using the .push() method.

Find and print the total number of items in the list using .length

%%js
// Create a list of five favorite foods
let favoriteFoods = ["pizza", "sushi", "pasta", "ice cream", "burger"];

// Add two more items using .push()
favoriteFoods.push("tacos");
favoriteFoods.push("salad");

// Find and print the total number of items in the list using .length
let totalItems = favoriteFoods.length;
console.log("Total number of favorite foods: " + totalItems);

<IPython.core.display.Javascript object>

Popcorn Hack 4 Python : Find the sum of all the even numbers of a list called nums with integers using the previous list opperations.Define your list and define a variable to represent a potential value.

# Define the list of integers
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Initialize a variable to store the sum of even numbers
sum_of_evens = 0

# Iterate through the list to find even numbers and sum them
for num in nums:
    if num % 2 == 0:  # Check if the number is even
        sum_of_evens += num  # Add the even number to the sum

# Print the result
print("The sum of all even numbers in the list is:", sum_of_evens)

The sum of all even numbers in the list is: 30

Popcorn Hack 5 Javascript : Look for the element “banana” in the list “fruits” using If Else Statements

%%js
// Define the list of fruits
let fruits = ["apple", "orange", "banana", "grape", "kiwi"];

// Check if "banana" is in the fruits array
if (fruits.includes("banana")) {
    console.log("Banana is in the list!");
} else {
    console.log("Banana is not in the list.");
}

<IPython.core.display.Javascript object>

Homework Hack 1: Write a Python program that creates a list of the following numbers: 10, 20, 30, 40, 50. Then, print the second element in the list.

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

# Print the second element in the list
print(numbers[1])  # Index 1 corresponds to the second element

20

Homework Hack 2: Write a JavaScript program that creates an array of the following numbers: 10, 20, 30, 40, 50. Then, log the second element in the array to the console.

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

// Log the second element in the array to the console
console.log(numbers[1]); // Index 1 corresponds to the second element

<IPython.core.display.Javascript object>

Homework Hack 3: Python: Create a to-do list in whcih users can add, remove, and view items in their list.

# Initialize an empty to-do list
todo_list = []

# Function to display the to-do list
def display_list():
    if not todo_list:
        print("Your To-Do List is currently empty.")
    else:
        print("Your To-Do List:")
        for index, item in enumerate(todo_list, start=1):
            print(f"{index}. {item}")
    print()  # For better readability

# Main program loop
while True:
    # Display options for the user
    print("Options: (1) Add Item, (2) Remove Item, (3) View List, (4) Quit")
    choice = input("Please select an option: ")

    if choice == '1':  # Add item
        item = input("Enter the item to add: ")
        todo_list.append(item)
        print(f"'{item}' added to the list!\n")

    elif choice == '2':  # Remove item
        display_list()
        try:
            index = int(input("Enter the number of the item to remove: ")) - 1
            removed_item = todo_list.pop(index)
            print(f"'{removed_item}' removed from the list!\n")
        except (IndexError, ValueError):
            print("Invalid number. Please try again.\n")

    elif choice == '3':  # View list
        display_list()

    elif choice == '4':  # Quit
        print("Goodbye!")
        break

    else:
        print("Invalid option. Please choose a valid number (1-4).\n")

Options: (1) Add Item, (2) Remove Item, (3) View List, (4) Quit
'2' added to the list!

Options: (1) Add Item, (2) Remove Item, (3) View List, (4) Quit
Your To-Do List:
1. 2

Options: (1) Add Item, (2) Remove Item, (3) View List, (4) Quit
Goodbye!

Homework Hack 4: JavaScript: Create a workout tracker where users can log their workouts, including type, duration, and calories burned.

%%js 
// Initialize an empty workout log array
let workoutLog = [];

// Function to log a workout
function logWorkout(type, duration, caloriesBurned) {
    let workout = {
        type: type,
        duration: duration, // duration in minutes
        calories: caloriesBurned // calories burned
    };
    workoutLog.push(workout);
    console.log(`${type} workout of ${duration} minutes and ${caloriesBurned} calories burned added to the log.`);
}

// Function to display all workouts
function displayWorkouts() {
    if (workoutLog.length === 0) {
        console.log("No workouts logged yet.");
    } else {
        console.log("Workout Log:");
        workoutLog.forEach((workout, index) => {
            console.log(`${index + 1}. Type: ${workout.type}, Duration: ${workout.duration} minutes, Calories Burned: ${workout.calories}`);
        });
    }
}

// Example usage
logWorkout("Running", 45, 400);
logWorkout("Cycling", 60, 500);
logWorkout("Yoga", 30, 150);

displayWorkouts();

<IPython.core.display.Javascript object>