Loops

Learn how loops work in Python using for and while statements, with examples for range(), nested loops, and control statements like break and continue.

Loading...
Loops

What Are Loops?

Loops let us run a block of code multiple times.

For example, if you want to print numbers from 1 to 5, you could write:

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

But what if you wanted to print numbers from 1 to 1000?

Writing every print() manually would take a lot of time.

That’s where loops are useful.

The for Loop

A for loop lets you go through each item in a sequence one at a time.

For example, we can loop through a string:

name = "Python"
 
for letter in name:
    print(letter)
 
# Output:
 
# P
# y
# t
# h
# o
# n

Python takes one character at a time from the string and stores it in the variable letter.

You can think of it like this:

First loop  → P
Second loop → y
Third loop  → t
Fourth loop → h
Fifth loop  → o
Sixth loop  → n

The loop stops when there are no more characters.

The Variable Name Can Be Anything

In this example:

for letter in name:
    print(letter)

letter is just a variable name.

You could call it character:

for character in name:
    print(character)

It works the same way.

The general structure is:

for variable in sequence:
    # Code to repeat

Using range()

Now, what if you don’t want to loop through a string?

And, what if you simply want to repeat something a specific number of times?

That’s where the range() function is useful.

For example:

for number in range(5):
    print(number)
 
# Output:
 
# 0
# 1
# 2
# 3
# 4

Notice that it starts at 0 and stops before 5.

So range(5) gives us 0, 1, 2, 3, 4.

It does not include 5.

Starting From a Different Number

You can also tell range() where to start.

for number in range(5, 10):
    print(number)
 
# Output:
 
# 5
# 6
# 7
# 8
# 9

Here range(5, 10) means:

  • Start at 5
  • Stop before 10

Using a Step

You can also tell range() how much to increase by each time.

for number in range(5, 10, 2):
    print(number)
 
# Output:
 
# 5
# 7
# 9

Here range(5, 10, 2) means:

  • Start at 5
  • Stop before 10
  • Increase by 2 each time

So the values are:

5 → 7 → 9

Counting Backward

The step can also be negative.

A negative step makes range() count downward instead of upward:

for number in range(10, 0, -1):
    print(number)
 
# Output:
 
# 10
# 9
# 8
# 7
# 6
# 5
# 4
# 3
# 2
# 1

Here range(10, 0, -1) means:

  • Start at 10
  • Stop before 0
  • Decrease by 1 each time

A negative step is useful when you need to count backward.

range() Syntax

The general syntax is:

range(start, stop, step)

All three values don’t have to be provided.

range(stop)

range(5)

Starts from 0 and stops before 5.

range(start, stop)

range(5, 10)

Starts from 5 and stops before 10.

range(start, stop, step)

range(5, 10, 2)

Starts from 5, stops before 10, and increases by 2.

A Simple Example

Let’s use a for loop to print a message five times:

for number in range(5):
    print("Hello")
 
# Output:
 
# Hello
# Hello
# Hello
# Hello
# Hello

The variable number isn’t being used here, but the loop still runs five times.

Using range() With len()

You can combine range() with len() when you need both the index and the character at that position.

For example:

name = "Python"
 
for i in range(len(name)):
    print(i, name[i])
 
# Output:
 
# 0 P
# 1 y
# 2 t
# 3 h
# 4 o
# 5 n

Here, len(name) gives us the number of characters in the string, which is 6.

Then range(len(name)) gives us the indexes: 0, 1, 2, 3, 4, 5

We can use each index to access the corresponding character: name[i]

This gives you both the index and the character at that position.

This pattern is useful when you need to know where something is, not just what the value is.

For simply going through each character, you can still use:

for character in name:    
    print(character)

You don’t need indexes unless you actually need them.

Now, what if you don’t know exactly how many times you want the loop to run?

That’s where while loops come in.

What Is a while Loop?

A while loop repeats a block of code as long as a condition is True.

Here’s the basic syntax:

while condition:
    # code to repeat

For example:

count = 1
 
while count <= 5:
    print(count)
    count += 1
 
# Output:
 
# 1
# 2
# 3
# 4
# 5

