forked from ninas/umonya_notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfor_loops.html
316 lines (272 loc) · 10.8 KB
/
for_loops.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Introductory Programming in Python: Sequential Loops</title>
<link rel='stylesheet' type='text/css' href='style.css' />
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<script src="animation.js" type="text/javascript">
</script>
</head>
<body onload="animate_loop()">
<div class="page">
<h1>Introductory Programming in Python: Lesson 10<br />
Sequential Loops</h1>
<div class="centered">
[<a href="tuples.html">Prev: Tuples</a>] [<a href="index.html">Course Outline</a>] [<a href="strings.html">Next: Strings in depth</a>]
</div>
<h2>Loops over Lists</h2>
<p>In <a href="lists.html">lesson 8</a> we introduced the concept of lists. </p>
<p>A list is a type of variable that contains other elements. For instance we could create a shopping list. </p>
<pre class='listing'>
>>> shopping=['Milk','Bread','Eggs','Motherboard','Cheese','Jacket']
</pre>
<p>In order to view the individual contents of that list, we could refer to them by index</p>
<pre class='listing'>
>>> shopping[0]
'Milk'
>>> shopping[3]
'Motherboard'
</pre>
<p> In order to view all the items of our list, we could manually type in all the indexes, but what happens if you add more items later, or if you have 100 items? A better idea would be to use a while loop to change the index. We set the index to 0 to begin with, then while the index is less than length of the list, we print out the item in the list referenced by the index and increment the index.</p>
<pre class='listing'>
>>> index=0
>>> while (index<len(shopping)):
... print shopping[index]
... index+=1
...
Milk
Bread
Eggs
Motherboard
Cheese
Jacket
>>>
</pre>
<p>That works, but, once again python provides us a better tool for the job in the form of
the <a class="doclink" href="http://olympiad.cs.uct.ac.za/docs/python-docs-2.6/reference/compound_stmts.html#for">for
statement</a>.</p>
<p>The for statement is also a looping statement, like the while statement, except that it loops
over the elements of a list rather than until a boolean expression is false. It looks like this</p>
<pre class='definition'>
for <element> in <list>:
statement
statement
...
</pre>
<p>Where 'element' is a variable name (not necessarily 'element'),
which may be as yet unassigned (the for statement will assign a value
to it), or may be an already extant variable, in which case a new value
will be assigned to that variable by the for statement. 'list' is an
expression whose value is of type list.</p>
<p>What this does exactly is execute the indented statements
<strong>once for each element in the list 'list'</strong>. Each time
the statements are executed, the variable in the position of 'element'
is assigned the value of the next element in 'list', starting with the
first.</p>
<p>So, for example, the following program</p>
<pre class='listing'>
#a small program to display your shopping list
shopping=['Milk','Bread','Eggs','Motherboard','Cheese','Jacket']
for i in shopping:
print "Item:",i
</pre>
<p>produces the following output</p>
<pre class='listing'>
Item: Milk
Item: Bread
Item: Eggs
Item: Motherboard
Item: Cheese
Item: Jacket
</pre>
<p>Well, that's pretty cool. Notice how the variable i changes on every iteration (every repeat of the loop). But what if we wanted to number the list too, or have two lists, one with the item and one with the price. What we could do is have a list of indexes, and use the for loop to go through them, printing out both the index and the item in the shopping list that corresponds to that number. We could do that as follows: </p>
<pre class='listing'>
#a small program to display a numbered shopping list
indexes=[0,1,2,3,4,5]
shopping=['Milk','Bread','Eggs','Motherboard','Cheese','Jacket']
prices=['8','6','10','800','30','150']
for i in indexes:
print "Item number",i,"is",shopping[i],"and it costs R",prices[i]
</pre>
produces the following output
<pre class='listing'>
Item number 0 is Milk and it costs R 8
Item number 1 is Bread and it costs R 6
Item number 2 is Eggs and it costs R 10
Item number 3 is Motherboard and it costs R 800
Item number 4 is Cheese and it costs R 30
Item number 5 is Jacket and it costs R 150
</pre>
<p><i>Note that if you were printing this for your mother, she might not understand why milk is the 0th item and not the 1st, so you might want to <strong>print i+1</strong> so that it seems to start at 1.</i></p><p> That works alright. But if we were dealing with larger lists,
like of 19 items, or even thousands of items, we really don't
want to have to type out the list of possible indexes ([0, 1, 2, ...,
19]) every time. Python again comes to the rescue with another built in
function, <a class="doclink"
href="http://olympiad.cs.uct.ac.za/docs/python-docs-2.6/library/functions.html">range</a>.
'range' returns a list of numbers within a given range, and defined as
follows</p>
<pre class='definition'>
range([start,] stop [, step])
</pre>
<p>What it does is returns a list of integers, starting with the number
given by 'start' (or 0 if start is not given), up to but not including
the number given by 'stop'. If 'step' is given, the list will only
provide every step'th integer in the sequence. Examples probably
illustrate this better ...</p>
<pre class='listing'>
>>> range(5)
[0, 1, 2, 3, 4]
>>> range(4,10)
[4, 5, 6, 7, 8, 9]
>>> range(-3,3)
[-3, -2, -1, 0, 1, 2]
>>> range(0,10,2)
[0, 2, 4, 6, 8]
>>> range(10,20,3)
[10, 13, 16, 19]
>>>
</pre>
<p>So we can change our previous program slightly, as follows</p>
<pre class='listing'>
#a small program to display a numbered shopping list
shopping=['Milk','Bread','Eggs','Motherboard','Cheese','Jacket']
for i in range(len(shopping)):
print "Item number",i,"is",shopping[i]
</pre>
<p>The 'for loop' isn't only used with lists. The 'for loop' can be used with any iterable structure, ie. any structure which can be indexed. One such structure is the string, which you'll examine in depth in the next chapter. As has been mentioned previously, the string is basically a list of characters, and hence you can use a 'for loop' to iterate through those characters. So for example to print every letter of a word on a new line:
<pre class='listing'>
>>> for i in "Any Word":
... print i
...
A
n
y
W
o
r
d
</pre>
<p> The 'for loop' also works on parts sections of lists, and edited lists, here are some examples:</p>
<pre class='listing'>
>>> for i in ["Ford","Mercedes","BMW","Audi","Toyota","Nissan"][2:5]:
... print i
...
BMW
Audi
Toyota
>>> for i in "Experts Exchange"[6:10]:
... print i,
...
s E x
>>> for i in ["Animals",3,"blah"]+[2,True,"for you"]:
... print i, " | ",
...
Animals | 3 | blah | 2 | True | for you |
>>> for i in "Hello how are you doing?"[::2]:
... print i,
...
H l o h w a e y u d i g
</pre>
<h2>else Clauses in for loops</h2>
<p>'for loop' statements may also have an else clause, which is
executed when the list is exhausted, but not when the loop is
terminated by a break statement.</p>
<pre class='definition'>
for <variable> in <list>:
<statement>
[statement]
else:
<statement>
[statement]
</pre>
<h2>Exercises</h2>
<ol>
<li>Write a program that asks the user to enter two (whole) numbers and outputs the product. However, do so without using * but rather by repeatedly adding.</li>
<li>Write a program that prints out the string "repeat" 100 times.</li>
<li>Write a program that asks the user for their name, and a
number, then prints out the user's name, with some motivational comment, that many times.</li>
<li>What is an expression using the range function that yields a
list of 10 consecutive integers starting at 0?</li>
<li>What is an expression using the range function that yields a
list of 100 consecutive integers starting from 1?</li>
<li>What is an expression using the range function that yields a
list of 100 consecutive <strong>even</strong> integers starting
from 2?</li>
<li>Write a program that prints the <strong>odd</strong> numbers from 1 to 100 each on
its own line.</li>
<li>The triangular numbers are the numbers 1, 3, 6, 10, 15... The <i>n</i>'th triangular number is the sum of all the integers from 1 till <i>n</i>. EG the 4th triangular number is 1+2+3+4=10. Write a program that accepts an integer value for <i>n</i> from the user, and prints the <i>n</i>'th triangular number.</li>
<li>Write a program that accepts words from the user, storing them in a list, until the user enters the word "end". The program must then print out all the words in reverse order.</li>
<li><i>Modify your answer to question 10 from "Flow Control:
Conditionals", i.e. print out the numbers from 1 to 10 by which a
user entered number is divisible, to use a for loop instead of
multiple if statements.</i></li>
<li>Write a program that asks the user for the height of a triangle.
It must then print out a right handed triangle, with the right-angle on the
bottom left, made of asterisks ('*') of a height equal to the
number entered. Example input/output follows ...
<pre class='listing'>
Enter triangle height: 3
*
**
***
</pre>
<pre class='listing'>
Enter triangle height: 5
*
**
***
****
*****
</pre>
</li>
<li>Do the same as above, except now with the right-angle in the top right, and after you have printed the first triangle, you must start all over again until the user enters a blank line for input. Example ...
<pre class='listing'>
Enter triangle height: 3
***
**
*
Enter triangle height: 5
*****
****
***
**
*
Enter triangle height:
</pre>
</li>
<li>Write a program that prints out a 'Christmas' tree shape from
asterisks. The program should ask the user for the height of the
tree, in lines, and the tree should have a stalk of two lines
regardless. If the user enters a height, the tree should be printed
out, and the user should be prompted for another height until they
enter a blank line.
<pre class='listing'>
Enter tree height: 4
*
***
*****
*******
*
*
Enter tree height: 6
*
***
*****
*******
*********
***********
*
*
</pre>
</li>
</ol>
<div class="centered">
[<a href="tuples.html">Prev: Tuples</a>] [<a href="index.html">Course Outline</a>] [<a href="strings.html">Next: Strings in depth</a>]
</div>
</div>
<div class="pagefooter">
Copyright © James Dominy 2007-2008; Released under the <a href="http://www.gnu.org/copyleft/fdl.html">GNU Free Documentation License</a><br />
<a href="intropython.tar.gz">Download the tarball</a>
</div>
</body>
</html>