Professional Documents
Culture Documents
While Loops1
While Loops1
A "while loop" is a control flow statement in programming used to repeatedly execute a block
of code as long as a specified condition is true. It's useful when you want to repeat a task
multiple times until a certain condition is met.
1. **Condition**: This is the expression that is evaluated before each iteration of the loop. If
the condition evaluates to true, the loop continues executing; otherwise, it terminates.
2. **Loop Body**: The block of code inside the loop that gets executed repeatedly as long as
the condition remains true. It's often enclosed within curly braces `{}`.
Let's consider a simple example in Python where we want to print numbers from 1 to 5 using
a "while loop":
```python
i=1
while i <= 5:
print(i)
i=i+1
```
While loops are commonly used when you need to repeatedly process user input until a
certain condition is met. Here's an example in Python where we ask the user to enter a
positive number:
```python
number = int(input("Enter a positive number: "))
while number <= 0:
number = int(input("Invalid input! Please enter a positive number: "))
print("You entered:", number)
```
In this example, the loop continues to prompt the user to enter a positive number until they
provide a valid input (i.e., a number greater than `0`).
Be cautious when using "while loops" to ensure that the condition can eventually become
false. Otherwise, you may end up with an infinite loop, where the loop continues indefinitely.
For example:
```python
# This is an infinite loop
# Uncomment and run this code at your own risk
# while True:
# print("This is an infinite loop!")
```
### Conclusion:
While loops are essential for repeating a block of code until a specified condition is no longer
true. They provide a way to automate repetitive tasks and handle situations where the number
of iterations is not known in advance. Understanding how to use while loops helps you write
dynamic and flexible programs.