Iteration is the process of repeating a process over and over. Often in programming you need to repeat a block of code several times.

WHILE Loops

A while loop is known as a condition controlled loop, you should use it when you do not know how many times the code needs to repeat as you can say repeat while a condition is True.

userentry = "y"
while userentry != "n":
    userentry = input("Play again? y/n ")
print("Game over")

When run in IDLE:

How the while loop works

  • there is a condition after the word while, it works like an if condition. while the variable userentry is not equal to n the code inside the loop (that is indented) will repeat
  • when n is entered by the user, the loop will end and it will continue with the code after the loop (not indented). In this case it will print “Game Over”.

Example Program 1 - Guess the Number

This program asks the user to guess the number, it will keep asking them to guess the number until they guess it correctly. Once they have guessed it correctly it will tell them how many attempts it took.

answer = 15
attempts = 0
userentry = ""
#a loop that repeats while the users guess is not the same as the answer
while answer != userentry:
    userentry = int(input("Enter a number between 1 and 20 "))
    #each time through the loop 1 is added to the number of attempts
    attempts = attempts + 1
#after the loop it will say how many attempts it took
print("Well done you correctly guessed the number it took you " + str(attempts) + " attempts")

When run in IDLE:

Example Program 2 - Adding User Numbers Program

This program asks the user to enter a number. It then asks them whether they want to enter another. If they do it will ask them another and add it to the previous number, it will keep doing this until they say they do not want to enter any more numbers. Finally it will output the total.

total = 0
another = "Y"
# the loop will repeat while the user types Y when asked if they want to enter another number
while another == "Y":
    # asks the user to enter a number
    number = int(input("Enter a number to add to the total: "))
    #adds the number entered to the total
    total = total + number
    # asks the user if they want to enter another number
    another = input("Do you want to enter another number? Y/N ")
# after the loop ends it outputs the total
print("The total of your numbers was" + str(total))

When run in IDLE: