Spex3
    

Loops in Python: for and while Loops 🔁


    

    

Loops allow you to repeat a block of code multiple times, making programs more efficient and reducing repetition. Python has two main types of loops:

✅ for loop – Used for iterating over a sequence (like a list, tuple, or string).
✅ while loop – Repeats as long as a condition is True.

1️⃣ for Loop

Used to iterate over sequences (lists, strings, ranges, etc.).

🔹 Example: Looping Through a List



fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
print(fruit)

Output:



apple
banana
cherry

🔹 Looping Through a String


for letter in "Python":
print(letter)

Output:



P
y
t
h
o
n


🔹 Using range() in a for Loop
The range() function generates a sequence of numbers.




for i in range(5): # Loops from 0 to 4
print(i)

Output:



0
1
2
3
4


Different Ways to Use range()


for i in range(2, 10, 2): # (start, stop, step)
print(i)


Output:



2
4
6
8


2️⃣ while Loop

Repeats as long as the condition is True.

🔹 Example: Using a while Loop




count = 0

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


Output:



Count: 0
Count: 1
Count: 2
Count: 3
Count: 4


3️⃣ Loop Control Statements

Python provides special statements to control loop execution.

🔹 break Statement (Exit Loop)
Used to stop the loop when a condition is met.



for num in range(1, 10):
if num == 5:
break # Stop the loop when num is 5
print(num)


Output:



1
2
3
4


🔹 continue Statement (Skip an Iteration)
Skips the current iteration and moves to the next one.



for num in range(1, 6):
if num == 3:
continue # Skip when num is 3
print(num)


Output:



1
2
4
5


🔹 else with Loops
An else block runs when the loop completes normally (without break).



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



0
1
2
Loop finished!


    Date: 2025-03-22 00:00:00.000000