0% found this document useful (0 votes)
5 views27 pages

week4-2-forloops

The document covers the use of for-range and for-each loops in Python, emphasizing their application in repeating actions and iterating over iterable objects. It explains the structure of these loops, their differences from while loops, and introduces concepts like nesting loops and linear search algorithms. Additionally, it provides examples and learning goals related to control flow and algorithm translation.

Uploaded by

itxjack100
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)
5 views27 pages

week4-2-forloops

The document covers the use of for-range and for-each loops in Python, emphasizing their application in repeating actions and iterating over iterable objects. It explains the structure of these loops, their differences from while loops, and introduces concepts like nesting loops and linear search algorithms. Additionally, it provides examples and learning goals related to control flow and algorithm translation.

Uploaded by

itxjack100
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/ 27

For Loops

15-110 – Wednesday 02/05


Learning Goals
• Use for-range loops when reading and writing algorithms to repeat
actions a specified number of times

• Use for-each loops when reading and writing algorithms to loop over
iterable objects

• Translate algorithms from control flow charts to Python code

• Use nesting of statements to create complex control flow

• Recognize the linear search algorithm in multiple implementations


2
For-Range Loops

3
For-Range Loops Implement Repeated Actions
We've learned how to use while loops and loop control variables to
iterate until a certain condition is met. When that loop control is
straightforward (increase a number until it reaches a certain limit), we
can use a more standardized structure instead.

A for-range loop tells the program exactly how many times to repeat
an action. The loop control variable is updated by the loop itself!

for <loop_variable> in range(<max_num_plus_one>):


<loop_body>

4
While Loops vs. For-Range Loops
To sum the numbers from 0 to n in a In a for-range loop, the loop control
while loop, we'd write the following: variable starts at 0, and automatically
increases by 1 each loop iteration.
i = 0 result = 0
result = 0 for i in range(n + 1):
while i <= n:
result = result + i
result = result + i
print(result)
i = i + 1
print(result) We have to go up to n + 1 because
for-range goes up to but not including
the given number. It's like writing
while i < n + 1
5
For-Range Loop Flow Chart result = 0

Unlike while loops, we don't update the i = 0


loop control variable. The for-range loop
will do the update automatically.
We show actions done by the range True if i < n+1 False
function with a dotted outline here,
because they're implicit, not written
directly.
result = result + i

result = 0 print(result)
for i in range(n + 1):
i = i + 1
result = result + i
print(result)
6
range() Creates Loop Variable Values
When we run for i in range(10), range(10) assigns the loop
control variable the consecutive values 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, one
value each iteration.
We can also give range() two arguments, a start and an end value.
The loop control variable begins with the start value, is incremented by
1 each iteration, and goes up to but not including the end value.
The following code would generate the numbers 3, 4, 5, 6, and 7.

for i in range(3, 8):


print(i)
7
range() Also Has a Step
If we use three arguments in the range() function, the last argument is the step
of the range (how much the loop control variable should increase by each
iteration). The following example would print the even numbers from 1 to 10,
because it updates i by 2 each iteration.
for i in range(2, 11, 2):
print(i)
Anything we can do in a for loop can also be done in a while loop. In a while loop,
the above would be equivalent to:
i = 2
while i < 11:
print(i)
i = i + 2
8
range() Example: Countdown
Let's write a program that counts backwards from 10 to 1, using
range().

for i in range(10, 0, -1):


print(i)

Note that i has to end at 0 in order to make 1 the last number that is
printed.

9
Activity: Predict the Printed Values
Predict what the loop will print based on its range()

10
Nested Loops

11
Nesting Loops
We've already used nesting to put conditionals in other conditionals. Conditionals
can be nested in loops too, but more importantly, we can also nest loops inside of
loops!
We mostly do this with for-range loops, and mostly when we want to loop over
multiple dimensions.

for <loop_var_1> in range(<end_num_1>):


for <loop_var_2> in range(<end_num_2>):
<both_loops_body>
<just_outer_loop_body>
In nested loops, the inner loop is repeated every time the outer loop takes a step.

