The trick is “knowing” something about the whole loop when you are stuck writing code that only sees one entry at a time
Set some variables to initial values
for thing in data:
Look for something or do something to each entry separately,
updating a variable
Look at the variables
We make a variable that contains the largest value we have seen so far. If the current number we are looking at is larger, it is the new largest value we have seen so far.
largest_so_far = -1
print('Before', largest_so_far)
for the_num in [9, 41, 12, 3, 74, 15]:
if the_num > largest_so_far:
largest_so_far = the_num
print(largest_so_far, the_num)
print('After', largest_so_far)
zork = 0
print('Before', zork)
for thing in [9, 41, 12, 3, 74, 15]:
zork = zork + 1
print(zork, thing)
print('After', zork)
To count how many times we execute a loop, we introduce a counter variable that starts at 0 and we add one to it each time through the loop.
zork = 0
print('Before', zork)
for thing in [9, 41, 12, 3, 74, 15]:
zork = zork + thing
print(zork, thing)
print('After', zork)
To add up a value we encounter in a loop, we introduce a sum variable that starts at 0 and we add the value to the sum each time through the loop.
count = 0
sum = 0
print('Before', count, sum)
for value in [9, 41, 12, 3, 74, 15]:
count = count + 1
sum = sum + value
print(count, sum, value)
print('After', count, sum, sum/count)
An average just combines the counting and sum patterns and divides when the loop is done.
print('Before')
for value in [9, 41, 12, 3, 74, 15]:
if value > 20:
print('Large number', value)
print('After')
We use an if statement in the loop to catch/filter the values we are looking for.
found = false
print('Before', found)
for value in [9, 41, 12, 3, 74, 15]:
if value == 3:
found = True
print(found, True)
print('After', found)
If we just want to search and know if a value was found, we use a variable that starts at False and is set to True as soon as we find what we are looking for.
How would we change this to make it find the smallest value in the list?
smallest = None
print('Before')
for value in [9, 41, 12, 3, 74, 15]:
if smallest is None:
smallest = value
elif value < smallest:
smallest = value
print(smallest, value)
print('After', smallest)
We still have a variable that is the smallest so far.
The first time through the loop smallest is None, so we take the first value to be the smallest.
ex) 0 == 0.0 → True
0 is 0.0 → False [different data types]