£199.99 £139.99 for one year of Unlimited learning. Offer ends on 28 February 2023 at 23:59 (UTC). T&Cs apply

# Implement count function

Learn how to implement a count function in your code with this example.

Having discussed the algorithm for our counting function, let’s try to implement it in another context.

Imagine a class has completed a short online quiz to test their knowledge. Marks are out of 10, and you want to know how many learners got top marks. Wouldn’t it be good to get a computer to analyse the data for you?

• First let’s generate a set of random scores to represent the class. We’ll use the randint function, from Python’s random library, which takes a minimum and maximum number for the values to be generated.
from random import randintscores = []for x in range (0, 30): scores.append(randint(0, 10)) # Generate a random number from 0 to 10 and append to scoresprint(scores)

Now we have a list containing 30 learners’ quiz scores between 0 and 10.

• Next we want to know how many of those learners achieved a top score of 10.

To count the number of 10s, we need to iterate over the list checking to see if each score is equal to 10. When we find a 10, we need to increment a tens variable that keeps a count of how many we have found. Add the following to your existing code.

tens = 0 # Initialise a variable for counting scores of tenfor score in scores: if score == 10: tens += 1print("{0} learners got top marks".format(tens))

Tip: The line tens += 1 is short for tens = tens + 1. It’s such a common thing to do that Python and other programming languages have a shorthand for it.

## Challenge

Counting the number of occurrences in a list is a common task, so it makes sense to create a function that can check for any item in a list.

The function would need to take two parameters: the target item that we want to count occurrences of, and the list of items.

Can you add a generic count function to this program so that it prints out the number of learners that scored top marks?

import random## Add your count function here#scores = []for x in range (0, 30): scores.append(random.randint(0, 10))print(scores)top_scorers = count(10, scores) # Count function called hereprint("{0} learners got top marks".format(top_scorers))

See if you can use your function to count other items in lists.

• What about counting occurrences of a given item in a list of strings?
• Can you count numbers in a particular range, e.g. less than 3?
• Can you count vowels in a word?

In the next step, you’ll have the chance to share your code and suggestions.