Python While Loops
In Python, a while
loop is used to repeatedly execute a block of code as long as a certain condition is true. The general syntax of a while
loop in Python is as follows:
python
while condition:
# Code to be executed
The condition is a Boolean expression that determines whether the loop should continue executing or not. If the condition is initially false, the code inside the loop will not be executed at all.
Here’s an example that demonstrates a simple while
loop that prints numbers from 1 to 5:
python
count = 1
while count <= 5:
print(count)
count += 1
In this example, the variable count
is initially set to 1. The condition count <= 5
is evaluated before each iteration. As long as the condition is true, the code inside the loop (printing the value of count
) will be executed. After each iteration, the value of count
is incremented by 1 using the +=
operator. The loop continues until the condition becomes false when count
exceeds 5.
It’s important to ensure that the condition within the while
loop will eventually become false; otherwise, you may end up with an infinite loop, which can cause your program to hang or crash. To avoid this, you can include additional logic within the loop to modify the condition or use break
statement to exit the loop based on certain conditions.
Here’s an example of using a while
loop with a break
statement to simulate a simple guessing game:
python
secret_number = 42
while True:
guess = int(input("Enter your guess: "))
if guess == secret_number:
print("Congratulations! You guessed it.")
break
else:
print("Wrong guess. Try again.")
In this example, the while
loop continues indefinitely (True
is always true), but it can be exited using the break
statement when the user guesses the correct number.
Remember to be cautious while using while
loops to avoid infinite loops and ensure that the condition is appropriately modified within the loop to eventually become false.