You are on page 1of 40

Loops

for: determinate loops


The number of repetitions are determined
in advance.
while: indeterminate loops
The condition to end a loop is only satis-
fied during the execution of the loop itself.
Loop?
• Example 1:
• Program displays 1 – 5

for k in range(1,6):
print(k)
Basic for construct
•for k in range(first, last-1):
• The basic for construct •for k in range(first, last-1, increment):
for index in range( j, k): •loop 수행횟수
statements floor((last-first)/increment)+1
•floor(x)
for index in range( j, k, m): rounds x down towards –inf
statements ex) for k in range(1, 6, 2)
floor((6-1)/2)+1=floor(5/2)+1=3
for k in range(1,5):
print(k) 1
2
for k in range(1,5,2): 3
print(k) 4

1
* Program displays 1 – 100? 3
Looping Through Arithmetic Progres-
sion of Numbers
Example

• Display 1.0, 1.5, 2.0, 2.5, 3.0 using for loop.


• Display odd integer between 1 and 5.

• Factorials!
fact = 1
for k in range(1,10):
fact = k * fact
• Compute 10! print(fact)
More general for
• more general for
for index in v
– v: list or vector

for k in [2, 3, 5, 7]: x = [10, 20, 30, 40, 50, 60, 70, 80, 90]
print(k) n=[2, 3, 5, 7]
for k in n:
print(x[k])
Example
• Compute the sum of 1, 3, 7 using for-
loop and list [1, 3, 7].
num = 0
for k in [1, 3, 7]:
num = ????????

• Compute the multiplication of 1st, 3rd, 7th


element of x using for loop.
x = [10, 20, 30, 40, 50, 60, 70, 80, 90]
num = 1
for k in [1, 3, 7]:
num = ????????????????
Example
• Compute the sum of a=[2 3 5 8 13].
• Compute the sum of 1st, 3rd, 5th element of
a=[2 3 5 8 13].
• Compute the average of a=[2 3 5 8 13].
Looping Through
Characters of a String
• Example 6: Program requests a word as
input and displays it backwards.

word = “hello” word = “hello”


for k in word: for k in [1, 3]:
print(k) print(word[k])
Nested for Loops

• Body of for loop can contain any type of


Python statement
– Can contain another for loop.
• Second loop must be completely con-
tained inside the first loop
– Must have a different loop variable
Nested for Loops
• Example 4: Program displays a multipli-
cation table for the integers from 1 to 5
The pass Statement
• There are times when you want loop to
cycle through a sequence and not do
anything
– The pass statement should be used.
• The pass statement is a do-nothing
placeholder statement
Homework

ch3.4
51, 55, 56, 59, 60, 64, 67, 72, 73 
Relational and Logical Operators

• A condition is an expression
– Involving relational operators (such as < and
>=)
– Logical operators (such as and, or, and not)
– Evaluates to either True or False
• Conditions used to make decisions
– Control loops
– Choose between options
The for Loop
• Used to iterate through a sequence of val-
ues
• General form
of a for loop
• Sequence can be
– Arithmetic progression of numbers
– String
– List
– File object
The for Loop
• Variable is successively assigned each
value in the sequence

• Indented block of statements executed


after each assignment
• Physical indentation tells interpreter
where block starts and stops
Looping Through Arithmetic Progression
of Numbers

• Range function is used to generate an


arithmetic progression
Looping Through Arithmetic Progression
of Numbers

• Example 1: Code displays four integers


and their squares

:
Looping Through Arithmetic Progression
of Numbers
• Example 2: Program displays a table
showing the population each year until
2018.
Looping Through Arithmetic Progression
of Numbers

FIGURE 3.44 Flowchart for Example 2.


Step Values for the range Function

• Variation of the range function generates


a sequence of integers
– Successive integers differ by a value other
than 1
• Examples
Step Values for the range Function
• Example 3: Program requests
– amount deposited
– annual rate of interest
– then calculates balance after each quarter-year for
four quarters.
Step Values for the range Function

• Example 3, cont.
Step Values for the range Function

• If negative step value is used and initial


value is greater than terminating value,
– Range function generates a decreasing se-
quence
• Examples:
Nested for Loops

• Body of for loop can contain any type of


Python statement
– Can contain another for loop.
• Second loop must be completely con-
tained inside the first loop
– Must have a different loop variable
Nested for Loops
• Example 4: Program displays a multipli-
cation table for the integers from 1 to 5
Nested for Loops
• Example 5: Program uses nested for
loops to display a triangle of asterisks.
Looping Through
Characters of a String
• Example 6: Program requests a word as
input and displays it backwards.
Looping Through Items
of a List or Tuple
• Example 7: Program displays the months
whose names contains the letter r.
Looping Through Items
of a List or Tuple
• Example 8: Program replaces the name
of each month with its three-letter ab-
breviation.
Looping Through Items
of a List or Tuple
• Example 9: Program uses nested for
loops with list of ranks, list of suits
– Creates list consisting of 52 cards in deck of
cards
Looping Through Items
of a List or Tuple

FIGURE 3.45 Flowchart of nested for loops from Example 9.


Looping Through Lines of Text File

• Reads each line of the file in succession


– Executes indented block of statement(s) for
each line
• First line establishes connection between
program and file
Looping Through Lines of Text File
• Example 10: Program requests a first
name and then displays names of U.S.
presidents having that first name
The pass Statement

• There are times when you want loop to


cycle through a sequence and not do
anything
– The pass statement should be used.
• The pass statement is a do-nothing
placeholder statement
The pass Statement
• Example 11: Program displays the last
line of a file
Populating a List with
Contents of a Text File

One way of placing the contents of a text file into a list.


Populating a List with
Contents of a Text File

A more efficient way (to be explained in next two chapters)

You might also like