3.10 Hacks
Python/Javascript Popcorn and HW hacks
3.10.1 Popcorn Hack
// Create an empty array
let aList = [];
// Input items into the array
let userInput = prompt("Enter an item (type 'done' to finish):");
while (userInput.toLowerCase() !== 'done') {
aList.push(userInput);
userInput = prompt("Enter another item (or type 'done' to finish):");
}
// Use a for loop to print each item in the array
console.log("Items in the list:");
for (let i = 0; i < aList.length; i++) {
console.log(aList[i]);
}
3.10.2 Popcorn Hacks
// Create an array with some items
let aList = ["apple", "banana", "cherry", "date"];
// Display the second element (if it exists)
if (aList.length >= 2) {
console.log("Second element:", aList[1]);
} else {
console.log("The list has fewer than 2 items.");
}
// Delete the second element (if it exists)
if (aList.length >= 2) {
aList.splice(1, 1); // Removes the second element
}
// Display the updated list
console.log("Updated list:", aList);
3.10.3 Popcorn Hacks
# Create a list of favorite foods
favorite_foods = ["pizza", "sushi", "ice cream", "pasta", "tacos"]
# Add two more items to the list
favorite_foods.append("burgers")
favorite_foods.append("salad")
# Print the list
print("Favorite foods:", favorite_foods)
# Find and print the total number of items in the list
print("Total number of items:", len(favorite_foods))
3.10.4 Popcorn Hacks
# Define the list of integers
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Define a variable to store the sum of even numbers
even_sum = 0
# Iterate through the list and add even numbers to the sum
for num in nums:
if num % 2 == 0: # Check if the number is even
even_sum += num
# Print the sum of all even numbers
print("Sum of even numbers:", even_sum)
3.10.4 Popcorn Hack
# Define the list of fruits
fruits = ["apple", "banana", "cherry", "date"]
# Check if "banana" is in the list
if "banana" in fruits:
print("Banana is in the list.")
else:
print("Banana is not in the list.")
3.10 Homework Hacks
# Create a list of numbers
numbers = [10, 20, 30, 40, 50]
# Print the second element in the list
print("The second element in the list is:", numbers[1])
// 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]);
def display_menu():
print("\nTo-Do List Menu:")
print("1. Add an item")
print("2. Remove an item")
print("3. View items")
print("4. Quit")
# Initialize the to-do list
todo_list = []
while True:
display_menu()
choice = input("Choose an option (1-4): ")
if choice == '1': # Add an item
item = input("Enter the item to add: ")
todo_list.append(item)
print(f"'{item}' has been added to the list.")
elif choice == '2': # Remove an item
item = input("Enter the item to remove: ")
if item in todo_list:
todo_list.remove(item)
print(f"'{item}' has been removed from the list.")
else:
print(f"'{item}' is not in the list.")
elif choice == '3': # View items
if todo_list:
print("\nYour To-Do List:")
for idx, item in enumerate(todo_list, start=1):
print(f"{idx}. {item}")
else:
print("Your to-do list is empty.")
elif choice == '4': # Quit
print("Goodbye!")
break
else:
print("Invalid option, please try again.")
// Initialize the workout log
let workoutLog = [];
// Function to display the menu
function displayMenu() {
console.log("\nWorkout Tracker Menu:");
console.log("1. Log a workout");
console.log("2. View logged workouts");
console.log("3. Quit");
}
// Function to log a workout
function logWorkout() {
const type = prompt("Enter workout type (e.g., running, cycling):");
const duration = prompt("Enter duration (in minutes):");
const calories = prompt("Enter calories burned:");
const workout = {
type: type,
duration: parseInt(duration), // Convert duration to a number
calories: parseInt(calories) // Convert calories to a number
};
workoutLog.push(workout);
console.log(`Workout logged: ${type}, Duration: ${duration} mins, Calories burned: ${calories}`);
}
// Function to view logged workouts
function viewWorkouts() {
if (workoutLog.length === 0) {
console.log("No workouts logged yet.");
return;
}
console.log("\nLogged Workouts:");
workoutLog.forEach((workout, index) => {
console.log(`${index + 1}. Type: ${workout.type}, Duration: ${workout.duration} mins, Calories burned: ${workout.calories}`);
});
}
// Main program loop
while (true) {
displayMenu();
const choice = prompt("Choose an option (1-3):");
if (choice === '1') {
logWorkout();
} else if (choice === '2') {
viewWorkouts();
} else if (choice === '3') {
console.log("Goodbye!");
break;
} else {
console.log("Invalid option, please try again.");
}
}