How to make a counter in Python

Make a Python counter with an example: Learn how to create a simple counter, and see an example of counting from 0 to 10.

Creating a Counter in Python

Creating a counter in Python is a relatively straightforward process. The first step is to create a dictionary to store the count of each item. The dictionary should be initialized with keys that correspond to the items we want to count, and values of zero. For example, if we want to count the number of occurrences of the words "apple" and "orange" in a sentence, we could create the following dictionary:


counter_dict = {
    "apple": 0,
    "orange": 0
}

Next, we need to loop through the sentence and update the counter values based on the words we find. To accomplish this, we can use the built-in str.count() method. This method returns the number of times a substring appears in a string. We can use this to update the counter values like so:


sentence = "I ate an apple and an orange"

for word in counter_dict:
    counter_dict[word] = sentence.count(word)

The counter values will now be updated to reflect the number of occurrences of each word in the sentence. We can print out the updated counter values like so:


for word in counter_dict:
    print(f"{word}: {counter_dict[word]}")

# Output:
# apple: 1
# orange: 1

And that's it! We've successfully created a counter in Python that can be used to count the number of occurrences of any given word in a sentence.

Answers (0)