A while loop consists of a condition and until that condition is true, a set of statements is executed repeatedly.
A while loop is the only necessary repetition construct. The for loop, can be duplicated using a while loop, and with more control.
Here’s a look at the while
loop code:
x=4y=0while (y <= 10 ): ## the while loop will run till y<=10 condition is being mety += xx += 1## the loop will iterate 3 timesprint "the value of x is:",xprint "the value of y is:", y
In the code above, the while
loop runs as long as the condition, y<=10
, is being met. The statements on line 4 and line 5 execute if the expression inside the parenthesis evaluates to true.
When the expression evaluates to false the program comes out of the loop and prints the final values of x
and y
.
Below is an illustration of the code above to help illustrate the logic.
Free Resources