0% found this document useful (0 votes)
17 views

CMPE 102 - Module 6 - Iteration or Looping in Python (1)

Uploaded by

neil roque
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

CMPE 102 - Module 6 - Iteration or Looping in Python (1)

Uploaded by

neil roque
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Module 6

Iteration/Looping in Python
In this module you will learn how to rerun parts of
your program without duplicating instructions

1-1

DEPARTMENT OF COMPUTER ENGINEERING


Repetition Flow Control
• Computers are often used to do repetitive tasks
because humans don’t like to do the same thing
over and over again.
• In computer programs, repetition flow control is
used to execute a group of instructions repeatedly.
• Repetition flow control is also called iteration or
loop.
• In Python, repetition flow control can be expressed
by a for-statement or a while-statement that
allow us to execute a code block repeatedly.

DEPARTMENT OF COMPUTER ENGINEERING


Repetition: Computer View
• Continuing a process as long as a certain
condition has been met.
Ask for age as long as the answer is negative (outside allowable range)
How old are?

Minus 21!

slide 3

DEPARTMENT OF COMPUTER ENGINEERING


How To Determine If Loops Can Be Applied
• Something needs to occur multiple times (generally it will repeat
itself as long as some condition has been met).
• Example 1: Flowchart
N
Play again?

Run game again

END GAME
Re-running the entire
program Pseudo code
While the player wants to play
Run the game again

slide 4

DEPARTMENT OF COMPUTER ENGINEERING


How To Determine If Loops Can Be Applied
• Example 2:

Re-running specific parts of the program


Flowchart Pseudo code

N While input is invalid


Invalid input?
Prompt user for input
Y
Ask for input again

…rest of
program

slide 5

DEPARTMENT OF COMPUTER ENGINEERING


Basic Structure Of Loops
Whether or not a part of a program repeats is
determined by a loop control (typically the control is just
a variable).
• Initialize the control to the starting value
• Testing the control against a stopping condition
(Boolean expression)
• Executing the body of the loop (the part to be
repeated)
• Update the value of the control

slide 6

DEPARTMENT OF COMPUTER ENGINEERING


Types Of Loops
1.Pre-test loops
– Check the stopping condition before executing the
body of the loop.
– The loop executes zero or more times.
2.Post-test loops
– Checking the stopping condition after executing
the body of the loop.
– The loop executes one or more times.

slide 7

DEPARTMENT OF COMPUTER ENGINEERING


Pre-Test Loops
Initialize loop control
1. Initialize loop control
2. Check if the repeating
condition has been met
a. If it’s been met then go to Step
Condition No
3
met?
b. If it hasn’t been met then the
loop ends Yes

3. Execute the body of the loop


Execute body
(the part to be repeated)
4. Update the loop control
5. Go to step 2 Update control

After the loop


(done looping)
slide 8

DEPARTMENT OF COMPUTER ENGINEERING


Post-Test Loops
1. Initialize loop control Initialize loop control
(sometimes not needed
because initialization occurs
when the control is updated)
2. Execute the body of the loop Execute body
(the part to be repeated)
3. Update the loop control
4. Check if the repetition Update control
condition has been met
a. If the condition has been met then go
through the loop again (go to Step 2) Yes Condition
b. If the condition hasn’t been met then met?
the loop ends.

No

After the loop


(done looping)

slide 9

DEPARTMENT OF COMPUTER ENGINEERING


Pre-Test Loops In Python
1.While
2.For
Characteristics:
1. The stopping condition is checked before the body
executes.
2. These types of loops execute zero or more times.

slide 10

DEPARTMENT OF COMPUTER ENGINEERING


Post-Loops In Python
•Note: this type of looping construct has not
been implemented with this language.
•But many other languages do implement post
test loops.
Characteristics:
–The stopping condition is checked after the body executes.
–These types of loops execute one or more times.

slide 11

DEPARTMENT OF COMPUTER ENGINEERING


The while Statement
Python Syntax
Semantics
while condition:
code_block F
condition
•condition is a Boolean
expression. T

•code_block is, as usual, code_block


an indented sequence of
one or more statements.

DEPARTMENT OF COMPUTER ENGINEERING


