- What loops are ā understanding repetition in programming
- The while loop ā repeating code based on a condition
- The for loop ā iterating over sequences
- Nested loops ā loops inside loops
- Loop control ā break, continue, and else
- For vs While ā when to use each loop type
- Real-world examples ā applying loops in practice
- Hands-on practice with the interactive editor
What are Loops?
A loop is a programming construct that repeats a block of code multiple times. Instead of writing the same code over and over, you write it once and let the loop handle the repetition.
š” Key insight: Loops are the heart of automation. They let you perform repetitive tasks efficiently and are essential for processing large amounts of data.
Think of loops like a washing machine cycle. You load the clothes, set the cycle, and the machine repeats the washing, rinsing, and spinning steps automatically. Similarly, in programming, loops automate repetitive tasks, saving you time and effort.
Why Use Loops?
Imagine you need to print "Hello" 100 times. Without loops, you'd have to write 100 print statements. With a loop, you write just one and let the loop repeat it. Here's why loops are essential:
- Efficiency: Write less code, do more work
- Automation: Automate repetitive tasks
- Data Processing: Process lists, arrays, and collections
- Algorithm Implementation: Many algorithms rely on loops
- User Interaction: Keep programs running until user decides to exit
# Without loop (bad)
print("Hello")
print("Hello")
print("Hello")
# ... 97 more times!
# With loop (good)
for i in range(100):
print("Hello")
1. The while Loop
The while loop repeats a block of code as long as a condition is True. It's like saying, "While this condition is true, keep doing this."
# Syntax
while condition:
# Code to repeat
# Example
count = 1
while count <= 5:
print(count)
count += 1
# Output:
# 1
# 2
# 3
# 4
# 5
š How it works: The condition is checked before each iteration. If True, the code block executes. If False, the loop ends. This is called a "pre-test" loop because the condition is tested before the code runs.
š” Real-World Use: User Validation
# Keep asking until user enters a valid number
valid = False
while not valid:
try:
num = int(input("Enter a number: "))
valid = True
print(f"You entered: {num}")
except ValueError:
print("Invalid input! Try again.")
2. The for Loop
The for loop iterates over a sequence (like a list, tuple, string, or range). It's perfect for when you know exactly how many times you want to repeat something.
# Syntax
for item in sequence:
# Code to repeat
# Example 1: Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Example 2: Using range()
for i in range(1, 6):
print(i)
# Output:
# apple
# banana
# cherry
# 1
# 2
# 3
# 4
# 5
š How it works: The for loop takes each item from the sequence one by one, executes the code block, and moves to the next item. It automatically stops when there are no more items.
š” Real-World Use: Shopping Cart Total
# Calculate total price of items in cart
cart = [250, 300, 150, 100]
total = 0
for price in cart:
total += price
print(f"Total: ā¹{total}")
# Output: Total: ā¹800
3. Nested Loops
A nested loop is a loop inside another loop. The inner loop runs completely for each iteration of the outer loop. This is useful for working with multi-dimensional data or creating patterns.
# Nested loops for multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i * j}")
print("-" * 10)
# Output:
# 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
# ----------
4. Loop Control Statements
Python provides three statements to control the flow of loops:
š break
Exits the loop immediately
āļø continue
Skips the rest of the current iteration
š else
Runs when the loop completes normally
# break
for i in range(1, 10):
if i == 5:
break
print(i)
# Output: 1 2 3 4
# continue
for i in range(1, 6):
if i == 3:
continue
print(i)
# Output: 1 2 4 5
# else
for i in range(1, 4):
print(i)
else:
print("Loop completed!")
# Output: 1 2 3 Loop completed!
5. For vs While - When to Use
| Feature | for Loop | while Loop |
|---|---|---|
| Best For | Iterating over sequences | Repeating until a condition changes |
| Loop Count | Known in advance | May be unknown |
| Risk | Lower risk of infinite loops | Higher risk of infinite loops |
| Example | Processing a list | User input validation |
Try It Yourself!
Experiment with loops directly in your browser. Modify the code and see the results in real time.
LOOPS INTRODUCTION
========================================
1. WHILE LOOP
1 2 3 4 5
2. FOR LOOP
apple banana cherry
3. FOR LOOP WITH RANGE
1 2 3 4 5
4. BREAK
1 2 3 4
5. CONTINUE
1 2 4 5
ā Explore different loop types!
š You've Learned Python Loops!
You understand while loops, for loops, nested loops, and loop control statements. These are essential for writing efficient Python code!
Quick Quiz ā Test Your Knowledge
Let's see what you've learned about Python loops:
break statement do in a loop?else block run in a loop?Frequently Asked Questions
š¤ What is an infinite loop and how do I avoid it?
š§ Can I use break and continue together?
break and continue can be used together in the same loop. continue skips the rest of the current iteration and moves to the next one. break exits the loop completely.
š What is the difference between range() in Python 2 and 3?
range() returns a list, while xrange() returns an iterator. In Python 3, range() returns an iterator (like Python 2's xrange), which is more memory efficient for large sequences.
š Can I loop through a dictionary in Python?
for key in dict:, values using for value in dict.values():, or both using for key, value in dict.items():.
ā” Is it better to use for or while for performance?
for loops are faster and more readable because they handle iteration automatically. while loops are slower because they check the condition each time. Use for when you can, and while when you need more control.
šÆ Can I use else with a while loop?
else block in a while loop runs when the condition becomes false normally (not when broken). This is useful for checking if a loop was completed or interrupted.
š Where to Go From Here
Now that you understand loops in Python, here are the next topics to explore in detail:
š The while Loop
Deep dive into the while loop with advanced examples.
š The for Loop
Master the for loop with real-world examples.
š Loops Assignments
Practice what you've learned with real coding challenges.
Practice ā