You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
83
92
84
93
```python
85
94
odds = [1, 3, 5, 7, 9, 11]
@@ -96,35 +105,46 @@ for num in odds:
96
105
11
97
106
```
98
107
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:
100
109
101
-
```python
102
-
for variable in collection:
103
-
# do things using variable, such as print
104
-
```
110
+
{alt="Loop variable 'num' being assigned the value of each element in the list odds in turn and then being printed"}
105
111
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.
107
113
108
114
## Loop variables
109
115
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.
111
117
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.
119
118
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
121
120
121
+
You can use a `for` loop to iterate through each element in a string. `for` loops are not limited to operating on lists.
122
122
123
123
```python
124
-
forkittenin[2, 4, 6, 8]:
125
-
print(kitten)
124
+
forletterin'library of babel':
125
+
print(letter)
126
126
```
127
127
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
+
128
148
## Use `range` to iterate over a sequence of numbers.
129
149
130
150
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):
140
160
2
141
161
```
142
162
143
-
144
163
## Accumulators
145
164
146
165
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.
147
166
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
+
148
169
```python
149
170
# Sum the first 10 integers.
150
171
total =0
151
-
for number inrange(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 inrange(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}')
155
179
```
156
180
157
181
```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
169
193
```
170
194
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
+
171
201
172
202
::::::::::::::::::::::::::::::::::::::: challenge
173
203
174
-
## Reversing a String
204
+
## Loop through a list
175
205
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.
178
207
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.
188
209
189
210
::::::::::::::: solution
190
211
191
212
## Solution
192
213
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
+
201
219
```
220
+
202
221
```output
203
-
nit
222
+
lettuce
223
+
carrots
224
+
celery
204
225
```
205
-
If you were to expand out the loop the iterations would look something like this:
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.
264
283
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`.
266
285
267
286
268
287
::::::::::::::: solution
@@ -272,49 +291,55 @@ Tip: You can apply the .capitalize() function to capitalize the first letter of
272
291
```python
273
292
acronym =''
274
293
for color in ['red', 'green', 'blue']:
275
-
acronym = acronym + color[0].capitalize()
294
+
acronym = acronym + color[0]
276
295
print(acronym)
277
296
```
278
297
279
298
```output
280
-
RGB
299
+
rgb
281
300
```
282
301
302
+
You could also concatenate inside of the loop with `acronym += color[0]`.
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
292
310
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.
294
316
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.
0 commit comments