Python while loop With Examples

In this tutorial we will cover basics of python while loop. In the previous tutorial, we learned about Python for loop.

Python while loop

Python while loop is used to repeatedly execute some statements until the condition is true. So the basic structure of python while loop is:

For example, the following code will give you some ideas about the while loop. In this example, we are printing numbers from 1 to 4 inside loop and 5 in outside of the loop



In the example of for loop tutorial, we print each letter from words. We can implement that code use while loop. The following code will show you that.



An interesting fact about the loop is if you implement something using for loop, you can implement that in a while loop too. Try to implement examples shown in for loop tutorial in a while loop.

Python Nested while loop

You can write while loop inside another while loop. Suppose you need to print a pattern like this

    • 1
    • 1 2
    • 1 2 3
    • 1 2 3 4
    1 2 3 4 5

The following code will illustrate how to implement that using nested while loop.

Python while loop infinite problem

Since the while loop will continue to run until the condition becomes false, you should make sure it does otherwise program will never end. Sometimes it can come handy when you want your program to wait for some input and keep checking continuously.

If you run the above program, it will never end and you will have to kill it using the Ctrl+C keyboard command.

That’s all about python while loop example tutorial. For any queries please comment below.

By admin

Leave a Reply