Post

08. Python Loops - for and while

🚀 Master the art of iteration in Python! This guide unravels `for` and `while` loops, empowering you to automate tasks, process data efficiently, and build powerful applications. 💡 Learn about `break`, `continue`, and nested loops to become a loop expert!

08. Python Loops - for and while

What we will learn in this post?

  • 👉 Introduction to Loops
  • 👉 for Loop
  • 👉 The range() Function
  • 👉 while Loop
  • 👉 break Statement
  • 👉 continue Statement
  • 👉 else Clause in Loops
  • 👉 Nested Loops
  • 👉 Conclusion!

Looping Around: Repeating Actions in Python 🔄

Loops are your coding best friends when you need to do the same thing multiple times! Imagine writing the same line of code 100 times – a loop lets you avoid that headache! They’re all about automating repetitive tasks.

Why Use Loops? 🤷‍♀️

Instead of copy-pasting code, loops let you:

  • Save time: Automate repeated actions.
  • Make your code shorter: One loop can replace many lines.
  • Make your code easier to read: Loops clearly show repetition.

Python’s Loop Toolkit 🧰

Python has two main loop types:

  • for loops: Best for iterating through sequences (like lists or strings) a certain number of times. Example: for item in my_list: print(item)
  • while loops: Keep going while a condition is true. Example: while count < 10: print(count); count +=1
graph TD
    LOOP_START["Start"]:::startStyle --> LOOP_COND["Condition is True?"]:::condStyle
    LOOP_COND -- Yes --> LOOP_EXEC["Execute Code"]:::execStyle
    LOOP_EXEC --> LOOP_COND
    LOOP_COND -- No --> LOOP_END["End"]:::endStyle

    classDef startStyle fill:#ff9800,stroke:#e67e22,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef condStyle fill:#6b5bff,stroke:#4a3f6b,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef execStyle fill:#27ae60,stroke:#145a32,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef endStyle fill:#e74c3c,stroke:#c0392b,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;

    class LOOP_START startStyle;
    class LOOP_COND condStyle;
    class LOOP_EXEC execStyle;
    class LOOP_END endStyle;

    linkStyle default stroke:#2980b9,stroke-width:3px;


For more in-depth information you can check out Python’s official documentation on loops or W3Schools tutorial

Python For Loops: A Friendly Guide 🐍

Let’s explore Python’s for loops! They’re super useful for repeating actions with data like lists, strings, and numbers.

Understanding the for Loop

The basic structure is: for item in sequence:. It grabs each item from the sequence one by one and runs the code inside the loop.

Iterating over Sequences

  • Lists:
1
2
3
my_list = ["apple", "banana", "cherry"]
for fruit in my_list:
    print(fruit) # Output: apple, banana, cherry
  • Strings:
1
2
3
my_string = "Hello"
for letter in my_string:
    print(letter) # Output: H, e, l, l, o
  • Tuples:
1
2
3
my_tuple = (1, 2, 3)
for number in my_tuple:
    print(number) # Output: 1, 2, 3
  • Ranges: range(start, stop, step) creates a sequence of numbers.

    1
    2
    3
    4
    5
    6
    7
    8
    
    for i in range(5): # From 0 to 4
        print(i) # Output: 0, 1, 2, 3, 4
    
    for i in range(2,6): # From 2 to 5
        print(i) # Output: 2, 3, 4, 5
    
    for i in range(0, 10, 2): #From 0 to 8 with a step of 2
        print(i) # Output: 0, 2, 4, 6, 8
    

Understanding range() in Python 🐍

The range() function is super handy for creating sequences of numbers. Think of it as a shortcut to generate a list of numbers, especially useful when you need to repeat something a certain number of times!

The Basics of range()

The general syntax is: range(start, stop, step)

  • start: (Optional) Where the sequence begins (defaults to 0).
  • stop: (Required) Where the sequence stops (but doesn’t include this number).
  • step: (Optional) The increment between numbers (defaults to 1).

range() with for loops

range() is mostly used within for loops, allowing you to iterate a specific number of times.

