Skip to content

Commit 4eab639

Browse files
Merge pull request #85 from chennesy/add_loop_image
add for loops image and exercises
2 parents d4a35d6 + 2cad876 commit 4eab639

2 files changed

Lines changed: 128 additions & 103 deletions

File tree

episodes/fig/for_loop.png

42.3 KB
Loading

episodes/for-loops.md

Lines changed: 128 additions & 103 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
---
22
title: For Loops
3-
teaching: 10
3+
teaching: 25
44
exercises: 15
55
---
66

77
::::::::::::::::::::::::::::::::::::::: objectives
88

9-
- Explain what "for loops"" are normally used for.
9+
- Explain what `for` loops are normally used for.
1010
- Trace the execution of an un-nested loop and correctly state the values of variables in each iteration.
11-
- Write for loops that use the accumulator pattern to aggregate values.
11+
- Write `for` loops that use the accumulator pattern to aggregate values.
1212

1313
::::::::::::::::::::::::::::::::::::::::::::::::::
1414

@@ -79,7 +79,16 @@ for num in odds:
7979
7
8080
```
8181

82-
This code is shorter, and more robust as well. Even if the values of the `odds` list changes, the loop will still work.
82+
A `for` loop repeats an operation -- in this case, printing -- once for each element it encounters in a collection. The general structure of a loop is:
83+
84+
```python
85+
for variable in collection:
86+
# do things using variable, such as print
87+
```
88+
89+
We can call the loop variable anything we like, there must be a colon at the end of the line starting the loop, and we must indent anything we want to run inside the loop. Unlike many other programming languages, there is no command to signify the end of the loop body; everything indented after the `for` statement belongs to the loop.
90+
91+
Loops are more robust ways to deal with containers like lists. Even if the values of the `odds` list changes, the loop will still work.
8392

8493
```python
8594
odds = [1, 3, 5, 7, 9, 11]
@@ -96,35 +105,46 @@ for num in odds:
96105
11
97106
```
98107

99-
A `for` loop repeats an operation -- in this case, printing -- once for each element it encounters in a collection. The general structure of a loop is:
108+
Using a shorter version of the odds example above, the loop might look like this:
100109

101-
```python
102-
for variable in collection:
103-
# do things using variable, such as print
104-
```
110+
![](fig/for_loop.png){alt="Loop variable 'num' being assigned the value of each element in the list odds in turn and then being printed"}
105111

106-
We can call the loop variable anything we like, there must be a colon at the end of the line starting the loop, and we must indent anything we want to run inside the loop. Unlike many other programming languages, there is no command to signify the end of the loop body; everything indented after the `for` statement belongs to the loop.
112+
Each number (`num`) variable in the `odds` list is looped through and printed one number after another.
107113

108114
## Loop variables
109115

110-
Loop variables are created on demand when you define the loop and they will persist after the loop finishes. In other words, in the loop:
116+
Loop variables are created on demand when you define the loop and they will persist after the loop finishes. Like all variable names, it's helpful to give `for` loop variables meaningful names that you'll understand as the code in your loop grows. `for num in odds` is easier to understand than `for kitten in odds`, for example.
111117

112-
```python
113-
odds = [1, 3, 5, 7]
114-
for num in odds:
115-
print(num)
116-
print(num)
117-
```
118-
We are creating a new variable called `num` that will correspond to each element in the `odds` list as it passes through the loop. At the end of the loop, `num` is still equal to the last element in the list it was assigned to.
119118

120-
Like all variable names, it's helpful to give `for` loop variables meaningful names that you'll understand as the code in your loop grows. For example, `even` is probably a better variable to use than `kitten` here:
119+
## You can loop through other Python objects
121120

121+
You can use a `for` loop to iterate through each element in a string. `for` loops are not limited to operating on lists.
122122

123123
```python
124-
for kitten in [2, 4, 6, 8]:
125-
print(kitten)
124+
for letter in 'library of babel':
125+
print(letter)
126126
```
127127

128+
```output
129+
L
130+
i
131+
b
132+
r
133+
a
134+
r
135+
y
136+
137+
o
138+
f
139+
140+
B
141+
a
142+
b
143+
e
144+
l
145+
```
146+
147+
128148
## Use `range` to iterate over a sequence of numbers.
129149

130150
The built-in function `range()` produces a sequence of numbers. You can pass a single parameter to identify how many items in the sequence to range over (e.g. `range(5)`) or if you pass two arguments, the first corresponds to the starting point and the second to the end point. The end point works in the same way as Python index values ("up to, but not including").
@@ -140,129 +160,128 @@ for number in range(0,3):
140160
2
141161
```
142162

