Loops in Python | Python Course | Dataplexa

Loops in Python

Imagine you need to send a welcome email to 10,000 new users. Writing the same code 10,000 times is obviously impossible. This is where loops come in. A loop is a way to tell Python to repeat a block of code automatically — for as many times as you need.

Loops are one of the most powerful tools in programming. They let you process lists of data, count through numbers, read files line by line, and automate repetitive tasks that would otherwise take forever to write manually.

The Problem Loops Solve

Without loops, printing numbers 1 to 5 looks like this:

print(1)
print(2)
print(3)
print(4)
print(5)

That works for 5 numbers. But what if you need to print 1 to 1,000? Or process 50,000 customer records? That is where loops become essential — they repeat the same instruction automatically for as many steps as you define.

The for Loop

A for loop repeats a block of code once for each item in a sequence. When the sequence runs out of items, the loop stops. It is the most common type of loop in Python because you often need to process collections of data one item at a time.

for i in range(1, 6):
    print(i)
1 2 3 4 5
  • range(1, 6) generates the numbers 1, 2, 3, 4, 5 — it starts at 1 and stops before 6.
  • i is the loop variable. It holds the current number during each repetition.
  • The indented line runs once for each number in the range.

Understanding the range() Function

range() is a built-in function that generates a sequence of numbers. It has three forms:

ExpressionMeaningNumbers Produced
range(5)Start from 0, stop before 50 1 2 3 4
range(1, 5)Start from 1, stop before 51 2 3 4
range(1, 10, 2)Start 1, stop 10, step by 21 3 5 7 9
# Counting by 2s from 0 to 10
for num in range(0, 11, 2):
    print(num)
0 2 4 6 8 10

Looping Through a List

One of the most common uses of a for loop is going through every item in a list. Instead of accessing each item manually by its index number, the loop does it for you automatically.

courses = ["Python", "SQL", "AI"]

for course in courses:
    print("Now learning:", course)
Now learning: Python Now learning: SQL Now learning: AI
  • The loop variable course holds one item from the list on each repetition.
  • You do not need to know how many items are in the list — the loop handles that automatically.
  • This pattern is used constantly in data processing, report generation, and automation.

The while Loop

A while loop keeps repeating as long as a condition remains True. Unlike the for loop, it does not go through a fixed sequence — it just keeps going until something changes and makes the condition False.

count = 1

while count <= 5:
    print(count)
    count += 1    # increases count by 1 each time
1 2 3 4 5
  • The loop checks count <= 5 before each repetition.
  • When count becomes 6, the condition is False and the loop stops.
  • The line count += 1 is critical — without it, count would never change and the loop would run forever.

Avoiding Infinite Loops

An infinite loop is a while loop where the condition never becomes False. Python keeps running it forever until you force the program to stop. This is one of the most common beginner mistakes with while loops.

# WARNING — do not run this as-is
# This loop never stops because count never changes

count = 1
while count <= 5:
    print(count)
    # forgot to write: count += 1

Always make sure your while loop has something inside it that will eventually make the condition False. The most common way is to update a counter variable each time the loop runs.

The break Statement

break immediately stops the loop and exits it, even if there are still more items or the condition is still True. It is used when you find what you are looking for and no longer need the loop to continue.

for num in range(1, 10):
    if num == 5:
        break       # stop the loop when we reach 5
    print(num)
1 2 3 4
  • The loop was set to go from 1 to 9, but it stopped at 4 because break fired when num reached 5.
  • A real-world use: searching through a list of users and stopping as soon as you find the one you need.

The continue Statement

continue skips the rest of the current loop step and jumps straight to the next one. The loop does not stop — it just skips that one iteration and moves on.

for num in range(1, 6):
    if num == 3:
        continue    # skip number 3, keep going
    print(num)
1 2 4 5
  • Number 3 was skipped because continue jumped over the print line for that iteration.
  • A real-world use: processing a list of items but skipping ones that are invalid or already handled.

Nested Loops

A nested loop is simply a loop inside another loop. The inner loop completes all its repetitions for each single step of the outer loop. This is useful for working with grids, tables, or any data that has rows and columns.

for i in range(1, 4):
    for j in range(1, 4):
        print(i, j)
1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3
  • The outer loop sets i to 1, then the inner loop runs completely through 1, 2, 3.
  • Then the outer loop moves to 2, and the inner loop runs again from the start.
  • Nested loops are used for multiplication tables, seating charts, image grids, and matrix operations.

Real World Example — Sales Total Calculator

This is one of the most practical uses of a loop. A business needs to add up all their daily orders to get a total. Instead of adding each one manually, a loop does it automatically no matter how many orders there are.

orders = [250, 450, 300, 150, 800, 120]

total_sales = 0

for order in orders:
    total_sales += order    # add each order to the running total

print("Total Sales:", total_sales)
Total Sales: 2070
  • total_sales starts at 0 and grows with each order added.
  • The loop processes all 6 orders automatically without any manual addition.
  • If the orders list had 10,000 items, the exact same code would still work perfectly.

for Loop vs while Loop — When to Use Each

Both loops repeat code, but they are suited to different situations:

  • Use a for loop when you know the number of repetitions in advance, or when you are going through a list, range, or collection.
  • Use a while loop when repetition depends on a condition that changes over time — like waiting for user input, retrying a failed connection, or running until a target is reached.

Common Loop Mistakes

  • Forgetting to update the counter in a while loop — causes an infinite loop.
  • Off-by-one errorsrange(5) gives 0–4, not 1–5. Use range(1, 6) if you need 1–5.
  • Modifying a list while looping through it — this can cause items to be skipped or processed twice. Loop through a copy instead.
  • Confusing break and continuebreak exits the whole loop, continue only skips the current step.

Practice

Which loop type is used to go through a list or a range of numbers?



Which loop type keeps running as long as a condition is True?



Which keyword immediately stops a loop and exits it?



Which keyword skips the current loop step and moves to the next one?



Quick Quiz

Does range(5) include the number 5?




Which statement exits a loop completely?





A loop placed inside another loop is called what?





NEXT UP
Strings in Python
Learn how Python handles text — from indexing individual characters and slicing substrings to using built-in string methods to transform and format your data.