Skip to the content.

3.10 (a) hacks

#POPCORN HACK 1

a_list = []

#append items to list
user_input = input("Enter an item to add to the list: ")
a_list.append(user_input)

#prompt for input
while True:
    user_input = input("Enter another item or type 'q' to quit: ")
    if user_input.lower() == 'q':
        break
    a_list.append(user_input)

# Print each item in the list
for item in a_list:
    print(item)

item 1
item 2
wow item 3
#POPCORN HACK 2

# Create an empty list
aList = []

# Keep taking user input and adding to the list until the user types 'done'
while True:
    item = input("Enter an item to add to the list (type 'done' to finish): ")
    if item.lower() == 'done':
        break
    aList.append(item)

# Display the second element if it exists
if len(aList) >= 2:
    print(f"Second element: {aList[1]}")
else:
    print("There is no second element in the list.")

# Delete the second element if it exists
if len(aList) >= 2:
    del aList[1]
    print("Second element deleted.")
else:
    print("No second element to delete.")

# Display the updated list
print("Updated list:", aList)

#POPCORN HACK 3

# Create a list of your five favorite foods
favorite_foods = ["Pizza", "Sushi", "Burgers", "Tacos", "Pasta"]

# Add two more items to the list using the .append() method
favorite_foods.append("Ice Cream")
favorite_foods.append("Salad")

# Find and print the total number of items in the list using len()
total_items = len(favorite_foods)
print(f"Total number of items in the list: {total_items}")

Total number of items in the list: 7
#POPCORN HACK 4

# Define a list of integers called nums
nums = [10, 15, 8, 23, 42, 17, 6]

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

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

# Print the sum of even numbers
print(f"The sum of all even numbers in the list is: {sum_of_evens}")
The sum of all even numbers in the list is: 66

BIG HACKS

#HOMEWORK 1

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

# Print the second element in the list
print(f"The second element in the list is: {numbers[1]}")
The second element in the list is: 20
%%js
//HOMEWORK 2

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

// Log the second element in the array to the console
console.log("The second element in the array is:", numbers[1]);

<IPython.core.display.Javascript object>
#HOMEWORK 3

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

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

def remove_item():
    """Remove an item from the to-do list."""
    item = input("Enter the item to remove: ")
    if item in todo_list:
        todo_list.remove(item)
        print(f"'{item}' has been removed from your to-do list.")
    else:
        print(f"'{item}' is not in your to-do list.")

def view_list():
    """View all items in the to-do list."""
    if todo_list:
        print("Your to-do list:")
        for index, item in enumerate(todo_list, 1):
            print(f"{index}. {item}")
    else:
        print("Your to-do list is empty.")

# Main loop to interact with the to-do list
while True:
    print("\nTo-Do List Menu:")
    print("1. Add item")
    print("2. Remove item")
    print("3. View list")
    print("4. Quit")
    
    choice = input("Choose an option (1-4): ")

    if choice == '1':
        add_item()
    elif choice == '2':
        remove_item()
    elif choice == '3':
        view_list()
    elif choice == '4':
        print("Goodbye!")
        break
    else:
        print("Invalid choice. Please select a valid option.")

To-Do List Menu:
1. Add item
2. Remove item
3. View list
4. Quit
'take out the trash' has been added to your to-do list.

To-Do List Menu:
1. Add item
2. Remove item
3. View list
4. Quit
Your to-do list:
1. take out the trash

To-Do List Menu:
1. Add item
2. Remove item
3. View list
4. Quit
Goodbye!
%%js
//HOMEWORK 4

// Initialize an empty array to store workouts
let workoutTracker = [];

// Function to add a workout
function addWorkout() {
    let type = prompt("Enter workout type (e.g., Running, Swimming, etc.):");
    let duration = prompt("Enter duration in minutes:");
    let calories = prompt("Enter calories burned:");

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

    workoutTracker.push(workout);
    console.log(`${type} workout added successfully.`);
}

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

// Function to start the workout tracker
function workoutMenu() {
    let userChoice;

    while (true) {
        userChoice = prompt(
            "Workout Tracker Menu:\n1. Add Workout\n2. View Workouts\n3. Quit\nChoose an option (1-3):"
        );

        if (userChoice === "1") {
            addWorkout();
        } else if (userChoice === "2") {
            viewWorkouts();
        } else if (userChoice === "3") {
            console.log("Goodbye! Keep up the great workouts!");
            break;
        } else {
            console.log("Invalid choice, please select a valid option.");
        }
    }
}

// Start the workout tracker
workoutMenu();