🎯 Learning Objectives
After completing this section, you will understand:
- How to use for loops with ranges
- Loop control statements (break and continue)
- Nested loops and their applications
- Common loop patterns and techniques
⚡ Prerequisites
- Understanding of while loops
- Basic arithmetic operations
- Knowledge of conditional statements
1. For Loops with Range
The range() function generates a sequence of numbers, perfect for for loops:
# Basic range with one argument (stop)
for i in range(5): # 0 to 4
print(i)
# Range with start and stop
for i in range(1, 6): # 1 to 5
print(i)
# Range with start, stop, and step
for i in range(0, 10, 2): # Even numbers 0 to 8
print(i)
Range Function Parameters
range(stop): 0 to stop-1
range(start, stop): start to stop-1
range(start, stop, step): start to stop-1, counting by step
2. Loop Control Statements
Python provides statements to control loop execution:
Break Statement
# Exit loop when condition met
for i in range(1, 11):
if i == 5:
break
print(i)
# Prints 1, 2, 3, 4
Continue Statement
# Skip current iteration
for i in range(1, 6):
if i == 3:
continue
print(i)
# Prints 1, 2, 4, 5
3. Nested Loops
You can place one loop inside another to handle more complex patterns:
# Multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i*j}")
print() # Empty line between rows
# 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
Tips for nested loops:
- Keep track of your indentation
- Use meaningful variable names
- Consider performance with large ranges
4. Common Loop Patterns
Here are some common patterns you'll use with loops:
Pattern Printing
# Print a triangle
for i in range(5):
print('*' * (i + 1))
# Output:
# *
# **
# ***
# ****
# *****
Running Total
# Calculate sum of numbers
total = 0
for i in range(1, 6):
total += i
print(f"Sum: {total}") # Sum: 15
Create a number pyramid pattern:
rows = 5
for i in range(1, rows + 1):
for j in range(1, i + 1):
print(j, end=' ')
print()
# Output:
# 1
# 1 2
# 1 2 3
# 1 2 3 4
# 1 2 3 4 5
Find prime numbers in a range:
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
# Print prime numbers from 1 to 20
for num in range(1, 21):
if is_prime(num):
print(num, end=' ')
# Output: 2 3 5 7 11 13 17 19
🎉 Summary
You've learned about:
- Using for loops with range()
- Break and continue statements
- Working with nested loops
- Common loop patterns and techniques
This completes Part 2 of the Python course!