Now we are going to move on to one of my favourite commands – the “while loop”. The programs we have looked at so far did something once and then stopped. If you want to repeat part of a program a number of times, you need to use a loop.
In the image you can see a program called name4.py. It begins with the usual comment lines and the input line we have used before. The important new feature is the while command.
This compares the contents of the variable “name” with … well nothing. The while loop tells the computer to keep looping through the following few lines until “name” is empty. In other words, if the user presses the enter key, instead of entering a name, the program will exit the loop. Notice the exclamation mark and equals sign: this means “is not equal to”. Also notice the colon at the end of the while command. Just like with the “if” statement, this tells the computer that some instructions are coming which it must perform if the preceding condition is met.
So, the program will keep looping around asking for names and saying: “hello”, until we press enter.
Notice the indentations. Everything in the while loops is indented.The print lines are indented further as they are conditional on the preceding if commands. Another thing you might notice is that I get the input before entering the loop and then again at the end of the loop. I need to do this because, if I don’t have anything in “name” when it hits the while statement, the condition will not be met and the loop will be skipped. I need to ask for input again before going back to the start of the loop, so that the code in the loop will have some new data to work on.
One of the great things about computers is that they don’t argue, even when you ask them to do something stupid. For instance, look at this short program:
print(“You suck and I rule!”)
If you run this program, it will print the string over and over, until you force the program to quit by closing the window. This is the sort of program it used to be great fun to write on BBC micros in Dixons. It used to really annoy the salesmen (of course in those days we wrote in BASIC). The fun bit is in the while command. It asks the computer to keep doing the next line while one is greater than zero. Now since one is always going to be greater than zero, it’ll keep doing it for ever. On the whole, you’ll want to avoid creating infinite loops in your programs!