close menu
Loops-in-Programming--for-Loop---while-Loop Loops in Programming for Loop while Loop

Loops in Programming for Loop while Loop

13 February 2025

 Loops in Programming  for Loop   while Loop


Loops in Programming: for Loop & while Loop

Loops are used to execute a block of code multiple times until a specific condition is met. The two most commonly used loops in programming are for loops and while loops.

1. for Loop
The for loop is used when the number of iterations is know in advance. it iterates over sequences like lists, tuples, strings, or ranges.

Synatx :
for variable in sequence:
   # Code to execute in each iteration

Example: Iterationg Through a List 
fruits = ["Apple", "Banana", "Cherry"]

for fruit in fruits:
   print(fruit)

Output:
Apple  
Banana  
Cherry  

Example : Using range() in a for Loop
for i in range(1, 6):  # Iterates from 1 to 5
   print(i)

Output: 
1  
2  
3  
4  
5  

2. while Loop
The while loop is used when the number of iterations is not known beforehand and execution depends on a condition being True.

Synatx:
while condition:
   # Code to execute as long as the condition is true

Example: Counting Down Using a while Loop
count = 5

while count > 0:
   print(count)
   count -= 1  # Decrementing the counter

Output:
5  
4  
3  
2  
1  

Key Differences Between for and while Loops

Feature: Usage 
for Loop: Used when the number of iterations is known
while Loop: Used when the number of iteration is unknown

Feature: Condition
for Loop: Iterates over a sequence or range
while Loop: Runs until a specified condition becomes False

Feature: Example Use Case 
for Loop: Looping through a list or range 
while Loop: Running a program until a user exits

Both loops are fundamental for iteration, and choosing the right one depends on the specific problem being solved.

Whatsapp logo