100% found this document useful (7 votes)
71 views

Python for Informatics Exploring Information 1st Edition Dr. Charles R Severance 2024 scribd download

Information

Uploaded by

durteruccinf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (7 votes)
71 views

Python for Informatics Exploring Information 1st Edition Dr. Charles R Severance 2024 scribd download

Information

Uploaded by

durteruccinf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

Get ebook downloads in full at ebookname.

com

Python for Informatics Exploring Information 1st


Edition Dr. Charles R Severance

https://ebookname.com/product/python-for-informatics-
exploring-information-1st-edition-dr-charles-r-severance/

OR CLICK BUTTON

DOWNLOAD EBOOK

Explore and download more ebook at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Modernist informatics literature information and the


state 1st Edition Purdon

https://ebookname.com/product/modernist-informatics-literature-
information-and-the-state-1st-edition-purdon/

Exploring with Lewis and Clark Charles Floyd

https://ebookname.com/product/exploring-with-lewis-and-clark-
charles-floyd/

Programming Like a Pro for Teens 1st Edition Charles R.


Hardnett

https://ebookname.com/product/programming-like-a-pro-for-
teens-1st-edition-charles-r-hardnett/

An introduction to derivatives and risk management


Eighth Edition Brooks

https://ebookname.com/product/an-introduction-to-derivatives-and-
risk-management-eighth-edition-brooks/
Java Database Best Practices 1st Edition George Reese

https://ebookname.com/product/java-database-best-practices-1st-
edition-george-reese/

Ownership and Appropriation 1st Edition Veronica Strang


(Editor)

https://ebookname.com/product/ownership-and-appropriation-1st-
edition-veronica-strang-editor/

Radical Self Love A Guide to Loving Yourself Living


Your Dream 1st Edition Gala Darling

https://ebookname.com/product/radical-self-love-a-guide-to-
loving-yourself-living-your-dream-1st-edition-gala-darling/

Beyond Slavery Overcoming Its Religious and Sexual


Legacies 1st Edition Bernadette J. Brooten (Eds.)

https://ebookname.com/product/beyond-slavery-overcoming-its-
religious-and-sexual-legacies-1st-edition-bernadette-j-brooten-
eds/

Attached to Dispossession Sacrificial Narratives in


Post Imperial Europe Sacrificial Narratives in Post
Imperial Europe 1st Edition Vladimir Biti

https://ebookname.com/product/attached-to-dispossession-
sacrificial-narratives-in-post-imperial-europe-sacrificial-
narratives-in-post-imperial-europe-1st-edition-vladimir-biti/
The Non Geometric Lenin Essays on the Development of
the Bolshevik Party 1910 1914 First Edition Carter
Elwood

https://ebookname.com/product/the-non-geometric-lenin-essays-on-
the-development-of-the-bolshevik-party-1910-1914-first-edition-
carter-elwood/
Python for Informatics
Exploring Information

Version 0.0.4

Charles Severance
Copyright © 2009, 2010 Charles Severance.

Printing history:

December 2009: Begin to produce Python for Informatics: Exploring Information by re-mixing
Think Python: How to Think Like a Computer Scientist
June 2008: Major revision, changed title to Think Python: How to Think Like a Computer Scientist.
August 2007: Major revision, changed title to How to Think Like a (Python) Programmer.
April 2002: First edition of How to Think Like a Computer Scientist.

This work is licensed under a Creative Commons Attribution-Share Alike 3.0 Unported License. This
license is available at creativecommons.org/licenses/by-sa/3.0/.

The original form of this book is LATEX source code. Compiling this LATEX source has the effect
of generating a device-independent representation of a textbook, which can be converted to other
formats and printed.

The LATEX source for the Think Python: How to Think Like a Computer Scientist version of this book
is available from http://www.thinkpython.com.

The LATEX source for the Python for Informatics: Exploring Information version of the book is avail-
able from http://source.sakaiproject.org/contrib/csev/trunk/pyinf/.

The cover image shows social connectivity of NSF grant investigators at the University of Michigan
from September 1999 through October 2010 and was provided by Eric Hofer and visualized using
the GUESS software developed by Eytan Adar, both of the University of Michigan. The cover design
is by Terri Geitgey of the University of Michigan Library.
Preface

Python for Informatics: Remixing an Open Book


It is quite natural for academics who are continuously told to “publish or perish” to want
to always create something from scratch that is their own fresh creation. This book is
an experiment in not starting from scratch, but instead “re-mixing” the book titled Think
Python: How to Think Like a Computer Scientist written by Allen B. Downey, Jeff Elkner
and others.
In December of 2009, I was preparing to teach SI502 - Networked Programming at the
University of Michigan for the fifth semester in a row and decided it was time to write a
Python textbook that focused on exploring data instead of understanding algorithms and ab-
stractions. My goal in SI502 is to teach people life-long data handling skills using Python.
Few of my students were planning to be be professional computer programmers. Instead,
they planned be librarians, managers, lawyers, biologists, economists, etc. who happened
to want to skillfully use technology in their chosen field.
I never seemed to find the perfect data-oriented Python book for my course so I set out
to write just such a book. Luckily at a faculty meeting three weeks before I was about to
start my new book from scratch over the holiday break, Dr. Atul Prakash showed me the
Think Python book which he had used to teach his Python course that semester. It is a
well-written Computer Science text with a focus on short, direct explanations and ease of
learning.
The overall book structure has been changed to get to doing data analysis problems as
quickly as possible and have a series of running examples and exercises about data analysis
from the very beginning.
The first 10 chapters are similar to the Think Python book but there have been some
changes. Nearly all number-oriented exercises have been replaced with data-oriented ex-
erises. Topics are presented in the order to needed to build increasingly sophisticated data
analysis solutions. Some topics like try and catch are pulled forward and presented as
part of the chapter on conditionals while other concepts like functions are left until they are
needed to handle program complexity rather introduced as an early lesson in abstraction.
The word “recursion” does not appear in the book at all.
vi Chapter 0. Preface

In chapters 11-14, nearly all of the material is brand new, focusing on real-world uses and
simple examples of Python for data analysis including automating tasks on your computer,
retrieving data across the network, scraping web pages for data, using web services, parsing
XML data, and creating and using databases using Structured Query Language.

The ultimate goal of all of these changes is a shift from a Computer Science to an Infor-
matics focus is to only include topics into a first technology class that can be applied even
if one chooses not to become a professional programmer.

Students who find this book interesting and want to further explore should look at Allen
B. Downey’s Think Python book. Because there is a lot of overlap between the two books,
students will quickly pick up skills in the additional areas of computing in general and
computational thinking that are covered in Think Python. And given that the books have a
similar writing style and at times have identical text and examples, you should be able to
move quickly through Think Python with a minimum of effort.

As the copyright holder of Think Python, Allen has given me permission to change the
book’s license from the GNU Free Documentation License to the more recent Creative
Commons Attribution — Share Alike license. This follows a general shift in open doc-
umentation licenses moving from the GFDL to the CC-BY-SA (i.e. Wikipedia). Using
the CC-BY-SA license maintains the book’s strong copyleft tradition while making it even
more straightforward for new authors to reuse this material as they see fit.

I feel that this book serves an example of why open materials are so important to the future
of education, and want to thank Allen B. Downey and Cambridge University Press for their
forward looking decision to make the book available under an open Copyright. I hope they
are pleased with the results of my efforts and I hope that you the reader are pleased with
our collective efforts.

Charles Severance
www.dr-chuck.com
Ann Arbor, MI, USA
July 25, 2011

Charles Severance is a Clinical Associate Professor at the University of Michigan School


of Information.

Preface for “Think Python”


The strange history of “Think Python”
(Allen B. Downey)

In January 1999 I was preparing to teach an introductory programming class in Java. I had
taught it three times and I was getting frustrated. The failure rate in the class was too high
and, even for students who succeeded, the overall level of achievement was too low.
vii

One of the problems I saw was the books. They were too big, with too much unnecessary
detail about Java, and not enough high-level guidance about how to program. And they all
suffered from the trap door effect: they would start out easy, proceed gradually, and then
somewhere around Chapter 5 the bottom would fall out. The students would get too much
new material, too fast, and I would spend the rest of the semester picking up the pieces.
Two weeks before the first day of classes, I decided to write my own book. My goals were:

• Keep it short. It is better for students to read 10 pages than not read 50 pages.

• Be careful with vocabulary. I tried to minimize the jargon and define each term at
first use.

• Build gradually. To avoid trap doors, I took the most difficult topics and split them
into a series of small steps.

• Focus on programming, not the programming language. I included the minimum


useful subset of Java and left out the rest.

I needed a title, so on a whim I chose How to Think Like a Computer Scientist.


