In the “while” loop, we iteratively execute some code, based on certain conditions. Until the mentioned/decided condition is fulfilled, we will keep iterating.
“while” loop is also called “indefinite loop” as it keeps running til some logical condition is reached.
# Initialize a counter
counter = 0
# Loop until the counter reaches certain limit
while counter <= 5:
print(counter)
# Increase the counter
counter += 1
PythonOutput:
0
1
2
3
4
5
Plaintext# Initially there is not conditions for iteration limit of the loop
# It will keep iterating
while True:
inputStr = input("\nEnter your input here (or type # and press enter to end/cancel):\n\n")
# Break the loop if user enters #
if inputStr == "#":
print("While loop execution complete")
break
print(f"Input: {inputStr}")
PythonOutput:
Enter your input here (or type # and press enter to end/cancel):
test
Input: test
Enter your input here (or type # and press enter to end/cancel):
another test
Input: another test
Enter your input here (or type # and press enter to end/cancel):
last test
Input: last test
Enter your input here (or type # and press enter to end/cancel):
#
While loop execution complete
Plaintext