Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Loops

Loops are used in Python to execute a block of code multiple times. There are two main types of loops in Python:

  • for Loop – Used when you know how many times you want to iterate.
  • while Loop – Used when you want to run the loop as long as a condition is True.

1. for Loop

A for loop is used to iterate over a sequence (such as a list, tuple, or string).

Example 1: Using for loop with a range

for i in range(5):  # Iterates from 0 to 4
    print("Hello, World!", i)

Output:

Hello, World! 0
Hello, World! 1
Hello, World! 2
Hello, World! 3
Hello, World! 4

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

Example 2: Iterating over a list

fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits:
    print(fruit)


Output:

Apple
Banana
Cherry

2. while Loop

A while loop keeps running as long as the condition remains True.

Example: Using while loop

count = 1
while count <= 5:
    print("Count is:", count)
    count += 1  # Increments count

Output:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5

The loop stops when count exceeds 5.

Loop Control Statements

These statements help control loop execution:

  • break – Exits the loop.
  • continue – Skips the current iteration.
  • pass – Placeholder for future code.

Example 1: Using break

for i in range(10):
    if i == 5:
        break  # Stops the loop when i is 5
    print(i)

Output:

0
1
2
3
4


Example 2: Using continue

for i in range(5):
    if i == 2:
        continue  # Skips iteration when i is 2
    print(i)

Output:

0
1
3
4

Example 3: Using pass

for i in range(3):
    pass  # Placeholder, does nothing

Use pass when you have an empty loop or function that you will define later.

Conclusion

  • Use for loops when working with sequences.
  • Use while loops when running until a condition changes.
  • Use break, continue, and pass for better control.

    Leave a Reply

    Your email address will not be published.

    Need Help?