4.1 Welcome to Python Loops! πŸ”„

This tutorial will teach you how to repeat actions efficiently using loops in Python. Loops are essential programming tools that let you automate repetitive tasks without writing the same code over and over again.

4.2 What are Loops?

Loops allow you to execute a block of code multiple times. Instead of writing the same code repeatedly, you can use a loop to run it as many times as needed.

Without loops:

print("Hello, iteration 1!")
print("Hello, iteration 2!")
print("Hello, iteration 3!")
print("Hello, iteration 4!")
print("Hello, iteration 5!")
Hello, iteration 1!
Hello, iteration 2!
Hello, iteration 3!
Hello, iteration 4!
Hello, iteration 5!

With a loop:

for i in range(1, 6):
    print(f"Hello, iteration {i}!")
Hello, iteration 1!
Hello, iteration 2!
Hello, iteration 3!
Hello, iteration 4!
Hello, iteration 5!

Much cleaner, right? Let’s explore the two main types of loops in Python!

4.3 For Loops: Iterating Through Sequences

A for loop is used when you want to iterate through a sequence (like a list, string, or range) or when you know how many times you want to repeat an action.

Basic For Loop Syntax

for item in sequence:
    # Code to execute for each item

Looping Through a Range

The range() function generates a sequence of numbers:

# Print numbers 0 to 4
for i in range(5):
    print(i)
0
1
2
3
4
# Print numbers 1 to 5
for i in range(1, 6):
    print(i)
1
2
3
4
5
# Count by 2s from 0 to 10
for i in range(0, 11, 2):
    print(i)
0
2
4
6
8
10

Range parameters: - range(stop) - starts at 0, goes up to (but not including) stop - range(start, stop) - starts at start, goes up to (but not including) stop - range(start, stop, step) - starts at start, increments by step, stops before stop

Looping Through Lists

You can iterate directly through list items:

fruits = ["apple", "banana", "cherry", "date"]

for fruit in fruits:
    print(f"I like {fruit}s!")
I like apples!
I like bananas!
I like cherrys!
I like dates!
# Calculate sum of numbers
numbers = [10, 20, 30, 40, 50]
total = 0

for num in numbers:
    total += num

print(f"Sum of numbers: {total}")
Sum of numbers: 150

Looping Through Strings

Strings are sequences of characters, so you can loop through each character:

word = "Python"

for letter in word:
    print(letter)
P
y
t
h
o
n
# Count vowels in a string
text = "Hello, World!"
vowels = "aeiouAEIOU"
vowel_count = 0

for char in text:
    if char in vowels:
        vowel_count += 1

print(f"Number of vowels: {vowel_count}")
Number of vowels: 3

Looping with Index: enumerate()

Sometimes you need both the index and the value. Use enumerate():

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

for index, color in enumerate(colors):
    print(f"Color {index}: {color}")
Color 0: red
Color 1: green
Color 2: blue
# Start enumeration at 1 instead of 0
for index, color in enumerate(colors, start=1):
    print(f"Color #{index}: {color}")
Color #1: red
Color #2: green
Color #3: blue

Looping Through Dictionaries

You can loop through dictionary keys, values, or both:

student = {
    "name": "Alice",
    "age": 20,
    "grade": "A"
}

# Loop through keys
print("Keys:")
for key in student.keys():
    print(key)

# Loop through values
print("\nValues:")
for value in student.values():
    print(value)

# Loop through key-value pairs
print("\nKey-Value pairs:")
for key, value in student.items():
    print(f"{key}: {value}")
Keys:
name
age
grade

Values:
Alice
20
A

Key-Value pairs:
name: Alice
age: 20
grade: A

Nested For Loops

You can put loops inside other loops:

# Multiplication table
for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i} x {j} = {i * j}")
    print("---")  # Separator between rows
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
---
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
---
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
---
# Create a pattern
for i in range(1, 6):
    for j in range(i):
        print("*", end="")
    print()  # New line after each row
*
**
***
****
*****

4.4 While Loops: Repeating Until a Condition is Met

A while loop continues executing as long as a condition remains True. It’s used when you don’t know in advance how many iterations you’ll need.

Basic While Loop Syntax

while condition:
    # Code to execute while condition is True

Simple While Loop

# Count down from 5
count = 5

while count > 0:
    print(count)
    count -= 1  # Decrease count by 1

print("Blast off! πŸš€")
5
4
3
2
1
Blast off! πŸš€
# Sum numbers until reaching a target
total = 0
num = 1

while total < 100:
    total += num
    num += 1

print(f"Sum: {total}")
print(f"Numbers added: {num - 1}")
Sum: 105
Numbers added: 14

While Loop with User Input (Simulation)

# Keep asking until valid input
password = ""

while password != "python123":
    password = input("Enter password: ")
    if password != "python123":
        print("Incorrect! Try again.")

print("Access granted!")

Infinite Loops and Break

