We have studied loops in earlier lectures. There is another type of loop called While Loops. They work similarly to for loops. But differ in the sense that it allows the user to terminate the loop by setting flags.
A while loop is a fundamental concept in Python programming that allows you to repeatedly execute a block of code as long as a specified condition is true.
Syntax
while condition:
# code to be executed
The block of code under the “while” statement is executed repeatedly as long as the specified condition is true. The condition evaluates before each iteration, and if it is true, the loop continues. Once the condition becomes false, the loop stops.
When using while loops, be cautious to avoid infinite loops. Ensure the loop condition will eventually become false based on changes within the loop. While loops are useful for situations where the number of iterations is not known in advance. They provide a flexible way to control the flow of the program based on a dynamic condition. However, it is important to use them judiciously and ensure that the condition will eventually change to false to avoid infinite loops.
Example
a=0
while a<10:
print("This is while loop printing")
a += 1