Python Loops

Python loops are used to execute a block of code repeatedly. There are two primary types of loops in Python:

  • for loop
  • while loop

Why Use Loops?

Loops help reduce code repetition by allowing a block of code to run multiple times under a condition. You use them when you want to iterate over sequences (lists, strings, tuples, dictionaries, sets) or repeat a task until a condition is met.

Python for Loop

The for loop is used to iterate over a sequence.

Syntax:

for variable in sequence:
   # code block

Example:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
   print(fruit)

Output:

apple
banana
cherry

You can also use range() with a for loop:

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

Output:

0
1
2
3
4

Python while Loop

The while loop runs as long as a condition is True.

Syntax:

while condition:
   # code block

Example:

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

Output:

1
2
3
4
5

Loop Control Statements

Python provides control statements to modify loop behavior.

1. break – Exit the loop:

for i in range(10):
   if i == 5:
       break
   print(i)

Output:

0
1
2
3
4

2. continue – Skip to the next iteration:

for i in range(5):
   if i == 2:
       continue
   print(i)

Output:

0
1
3
4

3. pass – Do nothing (placeholder):

for i in range(3):
   pass  # Used when the loop is required syntactically but no action is needed

Nested Loops

You can place one loop inside another.

for i in range(3):
   for j in range(2):
       print(f"i={i}, j={j}")

Output:

i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1

else with Loops

Python allows an optional else clause after loops, which executes when the loop ends normally (no break).

for i in range(3):
   print(i)
else:
   print("Loop completed!")

Output:

0
1
2
Loop completed!

Loop Exercises

Try solving these:

  1. Print numbers from 1 to 10 using a while loop.
  2. Print even numbers between 1 and 20 using a for loop.
  3. Use a for loop to iterate through a dictionary and print key-value pairs.
  4. Use nested loops to print a pattern like:

Summary

Loop TypeDescription
forIterates over a sequence
whileRuns while condition is true
breakExits the loop early
continueSkips current iteration
passPlaceholder, does nothing
elseExecutes if loop ends normally