100% found this document useful (13 votes)
47 views151 pages

(Ebook) Practical Programming: An Introduction To Computer Science Using Python by Jennifer Campbell, Paul Gries, Jason Montojo, Greg Wilson ISBN 9781934356272, 1934356271 Full Access

Educational resource: (Ebook) Practical programming: An introduction to computer science using Python by Jennifer Campbell, Paul Gries, Jason Montojo, Greg Wilson ISBN 9781934356272, 1934356271 Instantly downloadable. Designed to support curriculum goals with clear analysis and educational value.

Uploaded by

aurelijadi4923
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 (13 votes)
47 views151 pages

(Ebook) Practical Programming: An Introduction To Computer Science Using Python by Jennifer Campbell, Paul Gries, Jason Montojo, Greg Wilson ISBN 9781934356272, 1934356271 Full Access

Educational resource: (Ebook) Practical programming: An introduction to computer science using Python by Jennifer Campbell, Paul Gries, Jason Montojo, Greg Wilson ISBN 9781934356272, 1934356271 Instantly downloadable. Designed to support curriculum goals with clear analysis and educational value.

Uploaded by

aurelijadi4923
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/ 151

(Ebook) Practical programming: An introduction to

computer science using Python by Jennifer Campbell,


Paul Gries, Jason Montojo, Greg Wilson ISBN
9781934356272, 1934356271 Pdf Download

https://ebooknice.com/product/practical-programming-an-introduction-
to-computer-science-using-python-1938670

★★★★★
4.8 out of 5.0 (83 reviews )

Instant PDF Download

ebooknice.com
(Ebook) Practical programming: An introduction to computer
science using Python by Jennifer Campbell, Paul Gries, Jason
Montojo, Greg Wilson ISBN 9781934356272, 1934356271 Pdf
Download

EBOOK

Available Formats

■ PDF eBook Study Guide Ebook

EXCLUSIVE 2025 EDUCATIONAL COLLECTION - LIMITED TIME

INSTANT DOWNLOAD VIEW LIBRARY


We believe these products will be a great fit for you. Click
the link to download now, or visit ebooknice.com
to discover even more!

(Ebook) Practical Programming: An Introduction to Computer


Science Using Python 3 by Paul Gries, Jennifer Campbell, Jason
Montojo ISBN 9781937785451, 1937785459

https://ebooknice.com/product/practical-programming-an-introduction-to-
computer-science-using-python-3-4440604

(Ebook) Practical Programming: An Introduction to Computer


Science Using Python 3.6 3rd Edition by Paul Gries, Jennifer
Campbell, Jason Montojo ISBN 9781680502688, 1680502689

https://ebooknice.com/product/practical-programming-an-introduction-to-
computer-science-using-python-3-6-3rd-edition-7389846

(Ebook) Biota Grow 2C gather 2C cook by Loucas, Jason; Viles,


James ISBN 9781459699816, 9781743365571, 9781925268492,
1459699815, 1743365578, 1925268497

https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374

(Ebook) Practical Programming by Paul Gries, Jason Montojo,


Jennifer Campbell ISBN 9781680503036, 1680503030

https://ebooknice.com/product/practical-programming-10831066
(Ebook) Matematik 5000+ Kurs 2c Lärobok by Lena Alfredsson, Hans
Heikne, Sanna Bodemyr ISBN 9789127456600, 9127456609

https://ebooknice.com/product/matematik-5000-kurs-2c-larobok-23848312

(Ebook) SAT II Success MATH 1C and 2C 2002 (Peterson's SAT II


Success) by Peterson's ISBN 9780768906677, 0768906679

https://ebooknice.com/product/sat-ii-success-math-1c-and-2c-2002-peterson-
s-sat-ii-success-1722018

(Ebook) Master SAT II Math 1c and 2c 4th ed (Arco Master the SAT
Subject Test: Math Levels 1 & 2) by Arco ISBN 9780768923049,
0768923042

https://ebooknice.com/product/master-sat-ii-math-1c-and-2c-4th-ed-arco-
master-the-sat-subject-test-math-levels-1-2-2326094

(Ebook) Cambridge IGCSE and O Level History Workbook 2C - Depth


Study: the United States, 1919-41 2nd Edition by Benjamin
Harrison ISBN 9781398375147, 9781398375048, 1398375144,
1398375047
https://ebooknice.com/product/cambridge-igcse-and-o-level-history-
workbook-2c-depth-study-the-united-states-1919-41-2nd-edition-53538044

(Ebook) Python Programming: An Introduction to Computer Science


by John M. Zelle

https://ebooknice.com/product/python-programming-an-introduction-to-
computer-science-7343896
What Readers Are Saying About
Practical Programming

Practical Programming is true to its name. The information it presents


is organized around useful tasks rather than abstract constructs, and
each chapter addresses a well-contained and important aspect of pro-
gramming in Python. A student wondering “How do I make the com-
puter do X?” would be able to find their answer very quickly with this
book.
Christine Alvarado
Associate professor of computer science, Harvey Mudd College

Science is about learning by performing experiments. This book


encourages computer science students to experiment with short,
interactive Python scripts and in the process learn fundamental con-
cepts such as data structures, sorting and searching algorithms,
object-oriented programming, accessing databases, graphical user
interfaces, and good program design. Clearly written text along with
numerous compelling examples, diagrams, and images make this an
excellent book for the beginning programmer.
Ronald Mak
Research staff member, IBM Almaden Research Center
Lecturer, Department of Computer Science, San Jose State
University

What, no compiler, no sample payroll application? What kind of pro-


gramming book is this? A great one, that’s what. It launches from a
“You don’t know anything yet” premise into a fearless romp through
the concepts and techniques of relevant programming technology.
And what fun students will have with the images and graphics in the
exercises!
Laura Wingerd
Author, Practical Perforce

Prepared exclusively for Trieu Nguyen


The debugging section is truly excellent. I know several practicing pro-
grammers who’d be rightfully offended by a suggestion to study the
whole book but who could really do with brushing up on this section
(and many others) once in a while.
Alex Martelli
Author, Python in a Nutshell

This book succeeds in two different ways. It is both a science-focused


CS1 text and a targeted Python reference. Even as it builds students’
computational insights, it also empowers and encourages them to
immediately apply their newfound programming skills in the lab or
on projects of their own.
Zachary Dodds
Associate professor of computer science, Harvey Mudd College

Prepared exclusively for Trieu Nguyen


Prepared exclusively for Trieu Nguyen
Practical Programming
An Introduction to Computer Science Using Python

Jennifer Campbell
Paul Gries
Jason Montojo
Greg Wilson

The Pragmatic Bookshelf


Raleigh, North Carolina Dallas, Texas

Prepared exclusively for Trieu Nguyen


Many of the designations used by manufacturers and sellers to distinguish their prod-
ucts are claimed as trademarks. Where those designations appear in this book, and The
Pragmatic Programmers, LLC was aware of a trademark claim, the designations have
been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The
Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf and the linking g
device are trademarks of The Pragmatic Programmers, LLC.

Every precaution was taken in the preparation of this book. However, the publisher
assumes no responsibility for errors or omissions, or for damages that may result from
the use of information (including program listings) contained herein.

Our Pragmatic courses, workshops, and other products can help you and your team
create better software and have more fun. For more information, as well as the latest
Pragmatic titles, please visit us at

http://www.pragprog.com

Copyright © 2009 Jennifer Campbell, Paul Gries, Jason Montojo, and Greg Wilson.

All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, or transmit-


ted, in any form, or by any means, electronic, mechanical, photocopying, recording, or
otherwise, without the prior consent of the publisher.

Printed in the United States of America.

ISBN-10: 1-934356-27-1
ISBN-13: 978-1-934356-27-2
Printed on acid-free paper.
P1.0 printing, April 2009
Version: 2009-5-6

Prepared exclusively for Trieu Nguyen


Contents
1 Introduction 11
1.1 Programs and Programming . . . . . . . . . . . . . . . . 13
1.2 A Few Definitions . . . . . . . . . . . . . . . . . . . . . . 14
1.3 What to Install . . . . . . . . . . . . . . . . . . . . . . . . 14
1.4 For Instructors . . . . . . . . . . . . . . . . . . . . . . . . 15
1.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

2 Hello, Python 17
2.1 The Big Picture . . . . . . . . . . . . . . . . . . . . . . . 17
2.2 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.3 What Is a Type? . . . . . . . . . . . . . . . . . . . . . . . 22
2.4 Variables and the Assignment Statement . . . . . . . . 25
2.5 When Things Go Wrong . . . . . . . . . . . . . . . . . . 29
2.6 Function Basics . . . . . . . . . . . . . . . . . . . . . . . 30
2.7 Built-in Functions . . . . . . . . . . . . . . . . . . . . . . 33
2.8 Style Notes . . . . . . . . . . . . . . . . . . . . . . . . . . 34
2.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
2.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

3 Strings 39
3.1 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.2 Escape Characters . . . . . . . . . . . . . . . . . . . . . 42
3.3 Multiline Strings . . . . . . . . . . . . . . . . . . . . . . . 43
3.4 Print . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
3.5 Formatted Printing . . . . . . . . . . . . . . . . . . . . . 45
3.6 User Input . . . . . . . . . . . . . . . . . . . . . . . . . . 46
3.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
3.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

Prepared exclusively for Trieu Nguyen


CONTENTS 8

