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.
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.
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.
Practical Applications of While Loops
0, and then print the total sum. Use int(input(...)) to get numbers.| Feature | While Loop | For Loop |
|---|---|---|
| Primary Use Case | When 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 Control | Controlled by a Boolean condition that must eventually become false. | Controlled by the elements in a sequence or a predefined range. |
| Key Advantage | Flexibility for conditional repetition, input validation, or event-driven tasks. | Concise syntax for iterating through collections, often less prone to infinite loops. |
| Example Scenario | Keep asking for user input until it's valid. | Process every item in a shopping cart. |
while and for loops, guiding you on when to choose each for specific programming tasks.whileloops execute a block of code repeatedly as long as a specified condition remainsTrue.It is essential to ensure that the loop's condition will eventually become
Falseto prevent infinite loops.The loop condition must be updated within the loop body to guarantee proper termination.
whileloops 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,
forloops are typically used when iterating over a known sequence or a fixed number of times.