Homework and Popcorn Hacks for Lessons 3.10
Lists
List Operations: Actions you can perform on lists, like adding, removing, or accessing elements. Pseudocode: A simplified way to outline a program's logic using plain language. List Functions: Built-in methods used to modify or retrieve information from lists List Inputs: Ways to add data to a list, such as user input
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 == "2":
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 == "3":
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
In python I made it so it allows users to interact with a list of numbers, with options to add numbers, calculate the sum, remove the last number, or exit. Runs an infinite while loop, allowing users to choose from four options: Enter a numeric value and add it to the list, add up all the numbers in the list and display the sum, remove the last number added to the list, exit .
Pseudocode
nums ← 1 to 100 odd_sum ← 0
FOR EACH score IN nums IF score MOD 2 ≠ 0 THEN odd_sum ← odd_sum + score END IF END FOR
DISPLAY (“Sum of odd numbers in the list:”, odd_sum)
nums = range(1, 101) # This creates a range of numbers from 1 to 100
odd_sum = 0
for score in nums:
if score % 2 != 0:
odd_sum += score
print("Sum of odd numbers in the list:", odd_sum)
Calculates the sum of all odd numbers in the range from 1 to 100. The odd_sum is initialized to 0. This will hold the sum of odd numbers. The for loop iterates through each number (score) in the nums range. Inside the loop, the condition if score % 2 != 0 checks if the number is odd. If it is, the number is added to odd_sum.
def gather_tasks():
tasks = []
print("Enter your tasks (type 'done' to finish):")
while True:
task = input("Task: ")
if task.lower() == 'done':
break
tasks.append(task)
return tasks
# Function to display tasks
def display_tasks(tasks):
count = len(tasks)
print(f"You have {count} task(s) on your list:") # No color
for task in tasks:
print(f"- {task}") # No color
# Main code
if __name__ == "__main__":
user_tasks = gather_tasks()
display_tasks(user_tasks)
User inputs a list of tasks and then displays them. The gather_tasks() statement, prompts the user to enter tasks one by one. The loop continues until the user types “done”. Each task is added to the tasks list. Once the user finishes, the function returns the list of tasks.
# Initial list
my_list = [1, 2, 3, 5]
# 1. Assign a value to a specific element
my_list[3] = 4 # Change the 4th element (index 3) from 5 to 4
print("After assigning value:", my_list) # Output: [1, 2, 3, 4]
# 2. Insert an element at a specific position
my_list.insert(1, 10) # Insert 10 at index 1
print("After inserting element:", my_list) # Output: [1, 10, 2, 3, 4]
# 3. Append a new element at the end
my_list.append(6) # Append 6 to the list
print("After appending element:", my_list) # Output: [1, 10, 2, 3, 4, 6]
# 4. Remove a specific element
my_list.remove(10) # Remove the value 10 from the list
print("After removing element:", my_list) # Output: [1, 2, 3, 4, 6]
# 5. Calculate the length of the list
list_length = len(my_list)
print("Length of the list:", list_length) # Output: 5
Demonstrates various ways to modify a list updating an element, inserting a new one, appending to the end, removing an item, and calculating the list’s length.
# Function to find the maximum and minimum numbers in a list
def find_max_and_min(number_list):
# Initialize variables to the first element of the list
max_value = number_list[0]
min_value = number_list[0]
# Iterate through the list
for number in number_list:
if number > max_value:
max_value = number
if number < min_value:
min_value = number
# Return both max and min values
return max_value, min_value
# Example list of numbers
number_list = [3, 5, 1, 9, 2]
# Call the function and display the results
max_number, min_number = find_max_and_min(number_list)
print("Maximum:", max_number) # Output: Maximum: 9
print("Minimum:", min_number) # Output: Minimum: 1
In Python, I defined a function find_max_and_min() to find the maximum and minimum values in a list of numbers.
# Function to accept user input and populate a list
def populate_list():
# Create an empty list to store user input
user_list = []
# Ask the user how many elements they want to add
num_elements = int(input("How many elements do you want to add? "))
# Accept inputs from the user to populate the list
for i in range(num_elements):
element = input(f"Enter element {i + 1}: ")
user_list.append(element) # Append each input to the list
return user_list
# Function to explore attributes/values of list elements
def explore_attributes(user_list):
print("\nList Elements and Their Attributes:")
for i, element in enumerate(user_list):
print(f"Element {i + 1}: '{element}', Type: {type(element)}")
if isinstance(element, str):
print(f" - Length of string: {len(element)}")
elif isinstance(element, int) or isinstance(element, float):
print(f" - Value: {element}")
print() # Blank line for readability
# Main program
if __name__ == "__main__":
user_list = populate_list()
explore_attributes(user_list)
A way to gather input from the user, store it in a list, and then examine the attributes of the list’s elements. The program prompts the user to input the number of elements they wish to add to the list and then collects the elements. It then prints each element along with its type (str, int, etc.), and for strings, it prints the length. For integers and floats, it simply displays their values.
# Function to populate the list with user input
def populate_list():
user_list = [] # Initialize an empty list
while True:
element = input("Enter a number to add to the list (or type 'done' to finish): ")
if element.lower() == 'done':
break # Exit the loop when the user is done adding numbers
try:
# Convert the input to a float or integer and append to the list
user_list.append(float(element))
except ValueError:
print("Please enter a valid number or 'done' to stop.")
return user_list
# Function to calculate and print the sum of all numbers in the list
def calculate_sum(user_list):
total_sum = sum(user_list) # Calculate the sum of all elements in the list
print(f"\nSum of numbers in the list: {total_sum}")
# Function to allow removing the last element using the .pop() method
def remove_last_element(user_list):
if user_list:
removed_element = user_list.pop() # Remove the last element
print(f"\nRemoved the last element: {removed_element}")
print(f"Updated list: {user_list}")
else:
print("\nThe list is already empty, nothing to remove.")
# Main program
if __name__ == "__main__":
# Step 1: Populate the list with user input
user_list = populate_list()
# Step 2: Calculate and print the sum of all numbers in the list
calculate_sum(user_list)
# Step 3: Allow user to remove the last element
while True:
remove = input("\nWould you like to remove the last element? (yes/no): ").lower()
if remove == 'yes':
remove_last_element(user_list)
else:
break
Collects the numbers and calculates their sum. It allows the user to remove the last element in the list and prints the updated list after each removal. The loop ends when the user decides not to remove any more elements.
Pseudocode
Step 1: Create a list of numbers from 1 to 100
Create a list called number_list containing numbers from 1 to 100.
Step 2: Initialize sum variable
Set sum_of_evens to 0.
Step 3: Iterate through each number in the list
FOR each number in number_list: IF number MOD 2 == 0: # Step 4: Add even numbers to the sum Add number to sum_of_evens. END IF END FOR
Step 5: Display the sum of even numbers
Display sum_of_evens.
import random # Import the random module
# Step 1: Create an empty list to store meal suggestions
meal_suggestions = []
# Step 2: Prompt the user to enter meal suggestions
while True:
meal = input("Enter a meal suggestion (or type 'done' to finish): ")
if meal.lower() == 'done': # Check if the user wants to stop
break
else:
meal_suggestions.append(meal) # Add the meal suggestion to the list
# Step 3: Randomly select a meal from the list
if meal_suggestions: # Ensure the list is not empty
selected_meal = random.choice(meal_suggestions) # Pick a random meal
# Step 4: Display the selected meal
print(f"How about this meal for today? {selected_meal}")
else:
print("No meal suggestions were entered.")
The script collects meal suggestions from the user, then randomly picks one and displays it. The user can keep adding meals and choose to stop at any time by typing ‘done’. If no suggestions are entered, the system notifies the user.