While Loops

This lesson covers how to use while loops in Python to execute blocks of code repeatedly as long as a specified condition remains true, and how to ensure your loops terminate correctly.

While Loop
A control flow statement that repeatedly executes a block of code as long as a specified Boolean condition evaluates to true.
Example: Counting down from a number until it reaches zero, where the loop continues as long as the number is greater than zero.

A while loop's structure is straightforward, yet precise. It begins with the while keyword, followed by a condition that evaluates to either True or False. A colon : marks the end of the condition.

The loop body consists of one or more statements, all indented consistently below the while line. These indented statements execute only when the condition is True. The loop continues to re-evaluate the condition and execute the body until the condition becomes False.

pythonBasic While Loop for Counting
⚠️ Beware of Infinite Loops

An infinite loop occurs when the loop's condition never becomes False, causing the program to execute the loop body indefinitely. This typically happens if the variable or state controlling the condition is not updated within the loop, or is updated in a way that always keeps the condition True. Infinite loops can freeze your program, consume excessive system resources, and prevent other code from running.

pythonPreventing Infinite Loops with Condition Updates
Check Your Understanding
Which of the following code snippets will result in an infinite loop?

Practical Applications of While Loops

pythonInput Validation with While Loops
Try It Yourself
Modify the input validation code to ensure the user enters a non-empty string for their name. The loop should continue until a non-empty name is provided.
python
pythonProcessing Data Until a Sentinel Value
Try It Yourself
Adapt the sentinel value example to calculate the sum of numbers entered by the user. The loop should stop when the user enters 0, and then print the total sum. Use int(input(...)) to get numbers.
python
While Loops vs. For Loops
FeatureWhile LoopFor Loop
Primary Use CaseWhen the number of iterations is unknown and depends on a condition.When iterating over a known sequence (list, tuple, string, range) or a fixed number of times.
Iteration ControlControlled by a Boolean condition that must eventually become false.Controlled by the elements in a sequence or a predefined range.
Key AdvantageFlexibility for conditional repetition, input validation, or event-driven tasks.Concise syntax for iterating through collections, often less prone to infinite loops.
Example ScenarioKeep asking for user input until it's valid.Process every item in a shopping cart.
This table outlines the key differences between while and for loops, guiding you on when to choose each for specific programming tasks.
Key Takeaways
  • while loops execute a block of code repeatedly as long as a specified condition remains True.

  • It is essential to ensure that the loop's condition will eventually become False to prevent infinite loops.

  • The loop condition must be updated within the loop body to guarantee proper termination.

  • while loops are best suited for tasks where the number of repetitions is unknown beforehand, such as input validation or processing data until a sentinel value is met.

  • In contrast, for loops are typically used when iterating over a known sequence or a fixed number of times.

← All lessons in Control Flow

Ready to keep this from fading?

Bitelrn turns lessons like this into a full course — quizzes, a knowledge map, and spaced review.

Get started free