Python While Loops
Python While Loop is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the line immediately after the loop in the program is executed.
Syntax
while expression: statement(s)
Example
i = 1 while i < 5: print(i) i += 1
Flowchart of While Loop
While loop falls under the category of indefinite iteration. Indefinite iteration means that the number of times the loop is executed isn’t specified explicitly in advance.
The break Statement
With the break statement
we can stop the loop even if the while condition is true:
Example
while i< 5: print(i) if i == 4: break i += 1 Output 1 2 3 4
The continue Statement
With the continue statement
we can stop the current iteration, and continue with the next:
Example
i= 0 while i < 6: i+= 1 if i == 4: continue print (i) Output 1 2 3 4 5 6
The else Statement
With the else statement
we can run a block of code once when the condition no longer is true:
Example
i= 1 while i < 5: print(i) i += 1 else: print("i is no longer less than 5") Output 1 2 3 4 i is no longer less than 5