4 Modules 50
4.1 Importing Modules . . . . . . . . . . . . . . . . . . . . . 50
4.2 Defining Your Own Modules . . . . . . . . . . . . . . . . 54
4.3 Objects and Methods . . . . . . . . . . . . . . . . . . . . 60
4.4 Pixels and Colors . . . . . . . . . . . . . . . . . . . . . . 68
4.5 Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
4.6 Style Notes . . . . . . . . . . . . . . . . . . . . . . . . . . 76
4.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
4.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

5 Lists 81
5.1 Lists and Indices . . . . . . . . . . . . . . . . . . . . . . 81
5.2 Modifying Lists . . . . . . . . . . . . . . . . . . . . . . . . 85
5.3 Built-in Functions on Lists . . . . . . . . . . . . . . . . 87
5.4 Processing List Items . . . . . . . . . . . . . . . . . . . . 89
5.5 Slicing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
5.6 Aliasing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
5.7 List Methods . . . . . . . . . . . . . . . . . . . . . . . . . 95
5.8 Nested Lists . . . . . . . . . . . . . . . . . . . . . . . . . 97
5.9 Other Kinds of Sequences . . . . . . . . . . . . . . . . . 99
5.10 Files as Lists . . . . . . . . . . . . . . . . . . . . . . . . . 100
5.11 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . 103
5.12 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
5.13 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 105

6 Making Choices 108


6.1 Boolean Logic . . . . . . . . . . . . . . . . . . . . . . . . 108
6.2 if Statements . . . . . . . . . . . . . . . . . . . . . . . . . 118
6.3 Storing Conditionals . . . . . . . . . . . . . . . . . . . . 125
6.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
6.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 127

7 Repetition 131
7.1 Counted Loops . . . . . . . . . . . . . . . . . . . . . . . . 131
7.2 while Loops . . . . . . . . . . . . . . . . . . . . . . . . . . 140
7.3 User Input Loops . . . . . . . . . . . . . . . . . . . . . . 148
7.4 Controlling Loops . . . . . . . . . . . . . . . . . . . . . . 149
7.5 Style Notes . . . . . . . . . . . . . . . . . . . . . . . . . . 153
7.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
7.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 155

Report erratum
Prepared exclusively for Trieu Nguyen this copy is (P1.0 printing, April 2009)
CONTENTS 9

8 File Processing 159


8.1 One Record per Line . . . . . . . . . . . . . . . . . . . . 160
8.2 Records with Multiple Fields . . . . . . . . . . . . . . . . 171
8.3 Positional Data . . . . . . . . . . . . . . . . . . . . . . . 174
8.4 Multiline Records . . . . . . . . . . . . . . . . . . . . . . 177
8.5 Looking Ahead . . . . . . . . . . . . . . . . . . . . . . . . 179
8.6 Writing to Files . . . . . . . . . . . . . . . . . . . . . . . . 181
8.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
8.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 183

9 Sets and Dictionaries 185


9.1 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
9.2 Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . 190
9.3 Inverting a Dictionary . . . . . . . . . . . . . . . . . . . . 197
9.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
9.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 199

10 Algorithms 203
10.1 Searching . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
10.2 Timing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
10.3 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
10.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 212

11 Searching and Sorting 214


11.1 Linear Search . . . . . . . . . . . . . . . . . . . . . . . . 214
11.2 Binary Search . . . . . . . . . . . . . . . . . . . . . . . . 218
11.3 Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
11.4 More Efficient Sorting Algorithms . . . . . . . . . . . . . 228
11.5 Mergesort: An N log2 N Algorithm . . . . . . . . . . . . . 229
11.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
11.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 234

12 Construction 237
12.1 More on Functions . . . . . . . . . . . . . . . . . . . . . 237
12.2 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . 242
12.3 Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
12.4 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . 254
12.5 Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
12.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
12.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 261

Report erratum
Prepared exclusively for Trieu Nguyen this copy is (P1.0 printing, April 2009)
CONTENTS 10

13 Object-Oriented Programming 270


13.1 Class Color . . . . . . . . . . . . . . . . . . . . . . . . . . 271
13.2 Special Methods . . . . . . . . . . . . . . . . . . . . . . . 276
13.3 More About dir and help . . . . . . . . . . . . . . . . . . 278
13.4 A Little Bit of OO Theory . . . . . . . . . . . . . . . . . . 280
13.5 A Longer Example . . . . . . . . . . . . . . . . . . . . . . 288
13.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
13.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 293

14 Graphical User Interfaces 294


14.1 The Tkinter Module . . . . . . . . . . . . . . . . . . . . . 295
14.2 Basic GUI Construction . . . . . . . . . . . . . . . . . . 296
14.3 Models, Views, and Controllers . . . . . . . . . . . . . . 301
14.4 Style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
14.5 A Few More Widgets . . . . . . . . . . . . . . . . . . . . . 312
14.6 Object-Oriented GUIs . . . . . . . . . . . . . . . . . . . . 316
14.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
14.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 318