1
2
3
4
5
6
7
8
9
10
11
# Simple loop from 0 to 4
for i in range(5): # stop is 5
    print(i) # Output: 0, 1, 2, 3, 4

# Loop from 1 to 9, increasing by 2
for i in range(1, 10, 2): # start=1, stop=10, step=2
    print(i) # Output: 1, 3, 5, 7, 9

# Loop backwards from 5 to 1
for i in range(5, 0, -1): # start=5, stop=0, step=-1
    print(i) # Output: 5, 4, 3, 2, 1

Remember the stop value isn’t included. You can use this to generate indexes for lists and other data structures too!

Let’s Loop with While! 🔁

Hey there! Let’s dive into the world of while loops. They’re super useful for repeating tasks until a certain condition changes.

The While Loop: How it Works 🤔

The while loop keeps running as long as its condition is True. Here’s the basic structure:

1
2
while condition:
    # Code to execute while the condition is True

Essentially, Python checks the condition first. If it’s True, the code inside the loop runs. Then, it checks the condition again. This continues until the condition becomes False.

When to While vs. For? 🤷‍♀️

  • for loop: Use when you know exactly how many times you want to repeat something (e.g., iterating through a list).

  • while loop: Use when you want to repeat something until a condition is met (e.g., keep asking for input until it’s valid).

Here’s an example:

graph TD
    DECIDE["Loop Decision"]:::decStyle --> FOR["for loop"]:::forStyle
    DECIDE --> WHILE["while loop"]:::whileStyle
    FOR --> F_KNOWN["Known number of iterations"]:::forStyle
    WHILE --> W_COND["Repeat until condition met"]:::whileStyle

    classDef decStyle fill:#f9e79f,stroke:#b7950b,color:#222,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef forStyle fill:#27ae60,stroke:#145a32,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef whileStyle fill:#6b5bff,stroke:#4a3f6b,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    linkStyle default stroke:#2980b9,stroke-width:3px;

for vs while Loops

Featurefor Loopwhile Loop
Use CaseKnown number of iterationsRepeat until condition is met
Syntaxfor item in sequence:while condition:
Typical UsageIterating lists, ranges, stringsInput validation, waiting for event
Condition LocationSequence/iterator in headerBoolean condition in header
Can be Infinite?Rare (with custom iterator)Common (while True)
Supports else clauseYesYes
Supports break/continueYesYes
ReadabilityVery clear for fixed iteration 
1
**Summary:** Use `for` loops when you know how many times to repeat. Use `while` loops when you want to keep going until something changes.
1
2
3
4
5
6
7
8
9
10
count = 0
while count < 5: # Check the condition before each loop
    print(f"Count is: {count}")
    count += 1 # Increment the counter (important!)
#Output:
#Count is: 0
#Count is: 1
#Count is: 2
#Count is: 3
#Count is: 4

Infinite Loops: The Danger Zone! ⚠️

If the condition in a while loop never becomes False, it’ll run forever! This is called an infinite loop.

1
2
3
# Example of an infinite loop (avoid this!)
# while True:
#     print("This will print forever!")

Always make sure your while loop has a way to eventually make the condition False.

Tip: You can usually stop an infinite loop by pressing Ctrl + C in your terminal.

Real world Example: Keep looping until the User enters correct Input. 🌍

1
2
3
4
5
6
7
8
9
10
11
user_input = ""
while user_input.lower() != "exit":
  user_input = input("Enter 'exit' to quit: ")
  print("You entered:", user_input)
#Output
#Enter 'exit' to quit: hello
#You entered: hello
#Enter 'exit' to quit: world
#You entered: world
#Enter 'exit' to quit: exit
#You entered: exit

Remember, while loops are a powerful tool, but use them wisely! 👍

The ‘break’ Statement: Your Loop Escape Hatch 🚪

The break statement is a powerful tool in programming that lets you exit a loop prematurely. Think of it as an emergency exit for your loops. Normally, a loop runs until its condition is false. But break lets you jump out of the loop immediately, regardless of the condition.

How It Works ⚙️

