Python® For Kids For Dummies®

Published by: John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, www.wiley.com

Copyright © 2015 by John Wiley & Sons, Inc., Hoboken, New Jersey

Media and software compilation copyright © 2015 by John Wiley & Sons, Inc. All rights reserved.

Published simultaneously in Canada

No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without the prior written permission of the Publisher. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.

Trademarks: Wiley, For Dummies, the Dummies Man logo, Dummies.com, Making Everything Easier, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and may not be used without written permission. Python is a registered trademark of Python Software Foundation. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc. is not associated with any product or vendor mentioned in this book.

LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.

For general information on our other products and services, please contact our Customer Care Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002. For technical support, please visit www.wiley.com/techsupport.

Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com.

Library of Congress Control Number: 2015944529

ISBN 978-1-119-09310-7 (pbk); ISBN 978-1-119-11216-7 (ebk); ISBN 978-1-119-11085-9 (ebk)

Python® For Kids For Dummies®

Visit www.dummies.com/cheatsheet/pythonforkids to view this book's cheat sheet.

Table of Contents

Cover

Introduction

About This Book

Conventions Used

Foolish Assumptions

Icons Used in This Book

Beyond the Book

Where to Go from Here

Week 1: Slithering into Python

Project 1: Getting Started with Python

Python and Why It’s Wonderful

Who’s Using Python

Making Things with Python

Understanding This Book’s Pedagogical Approach

Install Python on Mac OSX

Install Python on Windows

Install Python for Linux

Pin Python to Your Start Menu

Start the Python Interpreter

Use Python’s Built-In Documentation

Put the Kibosh on the Python Interpreter

Find Python Documentation Online

Join the Broader Python Community

Handle Problems

Learn How to Learn

Summary

Project 2: Hello World!

Write Hello World!

Spot and Fix Errors

Work with Literals

Literally Save Your Strings in Variables

Interrupt a Program

Drive Up to Python Keywords

Many Loop, Much Hello

Fill the Screen with Greetings

Make Python Count

Summary

Week 2: Building Guessing Games

Project 3: Guessing Game

Plan the Game

Get Input from the Player

Ask for Input

Make Sure Things Are Equal

Call the Operators

Divide in Python

Compare the Guess to a Number

Compare the Player’s Guess to the Computer’s Number

Tell Players If the Guess Is Wrong

Keep Asking Until the Player Guesses Correctly

Make Python Think of a Random Number

Use Namespaces

Finish Your Guessing Game

Summary

Project 4: Set Up Your Coding Environment

Use the Default Development Environment

Start IDLE

Stash Some IDLE Tricks

Use the IDLE Editor Window

Write Comments in Your Files

Insert Hash Comments

Save Your Shell Contents

Comment Out Code

Indent and Dedent Your Code

Summary

Project 5: A Better Guessing Game

Handle Your Functions

Naming Functions

Add Function Help Text

Make a Function Stub

Rework Your Guessing Game

Find a Logic Problem

Solve the Logic Problem

Notice Double Use of computers_number

Understand How Scope Works

Communicate with Your Function

Send Information to a Function

Give Some Arguments a Default Value

Communicate from the Function

Add a Score

Let the User Quit

The Complete Code

Summary

Week 3: Creating Word Games

Project 6: Hacker Speaker: 1337 Sp34k3r

Waiter, There’s An Object In My String

Dot Your Objects’ Attributes

Meet the List

Go Through the Elements of a List

Create Your Own List

Create a List on Steroids

Test Whether an Element’s In a List

Planning Your Elite Hacker Speaker

Set Up Your File

Make Code Letter Substitutions

Replace a Letter

Let the User Enter a Message

Define Letter Substitutions

Apply all the Substitutions

Use print to Debug the Code

Debug with IDLE’s Debugger

Summary

Project 7: Cryptopy

Slice Off Those Dud Characters

Make a Substitution Table

Set Up Your Cipher

Use the Dictionary

Create an Encryption Dictionary

Use a join

Rewrite the Encryption Function

Write the Decryption Function

Encrypt a Text File

Encrypt and Decrypt from a File

Decrypt from Your Shell