My first version was rough, but it worked. Students did the reading, and they understood
enough that I could spend class time on the hard topics, the interesting topics and (most
important) letting the students practice.
I released the book under the GNU Free Documentation License, which allows users to
copy, modify, and distribute the book.
What happened next is the cool part. Jeff Elkner, a high school teacher in Virginia, adopted
my book and translated it into Python. He sent me a copy of his translation, and I had the
unusual experience of learning Python by reading my own book.
Jeff and I revised the book, incorporated a case study by Chris Meyers, and in 2001 we
released How to Think Like a Computer Scientist: Learning with Python, also under the
GNU Free Documentation License. As Green Tea Press, I published the book and started
selling hard copies through Amazon.com and college book stores. Other books from Green
Tea Press are available at greenteapress.com.
In 2003 I started teaching at Olin College and I got to teach Python for the first time. The
contrast with Java was striking. Students struggled less, learned more, worked on more
interesting projects, and generally had a lot more fun.
Over the last five years I have continued to develop the book, correcting errors, improving
some of the examples and adding material, especially exercises. In 2008 I started work on
a major revision—at the same time, I was contacted by an editor at Cambridge University
Press who was interested in publishing the next edition. Good timing!
I hope you enjoy working with this book, and that it helps you learn to program and think,
at least a little bit, like a computer scientist.
viii Chapter 0. Preface

Acknowledgements for “Think Python”


(Allen B. Downey)
First and most importantly, I thank Jeff Elkner, who translated my Java book into Python,
which got this project started and introduced me to what has turned out to be my favorite
language.
I also thank Chris Meyers, who contributed several sections to How to Think Like a Com-
puter Scientist.
And I thank the Free Software Foundation for developing the GNU Free Documentation
License, which helped make my collaboration with Jeff and Chris possible.
I also thank the editors at Lulu who worked on How to Think Like a Computer Scientist.
I thank all the students who worked with earlier versions of this book and all the contribu-
tors (listed in an Appendix) who sent in corrections and suggestions.
And I thank my wife, Lisa, for her work on this book, and Green Tea Press, and everything
else, too.
Allen B. Downey
Needham MA

Allen Downey is an Associate Professor of Computer Science at the Franklin W. Olin


College of Engineering.
Contents

Preface v

1 Why should you learn to write programs? 1


1.1 Creativity and motivation . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 Computer hardware architecture . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Understanding programming . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 The Python programming language . . . . . . . . . . . . . . . . . . . . . 5
1.5 What is a program? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.6 What is debugging? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.7 Building “sentences” in Python . . . . . . . . . . . . . . . . . . . . . . . 9
1.8 The first program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.9 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.10 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

2 Variables, expressions and statements 15


2.1 Values and types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.2 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.3 Variable names and keywords . . . . . . . . . . . . . . . . . . . . . . . . 17
2.4 Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.5 Operators and operands . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
x Contents

2.6 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.7 Order of operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.8 Modulus operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.9 String operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.10 Asking the user for input . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.11 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.12 Choosing mnemonic variable names . . . . . . . . . . . . . . . . . . . . 23
2.13 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.14 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.15 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

3 Conditional execution 29
3.1 Boolean expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.2 Logical operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.3 Conditional execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.4 Alternative execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.5 Chained conditionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.6 Nested conditionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.7 Catching exceptions using try and except . . . . . . . . . . . . . . . . . . 34
3.8 Short circuit evaluation of logical expressions . . . . . . . . . . . . . . . 35
3.9 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.10 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
3.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

4 Functions 41
4.1 Function calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.2 Built-in functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.3 Type conversion functions . . . . . . . . . . . . . . . . . . . . . . . . . 42
4.4 Random numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Contents xi

4.5 Math functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44


4.6 Adding new functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.7 Definitions and uses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
4.8 Flow of execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
4.9 Parameters and arguments . . . . . . . . . . . . . . . . . . . . . . . . . 48
4.10 Fruitful functions and void functions . . . . . . . . . . . . . . . . . . . . 49
4.11 Why functions? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
4.12 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
4.13 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
4.14 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

5 Iteration 55
5.1 Updating variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
5.2 The while statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
5.3 Infinite loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
5.4 “Infinite loops” and break . . . . . . . . . . . . . . . . . . . . . . . . . 58
5.5 Finishing iterations with continue . . . . . . . . . . . . . . . . . . . . . 59
5.6 Definite loops using for . . . . . . . . . . . . . . . . . . . . . . . . . . 59
5.7 Loop patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
5.8 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
5.9 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
5.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

6 Strings 65
6.1 A string is a sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
6.2 Getting the length of a string using len . . . . . . . . . . . . . . . . . . . 66
6.3 Traversal through a string with a for loop . . . . . . . . . . . . . . . . . 66
6.4 String slices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
6.5 Strings are immutable . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
xii Contents

6.6 Searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
6.7 Looping and counting . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
6.8 The in operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
6.9 String comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
6.10 string methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
6.11 Parsing strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
6.12 Format operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
6.13 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
6.14 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
6.15 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

7 Files 81
7.1 Persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
7.2 Opening files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
7.3 Text files and lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
7.4 Reading files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
7.5 Searching through a file . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
7.6 Letting the user choose the file name . . . . . . . . . . . . . . . . . . . . 87
7.7 Using try, catch, and open . . . . . . . . . . . . . . . . . . . . . . . 88
7.8 Writing files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
7.9 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
7.10 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
7.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

8 Lists 93
8.1 A list is a sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
8.2 Lists are mutable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
8.3 Traversing a list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
8.4 List operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Contents xiii

8.5 List slices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96


8.6 List methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
8.7 Deleting elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
8.8 Lists and strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
8.9 Parsing lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
8.10 Objects and values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
8.11 Aliasing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
8.12 List arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
8.13 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
8.14 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
8.15 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107

9 Dictionaries 109
9.1 Dictionary as a set of counters . . . . . . . . . . . . . . . . . . . . . . . 111
9.2 Dictionaries and files . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
9.3 Looping and dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . 113
9.4 Advanced text parsing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
9.5 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
9.6 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
9.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

10 Tuples 119
10.1 Tuples are immutable . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
10.2 Comparing tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
10.3 Tuple assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
10.4 Dictionaries and tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
10.5 Multiple assignment with dictionaries . . . . . . . . . . . . . . . . . . . 123
10.6 The most common words . . . . . . . . . . . . . . . . . . . . . . . . . . 124
10.7 Using tuples as keys in dictionaries . . . . . . . . . . . . . . . . . . . . . 126
xiv Contents

10.8 Sequences: strings, lists, and tuples–Oh My! . . . . . . . . . . . . . . . . 127


10.9 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
10.10 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
10.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129

11 Automating common tasks on your computer 131


11.1 File names and paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
11.2 Example: Cleaning up a photo directory . . . . . . . . . . . . . . . . . . 132
11.3 Command line arguments . . . . . . . . . . . . . . . . . . . . . . . . . . 138
11.4 Pipes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
11.5 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
11.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141

12 Networked programs 143


12.1 HyperText Transport Protocol - HTTP . . . . . . . . . . . . . . . . . . . 143
12.2 The World’s Simplest Web Browser . . . . . . . . . . . . . . . . . . . . 144
12.3 Retrieving web pages with urllib . . . . . . . . . . . . . . . . . . . . . 146
12.4 Parsing HTML and scraping the web . . . . . . . . . . . . . . . . . . . . 146
12.5 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
12.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149

13 Using Web Services 151


13.1 eXtensible Markup Language - XML . . . . . . . . . . . . . . . . . . . . 151
13.2 Parsing XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
13.3 Looping through nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
13.4 Application Programming Interfaces (API) . . . . . . . . . . . . . . . . . 154
13.5 Twitter web services . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
13.6 Handling XML data from an API . . . . . . . . . . . . . . . . . . . . . . 157
13.7 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
13.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Contents xv

14 Using databases and Structured Query Language (SQL) 161


14.1 What is a database? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
14.2 Database concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
14.3 SQLite Database Browser . . . . . . . . . . . . . . . . . . . . . . . . . . 162
14.4 Creating a database table . . . . . . . . . . . . . . . . . . . . . . . . . . 163
14.5 Structured Query Language (SQL) summary . . . . . . . . . . . . . . . . 166
14.6 Spidering Twitter using a database . . . . . . . . . . . . . . . . . . . . . 167
14.7 Basic data modeling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
14.8 Programming with multiple tables . . . . . . . . . . . . . . . . . . . . . 175
14.9 Three kinds of keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
14.10 Using JOIN to retrieve data . . . . . . . . . . . . . . . . . . . . . . . . . 181
14.11 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
14.12 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
14.13 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
14.14 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185

A Debugging 187
A.1 Syntax errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
A.2 Runtime errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
A.3 Semantic errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192

B Contributor List 195


xvi Contents
Chapter 1

Why should you learn to write


programs?

Writing programs (or programming) is a very creative and rewarding activity. You can
write programs for many reasons ranging from making your living to solving a difficult
data analysis problem to having fun to helping someone else solve a problem. This book
assumes that everyone needs to know how to program and that once you know how to
program, you will figure out what you want to do with your newfound skills.
We are surrounded in our daily lives with computers ranging from laptops to cell phones.
We can think of these computers as our “personal assistants” who can take care of many
things on our behalf. The hardware in our current-day computers is essentially built to
continuously ask us the question, “What would you like me to do next?”.

What What What


Next? Next? Next?

What What What


PDA
Next? Next? Next?

