Beginner · Loops: repeating work · topic 10 of 50 · 20 min
while loops
Explanation
Repeat while something is true
A while loop has a condition, like an if. Before each round, Python checks the condition. If it is True, the block runs, and then Python goes back and checks again. When the condition becomes False, the loop ends and the program continues below it.
count = 1
while count <= 5:
print("Count is", count)
count = count + 1
print("Done")Step by step
- Python checks the condition: count <= 5.
- If it is True, the indented block runs once.
- Inside the block, count changes (count = count + 1).
- Python jumps back to step 1 and checks again.
- When the condition is False, Python skips the block and goes to the next line after the loop.
Saving until a goal
A while loop is useful when you do not know in advance how many rounds you need. Here we do not know how many weeks it takes to save for a cricket bat; the loop works it out.
saved = 0
weeks = 0
while saved < 3000:
saved = saved + 450
weeks = weeks + 1
print(f"After {weeks} weeks you have Rs {saved}")Halving and digits
price = 1000
rounds = 0
while price > 100:
price = price // 2
rounds = rounds + 1
print(rounds, price)n = 4721
while n > 0:
digit = n % 10
print(digit)
n = n // 10The short forms from Module 1 are very common in loops: count += 1 means count = count + 1, and n //= 10 means n = n // 10.
Watch the lesson
while loops · 1/6
In this lesson you will learn the while loop, which repeats as long as a condition is true.
Prefer a video by a teacher? Find free videos on “python while loop tutorial for beginners” on YouTube ↗
In real life: Saving for a new phone
Kavya wants a phone that costs Rs 15,000. She can save Rs 1,200 every month from her part-time job. How many months must she wait? A while loop adds one month of savings at a time until she has enough.
phone = 15000
monthly = 1200
saved = 0
months = 0
while saved < phone:
saved += monthly
months += 1
print(f"{months} months, saved Rs {saved:,}")Practice (0/3 done)
Write a function count_digits(n) that returns how many digits the positive whole number n has, using a while loop that removes one digit at a time with // 10. Example: count_digits(12345) returns 5.
Write a function months_to_goal(goal, monthly) that returns how many months of saving monthly rupees it takes to reach at least goal rupees. Example: months_to_goal(15000, 1200) returns 13.
Write a function digit_sum(n) that returns the sum of the digits of the positive whole number n. Example: digit_sum(4721) is 4 + 7 + 2 + 1 = 14.
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.