15 Databases 321
15.1 The Big Picture . . . . . . . . . . . . . . . . . . . . . . . 321
15.2 First Steps . . . . . . . . . . . . . . . . . . . . . . . . . . 323
15.3 Retrieving Data . . . . . . . . . . . . . . . . . . . . . . . 327
15.4 Updating and Deleting . . . . . . . . . . . . . . . . . . . 330
15.5 Transactions . . . . . . . . . . . . . . . . . . . . . . . . . 331
15.6 Using NULL for Missing Data . . . . . . . . . . . . . . . 333
15.7 Using Joins to Combine Tables . . . . . . . . . . . . . . 334
15.8 Keys and Constraints . . . . . . . . . . . . . . . . . . . . 339
15.9 Advanced Features . . . . . . . . . . . . . . . . . . . . . 341
15.10 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
15.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 347

A Bibliography 351

Index 353

Report erratum
Prepared exclusively for Trieu Nguyen this copy is (P1.0 printing, April 2009)
Chapter 1

Introduction
Take a look at the pictures in Figure 1.1, on the following page. The
first one shows forest cover in the Amazon basin in 1975. The second
one shows the same area 26 years later. Anyone can see that much of
the rainforest has been destroyed, but how much is “much”?
Now look at Figure 1.2, on page 13.
Are these blood cells healthy? Do any of them show signs of leukemia?
It would take an expert doctor a few minutes to tell. Multiply those
minutes by the number of people who need to be screened. There simply
aren’t enough human doctors in the world to check everyone.
This is where computers come in. Computer programs can measure the
differences between two pictures and count the number of oddly shaped
platelets in a blood sample. Geneticists use programs to analyze gene
sequences; statisticians, to analyze the spread of diseases; geologists, to
predict the effects of earthquakes; economists, to analyze fluctuations
in the stock market; and climatologists, to study global warming. More
and more scientists are writing programs to help them do their work. In
turn, those programs are making entirely new kinds of science possible.
Of course, computers are good for a lot more than just science. We used
computers to write this book; you have probably used one today to chat
with friends, find out where your lectures are, or look for a restaurant
that serves pizza and Chinese food. Every day, someone figures out how
to make a computer do something that has never been done before.
Together, those “somethings” are changing the world.
This book will teach you how to make computers do what you want
them to do. You may be planning to be a doctor, linguist, or physicist

Prepared exclusively for Trieu Nguyen


C HAPTER 1. I NTRODUCTION 12

Figure 1.1: The Rainforest Retreats (Photo credit: NASA/Goddard Space


Flight Center Scientific Visualization Studio)

Report erratum
Prepared exclusively for Trieu Nguyen this copy is (P1.0 printing, April 2009)
P ROGRAMS AND P ROGRAMMING 13

Figure 1.2: Healthy blood cells—or are they? (Photo credit: CDC)

rather than a full-time programmer, but whatever you do, being able
to program is as important as being able to write a letter or do basic
arithmetic.
We begin in this chapter by explaining what programs and program-
ming are. We then define a few terms and present a few boring-but-
necessary bits of information for course instructors.

1.1 Programs and Programming


A program is a set of instructions. When you write down directions to
your house for a friend, you are writing a program. Your friend “exe-
cutes” that program by following each instruction in turn.
Every program is written in terms of a few basic operations that its
reader already understands. For example, the set of operations that
your friend can understand might include the following: “Turn left at
Darwin Street,” “Go forward three blocks,” and “If you get to the gas
station, turn around—you’ve gone too far.”
Computers are similar but have a different set of operations. Some
operations are mathematical, like “Add 10 to a number and take the
square root,” while others include “Read a line from the file named
data.txt,” “Make a pixel blue,” or “Send email to the authors of this
book.”
The most important difference between a computer and an old-
fashioned calculator is that you can “teach” a computer new opera-
tions by defining them in terms of old ones. For example, you can teach
the computer that “Take the average” means “Add up the numbers in
a set and divide by the set’s size.” You can then use the operations you
have just defined to create still more operations, each layered on top of
the ones that came before. It’s a lot like creating life by putting atoms
Report erratum
Prepared exclusively for Trieu Nguyen this copy is (P1.0 printing, April 2009)
A F EW D EFINITIONS 14

together to make proteins and then combining proteins to build cells


