Module 4 - Section 1 - While and Functions

After the completion of this module the students will be able to:
  • identify when to use the while loop
  • explain the use of the break inside a while loop
  • create user defined functions
  • distinguish the use of return inside a function from print

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):

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

i = 0
while i < 10:
    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.