Be careful! A while True loop runs forever unless you use break:

# Controlled infinite loop
attempts = 0

while True:
    attempts += 1
    print(f"Attempt {attempts}")

    if attempts >= 5:
        print("Maximum attempts reached!")
        break  # Exit the loop
Attempt 1
Attempt 2
Attempt 3
Attempt 4
Attempt 5
Maximum attempts reached!

4.5 Loop Control Statements

Python provides special keywords to control loop execution:

1. Break: Exit the Loop Early

The break statement immediately exits the loop:

# Find first number divisible by 7
for num in range(1, 100):
    if num % 7 == 0:
        print(f"First number divisible by 7: {num}")
        break
First number divisible by 7: 7
# Search for a specific item
items = ["book", "pen", "laptop", "phone", "tablet"]
search = "laptop"

for item in items:
    if item == search:
        print(f"Found {search}!")
        break
else:
    # This executes if loop completes without break
    print(f"{search} not found")
Found laptop!

2. Continue: Skip to Next Iteration

The continue statement skips the rest of the current iteration and moves to the next:

# Print odd numbers only
for num in range(1, 11):
    if num % 2 == 0:  # If even
        continue  # Skip to next iteration
    print(num)
1
3
5
7
9
# Process only valid data
data = [10, -5, 20, -3, 30, 0, 15]

for value in data:
    if value <= 0:
        continue  # Skip non-positive values
    print(f"Processing: {value}")
Processing: 10
Processing: 20
Processing: 30
Processing: 15

3. Pass: Do Nothing (Placeholder)

The pass statement does nothing - it’s a placeholder for future code:

# Placeholder for future implementation
for num in range(5):
    if num == 3:
        pass  # TODO: Add special handling later
    else:
        print(num)
0
1
2
4

4.6 Loop Else Clause

Python loops can have an else clause that executes when the loop completes normally (without break):

# Check if a number is prime
num = 17
is_prime = True

for i in range(2, num):
    if num % i == 0:
        print(f"{num} is not prime (divisible by {i})")
        is_prime = False
        break
else:
    print(f"{num} is prime!")
17 is prime!
# Search with else clause
numbers = [1, 3, 5, 7, 9]
search_for = 4

for num in numbers:
    if num == search_for:
        print(f"Found {search_for}!")
        break
else:
    print(f"{search_for} not in list")
4 not in list

4.7 Common Loop Patterns

Pattern 1: Accumulator

Building up a value through iterations:

# Calculate factorial
n = 5
factorial = 1

for i in range(1, n + 1):
    factorial *= i

print(f"{n}! = {factorial}")
5! = 120

Pattern 2: Filtering

Collecting items that meet certain criteria:

# Filter even numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = []

for num in numbers:
    if num % 2 == 0:
        even_numbers.append(num)

print(f"Even numbers: {even_numbers}")
Even numbers: [2, 4, 6, 8, 10]

Pattern 3: Transformation

Converting each item in a sequence:

# Convert temperatures from Celsius to Fahrenheit
celsius_temps = [0, 10, 20, 30, 40]
fahrenheit_temps = []

for temp in celsius_temps:
    fahrenheit = (temp * 9/5) + 32
    fahrenheit_temps.append(fahrenheit)

print(f"Celsius: {celsius_temps}")
print(f"Fahrenheit: {fahrenheit_temps}")
Celsius: [0, 10, 20, 30, 40]
Fahrenheit: [32.0, 50.0, 68.0, 86.0, 104.0]

Pattern 4: Finding Maximum/Minimum

# Find the largest number
numbers = [45, 23, 67, 12, 89, 34]
max_num = numbers[0]  # Start with first number

for num in numbers:
    if num > max_num:
        max_num = num

print(f"Maximum number: {max_num}")
Maximum number: 89

4.8 Practice Exercises

Now it’s your turn! Try these exercises:

Exercise 1: Multiplication Table

Create a multiplication table for the number 7 (from 7Γ—1 to 7Γ—10):

# Your code here:
number = 7
# Use a for loop to print multiplication table

Exercise 2: Sum of Even Numbers

Calculate the sum of all even numbers between 1 and 50:

# Your code here:
total = 0
# Use a loop to add even numbers

Exercise 3: Reverse a String

Write code to reverse a string using a loop:

text = "Python"
reversed_text = ""
# Use a loop to reverse the string

Exercise 4: Password Validator

Create a simple password strength checker that loops until a valid password is entered. A valid password should be at least 8 characters long:

# Simulate checking password length
test_passwords = ["abc", "hello", "python123"]

for pwd in test_passwords:
    # Check if password is valid
    pass

Exercise 5: FizzBuzz

Classic programming challenge! Print numbers 1-20, but: - Print β€œFizz” for multiples of 3 - Print β€œBuzz” for multiples of 5 - Print β€œFizzBuzz” for multiples of both 3 and 5

# Your code here:
for num in range(1, 21):
    # Add your logic
    pass