12
Example: Coordinate Plane with Nested Loops
Suppose we want to print all the coordinates on a plane from (0,0) to
(4,3).

for x in range(5):
for y in range(4):
print("(", x, ",", y, ")")

Note that every iteration of y happens anew in each iteration of x.

13
Tracing Nested Loops Iteration x y x*y
1 1 1 1
2 1 2 2
The following code prints out a 4x3 3 1 3 3
multiplication table. We can use code 4 2 1 2
tracing to find the values at each iteration of 5 2 2 4
the loops. 6 2 3 6
7 3 1 3
for x in range(1, 5): 8 3 2 6
9 3 3 9
for y in range(1, 4):
10 4 1 4
print(x, "*", y, "=", x * y) 11 4 2 8
12 4 3 12

14
For-Each Loops

15
Iterable Values
There are some types of values that can be thought of as a whole
composed of many parts. We call these types iterable, because we can
iterate over each of the parts in turn.

Of the types we've explored so far, strings are iterable, because they
are composed of characters (individual letters or symbols).

16
For-Each Loops Repeat Over Iterable Values
We can use for-each loops to iterate over values that are iterable! A
for-each loop over a string looks like this:

for <character_variable> in <string>:


<character_action_body>
For example, if we run the following code, it will print out each
character of the string with an exclamation point after it.

for c in "Hello":
print(c + "!")
17
Linear Search

18
Searching for Characters
Suppose we want to determine whether a string contains a specific
character. How can we do that?

We'll need to think about this from a computer's perspective...

19
How Computers See Characters
If we ask a computer to check if a character is in a string, it sees the
whole string as a series of not-yet-known characters:

S T E L L A

In order to determine if the character is one of them, it needs to check


each character in turn.

S T E L L A
20
For-Each Search Function
We can use a for-each loop to implement this approach as code.

def containsChar(s, c):


for letter in s:
if letter == c:
return True
return False

Note that we can return True as soon as we find the character, but we
can't return False until we've gone through all the characters.
21
Check-Any and Check-All Loop Patterns
Search follows a common pattern for functions that return a Boolean.
A check-any pattern returns True if any of the characters in the string
meet a condition, and False otherwise.
A check-all pattern returns True if all of the characters in the string
meet a condition, and False otherwise.

def check_any(s, c): def check_all(s, c):


for letter in s: for letter in s:
if letter == c: if letter != c:
return True return False
return False return True 22
Finding a Location
Now we can find if a character is in a string, but we don't know where it
is. How can we find the character's position?

First, we need to determine what each character's position is. Python


assigns integer positions in order, starting with 0.

S T E L L A

0 1 2 3 4 5
23
Getting Characters By Location
If we know a character's position, Python will let us access that
character directly from the string. Use square brackets with the integer
position in between to get the character.

s = "STELLA"
c = s[2] # "E"

We can get the number of characters in a string with the built-in


function len(s). This function will come in handy soon.

24
For-Range Search Function
Now we can write a search function that returns the position of a character.
This time, we'll write it as a for-range loop, where the loop control variable i
is each position in the string.
Instead of returning True or False, we'll return the position. If we don't find
the character, we'll return -1.

def charLocation(s, c):


for i in range(len(s)):
if s[i] == c:
return i Question: If c appears more than once
return -1 in s, which position will it return?
25
While Loop Search Function
Anything that can be done with a We could also use a for-each loop and
for-range loop can also be done with add a counter variable. This works the
a while loop. same way.

def charLocation(s, c): def charLocation(s, c):


i = 0 i = 0
while i < len(s): for letter in s:
if s[i] == c: if letter == c:
return i return i
i = i + 1 i = i + 1
return -1 return -1

Which of the three approaches is best? It depends!


26
Learning Goals
• Use for-range loops when reading and writing algorithms to repeat
actions a specified number of times

• Use for-each loops when reading and writing algorithms to loop over
iterable objects

• Translate algorithms from control flow charts to Python code

• Use nesting of statements to create complex control flow

• Recognize the linear search algorithm in multiple implementations


27

You might also like