The while loop in Python is basically just a way to construct code that will keep repeating while a certain expression is true. To create a while loop, you’ll need a target statement and a condition, and the target statement is the code that will keep executing for as long as the condition remains true.
- Python Programming – Python Control Statements
- Python Programming – Python Loops
- Using Python’s Pass Statement | What is Pass Statement in Python? | Python pass statement example
The syntax for a while loop looks like this:
while condition
target statement
The best way to understand a while loop, however, is to see what it does in context. Check out how it works in the example below:
count = 0 while (count < 4): print count count = count + 1 print "Bye!"
So the output for the while loop above should look like this:
0 1 2 3 Bye!
Count starts off at 0, and each time the loop is executed, the count is increased by 1, as it’s instructed to by the code (count = count + 1). Because of the condition, the loop is only executed while count is less than four. So after the fourth execution, count becomes four, and the loop is broken. Then the next line of code (print “Bye!”) can be executed.