8 Python While loop
8 Python While loop
A while loop in Python programming language repeatedly executes a target statement as long as the
specified boolean expression is true.
This loop starts with while keyword followed by a boolean expression and colon symbol (:). Then, an
indented block of statements starts.
Here, statement(s) may be a single statement or a block of statements with uniform indent.
The condition may be any expression, and true is any non-zero value.
As soon as the expression becomes false, the program control passes to the line immediately
following the loop.
If it fails to turn false, the loop continues to run, and doesn't stop unless forcefully stopped.
while expression:
statement(s)
count=0
while count<5:
count+=1
You must be cautious when using while loops because of the possibility that this condition never
resolves to a FALSE value.
This results in a loop that never ends. Such a loop is called an infinite loop.
count=0
while count<5:
If the else statement is used with a while loop, the else statement is executed when the condition
becomes false before the control shifts to the main line of execution.
count=0
while count<5:
count+=1
else:
i=0
while i < 5:
print(i)
i += 1
i=0
while i < 3:
print(i)
i += 1
else:
print("Loop finished")
while True:
i=0
print(fruits[i])
i += 1
while True:
if num == 0:
print("Exiting...")
break