Loops in Python
Learn how to repeat actions using for loops and while loops, and discover how range() helps you control counting patterns.
The for Loop
A for loop repeats a block of code a specific number of times. It is perfect when you know in advance how many times you want to repeat something. The range() function generates a sequence of numbers for the loop to iterate through.
# Print "Hello" 5 times
for i in range(5):
print("Hello!", i)
# Output:
# Hello! 0
# Hello! 1
# Hello! 2
# Hello! 3
# Hello! 4
Notice that range(5) gives numbers 0, 1, 2, 3, 4 (it starts at 0 and stops before 5). You can also specify a start, stop, and step:
# range(start, stop, step)
for i in range(1, 11): # 1 to 10
print(i, end=" ")
# Output: 1 2 3 4 5 6 7 8 9 10
for i in range(0, 20, 5): # 0, 5, 10, 15
print(i, end=" ")
# Output: 0 5 10 15
for i in range(10, 0, -1): # Counting down
print(i, end=" ")
# Output: 10 9 8 7 6 5 4 3 2 1
The while Loop
A while loop repeats as long as a condition is True. It is ideal when you do not know in advance how many times the loop needs to run.
# Keep asking until the user gets the password right
password = ""
while password != "python123":
password = input("Enter the password: ")
print("Access granted!")
# Count up to a target
count = 1
while count <= 5:
print("Count:", count)
count = count + 1 # Don't forget to update!
Warning: If the condition never becomes False, the loop runs forever (an infinite loop). Always make sure the variable in the condition changes inside the loop!
Looping Through Items
For loops can also iterate directly over a collection of items like a list or a string, not just numbers:
# Loop through a list of subjects
subjects = ["Maths", "English", "Science"]
for subject in subjects:
print("I study", subject)
# Loop through characters in a string
word = "Python"
for letter in word:
print(letter, end="-")
# Output: P-y-t-h-o-n-
Key Vocabulary
for loop
A loop that repeats a set number of times, often using range() or iterating over a collection.
while loop
A loop that continues as long as a condition remains True.
range()
A function that generates a sequence of numbers. Takes up to three arguments: start, stop, step.
Infinite Loop
A loop that never stops because its condition is always True. Usually a bug to avoid.
Worked Examples
Print the 7 times table from 1 to 12.
# 7 times table
for i in range(1, 13):
result = 7 * i
print(f"7 x {i} = {result}")
Step 1: Use range(1, 13) to count from 1 to 12.
Step 2: Multiply 7 by the loop variable i each time.
Output: 7 x 1 = 7, 7 x 2 = 14, ... 7 x 12 = 84
Add up all the numbers from 1 to 100 using a for loop.
# Sum of 1 to 100
total = 0
for number in range(1, 101):
total = total + number
print("The sum of 1 to 100 is:", total)
# Output: The sum of 1 to 100 is: 5050
Step 1: Start a total variable at 0.
Step 2: Loop from 1 to 100, adding each number to the total.
Key point: This is called an accumulator pattern — a very common technique in programming.
Use a while loop to simulate a number guessing game.
secret = 42
guess = 0
attempts = 0
while guess != secret:
guess = int(input("Guess the number: "))
attempts = attempts + 1
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
print(f"Correct! You got it in {attempts} attempts.")
Step 1: The while loop keeps running until the guess matches the secret number.
Step 2: Inside the loop, give hints ("Too low!" or "Too high!") to help the user.
Key point: The attempts counter tracks how many guesses were made.
Knowledge Check
Select the correct answer for each question. Click "Check Answer" to see if you are right.
Question 1
How many times will this loop run?
for i in range(4):
print(i)Question 2
What will range(2, 8) produce?
Question 3
Which loop is best when you do NOT know how many times to repeat?
Question 4
What will this code print?
total = 0
for i in range(1, 4):
total = total + i
print(total)Question 5
What causes an infinite loop?
Key Concepts Summary
-
●
for loops repeat a known number of times using
range()or a collection. - ● while loops repeat as long as a condition is True — ideal for unknown repetitions.
-
●
range(stop),range(start, stop), andrange(start, stop, step)control counting patterns. - ● The accumulator pattern (starting at 0, adding in a loop) is a fundamental programming technique.
- ● Always ensure a while loop's condition will eventually become False to avoid infinite loops.