Python provides different type of looping mechanism.
while is the most popular one after
while loops generally used to iterate and check given condition result as boolean. If the condition is
True the loop will resume but if the condition is
False the while loop will be ended.
Here is the syntax of
while loop in Python.
while (CONDITION): STATEMENT
In this part we will look simple but instructive example in order see how
while loop works. We will create a int variable
count and we will count up to
10 . When the counter is
10 we will stop the while loop.
counter=0 while counter < 10: print(counter) counter = counter+1
General development problems will generally requires to stop loops if given condition is met. But some time we may need to run loops forever unless it is ended externally like killing the process. In this example we will look
infinite loop . We will put
True boolean value to the
while condition part like below.
while (True): print("I will run forever")
Else Statement with While
else is a python statements which is used with
if-elif-else statements. But there is also use case with
while statement too.
else statement executed when while loop is ended with a
False condition. In this example we use previous example but also add
else statement and print
"Previous while loop ended" .
counter=0 while counter < 10: print(counter) counter = counter+1 else: print("Previous while ended loop ended")
while loops we may need to terminate the loop. There are different ways to terminate a loop. First one is we can change the condition of
while loop but this can not be easy sometimes. Second one is better, more readable and practical way. We can end the loop with
break will stop the loop where it issued.
In this example we will stop the loop if the counter is equal to
5 by issuing
counter=0 while counter < 10: if(counter==5): break print(counter) counter=counter+1