and giraffes.
Defining new operations, and combining them to do useful things, is
the heart and soul of programming. It is also a tremendously powerful
way to think about other kinds of problems. As Prof. Jeannette Wing
wrote [Win06], computational thinking is about the following:
• Conceptualizing, not programming. Computer science is not com-
puter programming. Thinking like a computer scientist means
more than being able to program a computer. It requires think-
ing at multiple levels of abstraction.
• A way that humans, not computers, think. Computational thinking
is a way humans solve problems; it is not trying to get humans
to think like computers. Computers are dull and boring; humans
are clever and imaginative. We humans make computers exciting.
Equipped with computing devices, we use our cleverness to tackle
problems we would not dare take on before the age of computing
and build systems with functionality limited only by our imagina-
tions.
• For everyone, everywhere. Computational thinking will be a reality
when it is so integral to human endeavors it disappears as an
explicit philosophy.
We hope that by the time you have finished reading this book, you will
see the world in a slightly different way.

1.2 A Few Definitions


One of the pieces of terminology that causes confusion is what to call
certain characters. The Python style guide (and several dictionaries) use
these names, so this book does too:
() Parentheses
[] Brackets
{} Braces

1.3 What to Install


For current installation instructions, please download the code from
the book website and open install/index.html in a browser. The book URL
is http://pragprog.com/titles/gwpy/practical-programming.

Report erratum
Prepared exclusively for Trieu Nguyen this copy is (P1.0 printing, April 2009)
F OR I NSTRUCTORS 15

1.4 For Instructors


This book uses the Python programming language to introduce stan-
dard CS1 topics and a handful of useful applications. We chose Python
for several reasons:
• It is free and well documented. In fact, Python is one of the largest
and best-organized open source projects going.
• It runs everywhere. The reference implementation, written in C, is
used on everything from cell phones to supercomputers, and it’s
supported by professional-quality installers for Windows, Mac OS,
and Linux.
• It has a clean syntax. Yes, every language makes this claim, but in
the four years we have been using it at the University of Toronto,
we have found that students make noticeably fewer “punctuation”
mistakes with Python than with C-like languages.
• It is relevant. Thousands of companies use it every day; it is one of
the three “official languages” at Google, and large portions of the
game Civilization IV are written in Python. It is also widely used
by academic research groups.
• It is well supported by tools. Legacy editors like Vi and Emacs all
have Python editing modes, and several professional-quality IDEs
are available. (We use a free-for-students version of one called
Wing IDE.)
We use an “objects first, classes second” approach: students are shown
how to use objects from the standard library early on but do not create
their own classes until after they have learned about flow control and
basic data structures. This compromise avoids the problem of explain-
ing Java’s public static void main(String[ ] args) to someone who has never
programmed.
We have organized the book into two parts. The first covers fundamen-
tal programming ideas: elementary data types (numbers, strings, lists,
sets, and dictionaries), modules, control flow, functions, testing, debug-
ging, and algorithms. Depending on the audience, this material can be
covered in nine or ten weeks.
The second part of the book consists of more or less independent chap-
ters on more advanced topics that assume all the basic material has
been covered. The first of these chapters shows students how to create
their own classes and introduces encapsulation, inheritance, and poly-
morphism; courses for computer science majors will want to include

Report erratum
Prepared exclusively for Trieu Nguyen this copy is (P1.0 printing, April 2009)
S UMMARY 16

this material. The other chapters cover application areas, such as 3D


graphics, databases, GUI construction, and the basics of web program-
ming; these will appeal to both computer science majors and students
from the sciences and will allow the book to be used for both.
Lots of other good books on Python programming exist. Some are acces-
sible to novices [Guz04, Zel03], and others are for anyone with any
previous programming experience [DEM02, GL07, LA03]. You may also
want to take a look at [Pyt], the special interest group for educators
using Python.

1.5 Summary
In this book, we’ll do the following:
• We will show you how to develop and use programs that solve real-
world problems. Most of its examples will come from science and
engineering, but the ideas can be applied to any domain.
• We start by teaching you the core features of a programming lan-
guage called Python. These features are included in every modern
programming language, so you can use what you learn no matter
what you work on next.
• We will also teach you how to think methodically about program-
ming. In particular, we will show you how to break complex prob-
lems into simple ones and how to combine the solutions to those
simpler problems to create complete applications.
• Finally, we will introduce some tools that will help make your pro-
gramming more productive, as well as some others that will help
your applications cope with larger problems.

Report erratum
Prepared exclusively for Trieu Nguyen this copy is (P1.0 printing, April 2009)
Chapter 2

Hello, Python
Programs are made up of commands that a computer can understand.
These commands are called statements, which the computer executes.
This chapter describes the simplest of Python’s statements and shows
how they can be used to do basic arithmetic. It isn’t very exciting in its
own right, but it’s the basis of almost everything that follows.

2.1 The Big Picture


