week4-2-forloops
week4-2-forloops
• Use for-each loops when reading and writing algorithms to loop over
iterable objects
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!
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
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.
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.
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, ")")
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 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?
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
S T E L L A
20
For-Each Search Function
We can use a for-each loop to implement this approach as code.
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.
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"
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.
• Use for-each loops when reading and writing algorithms to loop over
iterable objects