Introduction

Loops are used in Python to repeatedly execute a block of code. In this guide, we'll explore two types of loops: for and while, and how they allow you to automate repetitive tasks in your code.


The For Loop

The for loop is used to iterate over a sequence (such as a list, tuple, or string) or other iterable objects. It executes a block of code for each item in the sequence. For example:

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

The While Loop

The while loop is used to repeatedly execute a block of code as long as a specified condition is true. For example:

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

Loop Control Statements

Python provides loop control statements to modify the behavior of loops. Common ones include:

  • break: Terminates the loop prematurely.
  • continue: Skips the current iteration and continues to the next one.

For example:

numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
break
print(num)
for num in numbers:
if num == 3:
continue
print(num)

Nested Loops

You can nest loops inside other loops to create complex iteration patterns. For example:

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

Conclusion

Loops are a fundamental concept in programming, and in Python, they are used to automate repetitive tasks. The for and while loops, along with control statements, give you the tools to efficiently iterate over data and execute code multiple times.