Tải bản đầy đủ (.pdf) (432 trang)

hello world

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (29.96 MB, 432 trang )

www.it-ebooks.info
Hello World!
Licensed to Deborah Christiansen <>
www.it-ebooks.info
Licensed to Deborah Christiansen <>
www.it-ebooks.info
Hello World!
Computer Programming for Kids
and Other Beginners
WARREN SANDE
CARTER SANDE
MANNING
Greenwich
(74° w. long.)
Licensed to Deborah Christiansen <>
www.it-ebooks.info
For online information and ordering of this and other Manning books, please visit
www.manning.com. The publisher offers discounts on this book when ordered in quantity.
For more information, please contact:
Special Sales Department
Manning Publications Co.
Sound View Court 3B fax: (609) 877-8256
Greenwich, CT 06830 email:
©2009 by Manning Publications Co. All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in
any form or by means electronic, mechanical, photocopying, or otherwise, without prior written
permission of the publisher.
Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial caps
or all caps.


Recognizing the importance of preserving what has been written, it is Manning’s policy to have
the books we publish printed on acid-free paper, and we exert our best efforts to that end.
Recognizing also our responsibility to conserve the resources of our planet, Manning books are
printed on paper that is at least 15% recycled and processed without elemental chlorine.
Manning Publications Co. Development editor: Cynthia Kane
Sound View Court 3B Copyeditors: Andy Carroll, Anna Welles
Greenwich, CT 06830 Technical proofreader: Ignacio Beltran-Torres
Typesetter: Marija Tudor
Illustrator: Martin Murtonen
Cover designer: Leslie Haimes
Fourth, corrected printing August 2009
ISBN 978-1-933988-49-8
Printed in the United States of America
12345678910–MAL–15141312111009
Licensed to Deborah Christiansen <>
www.it-ebooks.info
To our family,
who inspire, encourage, and support us
in school, work, and life
Licensed to Deborah Christiansen <>
www.it-ebooks.info
Licensed to Deborah Christiansen <>
www.it-ebooks.info
vii
Contents
Preface xiii
Acknowledgments xix
About this book xxi
1 Getting Started 1
Installing Python 1


Starting Python with IDLE 2

Instructions,
please 3

Interacting with Python 5

Time to program 7
Running your first program 8

If something goes wrong 9
Your second program 11
2 Remember This—Memory and Variables 14
Input, processing, output 14

Names 16

What’s in a name? 20
Numbers and strings 21

How “variable” are they? 22

The new
me 23
3Basic Math26
The four basic operations 27

Operators 28


Order of
operations 29

Two more operators 30

Really big and really
small 33
Licensed to Deborah Christiansen <>
www.it-ebooks.info
viii CONTENTS
4 Types of Data 38
Changing types 38

Getting more information: type() 41
Type-conversion errors 42

Using type conversions 42
5Input44
raw_input() 45

The print command and the comma 45
Inputting numbers 47

Input from the Web 49
6 GUIs—Graphical User Interfaces 52
What’s a GUI? 52

Our first GUI 53

GUI input 54

Pick your flavor 55

The number-guessing game . . . again 59
Other GUI pieces 60
7Decisions, Decisions62
Testing, testing 62

Indenting 65

Am I seeing double? 65
Other kinds of tests 66

What happens if the test is false? 67
Testing for more than one condition 69

Using “and” 69
Using “or” 70

Using “not” 70
8 Loop the Loop 74
Counting loops 75

Using a counting loop 77

A shortcut—
range() 78

A matter of style—loop variable names 80
Counting by steps 82


Counting without numbers 84
While we’re on the subject . . . 84

Bailing out of a loop—break and
continue 85
9 Just for You—Comments 89
Adding comments 89

Single-line comments 90

End-of-line
comments 90

Multiline comments 90

Commenting style 91
Commenting out 92
10 Game Time 94
Skier 94
11 Nested and Variable Loops 99
Nested loops 99

Variable loops 101

Variable nested loops 102
Even more variable nested loops 103

Using nested loops 105
Licensed to Deborah Christiansen <>
www.it-ebooks.info

ixCONTENTS
12 Collecting Things Together—Lists 112
What’s a list? 112

Creating a list 113

Adding things to a
list 113

What’s the dot? 114

Lists can hold anything 114
Getting items from a list 115

“Slicing” a list 116

Modifying
items 118

Other ways of adding to a list 118

Deleting from a
list 120

Searching a list 121

Looping through a list 122
Sorting lists 123

Mutable and immutable 126


Lists of lists: tables
of data 126
13 Functions 131
Functions—the building blocks 131

