Imagine you need to print the numbers from 1 to 100, or process a list of 1000 names, or keep asking a user for input until they provide a valid answer. Writing the same code 100 or 1000 times would be tedious and impractical. This is where loops come in—they allow you to repeat code multiple times efficiently.
Loops are one of the most powerful features in programming. They let you automate repetitive tasks, process collections of data, and create programs that can handle variable amounts of input. In this lesson, you'll learn about Python's two main types of loops: for loops and while loops. By mastering loops, you'll be able to write programs that are both more powerful and more concise.
What You'll Learn
- How to use
forloops to iterate over sequences - Understanding
range()for generating number sequences - Using
whileloops for conditional repetition - Controlling loop execution with
breakandcontinue - Nested loops for complex iterations
- Common loop patterns and best practices
- Avoiding infinite loops and common pitfalls
For Loops: Iterating Over Sequences
The for loop is used to iterate over a sequence (like a string, list, or range of numbers). It executes a block of code once for each item in the sequence. The basic syntax is:
for item in sequence:
# Code to execute for each item
print(item)
Here's a simple example:
# Iterating over a string
word = "Python"
for letter in word:
print(letter)
This will print each letter of "Python" on a separate line: P, y, t, h, o, n.
For loops are perfect for processing collections of data. Here's a practical example:
# Processing a list of names
names = ["Alice", "Bob", "Charlie", "Diana"]
for name in names:
greeting = f"Hello, {name}!"
print(greeting)
This loop will greet each person in the list, one at a time.
The Range Function
The range() function is incredibly useful with for loops. It generates a sequence of numbers that you can iterate over. There are three ways to use range():
# range(stop) - numbers from 0 to stop-1
for i in range(5):
print(i) # Prints: 0, 1, 2, 3, 4
# range(start, stop) - numbers from start to stop-1
for i in range(2, 6):
print(i) # Prints: 2, 3, 4, 5
# range(start, stop, step) - numbers with a step size
for i in range(0, 10, 2):
print(i) # Prints: 0, 2, 4, 6, 8
The range() function is perfect for repeating code a specific number of times:
# Print numbers 1 to 10
for number in range(1, 11):
print(f"Number: {number}")
# Calculate sum of numbers 1 to 100
total = 0
for i in range(1, 101):
total += i
print(f"Sum of 1 to 100: {total}")
While Loops: Conditional Repetition
While for loops iterate over a sequence, while loops repeat code as long as a condition is True. They're perfect for situations where you don't know in advance how many times you need to repeat:
# Basic while loop
count = 0
while count < 5:
print(f"Count: {count}")
count += 1 # Increment count
This loop will print numbers 0 through 4. The loop continues as long as count < 5 is True. Once count reaches 5, the condition becomes False and the loop stops.
Here's a practical example using while loops:
# Input validation with while loop
age = -1 # Initialize with invalid value
while age < 0 or age > 120:
age = int(input("Enter your age (0-120): "))
if age < 0 or age > 120:
print("Invalid age! Please try again.")
print(f"Your age is: {age}")
This loop keeps asking for input until the user provides a valid age.
Break and Continue
Sometimes you need more control over your loops. The break statement exits the loop immediately, while continue skips the rest of the current iteration and moves to the next one:
# Using break to exit early
for number in range(1, 11):
if number == 5:
break # Exit the loop when number is 5
print(number)
# Prints: 1, 2, 3, 4
# Using continue to skip iterations
for number in range(1, 11):
if number % 2 == 0: # Skip even numbers
continue
print(number)
# Prints: 1, 3, 5, 7, 9
Here's a practical example combining break with user input:
# Simple menu system
while True:
print("\nMenu:")
print("1. Option 1")
print("2. Option 2")
print("3. Quit")
choice = input("Enter your choice: ")
if choice == "1":
print("You selected Option 1")
elif choice == "2":
print("You selected Option 2")
elif choice == "3":
print("Goodbye!")
break # Exit the loop
else:
print("Invalid choice!")
Nested Loops
You can place loops inside other loops. This is called nesting and is useful for working with two-dimensional data or creating patterns:
# Nested loops for multiplication table
for i in range(1, 6):
for j in range(1, 6):
result = i * j
print(f"{i} x {j} = {result}", end=" ")
print() # New line after each row
This creates a 5x5 multiplication table. The outer loop handles rows, and the inner loop handles columns.
Here's another practical example:
# Pattern printing with nested loops
rows = 5
for i in range(1, rows + 1):
for j in range(i):
print("*", end="")
print() # New line
This prints a pattern of asterisks:
*
**
***
****
*****
Common Loop Patterns
Let's look at some common patterns you'll use frequently:
# Pattern 1: Accumulating values
total = 0
numbers = [10, 20, 30, 40, 50]
for num in numbers:
total += num
print(f"Total: {total}")
# Pattern 2: Finding maximum/minimum
numbers = [42, 15, 78, 23, 91, 5]
maximum = numbers[0] # Start with first number
for num in numbers:
if num > maximum:
maximum = num
print(f"Maximum: {maximum}")
# Pattern 3: Counting occurrences
text = "programming"
count = 0
for letter in text:
if letter == "r":
count += 1
print(f"Letter 'r' appears {count} times")
# Pattern 4: Building a new list
original = [1, 2, 3, 4, 5]
doubled = []
for num in original:
doubled.append(num * 2)
print(f"Doubled: {doubled}")
Avoiding Infinite Loops
One common mistake with while loops is creating an infinite loop—a loop that never stops. This happens when the condition never becomes False:
# DANGER: Infinite loop (don't run this!)
# count = 0
# while count < 5:
# print(count)
# # Forgot to increment count - loop never ends!
# CORRECT: Make sure condition eventually becomes False
count = 0
while count < 5:
print(count)
count += 1 # Always update the condition variable
Always ensure your while loop has a way to eventually make the condition False, or use break to exit when needed.
Try It Yourself
Practice using loops with these exercises:
-
Number Printer: Write a program that prints all even numbers from 2 to 100 using a
forloop. -
Sum Calculator: Create a program that asks the user for numbers until they enter 0, then displays the sum of all entered numbers.
-
Password Retry: Build a program that asks for a password. Give the user 3 attempts. If they enter the correct password, grant access. If they fail 3 times, deny access.
-
Multiplication Table: Create a program that prints a multiplication table from 1 to 10 using nested loops.
These exercises will help you become comfortable with different types of loops and when to use each one.
Summary
In this lesson, you've learned how to use loops to repeat code efficiently. You now understand for loops for iterating over sequences, while loops for conditional repetition, and how to use range() to generate number sequences. You've also learned about break and continue for controlling loop execution, and how to nest loops for complex iterations.
Loops are essential for writing efficient, powerful programs. They allow you to process collections of data, repeat actions multiple times, and create programs that can handle variable amounts of input. Combined with conditionals, loops give you the tools to build sophisticated programs.
Remember to be careful with while loops to avoid infinite loops—always ensure your condition can become False, or use break to exit when needed. Also, choose the right loop for the job: use for loops when you know how many iterations you need, and while loops when you need to repeat until a condition is met.
What's Next?
In the next lesson, we'll explore lists—Python's powerful data structure for storing collections of items. You'll learn how to create lists, add and remove items, access elements, and perform operations on lists. Lists work perfectly with loops, and together they form the foundation for handling collections of data in your programs.