Python Programming:
An Introduction
To Computer Science
Chapter 4
Loop Structures and Booleans
Objectives
To understand the concepts of definite
and indefinite loops as they are realized
in the Python for and while
statements.
To understand the programming
patterns interactive loop and sentinel
loop and their implementations using a
Python while statement.
Objectives
To understand the programming
pattern end-of-file loop and ways of
implementing such loops in Python.
To be able to design and implement
solutions to problems involving loop
patterns including nested loop
structures.
For Loops: A Quick Review
The for statement allows us to iterate
through a sequence of values.
for <var> in <sequence>:
<body>
The loop index variable var takes on
each successive value in the sequence,
and the statements in the body of the
loop are executed once for each value.
For Loops: A Quick Review
Suppose we want to write a program that can
compute the average of a series of numbers
entered by the user.
To make the program general, it should work
with any size set of numbers.
We don’t need to keep track of each number
entered, we only need know the running sum
and how many numbers have been added.
For Loops: A Quick Review
We’ve run into some of these things
before!
A series of numbers could be handled by
some sort of loop. If there are n numbers,
the loop should execute n times.
We need a running sum. This will use an
accumulator.
For Loops: A Quick Review
Input the count of the
numbers, n
Initialize sum to 0
Loop n times
Input a number, x
Add x to sum
Output average as sum/n
For Loops: A Quick Review
How many numbers do you have? 5
Enter a number >> 32
Enter a number >> 45
Enter a number >> 34
Enter a number >> 76
Enter a number >> 45
The average of the numbers is 46.4
For Loops: A Quick Review
# [Link]
# A program to average a set of numbers
# Illustrates counted loop with accumulator
def main():
n = eval(input("How many numbers do you have? "))
sum = 0.0
for i in range(n):
x = eval(input("Enter a number >> "))
sum = sum + x
print("\nThe average of the numbers is", sum / n)
Note that sum is initialized to 0.0 so that sum/n returns a float!
Definite Loops
A definite loop executes a definite
number of times, i.e., at the time
Python starts the loop it knows exactly
how many iterations to do.
for <var> in <sequence>:
<body>
The beginning and end of the body are
indicated by indentation.
10
Definite Loops
for <var> in <sequence>:
<body>
The variable after the for is called the
loop index. It takes on each successive
value in sequence.
11
Definite Loops
>>> for i in [0,1,2,3]:
print (i)
0
1
2
3
>>> for odd in [1, 3, 5, 7]:
print(odd*odd)
1
9
25
49
>>>
12
Definite Loops
In [Link], what did range(10) do?
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range is a built-in Python function that
generates a sequence of numbers,
starting with 0.
list is a built-in Python function that
turns the sequence into an explicit list
The body of the loop executes 10 times.
13
Definite Loops
for loops alter the flow of program
execution, so they are referred to as
control structures.
14
Indefinite Loops
That last program got the job done, but you
need to know ahead of time how many
numbers you’ll be dealing with.
What we need is a way for the computer to
take care of counting how many numbers
there are.
The for loop is a definite loop, meaning that
the number of iterations is determined when
the loop starts.
Indefinite Loops
We can’t use a definite loop unless we
know the number of iterations ahead of
time. We can’t know how many
iterations we need until all the numbers
have been entered.
We need another tool!
The indefinite or conditional loop keeps
iterating until certain conditions are
met.
Indefinite Loops
while <condition>:
<body>
condition is a Boolean expression, just like
in if statements. The body is a sequence of
one or more statements.
Semantically, the body of the loop executes
repeatedly as long as the condition remains
true. When the condition is false, the loop
terminates.
Indefinite Loops
The condition is tested at the top of the loop.
This is known as a pre-test loop. If the
condition is initially false, the loop body will
not execute at all.
Indefinite Loop
Here’s an example of a while loop
that counts from 0 to 10:
i = 0
while i <= 10:
print(i)
i = i + 1
The code has the same output as this
for loop:
for i in range(11):
print(i)
Indefinite Loop
The while loop requires us to manage
the loop variable i by initializing it to 0
before the loop and incrementing it at
the bottom of the body.
In the for loop this is handled
automatically.
Indefinite Loop
The while statement is simple, but yet
powerful and dangerous – they are a
common source of program errors.
i = 0
while i <= 10:
print(i)
What happens with this code?
Indefinite Loop
When Python gets to this loop, i is
equal to 0, which is less than 10, so the
body of the loop is executed, printing 0.
Now control returns to the condition,
and since i is still 0, the loop repeats,
etc.
This is an example of an infinite loop.
Indefinite Loop
What should you do if you’re caught in
an infinite loop?
First, try pressing control-c
If that doesn’t work, try control-alt-delete
If that doesn’t work, push the reset
button!
Drawing complex figures
Assignment 1
Write a Python program that produces
the following figure as its output.
Use for loops to capture the repetition.
Make DrawSquare method
====+====
# | #
# | #
# | #
====+====
# | #
# | #
# | #
====+====
Assignment2
Interest calculation
Analysis (Make Interest method)
Money deposited in a bank account earns
interest.
How much will the account be worth n
years from now?
Inputs: principal, interest rate, no. of years
Output: value of the investment in n years