Skip to content

Module 6 · Loops and Iteration — topic 2 of 12

while loops

A while loop repeats its block as long as a condition is true. Learn its structure, how to make sure it stops, typical patterns such as input validation and countdowns, and sentinel values.

Beginner 12 min read·Lesson 71 of 306 in Python Programming

Learning objectives

  • Write while loops that terminate
  • Update the loop variable correctly
  • Use while for input validation and sentinel-controlled input

Definition

A while loop repeats its block as long as a condition is true. Learn its structure, how to make sure it stops, typical patterns such as input validation and countdowns, and sentinel values.

Introduction

A while loop checks a condition; if it is true, it runs the body, then checks the condition again, and so on. As soon as the condition is false, the loop ends and the program continues after it.

Why it matters

Many tasks repeat an unknown number of times: keep asking until the answer is valid, keep doubling until a target is reached, keep reading until the user types quit. while is the natural fit for all of these.

Detailed explanation

The condition is checked before every iteration, including the first. If it is false at the start, the body never runs.

Something in the body must eventually make the condition false: updating a counter, reading new input or changing state. Otherwise the loop never ends.

A counter loop needs three parts: initialise (n = 1), test (while n <= 5), update (n += 1).

Input validation pattern: ask once before the loop, and inside the loop ask again while the answer is invalid.

A sentinel is a special value that signals the end of input, such as an empty line or the word done. The loop runs while the input is not the sentinel.

while True: with a break inside is a common, readable alternative when the stopping test naturally sits in the middle of the body.

Syntax

Text
initialise
while condition:
body
update
  • Set up the variables the condition uses.
  • The condition is tested before each iteration.
  • The update must move towards the condition becoming false.

Code examples

A countdown

Python
count = 3
while count > 0:
print(count)
count -= 1
print("Lift-off!")
Output
3
2
1
Lift-off!

Doubling until a target

Python
amount = 1000
years = 0
while amount < 2000:
amount *= 1.1
years += 1
print(years, round(amount, 2))
Output
8 2143.59

More examples

Validation and a sentinel

Python
age = input("Age: ")
while not age.isdigit():
print("Please enter digits only.")
age = input("Age: ")
print("Age accepted:", int(age))
total = 0
entry = input("Expense (blank to finish): ")
while entry != "":
total += float(entry)
entry = input("Expense (blank to finish): ")
print("Total spent:", total)
Input
twenty
20
120
45.5
Output
Age: Please enter digits only.
Age: Age accepted: 20
Expense (blank to finish): Expense (blank to finish): Expense (blank to finish): Total spent: 165.5

Step-by-step explanation

  • The first input is read before the loop so the condition has something to test.
  • While the answer isn’t all digits, an error is shown and the question is asked again.
  • The expense loop uses an empty line as the sentinel that stops input.
  • Each valid expense is added to total, and the prompts appear on one line here because typed input isn’t echoed during automatic checking.

Expected output

Running “Validation and a sentinel” with the sample input shown prints exactly:

TextInput
twenty
20
120
45.5
TextOutput
Age: Please enter digits only.
Age: Age accepted: 20
Expense (blank to finish): Expense (blank to finish): Expense (blank to finish): Total spent: 165.5

Practical applications

  • ATMs keep asking for a PIN until it is correct or attempts run out.
  • Downloaders retry while a connection keeps failing, up to a limit.
  • Simulations run while a time variable is below the end time.

Best practices

  • Make sure every path through the body moves towards ending the loop.
  • Prefer for when you know the number of iterations.
  • Add an attempt limit to loops that wait for external events.

Common mistakes

Forgetting to update

Avoid

n = 1
while n <= 5:
print(n)

Prefer

n = 1
while n <= 5:
print(n)
n += 1

Without n += 1 the condition never becomes false, causing an infinite loop.

Not reading input again inside the loop

Avoid

answer = input()
while answer != "yes":
print("Try again")

Prefer

answer = input()
while answer != "yes":
answer = input("Try again: ")

If the value tested never changes, the loop runs forever.

Key takeaways

  • while repeats while its condition is true.
  • The condition is checked before each iteration.
  • Initialise, test and update to make loops terminate.

Try it yourself

  1. 1
    Ask for numbers until the user types 0, then print their sum.
  2. 2
    Find how many times you can halve 1000 with // before it reaches 0.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic