The basic syntax for while
loop in Python is as follows:
main.py34 chars3 lines
The loop will keep running until the condition
is True
. Once the condition
becomes False
the loop will terminate and the program will continue to execute whatever is after the loop.
For example, let's say we want to print numbers from 0 to 4 using while
loop. We can write the following code to achieve that:
main.py59 chars5 lines
Output:
main.py10 chars6 lines
In the above example, the condition
is count < 5
and we start with count = 0
. We print the value of count
and increment it by 1. This process is repeated until the condition
becomes False
.
Note: Be careful while using while
loop, since if the condition
is always True
the loop will become an infinite loop and the program will never terminate. In that case, you'll need to manually terminate the program.
In general, the while
loop is useful when you need to execute a block of code repeatedly until a certain condition is met.
gistlibby LogSnag