While Loops - Lakelands Computing

Title
Go to content
While Loops
While loops are a type of iteration. They are a condition controlled loop. This means they will keep running a block of code until a condition is met. Think of it as repeat until..

  • start = False
  • while start is False:
  • go = input("type run to start")
  • if go=="run":
    • start = True

print ("the programming is starting")

This gives you a good idea of how while to works. The code is stuck in the loop until the start variable is changed from False.  Once it changes to True the loop is exited and the next section of code, in this example the print statement is run.

You can use while loops for things like password checks - see trinket for example,  note - whilst this  approach works, (and would get you marks if it was a GCSE exam question) it is a very insecure way to do a password check - the password is literally there in the code - and should not be used for anything where security matters.

While loops are also used a lot in games, for example to control and redraw the graphics :
  • life = 100
  • While life>0:
    • draw current image to the screen.

Have a play with the trinket. Note I have created an infinite loop with the third example, see if you can figure out what to change to stop it repeating the print statement.
All Text copyright Lakelands Academy & Mr T Purslow 2020.
All images copyright free / creative commons unless otherwise stated.
You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
Back to content