Python while Loops
Loops in Python
Loops allow you to execute a block of code repeatedly. Python provides two primary looping constructs:
-
whileloop – repeats as long as a condition remains true -
forloop – iterates over a sequence (like a list, range, or string)
This section focuses on the
while loop.
The while Loop
A while loop
runs a block of code as long as a specified condition evaluates to
True.
Syntax:
Example: Counting Numbers
-
The loop runs while
count < 5 -
count += 1is essential to avoid an infinite loop
Note: Always update the condition variable inside the loop.
Preparing the Loop Variable
Before a
while loop
starts, the variable used in the condition must be initialized.
Without initializing
attempts,
Python would raise an error.
The break Statement
The
break
statement terminates the loop immediately, even if the condition is still
true.
Example: Stop When a Match Is Found
-
Loop stops as soon as
numberbecomes 6 - Remaining iterations are skipped
The continue Statement
The
continue
statement skips the current iteration and moves directly to the next one.
Example: Skip a Specific Value
-
When
valueis 4, printing is skipped - Loop continues normally afterward
The else Block in a while Loop
The
else block
executes once, when the loop condition becomes false naturally (not via
break).
Example: Loop Completion Message
-
The
elseblock runs after the loop finishes - Useful for success messages or cleanup tasks
Important Note About break
If a
while loop is
terminated using
break, the
else block
will not execute.
Note: "Loop finished" is not printed because the loop exited early.
Common Use Cases of while Loops
- Repeating tasks until user input is valid
- Running background checks
- Implementing retry mechanisms
- Reading data until a condition is met
