Python While Loop Tutorial

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/python-while-loop-tutorial/
PINTEREST
PINTEREST
INSTAGRAM

Python provides different type of looping mechanism. while is the most popular one after for loops. 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.

Syntax

Here is the syntax of while loop in Python.

Loop

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.

Loop

Loop

Infinite Loop

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.

Infinite Loop

Infinite Loop

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" .

LEARN MORE  C - Arrays

Else Statement with While

Else Statement with While

Premature Termination

While running 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 keyword. 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 break keyword.

Premature Termination

Premature Termination

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/python-while-loop-tutorial/
PINTEREST
PINTEREST
INSTAGRAM

You may also like...

Leave a Reply

Your email address will not be published.

Enjoy this blog? Please spread the word :)