While loops
While loops are a type of condition-controlled loop. This means we don't know how many times they will run, just the condition that will cause them to stop. The most
problematic thing about while loops is that you can end up creating an infinite loop. This happens if there is no way for the code in the loop to change a value so that
eventually the condition evaluates as false.
capital = input("What is the capital of England? ") while capital != "London": print("Sorry, that was wrong. Try again.")
capital = input("What is the capital of England? ") print("Well done. You guessed it.") |
In the example above, the loop will run until the user correctly enters 'London'. Importantly, if they enter the correct answer straight away, the condition will immediately
evaluate as false and the while loop will not run. Instead the next line of unindented code is run. If there were no opportunity to input a new guess to store in the variable
capital then we would have an infinite loop because capital could never equal 'London'.
while loop syntax rules:
- while is in lower case
- while is followed by a Boolean condition
- There is a colon on the end
of the while line
- Any code you want to be executed each time through the loop is indented under the while loop
- There is a chance in the code for the condition
to become false during its execution
Syntax checker
Fix the code below so it counts and outputs the number of instances of the letter s are in a persons name they entered.
num = int(input("Enter a number between 1 and 4")) |
while num < 1 or num > 41>: |
num = int(input("Enter a number between 1 and 4")) |
print(f"You chose {num}") |
For or while?
You will find it is possible to write a for loop as a while loop and vice versa. In fact, this is a fairly common question type in exams. When should you use each?
for i in range with one parameter
When we specify one value the iterator starts with a value of 0 and goes until the iterator is one less than the specified number.
Type of loop |
When to use it |
For loops |
When you know, or can easily ascertain (e.g. through a len command), how many times the loop needs to run |
While loops |
When you don't know how many times the loop will run before it is run |
It is possible to use the break command in Python to cause a loop to stop running prematurely. This can make it easy to create certain structures, but in general,
it is better practice to define such loops with a condition that terminates naturally. In the examples below both pieces of code will let the user enter their
password up to 3 times but will stop if they get it correct in less tries.
Version 1 - with break
password = "LetMeIn$" for i in range(3): guess = input("Enter your password:") if guess ==
password: break if guess == password: print("Logged in")
else: print("Too many attempts. Account locked.") |
Version 2 - with a natural ending condition
password = "LetMeIn$" guesses = 0 guess = "" while guess != password and guesses < 3: guess = input("Enter your password:")
guesses = guesses + 1 if guess == password: print("logged in")
else: print("Too many attempts. Account locked.") |
Repeat until/ Do while loop
Many languages have what is called a do while or repeat until loop. This kind of loop is very similar to the while loop with the key difference being that code in
a repeat until/do while loop will always executes at least once. This is because this type of loop checks the condition at the end of the loop. Although Python does
not have a specific repeat until/do while method we can cause the same outcome by creating a while loop and forcing the condition to evaluate as True on the first
time the loop is executed.
capital = " " while capital != "London": capital = input("What is the capital of England? ") if capital != "London":
print("Sorry, that was wrong. Try again.") print("Well done. You guessed it.") |
In the example above, defining capital as an incorrect answer will force the loop to execute at least once. As the first time they have not already guessed we need to
move our check to later in the loop.