143-
144163
## Accumulators
145164

146165
A common loop pattern is to initialize an *accumulator* variable to zero, an empty string, or an empty list before the loop begins. Then the loop updates the accumulator variable with values from a collection.
147166

167+
We can use the `+=` operator to add a value to `total` in the loop below, so that each time we iterate through the loop we'll add the index value of the `range()` to `total`.
168+
148169
```python
149170
# Sum the first 10 integers.
150171
total = 0
151-
for number in range(1, 11):
152-
print(f'number is: {number} total is: {total}')
153-
total = total + number
154-
print(f'At the end of the loop, number is {number} and total is {total}')
172+
173+
# range(1,11) will give us the numbers 1 through 10
174+
for num in range(1, 11):
175+
print(f'num is: {num} total is: {total}')
176+
total += num
177+
178+
print(f'Loop finished. num is: {num} total is: {total}')
155179
```
156180

157181
```output
158-
number is: 1 total is: 0
159-
number is: 2 total is: 1
160-
number is: 3 total is: 3
161-
number is: 4 total is: 6
162-
number is: 5 total is: 10
163-
number is: 6 total is: 15
164-
number is: 7 total is: 21
165-
number is: 8 total is: 28
166-
number is: 9 total is: 36
167-
number is: 10 total is: 45
168-
At the end of the loop number is 10 and total is 55
182+
num is: 1 total is: 0
183+
num is: 2 total is: 1
184+
num is: 3 total is: 3
185+
num is: 4 total is: 6
186+
num is: 5 total is: 10
187+
num is: 6 total is: 15
188+
num is: 7 total is: 21
189+
num is: 8 total is: 28
190+
num is: 9 total is: 36
191+
num is: 10 total is: 45
192+
Loop finished. Num is: 10 total is: 55
169193
```
170194

195+
- The first time through the loop, `total` is equal to 0, and `num` is 1 (the range starts at 1). After those values print out we add 1 to the value of `total` (0), to get 1.
196+
- The second time through the loop, `total` is equal to 1, and `num` is 2. After those print out we add 2 to the value of `total` (1), to get 3.
197+
- The third time through the loop, `total` is equal to 3, and `num` is 3. After those print out we add 3 to the value of `total` (3), to bring us to 6.
198+
- And so on.
199+
- After the loop is finished the values of `total` and `num` retain the values that were assigned the last time through the loop. So `num` is equal to 10 (the last index value of `range()`) and `total` is equal to 55 (45 + 10).
200+
171201

172202
::::::::::::::::::::::::::::::::::::::: challenge
173203

174-
## Reversing a String
204+
## Loop through a list
175205

176-
Fill in the blanks in the program below so that it prints "nit"
177-
(the reverse of the original character string "tin").
206+
Create a list of three vegetables, and then build a `for` loop to print out each vegetable from the list.
178207

179-
Tip: you can concatenate two strings together using the `+` operator. For example, `'librar' + 'ian'` will create one string, `'librarian'`.
180-
181-
```python
182-
original = "tin"
183-
result = ____
184-
for char in original:
185-
result = ____ _ _____
186-
print(result)
187-
```
208+
Bonus: Create an accumulator variable to print out the index value of each item in the list along with the vegetable name.
188209

189210
::::::::::::::: solution
190211

191212
## Solution
192213