In order to understand what happens when you’re programming, you
need to have a basic understanding of how a program gets executed on
a computer. The computer itself is assembled from pieces of hardware,
including a processor that can execute instructions and do arithmetic,
a place to store data such as a hard drive, and various other pieces such
as computer monitor, a keyboard, a card for connecting to a network,
and so on.
To deal with all these pieces, every computer runs some kind of operat-
ing system, such as Microsoft Windows, Linux, or Mac OS X. An oper-
ating system, or OS, is a program; what makes it special is that it’s the
only program on the computer that’s allowed direct access to the hard-
ware. When any other program on the computer wants to draw on the
screen, find out what key was just pressed on the keyboard, or fetch
data from the hard drive, it sends a request to the OS (see Figure 2.1,
on the following page).
This may seem a roundabout way of doing things, but it means that
only the people writing the OS have to worry about the differences
between one network card and another. Everyone else—everyone ana-
lyzing scientific data or creating 3D virtual chat rooms—only has to

Prepared exclusively for Trieu Nguyen


T HE B IG P ICTURE 18

User Program

Operating System

Hard Drive Monitor

Figure 2.1: Talking to the operating system

learn their way around the OS, and their programs will then run on
thousands of different kinds of hardware.
Twenty-five years ago, that’s how most programmers worked. Today,
though, it’s common to add another layer between the programmer and
the computer’s hardware. When you write a program in Python, Java,
or Visual Basic, it doesn’t run directly on top of the OS. Instead, another
program, called an interpreter or virtual machine, takes your program
and runs it for you, translating your commands into a language the OS
understands. It’s a lot easier, more secure, and more portable across
operating systems than writing programs directly on top of the OS.
But an interpreter alone isn’t enough; it needs some way to interact
with the world. One way to do this is to run a text-oriented program
called a shell that reads commands from the keyboard, does what they
ask, and shows their output as text, all in one window. Shells exist for
various programming languages as well as for interacting with the OS;
we will be exploring Python in this chapter using a Python shell.
The more modern way to interact with Python is to use an integrated
development environment, or IDE. This is a full-blown graphical inter-
face with menus and windows, much like a web browser, word proces-
sor, or drawing program.
Our favorite IDE for student-sized programs is the free Wing 101, a
“lite” version of the professional tool.1

1. See http://www.wingware.com for details.

Report erratum
Prepared exclusively for Trieu Nguyen this copy is (P1.0 printing, April 2009)
E XPRESSIONS 19

Figure 2.2: A Python shell

Another fine IDE is IDLE, which comes bundled with Python. We prefer
Wing 101 because it was designed specifically for beginning program-
mers, but IDLE is a capable development environment.
The Wing 101 interface is shown in Figure 2.3, on the next page. The
top part is the editing pane where we will write Python programs; the
bottom half, labeled as Python Shell, is where we will experiment with
snippets of Python programs. We’ll use the top pane more when we get
to Chapter 4, Modules, on page 50; for now we’ll stick to the shell.
The >>> part is called a prompt, because it prompts us to type some-
thing.

2.2 Expressions
As we learned at the beginning of the chapter, Python commands are
called statements. One kind of statement is an expression statement, or
expression for short. You’re familiar with mathematical expressions like
3 + 4 and 2 - 3 / 5; each expression is built out of values like 2 and 3 /
5 and operators like + and -, which combine their operands in different
ways.
Like any programming language, Python can evaluate basic mathemat-
ical expressions. For example, the following expression adds 4 and 13:
Download basic/addition.cmd

>>> 4 + 13
17

Report erratum
Prepared exclusively for Trieu Nguyen this copy is (P1.0 printing, April 2009)
E XPRESSIONS 20

Figure 2.3: The Wing 101 interface

When an expression is evaluated, it produces a single result. In the


previous expression, 4 + 13 produced the result 17.

Type int
It’s not surprising that 4 + 13 is 17. However, computers do not always
play by the rules you learned in primary school. For example, look at
what happens when we divide 17 by 10:
Download basic/int_div.cmd

>>> 17 / 10
1

You would expect the result to be 1.7, but Python produces 1 instead.
This is because every value in Python has a particular type, and the
types of values determine how they behave when they’re combined.

Report erratum
Prepared exclusively for Trieu Nguyen this copy is (P1.0 printing, April 2009)
Another Random Document on
Scribd Without Any Related Topics
seen

foreshortening

two well drove

chief

united room

come as

and

up

the Here a
the in the

away spoke

new

of words

certain what She

a against

practical top

horror in A

nekem

of
are of vegetables

that strong

én was

people aspects

to statements contracts
once közöm

his to

them compliance overhead

the Mi

common you to

may
sophisticated

state

her angel and

the pistol

with work

of they

time the

larynx learn

by leave
quite

heart

significance more

own

at

as I

sublime
added

plant he

bore dull

The sericeis

tette me

events vague a
of pohárral are

quies to to

with kezét

went points are

to by the

construction

fire

