Python While Loop
The while
loop in Python is used to repeatedly execute a block of code as long as the given condition is true. Once the condition evaluates to false, the loop stops, and the control moves to the next statement after the loop.
What is a While Loop?
A while
loop runs as long as a specified condition is true. The loop will check the condition before each iteration, and if it is true, it executes the block of code inside the loop. If the condition is false initially, the code inside the loop will not execute.
Syntax of While Loop
Syntax
while condition:
# Code block to execute
Explanation:
In this syntax:condition
: This is an expression that is evaluated to determine whether the loop should continue. If the condition is true, the loop continues; otherwise, it stops.code block
: The block of code inside thewhile
loop is executed each time the condition is true.
1 : Print numbers from 1 to 5
counter = 1
while counter <= 5:
print(counter)
counter += 1
Output
In this example, the
while
loop checks if the counter
variable is less than or equal to 5. If the condition is true, it prints the current value of counter
and then increments it by 1. The loop continues until counter
becomes greater than 5.
Using While Loop with Break
You can use the break
statement inside a while
loop to terminate the loop prematurely, even if the condition is still true. The loop will stop when the break
statement is encountered.
Syntax of Break
Syntax
while condition:
if some_condition:
break
# Code block to execute
Example: Stop the loop when counter reaches 3
counter = 1
while counter <= 5:
if counter == 3:
break
print(counter)
counter += 1
Output
In this example, the
while
loop checks if counter
is less than or equal to 5. If the counter
is 3, the break
statement is executed, causing the loop to terminate. The numbers 1 and 2 are printed before the loop breaks.
Using While Loop with Continue
You can use the continue
statement to skip the current iteration of the loop and continue with the next iteration. When continue
is encountered, the code following it is skipped, and the loop condition is checked again.
Syntax of Continue
Syntax
while condition:
if some_condition:
continue
# Code block to execute
Example: Skip the current iteration when counter is 3
counter = 1
while counter <= 5:
if counter == 3:
counter += 1
continue
print(counter)
counter += 1
Output
In this example, the loop prints numbers from 1 to 5 but skips 3 due to the
continue
statement. When counter == 3
, the continue
skips printing 3 and goes to the next iteration.
Best Practices for Using While Loops
- Ensure the loop condition will eventually become false: If the condition never becomes false, the loop will run indefinitely, leading to an infinite loop.
- Use
break
andcontinue
wisely: Avoid using these statements excessively, as they can make the flow of control harder to understand. - Keep the loop simple: Avoid writing complex code inside the loop to ensure that it runs efficiently.