Change the Code to Decrypt Too

The Complete Code

Summary

Project 8: Silly Sentences

Insert Format Strings

Have the Right Number of Values

Use the Tuple Data Type

Get Started on Your Silly Sentences

Fill the Template

Add More Words

The Complete Code

Summary

Week 4: Stepping Up to Object-Oriented Programming

Project 9: Address Book

Your First Class Objects

Create a Class

Create an Instance

Create Class and Instance Attributes

Plan Your Address Book

Set Up Your File and Create a Class

Add Your First Person

Instantiate an Instance Using __init__

Create a Function to Print the Instance

Use __repr__ Magic

Initialize the AddressBook Instance

Find Pickle Power

Add a save Function

Loading a Saved Pickle in the Same Application

Test the load Method

Add an Interface

Fill in the Methods

The Complete Code

Summary

Project 10: Math Trainer

Planning Your Math Trainer

Setting Up

Create Questions

Ask Lots of Questions in a Row

Print Out a Times Table

Print Multiple Tables Across the Screen

Start on the User Interface

Add Quit Functionality

Polishing It Off

Summary

About the Author

Cheat Sheet

Connect with Dummies

End User License Agreement

Guide

Cover

Table of Contents

Begin Reading

Pages

i

ii

iii

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

316

Introduction

Hi! Welcome to the book. You’re going on a tour of all things Python. If you join me and code along with the projects, you’ll have your basic Python programming wings by the end of the book.

Everything in this book you need to know by doing — typing in the code or, better yet, thinking up the code before reading what I’ve done.

About This Book

This book walks you through all the parts you have to know about Python programming. You get examples. I talk about planning programs. And I help link you with the broader Python community so that you can head out there after mastering the projects in this book.

Conventions Used

Keep these things in mind while you read:

Sometimes words are in italics and then I explain the words. Here is an example: “The objects in the list are called elements.” When you see this sentence, you know to keep your eyes peeled for a definition. (Elements are the objects in a list.)

Python code is written in a different font from the other text. Sometimes it’s inline with the text and looks like this: print('Hello World!').

Sometimes it’s a separate block of text, like this:

print('Hello World!')

Some code blocks have a >>> at the front of some lines. I’m showing you what happens when you’re using an interactive Python prompt. You need to type the code that follows the >>> in this book into the Python console that’s running on your computer to see what happens:

>>> my_message = "Hello World!"

>>> print(my_message)

The number of spaces at the front of each line of code is important. The length of your lines isn’t (technically) significant, but Python style guidelines suggest lines with no more than 79 characters (letters, numbers, spaces, or punctuation marks). This book isn’t as wide as your screen; it only lets me show 69 characters in a line. I’ve broken (split) some lines of code in the book. I split them to make sure that the code works and prints the right way. Be careful when you type them in! It’s not always clear how many spaces are at the front of the broken line.

I split lines two ways.

The first is implicitly. Basically, you can split the code in between any pair of parentheses at a comma. Python still sees it as a single line. The second and later parts of a split line should be indented to where the parentheses opened. Here’s an example from the code in Project 9:

values = (e.first_name, e.family_name,

          e.date_of_birth, e.email_address)

Even though you type this as two separate lines, Python sees it as a single line. (Think of it as one long line.) Type this code as you see it, pressing Enter at the end of each line and typing spaces at the start of each line so that the first character in the line is in the right place.

The second way to split a line is explicitly with the backslash character: \ (not /). Here’s an example from Project 9:

raw_input_prompt = "Press: 1 for training,"+\

                   " 2 for testing, 3 to quit.\n"

You type these as two separate lines, with the \ at the end of the first line. However, Python sees it as a single line.

When using the Python interpreter in Projects 2 and 3 only, each new line starts with either … or >>>. If you don’t see these in the code in the book, then the previous line is meant to be typed in as one long line. For example, the following code is from Project 2:

>>> my_second_message = 'This name is a little long. Ideally, try to keep the name short, but not too short.'

This code doesn’t have … or >>> at the start of the second or third line. This means you’re supposed to type it all in before pressing Enter. Only press Enter after typing too short.' at the end, not after typing little long. and but not.

