Day 4: Loops in Python

Day 4: Loops in Python

·

2 min read

Loops are used to repeat instructions

  1. while loops

  2. for loops

While loop

The while loop is a control flow statement that allows you to execute a block of code repeatedly as long as a given condition is True. It is particularly useful when the number of iterations is not known in advance and depends on a condition being met.

#While syntax
while condition:
    # Code block to execute

#Example:
count = 1
while count <= 5:
    print("hello")
    count += 1

condition: This is a boolean expression that is evaluated before each iteration. If it evaluates to True, the loop executes the code block. If False, the loop terminates.

Loop Control Statements

Python provides control statements to modify loop behavior:

  • break – Exit the loop immediately.

  • continue – Skip the current iteration and move to the next.

  • pass – Placeholder for future code.

Think of it as a “do nothing” statement that allows your program to move past that point without error.

Why Use pass?

1. Empty Code Blocks: In Python, blocks of code (like in functions, loops, conditionals, etc.) cannot be empty.

If you try to leave them empty, Python will raise an IndentationError. The pass statement can be used as a placeholder to avoid such errors.

2. Code Stubbing: When writing or designing a program, you might want to outline the structure without actually implementing the logic.

You can use pass to temporarily fill in code blocks.

#Example: Using break to stop early
for number in range(10):
    if number == 5:
        break  # Stop loop when number is 5
    print(number)

#Example: Using continue to skip an iteration
for number in range(5):
    if number == 2:
        continue  # Skip number 2
    print(number)

#Example for pass statement
x = 5
if x > 0:
    pass # Placeholder for future code
else:
    print("Hello")

For Loop

A for loop is used when we need to iterate over a sequence (list, tuple, string, dictionary, or range).

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

Nested Loops

Loops inside loops can be powerful for working with multidimensional data.

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