Python while
Loop
In Python, loops are essential constructs that allow repetitive execution of code. One of the most commonly used loops is the while
loop. It enables you to repeat a block of code as long as a specified condition is True
. If you’re looking to understand how to use the while
loop in Python effectively, this post is for you!
In this blog post, we will explain how the while
loop works in Python, go through its syntax, and provide several examples to help you learn how to use it in your own programs.
while
Loop in Python?The while
loop in Python repeatedly executes a block of code as long as a given condition evaluates to True
. Once the condition becomes False
, the loop terminates.
while
Loop:
while condition:
# Code to execute while the condition is True
while
loop is executed as long as the condition is True
.while
Loop WorksThe while
loop begins by checking the condition. If the condition is True
, the block of code inside the loop runs. After the block of code is executed, the condition is checked again. If it’s still True
, the loop repeats. This continues until the condition becomes False
.
while
LoopLet’s look at a simple example where we print numbers from 1 to 5.
# Example: Simple while loop
num = 1
while num <= 5:
print(num)
num += 1 # Increment num by 1
Output:
1
2
3
4
5
In this example:
num
is less than or equal to 5.num
is incremented by 1.num
becomes 6, the condition num <= 5
becomes False
, and the loop stops.while
LoopIf you’re not careful with your condition, it’s possible to create an infinite loop, where the condition never becomes False
. This is often unintentional but can happen if the condition always evaluates to True
.
while
Loop
# Example: Infinite while loop (never ending)
while True:
print("This will run forever!")
Warning: The loop above will run infinitely, printing the message repeatedly until you interrupt the program (e.g., by pressing Ctrl+C
).
To avoid infinite loops, always ensure that the condition will eventually evaluate to False
at some point.
break
and continue
with a while
LoopPython’s while
loop can also use break
and continue
statements for controlling the flow of the loop.
break
: Terminates the loop immediately.continue
: Skips the rest of the code in the current iteration and moves to the next iteration.break
in a while
Loop
# Example: Using break to exit the loop
count = 0
while count < 10:
if count == 5:
break # Exit the loop when count reaches 5
print(count)
count += 1
Output:
0
1
2
3
4
In this example:
count
reaches 5.count == 5
, the break
statement is triggered, and the loop exits.continue
in a while
Loop
# Example: Using continue to skip iteration
count = 0
while count < 5:
count += 1
if count == 3:
continue # Skip printing when count is 3
print(count)
Output:
1
2
4
5
In this case:
count
equals 3, the continue
statement causes the loop to skip that iteration and move to the next.while
LoopsJust like other loops, you can also have nested while
loops, where one while
loop is inside another. This is useful when working with multi-dimensional data or performing repeated tasks within another repeated task.
while
Loop
# Example: Nested while loop
i = 1
while i <= 3:
j = 1
while j <= 2:
print(f"i={i}, j={j}")
j += 1
i += 1
Output:
i=1, j=1
i=1, j=2
i=2, j=1
i=2, j=2
i=3, j=1
i=3, j=2
In this example:
while
loop iterates over i
from 1 to 3.i
, the inner while
loop iterates over j
from 1 to 2.else
with a while
LoopIn Python, you can use the else
block with a while
loop. The else
block runs when the loop condition becomes False
and the loop exits normally (i.e., not due to a break
statement).
else
with a while
Loop
# Example: Using else with while loop
count = 0
while count < 3:
print(f"Count is {count}")
count += 1
else:
print("Loop completed without a break.")
Output:
Count is 0
Count is 1
Count is 2
Loop completed without a break.
In this example:
else
block executes after the loop completes, as the condition count < 3
becomes False
.Let’s implement a simple guessing game where the program repeatedly asks the user to guess a number until they get it right.
# Example: Guessing game using while loop
secret_number = 7
guess = None
while guess != secret_number:
guess = int(input("Guess the secret number: "))
if guess < secret_number:
print("Too low, try again.")
elif guess > secret_number:
print("Too high, try again.")
else:
print("Congratulations, you guessed it!")
In this example:
while
loop continues asking the user for input until they guess the correct number.