Arrays · 7 / 23 Theory

Menu programs, statistics and common mistakes

The last exercise of the lesson, Mathematical statistics, brings everything together: a list that grows, a menu that repeats until you exit and calculations over the data. This article gives the structure and reviews the most common mistakes.

Structure of a program with a menu

data = []

while True:
    print("1. Add a number")
    print("2. Show the average")
    print("0. Exit")
    option = input()

    if option == "1":
        data.append(float(input()))
    elif option == "2":
        if len(data) > 0:
            print(sum(data) / len(data))
        else:
            print("No data")
    elif option == "0":
        break
    else:
        print("Invalid option")

It is a while True with an if/elif/else inside and a break in the exit option. The data list is created outside the loop, so that it keeps the values between turns.

Limit of elements

If the statement limits the list (for example, 1000 numbers), check len(data) < 1000 before adding.

Usual statistics

data = [4.0, 8.0, 1.0, 9.0, 3.0]
ordered = sorted(data)

average = sum(data) / len(data)
largest = max(data)
smallest = min(data)
span = largest - smallest

n = len(ordered)
if n % 2 == 1:
    median = ordered[n // 2]
else:
    median = (ordered[n // 2 - 1] + ordered[n // 2]) / 2

print(average, largest, smallest, span, median)   # 5.0 9.0 1.0 8.0 4.0

The median is the central value of the sorted list; if there is an even number of data, the average of the two central ones.

Common mistakes with lists

  • IndexError: using an index equal to len(list) or greater. The last index is len(list) - 1.
  • Confusing copying with assigning: b = a does not copy the list; use a.copy().
  • Modifying the list while looping over it: removing elements inside a for x in list skips elements. Loop over a copy (for x in list.copy()) or build a new list.
  • l = l.sort(): sort() returns None.
  • Empty lists: max([]) raises ValueError and sum(l) / len(l) raises ZeroDivisionError. Check if l: first.
  • Matrices with [[x] * c] * r: all rows are the same list.
  • Reading numbers without converting: input() returns text; convert with int() or float() before adding.
l = [1, 2, 3, 4]
for x in l:
    if x % 2 == 0:
        l.remove(x)
print(l)   # [1, 3]   (looks fine, but with [2, 4] it gives [4]: it skips elements)