Example
n = int(input(“Enter a number))
F
while n > 0: n > 0
print(n) T
n = n-1
print(n)
print("Go!")
n = n-1
>>> countdown
Enter a number: 4
4
3
2 print("Go!")
1
Go!
>>> countdown
This means, in this case,
Enter a number: 0
that the loop body doesn't
Go!
get executed at all. Why?
DEPARTMENT OF COMPUTER ENGINEERING
The while Loop: a Condition-Controlled Loop
• while loop: while condition is true, do
something
– Two parts:
• Condition tested for true or false value
• Statements repeated as long as condition is true
– In flow chart, line goes back to previous part
– General format:
while condition:
statements

DEPARTMENT OF COMPUTER ENGINEERING


The while Loop: a Condition-Controlled Loop

DEPARTMENT OF COMPUTER ENGINEERING


The while Loop: a Condition-Controlled Loop
• In order for a loop to stop executing,
something has to happen inside the loop to
make the condition false
• Iteration: one execution of the body of a loop
• while loop is known as a pretest loop
– Tests condition before performing an iteration
• Will never execute if condition is false to start with
• Requires performing some steps prior to the loop

DEPARTMENT OF COMPUTER ENGINEERING


The while Loop: a Condition-Controlled Loop
• This type of loop can be used if it’s not known in advance how
many times that the loop will repeat (most powerful type of loop,
any other type of loop can be simulated with a while loop).
– It can repeat so long as some arbitrary condition holds true.

• Syntax:
(Simple condition)
while (Boolean expression):
body
(Compound condition)
while (Boolean expression) Boolean operator (Boolean expression):
body

slide 17

DEPARTMENT OF COMPUTER ENGINEERING


The while Loop: a Condition-Controlled Loop

• Program name: while1.py


1) Initialize control
i = 1
2) Check condition
while (i <= 3):
print("i =", i) 3) Execute body
i = i + 1
print("Done!")

4) Update control

slide 18

DEPARTMENT OF COMPUTER ENGINEERING


The while Loop: a Condition-Controlled Loop

• Program name: while1.py Tracing:


Execution Variable
i = 1
while (i <= 5): >python while1.py i
print("i =", i)
i = i + 1
print("Done!")

slide 19

DEPARTMENT OF COMPUTER ENGINEERING


Countdown Loop
• Program name: while2.py Tracing:
i = 3
while (i >= 1): Execution Variable
print("i =", i) i
>python while2.py
i = i - 1
print("Done!")

slide 20

DEPARTMENT OF COMPUTER ENGINEERING


Common Mistakes: While Loops
• Forgetting to include the basic parts of a
loop.
– Updating the control
i = 1
while(i <= 4):
print("i =", i)

slide 21

DEPARTMENT OF COMPUTER ENGINEERING


Illustrative example

slide 22

DEPARTMENT OF COMPUTER ENGINEERING


Definite Loops: the for Statement
Python for variable in sequence :
Syntax code_block

• variable after for is called the loop index.


It takes on each successive value in sequence in
the order they appear in the sequence.
•The sequence can be one of the Python sequence
objects such as a string, a list, a tuple, or a range
of integers from the built-in function range().

DEPARTMENT OF COMPUTER ENGINEERING


How the for statement works
for variable in sequence :
code_block
more items in F
sequence
?
T
variable = next item
The number of times
the code_block is
executed is precisely code_block
the number of items
in the sequence.

DEPARTMENT OF COMPUTER ENGINEERING


The range() function
Python
Syntax
range(start, stop, step)
•In its most general form, the range() function
takes three integer arguments: start, stop, and
step.
•range(start, stop, step) produces the
sequence of integers:
start, start + step, start + 2*step, start + 3*step, …
If step is positive, If step is negative,
the last element is the last element is
the largest integer the smallest integer
less than stop. greater than stop.

DEPARTMENT OF COMPUTER ENGINEERING


Hands-on Example To see the type
of object range()
>>> type(range(-4,14,3))
<class 'range'> This doesn't show the sequence
generated by range().
>>> range(-4,14,3)
range(-4, 14, 3) Use the built-in function list() to
>>> list(range(-4,14,3)) show the sequence.
[-4, -1, 2, 5, 8, 11]
Try a negative step.
>>> list(range(14,-4,-3))
[14, 11, 8, 5, 2, -1] produces the empty sequence
>>> list(range(5,3,1)) because step is positive and start
[] is not less than stop.
>>> list(range(3,5,-1)) produces the empty sequence
[] because step is negative and
>>> start is not greater than stop.

Note that the stop value will never


