While loop

 A while loop repeatedly executes instructions inside the loop while a certain condition remains valid.


Syntax

while condition is true:

    do A


When using a while loop, we need to first declare a variable to function as a loop counter. We will call this variable counter. The condition in the while statement will evaluate the value of counter to determine if it is smaller (or greater) than a certain value. If it is, the loop will be executed.


Example

counter = 5

while counter > 0:

    print("Counter = ", counter)

    counter = counter - 1


The line counter = counter - 1 is crucial as it decreases the value of counter by 1 and assigns this new value back to counter, overwriting the original value. We do this so that the loop condition while counter > 0 will eventually evaluate to False. If we do not do that, the loop will keep on running resulting in an infinite loop.

No comments:

Post a Comment