I Learned About Python Loops Today

kasumbi philkasumbi phil
3 min read

As part of my Python learning journey, today was all about loops — a core concept that allows us to repeat tasks efficiently. I dove into while loops, for loops, and learned about the break and continue statements. I even got to write some small programs that helped me understand them better. Here’s a recap of what I learned!

Understanding while Loops

The while loop in Python keeps running as long as the condition is True. One key thing I learned is that:

🔑 You must initialize your loop variable before the loop starts.

That’s because the loop condition depends on it. Here's a simple example of using a while loop to print even numbers between 0 and 20:

even_numbers = 0

while even_numbers <= 20:
    print(f"even....{even_numbers}")
    even_numbers += 2

Another way to achieve the same result with a conditional check:

count = 0

while count <= 20:
    if count % 2 == 0:
        print(count)
    count += 1

Exploring for Loops

A for loop is used to iterate over a sequence — like a list, tuple, or range. Here’s how I printed even numbers from 1 to 100 using a for loop.

# Method 1: Using if condition
for i in range(100):
    if i % 2 == 0:
        print(i)

But then I learned a better way to avoid using an if:

# Method 2: Using step in range
for i in range(0, 100, 2):
    print(i)

The range(start, stop, step) function makes it super clean and efficient!

break and continue in Loops

Next, I learned about two important control statements:

  • continue: Skips the current iteration and moves to the next one.

  • break: Exits the loop entirely when a condition is met.

I applied continue in a real-world inspired task: calculating the total price of a shopping cart, which had an invalid item (a string).

Here’s the code I wrote:

cart = [10, 20, 30, "five", 70, 100]
total = 0

for item_price in cart:
    if isinstance(item_price, str):
        continue  # Skip non-numeric item
    total += item_price

print(f"The total cost is: {total}")

✅ This program loops through the cart, skips the "five" (which is a string), and calculates the total of the numeric items.

Today's lesson gave me a solid foundation in Python loops. I now understand:

  • Why initialization is key in while loops

  • How to make for loops cleaner using range()

  • The usefulness of break and continue in controlling the flow of loops

I'm excited to keep building on this and use loops confidently in real projects.

Next, I plan to dive into functions and lists, and see how they work together with loops to make programs more dynamic.

0
Subscribe to my newsletter

Read articles from kasumbi phil directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

kasumbi phil
kasumbi phil