Doing the Same Thing Again and Again
Every morning, a class teacher opens the register and calls out each name: “Aarav?” “Present!” “Diya?” “Present!” The action is the same every time. Only the name changes. When the last name is called, attendance is done.
Now think of a shopkeeper with a shelf of biscuit packets. Each time a customer buys one, the stock goes down by one. The shopkeeper keeps selling while there are packets left. They do not know in advance how many customers will come, they just stop when the shelf is empty.
These are the two kinds of repetition in programming, and Python has a loop for each. A for loop goes through a collection item by item, like the teacher with the register. A while loop keeps going as long as a condition is true, like the shopkeeper with the stock. In this lesson you will learn both, plus range(), break and continue.
Step 1: The for Loop over a List
A list is a group of values inside square brackets, such as ["Aarav", "Diya"]. You will study lists properly in the next lesson. For now, just know that a for loop can take each item from a list, one at a time.
Read the loop below like a sentence: “for each name in the students list, print it with Present.” The variable name holds a different student each time the loop runs. Each run of the loop body is called an iteration.
students = ["Aarav", "Diya", "Ishaan", "Meera"]
for name in students:
print(f"{name}: Present")
print("Attendance complete.")
# Aarav: Present
# Diya: Present
# Ishaan: Present
# Meera: Present
# Attendance complete.
Just like if, the for line ends with a colon, and the lines inside the loop are indented by 4 spaces. The last print is not indented, so it runs only once, after the loop finishes.
Step 2: Looping over a String
A string is a sequence of characters, so a for loop can walk through it letter by letter:
word = "CHAI"
for letter in word:
print(letter)
# C
# H
# A
# I
Step 3: Counting with range()
Often you do not have a list. You just want to repeat something a fixed number of times, or count from one number to another. The range() function produces a sequence of whole numbers for you. It can take one, two or three values:
| You write | Numbers you get | Meaning |
|---|---|---|
range(4) | 0, 1, 2, 3 | Start at 0, stop before 4 |
range(1, 6) | 1, 2, 3, 4, 5 | Start at 1, stop before 6 |
range(2, 11, 2) | 2, 4, 6, 8, 10 | Jump by 2 each time (the step) |
range(5, 0, -1) | 5, 4, 3, 2, 1 | A negative step counts down |
The most important rule: the stop number is never included. To count from 1 to 10, you write range(1, 11). In the example, print(n, end=" ") prints a space instead of a new line, so the numbers appear side by side.
# range(stop): from 0 up to, but not including, stop
for n in range(4):
print(n, end=" ") # 0 1 2 3
print()
# range(start, stop): roll numbers 1 to 5
for roll in range(1, 6):
print(roll, end=" ") # 1 2 3 4 5
print()
# range(start, stop, step): every second bench
for bench in range(2, 11, 2):
print(bench, end=" ") # 2 4 6 8 10
print()
# A negative step counts down
for count in range(5, 0, -1):
print(count, end=" ") # 5 4 3 2 1
print("Lift off!")
Step 4: Multiplication Tables
Remember writing tables in your notebook as a child? A loop writes them in less than a second. Change number to any value and run it again.
number = 7
for i in range(1, 11):
print(f"{number} x {i} = {number * i}")
# 7 x 1 = 7
# 7 x 2 = 14
# ...
# 7 x 10 = 70
Step 5: Adding Up a Total
One of the most common jobs for a loop is to accumulate a total. The pattern has two parts. First, before the loop, create a variable that starts at 0. Then, inside the loop, add each value to it. This variable is often called an accumulator. Here a chai stall adds up its sales for the week:
daily_sales = [450, 380, 520, 610, 300, 720, 690] # Monday to Sunday
total = 0 # 1. start with an empty "box"
for amount in daily_sales:
total = total + amount # 2. add each day to the box
print(f"Total sales this week: Rs. {total}") # Rs. 3670
print(f"Average per day: Rs. {total / len(daily_sales):.2f}") # Rs. 524.29
The line total = total + amount can also be written total += amount. Both do the same thing. You will see += in a lot of Python code.
Step 6: The while Loop
A while loop checks a condition before each iteration. If the condition is True, the body runs. Then Python goes back to the top and checks again. When the condition becomes False, the loop ends. This is the shopkeeper selling until the shelf is empty:
stock = 5 # packets of biscuits on the shelf
sold_today = 0
while stock > 0:
stock = stock - 1
sold_today = sold_today + 1
print(f"Sold one packet. Left on shelf: {stock}")
print(f"Out of stock! Sold {sold_today} packets today.")
# Sold one packet. Left on shelf: 4
# ...
# Sold one packet. Left on shelf: 0
# Out of stock! Sold 5 packets today.
Notice the line stock = stock - 1. Something inside a while loop must change the condition, or the loop will never stop.
for or while? Use for when you know what you are looping over: a list, a string or a range of numbers. Use while when you only know the condition for stopping, such as “until the stock runs out” or “until the user types the right answer”.
Step 7: break and continue
Two keywords give you more control inside any loop:
breakstops the loop completely and jumps to the code after it.continueskips the rest of the current iteration and moves straight to the next one.
In this example, a customer who wants 0 packets is skipped with continue, and the counter closes with break when a customer wants more than the stock:
orders = [2, 3, 0, 4, 1, 5] # packets each customer wants
stock = 8
for wanted in orders:
if wanted == 0:
continue # nothing to do, skip to the next customer
if wanted > stock:
print(f"Only {stock} left, cannot give {wanted}. Closing the counter.")
break # stop the loop completely
stock = stock - wanted
print(f"Gave {wanted}, stock now {stock}")
# Gave 2, stock now 6
# Gave 3, stock now 3
# Only 3 left, cannot give 4. Closing the counter.
Step 8: Avoiding Infinite Loops
An infinite loop is a loop that never ends because its condition never becomes false. Every programmer writes one sooner or later, so do not panic. Here is a typical example. It is shown without a Try button on purpose:
stock = 5
while stock > 0:
print("Selling...")
# Forgot to write: stock = stock - 1
# stock is always 5, so this loop never ends!
If your program seems stuck in the playground, press the Stop button. On your own computer, press Ctrl + C in the terminal. Then look for the line that should change the loop condition.
Before you run a while loop, ask yourself one question: “Which line moves me closer to the end?” If you cannot point to it, the loop will run forever.
Step 9: The Loop else (Briefly)
Python has an unusual feature: a loop can have an else block. It runs only when the loop finishes normally, without a break. It is handy for searches: “I looked at every name and did not find it.” You will not need it often, but now you will recognise it when you see it.
absent_today = ["Kabir", "Sana"]
search = "Ravi"
for name in absent_today:
if name == search:
print(f"{search} is absent today.")
break
else:
# runs only if the loop finished WITHOUT a break
print(f"{search} is not on the absent list.")
# Ravi is not on the absent list.
Real-Life Example: A Savings Plan for a New Phone
Riya wants to buy a phone. She can save Rs. 500 every month from her part-time tuition work, and every third month her grandmother adds Rs. 100 to her savings box. How many months will it take? We do not know the number of months in advance, so this is a job for a while loop. The Input box already holds a price of 6000 and monthly savings of 500.
goal = int(input("Price of the phone you want (Rs.): "))
monthly = int(input("How much can you save each month (Rs.)? "))
saved = 0
month = 0
while saved < goal:
month = month + 1
saved = saved + monthly
if month % 3 == 0:
saved = saved + 100 # a small bonus from family every 3 months
print(f"Month {month}: Rs. {saved} (got a Rs. 100 bonus)")
else:
print(f"Month {month}: Rs. {saved}")
print(f"You reach your goal of Rs. {goal} in {month} months.")
print(f"You will have Rs. {saved - goal} left over.")
With the default input, the program prints one line per month and finishes with “You reach your goal of Rs. 6000 in 12 months.” and Rs. 400 left over. The % operator (remainder) checks for every third month: month % 3 == 0 is true for months 3, 6, 9 and 12.
Try these changes:
- Change the inputs to a price of 15000 and savings of 1200.
- Add a
breakthat stops the plan after 24 months and prints “This goal needs more than two years.” - Remove the bonus and see how many extra months Riya needs.
Common Mistakes
- Expecting
range()to include the stop number.range(1, 10)stops at 9. Writerange(1, 11)to reach 10. - Forgetting to update the counter in a
whileloop. The loop runs forever. Make sure a line inside the loop changes the condition, and use the Stop button if you get stuck. - Resetting the total inside the loop. If
total = 0is inside the loop, it goes back to zero every time. Put it before the loop. - Wrong indentation. A line that should run once after the loop is indented by mistake, so it runs on every iteration. Check which lines are pushed in.
- Changing the loop variable and expecting the loop to follow. In
for i in range(5):, writingi = 10inside the loop does not skip ahead. The next iteration still takes the next number from the range.
Practice Task: The Kirana Store Day Report
A small store wants a short report at the end of the day. Complete the three TODOs in the starter code:
- Use a
forloop and anifto count how many times “milk” was sold - Use
range()to print the 5 times table - Use a
whileloop to sell 6 eggs at a time from a stock of 20, until fewer than 6 are left
items_sold = ["milk", "bread", "milk", "eggs", "milk", "bread", "atta", "milk"]
# TODO 1: Use a for loop to count how many times "milk" was sold
# TODO 2: Use range() to print the 5 times table from 5 x 1 to 5 x 10
# TODO 3: Use a while loop: start with 20 eggs in stock and sell 6 per
# customer until fewer than 6 are left. Print the stock after
# each sale, then print how many eggs are left at the end.
Show one possible answer (try it yourself first!)
items_sold = ["milk", "bread", "milk", "eggs", "milk", "bread", "atta", "milk"]
# 1. Counting milk
milk_count = 0
for item in items_sold:
if item == "milk":
milk_count = milk_count + 1
print(f"Milk sold: {milk_count} times") # Milk sold: 4 times
# 2. The 5 times table
for i in range(1, 11):
print(f"5 x {i} = {5 * i}")
# 3. Selling eggs
eggs = 20
while eggs >= 6:
eggs = eggs - 6
print(f"Sold 6 eggs. Stock: {eggs}")
print(f"Eggs left at the end: {eggs}")
# Sold 6 eggs. Stock: 14
# Sold 6 eggs. Stock: 8
# Sold 6 eggs. Stock: 2
# Eggs left at the end: 2
Key Takeaways
- A
forloop takes each item from a list, a string or arange(), one at a time. range(start, stop, step)makes a sequence of numbers. The stop number is never included.- To add up a total, start a variable at 0 before the loop and add to it inside the loop.
- A
whileloop runs as long as its condition is true, so something inside it must change the condition. breakends a loop early andcontinueskips to the next iteration. Press Stop if a loop never ends.