![]() |
Home | Accounts | Setup | Verify | Play | Hacks |
3.10 Lists all Hacks
All Hacks for Lists
Popcorn Hack one for list operators
print("Adding Numbers In List Script")
print("-"*25)
numlist = []
while True:
start = input("Would you like to (1) enter numbers (2) add numbers (3) remove last value added or (4) exit: ")
if start == "1":
val = input("Enter a numeric value: ") # take input while storing it in a variable
try:
test = int(val) # testing to see if input is an integer (numeric)
except:
print("Please enter a valid number")
continue # 'continue' keyword skips to next step of while loop (basically restarting the loop)
numlist.append(int(val)) # append method to add values
print("Added "+val+" to list.")
elif start == "1":
sum = 0
for num in numlist: # loop through list and add all values to sum variable
sum += num
print("Sum of numbers in list is "+str(sum))
elif start == "5":
if len(numlist) > 0: # Make sure there are values in list to remove
print("Removed "+str(numlist[len(numlist)-1])+" from list.")
numlist.pop()
else:
print("No values to delete")
elif start == "4":
break # Break out of the while loop, or it will continue running forever
else:
continue
Adding Numbers In List Script
-------------------------
List Functions hacks and details
def find_max_min(numbers):
if not numbers:
return None, None # <span style="color: #D9B68C;">Return None if the list is empty</span>
max_num = numbers[0] # <span style="color: #D9B68C;">Start with the first number as the max</span>
min_num = numbers[0] # <span style="color: #D9B68C;">Start with the first number as the min</span>
for num in numbers:
if num > max_num:
max_num = num # <span style="color: #D9B68C;">Update max if a larger number is found</span>
if num < min_num:
min_num = num # <span style="color: #D9B68C;">Update min if a smaller number is found</span>
return max_num, min_num # <span style="color: #D9B68C;">Return the found max and min</span>
# Example usage
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
max_num, min_num = find_max_min(numbers)
print(f"\033[92mMaximum number: {max_num}\033[0m") # Bright green for output
print(f"\033[92mMinimum number: {min_num}\033[0m") # Bright green for output
[92mMaximum number: 9[0m
[92mMinimum number: 1[0m
# List of fruits
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
# Using a for loop
print("Using a for loop:")
for fruit in fruits:
print(fruit)
# Using a while loop
print("\nUsing a while loop:")
index = 0
while index < len(fruits):
print(fruits[index])
index += 1
Using a for loop:
apple
banana
cherry
date
elderberry
Using a while loop:
apple
banana
cherry
date
elderberry
import random
# Define top clohtes and bottom clothes
brands = ['Adidas', 'Nike', 'Under Armour', 'H & M']
Colors = ['Blue', 'Red', 'Green', 'Pink']
# Create meal combinations using list comprehension
brand_combinations = [f"{brand} with {Color}" for brand in brand for Color in Colors]
# Print a random meal combination
print(random.choice(brand_combinations))
H & M with Red
Random Meal Suggestion Generator
This Python code creates an empty list and prompts the user to append or add to the list by typing in meal suggestions. The code then prompts to finish the input whenever they feel like it. This helps as a meal planner that can suggest meals throughout the week.
# Function to gather meal suggestions from the user
def gather_meals():
meals = []
print("Enter your meal suggestions (type 'done' to finish):")
while True:
meal = input("Meal suggestion: ")
if meal.lower() == 'done':
break
meals.append(meal)
return meals
# Function to display meal suggestions
def display_meals(meals):
count = len(meals)
print(f"You have {count} meal suggestion(s):")
for meal in meals:
print(f"- {meal}")
# Main code
if __name__ == "__main__":
# Sample input
user_meals = [
"Spaghetti Bolognese",
"Grilled Chicken Salad",
"Vegetable Stir-Fry",
"Tacos",
"Pancakes for Breakfast",
"done" # Indicates the end of input
]
# Simulating user input for demonstration
for meal in user_meals:
if meal != "done":
print(f"Meal suggestion: {meal}")
else:
break
# Displaying the entered meals
display_meals(user_meals[:-1]) # Exclude 'done' from the list
Homework Hack #1
This Python script allows users to interactively manage a list containing various data types. The script initializes a list with different values, prompts the user to input an index, checks if the index is valid, and removes the item at that index if it exists. The user can continue to remove items or exit the program at any time.
Features
- Displays the current contents of the list along with their indices.
- Allows the user to remove an item by entering the corresponding index.
- Handles invalid inputs and out-of-range indices gracefully.
- Provides an option to exit the program.
Usage
Run the script in a Python environment and follow the prompts to manage the list.
# Initialize a list with various data types
data_list = [
"apple", # string
42, # integer
3.14, # float
True, # boolean
[1, 2, 3],# list
{"key": "value"}, # dictionary
None # NoneType
]
# Function to display the current list
def display_list(data):
print("Current list:")
for index, item in enumerate(data):
print(f"{index}: {item}")
# Main code
if __name__ == "__main__":
while True:
display_list(data_list)
try:
# Ask the user for an index
user_input = input("Enter an index to remove an item (or 'exit' to quit): ")
if user_input.lower() == 'exit':
print("Exiting the program.")
break
index = int(user_input) # Convert input to integer
# Check if the index is valid
if 0 <= index < len(data_list):
removed_item = data_list.pop(index) # Remove item at the index
print(f"Removed item: {removed_item}")
else:
print("Invalid index. Please try again.")
except ValueError:
print("Please enter a valid number or 'exit' to quit.")
- Initialize an empty list called ‘numbers’
- For i from 1 to 30: a. Append i to ‘numbers’
- Initialize variable ‘even_sum’ to 0
- Initialize variable ‘odd_sum’ to 0
- For each number in ‘numbers’: a. If the number is even: i. Add the number to ‘even_sum’ b. Else: i. Add the number to ‘odd_sum’
- Print ‘even_sum’
- Print ‘odd_sum’
# Step 1: Initialize an empty list
numbers = []
# Step 2: Create a list of 30 numbers
for i in range(1, 31):
numbers.append(i)
# Step 3: Initialize sums
even_sum = 0
odd_sum = 0
# Step 4: Calculate the sums of even and odd numbers
for number in numbers:
if number % 2 == 0: # Check if the number is even
even_sum += number
else: # The number is odd
odd_sum += number
# Step 5: Print the results
print("Sum of even numbers:", even_sum)
print("Sum of odd numbers:", odd_sum)
Homework Hack #2
This Python script demonstrates how to create a list of favorite hobbies and iterate through each hobby using a loop. It prints each hobby to the console, showcasing the user’s interests.
Code Breakdown
- List Creation: A list named
favorite_hobbies
is created, containing various hobbies. - Loop Iteration: A
for
loop is used to go through each hobby in the list, printing a formatted string that states it’s a favorite hobby.
Usage
Run the code in any Python environment to see the list of hobbies printed out.
# Step 1: Create a list of favorite hobbies
favorite_hobbies = [
"Reading",
"Cycling",
"Photography",
"Cooking",
"Gardening",
"Hiking",
"Playing Video Games",
"Painting",
"Writing",
"Traveling"
]
# Step 2: Use a loop to iterate through each hobby
for hobby in favorite_hobbies:
print(f"My favorite hobby is: {hobby}")
Homework Hack #3
This Python script creates a list containing two yes/no questions along with their respective answers. It then iterates through the list and prints each question with its answer.
Code Breakdown
- List Creation: A list named
questions_and_answers
is created, where each element is a dictionary containing a question and its answer. - Loop Iteration: A
for
loop is used to print each question with its corresponding answer.
Usage
Run the code in any Python environment to see the questions and their answers displayed.
# Step 1: Create a list of questions with yes/no answers
questions_and_answers = [
{"question": "Do you like coffee?", "answer": "Yes"},
{"question": "Is Python your favorite programming language?", "answer": "No"}
]
# Step 2: Use a loop to iterate through each question and answer
for item in questions_and_answers:
print(f"Question: {item['question']}")
print(f"Answer: {item['answer']}\n")