0% found this document useful (0 votes)
10 views5 pages

5 While Loop

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views5 pages

5 While Loop

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

MODERNISATION OF HIGHER

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

5.1 Updating variables


A common pattern in assignment statements is an assignment statement that updates a
variable, where the new value of the variable depends on the old.
x=x+1
This means “get the current value of x, add 1, and then update x with the new value.”
If you try to update a variable that doesn’t exist, you get an error, because Python
evaluates the right side before it assigns a value to x:
>>> x = x + 1
NameError: name 'x' is not defined
Before you can update a variable, you have to initialize it, usually with a simple
assignment:
>>> x = 0
Lecture: 5
Topic: While Loop
>>> x = x + 1
Updating a variable by adding 1 is called an increment; subtracting 1 is called a
decrement.

5.2 The while statement


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!”.
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 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.

5.3 Infinite loops


An endless source of amusement for programmers is the observation that the directions
on shampoo, “Lather, rinse, repeat,” are an infinite loop because there is no iteration
variable telling you how many times to execute the loop.
Lecture: 5
Topic: While Loop
In the case of countdown, we can prove that the loop terminates because we know that
the value of n is finite, and we can see that the value of n gets smaller each time through
the loop, so eventually we have to get to 0. Other times a loop is obviously infinite
because it has no iteration variable at all.
Sometimes you don’t know it’s time to end a loop until you get half way through the
body. In that case you can write an infinite loop on purpose and then use the break
statement to jump out of the loop.
This loop is obviously an infinite loop because the logical expression on the while
statement is simply the logical constant True:
n = 10
while True:
print(n, end=' ')
n = n - 1
print('Done!')

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.”).

5.4 Finishing iterations with continue


Sometimes you are in an iteration of a loop and want to finish the current iteration and
immediately jump to the next iteration. In that case you can use the continue statement
to skip to the next iteration without finishing the body of the loop for the current
iteration.
Here is an example of a loop that copies its input until the user types “done”, but treats
lines that start with the hash character as lines not to be printed (kind of like Python
comments).
while True:
line = input('> ')
if line[0] == '#':
continue
if line == 'done':
break
print(line)
print('Done!')

Here is a sample run of this new program with continue added.


> hello there
hello there
> # don't print this
> print this!
print this!
> done
Done!

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

You might also like