Programmers add an operating system and a set of applications to the hardware and we
end up with a Personal Digital Assistant that is quite helpful and capable of helping many
different things.
Our computers are fast and have vast amounts of memory and could be very helpful to us
if we only knew the language to speak to explain to the computer what we would like it to
“do next”. If we knew this language we could tell the computer to do tasks on our behalf
that were repetitive. Interestingly, the kinds of things computers can do best are often the
kinds of things that we humans find boring and mind-numbing.
2 Chapter 1. Why should you learn to write programs?

For example, look at the first three paragraphs of this chapter and tell me the most com-
monly used word and how many times the word is used. While you were able to read and
understand the words in a few seconds, counting them is almost painful because it is not
the kind of problem that human minds are designed to solve. For a computer the opposite
is true, reading and understanding text from a piece of paper is hard for a computer to do
but counting the words and telling you how many times the most used word was used is
very easy for the computer:

python words.py
Enter file:words.txt
to 16

Our “personal information analysis assistant” quickly told us that the word “to” was used
sixteen times in the first three paragraphs of this chapter.

This very fact that computers are good at things that humans are not is why you need to
become skilled at talking “computer language”. Once you learn this new language, you can
delegate mundane tasks to your partner (the computer), leaving more time for you to do the
things that you are uniquely suited for. You bring creativity, intuition, and inventiveness to
this partnership.

1.1 Creativity and motivation


While this book is not intended for professional programmers, professional programming
can be a very rewarding job both financially and personally. Building useful, elegant, and
clever programs for others to use is a very creative activity. Your computer or Personal
Digital Assistant (PDA) usually contains many different programs from many different
groups of programmers, each competing for your attention and interest. They try their best
to meet your needs and give you a great user experience in the process. In some situations,
when you choose a piece of software, the programmers are directly compensated because
of your choice.

If we think of programs as the creative output of groups of programmers, perhaps the


following figure is a more sensible version of our PDA:

Pick Pick Pick


Me! Me! Me!

Pick Pick Buy


PDA
Me! Me! Me :)

For now, our primary motivation is not to make money or please end-users, but instead
for us to be more productive in handling the data and information that we will encounter
in our lives. When you first start, you will be both the programmer and end-user of your
1.2. Computer hardware architecture 3

programs. As you gain skill as a programmer and programming feels more creative to you,
your thoughts may turn toward developing programs for others.

1.2 Computer hardware architecture


Before we start learning the language we speak to give instructions to computers to develop
software, we need to learn a small amount about how computers are built. If you were to
take apart your computer or cell phone and look deep inside, you would find the following
parts:

What
Software Next?

Central
Input Processing
Output Network
Unit
Devices

Main
Secondary
Memory
Memory

The high-level definitions of these parts are as follows:

• The Central Processing Unit (or CPU) is that part of the computer that is built to be
obsessed with “what is next?”. If your computer is rated at 3.0 Gigahertz, it means
that the CPU will ask “What next?” three billion times per second. You are going to
have to learn how to talk fast to keep up with the CPU.
• The Main Memory is used to store information that the CPU needs in a hurry. The
main memory is nearly as fast as the CPU. But the information stored in the main
memory vanishes when the computer is turned off.
• The Secondary Memory is also used to store information, but it is much slower
than the main memory. The advantage of the secondary memory is that it can store
information even when there is no power to the computer. Examples of secondary
memory are disk drives or flash memory (typically found in USB sticks and portable
music players).
• The Input and Output Devices are simply our screen, keyboard, mouse, micro-
phone, speaker, touchpad, etc. They are all of the ways we interact with the com-
puter.
4 Chapter 1. Why should you learn to write programs?

• These days, most computers also have a Network Connection to retrieve informa-
tion over a network. We can think of the network as a very slow place to store and
retrieve data that might not always be “up”. So in a sense, the network is a slower
and at times unreliable form of Secondary Memory

While most of the detail of how these components work is best left to computer builders, it
helps to have a some terminology so we can talk about these different parts as we write our
programs.

As a programmer, your job is to use and orchestrate each of these resources to solve the
problem that you need solving and analyze the data you need. As a programmer you will
mostly be “talking” to the CPU and telling it what to do next. Sometimes you will tell the
CPU to use the main memory, secondary memory, network, or the input/output devices.

What
Software Next?

Central
Input Processing
Output Network
Unit
Devices

Main
Secondary
Memory
Memory
You

You need to be the person who answers the CPU’s “What next?” question. But it would be
very uncomfortable to shrink you down to 5mm tall and insert you into the computer just
so you could issue a command three billion times per second. So instead, you must write
down your instructions in advance. We call these stored instructions a program and the act
of writing these instructions down and getting the instructions to be correct programming.

1.3 Understanding programming


In the rest of this book, we will try to turn you into a person who is skilled in the art
of programming. In the end you will be a programmer — perhaps not a professional
programmer but at least you will have the skills to look at a data/information analysis
problem and develop a program to solve the problem.

In a sense, you need two skills to be a programmer:


1.4. The Python programming language 5

• First you need to know the programming language (Python) - you need to know the
vocabulary and the grammar. You need to be able spell the words in this new lan-
guage properly and how to construct well-formed “sentences” in this new languages.
• Second you need to “tell a story”. In writing a story, you combine words and sen-
tences to convey an idea to the reader. There is a skill and art in constructing the story
and skill in story writing is improved by doing some writing and getting some feed-
back. In programming, our program is the “story” and the problem you are trying to
solve is the “idea”.

Once you learn one programming language such as Python, you will find it much easier to
learn a second programming language such as JavaScript or C++. The new programming
language has very different vocabulary and grammar but once you learn problem solving
skills, they will be the same across all programming languages.
You will learn the “vocabulary” and “sentences” of Python pretty quickly. It will take
longer for you to be able to write a coherent program to solve a brand new problem. We
teach programming much like we teach writing. We start reading and explaining programs
and then we write simple programs and then write increasingly complex programs over
time. At some point you “get your muse” and see the patterns on your own and can see
more naturally how to take a problem and write a program that solves that problem. And
once you get to that point, programming becomes a very pleasant and creative process.
We start with the vocabulary and structure of Python programs. Be patient as the simple
examples remind you of when you started reading for the first time.

1.4 The Python programming language


The programming language you will learn is Python. Python is an example of a high-level
language; some other high-level languages you might have heard of are C, C++, Perl, Java,
Ruby, and JavaScript.
There are also low-level languages, sometimes referred to as “machine languages” or “as-
sembly languages.” Loosely speaking, computers can only execute programs written in
low-level languages. So programs written in a high-level language have to be processed
before they can run. This extra processing takes some time, which is a small disadvantage
of high-level languages.
However, the advantages are enormous. First, it is much easier to program in a high-level
language. Programs written in a high-level language take less time to write, they are shorter
and easier to read, and they are more likely to be correct. Second, high-level languages
are portable, meaning that they can run on different kinds of computers with few or no
modifications. Low-level programs can run on only one kind of computer and have to be
rewritten to run on another.
Due to these advantages, almost all programs are written in high-level languages. Low-
level languages are used only for a few specialized applications.
6 Chapter 1. Why should you learn to write programs?

Two kinds of programs process high-level languages into low-level languages: inter-
preters and compilers. An interpreter reads a high-level program and executes it, meaning
that it does what the program says. It processes the program a little at a time, alternately
reading lines and performing computations.

SOURCE INTERPRETER OUTPUT


CODE

A compiler reads the program and translates it completely before the program starts run-
ning. In this context, the high-level program is called the source code, and the translated
program is called the object code, machine code or the executable. Once a program is
compiled, you can execute it repeatedly without further translation.

SOURCE COMPILER OBJECT OUTPUT


EXECUTOR
CODE CODE

Python is considered an interpreted language because Python programs are executed by an


interpreter. There are two ways to use the interpreter: interactive mode and script mode.
To start interactive mode, you have to run the Python interpreter program. In a UNIX or
Windows command window, you would type python to run the Python interpreter.
In interactive mode, you type Python programs and the interpreter prints the result:

>>> 1 + 1
2
>>>

The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready. If you type
1 + 1, the interpreter replies 2. The chevron is the Python interpreter’s way of asking you,
“What do you want me to do next?”. You will notice that as soon as Python finishes one
statement it immediately is ready for you to type another statement.
Typing commands into the Python interpreter is a great way to experiment with Python’s
features, but it is a bad way to type in many commands to solve a more complex problem.
When we want to write a program, we use a text editor to write the Python instructions into
a file, which is called a script. By convention, Python scripts have names that end with
.py.
To execute the script, you have to tell the interpreter the name of the file. In a UNIX or
Windows command window, you would type python dinsdale.py. In other development
environments, the details of executing scripts are different. You can find instructions for
your environment at the Python Website python.org.
1.5. What is a program? 7

Working in interactive mode is convenient for testing small pieces of code because you can
type and execute them immediately. But for anything more than a few lines, you should
save your code as a script so you can modify and execute it in the future.

1.5 What is a program?


A program is a sequence of instructions that specifies how to perform a computation.
The computation might be something mathematical, such as solving a system of equations
or finding the roots of a polynomial, but it can also be a symbolic computation, such as
searching and replacing text in a document or (strangely enough) compiling a program.

The details look different in different languages, but a few basic instructions appear in just
about every language:

input: Get data from the keyboard, a file, or some other device, pausing if necessary.

output: Display data on the screen or send data to a file or other device.

sequential execution: Perform statements one after another in the order they are encoun-
tered in the script.

