top of page
top

Python 6B - While Loops

noun-loop-6036209-FFFFFF.png

Types of Loop

The third construct of programming (after Sequence and Selection) is Iteration. If you iterate something, then you repeat it.

​

There are two key loops to use in Python: for loops and while loops.

​

A for loop is count controlled – e.g. “For 10 seconds I will jump up and down”.
The loop will continue until the count (e.g. 10 seconds) has finished.

​

A while loop is condition controlled – e.g. “While I am not out of breath, I will jump up and down.”
The loop will continue as long as the condition remains true.

Simple While Loops

A while loop keeps repeating as long as the starting condition is true. If the condition of the while loop becomes false, the loop ends.

​​

In this example, the number variable is increased by 1 inside of the loop until it is no longer less than or equal to 10.

number = 1

while number <= 10:

    print(number)
    number = number + 1

1

2

3

4

5

6

7

8

9

10

Comparison Operators

==   equal to

!=    not equal to

<     less than

<=   less than or equal to

>     greater than

>=   greater than or equal to

It is important to give the variable a value before you start the while loop. I have assigned number as 1.

​

The last line increases the number by 1 otherwise the number would stay at 1 and the loop would repeat forever.

While Loops Task 1 (Countdown from 100)

Example solution (shortened):

Create a simple while loop that starts at 100 and prints each number down to 1. Think about the comparison operator you will need to check you have reached 1.

100

99

98

...

...

3

2

1

Inputs Inside While Loops

If you want the user to keep entering an input until they give a certain answer then you need to put the input inside the while loop:

age = 0

while age < 18:
    print("Only adults allowed to the casino.")
    age =
int(input("Enter your age: "))

print("Welcome and enjoy your visit.")

Only adults allowed to the casino.
Enter your age:
14
Only adults allowed to the casino.
Enter your age:
18
Welcome and enjoy your visit.

month = " "

while month != "July":
    month =
input("Guess the month I'm thinking of: ")

print("Correct! It was July!")

Guess the month I'm thinking of: August
Guess the month I'm thinking of: June
Guess the month I'm thinking of: July
Correct! It was July!

Notice that the variable in the condition (age or month in these examples) has to be given a value first before it can be used in a while condition.

 

The program will crash if the variable is not declared and assigned a value - for example, the age cannot be checked to see if it less than 18 if there is no age variable!

​​

For string variables like month in the example above then a blank default value like " " can be used. For integer variables often 0 will be used.

While Loops Task 2 (Guess the Colour)

Example solution:

Use a variable named colour and a while loop that allows the user to keep entering colours until a specific one (your choice) has been input.

Guess the colour: blue
Guess the colour: purple
Guess the colour: yellow
Correct! It was yellow!

While Loops Task 3 (Integer Trivia)

Use a while loop to ask a question that has an integer (whole number) as an answer, such as "How many James Bond films did Daniel Craig appear in?" or "In which year did Wigan Athletic win the FA Cup?".

​

Remember that integers do not use speech marks, e.g. year = 0

Example solution:

Which year was the first Iron Man movie? 2010
Which year was the first Iron Man movie? 2009
Which year was the first Iron Man movie? 2008
Correct! It was 2008!

While True Loops

A while True loop will repeat indefinitely, only stopping when the break command is used to end the loop.

​

While True loops are often preferred because you do not need to set default values for any variables before the loop begins.

while True:
    password =
input("Enter the password: ")

   
if password == "icecream21":
       
print("Correct Password!")
       
break

Enter the password: vanilla32
Enter the password: chocolate83
Enter the password: strawberry100
Enter the password: icecream21
Correct Password!

The program below has been adapted to record the number of attempts made. The value is increased by 1 each time the loop restarts.

guesses = 0

while True:
    guesses = guesses + 1
    password =
input("Enter the password: ")

    if password == "goat7":
        print("Correct Password! It took",guesses,"attempts!")
        break
    else:
        print("Incorrect. Try again!")

Enter the password: sheep3
Incorrect. Try again!
Enter the password:
cow4
Incorrect. Try again!
Enter the password:
horse5
Incorrect. Try again!
Enter the password:
goat7
Correct Password! It took 4 attempts!

The continue command will move to the next iteration (it can be considered as starting the loop again).

​

The program below allows numbers to be entered and keeps track of a running total. Entering 1 inputs a number, 2 displays the total and 3 stops the program.

total = 0

while True:
    choice =
input("\nType 1 to enter, 2 for a total and 3 to stop: ")
   
if choice == "1":
        number =
int(input("Enter a number: "))
        total = total + number
       
continue

    elif choice == "2":
       
print("The total is" , total)
       
continue

    elif choice == "3":
       
break

print("\nProgram finished.")

Type 1 to enter, 2 for the total and 3 to stop: 1
Enter a number: 40

Type 1 to enter, 2 for the total and 3 to stop: 1
Enter a number: 35

Type 1 to enter, 2 for the total and 3 to stop: 2
The total is 75

Type 1 to enter, 2 for the total and 3 to stop: 3

Program finished.

While Loops Task 4 (Guess the Planet)

Example solution:

Use a while True loop to keep asking a user to input a planet. Keep track of the number of guesses that have been made and output the total when they input the correct planet.

 

Use the second example in the 'While True Loops' section above to help you. 

Enter a planet: Mars
Incorrect guess, try again!

Enter a planet: Mercury
Incorrect guess, try again!

Enter a planet: Neptune
Correct it was Neptune!

While Loops Task 5 (Up to 100)

Create a while True loop that asks the user to enter a number. Add the number to a total variable and print it.

 

When the total reaches 100 or more, stop the program.

​

Don't forget to set the total variable to 0 at the start and to add the number entered by the user to the total.

Example solution:

Enter a number: 34
The current total is: 34
Enter a number:
29
The current total is: 63
Enter a number:
18
The current total is: 81
Enter a number:
22
The current total is: 103
Over 100!

bottom of page