Calling a function 133
Passing arguments to a function 134

Functions with more than
one argument 137

Functions that return a value 139

Variable
scope 140

Forcing a global 143

A bit of advice on naming
variables 144
14 Objects 146
Objects in the real world 147

Objects in Python 147
Object = attributes + methods 148

What’s the dot? 149
Creating objects 149


An example class—HotDog 154
Hiding the data 159

Polymorphism and inheritance 159
Thinking ahead 162
15 Modules 164
What’s a module? 164

Why use modules? 164

Buckets of
blocks 165

How do we create modules? 165

How do we use
modules? 166

Namespaces 167

Standard modules 170
16 Graphics 174
Getting some help—Pygame 174

A Pygame window 175
Drawing in the window 178

Individual pixels 186
Images 190


Let’s get moving! 192

Animation 193
Smoother animation 194

Bouncing the ball 196
Wrapping the ball 198
17 Sprites and Collision Detection 202
Sprites 202

Bump! Collision detection 208
Counting time 212
Licensed to Deborah Christiansen <>
www.it-ebooks.info
x CONTENTS
18 A New Kind of Input—Events 217
Events 217

Keyboard events 219

Mouse events 223
Timer events 225

Time for another game—PyPong 227
19 Sound 239
More help from Pygame—mixer 239

Making sounds versus playing
sounds 240


Playing sounds 240

Controlling volume 243
Repeating music 245

Adding sounds to PyPong 245

More wacky
sounds 246

Adding music to PyPong 250
20 More GUIs 254
Working with PythonCard 254

Components 255

Making our GUI
do something 258

The return of event handlers 259

Moving the
button 260

More useful GUIs 260

TempGUI 261

What’s on the
menu? 266

21 Print Formatting and Strings 273
New lines 274

Horizontal spacing—tabs 275

Inserting variables in
strings 277

Number formatting 278

Strings ’n’ things 282
22 File Input and Output 290
What’s a file? 291

Filenames 291

File locations 292
Opening a file 296

Reading a file 297

Text files and binary
files 299

Writing to a file 300

Saving your stuff in files:
pickle 303

Game time again—Hangman 305

23 Take a Chance—Randomness 313
What’s randomness? 313

Rolling the dice 314

Creating a deck of
cards 319

Crazy Eights 323
24 Computer Simulations 336
Modeling the real world 336

Lunar Lander 337

Keeping
time 342

Time objects 343

Saving time to a file 347
Virtual Pet 349
Licensed to Deborah Christiansen <>
www.it-ebooks.info
xiCONTENTS
25 What’s Next? 358
General programming 358

Python 359

Game programming

and Pygame 359

Other Python stuff 360

Look around 362
Appendix A Variable Naming Rules 363
Answers to Self-Test Questions 365
Chapter 1: Getting Started 365

Chapter 2: Remember This—
Memory and Variables 366

Chapter 3: Basic Math 367
Chapter 4: Types of Data 368

Chapter 5: Input 369
Chapter 6: GUIs—Graphical User Interfaces 371

Chapter 7:
Decisions, Decisions 372

Chapter 8: Loop the Loop 374
Chapter 9: Just for You—Comments 375

Chapter 10: Game
Time 376

Chapter 11: Nested and Variable Loops 376
Chapter 12: Collecting Things Together—Lists 377


Chapter 13:
Functions 379

Chapter 14: Objects 380

Chapter 15:
Modules 382

Chapter 16: Graphics 383

Chapter 17: Sprites
and Collision Detection 385

Chapter 18: A New Kind of Input—
Events 385

Chapter 19: Sound 386

Chapter 20: More
GUIs 386

Chapter 21: Print Formatting and Strings 387
Chapter 22: File Input and Output 388

Chapter 23: Take a
Chance—Randomness 390

Chapter 24: Computer Simulations 391
Index 393
Licensed to Deborah Christiansen <>