conditional execution: Check for certain conditions and execute or skip a sequence of
statements.

repeated execution: Perform some set of statements repeatedly, usually with some varia-
tion.

reuse: Write a set of instructions once and give them a name and then reuse those instruc-
tions as needed throughout your program.

Believe it or not, that’s pretty much all there is to it. Every program you’ve ever used, no
matter how complicated, is made up of instructions that look pretty much like these. So you
can think of programming as the process of breaking a large, complex task into smaller and
smaller subtasks until the subtasks are simple enough to be performed with one of these
basic instructions.

1.6 What is debugging?


Programming is error-prone. For whimsical reasons, programming errors are called bugs
and the process of tracking them down is called debugging.

Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic
errors. It is useful to distinguish between them in order to track them down more quickly.
8 Chapter 1. Why should you learn to write programs?

1.6.1 Syntax errors


Python can only execute a program if the syntax is correct; otherwise, the interpreter dis-
plays an error message. Syntax refers to the structure of a program and the rules about that
structure. For example, parentheses have to come in matching pairs, so (1 + 2) is legal,
but 8) is a syntax error.
In English readers can tolerate most syntax errors, which is why we can read certain abstract
poetry. Python is not so forgiving. If there is a single syntax error anywhere in your
program, Python will display an error message and quit, and you will not be able to run
your program. During the first few weeks of your programming career, you will probably
spend a lot of time tracking down syntax errors. As you gain experience, you will make
fewer errors and find them faster.

1.6.2 Runtime errors


The second type of error is a runtime error, so called because the error does not appear until
after the program has started running. These errors are also called exceptions because they
usually indicate that something exceptional (and bad) has happened.
Runtime errors are rare in the simple programs you will see in the first few chapters, so it
might be a while before you encounter one.

1.6.3 Semantic errors


The third type of error is the semantic error. If there is a semantic error in your program,
it will run successfully in the sense that the computer will not generate any error messages,
but it will not do the right thing. It will do something else. Specifically, it will do what you
told it to do but not what you meant for it to do.
The problem is that the program you wrote is not the program you wanted to write. The
meaning of the program (its semantics) is wrong. Identifying semantic errors can be tricky
because it requires you to work backward by looking at the output of the program and
trying to figure out what it is doing.

1.6.4 Experimental debugging


One of the most important skills you will acquire is debugging. Although it can be frus-
trating, debugging is one of the most intellectually rich, challenging, and interesting parts
of programming.
In some ways, debugging is like detective work. You are confronted with clues, and you
have to infer the processes and events that led to the results you see.
Debugging is also like an experimental science. Once you have an idea about what is going
wrong, you modify your program and try again. If your hypothesis was correct, then you
1.7. Building “sentences” in Python 9

can predict the result of the modification, and you take a step closer to a working program.
If your hypothesis was wrong, you have to come up with a new one. As Sherlock Holmes
pointed out, “When you have eliminated the impossible, whatever remains, however im-
probable, must be the truth.” (A. Conan Doyle, The Sign of Four)
For some people, programming and debugging are the same thing. That is, programming
is the process of gradually debugging a program until it does what you want. The idea is
that you should start with a program that does something and make small modifications,
debugging them as you go, so that you always have a working program.
For example, Linux is an operating system that contains thousands of lines of code, but it
started out as a simple program Linus Torvalds used to explore the Intel 80386 chip. Ac-
cording to Larry Greenfield, “One of Linus’s earlier projects was a program that would
switch between printing AAAA and BBBB. This later evolved to Linux.” (The Linux
Users’ Guide Beta Version 1).
Later chapters will make more suggestions about debugging and other programming prac-
tices.

1.7 Building “sentences” in Python


The rules (or grammar) of Python are simpler and more precise than the rules of a natural
language that we use to speak and write.
Natural languages are the languages people speak, such as English, Spanish, and French.
They were not designed by people (although people try to impose some order on them);
they evolved naturally.
Formal languages are languages that are designed by people for specific applications. For
example, the notation that mathematicians use is a formal language that is particularly good
at denoting relationships among numbers and symbols. Chemists use a formal language to
represent the chemical structure of molecules. And most importantly:

Programming languages are formal languages that have been designed to


express computations.

Formal languages tend to have strict rules about syntax. For example, 3 + 3 = 6 is a syntac-
tically correct mathematical statement, but 3 + +3@6 is not. H2 O is a syntactically correct
chemical formula, but 2 Zz is not.
Syntax rules come in two flavors, pertaining to tokens and structure. Tokens are the basic
elements of the language, such as words, numbers, and chemical elements. One of the
problems with 3 + +3@6 is that @ is not a legal token in mathematics (at least as far as I
know). Similarly, 2 Zz is not legal because there is no element with the abbreviation Zz.
The second type of syntax error pertains to the structure of a statement; that is, the way the
tokens are arranged. The statement 3 + +3@6 is illegal because even though + is a legal
10 Chapter 1. Why should you learn to write programs?

token and you can have more than one plus in an exression, you cannot have one right after
another. Similarly, in a chemical formula the subscript comes after the element name, not
before.

Exercise 1.1 Write a well-structured English sentence with invalid tokens in it. Then write
another sentence with all valid tokens but with invalid structure.

When you read a sentence in English or a statement in a formal language, you have to
figure out what the structure of the sentence is (although in a natural language you do this
subconsciously). This process is called parsing.
For example, when you hear the sentence, “The penny dropped,” you understand that “the
penny” is the subject and “dropped” is the predicate. Once you have parsed a sentence, you
can figure out what it means, or the semantics of the sentence. Assuming that you know
what a penny is and what it means to drop, you will understand the general implication of
this sentence.
Although formal and natural languages have many features in common—tokens, structure,
syntax, and semantics—there are some differences:

ambiguity: Natural languages are full of ambiguity, which people deal with by using con-
textual clues and other information. Formal languages are designed to be nearly or
completely unambiguous, which means that any statement has exactly one meaning,
regardless of context.
redundancy: In order to make up for ambiguity and reduce misunderstandings, natural
languages employ lots of redundancy. As a result, they are often verbose. Formal
languages are less redundant and more concise.
literalness: Natural languages are full of idiom and metaphor. If I say, “The penny
dropped,” there is probably no penny and nothing dropping1 . Formal languages mean
exactly what they say.

People who grow up speaking a natural language—everyone—often have a hard time ad-
justing to formal languages. In some ways, the difference between formal and natural
language is like the difference between poetry and prose, but more so:

Poetry: Words are used for their sounds as well as for their meaning, and the whole poem
together creates an effect or emotional response. Ambiguity is not only common but
often deliberate.
Prose: The literal meaning of words is more important, and the structure contributes more
meaning. Prose is more amenable to analysis than poetry but still often ambiguous.
Programs: The meaning of a computer program is unambiguous and literal, and can be
understood entirely by analysis of the tokens and structure.
1 This idiom means that someone realized something after a period of confusion.
1.8. The first program 11

Here are some suggestions for reading programs (and other formal languages). First, re-
member that formal languages are much more dense than natural languages, so it takes
longer to read them. Also, the structure is very important, so it is usually not a good idea
to read from top to bottom, left to right. Instead, learn to parse the program in your head,
identifying the tokens and interpreting the structure. Finally, the details matter. Small er-
rors in spelling and punctuation, which you can get away with in natural languages, can
make a big difference in a formal language.

1.8 The first program


Traditionally, the first program you write in a new language is called “Hello, World!” be-
cause all it does is display the words, “Hello, World!” In Python, it looks like this:

print 'Hello, World!'

This is an example of a print statement2 , which doesn’t actually print anything on paper.
It displays a value on the screen. In this case, the result is the words

Hello, World!

The quotation marks in the program mark the beginning and end of the text to be displayed;
they don’t appear in the result.

Some people judge the quality of a programming language by the simplicity of the “Hello,
World!” program. By this standard, Python does about as well as possible.

1.9 Debugging
It is a good idea to read this book in front of a computer so you can try out the examples as
you go. You can run most of the examples in interactive mode, but if you put the code into
a script, it is easier to try out variations.

Whenever you are experimenting with a new feature, you should try to make mistakes.
For example, in the “Hello, world!” program, what happens if you leave out one of the
quotation marks? What if you leave out both? What if you spell print wrong?

This kind of experiment helps you remember what you read; it also helps with debugging,
because you get to know what the error messages mean. It is better to make mistakes now
and on purpose than later and accidentally.

Programming, and especially debugging, sometimes brings out strong emotions. If you are
struggling with a difficult bug, you might feel angry, despondent or embarrassed.
2 In Python 3.0, print is a function, not a statement, so the syntax is print(’Hello, World!’). We will get

to functions soon!
12 Chapter 1. Why should you learn to write programs?

There is evidence that people naturally respond to computers as if they were people3 . When
they work well, we think of them as teammates, and when they are obstinate or rude, we
respond to them the same way we respond to rude, obstinate people.

Preparing for these reactions might help you deal with them. One approach is to think of
the computer as an employee with certain strengths, like speed and precision, and particular
weaknesses, like lack of empathy and inability to grasp the big picture.

Your job is to be a good manager: find ways to take advantage of the strengths and mitigate
the weaknesses. And find ways to use your emotions to engage with the problem, without
letting your reactions interfere with your ability to work effectively.