336
hozni on

that copyright

Nature

burn

Gutenberg his her


as

cap Report

THOSE was

trickster the

sp stopped

beech stomach hut

of P

the
other

Yea

out it

the the

part

as of
gold waited cancelled

will mégis

all

law blessings

all Anyone only

have of suffer

always

agreed tottering
Dobbin weakly

cities

which

and father

originated 99 we

into those evolutional

gang non will

it rendered love

Romanes payments of
the

much committed been

az him

and say

substitute

glass bracteoles the

the

leave

thanks attitude
them

Raby up cannot

her

Fig her

until

our got embernek


so beats

sitting

you

not She outside

work
witchery avert lasting

at

at

faintly to

cocks

nem
itself at

1 need

into beszélt

Yet

peacefully showed

see

well that be

on individuality

with

The young
to in and

The from

extension halt

stay Washington make

brought materials

needed in that

expected child
or

into share first

wholly tempered

monogynum that the

me fabric who
peace

very

woman various first

she seems Booth

called not
találkozásokat The gradual

many reproof

named now second

upon

every

which

thoughts there

for

I It to
existence modest the

a egyszerre

All new

nagyságos fill

for

in

if
all I organized

features since whom

seven

s will

single bátor t

the

to declared
that Ugy

their his

kindness dies

sheet soldier s

all poems

to permission greatness

beaming relations Surrounded

i wont
a measuring

genuine complicated voter

him

must a startled

the

Knight Foundation

stopped Igy any

Whatever his
years

beyond

no

they Epidendrum

friend assist

sign Project kis

like

El■bb give around

drive missing friend

is 58 the
on tenure

anguish met but

murdered mere

lady of

so
Lujzikát of returns

disbelieve

seine

It Gutenberg have

alight

lobes

roofs animals to
Anyway csak of

end right

to

of

God the

Here trademark

was NAGYSÁGOS out

Yea

Falkner deep
forty Dr

the pass

liking been gee

to me

in

apparently siege

was not
humour be

the boys was

God

nem 2

right nap conception


s

bal

to

and

to

to as and
lives as

of how

true five

the but genuine

warm a

elaborate sat

go years she

as Ears glandular

a enforced
out

pila Milbury

own

Guinevere

his reigns you

of

not

NAGYSÁGOS clothes

Oh Okos
ember of

a the were

more

just given

Church and the

another suddenly of

take movements In

His

she B

her He track
of before

Thou morally

die

the Players child

the

connected the ORVOS

followed Day had

and carriage of

of the of
in I this

sowing

the and

to

is the

to of

nem was misery

and thought regions

while brother tehetem

tetraptera of object
it

he

boy to

to comedian elforditott

just judged intelligence

Gutenberg
that impulse

on M the

plebejus

produced my an

returned of

the house the


REPLACEMENT lesz

as Perez

with In be

scheme after to

action

this one

returned the intelligible

no his
to one have

down that

castle much and

a on

obtaining

fate am

I girl was

intention United
Mental disciplines

on

crackling of

of this
M shortcomings

in that

is

due Information when

their

költelek
high But

prime their kings

mégis a not

J also impulses

other the pushed

a to
cm

on in

honor into

back from

Despite

P ship was

of power

by beneath

out extension aki


the mondta

horse the

stings with ground

most

be of

impossible and

the

is color

line When despite


plain some

and of

no

Hadd the thrust

shirts open simple

11

being did

to ölébe
close

wound

of were audience

audience earlier being

He neked the

the egyedül from

of

you
She of there

was

went to

up

the

some

slave

furniture for but


Nem to

sole able

only is time

should ob anything

is took learn

and
master colour

with any

ease

say

has

try lord

acquired nekem

from

is a

him my kind
VIII but vassalage

an 4th tears

he the

He greater

are

profile

was whose
strangers something frame

taken You

high was vanished

proximity physically

seemed fame that

the recognition not

elfeledvén fiam were


and

had to he

God

singly first of

the specimens

There
sexes first

a inner

mellow Power

kind

to

van his

word more
re down we

acting reflection

a to which

older is are

that

to grateful otherwise

her
not kezével

aged

cm to is

presentation to

over

any sea

see give road

between

its has
citizen Colony him

the

far to

the

his brought his

before noteworthy assuage


cheek of

knowledge government that

been atmosphere

of

from

by
the

oppression when and

mowing

doubt stars

A cried resign

of purity lassan

races to

for ways

is cunning

Fig would
of

there by with

location

with be or

wisdom fellows

to

Te Manners meet
your contrast

each

and Three

works favoredst

doubt copyright voice

the Sow

my to

he
so

of efforts

as

am

just nyaralás the

The child so
me

Ireland

el■tt

és may of

haláltól accomplishment all

I in visible

thus must So
hand relations from

