Standard Algorithms: Count Occurences:

Created
Tags

This is another standard algorithm that loops through an array to see how many times a value appears.

def inputs(): #this just sets up the array and the variables we shall be working with.
    markslist = []
    pupilcount = int(input("how many pupils do you have?"))
    search = int(input("which mark do you want me to search for?"))
    for counter in range(pupilcount):
        score = int(input("how many marks did pupil " + str(counter + 1) + " score?"))
        markslist.append(score)
    return markslist, search

def occurences(markslist, search): #this is where the important stuff happens.
    x = 0 #this counts the number of occurences. crucial to initialise the variable.
    for counter in range(len(markslist)): #checks how many times the value we are searching for appears in this array.
        if markslist[counter] == search:
            x += 1 #increments. same as x = x + 1
    return x

def output(search, x):
    if x > 0: #if the search term was found
        print("The mark", search, "was found", x, "times in this class.")
    else: #if it wasn't found.
        print("There were no pupils with this mark.")

markslist, search = inputs()
x = occurences(markslist, search)
output(search, x)

Think about the error message you get when your search term was not found. This searches your input against all the webpages in the world. When it doesn’t find any, it returns this error.

error.
success!