Python Loops

Repeat tasks with for loops and while loops.

Imagine you need to display the message Welcome to DevBrainBox ten times. Writing the same print() statement ten times would make the code long and repetitive.

A loop provides a better solution by repeating the same block of code without writing it again and again. Loops save time, reduce errors, and make programs easier to maintain.

In this lesson, you will learn what loops are, why they are useful, and how to use Python's two main loop types: for loops and while loops.

What is a Loop?

A loop is a programming structure that repeatedly executes a block of code until a condition is met or all items in a sequence have been processed.

  • Displaying a message multiple times
  • Processing items in a list
  • Reading data from a file
  • Performing repeated calculations
  • Creating patterns or tables

Without loops, these tasks would require writing the same code many times.

The for Loop

Use a for loop when you know how many times a task should repeat or when you want to process every item in a collection.

Syntax

python
for variable in sequence:
    # Code to execute
    pass

Example

python
for i in range(5):
    print("Welcome to DevBrainBox")

Output

text
Welcome to DevBrainBox
Welcome to DevBrainBox
Welcome to DevBrainBox
Welcome to DevBrainBox
Welcome to DevBrainBox

range(5) generates numbers from 0 through 4, causing the loop to run five times.

Using range()

The range() function generates a sequence of integers and is commonly used with for loops. Its stopping value is excluded.

range(stop)

python
for i in range(5):
    print(i)

Output

text
0
1
2
3
4

range(start, stop)

python
for i in range(1, 6):
    print(i)

Output

text
1
2
3
4
5

range(start, stop, step)

python
for i in range(2, 11, 2):
    print(i)

Output

text
2
4
6
8
10

The third argument specifies the step between generated numbers.

Looping Through a String

A for loop can process a string one character at a time.

python
word = "Python"

for letter in word:
    print(letter)

Output

text
P
y
t
h
o
n

Looping Through a List

Loops are often used to process collections such as lists. This is easier and more flexible than accessing each item manually.

python
fruits = ["Apple", "Banana", "Orange"]

for fruit in fruits:
    print(fruit)

Output

text
Apple
Banana
Orange

The while Loop

A while loop repeats as long as its condition remains true.

Syntax

python
while condition:
    # Code to execute
    pass

Example

python
count = 1

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

Output

text
1
2
3
4
5

count increases after each iteration. Once it becomes greater than 5, the condition is false and the loop stops.

Infinite Loops

If a while condition never becomes false and no other statement exits the loop, it runs indefinitely.

python
count = 1

while count > 0:
    print(count)

This loop never ends because count is never changed. Always ensure a while loop has a condition that can eventually become false or a deliberate exit path.

Loop Control Statements

break

break immediately exits the nearest active loop.

python
for number in range(1, 10):
    if number == 5:
        break
    print(number)

Output

text
1
2
3
4

continue

continue skips the rest of the current iteration and moves to the next one.

python
for number in range(1, 6):
    if number == 3:
        continue
    print(number)

Output

text
1
2
4
5

pass

pass is a placeholder that performs no action. It is useful when a syntactically valid loop body is needed temporarily.

python
for number in range(3):
    pass

print("Loop completed.")

Nested Loops

A loop inside another loop is a nested loop. For every outer-loop iteration, the inner loop runs through its sequence. Nested loops are useful for tables, grids, combinations, and patterns.

python
for i in range(1, 4):
    for j in range(1, 3):
        print(i, j)

Output

text
1 1
1 2
2 1
2 2
3 1
3 2

Choosing Between for and while

LoopUse It When
forProcessing a sequence or repeating a known range of times
whileRepetition depends on a condition that changes during execution

Choosing the appropriate loop makes code easier to understand and maintain.

Key Takeaways

  • Loops repeat code without duplication.
  • Python provides for and while loops.
  • for loops commonly work with range(), lists, strings, and other iterables.
  • while loops continue until their condition becomes false.
  • break exits a loop immediately.
  • continue skips the current iteration and moves to the next one.
  • pass acts as a placeholder when no action is needed.
  • Nested loops allow one loop to run inside another.
  • Ensure while-loop conditions can eventually become false to avoid unintended infinite loops.
  • Loops are essential for writing efficient, clean, and reusable Python programs.
Let's learn with DevBrainBox AI