Counting and Filtering
The second pattern counts: how many elements of a list meet a condition? It looks like adding up, but instead of the value, you add 1, and only when an if says so:
temperatures = [18, 24, 27, 15, 31, 22, 29]
hot_days = 0
for temperature in temperatures:
if temperature >= 25:
hot_days += 1
print("Hot days:", hot_days)Hot days: 3The counter hot_days starts at 0, before the loop. The loop looks at every temperature, and the if decides whether to count it. hot_days += 1 runs only for 27, 31 and 29, so at the end, the counter is 3. Notice that hot_days += 1 is indented twice: it belongs to the if, which is inside the loop. Again, you print the result after the loop.
Sometimes you want to know not only how many, but also which ones. Then start with an empty list and add each matching element to it with .append():
temperatures = [18, 24, 27, 15, 31, 22, 29]
hot = []
for temperature in temperatures:
if temperature >= 25:
hot.append(temperature)
print("Hot temperatures:", hot)
print("Hot days:", len(hot))Hot temperatures: [27, 31, 29]
Hot days: 3This way, you build a new list from the elements you want, and the original list stays as it was. And len() tells you how many elements the new list has.
Instructions
The list scores holds the points from a test. You pass with 50 points or more. Count the students who passed: create a variable passed with the value 0, go through scores with a loop, and for every score of at least 50, increase passed by 1. After the loop, print the result with print("Passed:", passed). The output is Passed: 5.
Now also collect the scores below 50: before the loop, create an empty list failed, and inside the loop, add each score below 50 to it with .append() (an else will do). After the loop, print it with print("Failed:", failed). The output is Failed: [45, 38, 29].
Start programming for free
5/11