Python while Loop – Executes a target statement until a given condition is true. The while loop works on the repeated execution of code based on a given Boolean condition. If you have already known in programming then you know this statement is common in various programming languages.
As below digram, the first loop checks the conditions then decide what to do. For example, if 2 > 1 then a condition is true and then the next code statement will execute. Now in next loop condition is 2 > 2, which means its wrong and loop will be over.
In this tutorial, you will learn how to use a Python while Loop Statements with a basic example.
The Basic syntax of while true loop.
The something that is being done will continue to be executed until the condition that is being assessed is no longer true.
Python while Loop Example
The loop run until the
count < 9 (when the count is greater or equal to 9, it will break the loop), and print the current count in the console.
count = 0
while count < 9:
print("The count is:", count)
count = count + 1
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
As you can see, this compacts the whole thing into a piece of code managed entirely by the while loop. It’s a just Basic and Simple python while loop example.
Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Allof The example of while is in Python 3, so it may change its different from python 2 or upgraded versions.