Fall 2024 - P2
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
3.10.3 List Functions
Student led teaching on Lists. Learn how storage and manipulation of multiple items using indexing to access individual elements.
Find Max and Min Numbers in a List
This Python code defines a function to find the maximum and minimum numbers in a list.
- Function:
find_max_min(numbers)
takes a list and returns the max and min values. - Empty List Check: Returns
(None, None)
if the list is empty. - Initialization: Sets
max_num
andmin_num
to the first element. - Iteration: Loops through the list to update
max_num
andmin_num
. - Example Usage:
Example Code:
def find_max_min(numbers): # Check for empty list if not numbers: return (None, None) max_num = min_num = numbers[0] # Initialization # Iterate through the list for num in numbers: if num > max_num: max_num = num if num < min_num: min_num = num # Return the max and min values return max_num, min_num # Example usage numbers = [3, 1, 4, 1, 5, 9] max_num, min_num = find_max_min(numbers) print(f"\033[92mMax: {max_num}, Min: {min_num}\033[0m") # Bright green for output
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"Maximum number: {max_num}")
print(f"Minimum number: {min_num}")
Maximum number: 9
Minimum number: 1
Iteration Through Loops in Python
This code demonstrates how to iterate through a list using both a for
loop and a while
loop.
- For Loop: Iterates through each element in a list.
- While Loop: Continues until a condition is no longer met.
Example Code:
# List of numbers numbers = [1, 2, 3, 4, 5] # Using a for loop print("Using a for loop:") for num in numbers: print(num) # Using a while loop print("\nUsing a while loop:") index = 0 while index < len(numbers): print(numbers[index]) index += 1
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Using a for loop
print("Using a for loop:")
for num in numbers:
print(num)
# Using a while loop
print("\nUsing a while loop:")
index = 0
while index < len(numbers):
print(numbers[index])
index += 1
Using a for loop:
1
2
3
4
5
Using a while loop:
1
2
3
4
5
Another Example
# 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
And here is a cool Rock, Paper, Scissors Game hat uses iterations through the lists by using loops to find the right number.
import random
import ipywidgets as widgets
from IPython.display import display, clear_output, HTML
# Game choices
choices = ["rock", "paper", "scissors"]
# Function to determine the winner
def determine_winner(player, computer):
if player == computer:
return "It's a tie!"
elif (player == "rock" and computer == "scissors") or \
(player == "paper" and computer == "rock") or \
(player == "scissors" and computer == "paper"):
return "You win!"
else:
return "Computer wins!"
# Function to handle button clicks
def on_button_click(choice):
computer_choice = random.choice(choices)
result = determine_winner(choice, computer_choice)
# Clear previous output
clear_output(wait=True)
# Display choices and result with earthy theme
output_html = f"""
<div style="background-color: #4E3B31; color: #D9B68C; padding: 10px; border-radius: 5px; font-size: 14px;">
<p>You chose: <strong style="color: #4A7C2E;">{choice}</strong></p>
<p>Computer chose: <strong style="color: #4A7C2E;">{computer_choice}</strong></p>
<p>{result}</p>
</div>
"""
display(HTML(output_html))
# Create buttons for each choice
buttons = {choice: widgets.Button(description=choice.capitalize()) for choice in choices}
# Set up the button click event
for choice, button in buttons.items():
button.on_click(lambda b, choice=choice: on_button_click(choice))
# Display buttons
display(*buttons.values())
You chose: rock
Computer chose: paper
Computer wins!
Homework
Create a list of your favorite hobbies and use loops to run through each hobby. Here is a code starter to get your thoughts going.
hobbies = ["Reading", "Hiking", "Cooking", "Gaming", "Photography"]