www.it-ebooks.info
Licensed to Deborah Christiansen <>
www.it-ebooks.info
xiii
Preface
The preface is that part at the beginning of a book that you skip over to get to the good
stuff, right? Sure, you can skip over it if you want (hey, you’re the one turning the pages),
but who knows what you might miss. . . . It’s not very long, so maybe you should give it a
look, just in case.
What is programming?
Very simply, programming means telling a computer to do something. Computers are dumb
machines. They don’t know how to do anything. You have to tell them everything, and you
have to get all the details right.
Duhhhhhhhhh…
Licensed to Deborah Christiansen <>
www.it-ebooks.info
xiv PREFACE
But if you give them the right instructions, they can do many wonderful and amazing things.
A computer program is made up of a number of instructions. Computers do all the great
things they do today because a lot of smart programmers wrote programs or software to tell
them how. Software just means a program or collection of programs that run on your com-
puter, or sometimes on another computer yours is connected to, like a web server.
Python—a language for us and the computer
All computers use binary inside. But most people don’t speak binary very well. We need an
easier way to tell the computer what we want it to do. So people invented programming
languages. A computer programming language lets us write things in a way we can under-
stand, and then translates that into binary for the computer to use.
An instruction is a basic command you give to a
computer, usually to do a single, very specific thing.
Computers “think” using lots and lots

and LOTS of electrical circuits. At
the most basic level, these circuits
are switches that are either ON or
OFF.
Engineers and computer scientists use
1 and 0 to stand for ON and OFF. All
these 1s and 0s are a kind of code
called binary. Binary really just
means “two states.” The two states
are ON and OFF, or 1 and 0.
Did you know: binary digit = bit.
Licensed to Deborah Christiansen <>
www.it-ebooks.info
xvPREFACE
There are many different programming languages. This book will teach you how to use one
of those languages—one called Python—to tell the computer what to do.
Why learn programming?
Even if you don’t become a professional programmer (most people don’t), there are lots of
reasons to learn programming:

The most important is because you want to! Programming can be very interesting and
rewarding, as a hobby or a profession.

If you’re interested in computers and want to know more about how they work and
how you can make them do what you want, that’s a good reason to learn about
programming.

Maybe you want to make your own games, or maybe you can’t find a program that
does exactly what you want or need it to do, so you want to write your own.
No, no, no!

I only speak
human-ese!
1110001101
0001110011
0100101000
>>> print “Hello”
Ah! Now I
get it! Hello!
Hello
About
time!
Licensed to Deborah Christiansen <>
www.it-ebooks.info
xvi PREFACE

Computers are everywhere these days, so there’s a good chance you’ll use computers
at work, at school, or at home—probably all three. Learning about programming will
help you understand computers better in general.
Why Python?
With all the programming languages to choose from (and there are a lot!), why did I pick
Python for a programming book for kids? Here are a few reasons:

Python was created from the start to be easy to learn. Python programs are about the
easiest to read, write, and understand of any computer language I have seen.

Python is free. You can download Python—and many, many fun and useful programs
written in Python—for free. I’ll tell you where in chapter 1.

Python is open source software. Part of what open source means is that any user can
extend Python (create things that let you do more with Python, or do the same things

more easily). Many people have done this, and there is a large collection of free
Python stuff that you can download.

Python isn’t a toy. Although it’s very good for learning programming, it’s also used by
thousands of professionals around the world every day, including programmers at
institutions like NASA and Google. So once you learn Python, you don’t have to switch
to a “real” language to make “real” programs. You can do a lot with Python.

Python runs on different kinds of computers. Python is available for Windows PCs,
Macs, and computers running Linux. Most of the time, the same Python program that
works on your Windows PC at home will work on the Mac at your school. You can use
this book with virtually any computer that has Python. (And remember, if the com-
puter you want to use doesn’t have Python, you can get it for free.)

I like Python. I enjoy learning it and using it, and I think you will, too.
#
!
/
b
i
n
/
e
n
v

p
y
t
h

o
n

#

P
a
g
i
n
a
t
e

a

t
e
x
t

f
i
l
e
,

a
d
d

i
n
g

a

h
e
a
d
e
r

a
n
d

f
o
o
t
e
r

i
m
p
o
r
t


s
y
s
,

t
i
m
e
,

s
t
r
i
n
g

#

I
f

n
o

a
r
g

u
m
e
n
t
s

w
e
r
e

g
i
v
e
n
,

p
r
i
n
t

a

h
e
l

p
f
u
l

m
e
s
s
a
g
e

i
f

l
e
n
(
s
y
s
.
a
r
g
v
)
!

=
2
:

p
r
i
n
t

'
U
s
a
g
e
:

p
y
p
r
i
n
t

f
i
l
e

n
a
m
e
'
s
y
s
.
e
x
i
t
(
0
)
c
l
a
s
s

#

I
n
c
r
e
m

e
n
t

t
h
e

p
a
g
e

c
o
u
n
t
,

a
n
d

r
e
s
e
t


t
h
e

l
i
n
e

c
o
u
n
t

s
e
l
f
.
h
e
a
d
e
r
_
w
r
i

t
t
e
n
=
I
f

n
o

I
f

n
o

