
Python Loops: Automating Repetitive Tasks Like a Pro
Python loops let you avoid printing “Happy New Year” 100 times by hand, or checking every item in a 10,000 row spreadsheet, one line at a time. Doing that manually would take forever. That's exactly the kind of repetitive work computers exist to handle. In this article, you'll learn Python loops, the two loop types Python offers, and how to use them to automate repetitive tasks like a pro.
For Loops: Definite Iteration
A for loop runs a block of code once for each item in a sequence, like a list:
fruits = ["mango", "banana", "papaya"]
for fruit in fruits:
print(f"I like {fruit}")
Here's how to read this out loud: “for each fruit in the fruits list, print a sentence about it.” On the first pass, fruit holds "mango". On the second pass, it holds "banana", and so on. The loop stops automatically once it reaches the last item. This is called definite iteration, because Python already knows exactly how many times the loop will run: once per item.
The range() Function
Most of the time you don't have a list ready. You just want to repeat something a fixed number of times. That's what range() is for. It generates a sequence of numbers on the fly:
for i in range(5):
print(f"Repetition number {i}")
This prints numbers 0, 1, 2, 3, and 4. Notice it stops before reaching 5. range(5) means “5 numbers, starting from 0”, not “up to and including 5”. This trips up a lot of beginners, so it's worth remembering early.
range() can also take a start, a stop, and a step:
for i in range(2, 10, 2): # start at 2, stop before 10, step by 2
print(i) # 2, 4, 6, 8
The step tells Python how much to add each time. A step of 2 skips every other number. You can even use a negative step, like range(10, 0, -1), to count down instead of up.
While Loops: Indefinite Iteration
A while loop keeps running as long as a condition stays true. Unlike a for loop, Python doesn't know in advance how many times it will run. This is called indefinite iteration, and it's useful whenever the number of repetitions depends on something that happens while the program runs, like user input.
count = 1
while count <= 5:
print(f"Count is {count}")
count += 1
Read this as "while count is less than or equal to 5, print it, then add 1 to count." The line count += 1 is short for count = count + 1. This line is essential. Without it, count would stay at 1 forever, the condition would always stay true, and the loop would never stop. This is called an infinite loop, one of the most common bugs beginners run into. Always make sure something inside a while loop eventually makes its condition false.
Loop Control: break and continue
for number in range(1, 10):
if number == 5:
break # stop the loop entirely
print(number)
for number in range(1, 10):
if number % 2 == 0:
continue # skip the rest of this pass, go to the next one
print(number)
These two keywords change how a loop behaves from the inside. break stops the entire loop immediately, even if there are more items left to go through. In the first example, the loop prints 1, 2, 3, 4, and then stops the moment number becomes 5, never printing 5 or anything after it.
continue is gentler. It only skips the rest of the current pass and moves on to the next one, without stopping the whole loop. In the second example, whenever number is even, Python jumps straight back to the top of the loop, skipping the print(number) line for that specific number only.
Nested Loops
for row in range(1, 4):
for col in range(1, 4):
print(f"({row},{col})", end=" ")
print()
A loop inside another loop is called nesting. The inner loop, over col, runs completely for every single pass of the outer loop, over row. So with 3 values for row and 3 values for col, the inner print() line runs 3 times 3, or 9 times in total. Nested loops are useful for grids, tables, and pattern generation, but they can get slow with large ranges, since the total repetitions multiply together rather than just add up.
Practical Project 1: Multiplication Table Generator
number = int(input("Which number's multiplication table? "))
for i in range(1, 11):
print(f"{number} x {i} = {number * i}")
This small program asks for a number, then loops from 1 to 10 (remember, range(1, 11) stops before 11), printing one multiplication line per pass. It's a simple, direct use of a for loop with a known, fixed number of repetitions.
Practical Project 2: Number Guessing Game
import random
secret_number = random.randint(1, 20)
attempts = 0
while True:
guess = int(input("Guess a number between 1-20: "))
attempts += 1
if guess == secret_number:
print(f"Correct! You got it in {attempts} tries.")
break
elif guess < secret_number:
print("Too low, try again.")
else:
print("Too high, try again.")
This project is a great example of why while loops exist. You have no idea how many guesses the player will need, so a for loop wouldn't fit well here. Notice the condition is simply True. This creates a loop that would normally run forever, on purpose. The only way out is the break statement inside the if guess == secret_number: block. This pattern, while True combined with a break, is extremely common in real Python code whenever you want to keep looping "until something specific happens", rather than for a fixed number of times.
Avoiding Infinite Loops
- Always update the variable your
whilecondition depends on, usually near the end of the loop body. - Double check that your loop's exit condition can actually be reached. A condition like
while count < 5never becomes false ifcountonly ever increases past 5 in big jumps. - If you use
while True, make sure there is abreakstatement somewhere inside that can actually be reached. - If a program hangs and won't stop, press
Ctrl+Cin the terminal to force stop it.
Common Beginner Mistakes
- Off by one errors: forgetting that
range(5)stops before 5, not at 5. If you need to include 10, writerange(1, 11), notrange(1, 10). - Forgetting to update the loop variable: a
whileloop with no line likecount += 1anywhere inside it will usually run forever. - Using
breakwhen you meantcontinue:breakexits the whole loop, whilecontinueonly skips to the next pass. Mixing these up often causes a loop to stop far too early. - Modifying a list while looping over it: removing or adding items to a list during a
forloop over that same list can skip items or cause unexpected results. This is a more advanced pitfall worth knowing about once you start working with lists in the next article.
Try It Yourself
Practice these three short exercises in a new file called practice_loops.py before moving on:
- Use a
forloop andrange()to print all even numbers from 2 to 20. - Write a
whileloop that keeps asking the user to enter a password until they type the correct one. - Modify the Number Guessing Game so it also prints "Game over, you're out of tries!" and stops if the player hasn't guessed correctly within 5 attempts.
Frequently Asked Questions
When should I use a for loop instead of a while loop?
Use for when you know exactly how many times to repeat, like going through every item in a list. Use while when the repetition depends on a changing condition, like user input or a game state.
Does range(5) include the number 5?
No. range(5) produces 0, 1, 2, 3, and 4. It stops before reaching 5.
Why is my loop running forever?
Check that your while condition eventually becomes false. A common cause is forgetting to update the counter variable inside the loop body.
Can I loop through a string?
Yes. Strings are sequences too, so for letter in "Python": loops through each character one at a time, printing P, y, t, h, o, then n.
What's the difference between break and returning from a function?
break only stops the loop it's directly inside. Any code written after the loop still runs normally. We'll cover functions, and how they exit differently, in a later article.
Ready to organize and manage collections of data? In our next article, we'll dive into Python lists, your first real data structure, and combine them with the loops you just learned to build a fully functional personal task manager.
Learning programming works best as a collaborative process, and your questions and insights help make these tutorials more effective for everyone. If you get stuck avoiding an infinite loop, run into unexpected results with the guessing game, or discover a creative twist on either project, please share your experience in the comments. Your feedback helps create a learning community where we can all benefit from each other's discoveries and solutions.
You Might Also Like

Handling Errors Like a Professional Python Developer
... Read more

Writing Clean Python Functions: Code Organization Made Simple
... Read more

Python Dictionaries: Storing Data with Purpose
Master Python dictionaries — key-value pairs, nesting, and comprehensions — with a hands-o...

Python Lists: Your First Data Structure Adventure
Master Python lists — creation, indexing, slicing, methods, and comprehensions — with a ha...
Comments
No comments yet — be the first to start the conversation!