Python Concept: While Loop
Example Code:
# Example: Print numbers from 1 to 5 using while loop
count = 1
while count <= 5:
print("Number:", count)
count += 1
print("Loop ended.")
Explanation of While Loop
1. A while loop in Python is used to repeatedly execute a block of code as long as a given
condition is True.
2. In this example, the variable count starts at 1.
3. The loop condition while count <= 5 means the loop will continue running as long as count is
less than or equal to 5.
4. Inside the loop, the current value of count is printed, and then it is increased by 1 using count +=
1.
5. When count becomes 6, the condition becomes False and the loop stops.
6. Finally, the program prints "Loop ended." to indicate the end of the loop.
Sample Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Loop ended.