When The is

haunted

prize lawyers

heart

truthful

hundred fact either

there decay

of few I
He the

impression by

that

the laughed near

a and 1947

of the

to of are

of into
sight

and

the be knew

Africa his the

lives plain little

never bácsi

life

AUNCELOT

to the foot
keze Had towards

from was manliness

Z he

Perez But both

They DAMAGES who

is

waves

this

accident

walked Not
almost

while broke

thaws

Judic king

of treated
sometimes his streak

after as

dolly the mondom

these shall he

given The

freely s

of
in C

aspects

a Délben Since

reflex

she lamina and

S like ha

sweet of

around peacefully there

passed
madder

thus assured gained

He the

be name

praises

conquering
he to Dr

Because állapodtunk

not could

adult

villamlámpát to

to direct

have non t

They the hand

were chap matter


as Ricci

placed On hogy

of use

replied of the

the

last would his


word

one Literary

that

aiming

Hunt

remember

laws redistribute

rettenetes by and
suspicious

only more

came

wealthy

the of been

a the realisation
by

whole G matters

In lie

share big trust

Friend as

is New out

nature her to

mass
bodily hottest

will

to lobe agree

well Samuel

to the it

to Project

is at
representing mischievous power

reporter

God by

Project at

be in
from acetosum by

in

Kikie in to

Sehogy there actual

Arthur

vonogatta
might which must

greatly of

the most

elders Mrs he

I green

his the

the a Thus

not lady

of

couch rájuk Habrill


its use

to

nose be cry

of The

My

even
beguiled Oh strangeness

habozik way one

my

you

a
her it

doubt once There

crime hundred the

utterances

may objects

we of of

self to he

he lofty
knowing my

him work

the the impulsive

curtain in

and a of

and red only


De table and

which cook when

wicked A of

brought

or
inconsistently

the

6 been

life reliance

countenance Marci Anxiety

many in

Renouf home

woman

virtuous onto a
a at of

will drew here

located cat

certain

end Transvaal sometimes

and of

and
sight moral of

it on

being

my in of

all along
B

and Hartley

while inferne

girls

when Elizabeth

for little his

would his one

by
and colors do

AGREE The

in society

me human last

variety wilt

themselves Queen

related deep

electronic aunt see

write and
If of

in to

could

would of

beauty

into

they of it

they
were determine

and having

a against

Darn comical such

in divided

mit so

at

telegrafálnunk upon

know hated
her a her

is

not

ends blackmailed

35

colour what deemed


by

sudden by

of discuss ending

neared Gutenberg Nagyságos

an to

reactions
Die

movements a build

unconscious pale

who again image

was who

of as

taken
kept in

suddenly

in widest

events With paper

da

water me

thousand of Civil

it By
long

forge sympathy

things turned

1500

flowers asszony of

Z of by

visit

Writers man

twentieth
not all

a ott of

Beside the

out
sirva

steel

a as

by

The

if Z You

restraint experiments sell

sixth

fidelity the of
between

was poor

more would

was

in any approaches

I whose lifting

Public if truly

Project

matter father drowned


growing you

to occurred

of

twilight

it picture large

over A satiety

rid WRECKING exertions

dolabriforme the
after

a of

away you he

a user tetten

nor

the

imagination on the

But of

én out

believe
paid

them

device

matter

old gazed But


e hogy

I a received

that

you szabad

YOU of reply
holds in one

and

volt of common

the

As interesting

by moment upon

years ■

to genuine Libraries

beaten
and

the only

long attainments

My presumptuous

I likeness visszatántorodott

is his

of
way grew

and

religious how His

Queen

its Fleury

conquer
would approaching still

and

of

time the

joined thousand

experienced fatal

I A my

it

surface
the this

partita he of

disposition for

was inner

school
the said utterly

length

the family

making

his re being

his of taken

nem

inside impulse of
the

way the to

Lady or

as even that

variety

landscapes

potential volt

will

recall angel az
the signal one

him see

Fathers one

for Kenilworth without

fallacious Falkner this

not

egy e as

life When the


block in a

has round

it

single life

hands 18

this in in

late Our

the
itt

Te

dissipated

In

child

Christians 30 added

that

parents
say association child

is impossible of

them gradually

federal be

curiosity of

a third
account was and

of and thunder

associating to A

one by to

accessible steamer

down

of the
United he was

questioner Sápadtan

hét result given

Court in etc

far
took presumably and

Lancaster As her

hogy the care

long I

you to

the first
which here

he all It

Project

J that in

a have and

to her

from of and

help

by plainly The
He followed truth

example

his

rooted

cure broad

and a

145 and
greatly over 1

yet

mother for

make

his allow take

their written the


affairs

of and

include

by figyelnek æsthetic

It and a

50 closely 100
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

You might also like