Practice 6 — for loops
Skills: 4
Reading: the Notes section of Class 22
Working with for Loops
To define our own list processing functions, we need a way to do computations for each element in the list. We'll use iteration with for loops.
This requires being able to change the value of variables, which PLL allows inside functions at #level intermediate (so that should be the first line of your file).
Pattern is:
def my_function(my_list: list) -> ...:
my_var = initial_value
for my_elt in my_list:
# CODE IMPLEMENTATION HERE
return my_var # Final result
Example: while sum is built in, we could have defined it ourselves as:
def my_sum(num_list: list[float]) -> float:
total = 0
for n in num_list:
total = total + n
return total
def test_my_sum():
assert my_sum([0, 1, 2, 3]) == 6
Implementing Basic Functions
Product Function
Define your own product function that takes a list of numbers and returns their product (multiply all of them together).
def my_product(num_list: list[float]) -> float:
# YOUR CODE HERE
pass
def test_my_product():
assert my_product([2, 3, 4]) == 24
assert my_product([1, 2, 3, 4, 5]) == 120
Length Function
Define a function my_length that takes a list of any value and returns the number of elements in the list.
def my_length(lst: list) -> int:
# YOUR CODE HERE
pass
def test_my_length():
assert my_length(["a", "b", "c"]) == 3
assert my_length([1, 2, 3, 4, 5]) == 5
assert my_length([]) == 0
Finding Maximum Values
Maximum Function
Define a function my_max that finds the largest number in a list.
def my_max(num_list: list[float]) -> float:
# YOUR CODE HERE
pass
def test_my_max():
assert my_max([3, 7, 2, 9, 1]) == 9
assert my_max([5]) == 5
assert my_max([-10, -5, -20]) == -5
Is there any issue with the choice of initial_value for this problem?
Wrap-Up
What's the difference between defining a variable and changing its value? When might you implement your own list functions instead of using built-ins?