techmore.in

Python - Loops

What: Loops in Python are control structures used to repeat a block of code multiple times until a condition is met.

Why: To reduce redundancy, perform repeated tasks efficiently, and write DRY (Don't Repeat Yourself) code.

When: Use loops when you need to perform an action repeatedly, such as iterating over a list, performing calculations, or automating tasks.

1. for Loop

The for loop is used for iterating over a sequence (like a list, tuple, dictionary, set, or string).

python
# Looping through a list numbers = [1, 2, 3, 4, 5] for num in numbers: print(num)

2. while Loop

The while loop executes a block of code as long as the condition is true.

python
# Print numbers from 1 to 5 i = 1 while i <= 5: print(i) i +=1

3. break Statement

break is used to exit the loop prematurely when a condition is met.

python
# Stop when number is 3 for i in range(1, 6): if i == 3: break print(i)

4. continue Statement

continue skips the current iteration and continues with the next one.

python
# Skip number 3 for i in range(1, 6): if i == 3: continue print(i)

5. else with Loops

else block after loop executes if loop ends normally (not via break).

python
for i in range(3): print(i) else: print("Loop finished")

Pros

s
  • Efficient iteration
  • Reduces redundancy
  • Highly readable and concise

Cons

  • Can lead to infinite loops if condition isn't updated properly
  • May be overused where vectorized solutions (NumPy, pandas) are better

Use Python loops mindfully to write efficient and readable code.