Learning to debug can be frustrating, but it is a valuable skill that is useful for many activi-
ties beyond programming. At the end of each chapter there is a debugging section, like this
one, with my thoughts about debugging. I hope they help!

1.10 Glossary
central processing unit: The heart of any computer. It is what runs the software that we
write; also called “CPU” or “the processor”.

main memory: Stores programs and data. Main memory loses its information when the
power is turned off.

secondary memory: Stores programs and data and retains its information even when the
power is turned off. Generally slower than main memory. Examples of secondary
memory include disk drives and flash member in USB sticks.

problem solving: The process of formulating a problem, finding a solution, and express-
ing the solution.

high-level language: A programming language like Python that is designed to be easy for
humans to read and write.

low-level language: A programming language that is designed to be easy for a computer


to execute; also called “machine code” or “assembly language.”

machine code: The lowest level language for software which is the language that is di-
rectly executed by the central processing unit (CPU).

portability: A property of a program that can run on more than one kind of computer.

interpret: To execute a program in a high-level language by translating it one line at a


time.
3 See Reeves and Nass, The Media Equation: How People Treat Computers, Television, and New Media Like

Real People and Places.


1.10. Glossary 13

compile: To translate a program written in a high-level language into a low-level language


all at once, in preparation for later execution.
source code: A program in a high-level language before being compiled.

object code: The output of the compiler after it translates the program.
executable: Another name for object code that is ready to be executed.
prompt: Characters displayed by the interpreter to indicate that it is ready to take input
from the user.
script: A program stored in a file (usually one that will be interpreted).

interactive mode: A way of using the Python interpreter by typing commands and expres-
sions at the prompt.
script mode: A way of using the Python interpreter to read and execute statements in a
script.
program: A set of instructions that specifies a computation.

bug: An error in a program.


debugging: The process of finding and removing any of the three kinds of programming
errors.

syntax: The structure of a program.


syntax error: An error in a program that makes it impossible to parse (and therefore im-
possible to interpret).
exception: An error that is detected while the program is running.
semantics: The meaning of a program.

semantic error: An error in a program that makes it do something other than what the
programmer intended.

natural language: Any one of the languages that people speak that evolved naturally.
formal language: Any one of the languages that people have designed for specific pur-
poses, such as representing mathematical ideas or computer programs; all program-
ming languages are formal languages.
token: One of the basic elements of the syntactic structure of a program, analogous to a
word in a natural language.

parse: To examine a program and analyze the syntactic structure.


print statement: An instruction that causes the Python interpreter to display a value on
the screen.
14 Chapter 1. Why should you learn to write programs?

1.11 Exercises
Exercise 1.2 Use a web browser to go to the Python Website python.org. This page
contains information about Python and links to Python-related pages, and it gives you the
ability to search the Python documentation.
For example, if you enter print in the search window, the first link that appears is the
documentation of the print statement. At this point, not all of it will make sense to you,
but it is good to know where it is.

Exercise 1.3 Start the Python interpreter and type help() to start the online help utility.
Or you can type help('print') to get information about the print statement.
If this example doesn’t work, you may need to install additional Python documentation or
set an environment variable; the details depend on your operating system and version of
Python.

Exercise 1.4 Start the Python interpreter and use it as a calculator. Python’s syntax for
math operations is almost the same as standard mathematical notation. For example, the
symbols +, - and / denote addition, subtraction and division, as you would expect. The
symbol for multiplication is *.
If you run a 10 kilometer race in 43 minutes 30 seconds, what is your average time per
mile? What is your average speed in miles per hour? (Hint: there are 1.61 kilometers in a
mile).
Chapter 2

Variables, expressions and


statements

2.1 Values and types


A value is one of the basic things a program works with, like a letter or a number. The
values we have seen so far are 1, 2, and 'Hello, World!'.

These values belong to different types: 2 is an integer, and 'Hello, World!' is a string,
so-called because it contains a “string” of letters. You (and the interpreter) can identify
strings because they are enclosed in quotation marks.

The print statement also works for integers. We use the python command to start the
interpreter.

python
>>> print 4
4

If you are not sure what type a value has, the interpreter can tell you.

>>> type('Hello, World!')


<type 'str'>
>>> type(17)
<type 'int'>

Not surprisingly, strings belong to the type str and integers belong to the type int. Less
obviously, numbers with a decimal point belong to a type called float, because these
numbers are represented in a format called floating-point.
16 Chapter 2. Variables, expressions and statements

>>> type(3.2)
<type 'float'>

What about values like '17' and '3.2'? They look like numbers, but they are in quotation
marks like strings.

>>> type('17')
<type 'str'>
>>> type('3.2')
<type 'str'>

They’re strings.

When you type a large integer, you might be tempted to use commas between groups of
three digits, as in 1,000,000. This is not a legal integer in Python, but it is legal:

>>> print 1,000,000


1 0 0

Well, that’s not what we expected at all! Python interprets 1,000,000 as a comma-
separated sequence of integers, which it prints with spaces between.

This is the first example we have seen of a semantic error: the code runs without producing
an error message, but it doesn’t do the “right” thing.

2.2 Variables
One of the most powerful features of a programming language is the ability to manipulate
variables. A variable is a name that refers to a value.

An assignment statement creates new variables and gives them values:

>>> message = 'And now for something completely different'


>>> n = 17
>>> pi = 3.1415926535897931

This example makes three assignments. The first assigns a string to a new variable named
message; the second assigns the integer 17 to n; the third assigns the (approximate) value
of π to pi.

A common way to represent variables on paper is to write the name with an arrow pointing
to the variable’s value. This kind of figure is called a state diagram because it shows what
state each of the variables is in (think of it as the variable’s state of mind). This diagram
shows the result of the previous example:
2.3. Variable names and keywords 17

message ’And now for something completely different’


n 17
pi 3.1415926535897931

To display the value of a variable, you can use a print statement:


>>> print n
17
>>> print pi
3.14159265359
The type of a variable is the type of the value it refers to.
>>> type(message)
<type 'str'>
>>> type(n)
<type 'int'>
>>> type(pi)
<type 'float'>

2.3 Variable names and keywords


Programmers generally choose names for their variables that are meaningful—they docu-
ment what the variable is used for.
Variable names can be arbitrarily long. They can contain both letters and numbers, but they
have to begin with a letter. It is legal to use uppercase letters, but it is a good idea to begin
variable names with a lowercase letter (you’ll see why later).
The underscore character (_) can appear in a name. It is often used in names with multiple
words, such as my_name or airspeed_of_unladen_swallow.
If you give a variable an illegal name, you get a syntax error:
>>> 76trombones = 'big parade'
SyntaxError: invalid syntax
>>> more@ = 1000000
SyntaxError: invalid syntax
>>> class = 'Advanced Theoretical Zymurgy'
SyntaxError: invalid syntax
76trombones is illegal because it does not begin with a letter. more@ is illegal because it
contains an illegal character, @. But what’s wrong with class?
It turns out that class is one of Python’s keywords. The interpreter uses keywords to
recognize the structure of the program, and they cannot be used as variable names.
18 Chapter 2. Variables, expressions and statements

Python reserves 31 keywords1 for its use:

and del from not while


as elif global or with
assert else if pass yield
break except import print
class exec in raise
continue finally is return
def for lambda try

You might want to keep this list handy. If the interpreter complains about one of your
variable names and you don’t know why, see if it is on this list.

2.4 Statements
A statement is a unit of code that the Python interpreter can execute. We have seen two
kinds of statements: print and assignment.
When you type a statement in interactive mode, the interpreter executes it and displays the
result, if there is one.
A script usually contains a sequence of statements. If there is more than one statement, the
results appear one at a time as the statements execute.
For example, the script

print 1
x = 2
print x

produces the output

1
2

The assignment statement produces no output.

2.5 Operators and operands


Operators are special symbols that represent computations like addition and multiplica-
tion. The values the operator is applied to are called operands.
The operators +, -, *, / and ** perform addition, subtraction, multiplication, division and
exponentiation, as in the following examples:
1 In Python 3.0, exec is no longer a keyword, but nonlocal is.
2.6. Expressions 19

20+32 hour-1 hour*60+minute minute/60 5**2 (5+9)*(15-7)

The division operator might not do what you expect:

>>> minute = 59
>>> minute/60
0

The value of minute is 59, and in conventional arithmetic 59 divided by 60 is 0.98333, not
0. The reason for the discrepancy is that Python is performing floor division2 .

When both of the operands are integers, the result is also an integer; floor division chops
off the fraction part, so in this example it rounds down to zero.

If either of the operands is a floating-point number, Python performs floating-point division,


and the result is a float:

>>> minute/60.0
0.98333333333333328

2.6 Expressions
An expression is a combination of values, variables, and operators. A value all by itself
is considered an expression, and so is a variable, so the following are all legal expressions
(assuming that the variable x has been assigned a value):

17
x
x + 17

If you type an expression in interactive mode, the interpreter evaluates it and displays the
result:

>>> 1 + 1
2

But in a script, an expression all by itself doesn’t do anything! This is a common source of
confusion for beginners.

Exercise 2.1 Type the following statements in the Python interpreter to see what they do:

