HomePYTHON🔁 Loops in Python

🔁 Loops in Python

Loops in Python

Loops are used to execute a block of code repeatedly as long as a condition is true or until a specific number of times.

🧠 Types of Loops in Python:

  1. for loop
  2. while loop
  3. Nested loops
  4. loop control statementsbreak, continue, pass

1️⃣ for Loop

✅ Definition:

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

🔹 Syntax:

for variable in sequence:
    # code block

✅ Example 1: Loop through a list

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

✅ Example 2: Use with range()

for i in range(5):
    print(i)
    
   // Output: 0 1 2 3 4

2️⃣ while Loop

✅ Definition:

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

🔹 Syntax:

while condition:
    # code block

✅ Example:

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

3️⃣ Nested Loops

✅ Definition:

A loop inside another loop.

✅ Example:

for i in range(3):
    for j in range(2):
        print(f"i={i}, j={j}")

🔃 Loop Control Statements

break

Used to exit the loop early.

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

continue

Skips the current iteration.

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

pass

Does nothing (used as a placeholder).

for i in range(3):
    pass  # Just a placeholder

🔂 Loop with else

else with for or while:

Executes only if the loop is not terminated by break.

for i in range(3):
    print(i)
else:
    print("Finished without break.")

🔍 Real-World Example: Sum of Even Numbers

sum = 0
for i in range(1, 11):
    if i % 2 == 0:
        sum += i
print("Sum of even numbers:", sum)

🔁 Summary Table:

Loop TypeWhen to UseCan Use Else?Control Statements
forIterating over sequences✅ Yesbreak, continue, pass
whileWhen the number of iterations is unknown✅ Yesbreak, continue, pass
NestedComplex patterns (grids, matrices)✅ Yesbreak, continue, pass

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *