INTELEVO EP 05 – Complete Tutorial for AI & Data Science
Introduction
Imagine you’re a teacher who needs to print grade reports for 150 students. Without loops, you’d write 150 individual print statements. With loops? Just five lines of code. That’s the power of iteration.
Loops are one of the most powerful features in programming. They let you automate repetitive tasks, process large datasets, and write cleaner, more maintainable code. Whether you’re analyzing data, validating user input, or processing collections of items, loops are essential.
In this guide, we’ll explore everything you need to know about loops in Python—from basic for loops to advanced patterns and real-world applications.
Why Do We Need Loops?
Let’s start with a concrete example. Suppose you want to print the first five items in a list:
Without Loops (Repetitive & Unmaintainable)
print("Item 1")
print("Item 2")
print("Item 3")
print("Item 4")
print("Item 5")
This works for 5 items, but what if you have 100? Or 10,000? The code becomes:
- Repetitive: You’re writing the same logic multiple times
- Hard to maintain: Changing one line means changing it everywhere
- Poorly scalable: It doesn’t adapt to different data sizes
With Loops (Clean & Scalable)
for i in range(1, 6):
print(f"Item {i}")
Same result, but now it’s:
- Concise: Just two lines instead of five
- Maintainable: Change the logic once, apply everywhere
- Scalable: Works for 5 items or 5 million items with the same code
This is why loops are fundamental to programming. Let’s dive deeper.
for Loops: Iteration Over Sequences
for Loops: Iteration Over Sequences
A for loop repeats a block of code once for each item in a sequence. It’s the go-to choice when you know you want to process every element in a collection.
for item in sequence:
# Code to execute for each item
Breaking Down the Syntax
| Part | Meaning |
|---|---|
| for | Loop keyword |
| item | Loop variable (name you choose) |
| in | Keyword that establishes the relationship |
| sequence | Collection to iterate over (list, string, range, etc.) |
Practical Example
numbers = [10, 20, 30, 40]
for num in numbers:
print(f"Number: {num}")
# Output:
# Number: 10
# Number: 20
# Number: 30
# Number: 40
In this example:
numis the loop variable—it holds the current item- The loop runs 4 times (once per number)
- On each iteration,
numtakes the next value from the list
Iterating Over Strings
Loops work great with strings too:
word = "Python"
for letter in word:
print(letter)
# Output:
# P
# y
# t
# h
# o
# n
for Loops with range()
The range() function generates sequences of numbers and is incredibly useful for controlling loop iterations.
range(start, stop, step)
- start (optional): Where to begin (default: 0)
- stop: Where to end (exclusive—not included)
- step (optional): Gap between numbers (default: 1)
Common range() Patterns
| Pattern | Explanation | Output |
|---|---|---|
range(5) | 0 up to (but not including) 5 | 0, 1, 2, 3, 4 |
range(1, 6) | 1 up to (but not including) 6 | 1, 2, 3, 4, 5 |
range(0, 10, 2) | 0 to 10, stepping by 2 | 0, 2, 4, 6, 8 |
range(10, 0, -1) | 10 down to 1 (negative step) | 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 |
Practical Examples
Simple Counting
for i in range(1, 11):
print(i)
# Output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
for i in range(0, 21, 5):
print(i)
# Output: 0, 5, 10, 15, 20
for i in range(5, 0, -1):
print(i)
print("Blastoff!")
# Output: 5, 4, 3, 2, 1, Blastoff!
while Loops: Condition-Based Repetition
While for loops iterate a known number of times, while loops continue as long as a condition is True. They’re perfect when you don’t know in advance how many iterations you need.
Syntax:
while condition:
# Code to execute while condition is True
for vs while: When to Use Each
| Aspect | for Loop | while Loop |
|---|---|---|
| When to use | Known number of iterations | Condition-based iteration |
| Best for | Processing sequences | User input, unknown duration |
| Complexity | Simpler, less error-prone | Requires careful condition management |
Comparing for and while
Here’s the same logic implemented both ways:
Using a for Loop (Known iterations)
for i in range(3):
print(f"Loop {i}")
# Runs exactly 3 times
Using a while Loop (Condition-based)
count = 0
while count < 3:
print(f"Loop {count}")
count += 1
# Runs until count reaches 3
Important: Avoiding Infinite Loops
A common mistake is forgetting to update the condition variable:
# ⚠️ INFINITE LOOP - DON'T RUN THIS
count = 0
while count < 10:
print(count)
# Oops! count never increases
# This runs forever
Always ensure the condition will eventually become False.
Practical while Loop Example
Prompting for valid input:
response = ""
while response.lower() not in ["yes", "no"]:
response = input("Do you want to continue? (yes/no): ")
print(f"You said: {response}")
Loop Control: break and continue
While loops can be interrupted or redirected using break and continue statements.
break: Exit the Loop
The break statement immediately terminates the loop, regardless of the condition.
for i in range(5):
if i == 3:
break
print(i)
Output: 0, 1, 2
The loop stops when i reaches 3, even though range(5) would normally go to 4.
Real-world example: Searching for an item
items = ["apple", "banana", "cherry", "date", "elderberry"]
search_for = "cherry"
for item in items:
if item == search_for:
print(f"Found {search_for}!")
break
else:
print(f"{search_for} not found")
continue: Skip to the Next Iteration
The continue statement jumps to the next iteration, skipping the remaining code in the current iteration.
for i in range(5):
if i == 2:
continue
print(i)
# Output: 0, 1, 3, 4
Notice that 2 is skipped—the print() statement never runs when i == 2.
Real-world example: Processing data (skip invalid entries)
numbers = [1, -2, 3, -4, 5, 0, 6]
for num in numbers:
if num <= 0:
continue # Skip negative and zero values
print(f"Processing: {num}")
# Output:
# Processing: 1
# Processing: 3
# Processing: 5
# Processing: 6
for-else: What Happens When the Loop Completes
for i in range(5):
if i == 10: # Never true
break
else:
print("Loop completed without break") # This runs
# vs.
for i in range(5):
if i == 3:
break
else:
print("Loop completed without break") # This doesn't run
Nested Loops: Loops Within Loops
A nested loop is a loop inside another loop. The inner loop completes entirely for each iteration of the outer loop.
Why Nested Loops?
Nested loops are essential for processing multi-dimensional data—grids, matrices, tables, or any data that has multiple levels.
Multiplication Table Example
for i in range(1, 4):
for j in range(1, 4):
print(f"{i}×{j}={i*j}", end=" ")
print() # New line after inner loop
# Output:
# 1×1=1 1×2=2 1×3=3
# 2×1=2 2×2=4 2×3=6
# 3×1=3 3×2=6 3×3=9
How it works:
- Outer loop:
icycles through 1, 2, 3 (3 iterations) - Inner loop: For each value of
i,jcycles through 1, 2, 3 (3 iterations per outer loop) - Total operations: 3 × 3 = 9 multiplication operations
Pattern Analysis
Iteration 1: i=1, inner loop runs 3 times (j=1,2,3)
Iteration 2: i=2, inner loop runs 3 times (j=1,2,3)
Iteration 3: i=3, inner loop runs 3 times (j=1,2,3)
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in grid:
for num in row:
print(num, end=” “)
print()
Output:
1 2 3
4 5 6
7 8 9
Performance Consideration
Nested loops can become computationally expensive. A 10×10 nested loop runs 100 operations; a 10×10×10 triple loop runs 1,000 operations. As loops increase, the complexity grows exponentially.
Common Loop Patterns
Professional programmers use certain patterns repeatedly. Mastering these will level up your coding skills.
1. Iterate with Index: enumerate()
When you need both the index (position) and the value:
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits):
print(f"Index {i}: {fruit}")
# Output:
# Index 0: apple
# Index 1: banana
# Index 2: cherry
You can also start the index at a different number:
names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]
for name, score in zip(names, scores):
print(f"{name}: {score}")
# Output:
# Alice: 85
# Bob: 92
# Charlie: 78
The loop stops when the shortest list is exhausted:
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30] # Shorter!
for name, age in zip(names, ages):
print(f"{name}: {age}")
# Output:
# Alice: 25
# Bob: 30
# (Charlie is skipped because there's no corresponding age)
3. Accumulator Pattern: Build Up a Result
Keep a running total or collection:
numbers = [10, 20, 30, 40, 50]
total = 0
for num in numbers:
total += num
print(f"Sum: {total}") # Output: Sum: 150
This pattern is used for summing, averaging, counting, and collecting results:
# Averaging
scores = [85, 92, 78, 95, 88]
total = 0
for score in scores:
total += score
average = total / len(scores)
print(f"Average: {average:.1f}") # Output: Average: 87.6
# Building a list
numbers = [1, 2, 3, 4, 5]
squares = []
for num in numbers:
squares.append(num ** 2)
print(squares) # Output: [1, 4, 9, 16, 25]
4. Conditional Iteration: Filter While Looping
Process only items that meet certain criteria:
numbers = [5, 12, 8, 23, 15, 30, 9]
for num in numbers:
if num > 10:
print(num)
# Output:
# 12
# 23
# 15
# 30
Combine with other patterns:
students = [
{"name": "Alice", "score": 85},
{"name": "Bob", "score": 92},
{"name": "Charlie", "score": 78}
]
for student in students:
if student["score"] >= 90:
print(f"{student['name']}: A")
elif student["score"] >= 80:
print(f"{student['name']}: B")
else:
print(f"{student['name']}: C")
Real-World Loop Applications
Understanding loops theoretically is one thing; applying them to real problems is another. Here are two practical scenarios you’ll encounter regularly.
Application 1: Data Analysis
Analyze student scores and calculate statistics:
scores = [85, 92, 78, 95, 88]
# Calculate total and average
total = sum(scores)
average = total / len(scores)
# Grade assignment with loop
print("Grade Report:")
for score in scores:
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"{score}: {grade}")
print(f"Average: {average:.1f}")
print(f"Highest: {max(scores)}")
print(f"Lowest: {min(scores)}")
Output
Grade Report:
85: B
92: A
78: C
95: A
88: B
Average: 87.6
Highest: 95
Lowest: 78
Application 2: Input Validation
Ensure users enter valid passwords:
while True:
password = input("Enter a password: ")
# Check length
if len(password) < 8:
print("❌ Password too short (minimum 8 characters)")
continue
# Check for at least one digit
if not any(c.isdigit() for c in password):
print("❌ Password must contain at least one digit")
continue
# Check for uppercase
if not any(c.isupper() for c in password):
print("❌ Password must contain at least one uppercase letter")
continue
# All checks passed
print("✓ Password accepted!")
break
This demonstrates:
while True for continuous prompting
continue to skip back to the next attempt
break to exit when valid
any() function to check conditions
Key Takeaways
The Loops make code scalable, write once, process millions of items demonstrates,
for loops can when you know the number of iterations (sequences, ranges)
while loops when you need condition-based repetition (user input, unknown duration)
break to exit a loop early
continue to skip to the next iteration
enumerate() when you need both index and value
zip() to iterate multiple sequences in parallel
Master nested loops for processing multi-dimensional data
Watch for infinite loops—always ensure the condition becomes False
What’s Next?
You’ve mastered loops—one of the most essential programming concepts. Now it’s time to level up with Functions & Code Reusability in Episode 6.
With functions, you’ll learn how to:
- ✓ Define and call functions
- ✓ Use parameters and arguments
- ✓ Return values and manage scope
- ✓ Organize code effectively
- ✓ Write reusable, maintainable code
Loops let you automate repetitive tasks; functions let you encapsulate logic and reuse it throughout your program. Together, they’re the foundation of professional Python development.
Practice Challenges
Try these exercises to solidify your understanding:
- Sum and Average: Write a loop that finds the sum and average of numbers in a list
- Pattern Printing: Use nested loops to print a pyramid pattern:
*
**
***
****
*****
- FizzBuzz: Print numbers 1-100, but print “Fizz” for multiples of 3, “Buzz” for multiples of 5, and “FizzBuzz” for multiples of both
- Even Numbers: Use a loop to find all even numbers between 1 and 50
- Password Validator: Implement a password validator that checks for length, digits, and special characters
Subscribe to Intelevo on YouTube and join thousands of learners mastering Python from the ground up. Follow along with video tutorials, interactive examples, and real-world projects.
Happy looping! 🐍
