Python Loops
Introduction
Loops are one of the fundamental concepts in programming that allow you to execute a block of code repeatedly. In Python, loops provide an efficient way to automate repetitive tasks, process collections of data, and implement algorithms that require iteration.
Without loops, you would need to write the same code multiple times, making your programs longer, harder to maintain, and less efficient. Python provides two main types of loops: for
loops and while
loops, each serving different purposes in your code.
In this tutorial, you'll learn:
- How
for
andwhile
loops work - When to use each type of loop
- How to control loop execution with
break
,continue
, andelse
- Common loop patterns and best practices
For Loops
A for
loop in Python is used to iterate over a sequence (such as a list, tuple, dictionary, string, or range) and execute a block of code for each item in the sequence.
Basic Syntax
for item in sequence:
# Code to execute for each item
Simple For Loop Example
Let's start with a basic example that prints each number in a list:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
Output:
1
2
3
4
5
Looping Through a Range
The range()
function is commonly used with for
loops to execute a block of code a specific number of times:
for i in range(5): # range(5) generates numbers from 0 to 4
print(f"Iteration {i}")
Output:
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
You can customize the range()
function with start, stop, and step parameters:
# range(start, stop, step)
for i in range(2, 10, 2): # Start at 2, stop before 10, step by 2
print(i)
Output:
2
4
6
8
Looping Through Strings
Strings are sequences of characters, so you can loop through each character:
word = "Python"
for char in word:
print(char)
Output:
P
y
t
h
o
n
Looping Through Dictionaries
When looping through dictionaries, the default behavior is to iterate through the keys:
student = {
"name": "Alice",
"age": 21,
"major": "Computer Science"
}
# Iterating through keys
for key in student:
print(key, ":", student[key])
# Alternatively, using items() method to get both key and value
print("\nUsing items() method:")
for key, value in student.items():
print(key, ":", value)
Output:
name : Alice
age : 21
major : Computer Science
Using items() method:
name : Alice
age : 21
major : Computer Science
While Loops
A while
loop continues to execute a block of code as long as a specified condition is True
.
Basic Syntax
while condition:
# Code to execute while condition is True
Simple While Loop Example
count = 1
while count <= 5:
print(f"Count: {count}")
count += 1 # Increment count to eventually end the loop
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Infinite Loops and How to Avoid Them
A common mistake is creating an infinite loop by forgetting to update the condition variable:
# WARNING: This is an infinite loop (don't run this)
# while True:
# print("This will run forever!")
To avoid infinite loops, always make sure that:
- The condition will eventually become
False
- You have a way to break out of the loop
# Safe example with a break statement
counter = 0
while True:
print(f"Counter: {counter}")
counter += 1
if counter >= 5:
print("Breaking the loop")
break
Output:
Counter: 0
Counter: 1
Counter: 2
Counter: 3
Counter: 4
Breaking the loop
Loop Control Statements
Python provides statements that allow you to control the flow of loops:
Break Statement
The break
statement immediately terminates a loop and moves to the code after the loop:
for i in range(10):
if i == 5:
print("Found 5! Breaking loop...")
break
print(i)
Output:
0
1
2
3
4
Found 5! Breaking loop...
Continue Statement
The continue
statement skips the current iteration and moves to the next iteration:
for i in range(10):
if i % 2 == 0: # Skip even numbers
continue
print(f"Odd number: {i}")
Output:
Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
Odd number: 9
Else Clause in Loops
Python allows an else
clause after loops that executes when the loop completes normally (without a break
):
# Loop with break
print("Loop with break:")
for i in range(5):
print(i)
if i == 3:
break
else:
print("Loop completed normally")
# Loop without break
print("\nLoop without break:")
for i in range(5):
print(i)
else:
print("Loop completed normally")
Output:
Loop with break:
0
1
2
3
Loop without break:
0
1
2
3
4
Loop completed normally
Nested Loops
You can place one loop inside another to create more complex iteration patterns:
for i in range(1, 4):
for j in range(1, 4):
print(f"({i}, {j})", end=" ")
print() # New line after each inner loop completes
Output:
(1, 1) (1, 2) (1, 3)
(2, 1) (2, 2) (2, 3)
(3, 1) (3, 2) (3, 3)
Practical Examples
Example 1: Calculating Factorial
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
number = 5
print(f"The factorial of {number} is {factorial(number)}")
Output:
The factorial of 5 is 120
Example 2: Finding Prime Numbers
def is_prime(num):
if num <= 1:
return False
if num <= 3:
return True
# Check divisibility up to square root of num
i = 2
while i * i <= num:
if num % i == 0:
return False
i += 1
return True
# Print prime numbers between 1 and 20
print("Prime numbers between 1 and 20:")
for number in range(1, 21):
if is_prime(number):
print(number, end=" ")
Output:
Prime numbers between 1 and 20:
2 3 5 7 11 13 17 19
Example 3: Processing Data with Loops
Let's analyze a list of student scores to calculate statistics:
scores = [85, 92, 78, 65, 97, 88, 72, 81, 89, 94]
# Calculate sum and average
total = 0
count = 0
for score in scores:
total += score
count += 1
average = total / count
# Find minimum and maximum scores
min_score = scores[0]
max_score = scores[0]
for score in scores:
if score < min_score:
min_score = score
if score > max_score:
max_score = score
print(f"Scores: {scores}")
print(f"Total students: {count}")
print(f"Total score: {total}")
print(f"Average score: {average:.2f}")
print(f"Minimum score: {min_score}")
print(f"Maximum score: {max_score}")
Output:
Scores: [85, 92, 78, 65, 97, 88, 72, 81, 89, 94]
Total students: 10
Total score: 841
Average score: 84.10
Minimum score: 65
Maximum score: 97
Loop Performance Considerations
When working with loops, consider these performance tips:
-
Avoid unnecessary work inside loops: Move operations that don't change with each iteration outside the loop.
-
Use list comprehensions for simple transformations:
# Instead of:
squares = []
for i in range(10):
squares.append(i ** 2)
# Use list comprehension:
squares = [i ** 2 for i in range(10)]
print(squares)
Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
- Consider using
enumerate()
when you need both index and value:
fruits = ["apple", "banana", "cherry", "date"]
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
Output:
Index 0: apple
Index 1: banana
Index 2: cherry
Index 3: date
Summary
In this tutorial, you've learned about:
- For loops: Used to iterate through sequences with a known number of items
- While loops: Used when you need to repeat code based on a condition
- Loop control statements:
break
,continue
, andelse
clause - Nested loops: How to create more complex iteration patterns
- Practical examples showing how loops can solve real-world problems
Loops are essential to Python programming and mastering them will significantly improve your ability to write effective and efficient code.
Exercises
To practice your loop skills, try these exercises:
- Write a program that prints the first 10 Fibonacci numbers using a loop.
- Create a program that finds all numbers divisible by 7 between 1 and 100.
- Write a loop to reverse a string without using the built-in
reversed()
function. - Create a pattern of stars that forms a right-angled triangle using nested loops.
- Write a program that simulates a guessing game where the user has to guess a random number between 1 and 100.
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)