Welcome back! In the previous tutorial, we learned about the for
loop and how it allows us to iterate over sequences. Now, let’s dive into another powerful looping construct: the while
loop. The while
loop in Python is used to repeatedly execute a block of code as long as a given condition is true. This is especially useful when the number of iterations is not known beforehand. In this article, we’ll explore how to use the while
loop in Python effectively.
What is a While Loop?
A while
loop repeatedly executes a block of code as long as the specified condition evaluates to True
. The condition is checked before each iteration, and if it evaluates to False
, the loop terminates.
Syntax
The basic syntax of a while
loop in Python is:
while condition:
# Code to execute while the condition is true
Here, condition
is a boolean expression that is evaluated before each iteration. If the condition is True
, the code inside the while
block is executed. If the condition is False
, the loop terminates, and the program continues with the next statement after the loop.
Example: Simple While Loop
Let’s start with a simple example of a while
loop that prints numbers from 1 to 5.
count = 1
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
In this example, the while
loop iterates as long as count
is less than or equal to 5. The count
variable is incremented by 1 in each iteration.
Infinite Loop
A while
loop can become an infinite loop if the condition never evaluates to False
. An infinite loop will keep running until you manually interrupt it or force the program to stop.
Example: Infinite Loop
while True:
print("This is an infinite loop. Press Ctrl+C to stop.")
Be cautious with infinite loops, as they can cause your program to hang.
Using break
Statement
The break
statement is used to exit a loop prematurely, even if the loop’s condition is still True
.
Example: Using break
in a While Loop
count = 1
while count <= 10:
print(count)
if count == 5:
break
count += 1
Output:
1
2
3
4
5
In this example, the while
loop is terminated when count
equals 5, thanks to the break
statement.
Using continue
Statement
The continue
statement is used to skip the current iteration of the loop and proceed to the next iteration.
Example: Using continue
in a While Loop
count = 0
while count < 10:
count += 1
if count % 2 == 0:
continue
print(count)
Output:
1
3
5
7
9
In this example, the while
loop skips the current iteration when count
is even, thanks to the continue
statement.
Using else
with While Loop
The else
block can be used with a while
loop. The else
block is executed when the loop condition becomes False
.
Example: Using else
with While Loop
count = 1
while count <= 5:
print(count)
count += 1
else:
print("Loop has ended.")
Output:
1
2
3
4
5
Loop has ended.
In this example, the else
block is executed after the while
loop finishes iterating.
Example: Using While Loop in a Program
Let’s create a simple program that prompts the user to guess a number between 1 and 10.
import random
# Generate a random number between 1 and 10
target_number = random.randint(1, 10)
# Initialize the guess variable
guess = None
# Start the while loop
while guess != target_number:
guess = int(input("Guess a number between 1 and 10: "))
if guess < target_number:
print("Too low! Try again.")
elif guess > target_number:
print("Too high! Try again.")
print("Congratulations! You guessed the correct number.")
In this program, we:
- Generate a random number between 1 and 10 using the
random.randint()
function. - Initialize the
guess
variable toNone
. - Use a
while
loop to repeatedly prompt the user to guess the number. - Provide feedback if the guess is too low or too high.
- Congratulate the user when they guess the correct number.
Conclusion
The while
loop is a powerful control structure in Python that allows you to execute a block of code repeatedly based on a condition. Understanding how to use while
loops, along with the break
and continue
statements, will help you write more flexible and dynamic programs.
In our next tutorial, we’ll explore functions in Python, which allow you to organize your code into reusable blocks. Stay tuned, and happy coding!