appear in the generated sequence.
DEPARTMENT OF COMPUTER ENGINEERING
Hands-on Example
>>> list(range(3,8,1))
[3, 4, 5, 6, 7] If step is omitted, the
>>> list(range(3,8)) default step is 1.
[3, 4, 5, 6, 7]
>>> list(range(0,5)) If start is omitted, the
[0, 1, 2, 3, 4] default start is 0.
>>> list(range(5))
[0, 1, 2, 3, 4]
So range(4) is the
>>> for i in range(4):
same as range(0,4)
print('i is', i)
and range(0,4,1).
i is 0
i is 1
i is 2
i is 3
DEPARTMENT OF COMPUTER ENGINEERING
The for Loop
• In Python a for-loop is used to step through a sequence e.g.,
count through a series of numbers or step through the lines in
a file.
• Syntax:
for <name of loop control> in <something that can be iterated>:
body
1) Initialize control
• Program name: for1.py 2) Check condition

total = 0
4) Update control
for i in range (1, 4, 1):
total = total + i
print("i=", i, "\ttotal=", total)
3) Execute body
print("Done!")

slide 28

DEPARTMENT OF COMPUTER ENGINEERING


The for Loop
• In Python a for-loop is used to step through a sequence
• Syntax:
for <name of loop control> in <something that can be iterated>:
body

• Program name: for1.py


i = 0
total = 0
for i in range (1, 4, 1):
total = total + i
print("i=", i, "\ttotal=", total)
print("Done!")

slide 29

DEPARTMENT OF COMPUTER ENGINEERING


Counting Down With A for Loop
• Program name: for2.py
i = 0
total = 0
for i in range (3, 0, -1):
total = total + i
print("i = ", i, "\t total = ", total)
print("Done!")

slide 30

DEPARTMENT OF COMPUTER ENGINEERING


for Loop: Stepping Through A Sequence Of Characters
• Recall: A for-loop in Python can step through any looping
sequence (number sequence, characters in a string, lines in a
file).
• Example: for3.py

slide 31

DEPARTMENT OF COMPUTER ENGINEERING


Erroneous for Loops
• The logic of the loop is such that the end
condition has already been reached with the
start condition.
• Example: for_error.py
for i in range (5, 0, 1):
total = total + i
print("i = ", i, "\t total = ", total)
print("Done!")

slide 32

DEPARTMENT OF COMPUTER ENGINEERING


Loop Increments Need Not Be Limited To One
• While: while_increment5.py
i = 0
while (i <= 100):
print("i =", i)
i = i + 5
print("Done!")

• For: for_increment5.py
for i in range (0, 105, 5):
print("i =", i)
print("Done!")

slide 33

DEPARTMENT OF COMPUTER ENGINEERING


Sentinels
• Sentinel: special value that marks the end of a
sequence of items
– When program reaches a sentinel, it knows that the
end of the sequence of items was reached, and the
loop terminates
– Must be distinctive enough so as not to be mistaken
for a regular value in the sequence
– Example: when reading an input file, empty line can
be used as a sentinel

DEPARTMENT OF COMPUTER ENGINEERING


Illustrative Example #1

DEPARTMENT OF COMPUTER ENGINEERING 35


Illustrative Example #2

DEPARTMENT OF COMPUTER ENGINEERING 36


Sentinel Controlled Loops
• The stopping condition for the loop occurs when the ‘sentinel’
value is reached.
• Program name: sum.py
total = 0
temp = 0
while(temp >= 0):
temp = input ("Enter a non-negative integer (negative to end
series): ")
temp = int(temp)
if (temp >= 0):
total = total + temp
print("Sum total of the series:", total)
Q: What if the user just
entered a single negative
number?

slide 37

DEPARTMENT OF COMPUTER ENGINEERING


Sentinel Controlled Loops
• Sentinel controlled loops are frequently used in conjunction with the error
checking of input.
• Example (sentinel value is one of the valid menu selections, repeat while
selection is not one of these selections)
selection = " "
while selection not in ("a", "A", "r", "R", "m", "M", "q", "Q"):
print("Menu options")
print("(a)dd a new player to the game")
print("(r)emove a player from the game")
print("(m)odify player")
print("(q)uit game")
selection = input("Enter your selection: ")
if selection not in ("a", "A", "r", "R", "m", "M", "q", "Q"):
print("Please enter one of 'a', 'r', 'm' or 'q' ")

slide 38

DEPARTMENT OF COMPUTER ENGINEERING


