While Loop
While is a condition controlled loop. It continues on condition that a certain test is met. In the example below the loop while continue so long as x > 0.
The pseudocode here does the following:
A variable called x is created and set to 15 A variable called y is created and set to 0 The while loop checks if x is greater than 0. It is so the code inside the loop will be executed.
It is, so the code inside will be executed again. This will continue until the while conditon ( x >0) fails. At this point the code inside the loop will be skipped and the following line of code will be executed. print(y). What will be displayed?Check the trace table to see all values of the given variables x and y, as well as the output.
|
While True
The following code is an infinite loop. It will keep displaying Hello World and never stop.
The following code is also an infinite loop. CheckThis is a boolean variable which is set to true. While ( CheckThis) is the same as While(CheckThis == true)
Do While Loop
The Do While loop will run the code inside the loop before checking the test condition. So in the code below the user will be asked to enter a password once before the password is checked.
Getting out of a Loop.. Break and Continue
Most loops include many lines of code which need to be executed inside the loop. Find out more about break and continue on W3Schools here.
Want to know more?
Find out more on W3Schools by clicking here.