In Python (programming language), loops are used to repeat a block of code multiple times. They help automate repetitive tasks and make programs more efficient.

Python mainly provides two types of loops:

  • for loop
  • while loop

πŸ”Ή 1️⃣ The for Loop

A for loop is used to iterate over a sequence such as a list, tuple, string, or range of numbers.

Syntax

for variable in sequence:
# code to execute

Example

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

Output:

0
1
2
3
4

Here, the range(5) function generates numbers from 0 to 4.


Example: Loop Through a List

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

Output:

apple
banana
mango

πŸ”Ή 2️⃣ The while Loop

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

Syntax

while condition:
# code to execute

Example

i = 1

while i <= 5:

print(i)
i += 1

Output:

1
2
3
4
5

The loop continues until the condition i <= 5 becomes False.


πŸ”Ή Infinite Loop Example

If the condition never becomes False, the loop runs forever.

while True:
print("This will run forever")

⚠️ Infinite loops should be avoided unless intentionally used.


πŸ”Ή Using break in Loops

The break statement stops the loop immediately.

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

Output:

0
1
2
3
4

πŸ”Ή Using continue in Loops

The continue statement skips the current iteration.

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

Output:

0
1
3
4

⭐ Key Points

  • Loops allow repeating tasks automatically.
  • for loops are commonly used for iterating over sequences.
  • while loops run based on a condition.
  • break stops a loop early.
  • continue skips the current iteration.