When the break statement is encountered inside a for or while loop, the loop’s execution stops, and the program control transfers to the next statement after the loop.

graph TD
    LOOP_START["Loop Start"]:::startStyle --> CHECK["Check Condition"]:::condStyle
    CHECK -- True --> EXEC["Execute Code"]:::execStyle
    EXEC --> BREAK{Break?}:::breakStyle
    BREAK -- Yes --> EXIT["Exit Loop"]:::endStyle
    BREAK -- No --> CONTINUE{Continue?}:::contStyle
    CONTINUE -- Yes --> CHECK
    CONTINUE -- No --> EXEC

    classDef startStyle fill:#ff9800,stroke:#e67e22,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef condStyle fill:#6b5bff,stroke:#4a3f6b,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef execStyle fill:#27ae60,stroke:#145a32,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef breakStyle fill:#e74c3c,stroke:#c0392b,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef contStyle fill:#f9e79f,stroke:#b7950b,color:#222,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef endStyle fill:#00bfae,stroke:#005f99,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    linkStyle default stroke:#2980b9,stroke-width:3px;

When to Use It 🤔

  • Finding Something: When you are searching for a specific item in a list, and you find it, use break to stop searching further.
  • Error Handling: If an error happens that makes the loop pointless, break is a way to gracefully exit.
  • Input Validation: If a user enters invalid data, use break to stop asking for input.

Examples 💡

  • Searching a List:
1
2
3
4
5
6
7
numbers = [1, 2, 3, 4, 5, 6]
target = 4

for num in numbers:
    if num == target:
        print("Found it!") # Found it!
        break # Exit the loop since we found the target
  • User Input Validation:
1
2
3
4
5
6
7
while True:
    age = input("Enter your age: ")
    if age.isdigit() and int(age) > 0:
        print("Age accepted!") #Age accepted!
        break # Valid age, exit the loop
    else:
        print("Invalid age. Please enter a positive number.") #Invalid age. Please enter a positive number

Continue Statement Explained 🚀

The continue statement in programming is like hitting the “skip” button on a song. It tells the program to immediately jump to the next iteration of a loop, bypassing any code that comes after it within the current iteration. Think of it as a shortcut to start the loop fresh!

How it Works 🤔

Instead of exiting the loop entirely (like break does), continue only skips the rest of the current round. The loop then resumes with the next value in the sequence.

1
2
3
4
5
6
7
8
for i in range(1, 6):
    if i % 2 == 0: # If 'i' is even
        continue  # Skip to the next iteration
    print(i)       # Only odd numbers will be printed
# Output:
# 1
# 3
# 5

Practical Uses 🛠️

  • Filtering Data: Skipping unwanted items.
  • Error Handling: Bypassing iterations where errors occur.
  • Optimizing Loops: Avoiding unnecessary calculations.

Example: Skipping Even Numbers

Here’s the code again to skip printing even numbers, continue is the secret ingredient to avoid printing those numbers that are multiple of 2.

1
2
3
4
5
6
7
8
for i in range(1, 6):
    if i % 2 == 0:
        continue # Skip even numbers
    print(i)
# Output:
# 1
# 3
# 5

Flowchart explaining the function of ‘continue’ within a loop

graph TD
    LOOP2_START["Start Loop"]:::startStyle --> LOOP2_COND["Condition Met?"]:::condStyle
    LOOP2_COND -- Yes --> LOOP2_CONT["Continue"]:::contStyle
    LOOP2_CONT --> LOOP2_START
    LOOP2_COND -- No --> LOOP2_EXEC["Execute Code"]:::execStyle
    LOOP2_EXEC --> LOOP2_END["End of Iteration"]:::endStyle
    LOOP2_END --> LOOP2_START

    classDef startStyle fill:#ff9800,stroke:#e67e22,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef condStyle fill:#6b5bff,stroke:#4a3f6b,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef contStyle fill:#f9e79f,stroke:#b7950b,color:#222,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef execStyle fill:#27ae60,stroke:#145a32,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef endStyle fill:#e74c3c,stroke:#c0392b,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;

    class LOOP2_START startStyle;
    class LOOP2_COND condStyle;
    class LOOP2_CONT contStyle;
    class LOOP2_EXEC execStyle;
    class LOOP2_END endStyle;

    linkStyle default stroke:#2980b9,stroke-width:3px;