a
r
g
u
m
e
n
t
s

a
r
g

u
m
e
n
t
s

1

;

s
e
l
f
.
c
o
u
n
t
=
1

;

#
!
/
b

i
n
/
e
n
v

p
y
t
h
o
n

#

P
a
g
i
n
a
t
e

a

Thinking like a programmer
We’re using Python in this book, but
most of what you’ll learn about pro-

gramming here can be used with any
computer language. Learning to program
with Python will give you a great start
on almost any other language you want
to use in the future.
p
r
i
n
t

>
>
>
H
e
l
l
o

i
f

#
p
r
i
n
t


>
>
>
H
e
l
l
o

i
f

#
p
r
i
n
t

>
>
>
H
e
l
l
o

i
f


#
Licensed to Deborah Christiansen <>
www.it-ebooks.info
xviiPREFACE
The fun stuff
There’s just one other thing I need to mention now. . . .
For kids especially, one of the most fun parts of using a computer is playing games, with
graphics and sound. We’re going to learn how to make our own games and do lots of things
with graphics and sound as we go along. Here are pictures of some of the programs we’ll
be making:
Licensed to Deborah Christiansen <>
www.it-ebooks.info
xviii PREFACE
But I think (as least I hope) you'll find learning the basics and writing your first programs as
enjoyable and rewarding as making those spaceships or skiers zoom around the screen.
Have fun!
Licensed to Deborah Christiansen <>
www.it-ebooks.info
xix
Acknowledgments
This book would never have been started, much less finished, without the inspiration, initia-
tive, and support of my wonderful wife, Patricia. When we couldn’t find a suitable book to
feed Carter’s keen interest in learning about programming, she said, “You should write one.
It would be a great project for you two to work on together.” As is often the case, she was
right. Patricia has a way of bringing out the best in people. So Carter and I started thinking
about what would be in such a book, writing chapter outlines and sample programs, and
finding ways to make it fun and interesting. Once we got started, Carter and Patricia made
sure we finished. Carter would give up bedtime stories to work on the book. And if we
didn’t work on it for a while, I would be reminded, “Daddy, we haven’t worked on the book

for days!” Carter and Patricia reminded me that, if you put your mind to it, you can do any-
thing. And all members of the family, including our daughter Kyra, gave up many hours of
family time while the book was in progress. I thank all of them for their patience and loving
support, which made this book possible.
Writing a manuscript is one thing, getting a book into people’s hands is another. This book
would never have been published without the enthusiastic and persistent support of
Michael Stephens at Manning Publications. Right from the start, he “got it” and agreedthat
there was a need for this kind of book. Michael’s steadfast belief in the project and his con-
tinued patience in guiding a rookie author through the process were immensely valuable
and appreciated.I would also like to say a sincere thank you to all the other folks at Man-
ning who helped make this book happen, in particular Mary Piergies for patiently coordi-
nating all aspects of the production process.
Licensed to Deborah Christiansen <>
www.it-ebooks.info
xx ACKNOWLEDGMENTS
This book would not be the same without Martin Murtonen’s lively and fun illustrations. His
work speaks for itself about Martin’s creativity and talent. But what doesn’t show is how
great he is to work with. It was a pleasure.
One day, I asked my friend and colleague Sean Cavanagh, “How would you do this in Perl?”
Sean said, “I wouldn’t. I would use Python.” So I took the plunge to learn a new program-
ming language. Sean answered many questions when I was learning Python and reviewed
early drafts. He also created and maintains the installer. His help is much appreciated.
I would also like to thank the many people who reviewed the book during its development
and helped prepare the manuscript: Vibhu Chandreshekar, Pam Colquhoun, Gordon
Colquhoun, Dr. Tim Couper, Josh Cronemeyer, Simon Cronemeyer, Kevin Driscoll, Jeffrey
Elkner, Ted Felix, David Goodger, Lisa L. Goodyear, Dr. John Grayson, Michelle Hutton, Horst
Jens, Andy Judkis, Caiden Kumar, Anthony Linfante, Shannon Madison, Kenneth McDonald,
Evan Morris, Prof. Alexander Repenning, André Roberge, Kari J. Stellpflug, Kirby Urner, and
Bryan Weingarten
The final result is much better for their efforts.

