Skip to main content

Command Palette

Search for a command to run...

🌀 Python Part 4 : Mastering Loops in Python – The 'for' Loop and the 'while' Loop

Updated
5 min readView as Markdown

If you’ve ever wanted your program to repeat a task — like greeting multiple people, counting items, or processing data — you’ll need loops. Python makes this easy with two main types of loops: for and while. In this post, we’ll dive into the powerful and beginner-friendly for loop.


🔁 What is a for Loop?

A for loop lets you repeat code for each item in a collection (like a list, string, or range of numbers).

✅ Basic Syntax:

for item in collection:
    # do something

🍎 Example 1: Loop Through a List

fruits = ["apple", "banana", "mango"]

for fruit in fruits:
    print("I like", fruit)

📤 Output:

I like apple  
I like banana  
I like mango

🔤 Example 2: Loop Through a String

for char in "hello":
    print(char)

📤 Output:

h  
e  
l  
l  
o

🔢 Example 3: Use range() for Repetition

The range() function is great when you want to repeat something a specific number of times.

for i in range(3):
    print("Hi", i)

📤 Output:

Hi 0  
Hi 1  
Hi 2

🧠 Deeper Dive: Advanced for Loop Patterns

1️⃣ range(start, stop, step)

for i in range(1, 11, 2):
    print(i)

📤 Output: 1 3 5 7 9


2️⃣ enumerate() – Get index and value

colors = ["red", "green", "blue"]

for index, color in enumerate(colors):
    print(f"Color {index} is {color}")

📤 Output:

Color 0 is red  
Color 1 is green  
Color 2 is blue

3️⃣ zip() – Loop through multiple lists

names = ["Alice", "Bob"]
scores = [90, 85]

for name, score in zip(names, scores):
    print(f"{name} scored {score}")

📤 Output:

Alice scored 90  
Bob scored 85

4️⃣ List Comprehension

A compact way to build lists inside a loop.

squares = [x**2 for x in range(1, 6)]
print(squares)

📤 Output:

[1, 4, 9, 16, 25]

5️⃣ Nested for Loops (Grid-Like Structures)

for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i} x {j} = {i*j}")

📤 Output:

1 x 1 = 1  
1 x 2 = 2  
...  
3 x 3 = 9

🔁 Mastering Loops in Python – The while Loop

We explored the for loop — great for looping through lists, strings, and known ranges. Now let’s explore its more flexible sibling: the while loop. This is your go-to tool when you don’t know ahead of time how many times to repeat something.


🔍 What is a while Loop?

A while loop repeats code as long as a condition is true.

✅ Basic Syntax:

while condition:
    # do something

If the condition is True, the code inside runs. Once it’s False, the loop ends.


🔢 Example 1: Count from 1 to 5

i = 1
while i <= 5:
    print(i)
    i += 1

📤 Output:

1  
2  
3  
4  
5

🔐 Example 2: Ask for a Password

password = ""

while password != "secret":
    password = input("Enter the password: ")

print("Access granted!")

📤 Output (user must type 'secret' to exit):

Enter the password: test  
Enter the password: secret  
Access granted!

🛑 Watch Out for Infinite Loops!

If the condition never becomes false, your loop will run forever.

while True:
    print("This will never stop unless you use 'break'")

Use with care, or it might freeze your program!


🚪 Example 3: Use break to Exit Early

while True:
    name = input("Enter your name (type 'exit' to stop): ")
    if name == "exit":
        break
    print("Hello,", name)

📤 Output:

Enter your name: Alice  
Hello, Alice  
Enter your name: exit

🔄 Example 4: Use continue to Skip

i = 0

while i < 10:
    i += 1
    if i % 2 == 0:
        continue  # Skip even numbers
    print(i)

📤 Output:

1  
3  
5  
7  
9

✅ Real-World Pattern: Validate Input

age = input("Enter your age: ")

while not age.isdigit():
    print("❌ Please enter a valid number.")
    age = input("Enter your age: ")

print("Your age is", age)

📤 Output:

Enter your age: abc  
❌ Please enter a valid number.  
Enter your age: 25  
Your age is 25

📋 Summary: When to Use while

Use CaseUse while if...
You don’t know how many times to loope.g., waiting for correct password
You want to run a loop until a conditione.g., user chooses to exit
You need a dynamic, flexible loope.g., retrying after failed input

🧩 Loop Control Keywords break , continue , pass

In the first two parts, we learned how to use for and while loops to repeat tasks. Now, let’s explore three special keywords that help you control how loops behave:


🛑 break – Exit a Loop Early

The break statement immediately stops the loop, even if the condition is still True.

🔍 Example: Exit on condition

while True:
    command = input("Type 'exit' to stop: ")
    if command == "exit":
        break
    print("You typed:", command)

📤 Output:

Type 'exit' to stop: hello  
You typed: hello  
Type 'exit' to stop: exit

🔄 continue – Skip Current Iteration

continue skips the rest of the loop for that specific cycle, then continues with the next one.

🔍 Example: Skip even numbers

for i in range(1, 6):
    if i % 2 == 0:
        continue
    print(i)

📤 Output:

1  
3  
5

📌 pass – Do Nothing (Placeholder)

The pass keyword literally does nothing. It’s useful when writing code you plan to finish later.

🔍 Example: Coming soon...

for i in range(3):
    pass  # I’ll add something here later

More from this blog

Data Science

39 posts