4.9 Solutions

Here are the solutions to the exercises:

Solution 1: Multiplication Table

Click to show solution
number = 7

for i in range(1, 11):
    result = number * i
    print(f"{number} x {i} = {result}")
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

Solution 2: Sum of Even Numbers

Click to show solution
total = 0

for num in range(1, 51):
    if num % 2 == 0:
        total += num

print(f"Sum of even numbers 1-50: {total}")
Sum of even numbers 1-50: 650

Alternative solution using range with step:

total = 0

for num in range(2, 51, 2):  # Start at 2, step by 2
    total += num

print(f"Sum of even numbers 1-50: {total}")
Sum of even numbers 1-50: 650

Solution 3: Reverse a String

Click to show solution
text = "Python"
reversed_text = ""

for char in text:
    reversed_text = char + reversed_text  # Add to beginning

print(f"Original: {text}")
print(f"Reversed: {reversed_text}")
Original: Python
Reversed: nohtyP

Alternative using index:

text = "Python"
reversed_text = ""

for i in range(len(text) - 1, -1, -1):  # Count backwards
    reversed_text += text[i]

print(f"Reversed: {reversed_text}")
Reversed: nohtyP

Solution 4: Password Validator

Click to show solution
test_passwords = ["abc", "hello", "python123"]

for pwd in test_passwords:
    if len(pwd) >= 8:
        print(f"'{pwd}' - Valid password βœ“")
    else:
        print(f"'{pwd}' - Too short (minimum 8 characters) βœ—")
'abc' - Too short (minimum 8 characters) βœ—
'hello' - Too short (minimum 8 characters) βœ—
'python123' - Valid password βœ“

Solution 5: FizzBuzz

Click to show solution
for num in range(1, 21):
    if num % 3 == 0 and num % 5 == 0:
        print("FizzBuzz")
    elif num % 3 == 0:
        print("Fizz")
    elif num % 5 == 0:
        print("Buzz")
    else:
        print(num)
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz

4.10 For vs While: When to Use Each?

Use for loops when: - βœ… You know how many iterations you need - βœ… You’re iterating through a sequence (list, string, range) - βœ… You’re using enumerate or working with indices

Use while loops when: - βœ… You don’t know how many iterations you’ll need - βœ… You’re waiting for a specific condition to become False - βœ… You’re processing input until a certain value appears - βœ… You’re implementing game loops or event loops

4.11 Common Loop Mistakes to Avoid

❌ Mistake 1: Infinite Loops

# This runs forever!
while True:
    print("Forever...")
# Always have a way to exit (break or condition change)

❌ Mistake 2: Off-by-One Errors

# This only prints 0-4, not 0-5!
for i in range(5):
    print(i)

# Use range(6) to get 0-5

❌ Mistake 3: Modifying List While Looping

# Don't do this!
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    numbers.remove(num)  # Bad: modifying while iterating

# Instead, create a new list or use list comprehension

❌ Mistake 4: Forgetting to Update Loop Variable

# This runs forever!
count = 0
while count < 5:
    print(count)
    # Forgot: count += 1

4.12 Loop Performance Tips

import time

# Tip 1: Use range for large sequences
start = time.time()
for i in range(1000000):
    pass
print(f"range() time: {time.time() - start:.4f} seconds")

# Tip 2: Avoid repeated calculations in loops
# ❌ Slow:
numbers = list(range(1000))
for i in range(len(numbers)):
    for j in range(len(numbers)):  # len() called many times
        pass

# βœ… Better:
length = len(numbers)
for i in range(length):
    for j in range(length):
        pass
range() time: 0.0106 seconds

4.13 Key Takeaways

✨ Remember:

  1. For loops iterate through sequences - use when you know how many times to loop
  2. While loops continue until a condition is False - use when iteration count is unknown
  3. break exits the loop immediately
  4. continue skips to the next iteration
  5. range(start, stop, step) generates number sequences
  6. enumerate() gives you both index and value
  7. Loop else clause runs when loop completes without break
  8. Nested loops let you work with multi-dimensional data
  9. Always ensure while loops have a way to exit (avoid infinite loops!)

4.14 Next Steps

Now that you understand loops, you’re ready to learn: - List comprehensions (elegant one-line loops) - Functions (organizing reusable code) - Error handling (try/except blocks) - File operations (reading and writing files)

Keep practicing with loops - they’re fundamental to programming! πŸš€

4.15 Additional Practice Challenges

Ready for more? Try these:

  1. Number Guessing Game: Use a while loop to let the user guess a number (1-10) until they get it right
  2. List Flattening: Given a nested list [[1,2], [3,4], [5,6]], use loops to create a flat list [1,2,3,4,5,6]
  3. Prime Numbers: Print all prime numbers between 1 and 100
  4. Pattern Printing: Create a pyramid pattern with asterisks
  5. Word Counter: Count how many times each word appears in a sentence

Happy looping! πŸ”„