The loop checks the condition before each repetition:

  • Is count <= 5? Yes → run the code.
  • Increase count by 1.
  • Check again.
  • Keep repeating while the condition is True.
  • When count becomes 6, the condition is False, so the loop stops.

Why Do We Need to Update the Variable?

Look at this example:

count = 1
 
while count <= 5:
    print(count)
    count += 1

The line: count += 1 is important.

It changes the value of count each time the loop runs.

Without it:

count = 1
 
while count <= 5:
    print(count)

count will always remain 1.

The condition count <= 5 will always be True, so the loop will keep running.

This is called an infinite loop.

Tip: If you accidentally create an infinite loop while testing, press Ctrl + C in the terminal to stop it.

while Loop With User Input

while loops are useful when you want to keep asking the user for something until a condition is met.

For example:

password = ""
 
while password != "python":
    password = input("Enter the password: ")
 
print("Access granted!")

This keeps asking for the password for as long as the user enters the wrong one. Once they type python, the condition becomes False and the loop stops.

while vs for

So when should you use a for loop and when should you use a while loop?

for loop

Use a for loop when you usually know what you’re looping over or how many times you want to repeat something.

for number in range(5):
    print(number)

while loop

Use a while loop when you want to keep repeating something until a condition becomes False.

number = 0
 
while number < 5:
    print(number)
    number += 1

Both examples produce similar results, but they work differently.

A Simple Example

Let’s print numbers from 1 to 10 using a while loop:

number = 1
 
while number <= 10:
    print(number)
    number += 1

The important parts are:

  • number = 1: This gives us the starting value.
  • while number <= 10: This tells Python when to continue the loop.
  • number += 1: This changes the value so the loop can eventually stop.

So far, we learned about while loops and how they repeat code while a condition is True.

But sometimes, you don’t want a loop to continue normally.

You may want to:

  • stop the loop completely
  • skip the current iteration and continue with the next one

That’s where break and continue come in.

The break Statement

The break statement stops a loop immediately.

For example:

for number in range(1, 11):
    if number == 5:
        break
 
    print(number)
 
# Output:
 
# 1
# 2
# 3
# 4

When number becomes 5, the if condition becomes True.

The break statement then stops the loop.

The numbers after 5 are never printed.

How It Works

The loop starts normally:

1 → print
2 → print
3 → print
4 → print
5 → break

Once break runs, Python exits the loop completely.

break With a while Loop

You can also use break inside a while loop.

number = 1
 
while number <= 10:
    if number == 5:
        break
 
    print(number)
    number += 1
 
# Output:
 
# 1
# 2
# 3
# 4

Even though the loop condition is number <= 10 the loop stops when number reaches 5 because of break.

A Common while True Pattern

As we saw above that an infinite loop can happen when the condition of a while loop never becomes False.

But an infinite loop isn’t always a mistake.

A very common pattern is to intentionally use while True and then use break when you want to stop the loop.

For example:

while True:
    answer = input("Type 'exit' to quit: ")
 
    if answer == "exit":
        break
 
    print("You typed:", answer)

Here, while True means the loop will keep running.

The loop only stops when the user types "exit".

When that happens, this condition becomes True:

if answer == "exit":

Then break stops the loop.

We treated infinite loops as something to avoid above. But while True combined with break is actually a common, intentional pattern. It keeps running until a specific condition inside the loop tells it to stop.

You’ll see this pattern often when building programs that need to keep asking for input until the user chooses to quit.

The continue Statement

The continue statement works differently.

Instead of stopping the whole loop, it skips the current iteration and moves to the next one.

For example:

for number in range(1, 6):
    if number == 3:
        continue
 
    print(number)
 
# Output:
 
# 1
# 2
# 4
# 5

When number is 3, continue skips the rest of that iteration.

The loop then continues with 4.

How It Works

1 → print
2 → print
3 → skip
4 → print
5 → print

The loop itself doesn’t stop.

Only that particular iteration is skipped.

break vs continue

The easiest way to remember the difference:

Statement What it does
break Stops the entire loop
continue Skips the current iteration

What About Nested Loops?

A loop can also be placed inside another loop. This is called a nested loop.

When you use break or continue inside nested loops, they only affect the innermost loop they’re written in.

