Practical – 152 : Construct and analyze code segments that perform iteration

1. Using for Loop

🔹 Example: Print numbers 1 to 5

for i in range(1, 6):

    print(i)

🔍 Analysis:

  • range(1, 6) generates values from 1 to 5.
  • The loop runs 5 times, printing each number.
  • for is used when the number of iterations is known or countable.

2. Using while Loop

🔹 Example: Count down from 5 to 1

count = 5

while count > 0:

    print(count)

    count -= 1

🔍 Analysis:

  • Loop continues as long as the condition (count > 0) is True.
  • You must manually update the counter (count -= 1) to avoid an infinite loop.
  • while is useful when the number of iterations is unknown beforehand.

3. Looping Over a List

fruits = [“apple”, “banana”, “mango”]

for fruit in fruits:

    print(“I like”, fruit)

🔍 Analysis:

  • for loop is ideal for iterating over sequences like lists or strings.
  • Automatically accesses each item in the list.

4. Nested Loop Example

for i in range(1, 4):

    for j in range(1, 4):

        print(f”i={i}, j={j}”)

🔍 Analysis:

  • Outer loop runs 3 times; for each outer loop iteration, the inner loop runs 3 times.
  • Results in 9 total iterations.
  • Used for 2D data like matrices or grids.

5. Using break and continue

for i in range(1, 10):

    if i == 5:

        break  # Stops loop when i is 5

    if i % 2 == 0:

        continue  # Skips even numbers

    print(i)

🔍 Analysis:

  • break exits the loop early.
  • continue skips to the next iteration.
  • Output: 1, 3 (stops before reaching 5, skips even numbers).

🔚 Summary:

Loop Type

Use When

for

You know how many times to loop or you’re looping over a sequence

while

You loop until a condition becomes false

break

You want to exit the loop early

continue

You want to skip a specific iteration