Python loops help you execute a block of code repeatedly. Instead of writing the same statements many times, you can use loops to automate repetitive tasks.

Python provides two main types of loops: for loops and while loops. You can also use nested loops to run one loop inside another.

In this tutorial, you will learn how Python loops work, how to use them with examples, and how to understand their output.

 

What Is a Loop in Python?

A loop in Python repeats a block of code based on a condition or a sequence of items.

For example, suppose you want to print numbers from 1 to 100. Writing 100 print statements would take time. Instead, you can use a loop to print all the numbers with just a few lines of code.

Python supports these common loop structures:

  • While Loop: Repeats code while a condition remains true.

  • For Loop: Iterates over items in a sequence or other iterable.

  • Nested For Loop: Runs one for loop inside another for loop.

Let’s understand each loop with practical examples.

 

1. While Loop in Python

A while loop executes a block of code as long as its condition evaluates to True.

Python checks the condition before every iteration. When the condition becomes False, the loop stops.

Syntax of a While Loop

while condition:
    # Code to execute

The condition controls how long the loop continues. Make sure the loop can eventually stop to avoid an infinite loop.

Example: Print Numbers from 1 to 4

x = 1

while x <= 4:
    print(x)
    x = x + 1

Output:

1
2
3
4

How Does This Code Work?

  1. First, x = 1 initializes the variable.

  2. Python checks whether x <= 4 is true.

  3. The print(x) statement displays the current value.

  4. The statement x = x + 1 increases the value by one.

  5. The loop continues until x becomes 5.

  6. When x <= 4 becomes false, Python exits the loop.

When should you use a while loop?

Use a while loop when you want to repeat an operation until a condition changes. For example, it can process data until a queue becomes empty or retry an operation until a limit is reached.

 

2. For Loop in Python

A for loop iterates over items in an iterable, such as a list, tuple, string, or range.

Python assigns each item to the loop variable and executes the loop body. The loop stops when there are no more items to process.

 

Syntax of a For Loop

for variable in iterable:
    # Code to execute

Here, variable receives an item during each iteration. The iterable supplies the items to process.

 

Example: Print Numbers Using range()

for i in range(3, 6):
    print(i)

Output:

3
4
5

How Does range() Work?

The range() function generates a sequence of integers.

In range(3, 6), the starting value is 3, and the stopping value is 6. Python excludes the stopping value.

Therefore, the loop prints 3, 4, and 5.

Remember these rules:

  • range(5) generates numbers from 0 to 4.

  • range(3, 6) generates numbers from 3 to 5.

  • range(1, 11) generates numbers from 1 to 10.

 

Example: Iterate Over a List

You can also use a for loop to process list items.

fruits = ["Apple", "Banana", "Mango"]

for fruit in fruits:
    print(fruit)

Output:

Apple
Banana
Mango

In this example, the loop processes each fruit in the list. It prints one item during every iteration.

When should you use a for loop?

Use a for loop when you want to process items in a collection or repeat an operation a known number of times.

 

3. Nested For Loop in Python

A nested for loop is a for loop placed inside another for loop.

The outer loop runs its iterations. For every outer iteration, the inner loop runs through its complete sequence.

Nested loops are useful for multiplication tables, patterns, matrices, and working with two-dimensional data.

 

Example: Multiplication Tables Using Nested Loops

for i in range(1, 3):
    for j in range(1, 11):
        k = i * j
        print(k, end=" ")
    print()

Output:

1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20

How Does This Code Work?

  1. The outer loop assigns i the values 1 and 2.

  2. For each value of i, the inner loop assigns j values from 1 to 10.

  3. The statement k = i * j calculates the product.

  4. print(k, end=" ") prints each result on the same line.

  5. The final print() moves the output to the next line.

The outer loop runs twice, while the inner loop runs ten times per outer iteration. Therefore, the program calculates 20 products.

Important: range(1, 3) produces 1 and 2, not 1, 2, and 3. To include 3, use range(1, 4).

 

4. Difference Between While Loop and For Loop

Both loops repeat code, but they are useful in different situations.

FeatureWhile LoopFor Loop
Main purposeRepeat while a condition is trueIterate over an iterable
ConditionChecked before each iterationContinues while items remain
Common useRepeat until a condition changesProcess a list or sequence
Risk of infinite loopPossible if the condition never becomes falseLess common with finite iterables
Examplewhile x <= 4:for i in range(1, 5):

Choose the loop that best fits your problem. Both loops can solve many of the same tasks.

 

5. Common Mistakes When Using Python Loops

Beginners often make a few common mistakes when working with loops.

Forgetting to Update a While Loop Variable

x = 1

while x <= 4:
    print(x)

This loop never ends because x remains 1. Add x += 1 inside the loop to update the variable.

 

Misunderstanding the range() Function

for i in range(3, 5):
    print(i)

This code prints 3 and 4. It does not print 5 because the ending value is excluded.

 

Incorrect Indentation

Python uses indentation to identify the statements inside a loop.

for i in range(1, 4):
    print(i)

The print() statement belongs to the loop because it is indented.

 

Forgetting the Inner Loop’s Repetition

In a nested loop, the inner loop executes fully for each outer iteration. This behavior can produce more results than expected.

 

6. Practice Questions

Try these exercises to improve your understanding of Python loops.

  1. Write a while loop to print numbers from 1 to 10.

  2. Write a for loop to print even numbers from 2 to 20.

  3. Use a for loop to calculate the sum of numbers from 1 to 100.

  4. Write a nested loop to print the multiplication tables of 2 and 3.

  5. Use a while loop to print numbers from 10 down to 1.

  6. Iterate over a list of names and print each name.

Try solving these problems before checking your solutions. Practice will help you understand loop conditions, iteration, and indentation.

 

FAQs

What are the types of loops in Python?

Python commonly uses for loops and while loops. A nested loop is a loop placed inside another loop.

What is the difference between a for loop and a while loop?

A for loop iterates over an iterable. A while loop repeats as long as its condition remains true.

What is a nested loop in Python?

A nested loop is a loop inside another loop. For example, a for loop inside another for loop is a nested for loop.

What does range() do in Python?

The range() function generates a sequence of integers. Its stopping value is excluded from the sequence.

Can a while loop run forever?

Yes. A while loop can become infinite if its condition never becomes false. You can prevent this by updating variables or using an appropriate stopping condition.