Introduction to Loops
Overview
Discover how loops let your program repeat actions efficiently. You'll explore when to use loops instead of repetitive code and understand the difference between definite and indefinite iteration.
What You Will Learn in This Lesson
By the end of this lesson, you will know:
- What loops are: Understand how loops let you repeat code efficiently.
- Why loops are useful: Learn when and why to use loops instead of writing repetitive code.
- Types of loops: Discover the two main types: definite and indefinite loops.
- When to use loops: Recognize situations where loops make your code better.
Why This Matters
Loops are one of the most powerful features in programming. They let you repeat actions without writing the same code over and over. Instead of writing print("Hello") ten times, you can use a loop to do it once. This makes your code shorter, easier to read, and easier to maintain.
Step 1: What Are Loops?
A loop is a way to repeat code multiple times. Think of it like a playlist that repeats songs, or a recipe step you do multiple times. Instead of writing the same code over and over, you write it once and tell Python how many times to repeat it (or when to stop).
Without Loops (Repetitive)
You'd have to write the same code multiple times:
print("Hello")
print("Hello")
print("Hello")
print("Hello")
print("Hello")
This is tedious and hard to change
With Loops (Efficient)
Write it once and repeat it:
for i in range(5):
print("Hello")
Much cleaner and easier to modify
Key Concept: Loops let you write code once and execute it multiple times. This is called "iteration" - repeating an action. Loops are essential for processing lists of data, repeating calculations, and automating repetitive tasks.
Step 2: Why Use Loops?
Loops solve several problems that come up when programming:
Efficiency
Instead of writing the same code many times, you write it once. This saves time and reduces errors.
# Instead of 100 lines:
for i in range(100):
print("Hello")
Flexibility
You can easily change how many times code runs by changing one number, instead of adding or removing lines.
# Change 5 to 10 easily:
for i in range(10):
print("Hello")
Processing Collections
Loops let you work with lists, strings, and other collections of data, doing something with each item.
# Process each item:
for name in ["Alice", "Bob", "Charlie"]:
print("Hello,", name)
Mini Practice #1: See the Difference
Try It YourselfCompare writing code without loops vs. with loops:
What happened? Both approaches produce the same output, but notice the difference. Without a loop, you need three separate print statements. With a loop, you write the print statement once and it runs three times. The loop version is shorter, easier to read, and if you wanted to count to 100, you'd just change range(1, 4) to range(1, 101) instead of writing 100 print statements! This is the power of loops.
Step 3: Types of Loops
Python has two main types of loops. Understanding the difference helps you choose the right one for each situation:
Definite Loops (for)
These loops run a specific number of times. You know exactly how many times the code will execute before the loop starts.
# Runs exactly 5 times
for i in range(5):
print("Hello")
Use when: You know how many times to repeat
Indefinite Loops (while)
These loops run as long as a condition is True. You don't know exactly how many times it will run - it depends on when the condition becomes False.
# Runs until count >= 5
count = 0
while count < 5:
print("Hello")
count = count + 1
Use when: You repeat until a condition changes
Real-World Analogy
Think of definite loops like counting to 10 - you know you'll count exactly 10 numbers. Think of indefinite loops like waiting for a bus - you keep waiting until the bus arrives (the condition changes). Both are useful, but for different situations.
Step 4: When to Use Loops
Here are common situations where loops are helpful:
# 1. Repeating an action multiple times
for i in range(10):
print("Hello")
# 2. Processing items in a list
names = ["Alice", "Bob", "Charlie"]
for name in names:
print("Hello,", name)
# 3. Counting or accumulating values
total = 0
for i in range(1, 6):
total = total + i
print(total) # Sums 1+2+3+4+5
# 4. Repeating until a condition is met
count = 0
while count < 5:
print(count)
count = count + 1
Rule of Thumb: If you find yourself copying and pasting the same code multiple times, or if you need to do something with each item in a collection, use a loop. Loops make your code cleaner, more maintainable, and less error-prone.
Step 5: Loop Structure
All loops in Python follow a similar structure. Understanding this structure helps you read and write loops correctly:
for variable in sequence:
# Code to repeat
print(variable)
# More code if needed
# After the loop ends, code continues here
print("Loop finished")
Loop Header
The first line defines the loop. It starts with for or while, includes a condition or sequence, and ends with a colon :.
Loop Body
The indented code after the colon is the "loop body" - this is what gets repeated. All code in the body must be indented consistently.
Loop Completion
When the loop finishes, Python continues with the next non-indented line. The loop doesn't run forever - it stops when its condition is met or sequence is exhausted.
Remember: Just like with if statements, the colon : after the loop header is required, and all code inside the loop body must be indented. Python uses indentation to know what belongs to the loop.
End-of-Lesson Exercises
Exercise 1: Write a Simple Loop
Write a for loop that prints "Hello" exactly 3 times. Use range(3).
Use for i in range(3): followed by an indented print statement.