A while
loop in Python allows you to repeatedly execute a block of code as long as a specified condition is True
. Unlike a for
loop that runs a predefined number of times, a while
loop continues until its condition becomes False
. This makes it particularly useful when the number of iterations is not known in advance.
Syntax of the while
Loop
The basic syntax of a while
loop is:
condition
: The loop will continue to execute as long as this condition evaluates to True
.False
.while
Loopcounter <= 5
is checked before each iteration. Once counter
becomes greater than 5, the loop stops.while
loop.True
.counter += 1
).while
LoopThe while
loop is ideal for cases where you don’t know in advance how many iterations you’ll need.
If the loop condition never becomes False
, the loop will run indefinitely. Be cautious when writing while
loops to avoid infinite loops unless they're intentional.
True
is always satisfied.while
Loop: break
and continue
break
Statement:The break
statement allows you to exit the loop immediately, regardless of the loop condition.
break
count
reaches 5, the loop terminates because of the break
statement.continue
Statement:The continue
statement skips the rest of the loop's current iteration and moves on to the next one.
continue
continue
, but continues with the next iteration.else
with a while
LoopPython allows an else
block to be used with a while
loop. The else
block is executed when the loop condition becomes False
naturally, not when the loop is exited via break
.
else
block executes after the loop completes, printing "Loop finished."while
LoopYou can use a while
loop to calculate the factorial of a number.
factorial
by n
until n
becomes 0. The result is 5! = 120
.A while
loop is great for repeating actions until a specific condition is met.
The while
loop in Python is a powerful control structure that allows for repeated execution of a block of code as long as a condition is True
. Whether used for user input, calculations, or even infinite loops, while
loops provide flexibility in situations where the number of iterations isn't predetermined. By combining it with statements like break
and continue
, you can effectively manage loop control and improve the efficiency of your programs.