Python - While Loops
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.
Such a loop is called infinite loop, which is undesired in a computer program.
while expression:
statement(s)
count=0
while count<5:
count+=1
print ("Iteration no. {}".format(count))
print ("End of while loop")
Python Infinite while Loop
A loop becomes infinite loop if a condition never becomes FALSE.
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:
print ("Iteration no. {}".format(count))
print ("End of while loop")
Python while-else Loop
Python supports having an else statement associated with a while loop.
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
print ("Iteration no. {}".format(count))
else:
print ("While loop over. Now in else block")
print ("End of while loop")
Some other examples
i=0
while i < 5:
print(i)
i += 1
i=0
while i < 3:
print(i)
i += 1
else:
print("Loop finished")
while True:
print("This will run forever unless stopped!")
break # Use break to prevent an infinite loop
fruits = ["apple", "banana", "cherry"]
i=0
while i < len(fruits):
print(fruits[i])
i += 1
while True:
num = int(input("Enter a number (0 to exit): "))
if num == 0:
print("Exiting...")
break
print(f"You entered: {num}")