4.1.1 - While loop


A while loop is used when a program needs to loop until a particular condition occurs.

Oddly enough, a while loop can be used anywhere that a for loop is used. It can be used to loop until an increment variable reaches a certain value. So why we have a for loop if a while loop can do everything? The for loop is simpler to use and code. A for loop that looks like this:

for i in range(10): print(i)

...can be done with a while loop that looks like this:

i = 0 while i < 10: print(i) i = i + 1


To achieve the same using a while loop we have to:

So a better use of the while loop is to ask for a reply from the user.

Copy the code to Thonny and save it as test_while (or whatever name you like) :

quit = "n" while quit == "n": quit = input("Do you want to quit? ")


What is the result of this code? If you reply n then the code stays in the loop and keeps asking. But if you reply anything else then the code gets out of the loop. It is not perfect but it is a start and you can try to make it better.