WARRENSANDE
I would like to thank Martin Murtonen for his exceptional caricature of me, my mom for let-
ting me go on the computer when I was two years old and for coming up with the idea of
writing a book, and, most importantly, my dad for all of the effort he put into this book with
me and showing me how to program.
CARTER SANDE
Licensed to Deborah Christiansen <>
www.it-ebooks.info
xxi
About this book
This book teaches the basics of computer programming. It’s meant for kids, but anyone who
wants to learn how to program a computer can use it.
You don’t need to know anything about programming to use this book, but you should
know the basics of using your computer. Maybe you use it for email, surfing the Web, listen-
ing to music, playing games, or writing reports for school. If you can do the basic things on
your computer, like starting a program and opening and saving files, you should have no
trouble using this book.
What you need
This book teaches programming using a computer language called Python. Python is free,
and you can download it from several places, including this book’s web site. To learn pro-
gramming using this book, all you need are

this book (of course!).

a computer, with Windows, Mac OS X, or Linux on it. The examples in this book are
done in Windows. (There is some help for Mac and Linux users on the book’s web site:
www.helloworldbook.com
.)

basic knowledge of how to use your computer (starting programs, saving files, and so

on). If you have trouble with this, maybe you can get someone to help you.

permission to install Python on your computer (from your parent, teacher, or whoever
is responsible for your computer).

the desire to learn and try things, even if they don’t always work the first time.
Licensed to Deborah Christiansen <>
www.it-ebooks.info
xxii ABOUT THIS BOOK
What you don’t need
To learn programming with this book, you don’t need

to buy any software. Everything you need is free, and a copy is available on the book’s
web site, www.helloworldbook.com
.

any knowledge of computer programming. This book is for beginners.
Using this book
If you’re going to use this book to help you learn programming, here are a few pointers that
will help you get more out of it:

follow along with the examples

type in the programs

do the quiz questions

don’t worry, be happy!
Follow along with the examples
When you see examples in the book, they’ll look like this:

Always try to follow along and type the programs in yourself. (I’ll tell you exactly how to do
it.) You could just sit in a big, comfy chair and read through this whole book, and you’d
probably learn something about programming. But you’ll learn a whole lot more by doing
some programming.
Type in the programs
The installer program that goes with this book will copy all the example programs to your
hard drive (if you want). The installer is on the book’s web site: www.helloworldbook.com
.
You can also view and download individual examples from the web site, but I encourage you
to type as many of them yourself as possible. Just by typing the programs, you’ll get a “feel”
for programming and for Python in particular. (And we can all use more typing practice!)
if timsAnswer == correctAnswer:
print "You got it right!"
score = score + 10
Licensed to Deborah Christiansen <>
www.it-ebooks.info
xxiiiABOUT THIS BOOK
I’m Carter.
I haven't noticed
anything unusual yet!
Just wanted to
say hi!
Do the quiz questions
At the end of every chapter, there are some questions to practice what you’ve learned. Do
as many as you can. If you’re stuck, try to find someone who knows about programming to
help you. Work through them together—you’ll learn a lot by doing that. Don’t peek at the
answers until you’re done, unless you’re really, really stuck. (Yes, some of the answers are in
the back of the book and on the web site, but like I said, don’t peek.)
Carter says
I wanted to make sure this book was good for

kids—fun and easy to understand.
Luckily, I had some help. Carter is a kid who
loves computers and wants to learn
more about them. So he helped me
to make sure I got this book right. When
Carter noticed something funny or unusual,
or something that didn’t make sense, we show
it like this:
Don't worry about making mistakes.
In fact, make lots of them! I
think making mistakes and figuring
out how to find them and fix them is
one of the best ways to learn.
In programming, your mistakes don't usually
cost you anything except a bit of time. So
make lots of them, learn lots from them, and
have fun.
Hey, mon! Chill.
You can’t break the
computah’, so just
give it a try.
Licensed to Deborah Christiansen <>
www.it-ebooks.info
xxiv ABOUT THIS BOOK
Note to parents and teachers
Python is a free, open source software, and there is no danger installing and using it on
your computers. You can get the Python software—and everything else you need to use
this book—for free at www.manning.com/helloworld
.
The download files are simple to install and use and are free of viruses and spyware.

Books like this used to come with CDs with all the software on them, but now most readers
(and publishers) prefer to use the Internet. If you can’t download the software from the
book’s web site, Manning can send you a CD containing the same files available on the web
site. There’s no cost for the CD, but you’ll have to pay the shipping and handling fee based
on your address.
To get the CD, send an email to with subject line “Hello World! CD.”
If you don’t have email, you can send a fax (609-877-8256), or a good, old-fashioned
letter to:
Hello World CD Request
Manning Publications Co.
Planetarium Station
PO Box 347
New York NY 10024
Licensed to Deborah Christiansen <>
www.it-ebooks.info

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×