193-
`result` is an empty string because we use it to build or accumulate on our reverse string. `char` is the loop variable for `original`. Each time through the loop `char` takes on one value from `original`. Use `char` with `result` to control the order of the string. Our loop code should look like this:
194-
195-
```
196-
original = "tin"
197-
result = ""
198-
for char in original:
199-
result = char + result
200-
print(result)
214+
```python
215+
vegetables = ['lettuce', 'carrots', 'celery']
216+
for veg in vegetables:
217+
print(veg)
218+
201219
```
220+
202221
```output
203-
nit
222+
lettuce
223+
carrots
224+
celery
204225
```
205-
If you were to expand out the loop the iterations would look something like this:
226+
Bonus:
206227

207228
```python
208-
#First loop
209-
char = "t"
210-
result = ""
211-
char + result = "t"
212-
#Second loop
213-
char = 'i"
214-
result = "t"
215-
char + result = "it"
216-
#Third loop
217-
char = "n"
218-
result = "it"
219-
char + result = "nit"
229+
idx = 0
230+
vegetables = ['lettuce', 'carrots', 'celery']
231+
for veg in vegetables:
232+
print(idx, veg)
233+
idx += 1
234+
220235
```
221236

237+
```output
238+
0 lettuce
239+
1 carrots
240+
2 celery
241+
```
242+
243+
222244
:::::::::::::::::::::::::
223245

224246
::::::::::::::::::::::::::::::::::::::::::::::::::
225-
226247
::::::::::::::::::::::::::::::::::::::: challenge
227248

228-
## Practice Accumulating
249+
## Use range() in a loop
229250

230-
Fill in the blanks to sum the lengths of each string in the list, `["book", "magazine", "dvd"]`
251+
Print out the numbers 10, 11, 12, 13, 14, 15, using range() in a `for` loop.
231252

232-
```python
233-
# Total length of the strings in the list: ["book", "magazine", "dvd"]
234-
total = 0
235-
for word in ["book", "magazine", "dvd"] :
236-
____ = total + ___(word)
237-
print(total)
238-
```
239253
::::::::::::::: solution
240254

241255
## Solution
242256

243257
```python
244-
total = 0
245-
for word in ["book", "magazine", "dvd"] :
246-
total = total + len(word)
247-
print(total)
258+
259+
for num in range(10, 16):
260+
print(num)
261+
248262
```
249263

250264
```output
265+
10
266+
11
267+
12
268+
13
269+
14
251270
15
252271
```
253272

254-
:::::::::::::::::::::::::
255273

274+
:::::::::::::::::::::::::
256275

257276
::::::::::::::::::::::::::::::::::::::::::::::::::
258277

259278
::::::::::::::::::::::::::::::::::::::: challenge
260279

261-
## Use slices in a loop
280+
## Use a string index in a loop
262281

263-
How would you loop through a list, `["red", "green", "blue"]` to create (and print out) the acronym `RGB`, pulling from the first letters in each string?
282+
How would you loop through a list with the values 'red', 'green', and 'blue' to create the acronym `rgb`, pulling from the first letters in each string? Print the acronym when the loop is finished.
264283

265-
Tip: You can apply the .capitalize() function to capitalize the first letter of a string. For example, `'university'.capitalize()` will yield `'University'`.
284+
Hint: Use the `+` operator to concatenate strings together. For example, `lib = 'lib' + 'rary'` will assign the value of 'library' to `lib`.
266285

267286

268287
::::::::::::::: solution
@@ -272,49 +291,55 @@ Tip: You can apply the .capitalize() function to capitalize the first letter of
272291
```python
273292
acronym = ''
274293
for color in ['red', 'green', 'blue']:
275-
acronym = acronym + color[0].capitalize()
294+
acronym = acronym + color[0]
276295
print(acronym)
277296
```
278297

279298
```output
280-
RGB
299+
rgb
281300
```
282301

302+
You could also concatenate inside of the loop with `acronym += color[0]`.
283303
:::::::::::::::::::::::::
284304

285305
::::::::::::::::::::::::::::::::::::::::::::::::::
286306

287307
::::::::::::::::::::::::::::::::::::::: challenge
288308

289-
## Use range() in a loop
290-
291-
How would you create a list including the numbers 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10, using range() in a `for` loop?
309+
## Subtract a list of values in a loop
292310

293-
Tips:
311+
1. Create an accumulator variable called `total` that starts at 100.
312+
2. Create a list called `numbers` with the values of 10, 15, 20, 25, 30.
313+
3. Create a `for` loop to iterate through each item in the list.
314+
4. Each time through the list update the value of `total` to subtract the value of the current list item from `total`. Tip: `-=` works for subtraction in the same way that `+=` works for addition.
315+
5. Print the value of `total` inside of the loop to keep track of its value throughout.
294316

295-
- You can create a blank list before the `for` loop by assigning a variable to `[]`. For example, `container_list = []`.
296-
- You can use the .append() method to add items to a list.
297317

298318
::::::::::::::: solution
299319

300320
## Solution
301321

302322
```python
303-
container = []
304-
for num in range(1, 11):
305-
container.append(num)
306-
print(container)
307-
323+
total = 100
324+
numbers = [10, 15, 20, 25, 30]
325+
for num in numbers:
326+
total -= num
327+
print(total)
308328
```
309329

310330
```output
311-
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
331+
90
332+
75
333+
55
334+
30
335+
0
312336
```
313337

314338
:::::::::::::::::::::::::
315339

316340
::::::::::::::::::::::::::::::::::::::::::::::::::
317341

342+
318343
:::::::::::::::::::::::::::::::::::::::: keypoints
319344

320345
- A *for loop* executes commands once for each value in a collection.

0 commit comments

Comments
 (0)