Python 6a - While Loops
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 until the condition is no longer true.
Simple While Loops
The second type of loop is a while loop which keeps running until the starting condition has been broken and is no longer true.
In the example below a number will continue to be increased by 1 inside of the loop until it is no longer less than 11, then the loop ends.
It is important to give the variable a value before you start the while loop. I have assigned number as 1.
Practice Task 1
Time to create a simple program using a while loop.
Use the example above to help you.
Start with a number variable that equals 15.
While the number is above 0 print the number and keep taking away 1 each turn.
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:
I also have put month = ” ” before the loop because Python needs to know the value of the variable before it checks to see if it is not equal to July.
I chose a default value of just a blank space so that it does not interfere with the program.
That is an important concept. We need to feed Python a default value if we are not going to refer to the variable in the while loop until it is first used inside of the loop (like the month example above). If we are using strings the default value should be a blank space like below:
Or if we are using numbers in a while loop then we need to make our variable equal a default value such as 0 before we use it:
Practice Task 2
1. Set a variable called total to equal 0.
While total is not equal (!=) to 4 ask the user to input a guess for a number between 1 and 10.
Make sure that your input line is indented inside of the while loop, not before or after.
2. Set a variable called name to equal ” “.
While name is not equal to Iron Man add an input line that asks “Who is Tony Stark better known as?”.
Example solution for #1: