πŸ” 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 statements – break, 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
No comments yet! You be the first to comment.

Leave a Reply

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