Loops in Python

Subject: Data Structures and Algorithms · Language: Python · Level: beginner · 6 min read

Learn for loop, while loop, range, nested loops, break, continue, and repeated DSA logic in Python.

Loops are used to repeat work. Many programming problems require repeated actions such as reading multiple values, printing a pattern, traversing a list, checking every character in a string, or searching for a target value.

A `for` loop is commonly used when the number of repetitions is known or when we need to visit every value in a sequence. For example, `for i in range(n)` gives indexes from `0` to `n - 1`, which is useful for list traversal.

A `while` loop is used when repetition depends on a condition. For example, while a number is greater than zero, we can keep extracting digits. The loop stops only when the condition becomes false, so the programmer must update values correctly.

Every loop needs a clear purpose. Ask what is repeated, where it starts, when it stops, and what changes after each round. These four questions help students avoid infinite loops and off-by-one errors.

The `break` statement exits the loop immediately. It is useful when the target is found and no more checking is needed. The `continue` statement skips the current iteration and moves to the next one, which is useful for ignoring unwanted values.

Loops are the heart of DSA. Arrays, strings, searching, sorting, prefix sums, frequency counting, sliding window, and two-pointer problems all depend on loops. A student who can trace loops clearly can solve many beginner and intermediate problems.

A loop is used to repeat a block of code multiple times. Instead of writing the same statement again and again, we write it once inside a loop and control how many times it should run.

Loops are one of the most important parts of programming because many problems require repeated work. Printing numbers from 1 to `n`, reading list elements, calculating a sum, searching for a value, and printing patterns all need loops.

In Python, the main loops are `for` and `while`. Python does not have a traditional `do while` loop like some other languages, but similar behavior can be created using `while True` with `break`.

for Loop

A `for` loop is commonly used when we know how many times the loop should run or when we want to visit each value in a sequence.

```python

for i in range(1, 6):

print(i)

```

Output

```text

1

2

3

4

5

```

In this loop, `range(1, 6)` produces values from 1 to 5. The ending value 6 is not included.

A `for` loop is very common in DSA because we often traverse lists, strings, and ranges of indexes.

range Function

The `range()` function creates a sequence of numbers. It is commonly used with `for` loops.

```python

range(5) # 0 to 4

range(1, 6) # 1 to 5

range(1, 10, 2) # 1, 3, 5, 7, 9

```

The third value is the step. It decides how much the number changes after each iteration.

Traversing a List

To visit each value in a list, use a `for` loop directly on the list.

```python

arr = [10, 20, 30]

for value in arr:

print(value)

```

Output

```text

10

20

30

```

Use this style when you only need values. If you need indexes, use `range(len(arr))`.

Traversing with Indexes

Indexes are needed when you want to update values, compare nearby elements, or print positions.

```python

arr = [10, 20, 30]

for i in range(len(arr)):

print(i, arr[i])

```

Output

```text

0 10

1 20

2 30

```

This pattern is useful in searching, sorting, prefix sums, and many array-style problems.

while Loop

A `while` loop repeats while a condition is true. It is useful when the number of repetitions is not fixed in advance.

```python

i = 1

while i <= 5:

print(i)

i += 1

```

Output

```text

1

2

3

4

5

```

Here, the loop continues as long as `i <= 5` is true. The update `i += 1` is important because it moves the loop toward stopping.

When to Use while Loop

Use `while` when repetition depends on a condition. Examples include reading digits of a number, moving two pointers, running until a target is found, or processing until a queue becomes empty.

In DSA, `while` is common in binary search, linked list traversal, queue processing, and two-pointer logic.

break Statement

```python

for value in arr:

if value == target:

found = True

break

```

This saves unnecessary work and makes the logic clear.

continue Statement

`continue` skips the current iteration and moves to the next one. It is useful when some values should be ignored.

```python

for value in arr:

if value < 0:

continue

print(value)

```

Sample Output when `arr = [4, -2, 7]`

```text

4

7

```

Here, negative values are skipped, and only non-negative values are printed.

Nested Loops

A nested loop means one loop inside another loop. Nested loops are used in pattern printing, matrix traversal, comparing pairs, and simple sorting algorithms.

```python

for i in range(3):

for j in range(3):

print(i, j)

```

Output

```text

0 0

0 1

0 2

1 0

1 1

1 2

2 0

2 1

2 2

```

Nested loops should be used carefully because they can increase time complexity. Two nested loops often mean O(n?) work.

Infinite Loop

An infinite loop happens when the loop condition never becomes false. This usually happens when the update is missing or incorrect.

```python

i = 1

while i <= 5:

print(i)

```

Output note

```text

This loop keeps printing 1 repeatedly because i is never updated.

```

In this example, `i` never changes, so the loop keeps running. Always make sure a `while` loop moves toward stopping.

Simulating do while

Python does not have a built-in `do while` loop. If you need a block to run at least once, use `while True` and break when needed.

```python

while True:

choice = int(input())

if choice == 0:

break

```

This style is useful for menu-driven programs.

Example Program

```python

n = int(input("Enter n: "))

total = 0

for i in range(1, n + 1):

total += i

print("Sum =", total)

print("Numbers:", end=" ")

i = 1

while i <= n:

print(i, end=" ")

i += 1

print()

```

Sample Input

```text

5

```

Output

```text

Enter n: Sum = 15

Numbers: 1 2 3 4 5

```

This program uses a `for` loop to calculate the sum from 1 to `n` and a `while` loop to print numbers from 1 to `n`.

Loops in DSA

Loops are used in almost every DSA topic. Lists need loops for traversal, strings need loops for character checking, searching uses loops to find a target, and sorting algorithms use loops for repeated comparisons.

When solving a problem, first identify what work is repeated. Then decide whether you need a `for` loop, a `while` loop, indexes, or direct values.

Loops are used when the same work must be repeated. Instead of writing the same statement many times, a loop lets us write the logic once and control how many times it runs.

A `for` loop in Python is commonly used when we already have a sequence or a range of values. For example, `for i in range(n)` runs with `i` values from `0` to `n - 1`. This pattern is very common for array indexing.

A `while` loop is useful when repetition depends on a condition, not a fixed count. For example, while reversing a number, we continue until the number becomes zero. The loop stops only when the condition becomes false.

Every loop should move toward stopping. In a `for` loop, Python moves through the sequence automatically. In a `while` loop, the programmer must update the variable manually. If the update is missing, the loop may become infinite.

In DSA, loops are used for traversal, counting, searching, sorting, prefix sums, sliding windows, and two-pointer logic. Most beginner mistakes happen because the loop starts at the wrong index, ends too early, or ends too late.

Practice Question

Take a number as input and print its multiplication table from 1 to 10. Then modify the program to calculate the sum of all table values.

More Python Lessons

Browse all PrepCampus study materials