Sometimes the output on your computer may look a little different from what you see in this book. For example, when you run a program in later projects, you might see a restart line. On my screen, all the following text is on a single line:

>>> ================================ RESTART ================================

In Project 4 you see how to automatically indent your code. Until then, each time you need to indent code, do it by pressing the spacebar four times before you add your code. If you have to indent code two levels, press the spacebar eight times (that’s two levels of indent by four spaces per level) before typing your code, and so on. You need to do this for each line of the indented code.

When I’m explaining how code works, I often provide a code template — an outline of how to use the code. A sample template is: help([object name]). In this template, the keyword is help, and it needs to be followed by a pair of parentheses. The square brackets indicate something which is optional. The italics mean you need to fill in. Everything not in italics, type it just like it looks. Using this template, the code help(help) works (it gets help on the help keyword), and so does help(), with nothing inside the parentheses (since [object name] was optional).

Web addresses (URLs) and programming code are in monofont. If you’re reading this book on a device connected to the Internet, you can click the address to visit that website. Try it: www.dummies.com.

Sometimes you need to choose something from a menu. I’m not talking about a burger and fries. I mean actions. For example, I might ask you to choose File ⇒ New File. This means that you go to the File menu and choose New File from it.

The word Ctrl means the Ctrl key on your keyboard. Ctrl+A means that you press the key marked Ctrl while you press the A key. All at the same time. Then release both keys. If you’re using a Mac, your keyboard has a control key — use it. Ctrl-A means press the control key down and press the A key. Then release both keys. Don’t use the option or command keys.

If you’re using a Mac, assume that when I say Enter key, it means the Return key on your keyboard.

Foolish Assumptions

I’ve tried not to make too many assumptions about you in this book. In order to use this book, you need to be able to turn on your computer and navigate the Start Menu (on Windows). To install Python you will need administrator access for the computer you’re installing it on.

Learning anything is slow going to start. You are going to need a bit of determination to make it through the book. Hang in there.

Icons Used in This Book

warning The Warning icon tells you to watch out! This information may save you headaches. In some cases, you could lose data if you don’t heed the warnings.

remember You’re gonna use this information for a long, long time. Commit it to long-term gray matter.

tip The Tip icon marks shortcuts that make programming easier.

codeconnection Coding Connections icons mark information that applies not just to Python, but to coding in general.

Beyond the Book

You can find a bunch more information outside this book. Check out:

Cheat Sheet: This book has an online cheat sheet at www.dummies.com/cheatsheet/pythonforkids. The Cheat Sheet has a list of Python keywords, common built-ins, and selected functions from the standard library. Use it as a quick reference when you’re coding.

Dummies.com online articles and bonus projects: In addition to the projects in this book, there are some bonus projects online. You can get them from www.dummies.com/extras/pythonforkids.

python4kids.brendanscott.com: Visit my Python for Kids blog. Many of the projects in this book started out there. The blog has a dedicated blog entry for each of the projects and has a heap of other things you can try, too. If you’ve got feedback, you can leave it on the blog page that applies.

Where to Go from Here

Right now you should go to Project 1 to read more about what this language can do and to install it. Before you move on to Project 2, make sure you know about Ctrl+C. Then you’re ready to write your first Python program! Move in and out of the projects as you like. The code in each project stands on its own. Be careful though — even though they don’t use code from earlier projects, they often use concepts introduced earlier.

Week 1

Slithering into Python

This week you’re …

Getting Started with Python

Building Hello World!

PROJECT 1

Getting Started with Python

In this project, you’re introduced to Python: where it’s used and what it’s used for. I explain the two current versions of Python. This book is focused on Python 2.7 and I explain why. With my help during this chapter, you install a copy of Python 2.7 (if you don’t already have it installed) and fire it up. I also tell you how to stop once you’ve started.

This project also shows you how to get Python’s documentation, both built in to Python and online. I give you ways to search online for answers to your Python problems, just in case you’ve never searched the Internet before. You also read about the Python community, which is one place you can go for help or new ideas. All that, but no actual programming? No worries. Actual programming starts in .

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!