print("Hello, iteration 1!")
print("Hello, iteration 2!")
print("Hello, iteration 3!")
print("Hello, iteration 4!")
print("Hello, iteration 5!")Hello, iteration 1!
Hello, iteration 2!
Hello, iteration 3!
Hello, iteration 4!
Hello, iteration 5!
This tutorial will teach you how to repeat actions efficiently using loops in Python. Loops are essential programming tools that let you automate repetitive tasks without writing the same code over and over again.
Loops allow you to execute a block of code multiple times. Instead of writing the same code repeatedly, you can use a loop to run it as many times as needed.
Without loops:
print("Hello, iteration 1!")
print("Hello, iteration 2!")
print("Hello, iteration 3!")
print("Hello, iteration 4!")
print("Hello, iteration 5!")Hello, iteration 1!
Hello, iteration 2!
Hello, iteration 3!
Hello, iteration 4!
Hello, iteration 5!
With a loop:
for i in range(1, 6):
print(f"Hello, iteration {i}!")Hello, iteration 1!
Hello, iteration 2!
Hello, iteration 3!
Hello, iteration 4!
Hello, iteration 5!
Much cleaner, right? Letβs explore the two main types of loops in Python!
A for loop is used when you want to iterate through a sequence (like a list, string, or range) or when you know how many times you want to repeat an action.
for item in sequence:
# Code to execute for each itemThe range() function generates a sequence of numbers:
# Print numbers 0 to 4
for i in range(5):
print(i)0
1
2
3
4
# Print numbers 1 to 5
for i in range(1, 6):
print(i)1
2
3
4
5
# Count by 2s from 0 to 10
for i in range(0, 11, 2):
print(i)0
2
4
6
8
10
Range parameters: - range(stop) - starts at 0, goes up to (but not including) stop - range(start, stop) - starts at start, goes up to (but not including) stop - range(start, stop, step) - starts at start, increments by step, stops before stop
You can iterate directly through list items:
fruits = ["apple", "banana", "cherry", "date"]
for fruit in fruits:
print(f"I like {fruit}s!")I like apples!
I like bananas!
I like cherrys!
I like dates!
# Calculate sum of numbers
numbers = [10, 20, 30, 40, 50]
total = 0
for num in numbers:
total += num
print(f"Sum of numbers: {total}")Sum of numbers: 150
Strings are sequences of characters, so you can loop through each character:
word = "Python"
for letter in word:
print(letter)P
y
t
h
o
n
# Count vowels in a string
text = "Hello, World!"
vowels = "aeiouAEIOU"
vowel_count = 0
for char in text:
if char in vowels:
vowel_count += 1
print(f"Number of vowels: {vowel_count}")Number of vowels: 3
Sometimes you need both the index and the value. Use enumerate():
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(f"Color {index}: {color}")Color 0: red
Color 1: green
Color 2: blue
# Start enumeration at 1 instead of 0
for index, color in enumerate(colors, start=1):
print(f"Color #{index}: {color}")Color #1: red
Color #2: green
Color #3: blue
You can loop through dictionary keys, values, or both:
student = {
"name": "Alice",
"age": 20,
"grade": "A"
}
# Loop through keys
print("Keys:")
for key in student.keys():
print(key)
# Loop through values
print("\nValues:")
for value in student.values():
print(value)
# Loop through key-value pairs
print("\nKey-Value pairs:")
for key, value in student.items():
print(f"{key}: {value}")Keys:
name
age
grade
Values:
Alice
20
A
Key-Value pairs:
name: Alice
age: 20
grade: A
You can put loops inside other loops:
# Multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i * j}")
print("---") # Separator between rows1 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
---
# Create a pattern
for i in range(1, 6):
for j in range(i):
print("*", end="")
print() # New line after each row*
**
***
****
*****
A while loop continues executing as long as a condition remains True. Itβs used when you donβt know in advance how many iterations youβll need.
while condition:
# Code to execute while condition is True# Count down from 5
count = 5
while count > 0:
print(count)
count -= 1 # Decrease count by 1
print("Blast off! π")5
4
3
2
1
Blast off! π
# Sum numbers until reaching a target
total = 0
num = 1
while total < 100:
total += num
num += 1
print(f"Sum: {total}")
print(f"Numbers added: {num - 1}")Sum: 105
Numbers added: 14
# Keep asking until valid input
password = ""
while password != "python123":
password = input("Enter password: ")
if password != "python123":
print("Incorrect! Try again.")
print("Access granted!")Be careful! A while True loop runs forever unless you use break:
# Controlled infinite loop
attempts = 0
while True:
attempts += 1
print(f"Attempt {attempts}")
if attempts >= 5:
print("Maximum attempts reached!")
break # Exit the loopAttempt 1
Attempt 2
Attempt 3
Attempt 4
Attempt 5
Maximum attempts reached!
Python provides special keywords to control loop execution:
The break statement immediately exits the loop:
# Find first number divisible by 7
for num in range(1, 100):
if num % 7 == 0:
print(f"First number divisible by 7: {num}")
breakFirst number divisible by 7: 7
# Search for a specific item
items = ["book", "pen", "laptop", "phone", "tablet"]
search = "laptop"
for item in items:
if item == search:
print(f"Found {search}!")
break
else:
# This executes if loop completes without break
print(f"{search} not found")Found laptop!
The continue statement skips the rest of the current iteration and moves to the next:
# Print odd numbers only
for num in range(1, 11):
if num % 2 == 0: # If even
continue # Skip to next iteration
print(num)1
3
5
7
9
# Process only valid data
data = [10, -5, 20, -3, 30, 0, 15]
for value in data:
if value <= 0:
continue # Skip non-positive values
print(f"Processing: {value}")Processing: 10
Processing: 20
Processing: 30
Processing: 15
The pass statement does nothing - itβs a placeholder for future code:
# Placeholder for future implementation
for num in range(5):
if num == 3:
pass # TODO: Add special handling later
else:
print(num)0
1
2
4
Python loops can have an else clause that executes when the loop completes normally (without break):
# Check if a number is prime
num = 17
is_prime = True
for i in range(2, num):
if num % i == 0:
print(f"{num} is not prime (divisible by {i})")
is_prime = False
break
else:
print(f"{num} is prime!")17 is prime!
# Search with else clause
numbers = [1, 3, 5, 7, 9]
search_for = 4
for num in numbers:
if num == search_for:
print(f"Found {search_for}!")
break
else:
print(f"{search_for} not in list")4 not in list
Building up a value through iterations:
# Calculate factorial
n = 5
factorial = 1
for i in range(1, n + 1):
factorial *= i
print(f"{n}! = {factorial}")5! = 120
Collecting items that meet certain criteria:
# Filter even numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
print(f"Even numbers: {even_numbers}")Even numbers: [2, 4, 6, 8, 10]
Converting each item in a sequence:
# Convert temperatures from Celsius to Fahrenheit
celsius_temps = [0, 10, 20, 30, 40]
fahrenheit_temps = []
for temp in celsius_temps:
fahrenheit = (temp * 9/5) + 32
fahrenheit_temps.append(fahrenheit)
print(f"Celsius: {celsius_temps}")
print(f"Fahrenheit: {fahrenheit_temps}")Celsius: [0, 10, 20, 30, 40]
Fahrenheit: [32.0, 50.0, 68.0, 86.0, 104.0]
# Find the largest number
numbers = [45, 23, 67, 12, 89, 34]
max_num = numbers[0] # Start with first number
for num in numbers:
if num > max_num:
max_num = num
print(f"Maximum number: {max_num}")Maximum number: 89
Now itβs your turn! Try these exercises:
Create a multiplication table for the number 7 (from 7Γ1 to 7Γ10):
# Your code here:
number = 7
# Use a for loop to print multiplication tableCalculate the sum of all even numbers between 1 and 50:
# Your code here:
total = 0
# Use a loop to add even numbersWrite code to reverse a string using a loop:
text = "Python"
reversed_text = ""
# Use a loop to reverse the stringCreate a simple password strength checker that loops until a valid password is entered. A valid password should be at least 8 characters long:
# Simulate checking password length
test_passwords = ["abc", "hello", "python123"]
for pwd in test_passwords:
# Check if password is valid
passClassic programming challenge! Print numbers 1-20, but: - Print βFizzβ for multiples of 3 - Print βBuzzβ for multiples of 5 - Print βFizzBuzzβ for multiples of both 3 and 5
# Your code here:
for num in range(1, 21):
# Add your logic
passHere are the solutions to the exercises:
number = 7
for i in range(1, 11):
result = number * i
print(f"{number} x {i} = {result}")7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
total = 0
for num in range(1, 51):
if num % 2 == 0:
total += num
print(f"Sum of even numbers 1-50: {total}")Sum of even numbers 1-50: 650
Alternative solution using range with step:
total = 0
for num in range(2, 51, 2): # Start at 2, step by 2
total += num
print(f"Sum of even numbers 1-50: {total}")Sum of even numbers 1-50: 650
text = "Python"
reversed_text = ""
for char in text:
reversed_text = char + reversed_text # Add to beginning
print(f"Original: {text}")
print(f"Reversed: {reversed_text}")Original: Python
Reversed: nohtyP
Alternative using index:
text = "Python"
reversed_text = ""
for i in range(len(text) - 1, -1, -1): # Count backwards
reversed_text += text[i]
print(f"Reversed: {reversed_text}")Reversed: nohtyP
test_passwords = ["abc", "hello", "python123"]
for pwd in test_passwords:
if len(pwd) >= 8:
print(f"'{pwd}' - Valid password β")
else:
print(f"'{pwd}' - Too short (minimum 8 characters) β")'abc' - Too short (minimum 8 characters) β
'hello' - Too short (minimum 8 characters) β
'python123' - Valid password β
for num in range(1, 21):
if num % 3 == 0 and num % 5 == 0:
print("FizzBuzz")
elif num % 3 == 0:
print("Fizz")
elif num % 5 == 0:
print("Buzz")
else:
print(num)1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Use for loops when: - β
You know how many iterations you need - β
Youβre iterating through a sequence (list, string, range) - β
Youβre using enumerate or working with indices
Use while loops when: - β
You donβt know how many iterations youβll need - β
Youβre waiting for a specific condition to become False - β
Youβre processing input until a certain value appears - β
Youβre implementing game loops or event loops
# This runs forever!
while True:
print("Forever...")
# Always have a way to exit (break or condition change)# This only prints 0-4, not 0-5!
for i in range(5):
print(i)
# Use range(6) to get 0-5# Don't do this!
numbers = [1, 2, 3, 4, 5]
for num in numbers:
numbers.remove(num) # Bad: modifying while iterating
# Instead, create a new list or use list comprehension# This runs forever!
count = 0
while count < 5:
print(count)
# Forgot: count += 1import time
# Tip 1: Use range for large sequences
start = time.time()
for i in range(1000000):
pass
print(f"range() time: {time.time() - start:.4f} seconds")
# Tip 2: Avoid repeated calculations in loops
# β Slow:
numbers = list(range(1000))
for i in range(len(numbers)):
for j in range(len(numbers)): # len() called many times
pass
# β
Better:
length = len(numbers)
for i in range(length):
for j in range(length):
passrange() time: 0.0106 seconds
β¨ Remember:
break exits the loop immediatelycontinue skips to the next iterationrange(start, stop, step) generates number sequencesenumerate() gives you both index and valueelse clause runs when loop completes without breakNow that you understand loops, youβre ready to learn: - List comprehensions (elegant one-line loops) - Functions (organizing reusable code) - Error handling (try/except blocks) - File operations (reading and writing files)
Keep practicing with loops - theyβre fundamental to programming! π
Ready for more? Try these:
[[1,2], [3,4], [5,6]], use loops to create a flat list [1,2,3,4,5,6]Happy looping! π