← View series: python tutorials
~/blog
Control Flow - Loops
Introduction
In this tutorial, you'll learn how to use loops in Python. Loops allow you to repeat code multiple times without writing it over and over. This is essential for processing collections of data, automating repetitive tasks, and implementing algorithms.
What You'll Learn
- The
forloop for iterating over sequences - The
whileloop for conditional repetition - Loop control statements:
break,continue, andelse - The
range()function - Nested loops
The for Loop
The for loop iterates over a sequence (like a list, string, or range):
Basic for Loop
# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)Output:
apple
banana
cherry
Iterating Over a String
# Each character in a string
for letter in "Python":
print(letter)Output:
P
y
t
h
o
n
The range() Function
range() generates a sequence of numbers, perfect for counting loops:
range() Basics
# range(stop) - from 0 to stop-1
for i in range(5):
print(i)Output:
0
1
2
3
4
range() with Start and Step
# range(start, stop) - from start to stop-1
for i in range(2, 6):
print(i)Output:
2
3
4
5
# range(start, stop, step)
for i in range(0, 10, 2):
print(i)Output:
0
2
4
6
8
# Negative step (counting backwards)
for i in range(5, 0, -1):
print(i)Output:
5
4
3
2
1
The while Loop
The while loop repeats as long as a condition is True:
Basic while Loop
# Count from 1 to 5
count = 1
while count <= 5:
print(count)
count += 1 # Don't forget this!
print("Done!")Output:
1
2
3
4
5
Done!
while with User Input
# Keep asking until user enters 'quit'
while True:
command = input("Enter command (type 'quit' to exit): ")
if command == "quit":
print("Goodbye!")
break
print(f"You entered: {command}")Loop Control Statements
break - Exit the Loop
The break statement immediately exits the loop:
# Find first even number
numbers = [1, 3, 5, 6, 7, 9]
for num in numbers:
if num % 2 == 0:
print(f"Found even number: {num}")
break # Exit the loopOutput:
Found even number: 6
continue - Skip to Next Iteration
The continue statement skips the rest of the current iteration:
# Print only odd numbers
for i in range(1, 10):
if i % 2 == 0:
continue # Skip even numbers
print(i)Output:
1
3
5
7
9
else - Run When Loop Completes Normally
The else block runs when the loop finishes without hitting break:
# Search for a number
numbers = [1, 3, 5, 7, 9]
search = 6
for num in numbers:
if num == search:
print(f"Found {search}!")
break
else:
# This runs if break was never hit
print(f"{search} not found in the list")Output:
6 not found in the list
Practical Examples
Example 1: Sum of Numbers
# Calculate sum of 1 to 100
total = 0
for i in range(1, 101):
total += i
print(f"Sum: {total}") # Output: 5050Example 2: Factorial
# Calculate factorial of 5
n = 5
factorial = 1
while n > 0:
factorial *= n
n -= 1
print(f"Factorial: {factorial}") # Output: 120Example 3: FizzBuzz
A classic programming problem:
# FizzBuzz: print 1-20, but fizz for multiples of 3,
# buzz for multiples of 5, fizzbuzz for both
for i in range(1, 21):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)Example 4: Finding Maximum
# Find the largest number in a list
numbers = [12, 45, 67, 23, 89, 34]
max_num = numbers[0] # Start with first number
for num in numbers:
if num > max_num:
max_num = num
print(f"Largest: {max_num}") # Output: 89Nested Loops
You can place loops inside other loops:
# Multiplication table (1-5)
for i in range(1, 6):
for j in range(1, 6):
print(f"{i * j:3d}", end=" ") # :3d formats as 3-digit
print() # New line after each rowOutput:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
⚠️ Warning: Nested loops can be slow. Avoid deep nesting (3+ levels).
for vs while - When to Use Which?
| Use Case | Loop Type |
|---|---|
| Iterating over a sequence (list, string) | for |
| Known number of iterations | for with range() |
| Unknown number of iterations | while |
| Loop until a condition changes | while |
Summary
In this tutorial, you learned:
- ✅ The
forloop for iterating over sequences - ✅ The
range()function for generating number sequences - ✅ The
whileloop for conditional repetition - ✅ Loop control:
break,continue, andelse - ✅ Nested loops
- ✅ Practical examples: sum, factorial, FizzBuzz
🧑💻 Practice Exercise
Create a program that:
- Asks the user for a number
- Prints a triangle pattern like this (for input 5):
*
**
***
****
*****
- Also prints the multiplication table for that number (1-10)
Click to see solution
# Triangle pattern and multiplication table
num = int(input("Enter a number: "))
# Triangle pattern
print("\n--- Triangle ---")
for i in range(1, num + 1):
print("*" * i)
# Multiplication table
print("\n--- Multiplication Table ---")
for i in range(1, 11):
result = num * i
print(f"{num} x {i} = {result}")Sample Output for input 5:
--- Triangle ---
*
**
***
****
*****
--- Multiplication Table ---
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
What's Next
In the next tutorial, we'll learn about Data Structures - Lists - how to work with collections of data.