That Blue Square Thing

Computer Science GCSE

While Loop - some help working them out...

While loops allow you to repeat a section of programming code. They are one of the key ways in which repetition can be coded (For loops being the other).

While loops are most useful when you don't know how many times you need to repeat the operation for. For example:

For loops, on the other hand, are excellent when you already know how many times you need to repeat something. Look for a page on using for loops coming very soon...

While loops are a little tricky though and there is always the danger of ending up in the scary sounding "infinite loop" if you're not careful. So, here's some help...

Basic While loop help

The basic syntax for a while loop is pretty straightforward. It involves using boolean condition (something which can either be True or False). You keep doing the while loop until the condition is False.

So, in the example below I want to keep on looping until myNumber reaches 10. You can probably work out how many times the loop needs to run (or how many times it will iterate) to get that far - it's not difficult!

myNumber = 0 # sets the variable myNumber to 0

while myNumber < 10:
print(myNumber)
myNumber = myNumber + 2

print() # prints an empty line
print("Out of loop")
print(myNumber)

The code will keep looping until myNumber < 10 (i.e. the number is less than 10) is False. This will happen any time that myNumber gets to at least 10.

Note that the indenting is really important in Python. The loop body is the indented section. This is the section of code which is repeated each time the loop runs. As always with Python the colon (the :) at the end of the while line is super important (and is the thing I'm most likely to miss out...)

A helpful starting point on while loops might be:

PDF iconWhile loops - while loops and how to use them

Also worth a look might be this - a menu system which uses a while loop in it.

PDF iconMenu system - a way of creating a menu system with lists involved as well (now with the missing colon replaced - thanks to whoever it was who pointed that out to me...)

Another while loop

Sometimes you want to keep doing something until a user tells you they're done. A while loop is an excellent way to do this.

The trick is setting up the boolean condition variable carefully. I usually use this technique:

check = "N" # set up check variable to enter loop

nameList = [ ] # set up an empty list

while check != "Y":
name = input("Enter the next name: ")
nameList.append(name) # add the name to the end of the list

check = input("Are you finished yet? (Y/N): ") # check if done
check = check.upper() # make check uppercase

print(nameList) # print the list out to check

The loop condition here is saying to continue the loop if check is not equal to (!=) "Y". In other words, do it until the user enters Y or y when they are asked if they are done.

This is a nice, simple way to let the user finish when they want to. It can be adapted to lots of problems. Note that it's really important that the variable check is set to something other than "Y" before the loop starts. It's also really, really important that you include a way for the user to change the value of check to something else (the input line). If you don't then there's no way out of the loop.

There are some example problems you can try below. I used these in class with my Year 10 group to give them something independent to work on. They range from a line by line walk through (for people who need to learn from scratch) to much more open (and more complex) problems.

PDF iconWhile Loop Exercise 1.0 - TeleFanz - a simple, line by line workthrough aimed at developing basic competence with while loops

Because this is the basics I'll give you a text file with a full solution in it as well. Just because I'm feeling kind. Do try and do it yourself first though.

Text file iconTeleFanz solution - as a text file. Copy and paste the code into IDLE

PDF iconWhile Loop Exercise 1.5 - Pips Dogs - an exercise using the same skills from 1.0, but without the line by line walkthrough. If you managed 1.0 you should be able to do this.

PDF iconWhile Loop Exercise 2.0 - Hello Python World - a more open problem, quite similar to the sort of thing you might get in a first task on controlled assessment pieces

PDF iconWhile Loop Exercise 2.5 - Hello Python World 2 - the same basic problem as 2.0 but with a bit of a twist using a customer ID number thrown in. THis did crop up on a controlled assessment piece one and is a nice bit of string manipulation

PDF iconWhile Loop Exercise 2.81 - Hello Python World 3 - this needs 2.5 done first and then asks for valid inputs (see below)

Validating data

While loops can be used to make sure users enter valid data. I set this as a problem in exercise 2.81 above. There are all sorts of ways to do this, so I'll just deal with a simple example here.

Say that a system needs the user to enter whether a disc is a CD or a DVD. The value entered must be one of those. Nothing else will do. A while loop is a good way of making the user keep on entering data until they enter one of these options.

Here's one way of doing it:

disctype = input("What type of disc? (CD or DVD): ")
disctype = disctype.upper() # convert to uppercase

while disctype != "CD" and disctype != "DVD":
print("That is an invalid input")
disctype = input("What type of disc? (CD or DVD): ")
disctype = disctype.upper() # convert to uppercase

print()
print("Type: " + disctype) # print on one line

This will keep looping the loop body until either CD or DVD is entered. Note that you need to use and in the loop condition (this sort of thing gets complex!).

Another way to do the same thing is to use a variable called something like "valid". This can be really helpful if your possible data entry values are a bit more complex!

Careful - this code is a little more complex...

valid = False

while not valid: # this is fine - valid is a boolean (see below)
disctype = input("What type of disc? (CD or DVD): ").upper()
if disctype == "CD":
valid = True
elif disctype == "DVD":
valid = True

print()
print("Type: " + disctype) # print on one line

In this case I'm using a boolean variable to control the loop. So the value must be True or False. So I can use a very simple while condition.

The condition means while valid != True. Or, put another way, while valid == False. You might not have used boolean variables like this before - that's OK; this is an interesting thing to throw in at this level.

The if and elif lines could have been written as below for efficiency:

if disctype == "CD" or disctype == "DVD":
valid = True

In this case we want to switch valid to True if the user has entered CD or DVD, so we need an or.