It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

Counters

In programming, a counter is a variable that is used to count something—like how many times a condition is met during a loop. This is especially useful when analyzing data.


1. Simple Counter Example

Let’s say you want to count how many even numbers exist in a list:

numbers = [1, 4, 7, 10, 12, 15]
count = 0

for number in numbers:
    if number % 2 == 0:
        count += 1

print("There are", count, "even numbers.")

Output

There are 3 even numbers.
  • The count += 1 increases the value of count by 1 every time the condition is met.

2. Counting Rows That Match a Condition

Now, let’s count how many students scored above 70:

students = [
    ["Name", "Score"],
    ["Alice", 85],
    ["Bob", 59],
    ["Charlie", 72],
    ["Diana", 91],
    ["Eve", 66]
]

count = 0

for student in students[1:]:
    if student[1] > 70:
        count += 1

print("Students with scores above 70:", count)

Output

Students with scores above 70: 3

3. Counting with Conditions and Filters

You can even combine counters with conditions and filters for more complex analysis.

# Data: List of employees with department and salary
employees = [
    ["Name", "Department", "Salary"],
    ["Alice", "Engineering", 72000],
    ["Bob", "Sales", 50000],
    ["Charlie", "Engineering", 64000],
    ["Diana", "Marketing", 58000],
    ["Eve", "Engineering", 83000],
    ["Frank", "Sales", 46000]
]

# Goal: Count how many Engineering employees earn more than 65,000

count = 0

for employee in employees[1:]:
    department = employee[1]
    salary = employee[2]

    if department == "Engineering" and salary > 65000:
        count += 1

print("Engineering employees earning more than 65,000:", count)

Output

Engineering employees earning more than 65,000: 2

Exercise: Try It Yourself!

Here’s a table of products with their prices. Write a program to count:

  • How many products cost more than 50.
    products = [
    ["Product", "Price"],
    ["Laptop", 899],
    ["Headphones", 49],
    ["Mouse", 35],
    ["Monitor", 120],
    ["Keyboard", 55]
    ]

Expected Output:

Products costing more than 50: 3