Skip to main content
Module 2 · Lesson 2 of 46/36 in the course~14 min
Module lessons (2/4)

while loops

Lesson preview5 hands-on exercises readyPython Course · Module 2 — Control flow

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) and while (dynamic termination condition).
  • Write safe while loops that always make progress towards the exit condition.
  • Emulate do-while loops with the idiomatic pattern while True: + guard condition break.

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

  1. 1The mental model: pre-condition + progress invariant
  2. 2Classic shapes and confident patterns
  3. 3Quick check
  4. 4Test yourself
Pro Lesson · Module 2 — Control flow

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.