7.4. Loop counters
Table of Contents
What Is a Loop Counter?
A loop counter is a variable that keeps track of how many times a loop has run, or which step you are currently on.
You will most often see loop counters:
- In
forloops that go through a sequence of numbers - In
whileloops where you manually increase a number each time
They are especially useful when you want to:
- Repeat something a specific number of times
- Number items (1st, 2nd, 3rd, …)
- Count how many times something happens
Loop Counters with `for` Loops
In Python, for loops often use a loop counter variable together with range().
Basic pattern:
for counter in range(start, stop):
# use counter inside the loopcounteris the loop counter variablestartis the first number (included)stopis the last number (not included)
Example: repeat something 5 times
for i in range(5):
print("Loop number:", i)Output:
Loop number: 0
Loop number: 1
Loop number: 2
Loop number: 3
Loop number: 4Here:
- The loop runs 5 times
- The counter
itakes the values0, 1, 2, 3, 4
Starting the Counter at 1
Humans usually count from 1, but range(5) starts at 0.
To start at 1, give both start and stop values:
for i in range(1, 6): # 1, 2, 3, 4, 5
print("Item number:", i)
Now i goes from 1 to 5.
Using the Counter Inside the Loop
You can use the counter to:
- Number printed lines
- Do calculations that depend on the step number
Example: square of each number
for n in range(1, 6):
square = n * n
print(n, "squared is", square)Step Size and Loop Counters
range() can also take a step value:
range(start, stop, step)stepis how much the counter changes each loop
Example: counting by 2 (even numbers):
for i in range(0, 11, 2): # 0, 2, 4, 6, 8, 10
print(i)Example: counting backwards:
for i in range(5, 0, -1): # 5, 4, 3, 2, 1
print(i)
The loop counter follows the pattern you set with start, stop, and step.
Loop Counters with `while` Loops
In a while loop, you usually create and update the loop counter yourself.
Basic pattern:
counter = start_value # 1. initialize
while some_condition: # 2. condition uses counter
# do something
counter = counter + 1 # 3. update counter
Example: repeat 5 times with a while loop
i = 0 # start
while i < 5: # condition
print("i is", i)
i = i + 1 # updateIf you forget to update the counter, the condition may never become false, causing an infinite loop. The counter update is what lets the loop eventually stop.
Common Counter Pattern in `while`
Counting from 1 to 5:
count = 1
while count <= 5:
print("Count:", count)
count = count + 1Counting Things Inside a Loop
Sometimes the loop counter is not just “how many times we loop”, but “how many times something specific happened”.
You do this with a separate counter variable.
Basic pattern:
count = 0
for each item in something:
if condition_is_true:
count = count + 1Example: count how many numbers are positive
numbers = [3, -1, 7, 0, -4, 2]
positive_count = 0
for n in numbers:
if n > 0:
positive_count = positive_count + 1
print("Positive numbers:", positive_count)Here:
positive_countis a counter variable- It starts at 0
- It increases by 1 every time we find a positive number
Shorthand for Increasing Counters
The line:
positive_count = positive_count + 1is very common. Python has a shorter form:
positive_count += 1Similarly:
counter -= 1meanscounter = counter - 1counter = 2meanscounter = counter 2
These are often used when updating loop counters.
Index Counters vs Item Values
When looping through a list, there are two common patterns:
- Loop over items directly (no explicit counter)
- Loop over positions (indexes) using a counter
Example list:
names = ["Alice", "Bob", "Charlie"]1. Loop over items (no manual index counter):
for name in names:
print(name)Here, there is no index counter; you just get each name.
2. Loop over indexes (using a counter):
for i in range(len(names)): # i = 0, 1, 2
print("Index:", i, "Name:", names[i])iis a loop counter for the positionslen(names)gives the number of items in the list
This pattern is useful when you need both:
- The position (index)
- The actual value
Using `enumerate()` for Index + Value
Python has a helper function enumerate() that gives you both index and item in one go:
for index, name in enumerate(names):
print(index, name)Here:
indexis the loop counter (0, 1, 2, …)nameis the value at that position
You can also start the index at 1:
for index, name in enumerate(names, start=1):
print(index, name)Off-by-One Errors with Counters
A very common mistake with loop counters is being off by one:
- Looping 4 times when you meant 5
- Stopping at 9 when you meant 10
This is called an off-by-one error.
Common patterns to remember:
range(n)→ goes from0ton - 1(runsntimes)range(1, n + 1)→ goes from1ton(also runsntimes)
Example: repeat something exactly n times, starting from 1:
n = 5
for i in range(1, n + 1): # 1, 2, 3, 4, 5
print("Step", i)Loop Counters with `break` and `continue`
When you use break or continue, the loop counter may not behave the way you first expect.
continueskips to the next loop iterationbreakstops the loop completely
Skipping Some Counter Values with `continue`
for i in range(1, 6): # 1 to 5
if i == 3:
continue # skip the rest of this loop
print(i)Output:
1
2
4
5
The counter i still goes 1, 2, 3, 4, 5, but 3 is never printed because that iteration is skipped.
Ending the Loop Early with `break`
for i in range(1, 11): # 1 to 10
print("i =", i)
if i == 4:
breakOutput:
i = 1
i = 2
i = 3
i = 4
The counter i would have gone up to 10, but break stops the loop when i reaches 4.
Practical Examples with Loop Counters
Example 1: Simple Countdown
start = 5
for i in range(start, 0, -1):
print(i)
print("Go!")Uses a counter that decreases each time.
Example 2: Sum of the First `n` Numbers
We want:
$$
1 + 2 + 3 + \dots + n
$$
n = 5
total = 0
for i in range(1, n + 1):
total += i
print("Sum from 1 to", n, "is", total)Example 3: Count How Many Times the User Enters “yes”
yes_count = 0
for i in range(3): # ask 3 times
answer = input("Type yes or no: ")
if answer == "yes":
yes_count += 1
print("You typed 'yes' this many times:", yes_count)Here:
iis a loop counter for the number of questionsyes_countis a counter for how many times the condition is met
Summary
- A loop counter is a variable that tracks loop progress or counts events.
- In
forloops, the counter often comes fromrange()orenumerate(). - In
whileloops, you must initialize and update the counter yourself. - Counters can track:
- How many times the loop has run
- Positions (indexes) in a collection
- How many times a condition was true
- Be careful of off-by-one errors when choosing
range()arguments. - Use
+= 1and-= 1to update counters concisely.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Chapter 1: What Is Programming?
- ☰ 1.1. What is a computer program?
- ☰ 1.2. What is Python?
- ☰ 1.3. Where is Python used?
- ☰ 1.4. How programming helps solve problems
- ☰ 1.5. Your first Python program
-
- ☰ 2. Chapter 2: Setting Up Python
- ☰ 2.1. Installing Python (Windows / macOS / Linux)
- ☰ 2.2. Using Python in the terminal
- ☰ 2.3. Using an IDE (IDLE / VS Code)
- ☰ 2.4. Running Python scripts
- ☰ 2.5. Python interactive mode
-
- ☰ 3. Chapter 3: Variables and Data Types
- ☰ 3.1. What is a variable?
- ☰ 3.2. Creating variables
- ☰ 3.3. Numbers
- ☰ 3.4. Test
- ☰ 3.5. Boolean values
- ☰ 3.6. Type checking
-
- ☰ 4. Chapter 4: Basic Operations
- ☰ 4.1. Arithmetic operations
- ☰ 4.2. Working with numbers
- ☰ 4.3. String operations
- ☰ 4.4. Combining text and variables
- ☰ 4.5. Comments in Python
-
- ☰ 5. Chapter 5: User Input and Output
- ☰ 5.1. Getting input from the user
- ☰ 5.2. Converting input to numbers
- ☰ 5.3. Formatting output
- ☰ 5.4. Writing interactive programs
-
- ☰ 6. Chapter 6: Conditions
- ☰ 6.1. Comparison operators
- ☰ 6.2. Logical operators
- ☰ 6.3. if, elif, else
- ☰ 6.4. Nested conditions
- ☰ 6.5. Common beginner mistakes
-
- ☰ 7. Chapter 7: Loops
- ☰ 7.1. Why loops are useful
- ☰ 7.2. for loops
- ☰ 7.3. while loops
- ☰ 7.4. Loop counters
- ☰ 7.5. break and continue
- ☰ 7.6. Loop exercises
-
- ☰ 8. Chapter 8: Data Collections
- ☰ 8.1. Lists
- ☰ 8.2. Tuples
- ☰ 8.3. Dictionaries
- ☰ 8.4. Sets (basics)
- ☰ 8.5. Choosing the right data structure
-
- ☰ 9. Chapter 9: Functions
- ☰ 9.1. Why functions matter
- ☰ 9.2. Defining functions
- ☰ 9.3. Parameters and arguments
- ☰ 9.4. Return values
- ☰ 9.5. Scope (local vs global)
- ☰ 9.6. Reusing code
-
- ☰ 10. Chapter 10: Working with Files
- ☰ 10.1. What is a file?
- ☰ 10.2. Reading text files
- ☰ 10.3. Writing and appending files
- ☰ 10.4. File paths
- ☰ 10.5. Simple file-based programs
-
- ☰ 11. Chapter 11: Errors and Debugging
- ☰ 11.1. Types of errors
- ☰ 11.2. Reading error messages
- ☰ 11.3. Common beginner errors
- ☰ 11.4. try and except
- ☰ 11.5. Debugging strategies
-
- ☰ 12. Chapter 12: Using Python Libraries
- ☰ 12.1. What is a library?
- ☰ 12.2. Importing modules
- ☰ 12.3. Standard libraries
- ☰ 12.3.1. math
- ☰ 12.3.2. random
- ☰ 12.3.3. datetime
-
- ☰ 12.4. Installing external libraries with pip
-
- ☰ 13. Chapter 13: Object-Oriented Programming
- ☰ 13.1. What is object-oriented programming?
- ☰ 13.2. Classes and objects
- ☰ 13.3. The `__init__` method
- ☰ 13.4. Attributes and methods
- ☰ 13.5. Encapsulation
- ☰ 13.6. Inheritance (basics)
- ☰ 13.7. Simple OOP examples
-
- ☰ 14. Chapter 14: Automation with Python
- ☰ 14.1. What is automation?
- ☰ 14.2. Automating simple tasks
- ☰ 14.3. Working with files and folders
- ☰ 14.4. Automating text processing
- ☰ 14.5. Scheduling scripts
- ☰ 14.6. Practical automation examples
-
- ☰ 15. Chapter 15: Web Development with Python
- ☰ 15.1. How the web works (basic overview)
- ☰ 15.2. Introduction to Flask
- ☰ 15.3. Creating a simple web server
- ☰ 15.4. Routing and templates
- ☰ 15.5. Handling user input (forms)
- ☰ 15.6. Very basic APIs
-
- ☰ 16. Chapter 16: Data Science with Python
- ☰ 16.1. What is data science?
- ☰ 16.2. Working with data
- ☰ 16.3. Introduction to NumPy
- ☰ 16.4. Introduction to pandas
- ☰ 16.5. Data visualization with matplotlib
- ☰ 16.6. Simple data analysis examples
-
- ☰ 17. Chapter 17: Mini Projects
- ☰ 17.1. Number guessing game
- ☰ 17.2. Simple calculator
- ☰ 17.3. To-do list
- ☰ 17.4. Password generator
- ☰ 17.5. Quiz application
- ☰ 17.6. Small web or data project
-
- ☰ 18. Chapter 18: Next Steps
- ☰ 18.1. How to practice Python
- ☰ 18.2. Writing clean and readable code
- ☰ 18.3. Choosing a specialization
- ☰ 18.3.1. Web development
- ☰ 18.3.2. Data science
- ☰ 18.3.3. Automation
- ☰ 18.3.4. Software development
-
- ☰ 18.4. Learning resources and communities
-
- ☰ 19. Appendix
- ☰ 19.1. Python syntax cheat sheet
- ☰ 19.2. Common errors and solutions
- ☰ 19.3. Glossary of terms
-
Comments
Please login to add a comment.
Don't have an account? Register now!