A while loop can result in an infinite loop - do a block of code until an event happens. This turns out to be useful when we are using a browser and want it to keep running (looping) until we click on the close window icon. Chapter 5/ Lesson 6 of py4e introduces loops. The while loop is the only loop you will ever need.
It is uncommon to use the else option with a while loop, but it is an option that may be useful. With the else statement we can run a block of code once when the condition no longer is true.
A while loop will continue to run the code inside the while block- in python this means indented below the while statement.
Until such time as this condition becomes false, or until such time as a condition becomes True and triggers a break, the code in the while block may loop indefinitely.
The first way is to initialise a variable and use the value of that variable to control the loop. In this case, it must be possible to change the value of that variable from within the loop, like this:
repeat = 'Y'
while repeat == 'Y':
print("In the loop")
repeat = input("Loop? Enter 'Y': ")
This code will repeat and evaluate the condition after the while statement repeatedly each time it has completed running the code in the while block - until the user enters something that does NOT match the str 'yes'. This is convenient as anything other that Y will terminate the loop.
A minor improvement would be to account for case by using the .upper() str method.
The second way to control a while loop is to make it infinite, and under certain condition(s) break out of the infinite loop.
while True:
print("In the loop")
choice = input("Loop? Enter 'Y': ")
if choice.upper() != 'Y':
break
In this case the check for the condition is inside the loop itself, rather than checked as an expression after the while statement. If the user enters anything other than 'Y' the break command will terminate the loop.
Both options are equally valid and neither is better than the other. It may be just a matter of personal preference as to which form to use.
You can find out more about break as well as pass and continue here where there are also code examples and more details about these statements.
In simplest terms:
break will escape from a loop
pass does nothing- often uses as a placeholder
continue means 'skip what is after this and go to the top of the current block'
This is simply a while loop inside another while loop, as illustrated by the following examples.
flowchart
example code