5
x = 5
x + 1
2 In Python 3.0, the result of this division is a float. In Python 3.0, the new operator // performs integer

division.
Another Random Document on
Scribd Without Any Related Topics
yhä kiihkeämmäksi eikä pysähtynyt, ennenkuin itse oli tästä
tavattomasta hakkaamisesta lopen uupunut.

Jok'ikinen takapihan Tupu sai vajaan viikon kuluessa kokea Hölpän


nokan lujuutta ja hänen kaulalihaksiensa kestävyyttä. Hän oli
välinpitämättömän näköisenä kävelevinään tai leikkivinään, ja
hetkellä, jolloin kanat vähimmin osasivat hyökkäystä odottaa,
hyppäsi hän hurjana heidän kimppuunsa, ponnisti ylenpalttisesti
voimiaan heitä takaa-ajaessaan ja löylyyttäessään ja iloitsi siitä, että
edes näin sai pakottavan lemmentarpeensa tyydyttää.

Hän alkoi Tupuille antaa ylimääräisiäkin selkäsaunoja, koettaen


saada ne ahdistetuksi johonkin nurkkaan, jossa ällistynyt pakolainen
otti vastaan löylytyksen pörristäen höyheniänsä, varoen päätään ja
heikosti, tukahtuneesti kaakattaen tuskissaan ja peloissaan. Eikä tuo
pitkällisen kotiorjuuden lopen masentama eläin typeryydessään
yrittänytkään vastustaa näin rohkean päättäväistä hyökkäystä.

Kaikki olisi käynyt hyvin ja Hölppä olisi kauan pysynyt Tupujen


tunnustettuna voittajana, jollei hän eräänä päivänä puolenpäivän
tienoossa, jolloin kanat olivat koolla nokkimassa emännän heille
ripottelemia jyväsiä, olisi halunnut jatkaa urotöitään ja hyökännyt
yhden kanan kimppuun. Siitä koitui hänelle pahaa. Koko kanalauma,
tuntiessaan näin koolla ollessaan voimansa, hyökkäsi siskon puolesta
kaulat lyhyinä Hölpän kimppuun ja rupesi joukolla ja anteliaasti
suorittamaan velkaansa, maksaen takaisin ne nokaniskut, joita hän
oli heille jakanut. Siinä syntyi mellakka: päät kohosivat, jyvät
unohtuivat, höyhenet pörristyivät, siivet pullistuivat, ja hätäiset ja
lyhyet vihanpurkaukset, jotka pääsivät ilmoille kaikista noista
eteenpäin ojennetuista nokista, saivat aikaan sanoinselittämättömän
kaakatuksen. Kun Tuput tiesivät lukumääränsä ja kiitetyn
yhteistuntonsa antavan heille voimaa, hyökkäsivät he Hölpän
kimppuun löylyttäen häntä kaikin voimin. Hölppä syöksyi tätä
uhkaavaa laumaa pakoon. Mutta vihainen joukko riensi hänen
kintereillään, toiset yrittivät tarttua Hölppään, toiset iskeä häntä
nokallaan, kiskoen häneltä irti höyheniä ja lyöden reikiä hänen
ihoonsa.

Talon ovi oli auki. Hölppä painui sisälle ja hänen perässään tulla
töytäsi kiukun vimmassa koko vihainen, kostonjanoinen lauma, joka
hänet auttamattomasti olisi repinyt kappaleiksi, jolleivät miehet olisi
kavahtaneet pystyyn katsomaan tätä äkkiarvaamatonta hyökkäystä
ja ajamaan kaakattavaa laumaa pakosalle.

Senjälkeen Hölppä ei enää löylytellyt Tupuja.

*****

Sadepäivinä hän oli ravintolan isäntäväen sulona ilahduttaen heitä


vikkelillä liikkeillään, huvittavalla uteliaisuudellaan ja
naurunsäkätyksellään. Hän otti vastaan kaikki mitä hänelle heitettiin,
olipa se syötäväksi kelpaavaa eli ei, ja, kuten kulloinkin päähän pisti,
söi sen tai kätki johonkin nurkkaan lankun tai kevyen kiven alle.
Pihalla ei enää ollut puunkappaletta, jonka suojasta ei löytynyt
leivän-, sokurin- tai perunanpalaa, vieläpä kuparirahojakin, joiden
löytö oli talon nulikoille sangen mieluinen yllätys. Ihmeteltiin, miten
nämä kätköt, joita kanat käyttivät hyväkseen, olivat syntyneet, sillä
harvoin kävi niitä Hölppä tarkastamassa, jolla ei milloinkaan ollut
nälkä ja jota nuo pienet kiillottomat kuparirahat eivät erikoisesti
hurmanneet.

Mutta hopeiset pöytäkalut, terässakset, miehen kello häntä


viehättivät. Ihmeteltävästi arvasi hän, että isäntäväki olisi kurittanut
häntä, jos hän niitä anasti heidän nähtensä. Kun hänelle sattui
vastustamaton anastamispuuska ja oikein erikoinen itaruuden tuuli,
odotteli hän hetkeä jolloin olisi yksin, varastaakseen ja kätkeäkseen
haluamiansa kiiltäviä esineitä. Näin varasti hän useita hopeisia
pöytäkaluja, kuljettaakseen ne puuvajan perälle suureen kuoppaan
risuaidan suojaan, jonne hän tästä puoleen vei kaikki hiukankin
kiiltävät esineet, joita sai siepatuksi. Näin hän tietämättään eräänä
päivänä aiheutti tappelun, joka oli vähällä päättyä surullisesti.

Eräänä sumuisena iltapäivänä kuljeskeli hän joutilaana pöytien


alla, etsien esineiden seasta jotakin, joka auttaisi häntä leikin tai
vehkeilyn alkuun, kavahtaen joutumasta juopottelijain poljettavaksi,
jotka siellä kuluttivat aikaansa kallistellen laseja ja juttuja kertoillen.

Siellä oli heitä neljä tai viisi pyöreän pöydän ympärillä,


lynkäpäisillään pöydän vahaliinalla, jolle viiniä oli läikkynyt. He
lörpöttelivät ja nauroivat, aikalailla liikutuksissaan, melkein
päihtyneinä, kilistellen laseja ja pulloja. Jo parikymmentä kertaa
olivat he vähällä tarttua toinen toisensa tukkaan jostakin muka
loukkaavasta sanasta tai likaisesta jutusta, jossa — kiihtyneessä
tilassaan kun olivat käyneet epäluuloisiksi — olivat huomaavinaan
häpäiseviä salaviittauksia.

Kyllästyneenä näihin juomavieraisiin käski isäntä heitä maksamaan


juominkinsa ja lähtemään tiehensä, lujasti kieltäytyen enää heille
mitään antamasta.

Vähäsen vielä sovintoa hierottuaan ja tyhjennettyään lasinsa, veti


heistä muuan, joka oli toisia päihtyneempi, taskustaan esiin suuren,
monivärisen nahkakukkaron, jonka hihnoja hän hitaasti aukoili, ja
otti sieltä esille kahdenkymmenen markan kultarahan, jonka aikoi
laskea kapakan isännän käteen. Hölppä hyppeli yhä lattialla melkein
miehen jaloissa. Pahaksi onneksi pääsi kultaraha paksujen,
pitkäaikaisesta juopottelusta pöhöttyneiden sormien lomitse
liukumaan ja putosi lattialle. Juopunut työnsi tuoliaan taapäin
saadakseen riittävästi tilaa kumartumaan ja ottamaan maasta rahan.
Hän ei nähnyt mitään. Toiset olivat meluten vieneet säärensä
hajalleen ja Hölppä mennä vilisti, kuin olisi tästä rähinästä
peloissaan, nokka pystyssä ovea kohden. Ei kukaan häntä
huomannut. Juopunut haki, kiroili; toisetkin kumartuivat etsimään;
isäntä ja emäntä tulivat myös lähemmäs ja tutkivat terävin katsein
lattianrakoja. Ei näkynyt mitään. Raapaistiin tulta, sytytettiin kynttilä.
Ei näkynyt mitään. Juopunut kiroili kovemmin, ärjyi, suuttui. Hän oli
kyllä ottanut esille kahdenkymmenen markan kultarahan — jonkun
oli täytynyt ottaa se. Ei käynyt päinsä tehdä tällaista pilaa
juomavieraalle tai ystävälle! Toiset juopuneet vakuuttivat
viattomuuttaan, hän myönsi heidän olevan syyttömiä ja syytti
isäntää, joka oli käskenyt heidän poistua. Miksikähän hän käskikään
heidän mennä ulos? Silloin alkoi sadella kirouksia, uhkauksia,
huutoja; kuului korvapuustien läimäyksiä, nyrkkejä heristettiin, lakit
lentelivät ilmassa, nenät vuotivat verta; pöytä huojui, läkkituopit ja
lasit menivät kumoon pelottavassa sekasorrossa miesten verisesti
otellessa, repiessä ja iskiessä toisiaan ja ulvoen vakuuttaessa
viattomuuttaan; emäntä kohotti kätensä taivasta kohti ja lähetti
hakemaan naapureita erottamaan näitä miehiä, jotka iskivät toisiaan
aivan umpimähkään eivätkä oikeastaan tienneet, miksi tappelivat.

