Learn / Python / Lists and loops: averaging sensor readings
Python, lesson 4 of 6
Lists and loops: averaging sensor readings
A list holds many values in order: readings = [10, 20, 30]. A for loop visits each one:
total = 0
for r in readings:
total = total + r
print(total) # 60
print(len(readings)) # 3, how many items
Good programs handle the awkward cases too. What should happen when the list is empty?
Your turn
Write average(readings) that returns the average of a list of numbers. For an empty list, return 0 instead of crashing.
Press Run to see what your code prints.
Hint: Check for an empty list first: if not readings: return 0. Then add them up and divide by len(readings).