While Loops
tags: #python/documentation/python_loops
Indefinite Loops Using While
Unlike a For Loop, which executes a block of code a finite number of times. The while loop is used to execute a block a code for as long as a condition is True. We can create a while loop using the while keyword:
#count control variable
while condition_statement:
#body of loop
<statement>
...
# control statement
Count Control Variable
In a while loop, a count control variable is explicitly initialized before the loop, and the loop continues to execute as long as a specified condition is True. The count variable is typically updated within the loop body as the control statement. Depending on how this variable is defined, the loop may or may not have a fixed number of iterations.
- This is AKA "loop control variable" or "counting variable".
This variable is used to control the loop's execution based on a specified condition. The loop executes for as long as the condition associated with the loop control variable remains True.
The loop control variable can be of any data type that can be evaluated using a Boolean Values and Expression.
General Structure
# Initialization of the loop control variable
count = 0
# While loop with a condition based on the loop control variable
while count < 5:
# Code inside the loop body
print(count)
# Iteration (update) of the loop control variable
count += 1
# Code outside the loop
Loops Without Conditions
We can run while loop without any condition using the following:
while True:
# body of loop
if condition
break
...
Instead of writing a condition after the while keyword, we just write the true value directly to indicate that the condition will always be True.
The while True loop in python will run without any conditions until the break statement executes inside the loop.
This happens because the while statement takes an expression and executes the loop body while the expression evaluates to True. Since True always evaluates to boolean 'True', the loop body executes indefinitely.