Koska kultarahaa ei milloinkaan näkynyt, päätteli ravintolan isäntä,


että juopunut ei ollutkaan ottanut kukkarostaan mitään, että hän oli
avannut sen vain etsiäkseen tappelun aihetta, ja kaikki yhtyivät
häneen.
Hölppä yksin tiesi asian oikean laidan. Hän lähti niin äkisti pihalle
sentähden, että hänellä oli nokassaan kultaraha, jonka hän oli
siepannut juopuneen kengältä samassa kun se oli siihen ääntä
antamatta pudonnut.

*****

Näihin aikoihin eräs juomavieraista sai päähänsä tuon Hölpälle


tuhoisan tuuman: jospa sen opettaisi juomaan viiniä!

Tuuma oli hankala toteuttaa, koska Hölppä tunsi voittamatonta


epäluuloa sekä viinin hajua että sen väriä kohtaan. Täytyi käyttää
petosta ja vedota harakan hyvin tunnettuun herkutteluhaluun.
Eräänä päivänä oli Hölppä pöydällä, jonka ääressä eräs juomavieras
istui jakaen harakan kanssa sokerileivän, jolle tämä oli ahne. Silloin
pudotti mies kuin vahingossa lasiinsa, johon oli kaatanut
enimmäkseen valkoista, hyvin sokeripitoista viiniä, palan, jota tarjosi
Hölpälle. Tämä lähestyi lasia ja epäluulostaan huolimatta nokki
pieninä murusina sokerileivän, sillä se oli mennyt palasiksi, maistaen
näin samalla sokeroitua nestettä, joka hänestä tuntui oivalliselta. Kun
mies sitten hetkisen perästä tarjosi lasin ilman sokerileipää, tulikin
hän sitä hotkien juomaan, palasipa sitten houkuttelemattakin lasin
ääreen useita kertoja peräkkäin.

Huomaamatta väritettiin neste ja sokeriannosta vähennettiin, niin


että jonkun ajan kuluttua Hölppä joi pelkkää viiniä ja syvästi halveksi
raikasta vettä, jonka pinnalla pölyhiukkaset harmaana kuorena
uiskentelivat.

Viinin ensimäiset vaikutukset Hölppään olivat omituiset: se


lörpötteli päivät päästään hyppien pöydältä toiselle, näykkien
juomavieraita, iskien niitä nokallaan, hääri sitten ivanhaluisen
näköisenä Mirrin edessä, joka häntä katseli viikset oikosenaan,
korvat nurin ja astui heti julkeasti nykimään hännästä Pyryä, joka
ärähti hänelle tavallista kovemmin, ilmaisten näin selvästi, että tätä
ilveilyä oli tarpeeksi kestänyt.

Ällistyneenä tästä läksytyksestä, asettui hän seisomaan jalat


haarallaan kohottaen hiukan siipiänsä niinkuin akka, joka kädet
lanteilla valmistuu haukkumaan naapurimuijaa, ja piti Pyrylle
neljännestunnin kestävän, pitkäpiimäisen ja vaikeasti tajuttavan
esitelmän, jossa samat kerakkeet säännöllisin väliajoin kertautuivat
niinkuin vanhoissa kiroussanoissa. Mutta Pyry oli kyllin älykäs, ettei
antanut tämän rauhaansa häiritä.

Kuin sekaisin omasta sanatulvastaan, meni Hölppä sitten piiloon


tuhkapesän viereen turvapaikkaansa ja vaipui uneen.

Joka päivä joi hän enemmän ja hänen paha tuulensa yltyi. Pyry
ärisi jo hänelle vihaisesti, juopot potkivat häntä hieman takapuoleen
ja Mirri raapaisi häntä kynsillään joitakin kertoja tosissaan.

Nyt hän ei enää tahtonut juoda muuta kuin viiniä, ja kun joskus
joku juopottelija tarjosi hänelle huvikseen vesilasin, kasteli hän siinä
nokkansa; näykkäsi sitten hetkellisen mielialansa vallassa
suutuksissaan aikalailla tarjoojaa tästä huonosta pilasta tai kaasi
päällään ja kaulallaan tämän lasin äkkiä kumoon.

Täysin tahdottomana alistuen himojensa valtaan, joiden varalle


eläimillä ei olennossaan ole hillitsevää eikä ohjaavaa voimaa, sieti
hän tästälähtien epäluuloitta mitä tyhmintä ja ilkeintä pilantekoa.

Koska hän erotuksetta tarttui kaikkeen mitä hänelle ojennettiin,


kätkeäkseen sen sitten, otti hän eräänä päivänä juopuneelta vastaan
juuri sytytetyn paperossin tarttuen sen palavaan päähän. Ensin kuuli
hän paperossin nokassaan kihahtavan, tunsi sitten palohajua, sitten
kuului heikko, vihlova tuskan korahdus ja sill'aikaa kun juopottelijat
olivat pakahtua naurusta, pakoili eläinparka nokka auki
sanomattomassa tuskassa, mitään näkemättä joka haaralle,
syöksyen pahki seiniin ja huonekaluihin, päästäen kurkustaan
vaikeroivaa kirkunaa ja epätoivon korahduksia. Kaksi päivää oli hän
syömättä ja juomatta pitäen nokkaa auki. Vähitellen opetti häntä
kärsimyksensä jälleen tajuamaan eläinelämäänsä, rappiotilaansa, ja
hän olla jurotti kaiket päivät synkkänä ja yksinäisenä pimeässä
nurkassaan.

Vihdoin rupesi hän jälleen syömään ja juomaan, ensin vettä, sitten


uudelleen viiniä, jota särpi vähin siemauksin. Hän kävi jälleen
riitaiseksi, leikki yhä vähemmän, janosi yhä enemmän alkohoolia, ja
kulutti aikaansa särpien viiniä juopottelijain lasista, nukkuen
nurkassaan tai puolivalveillaan hokien päihtyneenä yhtä ainoata,
yksitoikkoista ja tyhjäsisältöistä ääntä: puee, puee!

*****

Tänään ei ollut tapahtunut mitään erityistä. Hölppä oli juonut


kuten tavallisesti ja tapansa mukaan mennyt maata hämärissä vähän
sen jälkeen kun kanat olivat asettuneet yöpuulleen.

Kyyristyneenä turvapaikkaansa höyhenet pörröllään, pää kaulan


sisään vajonneena, nokka riipuksissa, paljaat silmäluomet
suljettuina, vapisi hän kumman painajaisen vallassa, missä mitä
lystillisimmät mielikuvat liittyivät mitä tuskallisimpiin.

Öljylampun varjostin oli syrjään vedetty, niin että valo osui


kirkkaana hänen piilopaikkaansa. Silloin hänestä tuntui, että kissat ja
kanat laumottain olivat liittyneet häntä vastaan ja piirittivät hänet
uhaten sytytetyillä, palavilla paperosseilla. Hän ravisti itseään
päästäkseen niiden takaa-ajoa pakoon, nosti vuoroin kumpaakin
jalkaansa ja sulki epätoivon voimalla nokkansa, jottei polttaisi sitä.

Äkkiä heräsi hän tästä painostavasta unesta kuullessaan kovalla


äänellä lausuttavan kaksitavuista nimeänsä. Hän avasi silmänsä,
mutta sulki ne äkisti jälleen tuntiessaan kirkkaan lampunvalon niitä
pistävästi sokaisevan. Mutta uudelleen kuului: Hölppä!

Hän ei liikahtanut, koska vielä oli painajaisunen ahdistuksen


vallassa. Hänen mieltään kalvoi epäluulo ja tuska hänen tuntiessaan,
ettei tässä oudossa, hänelle melkein tuntemattomassa ympäristössä
kyennyt pääsemään pakoon, ja hän pelkäsi sekä valoa että pimeää.

Mutta kaksi kättä nosti hänet ylös ja viskasi tylysti pöydälle


vastapäätä lamppua, punaiselta välkkyvällä nesteellä täytettyjen
pikarien keskelle, joita näkyi pöydän joka reunalla ikäänkuin rajana,
jonka yli hän ei saanut astua. Häikäistynä ja hurjana pelosta kääntyi
hän valoa pakoon, joka koski kipeästi silmiin, miesten nauraa
hohottaessa hänen neuvottomuudelleen ja tuskalleen.

— Otappas kulaus, Hölppä! Hänelle tarjottiin lasi.

Mutta Hölppä piti nokkansa ja silmänsä itsepintaisesti kiinni,


tuntien hämärästi tuossa käheässä äänessä vaaran piilevän.

— Hän ei haluakaan enää viiniä, tuo herkkusuu, sanoi eräs


juopunut. —
Jospa hänelle tarjoisi vähän väkevämpää!
Ja oitis hän tarjosi Hölpälle pienestä lasista paloviinaa. Mutta
nokka pysyi suljettuna, koska säikähtynyt eläin ei ymmärtänyt eikä
halunnut mitään.

Silloin eräs mies aukaisi väkisin Hölpän nokan toisen kaataessa


kurkkuun yhtä päätä vähissä erin kolme lusikallista alkohoolia.

Vaikutus oli eriskummainen.

Heti Hölppä suorihe pystyyn, tuntui kuin pitenevän, repäsi hurjat


