Python while Loops
Loops in Python
Loops allow you to execute a block of code repeatedly. Python provides two primary looping constructs:
• while loop – repeats as long as a condition remains true
• for loop – 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 :
while condition:
# code to execute
Example: Counting Numbers
• The loop runs while count < 5
• count += 1 is 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 number becomes 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 value is 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 else block 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