Recap: What Looping Constructs Are Available In
Python/When To Use Them
Construct When To Use
Pre-test loops You want the stopping condition to be checked before the loop body is executed
(typically used when you want a loop to execute zero or more times).
• While • The most powerful looping construct: you can write a ‘while’ loop to mimic the
behavior of any other type of loop. In general it should be used when you want a
pre-test loop which can be used for most any arbitrary stopping condition e.g.,
execute the loop as long as the user doesn’t enter a negative number.
• For • In Python it can be used to step through some sequence
Post-test: None You want to execute the body of the loop before checking the stopping condition
in Python (typically used to ensure that the body of the loop will execute at least once). The
logic can be simulated with a while loop.

slide 39

DEPARTMENT OF COMPUTER ENGINEERING


The Break Instruction
• It is used to terminate the repetition of a loop which is separate from the main
Boolean expression (it’s another, separate Boolean expression).
• General structure:
for (Condition 1): while (Condition 1):
if (Condition 2): if (Condition 2):
break break
• Specific example (mostly for illustration purposes at this point): break.py
str1 = input("Enter a series of lower case alphabetic characters: ")
for temp in str1:
if (temp < 'a') or (temp > 'z'):
break
print(temp)
print("Done")

Q: What if the user


just typed ‘abc’ and hit
enter?

slide 40

DEPARTMENT OF COMPUTER ENGINEERING


The Break Should Be Rarely Used
• Adding an extra exit point in a loop (aside from the Boolean expression in
the while loop) may make it harder to trace execution (leads to ‘spaghetti’
programming).
(while) N
Boolean met?

While adding a single


Y break may not always
Instruction result in ‘spaghetti’ it’s
the beginning of a bad
habit that may result
N (If) in difficult to trace
Boolean met? programs

Y
…rest of program

slide 41

DEPARTMENT OF COMPUTER ENGINEERING


An Alternate To Using A ‘Break’
• Instead of an ‘if’ and ‘break’ inside the
body of the loop
while (BE1):
if (BE2):
break
• Add the second Boolean expression as part of the
loop’s main Boolean expression
while (BE1) and not (BE2):

slide 42

DEPARTMENT OF COMPUTER ENGINEERING


Another Alternative To Using A ‘Break’
• If the Boolean expressions become too complex consider using a ‘flag’
flag = true
while (flag == true):
if (BE1):
flag == false
if (BE2)
flag == false
# Otherwise the flag remains set to true

• Both of these approaches still provide the advantage


of a single exit point from the loop.

slide 43

DEPARTMENT OF COMPUTER ENGINEERING


Nested Loops
• One loop executes inside of another loop(s).
• Example structure:
Outer loop (runs n times)
Inner loop (runs m times)
Body of inner loop (runs n x m times)

• Program name: nested.py


i = 1
while (i <= 2):
j = 1
while (j <= 3):
print("i = ", i, " j = ", j)
j = j + 1
i = i + 1
print("Done!")

slide 44

DEPARTMENT OF COMPUTER ENGINEERING


Nested Loops
Write a Python that will generate a pyramid of stars. The
program should ask the user to enter an integer to be
use as a basis of generating the pyramid of stars.
Sample output:
Enter an integer: 4 Enter an integer: 6
* *
* * * *
* * * * * *
* * * * * * * *
* * * * *
* * * * * *

DEPARTMENT OF COMPUTER ENGINEERING 45


Prg A Prg B
* *
** **
*** ***
**** ****
***** *****
**** ****
*** ***
** **
* *

slide 46
DEPARTMENT OF COMPUTER ENGINEERING
Prg C * *
** **
*** ***
**** ****
**********
**** ****
*** ***
** **
* *

slide 47
DEPARTMENT OF COMPUTER ENGINEERING
Nested Loops

DEPARTMENT OF COMPUTER ENGINEERING 48


Infinite Loops
• Infinite loops never end (the stopping condition is
never met).
• They can be caused by logical errors:
– The loop control is never updated (Example 1 – below).
– The updating of the loop control never brings it closer to the
stopping condition (Example 2 – next slide).
• Example 1: infinite1.py
i = 1
while (i <= 10):
print("i = ", i)
i = i + 1
To stop a program with an infinite loop in
Thonny simultaneously press the <ctrl> and
the <c> keys

slide 49

DEPARTMENT OF COMPUTER ENGINEERING


Infinite Loops

• Example 2: infinite2.py
i = 10
while (i > 0):
print("i = ", i)
i = i + 1
print("Done!")

To stop a program with an infinite


loop in Unix simultaneously press
the <ctrl> and the <c> keys

slide 50

DEPARTMENT OF COMPUTER ENGINEERING

You might also like