Skillversitas

Loops

Loops are used to execute a block of code repeatedly. Python provides two main types of loops: for and while.

In real life, we often do things repeatedly: reading every page of a book, checking every item in a shopping cart, or counting down seconds. Loops in Python do the same thing — repeating a certain task without having to rewrite the code over and over. This saves time and makes programs more efficient.

The for loop is best used when you know exactly how many iterations are needed (for example, processing every element in a list). Meanwhile, while is more flexible — it keeps running as long as a certain condition is still met. Python also provides the break (forced stop), continue (skip an iteration), and pass (placeholder) controls to manage loop flow.

Loop Control:

  • break — stops the loop completely
  • continue — skips the current iteration
  • pass — empty statement (placeholder)

Code Example

# for loop
fruits = ["apple", "mango", "orange"]
for item in fruits:
    print(item)

# for with range()
for i in range(5):
    print(i, end=" ")  # 0 1 2 3 4

# while loop
n = 5
while n > 0:
    print(n, end=" ")  # 5 4 3 2 1
    n -= 1

# break & continue
for i in range(10):
    if i == 3: continue
    if i == 7: break
    print(i, end=" ")  # 0 1 2 4 5 6

Code Explanation

The first for loop takes each element from the fruits list and prints it one by one. This is the most common way to process data in a collection.

for i in range(5) uses the range() function, which produces the numbers 0 through 4. On each iteration, the value of i increases automatically.

The while n > 0 loop checks the condition before each iteration. As long as n is still positive, the value of n is printed and then decreased by 1. When n reaches 0, the loop stops.

The last block combines continue and break. When i == 3, continue skips that iteration (the number 3 is not printed). When i == 7, break stops the entire loop, so the numbers 7, 8, and 9 never appear.

Everyday Example

E-commerce sites use loops to process shopping carts. The total price of each item in the cart is calculated. If an item is out of stock, continue can skip it. If the total purchase exceeds a certain limit, break can stop the processing.

cart = [{"item": "Book", "price": 50000},
        {"item": "Pencil", "price": 3000}]
total = 0

for product in cart:
    total += product["price"]
    print(f"{product['item']}: ${product['price']}")

print(f"Shopping total: ${total}")

Summary

Loops make programs capable of handling repetitive tasks efficiently. Whether using for for data collections or while for dynamic conditions, loops are an essential tool that turns short code into very powerful execution capability.