Further information on continue statement : Python continue Statement

Python’s Looping ‘Else’: A Secret Weapon ⚔️

Python has a neat little trick: an else clause paired with for and while loops! But it’s not quite like the usual if-else.

The ‘Else’ Execution Rule 📜

The else block executes only if the loop completes without encountering a break statement. Think of it as an “all clear” signal after the loop finishes its natural course.

  • Normal Completion: else runs.
  • break Encountered: else doesn’t run.

Practical Uses & Examples 💡

This feature shines when you’re searching for something within a loop.

1
2
3
4
5
6
7
8
9
10
11
# Searching for a prime number
numbers = [4, 6, 8, 9, 10]

for num in numbers:
    if num % 2 != 0:  # Check if number is not divisible by 2
        print(f"{num} is not an even number.")
        break # Exit loop if not an even number is found
else:
    print("All numbers are even.") # Run this if no break occurs

# Output: 9 is not an even number.

In this example, the else block isn’t executed because the break statement interrupts the loop.

1
2
3
4
5
6
7
8
9
10
#Loop with no break
numbers = [2,4,6,8,10]

for num in numbers:
    if num % 2 != 0:
        print (f"{num} is not an even number")
        break
else:
    print("All numbers are even.")
#Output : All numbers are even.

Here, the loop completes without a break, so the else block gets executed.

This else with loops can make your code cleaner and more readable! Check out these resources to dive deeper: Python docs, Real Python

Nested Loops: Loops within Loops 🔄

Nested loops are basically loops inside other loops! Imagine a clock: the second hand goes around completely for every minute the minute hand moves. That’s nesting!

graph TD
    OUTER["Outer Loop"]:::outerStyle --> INNER["Inner Loop"]:::innerStyle
    INNER --> ACTION["Action (e.g., print)"]:::actionStyle
    OUTER --> NEXT_ROW["Next Row"]:::outerStyle

    classDef outerStyle fill:#ff9800,stroke:#e67e22,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef innerStyle fill:#6b5bff,stroke:#4a3f6b,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef actionStyle fill:#27ae60,stroke:#145a32,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    linkStyle default stroke:#2980b9,stroke-width:3px;

Why Use Nested Loops? 🤔

They’re super useful for things like:

  • Matrix Operations: Working with rows and columns in a table.
  • Pattern Printing: Creating cool shapes with characters.
  • Iterating Multi-dimensional Arrays: Accessing each element in a grid-like structure.

Examples and Patterns 🎨

Here’s how to print a simple rectangle using nested loops in Python:

1
2
3
4
5
6
7
8
9
10
for i in range(5): # Outer loop for rows
    for j in range(10): # Inner loop for columns
        print("*", end="") # Print an asterisk without a newline
    print() # Move to the next line after each row
# Output:
# **********
# **********
# **********
# **********
# **********

Here is another simple example of a triangle:

1
2
3
4
5
6
7
8
9
10
11
n = 5
for i in range(n):
    for j in range(i+1):
        print("*", end="")
    print()
# Output:
# *
# **
# ***
# ****
# *****

Performance Considerations ⏱️

Be careful! Nested loops can become slow, especially with large datasets. The time complexity can be O(nm), where n and m are the number of iterations for each loop, this is often represented asO(n2)*. Try to optimize by:

  • Using more efficient algorithms.
  • Avoiding unnecessary calculations inside the loops.
  • Consider vectorization, using libraries like NumPy if you are using Python.

Conclusion

So, there you have it! I hope you found this helpful. Now it’s your turn! What are your thoughts? 🤔 Share your comments, questions, or any brilliant ideas you have in the section below. I’m really eager to hear from you! Let’s chat! 💬

This post is licensed under CC BY 4.0 by the author.