Loops in Python

Loops in Python are used when we want to repeat a block of code multiple times without writing it again and again.

Python mainly provides two types of loops:

  • for loop
  • while loop

Article Algo

1. for Loop

The for loop is used when we already know how many times a loop should run. It works by iterating over a sequence such as a list, tuple, string, or range.

Example

for i in range(1, 6): print(i)

Explanation

  • range(1, 6) generates numbers from 1 to 5.
  • Variable i takes one value at a time from the range.
  • print(i) runs once for each value of i.
  • The loop stops automatically when the range ends.

Article Algo

2. for Loop with List

A for loop can also be used to access elements of a list.

Example

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

Explanation

  • fruits is a list.
  • fruit stores one item from the list in each iteration.
  • The loop prints every fruit one by one.
  • No index is required to access list elements.

Article Algo

3. while Loop

The while loop is used when we do not know how many times the loop will run. It continues executing as long as the condition remains True.

Example

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

Explanation

  • The loop starts with count = 1.
  • The condition count <= 5 is checked before each iteration.
  • count += 1 increases the value of count.
  • When count becomes greater than 5, the loop stops.

Article Algo

4. Infinite while Loop

If the condition in a while loop never becomes false, the loop runs forever. This is called an infinite loop.

Example

while True: print("Hello")

Explanation

  • True never becomes false.
  • The loop keeps running continuously.
  • This type of loop should be used carefully.

Article Algo

5. Loop Control Statements

Python provides special statements to control loop execution.

a) break Statement

The break statement is used to stop the loop immediately.

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

Explanation:

  • The loop runs normally until i becomes 5.
  • When i == 5, break stops the loop.
  • Numbers after 4 are not printed.

b) continue Statement

The continue statement skips the current iteration.

for i in range(1, 6): if i == 3: continue print(i)

Explanation:

  • When i is 3, printing is skipped.
  • The loop continues with the next value.
  • All numbers except 3 are printed.

c) pass Statement

The pass statement does nothing and is used as a placeholder.

for i in range(5): pass

Explanation:

  • The loop runs 5 times.
  • No action is performed.
  • Used when logic is not written yet.

Article Algo

Final Note

Loops help reduce code repetition, improve readability, and make programs efficient.

Understanding for and while loops is essential for writing real-world Python programs.

Article Algo