Skip to content

Loops

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

  1. For Loop: Used to iterate over a sequence (such as a list, tuple, or string) or other iterable objects.
  2. While Loop: Used to execute a block of code as long as a given condition is True.

1. For Loop

A for loop iterates over a sequence (such as a list, string, or range) and runs the block of code for each item in that sequence.

Syntax:

python
for item in iterable:
    # Code to execute for each item

Example:

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

Output:

apple
banana
cherry

You can also use the range() function with a for loop to repeat a block of code a specific number of times.

Example:

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

Output:

0
1
2
3
4

2. While Loop

A while loop repeatedly executes a block of code as long as the given condition is True.

Syntax:

python
while condition:
    # Code to execute as long as condition is True

Example:

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

Output:

0
1
2
3
4

Common Loop Control Statements:

  • break: Exits the loop entirely.
  • continue: Skips the current iteration and moves to the next one.
  • else: A block of code that runs if the loop completes normally (not terminated by break).

Example with break and continue:

python
for i in range(10):
    if i == 5:
        break  # Stop the loop when i is 5
    if i % 2 == 0:
        continue  # Skip even numbers
    print(i)

Output:

1
3

J2J Institute private limited