Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly. Because iteration is so common, Python provides several language features to make it easier.
One form of iteration in Python is the
while statement. Here is a simple program that counts down from five and then says "Blastoff!".
%%python3 n = 5 while n > 0: print(n) n = n - 1 print('Blastoff!')
You can almost read the
while statement as if it were English. It means, "while
n is greater than 0, display the value of
n and then reduce the value of
n by 1. When you get to 0, exit the
while statement and display the word
More formally, here is the flow of execution for a
- Evaluate the condition, yielding
- If the condition is false, exit the
whilestatement and continue execution at the next statement.
- If the condition is true, execute the body and then go back to step
This type of flow is called a loop because the third step loops back around to the top. We call each time we execute the body of the loop an iteration. For the above loop, we would say, "It had five iterations", which means that the body of the loop was executed five times.
There are two things to remember about while loops:
- You MUST prime the loop BEFORE you begin the loop. In our example, notice that the value of
nis set to 5 BEFORE the loop.
- Also - there are some 'good ways' and some 'bad ways' to code loops.
BOTH of the following pieces of code do the same thing - the first one uses a specific condition in the while. This is the proper way to use a iteration loop.
The second section of code uses a Boolean 'True', in addition to a 'break' statement in the if block. This is NOT an appropriate method for using a while loop. It is correct, and it works - but it is not the preferred method of coding a loop.
# Pat # CSP 017 # Loops myInput = input('Enter a value') while myInput != 'stop': some code goes here... # Ask for more input myInput = input('Enter another value, or "stop" to quit') print(Some statement)
# Pat # CSP 017 # Loops # THIS IS NOT A GOOD WAY TO PROGRAM!! while True: myInput = input('Enter input') if myInput == 'stop' break print(Some statement)
- The body of the loop should change the value of one or more variables so that eventually the condition becomes false and the loop terminates. We call the variable that changes each time the loop executes and controls when the loop finishes the iteration variable. If there is no iteration variable, the loop will repeat forever, resulting in an infinite loop.