Python while loops
A while loop repeats a block of code for as long as a condition is true. It is one of the two iteration constructs required by every UK GCSE Computer Science specification (the other is the for loop). This unit covers the basic structure, how to make sure the loop actually stops (the classic infinite-loop mistake), using while loops for input validation, and the break statement for early exit. Every example runs in the browser so learners can watch the loop counter change on each iteration. Perfect for classroom teaching, GCSE and A Level revision, and independent or home-schooled learners.
What you'll learn
- Write a while loop with a clear stopping condition
- Update the loop variable inside the body to avoid infinite loops
- Use while for input validation (keep asking until the input is valid)
- Exit early with break when needed
- Distinguish condition-controlled (while) from count-controlled (for)
UK GCSE topic coverage
- Condition-controlled iteration
- Running totals
- Sentinel-controlled iteration
- Looping over characters
- Linear search preview
- String building
- Input validation
- Selection inside iteration
- Applied iteration
Worked example
Keep asking until the user enters a positive number
n = int(input("Enter a positive number: "))
while n <= 0:
print("That isn't positive.")
n = int(input("Try again: "))
print("Thanks, got", n)Try a full unit free with a RunPy account
Sign up free and get the whole of Unit 1 (Input, Output and Variables) with checked tasks and instant feedback, plus a selection of the exam-style questions so you can practice on real GCSE-style content before upgrading.
Lessons in this unit
Full interactive lessons with checked tasks are available to signed-in RunPy users. Unit 1 and a selection of exam-style questions are free with a RunPy account.
- Introducing while loops
- The accumulator pattern
- Sentinel-controlled loops
- Iterating over a string with while
- Searching inside a string
- Building a new string in a loop
- Input validation loops
- Nested logic inside loops
- Composite algorithm challenge
Frequently asked questions
- What causes an infinite loop?
- Forgetting to change the value that the condition tests. If the condition never becomes False, the loop runs forever. Always make sure the body modifies the variable in the condition.
- When should I use while instead of for?
- Use while when you don't know in advance how many times you need to loop — for example, keep asking for input until it's valid. Use for when you know exactly how many iterations you need.
- What does break do?
- break exits the loop immediately, skipping any remaining iterations. Useful for 'stop as soon as we find what we're looking for'.