silmänsä auki, riuhtasi rajusti siipensä levälleen ja syöksyi tarmonsa
takaa lamppua kohti, saaden juopot kauhistuksissaan peräytymään.
Veristen silmien salamoidessa hyppäsi hän vastustamattomalla
voimalla kohti valoa tuon lampun kimppuun, jota hänen
hullaantuneet aivonsa pitivät yksinomaisena syyllisenä hänen
sisässään riehuvaan polttoon.

Lamppu ei kestänyt tätä hurjaa hyökkäystä, vaan kaatui ja vieri


lattialle särkyen sirpaleiksi, öljy syttyi tuleen, joka poltti
seinäpapereita, tuoleja, pöytiä, uhaten näin taloa tulipalolla. Hölppä
tuleen tukehtuen paloi elävältä, mutta tämän ulkonaisen tuskan
rinnalla tuntui ehkä hänen sisäinen, aivoissa ja sisälmyksissä riehuva
polttonsa helpommalta.

Ja kun juopuneet olivat saaneet tuon juoppohullun harakan


sytyttämän tulen sammuksiin, tulkitsi yksi heistä, katsellen kuolleen
tai oikeammin vapautuneen eläimen puoleksi hiiltynyttä ja
jäykistynyttä ruumista, yleisen mielipiteen, jossa ilmeni ihmisten
äärimmäinen tunnottomuus:

— Äh! kuinka ilkeä tuokin raato sentään on!


*** END OF THE PROJECT GUTENBERG EBOOK KETUN
SEIKKAILUSTA HARAKAN VANKEUTEEN ***

Updated editions will replace the previous one—the old editions will
be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States copyright in
these works, so the Foundation (and you!) can copy and distribute it
in the United States without permission and without paying
copyright royalties. Special rules, set forth in the General Terms of
Use part of this license, apply to copying and distributing Project
Gutenberg™ electronic works to protect the PROJECT GUTENBERG™
concept and trademark. Project Gutenberg is a registered trademark,
and may not be used if you charge for an eBook, except by following
the terms of the trademark license, including paying royalties for use
of the Project Gutenberg trademark. If you do not charge anything
for copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such as
creation of derivative works, reports, performances and research.
Project Gutenberg eBooks may be modified and printed and given
away—you may do practically ANYTHING in the United States with
eBooks not protected by U.S. copyright law. Redistribution is subject
to the trademark license, especially commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the free


distribution of electronic works, by using or distributing this work (or
any other work associated in any way with the phrase “Project
Gutenberg”), you agree to comply with all the terms of the Full
Project Gutenberg™ License available with this file or online at
www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand, agree
to and accept all the terms of this license and intellectual property
(trademark/copyright) agreement. If you do not agree to abide by all
the terms of this agreement, you must cease using and return or
destroy all copies of Project Gutenberg™ electronic works in your
possession. If you paid a fee for obtaining a copy of or access to a
Project Gutenberg™ electronic work and you do not agree to be
bound by the terms of this agreement, you may obtain a refund
from the person or entity to whom you paid the fee as set forth in
paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only be


used on or associated in any way with an electronic work by people
who agree to be bound by the terms of this agreement. There are a
few things that you can do with most Project Gutenberg™ electronic
works even without complying with the full terms of this agreement.
See paragraph 1.C below. There are a lot of things you can do with
Project Gutenberg™ electronic works if you follow the terms of this
agreement and help preserve free future access to Project
Gutenberg™ electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright law
in the United States and you are located in the United States, we do
not claim a right to prevent you from copying, distributing,
performing, displaying or creating derivative works based on the
work as long as all references to Project Gutenberg are removed. Of
course, we hope that you will support the Project Gutenberg™
mission of promoting free access to electronic works by freely
sharing Project Gutenberg™ works in compliance with the terms of
this agreement for keeping the Project Gutenberg™ name associated
with the work. You can easily comply with the terms of this
agreement by keeping this work in the same format with its attached
full Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.

1.E. Unless you have removed all references to Project Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project Gutenberg™
work (any work on which the phrase “Project Gutenberg” appears,
or with which the phrase “Project Gutenberg” is associated) is
accessed, displayed, performed, viewed, copied or distributed:
This eBook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this eBook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is derived


from texts not protected by U.S. copyright law (does not contain a
notice indicating that it is posted with permission of the copyright
holder), the work can be copied and distributed to anyone in the
United States without paying any fees or charges. If you are
redistributing or providing access to a work with the phrase “Project
Gutenberg” associated with or appearing on the work, you must
comply either with the requirements of paragraphs 1.E.1 through
1.E.7 or obtain permission for the use of the work and the Project
Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is posted


with the permission of the copyright holder, your use and distribution
must comply with both paragraphs 1.E.1 through 1.E.7 and any
additional terms imposed by the copyright holder. Additional terms
will be linked to the Project Gutenberg™ License for all works posted
with the permission of the copyright holder found at the beginning
of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files containing a
part of this work or any other work associated with Project
Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute this


electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the Project
Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™ works
unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or providing


access to or distributing Project Gutenberg™ electronic works
provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™


electronic work or group of works on different terms than are set
forth in this agreement, you must obtain permission in writing from
the Project Gutenberg Literary Archive Foundation, the manager of
the Project Gutenberg™ trademark. Contact the Foundation as set
forth in Section 3 below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on, transcribe
and proofread works not protected by U.S. copyright law in creating
the Project Gutenberg™ collection. Despite these efforts, Project
Gutenberg™ electronic works, and the medium on which they may
be stored, may contain “Defects,” such as, but not limited to,
incomplete, inaccurate or corrupt data, transcription errors, a
copyright or other intellectual property infringement, a defective or
damaged disk or other medium, a computer virus, or computer
codes that damage or cannot be read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for


the “Right of Replacement or Refund” described in paragraph 1.F.3,
the Project Gutenberg Literary Archive Foundation, the owner of the
Project Gutenberg™ trademark, and any other party distributing a
Project Gutenberg™ electronic work under this agreement, disclaim
all liability to you for damages, costs and expenses, including legal
fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR
NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR
BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH
1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK
OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL
NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF
YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of receiving
it, you can receive a refund of the money (if any) you paid for it by
sending a written explanation to the person you received the work
from. If you received the work on a physical medium, you must
return the medium with your written explanation. The person or
entity that provided you with the defective work may elect to provide
a replacement copy in lieu of a refund. If you received the work
electronically, the person or entity providing it to you may choose to
give you a second opportunity to receive the work electronically in
lieu of a refund. If the second copy is also defective, you may
demand a refund in writing without further opportunities to fix the
problem.

1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of damages.
If any disclaimer or limitation set forth in this agreement violates the
law of the state applicable to this agreement, the agreement shall be
interpreted to make the maximum disclaimer or limitation permitted
by the applicable state law. The invalidity or unenforceability of any
provision of this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation,


the trademark owner, any agent or employee of the Foundation,
anyone providing copies of Project Gutenberg™ electronic works in
accordance with this agreement, and any volunteers associated with
the production, promotion and distribution of Project Gutenberg™
electronic works, harmless from all liability, costs and expenses,
including legal fees, that arise directly or indirectly from any of the
following which you do or cause to occur: (a) distribution of this or
any Project Gutenberg™ work, (b) alteration, modification, or
additions or deletions to any Project Gutenberg™ work, and (c) any
Defect you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new computers.
It exists because of the efforts of hundreds of volunteers and
donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project Gutenberg™’s
goals and ensuring that the Project Gutenberg™ collection will
remain freely available for generations to come. In 2001, the Project
Gutenberg Literary Archive Foundation was created to provide a
secure and permanent future for Project Gutenberg™ and future
generations. To learn more about the Project Gutenberg Literary
Archive Foundation and how your efforts and donations can help,
see Sections 3 and 4 and the Foundation information page at
www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-profit
501(c)(3) educational corporation organized under the laws of the
state of Mississippi and granted tax exempt status by the Internal
Revenue Service. The Foundation’s EIN or federal tax identification
number is 64-6221541. Contributions to the Project Gutenberg
Literary Archive Foundation are tax deductible to the full extent
permitted by U.S. federal laws and your state’s laws.

The Foundation’s business office is located at 809 North 1500 West,


Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up
to date contact information can be found at the Foundation’s website
and official page at www.gutenberg.org/contact

Section 4. Information about Donations to


the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission of
increasing the number of public domain and licensed works that can
be freely distributed in machine-readable form accessible by the
widest array of equipment including outdated equipment. Many
small donations ($1 to $5,000) are particularly important to
maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws regulating


charities and charitable donations in all 50 states of the United
States. Compliance requirements are not uniform and it takes a
considerable effort, much paperwork and many fees to meet and
keep up with these requirements. We do not solicit donations in
locations where we have not received written confirmation of
compliance. To SEND DONATIONS or determine the status of
compliance for any particular state visit www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states where


we have not met the solicitation requirements, we know of no
prohibition against accepting unsolicited donations from donors in
such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot make


any statements concerning tax treatment of donations received from
outside the United States. U.S. laws alone swamp our small staff.

Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could be
freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose network of
volunteer support.
Project Gutenberg™ eBooks are often created from several printed
editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how
to subscribe to our email newsletter to hear about new eBooks.

You might also like