A While loop's job is to repeat a section of code until you tell it to stop.
In the example below we'll look at two examples of using a While Loop.
Read through the code, predict what it will do, THEN try typing it.
The output is interesting isn't it?
The first part of the program basically uses the while loop to continuously add 1 to the variable called counter.
Counter starts at 0 and stops at the number you wanted to count up to (variable x).
The while loop says:
while counter <=x:
This means "Loop while the variable counter is <=x. When it is NOT <=x, exit the loop.
This is important to understand because this is why and how many times it will loop.
For it to loop, the condition that is being compared must be TRUE. In this case the condition is:
count <= x
Summary: The while statement loops as long as the condition is TRUE. To exit, make it not true!
The second part of the program shows a NESTED LOOP.
This is a LOOP inside of a LOOP. So the first loop activates, then the 2nd loop inside of the 1st one activates.
The 2nd loop must FINISH its looping before it can exit and allow the 1st loop to advance to its second round.
This reactivates the 2nd loop.
This pattern continues until the 1st loop's condition stops.
That's why you get two numbers counting down.
While True and Break
The 2nd way of making a loop is by using the statement:
While True:
This basically substitutes the condition statement (the thing you check to see if it's true to keep looping) with the statement True, thus making it loop forever.
Remember when the program loops, it is checking to see if a statement is true. For instance, is x < 5 or is x == 10. Rather than have a statement, you're just making it True.
The only way to break out of a While True, since you can't change the conditions, is with this command:
break
The break command forces an exit out of the current loop.
Try the example below to see the output:
You can use break even in loops that aren't using While True. It basically breaks you out of ANY loop you are in.
If you have an embedded loop, it only breaks you out of the loop you are in, not both loops!
Lesson 5 Assignment
Make a program that does the following:
Basically it produces the following code:
(if blank below this, clink on this link: https://drive.google.com/open?id=1AgUos5_iX8nYKqw_FLr8smAonh02lhFx