Let me tell you what happened the first time I wrote a loop.
I wanted to print numbers from 1 to 10. Simple enough. I had just read about while loops. I thought I understood them. So I wrote this:
number = 1
while number < 10:
print(number)
I ran it.
Numbers started printing. 1, 2, 3... wait. Same numbers? 1, 1, 1, 1, 1, 1, 1, 1...
The terminal filled up. Lines kept coming. The computer fan started spinning faster. I sat there frozen for three full seconds before I remembered to press Ctrl+C to stop it.
I had created an infinite loop. And I had no idea what I did wrong.
That moment is where this post starts.
What Even Is a Loop
You already know Python runs your code top to bottom, one line at a time. Loops break that rule in a useful way. They say: run this block of code multiple times before moving on.
Without loops, if you wanted to print numbers 1 through 10, you'd write:
print(1)
print(2)
print(3)
print(4)
print(5)
print(6)
print(7)
print(8)
print(9)
print(10)
That's fine for 10. What about 1000? What about a million? What if you don't know the number in advance?
That's where loops come in.
Python has two kinds. The for loop and the while loop. They do similar jobs but in different situations. Learn both.
The For Loop
A for loop goes through a collection of things, one by one, and runs your code for each one.
for number in range(1, 11):
print(number)
Output:
1
2
3
4
5
6
7
8
9
10
Ten lines. One instruction. That's the power.
Let's break down what each part means.
for starts the loop.
number is a variable you create right here. It gets a new value on each pass through the loop. You can name it anything. n, i, num, whatever makes sense.
in connects the variable to the collection.
range(1, 11) creates a sequence of numbers starting at 1 and going up to but not including 11. So 1 through 10. The second number is always exclusive. Feels weird at first. You get used to it.
The colon and indentation work the same as if statements. Everything indented under the for line runs on each pass.
Range Has Three Versions
Worth knowing all three now so they don't confuse you later.
range(5) # 0, 1, 2, 3, 4 (starts at 0 by default)
range(1, 6) # 1, 2, 3, 4, 5
range(0, 10, 2) # 0, 2, 4, 6, 8 (third number is the step)
for i in range(0, 10, 2):
print(i)
Output:
0
2
4
6
8
The step can also go backwards.
for i in range(10, 0, -1):
print(i)
Output:
10
9
8
7
6
5
4
3
2
1
Looping Over a List
Range isn't the only thing you can loop over. You can loop over any collection, including a list of items.
fruits = ["apple", "banana", "mango", "grape"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
mango
grape
The variable fruit takes on each value in the list, one by one. First pass it's "apple", second pass "banana", and so on. The loop runs exactly four times because there are four items.
This is something you'll do constantly in real code. Go through a list, do something with each item.
names = ["Alex", "Priya", "Sam", "Jordan"]
for name in names:
print(f"Hello, {name}!")
Output:
Hello, Alex!
Hello, Priya!
Hello, Sam!
Hello, Jordan!
The While Loop
A while loop is different. Instead of going through a collection, it keeps running as long as a condition stays true.
number = 1
while number <= 10:
print(number)
number = number + 1
Output:
1
2
3
4
5
6
7
8
9
10
Same result as the for loop example. Different mechanism.
The while loop checks the condition before every single pass. Is number <= 10? Yes? Run the block. Check again. Yes? Run again. At some point number becomes 11. Is 11 <= 10? No. Stop.
Now you see my mistake from the opening. I forgot number = number + 1. The number never changed. It stayed 1. The condition 1 < 10 was always true. The loop never stopped.
The golden rule for while loops: always make sure something inside the loop will eventually make the condition false. If nothing changes the condition, you loop forever.
Breaking Out Early
Sometimes you want to stop a loop before it naturally finishes. break does that.
for number in range(1, 20):
if number == 7:
print("Found 7, stopping")
break
print(number)
Output:
1
2
3
4
5
6
Found 7, stopping
The loop was set to run from 1 to 19. But when it hit 7, the break statement stopped the whole loop immediately. Everything after 7 never ran.
Skipping One Pass
continue is different from break. Instead of stopping the whole loop, it skips only the current pass and moves to the next one.
for number in range(1, 11):
if number == 5:
continue
print(number)
Output:
1
2
3
4
6
7
8
9
10
5 is missing. When number was 5, continue fired and Python jumped straight to the next iteration. The print(number) below it never ran for that one pass.
Keeping Count Inside a Loop
A really common pattern: start a counter at 0, add to it inside the loop.
total = 0
for number in range(1, 11):
total = total + number
print(f"Sum of 1 to 10: {total}")
Output:
Sum of 1 to 10: 55
The variable total lives outside the loop but gets updated inside it on every pass. After the loop finishes, total holds the final answer.
This pattern shows up everywhere. In real AI code you'll use it to track losses, scores, counts, totals. The shape of the pattern is always the same: set up a variable before the loop, update it inside, use it after.
Nested Loops
You can put a loop inside a loop. The inner one runs completely for every single pass of the outer one.
for row in range(1, 4):
for col in range(1, 4):
print(f"Row {row}, Col {col}")
Output:
Row 1, Col 1
Row 1, Col 2
Row 1, Col 3
Row 2, Col 1
Row 2, Col 2
Row 2, Col 3
Row 3, Col 1
Row 3, Col 2
Row 3, Col 3
Outer loop runs 3 times. Each time it runs, the inner loop runs 3 times. Total: 9 lines.
This matters more in AI than you'd expect. When you work with grids, matrices, images, you're often looping over rows and columns exactly like this.
A Practical Example
Let's use loops for something real. A simple number guessing game.
secret = 7
attempts = 0
guesses = [3, 9, 7]
for guess in guesses:
attempts = attempts + 1
if guess == secret:
print(f"Correct! You got it in {attempts} attempt(s)")
break
elif guess < secret:
print(f"Guess {guess}: too low")
else:
print(f"Guess {guess}: too high")
Output:
Guess 3: too low
Guess 9: too high
Correct! You got it in 3 attempt(s)
This combines everything you've learned so far. Variables, data types, conditions, and now loops. Notice how the pieces fit together.
When to Use Which
A simple way to decide:
Use for when you know what you're looping over. A list of names. A range of numbers. A known collection of things.
Use while when you don't know how many times you'll loop. Keep going until the user types "quit." Keep going until you find the answer. Keep going until some condition changes.
Most of the time in Python, for is what you want. while is for specific situations where the end condition isn't a fixed number of steps.
The Three Things That Go Wrong
Going infinite. You write a while loop and forget to update the condition. Solution: always find the line inside your while loop that changes the variable being checked. If that line doesn't exist, your loop runs forever.
Off by one. range(1, 10) gives you 1 through 9, not 1 through 10. The end number is not included. This bites everyone at least once. If your loop seems to stop one too early, add 1 to your range end.
Modifying a list while looping over it. This is a sneaky one. If you add or remove items from a list while a for loop is going through it, weird things happen. Loop over a copy instead, or collect your changes and apply them after the loop. You'll see why this matters more once you're working with data.
Try This
Create a file called loops_practice.py.
Write code that does all three of these things separately.
First: use a loop to print a multiplication table for any number you choose. So if you pick 5, it prints "5 x 1 = 5", "5 x 2 = 10" all the way to "5 x 10 = 50".
Second: use a loop to add up all even numbers between 1 and 100 and print the total.
Third: use a loop to go through this list and print only the names longer than 4 characters.
names = ["Alex", "Priya", "Sam", "Jordan", "Li", "Valentina", "Tom"]
Hints: the % operator tells you if a number is even (even numbers have zero remainder when divided by 2). The len() function tells you how long a string is.
What Comes Next
You can print 1000 items with one loop now. But what if you want to take a block of code and run it from different places in your program, with different inputs each time? That's a function. That's next.
Top comments (0)