For example, if a for loop is inside another for loop, a break inside the inner loop stops the inner loop, not the outer one.

for i in range(2):
    for j in range(2):
        if i == j:
            print(f"Breaking inner loop at i={i}, j={j}")
            break
    else:
        print(f"Outer loop iteration {i} completed without breaking.")
 
# Output:
 
# Breaking inner loop at i=0, j=0
# Outer loop iteration 1 completed without breaking.

Example: Skip Even Numbers

We can use continue to skip numbers we don’t want.

for number in range(1, 11):
    if number % 2 == 0:
        continue
 
    print(number)
 
# Output:
 
# 1
# 3
# 5
# 7
# 9

Here, % gives us the remainder.

If the remainder is 0, the number is even, so continue skips it.

Example: Stop When You Find a Number

You can use break when you want to stop searching after finding something.

for number in range(1, 11):
    if number == 7:
        print("Found it!")
        break
 
    print(number)
 
# Output:
 
# 1
# 2
# 3
# 4
# 5
# 6
# Found it!

Once 7 is found, the loop stops.

else With a for Loop

Here’s a simple example:

for number in range(5):
    print(number)
else:
    print("Loop finished")
 
# Output:
 
# 0
# 1
# 2
# 3
# 4
# Loop finished

The else block runs after the loop finishes normally.

In this example, the loop goes through all the numbers, finishes, and then the else block runs.

What Happens With break?

This is where loop else becomes more interesting.

Remember, break completely stops a loop.

If a loop is stopped using break, its else block does not run.

For example:

for number in range(1, 6):
    if number == 3:
        break
 
    print(number)
else:
    print("Loop finished")
 
# Output:
 
# 1
# 2

The else block doesn’t run because the loop was stopped by break.

The Easy Way to Remember It

Think of loop else like this:

  • The loop finished normally → else runs.
  • The loop stopped because of break → else doesn’t run.

This is different from the else used with if.

else With a while Loop

You can also use else with a while loop.

number = 1
 
while number <= 3:
    print(number)
    number += 1
else:
    print("Loop finished")
 
# Output:
 
# 1
# 2
# 3
# Loop finished

The condition eventually becomes False, so the loop ends normally and the else block runs.

while + break + else

Now let’s combine what we’ve learned.

number = 1
 
while number <= 5:
    if number == 3:
        break
 
    print(number)
    number += 1
else:
    print("Loop finished")
 
# Output:
 
# 1
# 2

The loop reaches 3 and break stops it.

Because the loop didn’t finish normally, the else block is skipped.

A Practical Example

Loop else can be useful when you’re searching for something.

For example:

numbers = [1, 2, 3, 4, 5]
 
for number in numbers:
    if number == 7:
        print("Found it!")
        break
else:
    print("Number not found")
 
# Output:
 
# Number not found

The loop checks every number.

Since 7 isn’t found, the loop finishes normally, so the else block runs.

Now let’s search for 3:

numbers = [1, 2, 3, 4, 5]
 
for number in numbers:
    if number == 3:
        print("Found it!")
        break
else:
    print("Number not found")
 
# Output:
 
# Found it!

This time, break runs when 3 is found.

Because the loop stopped with break, the else block doesn’t run.

continue Doesn’t Skip the else

There’s one more important thing to remember.

continue does not prevent the loop’s else block from running.

For example:

for number in range(5):
    if number == 2:
        continue
 
    print(number)
else:
    print("Loop finished")
 
# Output:
 
# 0
# 1
# 3
# 4
# Loop finished

The continue only skips the current iteration.

The loop still finishes normally, so else runs.

break vs continue vs else

Here’s a quick comparison:

Statement What happens
break Stops the loop completely
continue Skips the current iteration
Loop else Runs when the loop finishes normally

The important connection is:

Loop finishes normally → else runs
Loop stops with break   → else doesn't run
continue                → loop keeps going

Do You Need Loop else?

You don’t have to use loop else in every program.

It’s a Python feature that can be useful, especially when you’re searching for something and want to do something when the search finishes without finding a match.

If you’re just starting out, the most important thing to remember is: Loop else runs when the loop finishes without hitting break.


👉 Next tutorial: Python Functions