Module lessons (2/4)
while loops
Repeating while a condition holds true, and when to prefer while over for.
What you'll learn in this lesson
- Choose wisely between
for(known number or sequence) andwhile(dynamic termination condition). - Write safe
whileloops that always make progress towards the exit condition. - Emulate do-while loops with the idiomatic pattern
while True:+ guard conditionbreak.
Overview
While for visits the elements of a defined sequence, while continues to iterate a block as long as a Boolean condition remains true. It is the natural tool for convergence searches, simulations, token parsers, or polling until an event occurs.
Before every single iteration Python checks the boolean expression after while. If at least one variable involved in that condition does not advance within the body of the loop, the program enters an infinite loop.
Sections covered in this lesson
- 1The mental model: pre-condition + progress invariant
- 2Classic shapes and confident patterns
- 3Quick check
- 4Test yourself
Unlock "while loops" and the full Python Course curriculum
Repeating while a condition holds true, and when to prefer while over for.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Python Course plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.