5 While Loop
5 While Loop
EDUCATION
IN CENTRAL ASIA
THROUGH NEW TECHNOLOGIES
( HiEdTec )
Lecture: 5
Topic: While Loop
Key concepts:
• Iterations
• Indefinite loop
• While loop
• Break
• Continue
Objectives:
After getting acquainted with the material, you will be able to:
• define what is iteration
• use the while loop
• know what is while loop
• use break
• use continue
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 Blastoff!”
More formally, here is the flow of execution for a while statement:
1. Evaluate the condition, yielding True or False.
2. If the condition is false, exit the while statement and continue execution at the
next statement.
3. If the condition is true, execute the body and then go back to step 1.
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.
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.
If you make the mistake and run this code, you will learn quickly how to stop a runaway
Python process on your system or find where the power-off button is on your computer.
This program will run forever or until your battery runs out because the logical
expression at the top of the loop is always true by virtue of the fact that the expression
is the constant value True.
While this is a dysfunctional infinite loop, we can still use this pattern to build useful
loops as long as we carefully add code to the body of the loop to explicitly exit the loop
using break when we have reached the exit condition.
For example, suppose you want to take input from the user until they type done. You
could write:
while True:
line = input('> ')
if line == 'done':
break
print(line)
print('Done!')
The loop condition is True, which is always true, so the loop runs repeatedly until it hits
the break statement.
Each time through, it prompts the user with an angle bracket. If the user types done, the
break statement exits the loop. Otherwise the program echoes whatever the user types
and goes back to the top of the loop. Here’s a sample run:
> hello there
Lecture: 5
Topic: While Loop
hello there
> finished
finished
> done
Done!
This way of writing while loops is common because you can check the condition
anywhere in the loop (not just at the top) and you can express the stop condition
affirmatively (“stop when this happens”) rather than negatively (“keep going until that
happens.”).
All the lines are printed except the one that starts with the hash sign because when the
continue is executed, it ends the current iteration and jumps back to the while statement
to start the next iteration, thus skipping the print statement.
Lecture: 5
Topic: While Loop
Exercises
1. What is while?
2. What is the iteration?
3. What does the break do?
4. How should we use continue?
Exercise 1: Write a program which repeatedly reads numbers until
the user enters “done”. Once “done” is entered, print out the total, count, and average
of the numbers. If the user enters anything other than a number, detect their mistake
using try and except and print an error message and skip to the next number.
Enter a number: 4
Enter a number: 5
Enter a number: bad data
Invalid input
Enter a number: 7
Enter a number: done
16 3 5.333333333333333