-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathiteration-and-loops.html
More file actions
485 lines (436 loc) · 45.5 KB
/
iteration-and-loops.html
File metadata and controls
485 lines (436 loc) · 45.5 KB
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Python Basics for Data Science</title>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<meta name="description" content="Introductory Python materials for the INFO 370: Introduction to Data Science Course. Compiled by Michael Freeman.">
<meta name="generator" content="bookdown 0.3 and GitBook 2.6.7">
<meta property="og:title" content="Python Basics for Data Science" />
<meta property="og:type" content="book" />
<meta property="og:description" content="Introductory Python materials for the INFO 370: Introduction to Data Science Course. Compiled by Michael Freeman." />
<meta name="github-repo" content="rstudio/bookdown-demo" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="Python Basics for Data Science" />
<meta name="twitter:description" content="Introductory Python materials for the INFO 370: Introduction to Data Science Course. Compiled by Michael Freeman." />
<meta name="author" content="Joel Ross">
<meta name="date" content="2018-01-03">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="prev" href="logic-and-conditionals.html">
<link rel="next" href="lists-and-sequences.html">
<script src="libs/jquery-2.2.3/jquery.min.js"></script>
<link href="libs/gitbook-2.6.7/css/style.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-bookdown.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-highlight.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-search.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-fontsettings.css" rel="stylesheet" />
<style type="text/css">
div.sourceCode { overflow-x: auto; }
table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode {
margin: 0; padding: 0; vertical-align: baseline; border: none; }
table.sourceCode { width: 100%; line-height: 100%; }
td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
td.sourceCode { padding-left: 5px; }
code > span.kw { color: #007020; font-weight: bold; } /* Keyword */
code > span.dt { color: #902000; } /* DataType */
code > span.dv { color: #40a070; } /* DecVal */
code > span.bn { color: #40a070; } /* BaseN */
code > span.fl { color: #40a070; } /* Float */
code > span.ch { color: #4070a0; } /* Char */
code > span.st { color: #4070a0; } /* String */
code > span.co { color: #60a0b0; font-style: italic; } /* Comment */
code > span.ot { color: #007020; } /* Other */
code > span.al { color: #ff0000; font-weight: bold; } /* Alert */
code > span.fu { color: #06287e; } /* Function */
code > span.er { color: #ff0000; font-weight: bold; } /* Error */
code > span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
code > span.cn { color: #880000; } /* Constant */
code > span.sc { color: #4070a0; } /* SpecialChar */
code > span.vs { color: #4070a0; } /* VerbatimString */
code > span.ss { color: #bb6688; } /* SpecialString */
code > span.im { } /* Import */
code > span.va { color: #19177c; } /* Variable */
code > span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
code > span.op { color: #666666; } /* Operator */
code > span.bu { } /* BuiltIn */
code > span.ex { } /* Extension */
code > span.pp { color: #bc7a00; } /* Preprocessor */
code > span.at { color: #7d9029; } /* Attribute */
code > span.do { color: #ba2121; font-style: italic; } /* Documentation */
code > span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
code > span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
code > span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
</style>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div class="book without-animation with-summary font-size-2 font-family-1" data-basepath=".">
<div class="book-summary">
<nav role="navigation">
<ul class="summary">
<li><a href="./">Python Basics for Data Science</a></li>
<li class="divider"></li>
<li class="chapter" data-level="" data-path="index.html"><a href="index.html"><i class="fa fa-check"></i>About the book</a></li>
<li class="chapter" data-level="1" data-path="software-installation.html"><a href="software-installation.html"><i class="fa fa-check"></i><b>1</b> Software Installation</a><ul>
<li class="chapter" data-level="1.1" data-path="software-installation.html"><a href="software-installation.html#summary"><i class="fa fa-check"></i><b>1.1</b> Summary</a></li>
<li class="chapter" data-level="1.2" data-path="software-installation.html"><a href="software-installation.html#r"><i class="fa fa-check"></i><b>1.2</b> R</a></li>
<li class="chapter" data-level="1.3" data-path="software-installation.html"><a href="software-installation.html#rstudio"><i class="fa fa-check"></i><b>1.3</b> RStudio</a></li>
<li class="chapter" data-level="1.4" data-path="software-installation.html"><a href="software-installation.html#anaconda-python"><i class="fa fa-check"></i><b>1.4</b> Anaconda (Python)</a></li>
<li class="chapter" data-level="1.5" data-path="software-installation.html"><a href="software-installation.html#git"><i class="fa fa-check"></i><b>1.5</b> Git</a></li>
<li class="chapter" data-level="1.6" data-path="software-installation.html"><a href="software-installation.html#command-line-tools-windows"><i class="fa fa-check"></i><b>1.6</b> Command-line Tools (Windows)</a><ul>
<li class="chapter" data-level="1.6.1" data-path="software-installation.html"><a href="software-installation.html#git-bash"><i class="fa fa-check"></i><b>1.6.1</b> Git Bash</a></li>
<li class="chapter" data-level="1.6.2" data-path="software-installation.html"><a href="software-installation.html#windows-bash"><i class="fa fa-check"></i><b>1.6.2</b> Windows Bash</a></li>
<li class="chapter" data-level="1.6.3" data-path="software-installation.html"><a href="software-installation.html#powershell-windows-management-framework"><i class="fa fa-check"></i><b>1.6.3</b> Powershell (Windows Management Framework)</a></li>
</ul></li>
<li class="chapter" data-level="1.7" data-path="software-installation.html"><a href="software-installation.html#text-editors"><i class="fa fa-check"></i><b>1.7</b> Text Editors</a><ul>
<li class="chapter" data-level="1.7.1" data-path="software-installation.html"><a href="software-installation.html#visual-studio-code"><i class="fa fa-check"></i><b>1.7.1</b> Visual Studio Code</a></li>
<li class="chapter" data-level="1.7.2" data-path="software-installation.html"><a href="software-installation.html#sublimetext"><i class="fa fa-check"></i><b>1.7.2</b> SublimeText</a></li>
<li class="chapter" data-level="1.7.3" data-path="software-installation.html"><a href="software-installation.html#atom"><i class="fa fa-check"></i><b>1.7.3</b> Atom</a></li>
</ul></li>
<li class="chapter" data-level="1.8" data-path="software-installation.html"><a href="software-installation.html#resources"><i class="fa fa-check"></i><b>1.8</b> Resources</a></li>
</ul></li>
<li class="chapter" data-level="2" data-path="functions.html"><a href="functions.html"><i class="fa fa-check"></i><b>2</b> Functions</a><ul>
<li class="chapter" data-level="2.1" data-path="functions.html"><a href="functions.html#resources-1"><i class="fa fa-check"></i><b>2.1</b> Resources</a></li>
<li class="chapter" data-level="2.2" data-path="functions.html"><a href="functions.html#what-are-functions"><i class="fa fa-check"></i><b>2.2</b> What are Functions?</a></li>
<li class="chapter" data-level="2.3" data-path="functions.html"><a href="functions.html#python-function-syntax"><i class="fa fa-check"></i><b>2.3</b> Python Function Syntax</a><ul>
<li class="chapter" data-level="2.3.1" data-path="functions.html"><a href="functions.html#object-methods"><i class="fa fa-check"></i><b>2.3.1</b> Object Methods</a></li>
</ul></li>
<li class="chapter" data-level="2.4" data-path="functions.html"><a href="functions.html#built-in-python-functions"><i class="fa fa-check"></i><b>2.4</b> Built-in Python Functions</a><ul>
<li class="chapter" data-level="2.4.1" data-path="functions.html"><a href="functions.html#modules-and-libraries"><i class="fa fa-check"></i><b>2.4.1</b> Modules and Libraries</a></li>
</ul></li>
<li class="chapter" data-level="2.5" data-path="functions.html"><a href="functions.html#writing-functions"><i class="fa fa-check"></i><b>2.5</b> Writing Functions</a><ul>
<li class="chapter" data-level="2.5.1" data-path="functions.html"><a href="functions.html#doc-strings"><i class="fa fa-check"></i><b>2.5.1</b> Doc Strings</a></li>
</ul></li>
</ul></li>
<li class="chapter" data-level="3" data-path="introduction-to-python.html"><a href="introduction-to-python.html"><i class="fa fa-check"></i><b>3</b> Introduction to Python</a><ul>
<li class="chapter" data-level="3.1" data-path="introduction-to-python.html"><a href="introduction-to-python.html#resources-2"><i class="fa fa-check"></i><b>3.1</b> Resources</a></li>
<li class="chapter" data-level="3.2" data-path="introduction-to-python.html"><a href="introduction-to-python.html#programming-with-python"><i class="fa fa-check"></i><b>3.2</b> Programming with Python</a><ul>
<li class="chapter" data-level="3.2.1" data-path="introduction-to-python.html"><a href="introduction-to-python.html#versions"><i class="fa fa-check"></i><b>3.2.1</b> Versions</a></li>
</ul></li>
<li class="chapter" data-level="3.3" data-path="introduction-to-python.html"><a href="introduction-to-python.html#running-python-scripts"><i class="fa fa-check"></i><b>3.3</b> Running Python Scripts</a><ul>
<li class="chapter" data-level="3.3.1" data-path="introduction-to-python.html"><a href="introduction-to-python.html#command-line"><i class="fa fa-check"></i><b>3.3.1</b> Command-Line</a></li>
<li class="chapter" data-level="3.3.2" data-path="introduction-to-python.html"><a href="introduction-to-python.html#jupyter-notebooks"><i class="fa fa-check"></i><b>3.3.2</b> Jupyter Notebooks</a></li>
</ul></li>
<li class="chapter" data-level="3.4" data-path="introduction-to-python.html"><a href="introduction-to-python.html#python-basics"><i class="fa fa-check"></i><b>3.4</b> Python Basics</a></li>
<li class="chapter" data-level="3.5" data-path="introduction-to-python.html"><a href="introduction-to-python.html#comments"><i class="fa fa-check"></i><b>3.5</b> Comments</a></li>
<li class="chapter" data-level="3.6" data-path="introduction-to-python.html"><a href="introduction-to-python.html#variables"><i class="fa fa-check"></i><b>3.6</b> Variables</a><ul>
<li class="chapter" data-level="3.6.1" data-path="introduction-to-python.html"><a href="introduction-to-python.html#data-types"><i class="fa fa-check"></i><b>3.6.1</b> Data Types</a></li>
</ul></li>
<li class="chapter" data-level="3.7" data-path="introduction-to-python.html"><a href="introduction-to-python.html#getting-help"><i class="fa fa-check"></i><b>3.7</b> Getting Help</a></li>
</ul></li>
<li class="chapter" data-level="4" data-path="logic-and-conditionals.html"><a href="logic-and-conditionals.html"><i class="fa fa-check"></i><b>4</b> Logic and Conditionals</a><ul>
<li class="chapter" data-level="4.1" data-path="logic-and-conditionals.html"><a href="logic-and-conditionals.html#resources-3"><i class="fa fa-check"></i><b>4.1</b> Resources</a></li>
<li class="chapter" data-level="4.2" data-path="logic-and-conditionals.html"><a href="logic-and-conditionals.html#booleans"><i class="fa fa-check"></i><b>4.2</b> Booleans</a><ul>
<li class="chapter" data-level="4.2.1" data-path="logic-and-conditionals.html"><a href="logic-and-conditionals.html#boolean-operators"><i class="fa fa-check"></i><b>4.2.1</b> Boolean Operators</a></li>
</ul></li>
<li class="chapter" data-level="4.3" data-path="logic-and-conditionals.html"><a href="logic-and-conditionals.html#conditional-statements"><i class="fa fa-check"></i><b>4.3</b> Conditional Statements</a><ul>
<li class="chapter" data-level="4.3.1" data-path="logic-and-conditionals.html"><a href="logic-and-conditionals.html#designing-conditions"><i class="fa fa-check"></i><b>4.3.1</b> Designing Conditions</a></li>
<li class="chapter" data-level="4.3.2" data-path="logic-and-conditionals.html"><a href="logic-and-conditionals.html#modules-vs.scripts"><i class="fa fa-check"></i><b>4.3.2</b> Modules vs. Scripts</a></li>
</ul></li>
</ul></li>
<li class="chapter" data-level="5" data-path="iteration-and-loops.html"><a href="iteration-and-loops.html"><i class="fa fa-check"></i><b>5</b> Iteration and Loops</a><ul>
<li class="chapter" data-level="5.1" data-path="iteration-and-loops.html"><a href="iteration-and-loops.html#resources-4"><i class="fa fa-check"></i><b>5.1</b> Resources</a></li>
<li class="chapter" data-level="5.2" data-path="iteration-and-loops.html"><a href="iteration-and-loops.html#while-loops"><i class="fa fa-check"></i><b>5.2</b> While Loops</a><ul>
<li class="chapter" data-level="5.2.1" data-path="iteration-and-loops.html"><a href="iteration-and-loops.html#counting-and-loops"><i class="fa fa-check"></i><b>5.2.1</b> Counting and Loops</a></li>
<li class="chapter" data-level="5.2.2" data-path="iteration-and-loops.html"><a href="iteration-and-loops.html#conditionals-and-sentinels"><i class="fa fa-check"></i><b>5.2.2</b> Conditionals and Sentinels</a></li>
</ul></li>
<li class="chapter" data-level="5.3" data-path="iteration-and-loops.html"><a href="iteration-and-loops.html#for-loops"><i class="fa fa-check"></i><b>5.3</b> For Loops</a><ul>
<li class="chapter" data-level="5.3.1" data-path="iteration-and-loops.html"><a href="iteration-and-loops.html#difference-from-while-loops"><i class="fa fa-check"></i><b>5.3.1</b> Difference from While Loops</a></li>
</ul></li>
<li class="chapter" data-level="5.4" data-path="iteration-and-loops.html"><a href="iteration-and-loops.html#working-with-files"><i class="fa fa-check"></i><b>5.4</b> Working with Files</a><ul>
<li class="chapter" data-level="5.4.1" data-path="iteration-and-loops.html"><a href="iteration-and-loops.html#tryexcept"><i class="fa fa-check"></i><b>5.4.1</b> Try/Except</a></li>
</ul></li>
</ul></li>
<li class="chapter" data-level="6" data-path="lists-and-sequences.html"><a href="lists-and-sequences.html"><i class="fa fa-check"></i><b>6</b> Lists and Sequences</a><ul>
<li class="chapter" data-level="6.1" data-path="lists-and-sequences.html"><a href="lists-and-sequences.html#resources-5"><i class="fa fa-check"></i><b>6.1</b> Resources</a></li>
<li class="chapter" data-level="6.2" data-path="lists-and-sequences.html"><a href="lists-and-sequences.html#lists"><i class="fa fa-check"></i><b>6.2</b> Lists</a><ul>
<li class="chapter" data-level="6.2.1" data-path="lists-and-sequences.html"><a href="lists-and-sequences.html#list-indices"><i class="fa fa-check"></i><b>6.2.1</b> List Indices</a></li>
</ul></li>
<li class="chapter" data-level="6.3" data-path="lists-and-sequences.html"><a href="lists-and-sequences.html#list-operations-and-methods"><i class="fa fa-check"></i><b>6.3</b> List Operations and Methods</a><ul>
<li class="chapter" data-level="6.3.1" data-path="lists-and-sequences.html"><a href="lists-and-sequences.html#lists-and-loops"><i class="fa fa-check"></i><b>6.3.1</b> Lists and Loops</a></li>
</ul></li>
<li class="chapter" data-level="6.4" data-path="lists-and-sequences.html"><a href="lists-and-sequences.html#nested-lists"><i class="fa fa-check"></i><b>6.4</b> Nested Lists</a></li>
<li class="chapter" data-level="6.5" data-path="lists-and-sequences.html"><a href="lists-and-sequences.html#tuples"><i class="fa fa-check"></i><b>6.5</b> Tuples</a></li>
</ul></li>
<li class="chapter" data-level="7" data-path="dictionaries.html"><a href="dictionaries.html"><i class="fa fa-check"></i><b>7</b> Dictionaries</a><ul>
<li class="chapter" data-level="7.1" data-path="dictionaries.html"><a href="dictionaries.html#resources-6"><i class="fa fa-check"></i><b>7.1</b> Resources</a></li>
<li class="chapter" data-level="7.2" data-path="dictionaries.html"><a href="dictionaries.html#dictionaries-1"><i class="fa fa-check"></i><b>7.2</b> Dictionaries</a><ul>
<li class="chapter" data-level="7.2.1" data-path="dictionaries.html"><a href="dictionaries.html#accessing-a-dictionary"><i class="fa fa-check"></i><b>7.2.1</b> Accessing a Dictionary</a></li>
</ul></li>
<li class="chapter" data-level="7.3" data-path="dictionaries.html"><a href="dictionaries.html#dictionary-methods"><i class="fa fa-check"></i><b>7.3</b> Dictionary Methods</a><ul>
<li class="chapter" data-level="7.3.1" data-path="dictionaries.html"><a href="dictionaries.html#dictionaries-and-loops"><i class="fa fa-check"></i><b>7.3.1</b> Dictionaries and Loops</a></li>
</ul></li>
<li class="chapter" data-level="7.4" data-path="dictionaries.html"><a href="dictionaries.html#nesting-dictionaries"><i class="fa fa-check"></i><b>7.4</b> Nesting Dictionaries</a></li>
<li class="chapter" data-level="7.5" data-path="dictionaries.html"><a href="dictionaries.html#which-data-structure-do-i-use"><i class="fa fa-check"></i><b>7.5</b> Which data structure do I use?</a></li>
</ul></li>
<li class="chapter" data-level="8" data-path="functional-iteration.html"><a href="functional-iteration.html"><i class="fa fa-check"></i><b>8</b> Functional Iteration</a><ul>
<li class="chapter" data-level="8.1" data-path="functional-iteration.html"><a href="functional-iteration.html#resources-7"><i class="fa fa-check"></i><b>8.1</b> Resources</a></li>
<li class="chapter" data-level="8.2" data-path="functional-iteration.html"><a href="functional-iteration.html#functions-are-variables"><i class="fa fa-check"></i><b>8.2</b> Functions ARE Variables</a><ul>
<li class="chapter" data-level="8.2.1" data-path="functional-iteration.html"><a href="functional-iteration.html#lambdas-anonymous-functions"><i class="fa fa-check"></i><b>8.2.1</b> lambdas: Anonymous Functions</a></li>
</ul></li>
<li class="chapter" data-level="8.3" data-path="functional-iteration.html"><a href="functional-iteration.html#functional-looping"><i class="fa fa-check"></i><b>8.3</b> Functional Looping</a><ul>
<li class="chapter" data-level="8.3.1" data-path="functional-iteration.html"><a href="functional-iteration.html#map"><i class="fa fa-check"></i><b>8.3.1</b> Map</a></li>
<li class="chapter" data-level="8.3.2" data-path="functional-iteration.html"><a href="functional-iteration.html#filter"><i class="fa fa-check"></i><b>8.3.2</b> Filter</a></li>
<li class="chapter" data-level="8.3.3" data-path="functional-iteration.html"><a href="functional-iteration.html#reduce"><i class="fa fa-check"></i><b>8.3.3</b> Reduce</a></li>
</ul></li>
<li class="chapter" data-level="8.4" data-path="functional-iteration.html"><a href="functional-iteration.html#list-comprehensions"><i class="fa fa-check"></i><b>8.4</b> List Comprehensions</a></li>
</ul></li>
<li class="chapter" data-level="9" data-path="pandas.html"><a href="pandas.html"><i class="fa fa-check"></i><b>9</b> Pandas</a><ul>
<li class="chapter" data-level="9.1" data-path="pandas.html"><a href="pandas.html#resources-8"><i class="fa fa-check"></i><b>9.1</b> Resources</a></li>
<li class="chapter" data-level="9.2" data-path="pandas.html"><a href="pandas.html#setup"><i class="fa fa-check"></i><b>9.2</b> Setup</a></li>
<li class="chapter" data-level="9.3" data-path="pandas.html"><a href="pandas.html#series"><i class="fa fa-check"></i><b>9.3</b> Series</a><ul>
<li class="chapter" data-level="9.3.1" data-path="pandas.html"><a href="pandas.html#series-operations-and-methods"><i class="fa fa-check"></i><b>9.3.1</b> Series Operations and Methods</a></li>
<li class="chapter" data-level="9.3.2" data-path="pandas.html"><a href="pandas.html#accessing-series"><i class="fa fa-check"></i><b>9.3.2</b> Accessing Series</a></li>
</ul></li>
<li class="chapter" data-level="9.4" data-path="pandas.html"><a href="pandas.html#data-frames"><i class="fa fa-check"></i><b>9.4</b> Data Frames</a><ul>
<li class="chapter" data-level="9.4.1" data-path="pandas.html"><a href="pandas.html#dataframe-operations-and-methods"><i class="fa fa-check"></i><b>9.4.1</b> DataFrame Operations and Methods</a></li>
<li class="chapter" data-level="9.4.2" data-path="pandas.html"><a href="pandas.html#accessing-dataframes"><i class="fa fa-check"></i><b>9.4.2</b> Accessing DataFrames</a></li>
</ul></li>
</ul></li>
<li class="divider"></li>
<li><a href="https://github.com/rstudio/bookdown" target="blank">Published with bookdown</a></li>
</ul>
</nav>
</div>
<div class="book-body">
<div class="body-inner">
<div class="book-header" role="navigation">
<h1>
<i class="fa fa-circle-o-notch fa-spin"></i><a href="./">Python Basics for Data Science</a>
</h1>
</div>
<div class="page-wrapper" tabindex="-1" role="main">
<div class="page-inner">
<section class="normal" id="section-">
<div id="iteration-and-loops" class="section level1">
<h1><span class="header-section-number">Chapter 5</span> Iteration and Loops</h1>
<p>One of the main benefits of using computers to perform tasks is that computers never get tired or bored, and so can do the same thing over and over and over and over and over and over again. This is a process known as <strong>iteration</strong>. Iteration represents another form of <em>control flow</em> (similar to conditionals), and is specified in a program using a set of statements called <strong>loops</strong>. In this module, you will learn the basics of writing loops to perform iteration; more advanced iteration concepts will be covered in later modules.</p>
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
<p><strong>Contents</strong></p>
<ul>
<li><a href="software-installation.html#resources">Resources</a></li>
<li><a href="iteration-and-loops.html#while-loops">While Loops</a></li>
<li><a href="iteration-and-loops.html#counting-and-loops">Counting and Loops</a></li>
<li><a href="iteration-and-loops.html#conditionals-and-sentinels">Conditionals and Sentinels</a></li>
<li><a href="iteration-and-loops.html#for-loops">For Loops</a></li>
<li><a href="iteration-and-loops.html#difference-from-while-loops">Difference from While Loops</a></li>
<li><a href="iteration-and-loops.html#working-with-files">Working with Files</a></li>
<li><a href="iteration-and-loops.html#tryexcept">Try/Except</a></li>
</ul>
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
<div id="resources-4" class="section level2">
<h2><span class="header-section-number">5.1</span> Resources</h2>
<ul>
<li><a href="https://books.trinket.io/pfe/05-iterations.html">Iterations (Downey)</a></li>
<li><a href="https://automatetheboringstuff.com/chapter2/">Flow Control (Sweigart)</a> (second half)</li>
<li><a href="http://openbookproject.net/thinkcs/python/english3e/iteration.html">Iteration (Severance)</a></li>
<li><a href="https://books.trinket.io/pfe/07-files.html">Files (Downey)</a></li>
<li><a href="https://automatetheboringstuff.com/chapter8/">Files and File Paths (Sweigart)</a></li>
</ul>
</div>
<div id="while-loops" class="section level2">
<h2><span class="header-section-number">5.2</span> While Loops</h2>
<p>Loops are <strong>control structures</strong> (similar to <code>if</code> statements) that allow you to perform iteration. These statements specify that a <em>block</em> of code should be executed repeatedly—the block is executed statement by statement, and then the flow of control “loops” back to the top to execute the statements again. Programming languages such as Python support a number of different kinds of loops, which differ primarily in how they determine whether or not to repeat the block (though this difference is reflected in the syntax).</p>
<p>In programming, the most basic <em>control structure</em> used for iteration is known as a <strong>while loop</strong>, which is used for “indefinite iteration” A Python while loop has the following structure:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="cf">while</span> condition:
<span class="co"># lines of code to run if the condition is True</span></code></pre></div>
<p>This construction looks much like an <code>if</code> statement, and is similar in many regards. As with an <code>if</code> statement, the <strong>condition</strong> can be any Boolean value (or any expression that evaluates to a boolean value), and it determines whether or not the loop’s <em>block</em> will be executed.</p>
<p>In order to understand how a while loop influences the flow of program control, consider a more concrete example:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">count <span class="op">=</span> <span class="dv">5</span>
<span class="cf">while</span> count <span class="op">></span> <span class="dv">0</span>:
<span class="bu">print</span>(count)
count <span class="op">=</span> count <span class="op">-</span> <span class="dv">1</span>
<span class="bu">print</span>(<span class="st">"Blastoff!"</span>)</code></pre></div>
<p>In this example, when the interpreter reaches the <code>while</code> statement, it first checks the condition (<code>count > 0</code>, where <code>count</code> is 5). Finding that condition to be <code>True</code>, the interpreter then executes the block, printing the <code>count</code> and then <em>decrementing</em> it. Once the block is executed, the interpreter loops back to the <code>while</code> statement and rechecks the condition. Finding that <code>count</code> (4) is still greater than 0, it executes the block again (causing <code>count</code> to decrement again). This continues until the interpreter loops to the <code>while</code> statement and finds that <code>count</code> has reached 0, and thus is no longer greater than 0. Since the condition is now <code>False</code>, the interpreter does <em>not</em> enter the loop, and proceeds to the following statement (“Blastoff!”).</p>
<p><strong>Importantly</strong>, the condition is only checked when the block is <em>about</em> to execute: both at the “start” of the loop, and then at the beginning of each subsequent iteration. Having the condition become <code>True</code> in the middle of the block (e.g., temporarily) will have no impact on the control flow. It is also possible for the interpreter to “never enter” the loop if the condition is not initially <code>True</code>.</p>
<div id="counting-and-loops" class="section level3">
<h3><span class="header-section-number">5.2.1</span> Counting and Loops</h3>
<p>The above example also demonstrates how to use a “counter” to determine whether or not the loop has run a sufficient number of times: this is known as a <strong>loop control variable (LCV)</strong>. The “standard” counting loop looks like:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">count <span class="op">=</span> <span class="dv">0</span> <span class="co"># 1. initialize the counter</span>
<span class="cf">while</span> count <span class="op"><</span> <span class="dv">100</span>: <span class="co"># 2. check if the counter has reached its target</span>
<span class="bu">print</span>(count) <span class="co"># 3. do some work (this may be multiple statements)</span>
count <span class="op">=</span> count <span class="op">+</span> <span class="dv">1</span> <span class="co"># 4. update the counter</span></code></pre></div>
<p>In order for a counted loop to work properly, you need to be careful about steps 2 and 4: the condition and the update.</p>
<p>First, recall that the condition is <em>whether to run the loop</em>, not <em>whether to stop</em>:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">count <span class="op">=</span> <span class="dv">0</span>
<span class="cf">while</span> count <span class="op">==</span> <span class="dv">100</span>: <span class="co"># bad condition!</span>
<span class="bu">print</span>(count)
count <span class="op">=</span> count <span class="op">+</span> <span class="dv">1</span></code></pre></div>
<p>In this case, the condition is not initially True, so the interpreter never enters the loop.</p>
<ul>
<li>When writing conditions, think <em>“do we keep going”</em> rather than <em>“are we there yet?”</em>. In loops (as in life), the journey is more important than the destination!</li>
</ul>
<p>Second, consider what happens if you forget to update the loop control variable:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">count <span class="op">=</span> <span class="dv">0</span>
<span class="cf">while</span> count <span class="op"><</span> <span class="dv">100</span>
<span class="bu">print</span>(count)
<span class="co"># no counter update</span></code></pre></div>
<p>In this case, the interpreter checks that <code>count</code> (0) is less than 100, then runs the loop. Then checks that <code>count</code> (still 0) is less than 100, then runs the loop. Then checks that <code>count</code> (<em>still</em> 0) is less than 100, then runs the loop…</p>
<p>This is known as an <strong>infinite loop</strong>: the loop will run forever, never being able to “break out” and reach the next statement.</p>
<ul>
<li>If you hit an infinite loop in Jupyter Notebook, use <code>Kernel > Interrupt</code> to break it and try again. If running a <code>.py</code> file on the command-line, use <code>Ctrl-C</code> to cancel the script.</li>
</ul>
<p>There are lots of ways to accidently produce an infinite loop:</p>
<ol style="list-style-type: decimal">
<li>Having a condition that is “too exact” can cause the loop control variable to “miss” a particular breaking value:</li>
</ol>
<p><code>python count = 0 while count != 100: # if we aren't yet at 100 print(count) count = count + 3 # this will never equal 100</code></p>
<p>Thus it is always safe to use <strong>inequalities</strong> (e.g., <code><</code> or <code>></code>) when writing loop conditions.</p>
<ol start="2" style="list-style-type: decimal">
<li>Resetting the counter in the body of the loop can cause it to never reach its goal:</li>
</ol>
<p><code>python count = 0 while count < 100: count = 0 # this resets the count! print(count) count = count + 1</code></p>
<p>The best way to catch these errors is to “play computer”: pretend that you are the compiler, and go through each statement one by one, keeping track of the loop control variable (writing its value down on a sheet of paper does wonders). This will help you be able to “trace” what your program is doing and catch any bugs there may be.</p>
</div>
<div id="conditionals-and-sentinels" class="section level3">
<h3><span class="header-section-number">5.2.2</span> Conditionals and Sentinels</h3>
<p>As with <code>if</code> statements the block for a <code>while</code> loop can contain any valid Python statements, including <code>if</code> statements or even other loops (called a “nested loop”). Control statements such as <code>if</code> are intended an extra step (4 spaces or 1 tab):</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co"># flip a coin until it shows up heads</span>
still_flipping <span class="op">=</span> <span class="va">True</span>
<span class="cf">while</span> still_flipping:
flip <span class="op">=</span> random.randint(<span class="dv">0</span>,<span class="dv">1</span>)
<span class="cf">if</span> flip <span class="op">==</span> <span class="dv">0</span>:
flip <span class="op">=</span> <span class="st">"Heads"</span>
<span class="cf">else</span>:
flip <span class="op">=</span> <span class="st">"Tails"</span>
<span class="bu">print</span>(flip)
<span class="cf">if</span> flip <span class="op">==</span> <span class="st">"Heads"</span>:
still_flipping <span class="op">=</span> <span class="va">False</span></code></pre></div>
<p>In this example, the <code>still_flipping</code> boolean variable acts as the <em>loop control variable</em>, as it determines whether or not the loop is repeated. Using a Boolean as a LCV is known as using a <strong>sentinel variable</strong>. A sentinel (guard) variable is used to control whether or not the program flow gets out of the loop: as long as the sentinel is <code>True</code>, the loop continues to run. Thus the loop can be “exited” by assigning the sentinel to be <code>False</code>. This is particularly useful when there may be a complex set of conditions that need to be met before the program can carry on.</p>
<ul>
<li>It is of course possible to design a sentinel such as <code>done_flipping</code>, and then have the <code>while</code> condition check that the sentinel is <strong>not</strong> <code>True</code>. This may be useful depending on how you’ve structured the algorithm. In either case, be sure that your sentinels are named carefully and accurately reflect the information conveyed by the variable!</li>
</ul>
</div>
</div>
<div id="for-loops" class="section level2">
<h2><span class="header-section-number">5.3</span> For Loops</h2>
<p>If you look back at the basic counting loop, you’ll notice that tracking the <code>count</code> loop control variable can be problematic. It is easy to forget the update statement (<code>count = count + 1</code>), and the the <code>count</code> variable itself acts as an extra “global” (or “less local”) variable that the interpreter needs to keep track of.</p>
<p>To avoid these problems, we can instead use a different kind of loop called a <strong>for loop</strong>. A for loop is used for “definite iteration”, when we want execute a loop a specific number of times. The basic Python for loop has the following structure:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="cf">for</span> local_variable <span class="kw">in</span> <span class="bu">range</span>(maximum):
<span class="co"># lines of code to run for each number</span></code></pre></div>
<p>For example, the basic counting while loop example could be rewritten using a simpler for loop:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="cf">for</span> count <span class="kw">in</span> <span class="bu">range</span>(<span class="dv">100</span>):
<span class="bu">print</span>(count)</code></pre></div>
<p><a href="https://docs.python.org/3/library/stdtypes.html#ranges"><code>range()</code></a> is a function that returns a value representing a sequence of numbers. It is an example of a <strong>sequence</strong> data structure, which is a way of representing multiple data items in a single variable. Sequences will be discussed more in later modules (including the most common type of sequence, a <strong>list</strong>). The <code>range()</code> function can be called with different arguments depending on the range and spread of numbers you wish to use:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co"># numbers 0 to 10 (not inclusive)</span>
<span class="co"># (0 through 9)</span>
<span class="bu">range</span>(<span class="dv">10</span>)
<span class="co"># numbers 1 through 11 (not inclusive)</span>
<span class="co"># (1 through 10)</span>
<span class="bu">range</span>(<span class="dv">1</span>,<span class="dv">11</span>)
<span class="co"># numbers 0 through 10 (not inclusive), skipping by 3</span>
<span class="co"># (0, 3, 6, 9)</span>
<span class="bu">range</span>(<span class="dv">0</span>, <span class="dv">10</span>, <span class="dv">3</span>)</code></pre></div>
<p>Thus <code>for count in range(100)</code> can be read as “for <em>each</em> number (called count) from 0 to 100”.</p>
<p>For loops may more properly be thought of as <strong>“for each”</strong> loops; they are used to go through the items in a collection (e.g., each number in a <code>range</code>), executing the loop body once for each item. The <strong><code>local_variable</code></strong> (e.g., <code>count</code>) in a for loop is <em>implicitly</em> assigned the value of the “current” item in the collection (e.g., which number in the range we’re on) at each iteration.</p>
<ul>
<li>For ranges, this basically means that the for loops keeps track of the current iteration; but the idea of this local variable will be more important as we introduce additional collection types.</li>
</ul>
<div id="difference-from-while-loops" class="section level3">
<h3><span class="header-section-number">5.3.1</span> Difference from While Loops</h3>
<p>The main difference between while loops and for loops is:</p>
<blockquote>
<p>while loops are used for <strong>indefinite</strong> iteration; for loops are used for <strong>definite</strong> iteration.</p>
</blockquote>
<p>While loops are appropriate when the interpreter doesn’t know <em>in advance</em> (before the loop starts) how many times the loop block will be executed: the loop does not have a definite number of iterations. On the other hand, a for loop is appropriate when the interpreter does know <em>in advance</em> (before the loop starts) how many times the block will be executed—a definite number of iterations. Note that that number of iterations may be a variable so not determined until runtime; however, the value of that variable will still be known when the <code>for</code> statement is executed.</p>
<p>All iteration can be written with a while loop; but when performing definite iteration, it is easier, faster, and more idiomatic to use a for loop!</p>
</div>
</div>
<div id="working-with-files" class="section level2">
<h2><span class="header-section-number">5.4</span> Working with Files</h2>
<p>For loops can be used to iterate through any collection (technically any “iterable” type). One of the more useful collections when working with data is external <strong>files</strong> (e.g., text files). Files can be treated as a collection or sequence of <em>lines</em> (each divided by a <code>\n</code> newline character), and thus Python can “read” a text file using a for loop to iterate over the lines of text in the file.</p>
<p>In order to read or write text file data, you use the built-in <a href="https://docs.python.org/3/library/functions.html#open"><code>open()</code></a> function, passing it the <em>path</em> to the file you wish to access. This function will then return an object representing that particular file (e.g., it’s location on the disk), with methods that you can use to read from and write to it.</p>
<ul>
<li>Remember to <strong>always</strong> use <em>relative</em> paths. Note that when using a Jupyter Notebook, the “current working directory” is the direction in which you ran the <code>jupyter notebook</code> command to start the server.</li>
</ul>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">my_file <span class="op">=</span> <span class="bu">open</span>(<span class="st">'myfile.txt'</span>) <span class="co"># open the file</span>
<span class="cf">for</span> line <span class="kw">in</span> my_file:
<span class="bu">print</span>(line) <span class="co"># print each line in the file</span></code></pre></div>
<p>Once you have opened a file, you can use a for loop to iterate through its line (as in the example above). You can also use a while loop, calling the <a href="https://docs.python.org/3.3/tutorial/inputoutput.html#methods-of-file-objects"><code>readline()</code></a> method <em>on</em> the file in order to read a single line at a time.</p>
<p>It is also possible to write out content to a file. To do this, you need to open the file with “write” access (allowing the program to write to and modify it) by passing <code>w</code> as the second argument to the <code>open()</code> function. You can then use the <code>write()</code> method to “print” text to the file:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co"># "open" the file with "write" access</span>
<span class="bu">file</span> <span class="op">=</span> <span class="bu">open</span>(<span class="st">'myfile.txt'</span>, <span class="st">'w'</span>)
<span class="bu">file</span>.write(<span class="st">"Hello world!</span><span class="ch">\n</span><span class="st">"</span>)
<span class="bu">file</span>.write(<span class="st">"It's a mighty fine morning</span><span class="ch">\n</span><span class="st">"</span>)</code></pre></div>
<ul>
<li>Note that unlike the <code>print()</code> function, <code>write()</code> does not include a line break at the end of each method call; you need to add those yourself!</li>
</ul>
<div id="tryexcept" class="section level3">
<h3><span class="header-section-number">5.4.1</span> Try/Except</h3>
<p>File operations rely on a context that is internal to the program itself: namely, that the file you wish to open actually exists at the location you specify! But that may not be the case—particularly if which file to open is specified by the user:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">filename <span class="op">=</span> <span class="bu">input</span>(<span class="st">"File to open: "</span>) <span class="co"># which file to open</span>
<span class="bu">file</span> <span class="op">=</span> <span class="bu">open</span>(filename) <span class="co"># "open" the file</span>
<span class="cf">for</span> line <span class="kw">in</span> <span class="bu">file</span>:
<span class="bu">print</span>(line)</code></pre></div>
<p>If the user provides a bad file name, your program will encounter an error <em>through no fault of your own as a programmer</em>:</p>
<div class="sourceCode"><pre class="sourceCode bash"><code class="sourceCode bash">$ <span class="ex">python</span> script.py
<span class="ex">File</span> to open: neener neener
<span class="ex">Traceback</span> (most recent call last)<span class="bu">:</span>
<span class="ex">File</span> <span class="st">"script.py"</span>, line 4, in <span class="op"><</span>module<span class="op">></span>
<span class="fu">file</span> = open(filename)
<span class="ex">FileNotFoundError</span>: [Errno 2] No such file or directory: <span class="st">'neener neener'</span></code></pre></div>
<p>Since it’s possible for the user to make a mistake, we could like the program not to simply fail with an error, but to instead be able to “recover” and keep running (e.g., by asking the user for a different file name). We can peform this kind of <a href="https://docs.python.org/3/tutorial/errors.html"><strong>error handling</strong></a> by utilizing a <strong><code>try</code></strong> statement with an <strong><code>except</code></strong> clause:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">filename <span class="op">=</span> <span class="bu">input</span>(<span class="st">"File to open: "</span>)
<span class="cf">try</span>: <span class="co"># this might break (not our fault)</span>
<span class="bu">file</span> <span class="op">=</span> <span class="bu">open</span>(filename)
<span class="cf">for</span> line <span class="kw">in</span> <span class="bu">file</span>:
<span class="bu">print</span>(line)
<span class="cf">except</span>: <span class="co"># catching FileNotFoundError</span>
<span class="bu">print</span>(<span class="st">"No such file"</span>)</code></pre></div>
<p>A <code>try</code> statement acts somewhat similar to an <code>if</code> statement; however, the <code>try</code> statement checks to see if any errors occur <em>within its block</em>. If such an error occurs, rather than the program catching, the interpreter will <em>immediately</em> jump to the <code>except</code> class and execute that block, before continuing on with the rest of the program.</p>
<ul>
<li>Note that this is an exception to the general rule that conditions are only checked at the start of a block; a <code>try</code> block effectively tells the computer to keep an eye out for any errors (“try this, but it might break”), with the <code>except</code> clause specifying what to do if such an error occurs.</li>
</ul>
<p><code>try</code> statements are used when a program may hit an error that is <em>not caused by programmer’s code, but by an external input</em> (e.g., from a user or a file). You should not use a <code>try</code> statement to fix broken program logic or invalid syntax: instead, you should fix those problems directly!</p>
</div>
</div>
</div>
</section>
</div>
</div>
</div>
<a href="logic-and-conditionals.html" class="navigation navigation-prev " aria-label="Previous page"><i class="fa fa-angle-left"></i></a>
<a href="lists-and-sequences.html" class="navigation navigation-next " aria-label="Next page""><i class="fa fa-angle-right"></i></a>
<script src="libs/gitbook-2.6.7/js/app.min.js"></script>
<script src="libs/gitbook-2.6.7/js/lunr.js"></script>
<script src="libs/gitbook-2.6.7/js/plugin-search.js"></script>
<script src="libs/gitbook-2.6.7/js/plugin-sharing.js"></script>
<script src="libs/gitbook-2.6.7/js/plugin-fontsettings.js"></script>
<script src="libs/gitbook-2.6.7/js/plugin-bookdown.js"></script>
<script src="libs/gitbook-2.6.7/js/jquery.highlight.js"></script>
<script>
require(["gitbook"], function(gitbook) {
gitbook.start({
"sharing": {
"github": false,
"facebook": true,
"twitter": true,
"google": false,
"weibo": false,
"instapper": false,
"vk": false,
"all": ["facebook", "google", "twitter", "weibo", "instapaper"]
},
"fontsettings": {
"theme": "white",
"family": "sans",
"size": 2
},
"edit": {
"link": "https://github.com/rstudio/bookdown-demo/edit/master/05-iteration.Rmd",
"text": "Edit"
},
"download": ["bookdown-demo.pdf", "bookdown-demo.epub"],
"toc": {
"collapse": "section",
"scroll_highlight": true
}
});
});
</script>
</body>
</html>