John M. Zelle
Wartburg College

Franklin, Beedle & Associates, Inc.

8536 SW St. Helens Drive, Suite D

Wilsonville, Oregon 97070


President and Publisher Production Cover Marketing Order Processing Printed in the U.S.A.

Jim Leisy ( TomSumner Dean Lake Ian Shadburne Christine Collier Krista Brown

Names of all products herein are used for identification purposes only and are trademarks and/or registered trademarks of their respective owners. Franklin, Beedle & Associates, Inc., makes no claim of ownership or corporate association with the products or companies that own them. ©2004 Franklin, Beedle & Associates Incorporated. No part of this book may be reproduced, stored in a retrieval system, transmitted, or transcribed, in any form or by any means—electronic, mechanical, telepathic, photocopying, recording, or otherwise—without prior written permission of the publisher. Requests for permission should be addressed as follows: Rights and Permissions Franklin, Beedle & Associates, Incorporated 8536 SW St. Helens Drive, Suite D Wilsonville, Oregon 97070 Library of Congress Cataloging-in-Publication data may be obtained from the publisher.


Foreword .............................................................................................................................. ix Preface ................................................................................................................................. x

Chapter 1
1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 1.10

The Universal Machine ............................................................................................. 1 Program Power ........................................................................................................ 3 What is Computer Science? ...................................................................................... 3 Hardware Basics ....................................................................................................... 5 Programming Languages .......................................................................................... 6 The Magic of Python ............................................................................................... 9 Inside a Python Program ......................................................................................... 14 Chaos and Computers ............................................................................................. 17 Chapter Summary ................................................................................................... 18 Exercises ................................................................................................................. 20

Computers and Programs


Chapter 2
2.1 2.2 2.3 

2.4 2.5

2.6 2.7

The Software Development Process ...................................................................... 25 Example Program: Temperature Converter .............................................................. 26 Elements of Programs ............................................................................................. 29 2.3.1 Names ........................................................................................................ 29 2.3.2 Expressions ................................................................................................. 30 Output Statements ................................................................................................. 31 Assignment Statements ......................................................................................... 33 2.5.1 Simple Assignment ..................................................................................... 33 2.5.2 Assigning Input ........................................................................................... 35 2.5.3 Simultaneous Assignment ........................................................................... 36 Definite Loops ....................................................................................................... 39 Example Program: Future Value ............................................................................ 42

Writing Simple Programs


2.8 2.9

Chapter Summary ................................................................................................... 45 Exercises ................................................................................................................. 46

Chapter 3
3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8

Numeric Data Types ............................................................................................... 51 Using the Math Library ........................................................................................... 55 Accumulating Results: Factorial ............................................................................... 58 The Limits of Int ..................................................................................................... 61 Handling Large Numbers: Long Ints ....................................................................... 64 Type Conversions .................................................................................................... 66 Chapter Summary ................................................................................................... 68 Exercises ............................................................................................................... 69

Computing with Numbers


Chapter 4
4.1 4.2 4.3 4.4



4.7 4.8

The String Data Type ........................................................................................... 77 Simple String Processing ...................................................................................... 82 Strings, Lists, and Sequences ................................................................................ 85 Strings and Secret Codes ...................................................................................... 87 4.4.1 String Representation .............................................................................. 87 4.4.2 Programming an Encoder ......................................................................... 89 4.4.3 Programming a Decoder ........................................................................... 90 4.4.4 Other String Operations ........................................................................... 94 4.4.5 From Encoding to Encryption ................................................................... 95 Input/Output as String Manipulation .................................................................... 97 4.5.1 Example Application: Date Conversion ..................................................... 97 4.5.2 String Formatting .................................................................................. 102 4.5.3 Better Change Counter .......................................................................... 104 File Processing ..................................................................................................... 106 4.6.1 Multi-Line Strings .................................................................................... 106 4.6.2 File Processing ...................................................................................... 107 4.6.3 Example Program: Batch Usernames ....................................................... 111 4.6.4 Coming Attraction: Objects ................................................................... 112 Chapter Summary ................................................................................................. 113 Exercises .............................................................................................................. 115

Computing with Strings


Chapter 5
5.1 5.2 5.3 5.4 5.5 5.6 5.7

Overview ............................................................................................................ The Object of Objects .......................................................................................... Simple Graphics Programming .............................................................................. Using Graphical Objects ..................................................................................... Graphing Future Value ......................................................................................... Choosing Coordinates ........................................................................................... Interactive Graphics .............................................................................................. 5.7.1 Getting Mouse Clicks ............................................................................... 5.7.2 Handling Textual Input ............................................................................

Objects and Graphics

123 124 125 129 135 143 146 146 148


5.8 Graphics Module Reference .................................................................................. 151 5.8.1 GraphWin Objects ................................................................................... 151 5.8.2 Graphics Objects ................................................................................... 152 5.8.3 Entry Objects .......................................................................................... 155 5.8.4 Displaying Images .................................................................................... 155 5.8.5 Generating Colors .................................................................................... 156 Chapter Summary ................................................................................................. 156 Exercises .............................................................................................................. 157


5.9 5.10

Chapter 6
6.1 6.2 6.3 6.4 6.5

6.6 6.7 6.8

The Function of Functions ................................................................................... 165 Functions, Informally ............................................................................................ 167 Future Value with a Function ............................................................................. 171 Functions and Parameters: The Details ................................................................. 173 Getting Results from a Function ........................................................................... 177 6.5.1 Functions That Return Values ................................................................. 177 6.5.2 Functions that Modify Parameters ......................................................... 181 Functions and Program Structure ......................................................................... 187 Chapter Summary ................................................................................................. 191 Exercises .............................................................................................................. 191

Defining Functions


Chapter 7

7.2 7.3 7.4 7.5

7.6 7.7

Simple Decisions ................................................................................................... 199 7.1.1 Example: Temperature Warnings ............................................................ 200 7.1.2 Forming Simple Conditions .................................................................... 202 7.1.3 Example: Conditional Program Execution ................................................. 204 Two-Way Decisions ............................................................................................... 206 Multi-Way Decisions ............................................................................................. 210 Exception Handling ............................................................................................... 213 Study in Design: Max of Three ............................................................................. 217 7.5.1 Strategy 1: Compare Each to All ............................................................ 218 7.5.2 Strategy 2: Decision Tree ......................................................................... 220 7.5.3 Strategy 3: Sequential Processing .......................................................... 221 7.5.4 Strategy 4: Use Python .......................................................................... 223 7.5.5 Some Lessons .......................................................................................... 224 Chapter Summary ................................................................................................. 225 Exercises .............................................................................................................. 225

Decision Structures


Chapter 8
8.1 8.2 8.3

For Loops: A Quick Review .................................................................................. 233 Indefinite Loops ................................................................................................... 235 Common Loop Patterns ....................................................................................... 237 8.3.1 Interactive Loops ................................................................................... 237 8.3.2 Sentinel Loops ......................................................................................... 239 8.3.3 File Loops ................................................................................................ 242

Loop Structures and Booleans


8.4 8.5

8.3.4 Nested Loops .......................................................................................... 244 Computing with Booleans .................................................................................... 246 8.4.1 Boolean Operators ................................................................................... 246 8.4.2 Boolean Algebra .................................................................................... 250 Other Common Structures ................................................................................... 251 8.5.1 Post-Test Loop ........................................................................................ 251 8.5.2 Loop and a Half ...................................................................................... 254 8.5.3 Boolean Expressions as Decisions ........................................................... 254 Chapter Summary ................................................................................................. 258 Exercises .............................................................................................................. 259

8.6 8.7

Chapter 9
9.1 9.2 9.3 

9.4 9.5 9.6 9.7

Simulating Racquetball ......................................................................................... 265 9.1.1 A Simulation Problem ............................................................................ 266 9.1.2 Analysis and Specification ........................................................................ 266 PseudoRandom Numbers .................................................................................... 268 Top-Down Design .................................................................................................. 270 9.2.1 Top-Level Design ................................................................................... 271 9.2.2 Separation of Concerns ............................................................................ 273 9.2.3 Second-Level Design ................................................................................ 273 9.2.4 Designing simNGames ........................................................................... 275 9.2.5 Third-Level Design .................................................................................. 277 9.2.6 Finishing Up ............................................................................................ 280 9.2.7 Summary of the Design Process ............................................................... 282 Bottom-Up Implementation .................................................................................. 283 9.4.1 Unit Testing ............................................................................................. 283 9.4.2 Simulation Results ................................................................................... 285 Other Design Techniques .................................................................................... 286 9.5.1 Prototyping and Spiral Development ........................................................ 286 9.5.2 The Art of Design ................................................................................. 288 Chapter Summary ................................................................................................. 288 Exercises .............................................................................................................. 289

Simulation and Design


Chapter 10 Defining Classes
10.1 10.2

10.3 10.4 10.5

Quick Review of Objects .................................................................................... Example Program: Cannonball .............................................................................. 10.2.1 Program Specification ............................................................................ 10.2.2 Designing the Program .......................................................................... 10.2.3 Modularizing the Program ....................................................................... Defining New Classes ........................................................................................... 10.3.1 Example: Multi-Sided Dice ..................................................................... 10.3.2 Example: The Projectile Class .................................................................. Data Processing with Class .................................................................................. Objects and Encapsulation ................................................................................... 10.5.1 Encapsulating Useful Abstractions ........................................................... 10.5.2 Putting Classes in Modules ....................................................................

295 296 296 297 301 303 303 307 309 313 313 315


10.5.3 Module Documentation ........................................................................... 315 10.5.4 Working with Multiple Modules ............................................................... 317 Widgets ............................................................................................................... 318 10.6.1 Example Program: Dice Roller ................................................................. 319 10.6.2 Building Buttons ................................................................................... 319 10.6.3 Building Dice ........................................................................................... 323 10.6.4 The Main Program .................................................................................. 327 Chapter Summary ................................................................................................. 328 Exercises .............................................................................................................. 329



10.7 10.8

Chapter 11 Data Collections
11.1 11.2

11.3 11.4 11.5


11.7 11.8

Example Problem: Simple Statistics .................................................................... 337 Applying Lists ...................................................................................................... 339 11.2.1 Lists and Arrays ....................................................................................... 340 11.2.2 List Operations ........................................................................................ 341 11.2.3 Statistics with Lists ................................................................................. 345 Lists of Objects .................................................................................................... 350 Designing with Lists and Classes ........................................................................... 353 Case Study: Python Calculator ........................................................................... 359 11.5.1 A Calculator as an Object ........................................................................ 359 11.5.2 Constructing the Interface ....................................................................... 360 11.5.3 Processing Buttons .................................................................................. 363 Non-Sequential Collections ................................................................................... 367 11.6.1 Dictionary Basics ................................................................................... 367 11.6.2 Dictionary Operations ............................................................................ 368 11.6.3 Example Program: Word Frequency ......................................................... 370 Chapter Summary ................................................................................................. 375 Exercises .............................................................................................................. 376


Chapter 12 Object-Oriented Design
12.1 12.2



The Process of OOD ............................................................................................ Case Study: Racquetball Simulation ..................................................................... 12.2.1 Candidate Objects and Methods .............................................................. 12.2.2 Implementing SimStats ............................................................................ 12.2.3 Implementing RBallGame ......................................................................... 12.2.4 Implementing Player ................................................................................ 12.2.5 The Complete Program ......................................................................... Case Study: Dice Poker ........................................................................................ 12.3.1 Program Specification ............................................................................ 12.3.2 Identifying Candidate Objects .................................................................. 12.3.3 Implementing the Model .......................................................................... 12.3.4 A Text-Based UI ...................................................................................... 12.3.5 Developing a GUI .................................................................................. OO Concepts ....................................................................................................... 12.4.1 Encapsulation .......................................................................................... 12.4.2 Polymorphism ..........................................................................................

385 388 388 390 392 395 396 399 399 400 402 406 409 417 418 418


12.5 12.6

12.4.3 Inheritance ............................................................................................... 419 Chapter Summary ................................................................................................. 421 Exercises .............................................................................................................. 422

Chapter 13 Algorithm Design and Recursion




13.5 13.6

Searching ........................................................................................................... 426 13.1.1 A Simple Searching Problem .................................................................. 426 13.1.2 Strategy 1: Linear Search ......................................................................... 427 13.1.3 Strategy 2: Binary Search ........................................................................ 428 13.1.4 Comparing Algorithms ........................................................................... 429 Recursive Problem-Solving .................................................................................... 431 13.2.1 Recursive Definitions ............................................................................... 432 13.2.2 Recursive Functions ................................................................................. 434 13.2.3 Example: String Reversal ......................................................................... 435 13.2.4 Example: Anagrams ................................................................................. 437 13.2.5 Example: Fast Exponentiation .................................................................. 438 13.2.6 Example: Binary Search ........................................................................... 439 13.2.7 Recursion vs. Iteration ........................................................................... 440 Sorting Algorithms ................................................................................................ 443 13.3.1 Naive Sorting: Selection Sort ................................................................... 443 13.3.2 Divide and Conquer: Merge Sort ............................................................ 445 13.3.3 Comparing Sorts .................................................................................... 447 Hard Problems ..................................................................................................... 450 13.4.1 Towers of Hanoi .................................................................................... 450 13.4.2 The Halting Problem ............................................................................... 455 13.4.3 Conclusion ................................................................................................ 459 Chapter Summary ................................................................................................. 459 Exercises .............................................................................................................. 460


Appendix A Python Quick Reference Appendix B Using Python and IDLE Appendix C Glossary Index

469 479 491 503


When the publisher first sent me a draft of this book, I was immediately excited. Disguised as a Python textbook, it is really an introduction to the fine art of programming, using Python merely as the preferred medium for beginners. This is how I have always imagined Python would be most useful in education: not as the only language, but as a first language, just as in art one might start learning to draw using a pencil rather than trying to paint in oil right away. The author mentions in his preface that Python is near-ideal as a first programming language, without being a “toy language.” As the creator of Python I don’t want to take full credit for this: Python was derived from ABC, a language designed to teach programming in the early 1980s by Lambert Meertens, Leo Geurts, and others at CWI (National Research Institute for Mathematics and Computer Science) in Amsterdam. If I added anything to their work, it was making Python into a non-toy language, with a broad user base and an extensive collection of standard and third-party application modules. I have no formal teaching experience, so I may not be qualified to judge its educational effectiveness. Still, as a programmer with nearly 30 years experience, reading through the chapters I am continuously delighted by the book’s clear explanations of difficult concepts. I also like the many good excercises and questions which both test understanding and encourage thinking about deeper issues. Reader of this book, congratulations! You will be well rewarded for studying Python. I promise you’ll have fun along the way, and I hope you won’t forget your first language once you have become a proficient software developer. —Guido van Rossum


This book is designed to be used as the primary textbook in a college-level first course in computing. It takes a fairly traditional approach, emphasizing problem solving, design, and programming as the core skills of computer science. However, these ideas are illustrated using a non-traditional language, namely Python. In my teaching experience, I have found that many students have difficulty mastering the basic concepts of computer science and programming. Part of this difficulty can be blamed on the complexity of the languages and tools that are most often used in introductory courses. Consequently, this textbook was written with a single overarching goal: to introduce fundamental computer science concepts as simply as possible without being simplistic. Using Python is central to this goal. Traditional systems languages such as C++, Ada, and Java evolved to solve problems that arise in large-scale programming, where the primary emphasis is on structure and discipline. They were not designed to make writing small- or medium-scale programs easy. The recent rise in popularity (in industry, if not necessarily in academia) of scripting (sometimes called “agile”) languages, such as Python, suggests an alternative approach. Python is very flexible and makes experimentation easy. Solutions to simple problems are simply and elegantly expressed. Python provides a great laboratory for the neophyte programmer. Python has a number of features that make it a near-perfect choice as a first programming language. The basic structures are simple, clean, and well designed, which allows students to focus on the primary skills of algorithmic thinking

This book presents a simple-to-use graphics package (provided as a Python module) that allows students both to learn the principles of computer graphics and to practice object-oriented concepts without the complexity inherent in a full-blown graphics library and eventdriven programming. For example. Rather.” It is a realworld. But Python is not a “toy language. Students love working on programs that include graphics. the introduction of string methods makes a perfect bridge to the use of objects. there are other features of this book designed to make it a gentler introduction to computer science. This is done purposely in an effort to meet students “where they’re at. which are generally preferable. Similarly. this book is intended as an introduction to computing. The book is packed with complete programming examples to solve real problems.” Most beginning students know nothing about strings or objects. I have purposely avoided certain Python features and idioms that are not generally found in other languages. . namely strings and string functions. production language that is freely available for virtually every programming platform and comes standard with its own easy-to-use integrated programming environment. Python is used to illustrate fundamental principles of design and programming that apply in any language or computing environment. There are already many good books about Python on the market. teaching Python is not the main point of this book. The best part is that Python makes learning to program fun again. · Interesting examples. From there. the chapter on the string data type uses functions from the string library before introducing string methods. Thus. but they are already quite familiar with the basic concepts of computation in the context of mathematics (numbers).Preface xi and program design without getting bogged down in arcane language details. Besides using Python. Concepts learned in Python carry over directly to subsequent study of systems languages such as Java and C++. it is a natural progression to start with numeric algorithms and functions and extend those ideas to a less familiar data type. Although I use Python as the language. In some places. there are places in the book where the “Pythonic” way of doing things has been eschewed for pedagogical reasons. Some of these features include the following: · Extensive use of computer graphics.

· Just-in-time object coverage. Students learn multiple design techniques.” but gradually introduces object concepts after a brief initial grounding in the basics of imperative programming. Additionally. Ideas that take more time to master are introduced in early chapters and reinforced in later chapters. and Computing with Numbers) are essential introduction and should probably be covered in order. Exercises at the end of every chapter provide ample opportunity for students to both reinforce chapter material and practice new programming skills. The narrative style of this book introduces key computer science concepts in a natural way as an outgrowth of a developing discussion. though not necessarily covering every section in depth. giving them time to assimilate an increasing level of detail as they progress. including top-down (functional decomposition). · Extensive end-of-chapter problems. · Flexible spiral coverage. My classes cover virtually all of the material in the first twelve chapters in order. Chapters 1–3 (Computers and Programs. This book is neither strictly “objects early” nor “objects late. One or two topics from Chapter 13 (Algorithm Design and Recursion) are generally interspersed at appropriate places during the term. Since the goal of the book is to present concepts simply. the textbook material is flexible enough to accommodate other approaches. Writing Simple Programs. The first several sections of Chapter 4 (Computing with Strings) are also fundamental to mate- . and object-oriented methods.xii Preface · Readable prose. Still. each chapter is organized so that students are introduced to new ideas in a gradual way. I have tried to keep the material relatively flexible. there is probably more material here than can be covered in a typical one-semester introduction. Coverage Options In keeping with the goal of simplicity. Recognizing that different instructors prefer to approach topics in other orders. The proper place for the introduction of object-oriented techniques is an ongoing controversy in computer science education. I have tried to avoid random facts or tangentially related sidebars. spiral (prototyping). I have tried to limit inclusion of material that would not be covered in a first course.

Much that I have learned from those books has undoubtedly found its way into these pages. who offered unflagging support. There are a few specific authors whose approaches have been so important that I feel they deserve special mention. and Associates. Many people have contributed either directly or indirectly to the production of this book. I also learned much about teaching computer science from Nell Dale. Dewdney has always had a knack for finding simple examples that illustrate complex issues. and Josef Breutzmann. Instructors wishing to emphasize object-oriented design need not spend much time on Chapter 9. Beedle. I also owe a debt to wonderful textbooks from both Owen Astrachan and Cay Horstmann. including Christine Collier and Krista Brown. Lib Bingham. if desired. but the material in Chapter 11 could easily be moved earlier. and especially Jim Leisy. Thanks also goes to all of my students. I also want to acknowledge the fine folks at Franklin. I have also received much help and encouragement from my colleagues at Wartburg College: Lynn Olson. A. I have borrowed a few of those and given them new legs in Python. should the instructor want to cover lists (arrays) before covering design. and to Wartburg College for giving me sabbatical support to work on the book. for whom I was fortunate enough to serve as a TA when I was a graduate student at the University of Texas. and Dean Lake. Acknowledgments My approach to CS1 has been influenced over the years by the many fine textbooks that I have read and used for classes. Chapters 9–12 are written to be taken in order. but the later sections (String formatting and File Processing) can be delayed until later in the course. Decision Structures. Chapter 13 contains more advanced material that may be covered at the end or interspersed at various places throughout the course. but most importantly. Chapters 5–8 (Graphics and Objects. Last. Defining Functions. Tom Sumner. who .K. who turned my pet project into a real textbook. who have taught me so much about teaching.Preface xiii rial throughout the book. and Loop Structures and Booleans) are designed to stand independently and can be taken in virtually any order. The graphics library I introduce in Chapter 5 was directly inspired by my experience teaching with a similar library designed by Horstmann. I am grateful to Dave Reed at Capital University who used early versions and offered numerous insightful suggestions. I acknowledge my wife. who supplied many project ideas.

and morale booster while putting up with me throughout this project. advisor.NEL 2HAB=?A has served as editor. I also thank the following individuals who read and commented on parts or all of the manuscript: Rus May Carolyn Miller Guido van Rossum Jim Sager Christine Shannon Paul Tymann Suzanne Westbrook Morehead State University North Carolina State University Elemental Security California State University. Chico Centre College Rochester Institute of Technology University of Arizona —JMZ .

’ To understand the form and function of computer programming languages. A modern computer can be defined as “a machine that stores and manipulates information under the control of a changeable program.” There are two q . ’ To begin using the Python programming language. make movies. design airplanes. Computers are used to predict the weather. ’ To understand the basic design of a modern computer. and control factories. “•”–“ —Y˜™‚pdfe™‡‰„‚hgI‘ihjlkminƒo˜™‡pe™‚ Almost everyone has used a computer at one time or another. perform financial transactions. ’ To learn what computer scientists study and the techniques that they use. Perhaps you have played computer games or used a computer to write a paper or balance your checkbook. Have you ever stopped to wonder what exactly a computer is? How can one device perform so many different tasks? These basic questions are the starting point for learning about computers and computer programming.QSRUTWVYXa`cb d ¤ ¥§e fhg©¨piq u rs¦t  iq¥pvwiqrse x€y31‚„ƒ†…ˆ‡‰„‚„‘ ’ To understand the respective roles of hardware and software in a computing system. ’ To learn about chaotic models and their implications for computing. run businesses.

then the computer performs a different sequence of actions. What exactly does this mean? A computer program is a detailed. Every computer is just a machine for executing (carrying out) programs. but there are literally thousands of other kinds of computers both real and theoretical. provided you can describe the task to be accomplished in sufficient detail. There are many different kinds of computers. If we change the program. but the program controlling the machine changes. We would not consider either the calculator or the gas pump as full-fledged computers.r s@tvuxwzy|{I}†~€s‚Hƒ„w€…†y|{‡}$ˆ‰uxŠŒ‹Ž3}$‚I1}"uxƒoˆ key elements to this definition. performs a different task. They are different from computers in that they are built to perform a single. the pump uses certain inputs: the current price of gas per gallon and signals from a sensor that reads the rate of gas flowing into your car. This means we can put information into a computer. with suitable programming. each computer can basically do all the things that any other computer can do. The first is that computers are devices for manipulating information. useful forms. The pump transforms this input into information about how much gas you took and how much money you owe. You might be familiar with Macintoshes and PCs. It can do anything you want it to do. This is where the second part of our definition comes into the picture: Computers operate under the control of a changeable program. at the next moment a financial planner. and then output or display the information for our interpretation. Computers are not the only machines that manipulate information. One of the remarkable discoveries of computer science is the realization that all of these different computers have the same power. and it can transform the information into new. although modern versions of these devices may actually contain embedded computers. and later on. In this sense. step-by-step set of instructions telling a computer exactly what to do. and hence. When you use a simple calculator to add up a column of numbers. As you fill your tank. the PC that you might have sitting on your desk is really a universal machine. Another simple example is a gas pump. The machine stays the same. you are entering information (the numbers) and the calculator is processing the information to compute a running sum which is then displayed. specific task. It is this flexibility that allows your PC to be at one moment a word processor. an arcade game. Now that’s a powerful machine! .

computers would just be expensive paperweights. Non-programmers often feel they are slaves of their computers. But others can also benefit from the experience. However. The process of creating software is called programming. A famous computer scientist named Edsger Dijkstra once quipped that computers are to computer science what telescopes are to astronomy. especially the ability to analyze complex systems by reducing them to interactions of understandable subsystems. Programming is a fundamental part of computer science and is. regardless of your occupation. many people actually write computer programs as a hobby. Computers are so commonplace in the business world today that the ability to understand and program computers might just give you the edge over your competition. As you probably know. and that is the main focus of this book. It is the software that determines what any computer can do. It is an intellectually engaging activity that allows people to express themselves through useful and sometimes remarkably beautiful creations. More than a few liberal arts majors have turned a couple of computer programming classes into a lucrative career option. are truly in control. Computers have become a commonplace tool in our society. Programmers. Computer programming is a challenging activity. “•”– ž ˜Ÿio…€‡‘¡ ¢™£›¥¤§¦n…¨‚™gª©«ƒ¬‡‚™e™ƒ­‚h® You might be surprised to learn that computer science is not the study of computers. Good programming requires an ability to see the big picture while paying attention to minute detail. Not everyone has the talent to become a first-class programmer. Believe it or not. therefore. Programming also develops valuable problemsolving skills. There are lots of good reasons to learn programming.~€ rH3}‘‚€1}"uxƒ€H‚Œ’“{‡} “•”–• —˜gI™hšqgIi•› —Ž™„œ‚™g ” You have already learned an important lesson of computing: Software (programs) rules the hardware (the physical machine). then this book is for you. virtually anyone can learn how to program computers. important to anyone interested in becoming a computer professional. If you want to become a more intelligent user of computers. however. Programming can also be loads of fun. this book will help you to become a programmer. The com- . With some patience and effort on your part. just as not everyone has the skills to be a professional athlete. Without software. programmers are in great demand. Understanding the strengths and limitations of this tool requires an understanding of programming.

The algorithms that solve these problems take too long or require too much memory to be of practical value. analyzing. however. artificial intelligence. but it is not itself the object of study. human-computer interaction.¯ s@tvuxwzy|{I}†~€s‚Hƒ„w€…†y|{‡}$ˆ‰uxŠŒ‹Ž3}$‚I1}"uxƒoˆ puter is an important tool in computer science. It may mean that I’m just not smart enough. These days. we develop a step-by-step process for achieving the desired result. Analysis is the process of examining algorithms and problems mathematically. experimentation is often needed in order to verify and refine the analysis. As you begin writing your own programs. computer scientists rely on experimentation. Even when theoretical analysis is done. Analysis of algorithms is an important part of computer science. analysis. and experimentation.” The design of algorithms is one of the most important facets of computer science. In such cases. Other problems are intractable. you will get plenty of opportunities to observe your solutions in action. then the problem is solvable. That is. This is where analysis comes in. the real question is What processes can we describe? Put another way. For most problems. the fundamental question of computer science is simply What can be computed? Computer scientists use numerous techniques of investigation to answer this question. In this book you will find techniques for designing and implementing algorithms. all of which fall under the general umbrella of computing. One weakness of design is that it can only answer the question What is computable? in the positive. One way to demonstrate that a particular problem can be solved is to actually design a solution. Computer scientists call this an algorithm. The three main ones are design. Often we require empirical testing of the system to determine that this bottom-line has been met. the bottom line is whether a working. Some example areas include networking. Computer scientists have shown that some seemingly simple problems are not solvable by any algorithm. reliable system can be built. I have defined computer science in terms of designing. they actually implement systems and then study the resulting behavior. Some problems are too complex or ill-defined to lend themselves to analysis. or I haven’t hit upon the right idea yet. and this is certainly the core of the academic discipline. computer scientists are involved in far-flung activities. throughout this book we will touch on some of the fundamental principles. However. Since a computer can carry out any process that we can describe. Chapter 13 has examples of unsolvable and intractable problems. and evaluating algorithms. failing to find an algorithm does not mean that a problem is unsolvable. computa- . If I can devise an algorithm. That’s a fancy word that basically means “recipe.

The memory stores programs and data. software engineering. databases. management information systems. The CPU can only directly access information that is stored in main memory (called RAM for Random Access Memory). It’s a bit like driving a car. Although different computers can vary significantly in specific details. Wherever computing is done. but understanding the underlying principles will help you master the steps we go through to put our programs into action. “•”|µ ¶ªingI·„œingI‚p¸liŸ‘ˆ‡ƒ¬‘ You don’t have to know all the details of how a computer works to be a successful programmer. step on the accelerator. You could learn to drive by just memorizing what to do. tional science (using powerful computers to model scientific data). Main memory is fast. and computer security. when the power is . web and multimedia design. etc. The central processing unit (CPU) is the “brain” of the machine.~x ¯ °4u‡}"‹‡’†uI}${²±ˆuŒˆ 6 ³ ˆ ´ CPU Input Devices Output Devices Main Memory Secondary Memory   Figure . Knowing a little about internal combustion engines helps to explain why you have to do things like fill the gas tank. This is where all the basic operations of the computer are carried out. but a little more knowledge makes the whole process much more understandable. start the engine. Figure . the skills and knowledge of computer science are being applied. : Functional View of a Computer. at a   higher level all modern digital computers are remarkably similar. Let’s take a moment to “look under the hood” of your computer. but it is also volatile. The CPU can perform simple arithmetic operations like adding two numbers and can also do logical operations like testing to see if two numbers are equal. shows a functional view of a computer. That is.

there must also be some secondary memory that provides more permanent storage. like they do in science fiction movies. It would be nice if we could just tell a computer what to do using our native language. So what happens when you fire up your favorite game or word processing program? First. the CPU sends it to one or more output devices. when information needs to be displayed. “•”|º —˜gI™hšqgIi•›¥›»‡peŸšs¼Ÿi•enšq¦™ioš•‚o‘ Remember that a program is just a sequence of instructions telling a computer what to do. It doesn’t seem very exciting. You are probably familiar with common devices such as a keyboard. how long will it take to reach planet Alphalpha at maximum warp?”) Unfortunately. In a modern personal computer. does it? But the computer can execute this stream of simple instructions with blazing speed. and the appropriate action carried out. Humans interact with the computer through input and output devices. Optical media such as CD (compact disc) and DVD (digital versatile disc) are also common. we need to provide those instructions in a language that a computer can understand. For example. Once the instructions are loaded. if I say: “I saw the man in the park with the telescope. Then the next instruction is fetched. instruction after instruction. or did the man? And who was in the . the instructions that comprise the program are copied from the (more) permanent secondary memory into the main memory of the computer. and monitor (video screen). Even if computers could understand us. Natural language is fraught with ambiguity and imprecision. the information in the memory is lost. human languages are not very well suited for describing complex algorithms. Similarly. Technically the CPU follows a process called the fetch-execute cycle. execute. designing a computer to understand human language is still an unsolved problem. the CPU starts executing the program.¹ s@tvuxwzy|{I}†~€s‚Hƒ„w€…†y|{‡}$ˆ‰uxŠŒ‹Ž3}$‚I1}"uxƒoˆ turned off. despite the continuing efforts of many top-flight computer scientists (including your author). This is really all the computer does from the time that you turn it on until you turn it off again: fetch. Thus. and the computer does amazing things. decode. decoded and executed. The first instruction is retrieved from memory. this is usually some sort of magnetic medium such as a hard disk (also called a hard drive) or floppy. Information from input devices is processed by the CPU and may be shuffled off to the main or secondary memory. zipping through millions of instructions each second. The cycle continues. (“Computer. decoded to figure out what it represents.” did I have the telescope. Put enough simple instructions together in just the right way. mouse. Obviously.

~x ´P¨½}$‚IH}$uxƒ•ƒ 6 Š†Ž¾‡uxŠŒ1…vuŒI{zˆ ¿ park? We understand each other most of the time only because all humans share a vast store of common knowledge and experience. the addition of two numbers can be ÑÈßàÂcácË . it’s even more complicated than this because the instructions and numbers are represented in binary notation (as sequences of 0s and 1s). and the process of writing an algorithm in a programming language is called coding. These special notations are called programming languages. Figure . expressed more naturally: but we need some way to translate the high-level language into the machine language that the computer can execute. they are designed to be used and understood by humans. Scheme. All of the languages mentioned above are examples of high-level computer languages. Although these languages differ in many details. A compiler is a complex computer program that takes another program written in a high-level language and translates it into an equivalent program in the   machine language of some computer. ÀPÁÂHÀÄ1ŽÆÈǐÉ1ÊˈÆHÌWÍHÌÁxÊcÊÎÆxÊ3ÁHÌPÏÐÀPÁÑHÂ1ĽÒ1ÁÓÇ¡ÔPÕPÕÎÖUҀǨÄÁUÄ1ŽÆW×1ØHÙ ÀPÁÂHÀÄ1ŽÆÈǐÉ1ÊˈÆHÌWÍHÌÁxÊcÊÎÆxÊ3ÁHÌPÏÐÀPÁÑHÂ1ĽÒ1ÁÓÇ¡ÔPÕPÕ¨ÔÐҀǨÄÁUÄ1ŽÆW×1ØHÙ Ú ÃPÀÄHňÆcÄPۈÁÈÇPÉHʨ˽ÆHÌ3ÜcҀÇÐÄ1ŽÆW×1ØHÙ ÜxĨÁH̨ÆUÄHňÆcÌƽ܇É3À£Ä¡Ò€Ç¨ÄÁÝÀPÁÑH£Ä3Ò1ÁÓÇ¡ÔPÕPÕÞ This seems like a lot of work to add two numbers. Even then. Perl. Every structure in a programming language has a precise form (its syntax) and a precise meaning (its semantics). Although they are precise. There are two ways to do this: a high-level language can either be compiled or interpreted. In fact. That’s a lot easier for us to understand. Strictly speaking. unambiguous syntax and semantics. You may have heard of some other languages. or BASIC. Java. such as C++. shows a block diagram of the . doesn’t it? Actually. computer hardware can only understand a very low-level language known as machine language. It is the language that we will use throughout this book. Computer scientists have gotten around this problem by designing notations for expressing computations in an exact and unambiguous way. The instructions that the CPU actually carries out might be something like this. they all share the property of having well-defined. Suppose we want the computer to add two numbers. programmers often refer to their programs as computer code. Python is one example of a programming language. miscommunication is commonplace. A programming language is something like a code for writing down the instructions that a computer will follow. In a high-level language like Python.

â s@tvuxwzy|{I}†~€s‚Hƒ„w€…†y|{‡}$ˆ‰uxŠŒ‹Ž3}$‚I1}"uxƒoˆ Source Code (Program) Compiler Machine Code Inputs Running Program Outputs   Figure . Each kind of com- . but interpreted languages lend themselves to a more flexible programming environment as programs can be developed and run interactively. : Interpreting a High-Level Language. the interpreter and the source are needed every time the program runs. compiling process. The machine language of a computer is created by the designers of the particular CPU. The translation process highlights another advantage that high-level languages have over machine language: portability. since the translation is done once and for all. and the resulting machine code is a program that the computer can directly execute. : Compiling a High-Level Language Source Code (Program) Computer Running an Interpreter Outputs Inputs  ! Figure . An interpreter is a program that simulates a computer that understands a high-level language. Figure . Rather than translating the source program into a machine language equivalent. The high-level program is called source code. Compiled programs tend to be faster. once a program is compiled. The dashed line in the diagram represents the execution of the machine code. the interpreter analyzes and executes the source code in ! struction by instruction as necessary. The difference between interpreting and compiling is compiling is a oneshot translation. illustrates the process. it may be run over and over again without further need for the compiler or the source code. In the interpreted case.

those spirits only understand a very arcane language that we do not know. and it directs the underlying spirits to carry out our demands. The ultimate goal is to make the computer do our bidding. When you first start the interpreter program. What we need is a friendly Genie that can direct the spirits to fulfill our wishes. Our Genie is a Python interpreter. Unfortunately. We communicate with the Genie through a special language of spells and incantations (i. On the other hand. we will write programs that control the computational processes inside the machine.~€ ¹H£ã„t†{qä²uŒ 6 ³ ‚‡åæHç†yèt†‚HŠ é puter has its own machine language. if I design a new computer. The best way to start learning about Python is to let our Genie out of the bottle and try some spells. You can start the Python interpreter in an interactive mode and type in some commands to see what happens. you may see something like the following: ؐÏPÄHňÁ£Ç¡Ô„ïðÞòñôóÎ֓õlöˆÂ1Ì»ÖxÞÝÔHՐÕPބõfÖPÖ­÷èÔHøn÷ùՐÞ3ú ûpü א×ÝԄïðýø€ÔPՐÕPՐÕPþÞÎÖÿ¡ ñ  ˆÆH£ à ¢½Â£¥ Ä ¤3ÒIǐ§ É ¦ÝþoïðÞÝԄïðý© ø ¨3ÖPÖxÕ3 ú €ÁÓÇÿÀҀÇP§ É ¦¨Ô  Ï ½ Æ ôŽƨ À 3 õ xÑ£Á ¨ÏÌ3" Ò !1Ũ# Ä Î$ õ xÑxÌÆPÈÒÓÄ3% Ü Á1& Ì IÀ¨ÒÑ1ÆÓÇ@ÜÓ' Æ ͐ÁHÌÈÊÎÁ1ÌÆÐÒILj͐ÁHÌ£ÊÎÂ1ĽÒ1Á£Çhï (©()( The 01020 is a Python prompt indicating that the Genie is waiting for us to give it a command. it’s time to start having fun with Python. a complete command is called a statement. The computational processes inside the computer are like magical spirits that we can harness for our work. and then any program written in Python can be run on my new computer. a program written in a high-level language can be run on many different kinds of computers as long as there is a suitable compiler or interpreter (which is just another program). Here is a sample interaction with the Python interpreter: Ä 3¢ˆÆÀÀHÁ„5 õ 4ÁḦÀ16 à  (©()( ̽ҀÇ ¢ˆÆÀÀHÁ„5 õ 4ÁḦÀ1à . I can also program a Python interpreter for it. as is.. Python). In programming languages.e. A program for a Pentium CPU won’t run on a Macintosh that sports a PowerPC. For example. You have already seen that there is no magic in this process. “•”–ê —Y˜™‚pkëinš§‡ƒ»™„ìY—îí¬…Î˜Ÿ™£e Now that you have all the technical details. To this end. We can give instructions to the Python interpreter. but in some ways programming feels like magic.

We have told Python ňƨÀÀHÁ what should happen when the function is used as a command. It’s a good idea to fire up Python and try the examples yourself. Here is an example of creating a new ŽƐÀÀPÁ : function called (©()( èÆHÍUŽƨÀPÀPÁ¬ñIú¬÷ Ì3ÒIÇA Ä 8¢ˆÆÀÀPB Á  Ì3ÒIÇA Ä vאÁ€C Ê É¨ÄÆ1ÌÎÜ Â£ÌE Æ D1ɐ Ç  (©()( ňƨÀPÀPÁ The first line tells Python that we are defining a new function called . we haven’t actually asked Python to perform it yet. Python ¨Ì3Ò€Ç¨Ä statement responds on the next line by printing the phrase. Usually we want to move beyond snippets and execute an entire sequence of statements. following lines are indented to show that they are part of the ÇĨÆHÌ ( The blank line (obtained by hitting the F G key twice) lets Python know that the definition is finished. Here’s what happens when we use ňƨÀÀHÁ our command: (©()( ŽƐÀÀPÁ¬ñIú ¢ˆÆÀÀHÁ אÁ€C Ê PÉÄÆ1ÌÎÜYÂ1ÌE Æ D1ÉÇ (©()( . A function is invoked by typing its name. World. Python lets us put a sequence of statements together to create a brand-new command called a function. which is 5. The ŽƨÀPÀPÁ function. The first statement asks Python to display the literal phrase Hello. The third combines these two ideas. Notice that the definition did not cause anything to happen. The second ¨Ì3ÒIÇÄ asks Python to print the sum of 2 and 3. Snippets of interactive sessions are sprinkled throughout this book. When you see the Python prompt 01010 in an example.~87 (©()( 9 (©()( ̽ҀÇÄÝÔWáÝÞ s@tvuxwzy|{I}†~€s‚Hƒ„w€…†y|{‡}$ˆ‰uxŠŒ‹Ž3}$‚I1}"uxƒoˆ ̽ҀÇ Ä IÔcáÐހß63õ ÔWáÝÞ ÔcáÐހß@9 ̽ҀÇÄ Here I have tried out three examples using the Python statement. Python prints the part in quotes “2 + 3 =” followed by the result of adding 2 + 3. and the interpreter responds with another prompt. that should tip you off that an interactive session is being illustrated. This kind of interaction is a great way to try out new things in Python.

and you can create one using any program for editing text. like a notepad or word processor program (provided you save your program as a “plain text” file). (©()( !P̨ƐÆHĉñ R1Á£ÅPÇÓú ¢ˆÆÀÀHS Á R1ÁÓÅÇ ¢ˆÁ£Û¡Â1̨ÆcÏÁ£Q É P Ï £ú (©()( !P̨ƐÆHĉñ  ʓÒ1À16 G ¢ˆÆÀÀHÁ Ê@ÒHÀ1Ï G ¢ˆÁ£Û¡Â1̨ÆcÏÁ£Q É P (©()( !P̨ƐÆ1Ä Can you see what is happening here? When we use we can send different names to customize the result. For the time being. but you still need to include them when defining and using functions. Our program will illustrate a mathematical concept known as chaos. One problem with entering functions interactively at the Python prompt like this is that the definitions go away when we quit Python.~€ ¹H£ã„t†{qä²uŒ 6 ³ ‚‡åæHç†yèt†‚HŠ ¨Ì3ÒIÇÄ Å½Æ¨ÀPÀPÁ Do you see what this does? The two statements from the function are executed in sequence. You may be wondering about the parentheses in the definition and use of ŽƐÀÀHÁ . we have to type them all over again. A programming environment is specifically designed to help programmers write programs and includes features such as automatic indenting. Programs are usually created by typing definitions into a separate file called a module or script. and interactive development. Let’s illustrate the use of a module file by writing and running a complete program. This file is saved on a disk so that it can be used over and over again. If we want to use them again the next time. our functions will not use parameters. so the parentheses will be empty. Commands can have changeable parts called parameters that are placed within the parentheses. First the definition: Í !PÌÆPÆHĉH ñ ½Æ1ÌÎÜÓÁ£Ç“ú­÷ (©()( èÆH¥ Ì3ÒIÇA Ä 8¢ˆÆÀÀPB Á ÎI õ ˆÆHÌ3Ü£Á£Ç Ì3ÒIÇA Ä 8¢ˆÁ£Û¡Â1ÌÆcϨÁ£Q É PQ ~€~ Now we can use our customized greeting. color highlighting. A special type of program known as a programming environment simplifies the process. Let’s look at an example of a customized greeting using a parameter. . A module file is just a text file. The standard Python distribution includes a programming environment called IDLE that you may use for working on the programs in this book. We will discuss parameters in detail later on.

we will discuss it in the next section. One method that should always work is to start the Python interpreter and ҇c Ê ½ÁHÌPÄ then the file. you can run a Python program by clicking (or double-clicking) on the module file’s icon. If you are using IDLE (or another might type a command like programming environment) you can run a program by opening it in the editor and then selecting a command like import. we can run it any time we want. you ϐÄ1ŽÁÓÇ Ñ€Å½ÂPÁ½Ü¬U ï ¨Ï . Here is how that looks: Ê ½ÁHÌPġрŽÂPÁˆÜ (©()( ҇c HÅÎÒ¨ Ü ¨Ì) Á !ḦÂIÊ ÒHÀPÀÓÉ4ÜxĐÌÂ1Ä¨Æ½Ü ÂàÑIÅ3ÂPÁ1Ä3ÒPÑYÍ1ÉPÇ4ÑxÄ3Ò1ÁÓÇ Ç¨ÄÆ1ÌÐÂÈǐÉHʨ˽Æ1ÌU˽Æ1ÄPۈÆPÆ£ÇàÕÝÂxLjà ֆ÷WïèÔ©9 G ÕnïùþÞ3ÖÓ© Ô 9 ÕnïùþøP) ø d©dÎ Ö dÕø¨) Ô 9 Õnïùø) ý eÎÖx© Þ 9PÕ3Öx) Õ dÞý Õnf ï e¨Ô½ Ö e© ý 9)e3 Ö eþPý ÕnH ï 9PþP© Õ eg ý d¨Õ3ÖxýÎրýþ . This program can be run in a number of different ways that depend on the actual operating system and programming environment that you are using. You can see that this particular example Ê4Â¨Ò€Ç . run. If you are using a windowing system.~zr s@tvuxwzy|{I}†~€s‚Hƒ„w€…†y|{‡}$ˆ‰uxŠŒ‹Ž3}$‚I1}"uxƒoˆ Here is the program as we would type it into IDLE or some other editor and save in a module file: ó D3Ò1ÀPÆo÷ рÅ3ÂHÁ½Ü¬ïUÏ T ó Ú ÜPÒvC Ê 3ÀHV Æ ̨) Á !HÌˆÂ€Ê ÒHÀÀxÉ@܀Đ̈£Ä3ÒI§ Ç !WрÅ3ÂHÁHÄ½ÒÑ ËˆÆ£Å3 W3Ò£ÁH̙ï èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ Ä XHÅÎҨܨÌÁ)!ḦÂIÊ ÒHÀPÀÓÉ4ÜxĐÌÂ1Ä¨Æ½Ü ÂàÑIÅ3ÂPÁ1Ä3ÒPÑYÍ1ÉPÇ4ÑxÄ3Ò1ÁÓÇ ¦WßÿҀ© Ç PÉĉñ  ÇĨÆH̀ÂUÇPÉHʨ˽ÆHÌÈ˽ÆHÄHۈÆPÆ£ÇàÕÝÂxLjà ֭÷Óú G ͨÁ1ÌÿÒWҀÇÐ̈Âx§ Ç !Ææñ€Ö€Õ3ú­÷ ¦WßàÞoïð@ ý Y`¦aY¥ñ€V Ö ¨T¦3ú Ì3ÒIÇ¥ Ä ¦ Ê4¨ҀÇoñIú ÑIÅ3ÂPÁˆÜæb ï Ï ï ¨Ï U This file should be saved with the name . or execute. The extension indicates that this is a Python module. Don’t worry if you don’t understand what actually does. In a command line situation. The point here is that once we have a program in a module file. (Programs are often placed contains lines to define a new function called Ê4Â¨Ò€Ç in a function called .) The last line of the file is the command to invoke this Ê4ÂÒIÇ function.

Python assumes the module will have a ï ¨Ï U extension.~€ ¹H£ã„t†{qä²uŒ 6 ³ ‚‡åæHç†yèt†‚HŠ Õnïùýc9)9Pސý)eþgdceÞPø)d Õnï†ÖxøPøÎ Ö ePøþÔ3Öx© ý 9gd ÕnH ï 9gd) Õ d4րþý3ÖÓÔPÕPø¨Ô Õnïùý) ø eø¨g Ô eýPÞÕÞ Õnï†Ö Ö ec9PÕPýÕ3ÖxÕÎրþø (©()( ~†” ҇Êc½ÁHÌPġрŽÂPÁˆÜ ÑIÅ3ÂHÁ½Ü Typing the first line tells the Python interpreter to load the рŽÂPÁ½Ü¬ïU¨Ï module from the file into main memory. This is an intermediate file used by the Python interdisk called preter. As Python imports the module file. Technically. When you first import a module file in this way. The in the Ê4ÂÒIÇ module causes Python to create the function. you may delete the byte code files if you wish to save disk space. It’s just as if we ÐÆPÍ had typed them one-by-one at the interactive Python prompt. the function is invoked. Typing рŽÂPÁˆÜæïÊÎÂÒIÇnñIú ÊÎÂÒIÇ ÑIÅ3ÂHÁ½Ü tells Python to invoke the function in the module. we can run the program again by asking Python to exeÊ4Â¨Ò€Ç cute the command. Python creates a companion ï Ï½Ñ b file with a extension. In this example. After the module has been loaded. here is how it looks when we rerun the program with h ¡ i as the input: рŽÂPÁ½Ü¬ïÊÎÂҀÇoñIú ÒHÀPÀÓÉ4ÜxĐÌÂ1Ä¨Æ½Ü ÂàÑIÅ3ÂPÁ1Ä3ÒPÑYÍ1ÉPÇ4ÑxÄ3Ò1ÁÓÇ Ç¨ÄÆ1ÌÐÂÈǐÉHʨ˽Æ1ÌU˽Æ1ÄPۈÆPÆ£ÇàÕÝÂxLjà ֆ÷WïèÔPø G Õnïùþc9HՐސø ÕnïùþÞPc Õ 9gd) þ d) ý dC9Hø ÕnïùþøPþþÕPøø© Ô 9PþPÞÞ HÅÎҨܨÌÁ)!ḦÂIÊ (©()( . Notice that I did not include ï ¨Ï U ҇Êc½Á1ÌÄ the extension on the line. When Python encounters the ÊÎÂÒIÇ last line of the module. Continuing with our example. Python uses a hybrid compiling/interpreting process. The running program asks the user to enter a number between 0 and 1 (in this case. Python creates another file on the ÑIÅ3ÂPÁˆÜæb ï Ï3Ñ . I typed “.25”) and then prints out a series of 10 numbers. A module needs to be imported into a session only once. This byte code (the ï ¨Ï3Ñ U file available makes importing a module faster the second time around. thus running our program. However. We do this by using a special dot notation. The Python source in the module file is compiled into more primitive instructions ï Ï½Ñ U ) file is then interpreted. each line executes. Python will automatically recreate them as needed. Having a called byte code.

Don’t worry about understanding every detail right away. ÊÎÂÒIÇ : The next line of the program begins the definition of a function called èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ÊÎÂÒIÇ Strictly speaking. the module could have looked like this: ó D3Ò1ÀPÆo÷ рÅ3ÂHÁ½Ü¬U T ï Ï ó Ú ÜPÒvC Ê 3ÀHV Æ ̨) Á !HÌˆÂ€Ê ÒHÀÀxÉ@܀Đ̈£Ä3ÒI§ Ç !WрÅ3ÂHÁHÄ½ÒÑ ËˆÆ£Å3 W3Ò£ÁH̙ï ̽ҀǨÄAX1Å4ҨܨÌÁg!P̈ÂIÊ»ÒHÀPÀÓÉ4ÜxĐÌÂ1Ä¨Æ½Ü Â ÑIÅ3ÂHÁHÄ3ÒPÑ Í1ÉPÇ4ÑxÄ3Ò1ÁÓÇ ¡ ¦WßÿҀÇ)Éĉñ  ÇĨÆH̀ÂÈǐÉHʨ˽Æ1ÌU˽Æ1ÄPۈÆPÆ£ÇàÕÝÂxLjà ֆ÷£ú G ͨÁ1ÌÿÒWҀÇà̈Âxǧ!Ææñ€Ö€Õ3ú­÷ ¦WßÐÞnïðý@Y`¦aY¥ñIV Ö ¨¥¦3ú ̽ҀÇT Ä ¦ . ó The first two lines of the program start with the character: ó D3Ò1ÀPÆo÷ рÅ3ÂHÁ½Ü¬U T ï Ï ó Ú ÜPÒvC Ê 3ÀHV Æ ̨) Á !HÌˆÂ€Ê ÒHÀÀxÉ@܀Đ̈£Ä3ÒI§ Ç !WрÅ3ÂHÁHÄ½ÒÑ ËˆÆ£Å3 W3Ò£ÁH̙ï These lines are called comments. Since the lines of a module are executed as they are loaded. Let’s take a look at this program line by line and see what it does. That is. we will be returning to all of these ideas in the next chapter. we could have written our program without this definition.~ ¯ Õnïùøý©9gd¨ýPýÞPސސý Õnf ï e¨) Ô 9P) ý d¨ÔPg Õ d¨ÕþPÞ)d ÕnH ï 9PøPՐøþPՐýPc ø 9PþÔ3Ö ÕnïùýøPՐ) ø d)dÔHިԐg Ô e¨Ô Õnï† Ö d) þ d©d© ø ePc þ 9PýPc Þ 9 Õnp ï d¨ýPÕ¨© Ô 9dC9d¨ýÞPþø Õnïùýg þ d¨ø¨ÔHýøPÕ¨Ô3q Ö d¨ý (©()( s@tvuxwzy|{I}†~€s‚Hƒ„w€…†y|{‡}$ˆ‰uxŠŒ‹Ž3}$‚I1}"uxƒoˆ “•”sr t–eŸ‘ˆ‡·§‚òi—îí¬…3˜™™£e —˜gI™hšqgIi•› рŽÂPÁˆÜ The output from the program may not look very exciting. The Python interpreter always skips any ó text from the pound sign ( ) through the end of a line. it would not be necessary to create a function. but it illustrates a very interesting phenomenon known to physicists and mathematicians. They are intended for human readers of the program and are ignored by Python.

When Python gets to this statement. ¦WßÐÞnïù@ ý Y`¦vY¥ñIV Ö ¨T¦Îú ̽ҀǨ¥ Ä ¦ The effect of the loop is exactly the same as if we had written the body of the loop 10 times: ¦WßÐÞnïùý@Y`¦vY¥ñIÖV¨T¦Îú ̽ҀǨ¥ Ä ¦ ¦WßÐÞnïù@ ý Y`¦vY¥ñIV Ö ¨T¦Îú ̽ҀǨ¥ Ä ¦ ¦WßÐÞnïù@ ý Y`¦vY¥ñIV Ö ¨T¦Îú ¦ . The value ¦ that the user types in is then stored as the variable . This particular loop says to do something 10 times.~€ ¿Hcu Š†ˆ 6 ‹I{hu«Pç†yèt†‚HŠa½}$‚IH}$uxƒ ~†´ This version is a bit shorter. One immediate benefit of this approach was illustrated above. Take a look at the next line of the program: ¦WßÿҀ) Ç Éĉñ  ÇĨÆH̀ÂÈǐÉHʨ˽Æ1ÌU˽Æ1ÄPۈÆPÆ£ÇàÕÝÂxLjà ֆ÷£ú G Here is an example of a variable. A variable is used to give a name to a value so that we can refer to it at other points in the program. We don’t have to reload the module from the file in Ê4ÂÒIÇ order to run it again. it displays the quoted ÇÄÆ1ÌÐÂÈǐÉ1Ê˽Æ1ÌU˽Æ1ÄPÛƐƣÇÝÕÐÂÓLjà ֆ÷ and then pauses. waiting for the message G ÇÄÆ1Ì ( user to type something on the keyboard and press the FG key. ̽ҀǨA Ä X1Å4Ò¨ Ü ¨Ìg Á !P̈ÂIÊ»ÒHÀPÀÓÉ4ÜxĐÌÂ1Ä¨Æ½Ü Â¡ÑIÅ3ÂHÁHÄ3ÒPÑ Í1ÉPÇ4ÑxÄ3Ò1ÁÓ Ç  This line causes Python to print a message introducing the program when it runs. The lines indented underneath the loop heading are the statements that are done 10 times. the user entered . The next statement is an example of a loop. In the first example shown ïè) Ô 9 ¦ above. The entire line is an Ҁ) Ç É¨Ä statement. but it is customary to place the instructions that Ê4Â¨Ò€Ç comprise a program inside of a function called . Ê4ÂÒIÇ The first line inside of is really the beginning of our program. which would be necessary in the -less case. These form the body of the loop. it allows us to run the program by simply рÅ3ÂHÁ½Ü¬ïÊ4¨ҀÇoñIú invoking . ͐ÁHÌÿÒWÒIÇÐ̈ÂÓC Ç !¨Æ¬ñ€ÖxÕ½ú¬÷ A loop is a device that tells Python to do the same thing over and over again. which becomes the value of .

The computed value is y©h€C‚ƒwch ¡ x„X‚H…2†$wch ¡ x„ or wchˆ‡"yc…‡¡ x .~z¹ ̽ҀǨĥ¦ ̽ҀǨĥ¦ ̽ҀǨĥ¦ ̽ҀǨĥ¦ ̽ҀǨĥ¦ ̽ҀǨĥ¦ ̽ҀǨĥ¦ ̽ҀǨĥ¦ s@tvuxwzy|{I}†~€s‚Hƒ„w€…†y|{‡}$ˆ‰uxŠŒ‹Ž3}$‚I1}"uxƒoˆ ¦WßÐÞnïùý@Y`¦vY¥ñIÖV¨T¦Îú ¦WßÐÞnïùý@Y`¦vY¥ñIÖV¨T¦Îú ¦WßÐÞnïùý@Y`¦vY¥ñIÖV¨T¦Îú ¦WßÐÞnïùý@Y`¦vY¥ñIÖV¨T¦Îú ¦WßÐÞnïùý@Y`¦vY¥ñIÖV¨T¦Îú ¦WßÐÞnïùý@Y`¦vY¥ñIÖV¨T¦Îú ¦WßÐÞnïùý@Y`¦vY¥ñIÖV¨T¦Îú Obviously. The second line in the loop body is a type of statement we have encountered ¨Ì3Ò€Ç¨Ä before. ¦ ÒIÇ©PÉÄ Recall that the value of is wch ¡ x (from the statement). But what exactly do these statements do? The first one performs a calculation. ̽ҀǨ¥ Ä ¦ When Python executes this statement the current value of is displayed on the screen.73125. ¦WßÐÞnïù@ ý Y`¦vY¥ñIV Ö ¨T¦Îú ̽ҀǨ¥ Ä ¦ ¦ . using the loop instead saves the programmer a lot of trouble. After printing the value of . Once the value on the righthand side is computed. it is stored back (or assigned) into the variable that appears on the ß ¦ ¦ lefthand side of the . in this case . So. a statement. The part on the right side of the is a Y mathematical expression. the two statements of the loop are executed again. ¦ Remember the loop executes 10 times. ¦WßÐÞnïù@ ý Y`¦vY¥ñIV Ö ¨T¦Îú ß This is called an assignment statement. Python uses the character to indicate multiplication. The new value of ( wchˆ‡"yc…‡¡ x ) replaces the old value ( wch ¡ x ). the first number of output is 0.

~€ âHHs@tvuŒ‚IˆæuxŠŒ‹ sˆ‚1ƒ•w€…†y|{‡}$ˆ ~†¿ Of course. The function computed by this program has the general form: ’B‚”“•„X‚H…–†$“•„ . You might try working through the steps of the program yourself for a different input value (say wchx ). the results are always similar: the program spits back 10 seemingly random ¦ numbers between w and … . Repeated application of the logistic function can produce chaos. ¦ Can you see how the current value of is used to compute a new value each time around the loop? That’s where the numbers in the example run came from. Then run the program using Python and see how well you did impersonating a computer. which is wchˆ‡"i i §…Xwi£¡ x . It models certain kinds of unstable electronic circuits and is also sometimes used to predict population under limiting conditions. well. An interesting property of chaotic functions is that very small differences in the initial value can lead to large differences in the result as the formula is repeatedly applied. you’ll find that. the output seems unpredictable. now has the value wchˆ‡"yc…‡¡ x . “•”s‘  ˜ŸiŸ™„‘€i„e™·s ¢™£›¥¤§¦o…‚™gI‘ ¦ ÑIÅ3ÂPÁˆÜ I said above that the program illustrates an interesting phenomenon. What could be interesting about a screen full of numbers? If you try out the program for yourself. Þoïðý where ’ in this case is . the value of seems to jump around. Here is the output from a modified program that shows the results for initial values of wch ¡ x and wch ¡ i side by side: ҀÇ)É¨Ä ÕnïèÔ)9 ÕnïùþÞÎÖxÔ©9HÕ Õnïùþøg ø d©dÎÖ Õnïùø© ý e3Öx© Þ 9 Õnf ï e¨Ô3 Ö eýPø ÕnH ï 9Pþ) Õ eg ý d Õnïùc ý 9©9HސýPý Õnï†Öxøø3 Ö ePþ ÕnH ï 9gd¨g Õ d4 Ö e ÕnïèÔHø Õnïðþ©9PÕPސøÕ ÕnïðþPސ© Õ 9gd¨þ ÕnïðþPøþPþÕþ ÕnïðøPc ý 9d¨ýý ÕnH ï e© Ô 9H) ý dÔ Õn¡ ï 9HøÕPøþÎÖ ÕnïðýPøÕP) ø d©d ÕnïŒq Ö d¨g þ d©d¨þ ¨©¨)¨©¨)¨©¨©¨)¨©¨)¨©¨©¨)¨©¨)¨©¨©¨)¨©¨)¨©¨©¨)¨©¨g¨©¨)¨ . You can see this in the chaos program by entering numbers that differ by only a small amount. no matter what number you start with. As the program runs. Although our program has a well defined underlying behavior. This is called a logistic function. chaotically. so the formula computes a new value of ¦ as y©h€C‚ƒwchˆ‡"yc…‡¡ x„X‚H…1†‰wchˆ‡"yc…‡¡ x„ .

It can carry out any process that can be described in sufficient detail. the outputs stay similar for a few iterations. are the hallmarks of chaotic behavior. It’s very possible that even with perfect computer modeling. the results that they give us are only as useful as the mathematical models on which the programs are based. . we might never be able to measure existing weather conditions accurately enough to predict weather more than a few days in advance. apparent unpredictability and extreme sensitivity to initial values. there no longer seems to be any relationship between the two models. Computer models that are used to simulate and predict weather patterns are so sensitive that the effect of a single butterfly flapping its wings in New Jersey might make the difference of whether or not rain is predicted in Peoria. this small program has a valuable lesson to teach users of computers. As amazing as computers are. The process of creating software is called programming. The measurements simply can’t be precise enough to make the predictions accurate over a longer time frame.~zâ Õnïùýø©ePø¨ÔHý Õnï†Ö Ö e©9PÕPý s@tvuxwzy|{I}†~€s‚Hƒ„w€…†y|{‡}$ˆ‰uxŠŒ‹Ž3}$‚I1}"uxƒoˆ ÕnïfdýÕÔ©9©9 ÕnïðýP) þ døÞÕ With very similar starting values. ÑIÅ3ÂPÁˆÜ These two features of our program. computer science. By about the fifth iteration. As you can see. You may have heard of the so-called butterfly effect. Here is a summary of some of the key concepts: ’ A computer is a universal information-processing machine. and programming. but then differ markedly. Chaos has important implications for computer science. Computers can give incorrect results because of errors in programs. It turns out that many phenomena in the real world that we might like to model and predict with our computers exhibit just this kind of chaotic behavior. but even correct programs may produce erroneous results if the models are wrong or the initial inputs are not accurate enough. A description of the sequence of steps for solving a particular problem is called an algorithm. “•”s—  ˜Ÿi„¤n…‚™g © ¦§›¥› ingIí This chapter has introduced computers. Algorithms can be turned into software (programs) that determines what the hardware (physical machine) can and does accomplish.

’ A Python program is a sequence of commands (called statements) for the Python interpreter to execute. and experimentation. ’ Programs are written using a formal notation known as a programming language. Information that the CPU acts on (data and programs) is stored in main memory (RAM). and input and output devices. analysis. A high-level language must either be compiled or interpreted in order for the computer to understand it. to name a few. and information management systems. secondary memory. Information is entered into the computer via input devices. The models of many real-world phenomena exhibit chaotic behavior. main memory. The CPU is the brain of the computer that performs simple arithmetic and logical operations. which places some limits on the power of computing. and output devices display the results. databases. ’ Python is an interpreted language. ’ A mathematical model is called chaotic if very small changes in the input lead to large changes in the results. Python includes statements to do things such as print output to the screen. get input from the user. Computer hardware only understands a very low-level language known as machine language. Computer science is the foundation of the broader field of computing which includes areas such as networking. making them seem random or unpredictable. ’ A basic functional view of a computer system comprises a central processing unit (CPU). Programs are usually written using human-oriented high-level languages such as Python. High-level languages are more portable than machine language. but all share the property of having a precise syntax (form) and semantics (meaning). There are many different languages. One good way to learn about Python is to use the interactive interpreter for experimentation. calculate the value of a mathematical expression. and perform a sequence of statements multiple times (loop).~€ éHHs@tŒuxw†y|{‡}Q˜¨…€ƒ„ƒŸu‡}‘ç ’ Computer science is the study of what can be computed. ~†é . Computer scientists use the techniques of design. More permanent information is stored on secondary memory devices such as magnetic disks and optical devices.

and semantics is its form. 4. A problem is intractable when a) you cannot reverse its solution b) it involves tractors c) drum d) recipe . The CPU is the “brain” of the computer. 10. 9. 5. 2. 6. A programming environment refers to a place where programmers work. A loop is used to skip over a section of a program. ƒ |§„3…‡†§ˆ}Iˆj‰cŠ§…Œ‹"} 1. 3. A function definition is a sequence of statements that defines a new command. 7. Secondary memory is also called RAM. An algorithm is like a a) newspaper b) venus flytrap 3. A variable is used to give a name to a value so it can be referred to in other places. What is the fundamental question of computer science? a) How fast can a computer compute? b) What can be computed? c) What is the most effective programming language? d) How much money can a programmer make? 2.rq7 “•”–“d™ s@tvuxwzy|{I}†~€s‚Hƒ„w€…†y|{‡}$ˆ‰uxŠŒ‹Ž3}$‚I1}"uxƒoˆ egf„‚hgIƒ¬‡‘‚„‘ hjiCkmlniCoqpIrQi§sutqlnvxw%s y{zH|c})~Q©€cˆ‚3} 1. All information that a computer is currently working on is stored in main memory. The syntax of a language is its meaning. A chaotic function describes things that are random and unpredictable. 8. Computer science is the study of computers.

~x ~37HcŽŒ{I} ³Œ6 ˆ–{zˆ rH~ c) it has many solutions d) it is not practical to solve 4. Computer languages designed to be used and understood by humans are a) natural languages b) high-level computer languages c) machine languages d) fetch-execute languages 6. One difference between a compiler and an interpreter is a) a compiler is a program b) a compiler is used to translate high-level language into machine language c) a compiler is no longer needed after a program is translated d) a compiler processes source code 8. they begin with a pound sign ( ) 10. By convention. the statements of a program are often placed in a function called a) import b) IDLE c) program d) main 9. The items listed in the parentheses of a function definition are called a) parentheticals b) scripts c) comments d) parameters  …Œ‚3‹|c‚8‚X…ŒŠm 1. A statement is a) a translation of machine language b) a complete computer command c) a precise description of a problem d) a section of an algorithm 7. Compare and contrast the following pairs of concepts from the chapter: . Which of the following is not true of comments? a) They make a program more efficient b) They are intended for human readers c) They are ignored by Python ó d) In Python. Which of the following is not an example of secondary memory? a) RAM b) hard drive c) floppy d) CD-Rom 5.

10000000000000000555. For example. . You should assume that you are talking to someone who is conceptually able to do the task. Semantics 2. many of the numbers stored in a computer are not exact values. given what you have learned about chaotic behavior in Chapter 1. Program (c) Programming Language vs. such small differences are not a problem. As you will learn in a later chapter. Natural Language (d) High-Level Language vs. but has never actually done it before. but rather close approximations. Usually. 4. you should realize the need for caution in certain situations. (a) (b) (c) (d) (e) (f) ̽ҀǨÄ&3¢ˆÆÀÀHÁ„õîÛÁHÌÀHÃjž ̽ҀǨÄ&3¢ˆÆÀÀHÁ'Îõ$†ÛÁḦÀ1Ãjž ̽ҀǨÄÐÞ ̽ҀǨÄÐÞnïðÕ ̽ҀǨÄàÔcáàÞ ̽ҀǨÄàÔoïðՀáÝÞoïðÕ .1 might be stored as 0. Write down the results you see. 5. 3. however.6 by hand using the input value. List and explain in your own words the role of each of the five basic func  tional units of a computer depicted in Figure . Compiler (f) Syntax vs. Write a detailed algorithm for making a peanut butter and jelly sandwich (or some other everyday activity). Can you think of examples where this might be a problem? Explain. Trace through the Chaos program from Section 1. you might be telling a young child. Software (b) Algorithm vs. Start up an interactive Python session and try typing in each of the following commands. Show the sequence of output that results. ’”“fv••“H–B—$—˜l™wm•Sš#›§i•“¡œ©lnsi§s wch‘…ux as 1. the value 0. For example.rIr s@tvuxwzy|{I}†~€s‚Hƒ„w€…†y|{‡}$ˆ‰uxŠŒ‹Ž3}$‚I1}"uxƒoˆ (a) Hardware vs. Machine Language (e) Interpreter vs.

(Note: You will probably not be able to get the columns to line up as nicely as those in the example.8.~x ~37HcŽŒ{I} ³Œ6 ˆ–{zˆ ̽ҀǨÄ&IÔBfáAvÞ' ̽ҀǨÄ&IÔcáÝÞWß63õ ̽ҀǨÄàÔSY€Þ ̽ҀǨÄàÔSY©YUÞ ̽ҀǨÄàÔ¥ŸÝÞ ̽ҀǨÄàÔoïðÕ Ÿ€ÞoïðÕ r€” (g) (h) (i) (j) (k) (l) ÔcáàÞ 2. 6. Your modified line of code should look like this: ¦ÐßÐԄïð@ Õ Y£¦¡Y¥ñ€` Ö ¨E¦3ú Run the program for various input values and compare the results to those obtained from the original program. 3. (Advanced) Modify the Chaos program so that it accepts two inputs and then prints a table with two columns similar to the one shown in Section 1. Modify the Chaos program so that the number of values to print is determined by the user. Modify the Chaos program so that it prints out 20 values instead of 10. 5. Write a short paragraph describing any differences that you notice in the behavior of the two versions.0 in place of 3.) . Chapter 4 discusses how to print numbers with a fixed number of decimal places. You will have to add a line near the top of the program to get another value from the user: Çÿß¡ÒIÇ©PÉĄñ"3¢Á1Û ÊÎÂÓǨÏcǐÉHʨ˽Æ1ÌÎ܀܇ŽÁ£É½ÀHᢨÌ3ÒIÇÄ%P¡£ú Ç Then you will need to change the loop to use instead of a specific number.9 as the multiplier in the logistic function. Enter and run the Chaos program from Section 1. Try it out with various values of input to see that it functions as described in the chapter. 4.6. Modify the Chaos program using 2.


QSRUTWVYXa`cb¤£ i¦¥1¨§¥4¦ u v ¨ ¥4e fª©H  iq¥pvwiqrse x€y31‚„ƒ†…ˆ‡‰„‚„‘ ’ To know the steps in an orderly software development process. and they must be told what to do right down to the last detail. Output (IPO) pattern and be able to modify them in simple ways. The process of creating a program is often broken down into stages according to the information that is produced in each phase. The hard part is actually coming up with the program in the first place. It would be almost impossible without a systematic approach. ’ To understand the rules for forming valid Python identifiers and expressions. assign values to variables. get numeric information entered from the keyboard. Process. ’ To be able to understand and write Python statements to output information to the screen. Computers are very literal. Writing large programs is a daunting challenge. here’s what you should do: ­ ® . ’ To understand programs following the Input. and perform a counted loop •«”–“ —Y˜™‚©©q™„쌅ӜingI‚¬«ª‚‰‰„‚™j ™²¤§› ‚™en… —˜gI™qƒ¬‚„‘‘ As you saw in the previous chapter. In a nutshell. it is easy to run programs that have already been written.

” Maintain the Program Continue developing the program in response to the needs of your users. •«”–• egf„i•›¥¤•j ‚m—˜gI™hšqgIi•›³² — ‚h› ¤£‚™gIi„…Φ•gI‚© ¢™£eŸ‰„‚™gv…¨‚hg Let’s go through the steps of the software development process with a simple real-world example involving a fictional computer science student. so you should try everything you can think of that might “break” the program. Create a Design Formulate the overall structure of the program. Determine Specifications Describe exactly what your program will do. Try to understand as much as possible about it. It’s good to keep in mind the old maxim: “Nothing is foolproof because fools are too ingenious. Implement the Design Translate the design into a computer language and put it into the computer. Susan Computewell. Until you really know what the problem is. as she is fluent in many languages (including Python). Susan is spending a year studying in Germany.rI¹ s@tvuxwzy|{I}½rH°¯˜} 6 y 6 ŠŒ2˜ 6 ƒ„w± {£½}$‚IH}$uxƒoˆ Analyze the Problem Figure out exactly what the problem to be solved is. Test/Debug the Program Try out your program and see if it works as expected. Her problem is that she has a hard time figuring out the temperature in the morning so that she knows how to dress for the day. The main task is to design the algorithm(s) that will meet the specifications. The process of locating and fixing errors is called debugging a program. we will be implementing our algorithms as Python programs. If there are any errors (often called bugs). they keep evolving over years of use. During the debugging phase. your goal is to find errors. In this book. you should not worry about how your program will work. you cannot begin to solve it. She has no problems with language. At this point. but rather about deciding exactly what it will accomplish. Susan listens to the weather report each . For simple programs this involves carefully describing what the inputs and outputs of the program will be and how they relate to each other. This is where the how of the program gets worked out. Most programs are never really finished. then you should go back and fix them.

She knows that 0 degrees Celsius (freezing) is equal to 32 degrees Fahrenheit. she computes the ratio of Fahrenheit to Cel¶s»¡¹ . What should the input be? She decides that her program will allow her to type in the temperature in degrees Celsius. and 100 Celsius (boiling) is equal to 212 Fahrenheit. . she might consider writing a program that would actually listen to the radio announcer to get the current temperature using speech recognition algorithms. Susan immediÁ y£¡ . Now she needs to specify the exact relationship of the output to the input. This would be a much more ambitious project. She thinks it might be possible that a computer program could help her out. She immediately realizes that this is a simple algorithm that follows a standard pattern: Input. The purpose of specification is to decide exactly what this particular program will do to solve a problem. y£¡ . Susan does some quick figuring. If Susan had background in the field of Artificial Intelligence (AI). Susan begins with an analysis of her problem. And the output? The program will display the temperature converted into degrees Fahrenheit. Her program will prompt the user for some input information (the Celsius temperature). Using F to represent the Fahrenheit temperasius degrees as µ3¶sµ3·m¸¡µ ¶s¹¡¹3·m¹£º ¶s¹¡¹¦º½¼¾ ’ for ture and C for Celsius. the robot program would also solve the problem identified in the problem analysis. process it to convert to a Fahrenheit temperature. So. Process. but the temperatures are given in degrees Celsius. but Susan only comprehends temperatures that are in degrees Fahrenheit. the final formula for the relationship is ¿ ately sees that ’ º ºÃ¼¾ Á§Â That seems an adequate specification. Plugging in w and y£¡ for and ¿ . and she is used to Fahrenheit. respectively.rH rHCŽ‡uxƒ„w± {²3}$‚I1}"uxƒ”´@ã¨{Iƒ„w‡{‡}"u†y腀}${•s‚HŠ D {‡}‘y|{‡} r€¿ morning. Susan knows better than to just dive in and start writing a program without first having a clear idea of what she is trying to build. Notice that this describes one of many possible programs that could solve this problem. she might have the computer control a robot that goes to her closet and picks an appropriate outfit based on the converted temperature. to say the least! Certainly. With this information. For output. Susan is now ready to design an algorithm for her problem. Fortunately. Output (IPO). the conversion formula will have the form ¿ ºÀ¼¾©ÁI some constant ’ . the problem is pretty clear: the radio announcer gives temperatures in degrees Celsius. she never goes anywhere without her laptop computer. Next. In this case. and then output the result by displaying it on the computer screen. Being a computer science major. Susan has an idea to solve the problem. Susan considers the specifications of a program that might help her out.


s@tvuxwzy|{I}½rH°¯˜} 6 y 6 ŠŒ2˜ 6 ƒ„w± {£½}$‚IH}$uxƒoˆ

Susan could write her algorithm down in a computer language. However, the precision of writing it out formally tends to stifle the creative process of developing the algorithm. Instead, she writes her algorithm using pseudocode. Pseudocode is just precise English that describes what a program does. It is meant to communicate algorithms without all the extra mental overhead of getting the details right in any particular programming language. Here is Susan’s completed algorithm:

The next step is to translate this design into a Python program. This is straightforward, as each line of the algorithm turns into a corresponding line of Python code.


See if you can figure out what each line of this program does. Don’t worry if some parts are a bit confusing. They will be discussed in detail in the next section. After completing her program, Susan tests it to see how well it works. She uses inputs for which she knows the correct answers. Here is the output from two of her tests:



rH ”HC©± {‡ƒn{‡Š†y|ˆ¬‚I孍3}‘‚€1}"uxƒoˆ


You can see that Susan used the values of 0 and 100 to test her program. It looks pretty good, and she is satisfied with her solution. She is especially pleased that no debugging seems necessary (which is very unusual).




Now that you know something about the programming process, you are almost ready to start writing programs on your own. Before doing that, though, you need a more complete grounding in the fundamentals of Python. The next few sections will discuss technical details that are essential to writing correct programs. This material can seem a bit tedious, but you will have to master these basics before plunging into more interesting waters.
ÇȑÉÈƒÊ Ë –B—˜i§s

You have already seen that names are an important part of programming. We Ñ1Á£ÇcWÆ1ÌÄ give names to modules (e.g., ) and to the functions within modules Ê4Â¨Ò€Ç Ñ1ƐÀˆÜPÒIÉ@Ü (e.g., ). Variables are used to give names to values (e.g., and ÍÂxĄ̊ƣǐňƈÒxÄ ). Technically, all these names are called identifiers. Python has some rules about how identifiers are formed. Every identifier must begin with a letter or underscore (the “ ” character) which may be followed by any sequence of letters, digits, or underscores. This implies that a single identifier cannot contain any spaces. According to these rules, all of the following are legal names in Python:

Ñ1ƐÀˆÜHҀÉ@Ü Ü ½Â€Ê q Ü ½Â€ÊÎÔ q Å"½Â€Ê Ú ÇˆÃ !)!3Ü G Å"½Â€Q Ê ÌÂÓÇÃCÌ !©!½Ü

Ü ½Â€Ê Å"½Â€Ê ܀؈ÂIÊ q Å£Ø Ú ö Identifiers are case-sensitive, so , , , and are all different names to Python. For the most part, programmers are free to choose any name that conforms to these rules. Good programmers always try to choose names that describe the thing being named. One other important thing to be aware of is that some identifiers are part of Python itself. These names are called reserved words and cannot be used as


s@tvuxwzy|{I}½rH°¯˜} 6 y 6 ŠŒ2˜ 6 ƒ„w± {£½}$‚IH}$uxƒoˆ

ordinary identifiers. The complete list of Python reserved words is shown in  Table .1. and assert break class continue def del for is raise elif from lambda return else global not try except if or while exec import pass yield finally in print  Table .1: Python Reserved Words.



Programs manipulate data. The fragments of code that produce or calculate new data values are called expressions. So far our program examples have dealt mostly with numbers, so I’ll use numeric data to illustrate expressions. The simplest kind of expression is a literal. A literal is used to indicate a speрÅ3ÂHÁ½Ü¬U ï Ï Þnïðý Ö Ñ1Á£c Ç WÆ1̐ęb ï Ï you can find the numbers and . The cific value. In ýoïðÕ 9oïùÕ Þ¨Ô program contains , , and . These are all examples of numeric literals, ÞÔ and their meaning is obvious: represents, well, y£¡ . A simple identifier can also be an expression. We use identifiers as variables to give names to values. When an identifier appears in an expression, this value is retrieved to provide a result for the expression. Here is an interaction with the Python interpreter that illustrates the use of variables as expressions:
(©()( (©()( 9 (©()( 9 ÌÂѣƣË3¨ÑÎòñvҀÇPǽÆ1Ì£ÊÎÁˆÜxÄWÀÂˆÜ€Ä4ú­÷ D3Ò1ÀPÆ (©()( ̽ҀÇÄ¡Üq3ÂIÊ ̽ҀÇÄT¦ ¦ ¦Wß@9

ЈÂIÊÎÆ (©()( 

Ï3ÜIňƨÀÀ1ó¨Þgd ( 3õ¢À¨Ò€ÇˆÆÿ֓õҀÇÏP F ̽ҀÇÄ¡Üq3ÂIÊ G

̨̐ÁH̟÷ Üq½Â€Ê

rH ¯ Ñn…†yèw€…†y{˜Óy–u†y|{‡ƒo{IŠzy|ˆ
¦ 9


First the variable is assigned the value x (using the numeric literal ). The ¦ 9 next line has Python evaluate the expression . Python spits back , which is ¦ the value that was just assigned to . Of course, we get the same result when ¦ we put in a print statement. The last example shows what happens when we use a variable that has not been assigned a value. Python cannot find a value, so it reports a Name Error. This says that there is no value with that name. A variable must always be assigned a value before it can be used in an expression. More complex and interesting expressions can be constructed by combining simpler expressions with operators. For numbers, Python provides the normal set of mathematical operations: addition, subtraction, multiplication, division, á ¨ Y Ÿ Y©Y and exponentiation. The corresponding Python operators are: , , , , and . рŽÂPÁˆÜæU ï ¨Ï Ñ£Á£c Ç WÆHÌPęb ï Ï Here are some examples of complex expressions from and
Þnïùý@Y`¦aY¥ñ€ÖV¨T¦Îú ýnïù  Õ Ÿ¥9oïù@ Õ YÐѣƨÀÜPҀÉ4ÜYáÝÞ¨Ô

Spaces are irrelevant within an expression. The last expression could have been ýnïùÕcŸ)9oïðÕCYÑ£Æ¨ÀˆÜHҀÉ4ÜÓá¨ÞÔ written and the result would be exactly the same. Usually it’s a good idea to place some spaces in expressions to make them easier to read. Python’s mathematical operators obey the same rules of precedence and associativity that you learned in your math classes, including using parentheses to modify the order of evaluation. You should have little trouble constructing complex expressions in your own programs. Do keep in mind that only the round parentheses are allowed in expressions, but you can nest them if necessary to create expressions like this.

If you are reading carefully, you may be curious why, in her temperature ýnïùÕcŸ)9oïðÕ ý©Ÿ©9 conversion program, Susan chose to write rather than . Both of these are legal expressions, but they give different results. This mystery will be discussed in Chapter 3. If you can’t stand the wait, try them out for yourself and see if you can figure out what’s going on.
•«”|µ xW¦o…3¤§¦n…Щ£…¨io…‚™› ‚™eo…‘

Now that you have the basic building blocks, identifier and expression, you are ready for a more complete description of various Python statements. You al¨Ì3ÒIÇÄ ready know that you can display information on the screen using Python’s


s@tvuxwzy|{I}½rH°¯˜} 6 y 6 ŠŒ2˜ 6 ƒ„w± {£½}$‚IH}$uxƒoˆ

statement. But what exactly can be printed? Python, like all programming languages, has a precise set of rules for the syntax (form) and semantics (meaning) of each statement. Computer scientists have developed sophisticated notations called meta-languages for describing programming languages. In this book we will rely on a simple template notation to illustrate the syntax of statements. ¨Ì3ÒIÇÄ Here are the possible forms of the statement: Ì½Ò€Ç¨Ä Ì½Ò€Ç¨Ä Æ ¦Ì ( g F Ì½Ò€Ç¨Ä Æ ¦Ì ( õ ) g Æ ¦ Ì ( õÝïïPïHõ ) Æ ¦¨Ì ( F F F Ì½Ò€Ç¨Ä Æ ¦Ì ( õ ) g Æ ¦ Ì ( õÝïïPïHõ ) Æ ¦¨Ì ( õ
F F F ¨Ì3ÒIÇÄ In a nutshell, these templates show that a statement consists of the keyÌ3ÒIÇÄ followed by zero or more expressions, which are separated by comword mas. The angle bracket notation ( Ó10 ) is used to indicate “slots” that are filled in by other fragments of Python code. The name inside the brackets indicates Æ ¦ Ì ) stands for an expression. The ellipses (“...”) indicate an what is missing; indefinite series (of expressions, in this case). You don’t actually type the dots. ̽ҀÇÄ statement may be optionally ended with The fourth version shows that a ̽ҀÇÄ a comma. That is all there is to know about the syntax of . Ì½Ò€Ç¨Ä As far as semantics are concerned, a statement displays information in textual form. Any supplied expressions are evaluated left to right, and the resulting values are displayed on a single line of output in a left-to-right fashion. A single blank space character is placed between the displayed values. Ì3ÒIÇÄ statements will display on separate lines of the Normally, successive ̽ҀÇÄ screen. A bare (first version above) can be used to get a blank line of ¨Ì3ÒIÇÄ output. If a statement ends with a comma (fourth version), a final space is appended to the line, but the output does not advance to the next line. Using ̽ҀÇÄ this method, multiple statements can be used to generate a single line of output. Ì3ÒIÇÄ Putting it all together, this sequence of statements ̽ҀǨÄÝÞP) á d ̽ҀǨÄÝÞ„Ô õ doõ ހ  á d Ì½Ò€Ç¨Ä ̽ҀǨÄÝÞ„Ô õ doõ ̽ҀǨÄÝÞP) á d ̽ҀǨA Ä X1ŽÆÝÂÓÇ4܀ÛÆH̡Ґ% Ü Îõ ހ  á d

produces this output:

rH ´H"Õ@ˆ–ˆ 6 1Šxƒo{‡Š†y˜Óy–u†y|{‡ƒo{IŠzy|ˆ þ


ÞTdÐþ Þ dÐþ T HňÆÝÂÓÇ4܀ۈÆ1Ì¡Ò¨ÜÈþ 
¨Ì3ÒIÇÄ That last statement may be a bit confusing. According to the syntax ¨Ì3ÒIÇÄ 3HÅ½Æ templates above, requires a sequence of expressions. That means ÂÓÇ4܀ÛÆH̡Ґ% Ü  must be an expression. In fact, it is an expression, but it doesn’t produce a number. Instead, it produces another kind of data called a string. A sequence of characters enclosed in quotes is a string literal. Strings will be discussed in detail in a later chapter. For now, consider this a convenient way of labeling output.





Ø l™—$ٌ͕i§Ú2sslŒ•w'—˜i•wmt

One of the most important kinds of statements in Python is the assignment statement. We’ve already seen a number of these in our previous examples. The basic assignment statement has this form:



WˆÂ1̽ÒHÂxË3ÀPÆ Æ)¦¨Ì Here is an identifier and is an expression. The semantics of the assignment is that the expression on the right side is evaluated to produce a value, which is then associated with the variable named on the left side. Here are some of the assignments we’ve already seen: ¦WßÐÞnïùý@Y`¦vY¥ñIÖV¨T¦Îú

ÍÂxĄ̊ƣǐňƈÒxĀßÝýnïùÕ Ÿ 9oïðÕ@YWѣƨÀÜPҀÉ4ÜYáÝÞ¨Ô ¦W@ ß 9

A variable can be assigned many times. It always retains the value of the most recent assignment. Here is an interactive Python session that demonstrates the point:
(©()( (©()(


ʽÏ)ۈÂ1̀ßàÕ Ê½) Ï ÛˆÂ1Ì

” ¯

s@tvuxwzy|{I}½rH°¯˜} 6 y 6 ŠŒ2˜ 6 ƒ„w± {£½}$‚IH}$uxƒoˆ ʽÏ)ۈÂ1̀ßàþ ʽ) Ï ÛˆÂ1Ì Ê½Ï)ۈÂ1̀ßUʈϩÛÂ1ÌWá»Ö ʽ) Ï ÛˆÂ1Ì


(©()( (©()( (©()( e

The last assignment statement shows how the current value of a variable can be used to update its value. In this case I simply added one to the previous рŽÂPÁˆÜæïU¨Ï program from Chapter 1 did something similar, though a value. The bit more complex. Remember, the values of variables can change; that’s why they’re called variables. Sometimes it’s helpful to think of a variable as a sort of named storage location in computer memory, a box that we can put a value in. When the variable   changes, the old value is erased and a new one written in. Figure . shows ¦Ý¥ ß ¦Ýá Ö how we might picture the effect of using this model. This is exactly the way assignment works in some computer languages. It’s also a very simple way to view the effect of assignment, and you’ll find pictures similar to this throughout the book.

Before x = x + 1 x 10 x

After 11

Figure Ü . Ý : Variable as box view of


Python assignment statements are actually slightly different from the “variable as a box” model. In Python, values may end up anywhere in memory, and variables are used to refer to them. Assigning a variable is like putting one of those little yellow sticky notes on the value and saying, “this is x.” Figure Ü . Ü gives a more accurate picture of the effect of assignment in Python. An arrow is used to show which value a variable refers to. Notice that the old value doesn’t get erased by the new one; the variable simply switches to refer to the new value. The effect is like moving the sticky note from one object to another. This is the way assignment actually works in Python, so you’ll see some of these sticky-note style pictures sprinkled throughout the book as well.

rH ´H"Õ@ˆ–ˆ 6 1Šxƒo{‡Š†y˜Óy–u†y|{‡ƒo{IŠzy|ˆ




x = x + 1 x 10 x 10


 ¦ ßS¦Wá W Figure . : Variable as sticky note (Python) view of Ö

By the way, even though the assignment statement doesn’t directly cause the old value of a variable to be erased and overwritten, you don’t have to worry about computer memory getting filled up with the “discarded” values. When a value is no longer referred to by any variable, it is no longer useful. Python will automatically clear these values out of memory so that the space can be used for new values. This is like going through your closet and tossing out anything that doesn’t have a sticky note to label it. In fact, this process of automatic memory management is actually called garbage collection.
Çȑ×È‘Ç ÚãsqslŒ•wQl™wm•¡äUw'Í'r%t

The purpose of an input statement is to get some information from the user of a program and store it into a variable. Some programming languages have a special statement to do this. In Python, input is accomplished using an assignÒIÇ©É¨Ä ment statement combined with a special expression called . This template shows the standard form. WÂ1̽ÒHÂÓ˽ÀPÆ ( ߡҀ) Ç É¨Ä„ñ ̨ÁxC Ê ¨Ä ( ú
F F ¨ÌÁ€C Ê Ä Here is an expression that serves to prompt the user for input; this is almost always a string literal (i.e., some text inside of quotation marks). ÒI© Ç PÉÄ When Python encounters an expression, it evaluates the prompt and displays the result of the prompt on the screen. Python then pauses and waits ÇĨÆHÌ for the user to type an expression and press the ÓåG 0 key. The expression ÒI© Ç PÉÄ typed by the user is then evaluated to produce the result of the . This ÒI© Ç PÉÄ sounds complicated, but most uses of are straightforward. In our example Ҁ) Ç ÉÄ programs, statements are used to get numbers from the user.


s@tvuxwzy|{I}½rH°¯˜} 6 y 6 ŠŒ2˜ 6 ƒ„w± {£½}$‚IH}$uxƒoˆ


If you are reading programs carefully, you probably noticed the blank space inside the quotes at the end of these prompts. I usually put a space at the end of a prompt so that the input that the user types does not start right next to the prompt. Putting a space in makes the interaction easier to read and understand. Although these two examples specifically prompt the user to enter a number, a number is just a numeric literal—a simple Python expression. In fact, any valid expression would be just as acceptable. Consider the following interaction with the Python interpreter:
(©()( (©()(

Here, when prompted to enter an expression, the user typed “3 + 4 * 5.” ÂxÇ@Ü Python evaluated this expression and stored the value in the variable . When ÂxÇ@Ü got the value 23 as expected. printed, we see that Ҁ) Ç É¨Ä is like a delayed expression. The example interaction In a way, the ÂxÇ@Ü ßÝÞW¥ á daYE9 produced exactly the same result as if we had simply done . The difference is that the expression was supplied at the time the statement was executed instead of being determined when the statement was written by the programmer. Thus, the user can supply formulas for a program to evaluate.
Çȑ×È‘É Ø l™—$r•Ùˆtu–BwQi§vxr%s°Ú2sslŒ•w'—˜i•wmt

There is an alternative form of the assignment statement that allows us to calculate several values all at the same time. It looks like this:
F WÂ1Ì (


WˆÂ1Ì (


WˆÂ£Ì (







This is called simultaneous assignment. Semantically, this tells Python to evaluate all the expressions on the right-hand side and then assign these values to the corresponding variables named on the left-hand side. Here’s an example:

rH ´H"Õ@ˆ–ˆ 6 1Šxƒo{‡Š†y˜Óy–u†y|{‡ƒo{IŠzy|ˆ ܇ÉHÊ ¦ Ï Ã½ÒÓÍÍ Here would get the sum of and and would get the difference. This form of assignment seems strange at first, but it can prove remarkably ¦ Ï useful. Here’s an example: Suppose you have two variables and and you ¦ want to swap the values. That is, you want the value currently stored in to Ï Ï ¦ be in and the value that is currently in to be stored in . At first, you might think this could be done with two simple assignments. ¦WßWÏ ÏÝß ¦


This doesn’t work. We can trace the execution of these statements step-by-step to see why. ¦ Ï Suppose and start with the values 2 and 4. Let’s examine the logic of the program to see how the variables change. The following sequence uses comments to describe what happens to the variables as these two statements are executed: ó WˆÂ£Ì3Ò1ÂÓË3ÀHÆ½Ü T ¦ Ï ó¡Ò€ÇÎÒÓĽÒHV À WˆÂÀxÉ½ÆˆÜ Ô d ¦WßWÏ óUǽÁ£Û d d ÏÝß ¦ óWͽÒIÇ3ÂPÀ d d See how the first statement clobbers the original value of by assigning to it the Ï ¦ Ï value of ? When we then assign to in the second step, we just end up with Ï two copies of the original value. One way to make the swap work is to introduce an additional variable that ¦ temporarily remembers the original value of . ÄƀC Ê à¥ ß ¦ ¦WßWÏ ÏÝßWÄƀÊC Let’s walk-through this sequence to see how it works. ó WˆÂ£Ì3Ò1ÂÓË3ÀHÆ½Ü T ¦ Ï ÄƀÊC ó¡Ò€ÇÎÒÓĽÒHV À WˆÂÀxÉ½ÆˆÜ Ô d ǽT Á WÀÓɈÆUÏÆ1Ä ÄƀC Ê à¥ ß ¦ ó Ô d Ô ¦WßWÏ

”Iâ ó ÏÝßWÄƀÊC ó

s@tvuxwzy|{I}½rH°¯˜} 6 y 6 ŠŒ2˜ 6 ƒ„w± {£½}$‚IH}$uxƒoˆ
d d d


¦ Ï As you can see from the final values of and , the swap was successful in this case. This sort of three-way shuffle is common in other programming languages. In Python, the simultaneous assignment statement offers an elegant alternative. Here is a simpler Python equivalent: ¦oõ¢ÏÐ߀ÏoÆ õ ¦

Because the assignment is simultaneous, it avoids wiping out one of the original values. Simultaneous assignment can also be used to get multiple values from the Ҁ) Ç ÉÄ user in a single . Consider this program for averaging exam scores: óÐ  W©!ԄU ï Ï Ú ÜPÒvC ó Ê 3ÀHV Æ ̨) Á !Ḧ€ÊÐÄÁÝ  W¨ÆHÌg  !¨ÆÈÄPۈÁWg Æ ¦ÂIÊ¥ÜPÑ1Á1ÌÆˆÜ ó ¢1ÀPÀÓÉ@܀ĐÌÂ1ÄƈÜfÉ4Ü£ÆWÁPÍ Ê¨É3À£Ä3 Ò ½ÀPÆWҀ© Ç PÉÄ



The program prompts for two scores separated by a comma. Suppose the user ePø„õ ýÔ ÒIÇ©PÉÄ types . The effect of the statement is then the same as if we had done this assignment: ÜPÑ£ÁH̨ÆÎ֓õÜPÑ1Á1ÌƐÔU  ß eø‰õ ý¨Ô We have gotten a value for each of the variables in one fell swoop. This example used just two values, but it could be generalized to any number of inputs. Of course, we could have just gotten the input from the user using separate input statements.

rH ¹HCé4{ëêŠ 6 y|{²¾v‚Ó‚1wŒˆ ÜPÑ£ÁH̨ÆÎÖ ßÿҀÇ)É¨Ä„ñ ÜPÑ£ÁH̨ƨÔUßÿҀÇ)É¨Ä„ñ 
 G G



In some ways this may be better, as the separate prompts are more informative for the user. In this example the decision as to which approach to take is largely ÒIÇ©É¨Ä a matter of taste. Sometimes getting multiple values in a single provides a more intuitive user interface, so it’s a nice technique to have in your toolkit.


You already know that programmers use loops to execute a sequence of statements several times in succession. The simplest kind of loop is called a definite loop. This is a loop that will execute a definite number of times. That is, at the point in the program when the loop begins, Python knows how many times to go around (or iterate) the body of the loop. For example, the Chaos program from Chapter 1 used a loop that always executed exactly ten times.
ͨÁHÌÿÒÝÒIÇÐ̈ÂÓÇC!¨Æ¬ñ€ÖxÕ½ú¬÷ ¦WßÐÞnïð@ ý Y`¦aY¥ñIÖV¨¥¦3ú ̽ҀÇT Ä ¦

This particular loop pattern is called a counted loop, and it is built using a Python ͨÁ1Ì statement. Before considering this example in detail, let’s take a look at ͨÁ1Ì what loops are all about. ͐ÁHÌ loop has this general form: A Python
F F WˆÂ£Ì ( ˽ÁHÃPÏ (




The body of the loop can be any sequence of Python statements. The start and ͐ÁHÌ end of the body is indicated by its indentation under the loop heading (the WÂ1Ì ( Ò€Ç ÜÓÆ)í£É½Æ£ÇÎÑ1Æ ( ÷ F F part). ͨÁ1Ì The variable after the keyword is called the loop index. It takes on each ÜÓ) Æ í£É½Æ£ÇÎÑ1Æ ËˆÁPÃPÏ successive value in the , and the statements in the are executed ÜÓ) Æ í1ɈƣÇÎÑ1Æ once for each value. Often the portion consists of a list of values. Lists are a very important concept in Python, and you will learn more about them in upcoming chapters. For now, it’s enough to know that you can create a simple list by placing a sequence of expressions in square brackets. Some interactive examples help to illustrate the point:


s@tvuxwzy|{I}½rH°¯˜} 6 y 6 ŠŒ2˜ 6 ƒ„w± {£½}$‚IH}$uxƒoˆ

ͨÁ1ÌÿÒWÒ€Ç û Չõ‡Ö@õôԉõèÞ)n÷ Ì3ÒIÇÄ¡Ò



ͨÁ1ÌÐÁPÐáÒIÇ û Ö@õ ބõî9‰õ þ‰õ ý)n÷ Ì3ÒIÇÄÝÁHÐáYcÁPÃPÃ


Ö Ô©9



You can see what is happening in these two examples. The body of the loop is executed using each successive value in the list. The length of the list determines the number of times the loop will execute. In the first example, Ò the list contains the four values 0 through 3, and these successive values of ÁPÃPà are simply printed. In the second example, takes on the values of the first five odd natural numbers, and the body of the loop prints the squares of these numbers. рŽÂPÁ½Ü¬U ï ¨Ï Now, let’s go back to the example which began this section (from ) Look again at the loop heading: ͨÁHÌÿÒÝÒIÇÐ̈ÂÓC Ç !¨Æ¬ñ€ÖxÕ½ú¬÷
ͨÁ1Ì Comparing this to the template for the loop shows that the last portion, ̈Âx§ Ç !Ææñ€Ö€Õ3ú , must be some kind of sequence. Let’s see what the Python interpreter tells us. Ç !¨Æ¬ñ€Ö€Õ3ú (©()( ̈Âx§ û ՉõªÖ“õ Ôæõ Þ„Æ õ do˜ õ 9æõ ø„õ þ„Ô õ e‰õ ý) ̈ÂÓC Ç !¨Æ Do you see what is happening here? The function is a built-in Python ÌÂÓÇC!¨ÆæñIÖxÕ½ú command that simply produces a list of numbers. The loop using is exactly equivalent to one using a list of 10 numbers. ͨÁHÌÿÒÝÒIÇ û ՄõªÖ@õ ԉõ Þ‰Æ õ doî õ 9‰õ ø‰õ þ„Ô õ e„õ g ý Ÿ÷

rH ¹HCé4{ëêŠ 6 y|{²¾v‚Ó‚1wŒˆ ÌÂÓ§ Ç !Ææñ ) Æ ¦ Ì ( ú In general, F will produce a list of numbers that starts with Æ)¦ Ì ( 0 and goes up to, but not does not include, the value of F . If you think about it, you will see that the value of the expression determines the number of ÑIÅ3ÂHÁ½Üæb ï Ï items in the resulting list. In we did not even care what values the Ò loop index variable used (since the value of was not referred to anywhere in the loop body). We just needed a list length of 10 to make the body execute 10 times. As I mentioned above, this pattern is called a counted loop, and it is a very common way to use definite loops. When you want to do something in your ͨÁHÌ ÌÂÓC Ç !¨Æ loop with a suitable . program a certain number of times, use a ͨÁHÌ

¯ ~

ÒIÇÐ̈Âxǧ!¨Æ¬ñ Æ)¦¨Ì
F (


The value of the expression determines how many times the loop executes. The Ò name of the index variable doesn’t really matter much; programmers often use or ï as the loop index variable for counted loops. Just be sure to use an identifier that you are not using for any other purpose. Otherwise you might accidentally wipe out a value that you will need later. The interesting and useful thing about loops is the way that they alter the “flow of control” in a program. Usually we think of computers as executing a series of instructions in strict sequence. Introducing a loop causes Python to go ͐ÁHÌ loop back and do some statements over and over again. Statements like the are called control structures because they control the execution of other parts of the program. Some programmers find it helpful to think of control structures in terms of pictures called flowcharts. A flowchart is a diagram that uses boxes to represent different parts of a program and arrows between the boxes to show the sequence  ! of events when the program is running. Figure . depicts the semantics of the ͨÁ1Ì loop as a flowchart. ͨÁ1Ì If you are having trouble understanding the loop, you might find it useful to study the flowchart. The diamond shape box in the flowchart represents a decision in the program. When Python gets to the loop heading, it checks to see if there are any (more) items left in the sequence. If the answer is yes, the loop index variable is assigned the next item in the sequence, and then the loop body is executed. Once the body is complete, the program goes back to the loop heading and checks for another value in the sequence. The loop quits when there are no more items, and the program moves on to the statements that come after the loop.

¯ r

s@tvuxwzy|{I}½rH°¯˜} 6 y 6 ŠŒ2˜ 6 ƒ„w± {£½}$‚IH}$uxƒoˆ

more items in <sequence>


yes <var> = next item


! ͨÁ1Ì Figure . : Flowchart of a loop.



‚m—˜gI™hšqgIi•›³²Eð•¦o…Φ•gI‚òñ i„j|¦Ÿ‚

Let’s close the chapter with one more example of the programming process in action. We want to develop a program to determine the future value of an investment. We’ll start with an analysis of the problem. You know that money deposited in a bank account earns interest, and this interest accumulates as the years pass. How much will an account be worth ten years from now? Obviously, it depends on how much money we start with (the principal) and how much interest the account earns. Given the principal and the interest rate, a program should be able to calculate the value of the investment ten years into the future. We continue by developing the exact specifications for the program. Remember, this is a description of what the program will do. What exactly should the inputs be? We need the user to enter the initial amount to invest, the principal. We will also need some indication of how much interest the account earns. This depends both on the interest rate and how often the interest is compounded. One simple way of handling this is to have the user enter an annual percentage rate. Whatever the actual interest rate and compounding frequency, the annual

Now that we’ve thought the problem all the way through in pseudocode. In any case. this design illustrates that sometimes an algorithmic approach to a calculation can make the mathematics easier. How should the user represent an annual rate of 3%? There are a number of reasonable choices. and also because this version will lend itself to some modifications that are discussed in the programming exercises at the end of the chapter. the algorithm seems straightforward. ؐ̽ҀǨÄÐÂÓǻҀǨĐ̨ÁPÃ1ÉÎÑÓĽÒ1Á£Ç ¢I) Ç É¨Ä€ÄHňÆÝ€ÊÎÁÓɐǨÄÝÁPÍWÄHňV Æ ̽ҀÇÎѐ Ò ½ÂÀ f ñ ̽ҀÇ4ÑP Ò ½ÂÀ½ú ¢I) Ç É¨Ä€ÄHňÆÝÂÓǐÇPÉ3ÂPè À ½Æ1Ì3Ñ1ÆÓÇÄg  !¨Æ ̈£ÄÆòñ†  ÌÎú  ˆ" Æ ½ÆÂ1Ä Ö€ÕcÄ3҇Ê3ƽܬ÷ ̽ҀÇ4ÑP Ò ½ÂÀÈE ß ¨Ì3ҀÇÎѐq Ò 3T À Y¥ñ€ÖYáÐ"  ¨Ì4ú Ä É¨g Ä PÉĀÄ1ŽE Æ WˆÂPÀÓɈƀÁPE Í ̽ҀÇÎѐ Ò ½ÂÀ If you know a little bit about financial math (or just some basic algebra). Knowing how to calculate the interest for just one year allows us to calculate any number of years into the future. .rH ¿HcŽ‡uxƒ„w± {£3}‘‚€1}"uxƒ”´óӅ†y腀}${jô4u±7…Œ{ ¯ ” rate tells us how much the investment accrues in one year.  úqõmög„ . This leads us to the following specification: Program Future Value Inputs principal The amount of money being invested in dollars. then a $100 investment will grow to $103 in one year’s time. This formula Next we design an algorithm for the program. If the annual interest is 3%. Each line of the algorithm translates into a statement of Python. so that we can formulate our ideas without worrying about all the rules of Python. I have used a loop here both to illustrate another counted loop. Relationship Value after one year is given by õmö"÷Uø'ù3÷‡õ%ú©û¡‚H… needs to be applied 10 times. Output The value of the investment 10 years into the future.03. you probably realize that the loop in this design is not strictly necessary. it’s time to put our new Python knowledge to work and develop a program. there is a formula for calculating future value in a single step using exponentiation. Let’s assume the user supplies a decimal. Given our specification. We’ll use pseudocode. apr The annual percentage rate expressed as a decimal number. so the rate would be entered as 0.

1) ¨Ì3ÒIÇ4ѐÒq3ÂPÀUߣ̽ҀÇ4ÑPҽÀ¥Y ñIÖ á¡ÂÌÎú ¨Ì3ÒIÇÄ Output the value of the principal ( statement. Section 2.4) ̽ҀǨA Ä X1ŽÆEWˆÂPÀÓɈÆÐÒ€Ç ÖxÕcϨƨ£ÌÎÜcҐÜæ÷q3õI̽ҀÇÎѐҽÀ All of the statement types in this program have been discussed in detail in this chapter. you should go back and review the relevant descriptions.4) ̽ҀǨÄAX1Å4ҨܨÌÁg!P̈ÂIÊ»ÑHÂPÀÑIÉ3ÀÂ£ÄÆˆÜ ÄHňÆcÍ1ɨÄHɨÌÆEWˆÂPÀÓɈÆ' ̽ҀǨA Ä ‡ÁHÍРրc Õ ¨£Ïƨ£̡Ҁc Ç WƈÜxÄ£Ê3ƣǨęïq ÒI© Ç PÉÄ Input the amount of the principal ( statement. That about wraps it up. Here is the completed program: óWÍ1ɨĩWÀoïbÏ Ú ¨Ì) ó Á !ḦÂIÊàÄÁàÑ£ÁxÊCPÉĨÆUÄHňÆEWˆÂÀxɽƀÁHÍÐÂÓǻҀÇcWƈÜxÄ£Ê3Æ£Ç¨Ä ó Ñ1Â1̐̽Ò1ÆHÃÿÖxՀϨƨÂ1Ì3ÜcҀǨÄÁcÄ1ŽƀÍ1ɨÄHɨÌÆ Ã¨ÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ Ä XHÅÎҨܨÌÁ)!ḦÂIÊ ÑHÂPÀÑIÉ3ÀÂ£ÄÆˆÜ ÄHňƀÍ1ɨÄHĘ́ƣWˆÂPÀÓÉˆÆ ̽ҀÇ Ä ‡ÁPÍРրc Õ ¨1Ϩƨ£ÌàҀÇcWƈÜxÄ£Ê3ƣǨęïq ̽ҀÇ4ÑPҽÀÈßÿÒIÇ©É¨Ä„ñ" Â"¨ÌÝߡҀǩPÉĉñ  G Ç ÄÆ1ÌUÄ1ŽÆàҀÇÎÒÓĽÒHÀ§Ì3ÒIÇ4ÑPÒ3ÂPÀo÷ü£ú ¨ ÇĨÆHÌcÄ1ŽÆÝÂxǐǐɽÀÝÒIÇĨÆHÌƈÜxÄÜÂ1ĨÆn÷Óú G ͨÁ1ÌÿÒWҀÇÐ̈Âxǧ!Ææñ€Ö€Õ3ú­÷ Ì3ÒIÇ4ÑP Ò 3ÂPÀÈE ß ̽ҀÇÎѐҽÀTY¥ñ€Ö áàÂ"¨Ì4ú . Notice especially the counted loop pattern is used to apply the interest formula 10 times.2)  ¨ÌÝߡҀÇ)Éĉñ  ÇĨÆHÌUÄHŽÆÝÂxǐÇPÉ3ÀWҀÇĨÆH̨ƽÜxÄÜ£ÄÆn÷ " £ú G Repeat 10 times: (counted loop.2) ̽ҀÇÎѐҽÀ ß ÒIÇ©PÉĄñ" ÇÄÆ1ÌUÄ1ŽÆàÒIÇ4ÒÓĽÒHÂPÀè̽ҀÇ4ÑPҽÀo÷ Óú G Ҁ) Ç ÉÄ Input the annual percentage rate ( expression.6) ͨÁ1Ì ÒÝÒIÇÐ̈ÂÓÇC!¨Æ¬ñ€ÖxÕ½ú¬÷ Calculate principal = principal * (1 + apr) (simple assignment. Section 2.5. If you have any questions. Section 2. Section 2.¯I¯ s@tvuxwzy|{I}½rH°¯˜} 6 y 6 ŠŒ2˜ 6 ƒ„w± {£½}$‚IH}$uxƒoˆ Ì½Ò€Ç¨Ä Print an introduction ( statement.5. Section 2. Section 2.5.

and output portions of the program. or underscore characters. Program Specification: Deciding exactly what the program will do. Design: Writing an algorithm in pseudocode. output (IPO) pattern. ’ Identifiers are names. Identifiers in Python are case sensitive. Strategically placed “white space” can help make your programs more readable. digit. I leave the testing and debugging as an exercise for you. 2. they begin with an underscore or letter which can be followed by a combination of letter. An expression can be composed of the following components: . 6. •«”s‘  ˜Ÿi„¤n…‚™g © ¦§›¥› ingIí This chapter has covered a lot of ground laying out both the process that is used to develop programs and the details of Python that are necessary to implement simple programs. Here is a quick summary of some of the key points: ’ Writing programs requires a systematic approach to problem solving and involves the following steps: 1. ’ Programs are composed of statements that are built from identifiers and expressions. That’s about it for this example. ’ Expressions are the fragments of a program that produce data.rH âHHs@tŒuxw†y|{‡}Q˜¨…€ƒ„ƒŸu‡}‘ç ¯ ´ ̽ҀÇÄXHňÆEWˆÂPÀÓɽÆÝҀǥÖxՀϨƨÂ1Ì3ÜcҨܬ÷q3õI̽ҀÇ4ÑPҽÀ Ê4¨ҀÇoñIú Notice that I have added a few blank lines to separate the input. 3. Maintenance: Keeping the program up to date with evolving needs. processing. 5. Testing/Debugging: Finding and fixing errors in the program. ’ Many simple programs follow the input. Implementation: Translating the design into a programming language. Problem Analysis: Studying the problem to be solved. process. 4.

programs can get input from the keyboard. assignment of a value to a variable is done using the equal sign ß ( ). . For example literal representing the number three. and expoY©Y nentiation ( ). ’ One important use of a ͨÁ1Ì statement is in implementing a counted loop.¯ ¹ s@tvuxwzy|{I}½rH°¯˜} 6 y 6 ŠŒ2˜ 6 ƒ„w± {£½}$‚IH}$uxƒoˆ Þ literals A literal is a representation of a specific value. subtraction ( ). 2. which is useful for getting multiple input values with a single prompt. multiplication ( ). For example. A counted loop in ̈Âx§ Ç !Æ Python is created by using the built-in function to produce a suitably sized list of numbers. division ( ). The best way to write a program is to immediately write down some code and then debug it until it works. ’ Definite loops are loops that execute a known number of times.  Ì3Ò€Ç¨Ä ’ The Python output statement ¨ displays the values of a series of expressions to the screen. Python also allows simultaneous assignment. An algorithm can be written without using a programming language. A Python list is often used in a loop to provide a sequence of values for the loop. The ͨÁ1Ì Python statement is a definite loop that iterates through a sequence of ͨÁ1Ì values. •«”s— egf„‚™gIƒæ‡‘‚„‘ hjiCkmlniCoqpIrQi§sutqlnvxw%s y{zH|c})~Q©€cˆ‚3} 1. Using assignment. ’ In Python. which is a loop designed specifically for the purpose of repeating some portion of the program a specific number of times. variables A variable is an identifier that stores a value. is a operators Operators are used to combine expressions into more complex ¦WáÝÞ¡Y Ï á Y expressions. ’ The Python operators for numbers include the usual arithmetic operations á ¨ Y Ÿ of addition ( ). in the operators and are used.

7. 9. ƒ |§„3…‡†§ˆ}Iˆj‰cŠ§…Œ‹"} 1. The process of describing exactly what a computer program will do to solve a problem is called a) design b) implementation c) programming d) specification 4. Programs no longer require modification after they are written and debugged. In a flowchart. 10. 4. What is the correct formula for converting Celsius to Fahrenheit? a) ¿ €ý"xC‚ „ y£¡ b) ¿ xý"€C‚ „{†æy£¡ º º Á  Á µ3¶sµ3·m¸¡µ c) ¿ d) ¿ µ †‰ÿ ºTþ Á º ¶s¹¡¹3·m¹ 3. Fragments of code that produce or calculate new data values are called a) identifiers b) expressions c) productive clauses d) assignment statements . In Python. Reserved words make good variable names. Which of the following are not used in expressions? a) variables b) statements c) operators d) literals 6. variables. and operators. diamonds are used to show statements. A counted loop is designed to iterate a specific number of times. Which of the following is not a legal identifier? Ü ½Â€Ê q Üu Ú Ê ÔˆÜq½Â€Ê Üq½Â€Êmd1Ù a) b) c) d) 5. 8. Expressions are built from literals. 6. ¦Ýߥ¦Ðá Ö is a legal statement. 5. and rectangles are used for decision points. Which of the following is not a step in the software development process? a) Specification b) Testing/Debugging c) Fee setting d) Maintenance 2.rP éPCŽŒ{I} ³Œ6 ˆ–{ôˆ ¯ ¿ 3. Python does not allow the input of multiple values with a single statement. Python identifiers must start with a letter or underscore.

assignment. Explain the relationships among the concepts: definite loop. and counted loop. In Python. Show the output from the following fragments: ͨÁ1ÌÿÒÝҀÇÐ̈Âxǧ!Ææñ39ˆú¬÷ (a) ¨Ì3ÒIÇÄÿ¥ Ò YWÒ (b) (c) (d) ͨÁ1ÌÝÃÿÒ€Ç û މõ‡Ö@õ¡doõv֓õÒ9gŸ÷ ¨Ì3ÒIÇÄÝÃoõ ͨÁ1ÌÿÒÝҀÇÐ̈Âxǧ!Ææñëd3ú¬÷ ¨Ì3ÒIÇ& Ä 3¢ƨÀPÀP' Á  ͨÁ1ÌÿÒÝҀÇÐ̈Âxǧ!Ææñ39ˆú¬÷ ¨Ì3ÒIÇÄÿÒ¬õ c Ô Y©YPÒ . Write out the program (Section 1. 4. ’ Underline each expression. ’ Put a comment at the end of each line indicating the type of statement on that line (output.) ͐ÁHÌ 3. etc. getting user input is done with a special expression called ͨÁ1Ì ÌƐÂHà ÒIÇ©É¨Ä b) c) simultaneous assignment d) a)  …Œ‚3‹|c‚8‚X…ŒŠm 1. Which of the following is the most accurate model of assignment in Python? a) sticky-note b) variable-as-box c) simultaneous d) plastic-scale 10. input. loop. loop.6) and identify the parts of the program as follows: ’ Circle each identifier. The template F F describes a) a general for loop b) an assignment statement c) a flowchart d) a counted loop 9. рÅ3ÂHÁ½Ü¬U ï Ï 2.¯ â s@tvuxwzy|{I}½rH°¯˜} 6 y 6 ŠŒ2˜ 6 ƒ„w± {£½}$‚IH}$uxƒoˆ 7. List and describe in your own words the six steps in the software development process. Which of the following is not a part of the IPO pattern? a) Input b) Program c) Process d) Output ͐ÁHÌ WÂ1̽ÒHÂÓ˽ÀPÆ ( ҀÇàÌÂÓ§ Ç !Ææñ ) Æ ¦ Ì ( ú 8.

Why is it a good idea to first write out an algorithm in pseudocode rather than jumping immediately to Python code? ’”“fv••“H–B—$—˜l™wm•Sš#›§i•“¡œ©lnsi§s 1.e.3) to find the average of three exam scores. Modify the program (Section 2. Ñ£Á£C Ç W¨ÆHÌPęU ï ¨Ï program (Section 2.2) with a loop so that it exe3. Modify the program (Section 2. 7. ͣɩ Ä WÀ„U ï Ï Modify the program to use this method of entering the interest ̈£ÄÆ rate. A user-friendly program should print an introduction that tells the user Ñ£Á£ÇCW¨ÆHÌPęïU¨Ï what the program does.rP éPCŽŒ{I} ³Œ6 ˆ–{ôˆ ¯ é 5. Öx@ Õ Yè½Æ1Ì3Ò1ÁHÃ3Ü To compute the value in ten years.2) to print an introduction. and the number of years for the investment.  W©!ԄU  ï Ï 2. The program should prompt the user for the yearly rate ( ) and ½Æ1Ì3Ò£ÁPÃ3Ü the number of times that the interest is compounded each year ( ).5. if the interest rate is 3% and the interest is compounded quarterly..2) so that it computes and prints a table of Celsius temperatures and the Fahrenheit equivalents every 10 degrees from 0C to 100C. the interest accrued on an account is often described in terms of a nominal rate and the number of compounding periods. The inputs to the program will be the amount to invest each year. 8. Write a program that converts temperatures from Fahrenheit to Celsius. One kilometer is approximately 0. 9.62 miles. the account actually earns 3/4 % interest every 3 months. Modify the program (Section 2. 6. As an alternative to APR. For example. Make sure to change the final message to reflect the correct number of years. Ñ1Á£c Ç WÆ1̐ęb ï Ï 4. the interest rate. ͣɩ Ä WÀ„U ï Ï 5. the program will loop ̈£Äc Æ Ÿ½Æ1Ì3Ò1ÁHà times and accrue interest on each iteration. Suppose you have an investment plan where you invest a certain fixed Í1ÉÄ)WˆÂPÀoïU¨Ï to compute the total accumulation amount every year. Modify the program (Section 2. Write a program that converts distances measured in kilometers to miles. it converts 5 temperatures in a row). . Modify of your investment. Modify the cutes 5 times before quitting (i.7) so that the number of years for the investment is also a user input.

´q7 s@tvuxwzy|{I}½rH°¯˜} 6 y 6 ŠŒ2˜ 6 ƒ„w± {£½}$‚IH}$uxƒoˆ 10. . Make sure that the program prints an introduction that explains what it does. Write a program to perform a unit conversion of your own choosing.

’ To be able to use the Python math library. In this chapter. ’ To be able to read and write programs that process numerical data. they were seen primarily as number crunchers.QSRUTWVYXa`cb ¡  ¤ ¥ e fhg ¨¥@¦ ¥ v g e ¢ ¤£ ¦ ¥1¨ hpi« x€y31‚„ƒ†…ˆ‡‰„‚„‘ ’ To understand the concept of data types. ’ To be familiar with the basic numeric data types in Python. «”–“ § ¦•› ‚™g€‡ƒ «ªi„…i©— ín¤²‚„‘ When computers were first developed. we’ll take a closer look at programs that involve numerical calculations. Consider this program to calculate the value of loose change: ® q . ’ To understand the accumulator program pattern. and that is still an important application. The information that is stored and manipulated by computer programs is generically referred to as data. problems that involve mathematical formulas are easy to translate into Python programs. Different kinds of data will be stored and manipulated in different ways. ’ To understand the fundamental principles of how numbers are represented on a computer. As you have seen.

Technically. whole numbers and numbers that have fractional components are represented differently. Whole numbers are represented using the integer data type (int for short).25.01) are decimal fractions. . 4. . 3.´Ir s@tvuxwzy|{I}3”Hs‚Hƒ„w€…†y 6 ŠŒ•’ 6 yèt †…xƒ ‡{I}‘ˆ ó¡Ñ€Å½ÂÓÇC!¨ÆnïbÏ Ú ̨) ó Á !PÌ€ÊàĨÁàÑHÂPÀрɽÀÂ£ÄÆUÄ1ŽÆEWˆÂPÀÓɈƀÁPÍÿÜÓÁxÊÎÆàÑIÅ3Âxǧ!¨ÆÝҀÇàèÁÀÀPÂ1ÌÎÜ Ã¨ÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ Ä ‡×£Å½ÂÓÇC!¨Æ€×PÁ£ÉÇ¨ÄÆ1Ì# ̽ҀÇÄ ̽ҀÇ Ä ŒØˆÀHƨÂܣƀÆÓÇÄÆ1̀ÄHňÆàÑ1ÁÓɐÇÄÐÁHÍÝƨ¨рŠÑ1ÁҀÇÝÄPÏgˆÆnïq í1ɽÂ1̐ĨÆHÌ3Ü ßÿҀ) Ç Éĉñ  ÓÉ3£̐ĨÆHÌÎܬ˜ ÷ £ú ýÒvÊÎÆ½Ü ß ÒI© Ç PÉĄ" ñ  3҇ÊÎƈÜæ‰ ÷ £ú Ç4ÒP Ñ ÎˆÆÀˆÜYß¡ÒI© Ç PÉĄ" ñ XнҐ Ñ ÎƨÀÜæ‰ ÷ £ú ½ÆÓǐÇ4ңƽÜYß¡ÒI© Ç PÉĄ" ñ ŒØ¨Æ£ÇÇÎÒ1ƈÜæ‰ ÷ £ú ÄÁ1ĈÀÈS ß í£É3£̐ÄÆ1ÌÎ` Ü Y ïð© Ô 9cáWÈ҇ÊÎƈE Ü Y©ïŒÖ€Õ€áUÇ4ҐÑΈƐÀˆÜEY©ïðÕ©9UáE½ÆÓǐÇ4ңƽÜEY ̽ҀÇÄ ̽ҀÇ Ä XHňÆcÄÁ1ĈV À WˆÂÀxɽÆWÁH̀ÏÁ£É¨Ì¡Ñ€Å½ÂÓC Ç !¨ÆàÒ¨m Ü ÎõlĨÁHĐÀ ©¨    ïùÕÎÖ Ê4¨ҀÇoñIú Here is an example of the output. The values entered by the user (5. Values of type int can be positive or negative whole numbers. Numbers that can have fractional parts are represented as floating point (or float) values. So how do we tell whether a number is an int or a . . The data type of an object determines what values it can have and what operations can be performed on it.10.05. they don’t have any fractional part. The values of the coins (. ףŽÂÓC Ç !¨Æ€×PÁ£ÉÇ¨ÄÆ1Ì  ؈ÀHƨÂܣƀÆÓÇÄÆ1̀ÄHňÆàÑ1ÁÓɐÇÄÐÁHÍÝƨ¨рŠÓɽÂ1ÌPÄÆHÌ3Üæ÷59 ÎÒvÊÎƈÜæ÷lÞ Ð3ÒP Ñ ÎƨÀˆÜ¬5 ÷ d ØÆÓǐÇÎÒ1ƽܬ÷lø Ñ1ÁҀÇÝÄPÏgˆÆnï HňÆcÄÁ1ĈÀVWˆÂÀxɽÆWÁH̀ÏÁ£É¨Ì¡Ñ€Å½ÂÓÇC!¨ÆàÒ¨ÜÐֆïHe3Ö This program actually manipulates two different kinds of numbers. we say that these are two different data types. Inside the computer. 6) are whole numbers.

your general rule of thumb should be: If you don’t absolutely need fractional values. There is a limit to the precision. Đg Ï ˆÆ Python provides a special function called that tells us the data type of any value. As we have seen.1 summarizes these operations. Since float values are not exact. Values that represent counts can’t be fractional. but a literal that has a decimal point is represented by a float (even if the fractional part is 0). while ints always are. for ints than the more general algorithms required for float values. The underlying algorithms that perform computer arithmetic are simpler.”H ~€ ­…€ƒn{‡} 6 ³ @ é u†y–u²ãçxw‡{ôˆ ¨ ´€” float? A numeric literal that does not contain a decimal point produces an int value. Actually. this table is somewhat misleading since the two numeric data types have their own operations. of the stored values. One reason has to do with program style. Python supports the usual mathematical operations on numbers. and therefore faster. Another reason has to do with the efficiency of various operations. Consider the following interaction with Python: á dŸïðÕ (©()( ÞnïùՀ¥ . When addition is performed on floats. A value’s data type determines what operations can be used on it. You should be warned that the float type only stores approximations to real numbers. or accuracy. Using an int value tells µ the reader of a program that the value can’t be a fraction. Here is an interaction with the Python interpreter showing the difference between int and float literals: Ï ½ÆæñôÞ3ú (©()( Đ ÄPg Ï ˆÆ †ÒIÇÄ ( F Ï ½ÆæñôÞnï† Ö dÎú (©()( Đ ÄPg Ï ˆÆ èͨÀPÁ¨Â£Ä ( F Ï ½ÆæñôÞnïùÕ3ú (©()( Đ ÄPg Ï ˆÆ èͨÀPÁ¨Â£Ä ( F Ï ¢IÇĀ¡ ß ¨HÞ¨Ô (©()( ʽ% Ï ½Ææñ–ʽ% Ï ¢IÇÄÎú (©()( Đ ÄPg Ï ˆÆ †ÒIÇÄ ( F Ï DˆÀPÁÂ1ÄWßÝސÔoïùÕ (©()( ʽ) Ï ½Ææñ–ʽ) Ï DˆÀPÁÂ1ÄÎú (©()( Đ ÄPg Ï ˆÆ èͨÀPÁ¨Â£Ä ( F           You may be wondering why there are two different data types for numbers. Ta! ble . use an int. for example. whereas with ints the computer performs an integer addition. the computer performs a floating point addition. we can’t have y ¶ quarters.

the results are quite different. The third to last example shows the remainder operation ( ) in action. However. Integer division always produces an integer. and operations on ints produce ints. discarding any fractional result. gozinta (goes into) ten three times (with a remainder of one). ހá d ÞnïùÕ@Y`dŸïðÕ Þ@Y£d ÖÓԄïðÕ ÖÓÔ Ö ÕoïðÕ Ÿ€ÞnïùÕ x ÞnïùސÞPސސÞPސÞPސސÞPÞ Õ ŸWÞ (©()( Öx  (©()( Þ (©()( Ö ÖxÕ #" ÐÞ (©()( 9 (©()( ÂÓË4ܓñ39ˆú ÂÓË4ܓñ3¨HÞnïH9½ú ÞnïH9 Notice how operations on floats produce floats. in the case of division.” The expression.´ ¯ s@tvuxwzy|{I}3”Hs‚Hƒ„w€…†y 6 ŠŒ•’ 6 yèt †…xƒ ‡{I}‘ˆ ©¨  operator  † ý ! % ÂxË@Ü@ñIú þnïùÕ þ (©()( (©()( (©()( operation addition subtraction multiplication division exponentiation remainder absolute value ! Table . The remainder of divid- " . integer addition produces pretty much the same result as floating point addition. Think of Öx  Õ Ÿ€Þ produces y because three integer division as “gozinta.1: Python built-in numeric operations. Most of the time. for example. we don’t have to worry about what type of operation is being performed.

You may recall that the temperature conversion program from Chapter 2 ýoïðÕ©Ÿ©9oïùÕ ý©Ÿ©9 used the expression rather than .”P rP ½ˆ 6 Š†²yètŒ{£ä²u†yèt«¾ 6 ‡}"u‡}‘ç %$  ´€´ ing …žw by y is … . The former gives the correct multiplier of …"h . I must have a total of three dollars and y cents in is y y °…žw w º change. A library is just a module that contains some useful definitions. . The last two examples illustrate taking the absolute value of an expression. you may not have used the integer division or remainder operations before. Now you know why. while the latter yields … . A quadratic equation has the form úg“ µ 8“ ù w . since x gozinta € just once. Integer division tells you how many times one number goes into another and the remainder tells you how much is left ‚ƒúCý ž„X‚ ž„ ‚ƒú ž„ . Mathematically you could write the idea like this: ú º  As an example application. The input to the program will be the values of the coefficients ú . The thing to keep in mind is that these two operations are closely related. then I can find the y . Our next program illustrates the use of this library to compute the roots of quadratic equations. over. Here’s a program that does the job. suppose we calculated the value of our loose change in cents (rather than dollars). Python provides many other useful mathematical functions in a special math library. and the remaining change number of whole dollars by computing y yý©…žw w º y . If I have 383 cents. Depending on your math background. '& )( 0( 12( & !& 31 & !& «”–• d ‘ˆ‡penš …3˜™‚pkëio…3˜ ¼™‡–y™gIingIí ! Besides the operations listed in Table . and ù .1. The outputs are the two values given by the quadratic formula. ó í1ɽÂHÃḦÂ1ĽҐÑæU ¥ ï Ï Ú ¨Ì) ó Á !ḦÂIÊàÄHŽÂ1ÄÿÑ1Á€C Ê PÉÄÆˆÜ Ä1ŽÆcÌƐÀŲÁÁHÄ3Ü ÁPÍÐT  í£É3ÂHÃḦ£Ä3ҐÑY) Æ í£É3Â1ĽÒ1ÁÓDŽï ó ¢£ÀÀÓÉ4ÜxÄP̈Â1Ä¨Æ½Ü É@ÜÓÆWÁP̀ÄHňÆYÊ4£ÄHÅÿÀÒIËÌÂ1̐ϟï ó ШÁHÄÆo÷îÄHÅÎÒ¨ Ü ¨Ì) Á !ḦÂIÊ ÑÓ̈܇ŽƽÜUң̀ÄHňÆW) Æ í£É3Â1ĽÒ1ÁÓǀÅ3ÂÜ Ç½ÁcÌƐÀŲÁÁHÄ3Üæï ( . Thus. Such an equation has º   two solutions for the value of “ given by the quadratic formula: “ º 4(65¤7 ( † ( µ †üú)ù ¡"ú Let’s write a program that can find the solutions to a quadratic equation.

Here’s another example run: . To compute “ . In the quadratic Python to use the program we calculate µ †‰ú©ù with the line ýҐÜP Ñ  ˆÁÁ1ÄWß Ê4£ÄHÅhïz" Ü íH̐ĉñða Ë Y v Ë ¨EdaYcS  YÝÑú 7 7( Here is how the program looks in action: HÅÎÒ¨ Ü ¨ÌÁ)!ḦÂIÊàͽÒILjýÜYÄHŽÆc̨ƨÂPÀÐÜ£ÁÀÓÉĽÒ1ÁÓÇ@Ü Ä¨ÁÝÂEí1É3Â1ÃPÌÂ1Ä3ÒPÑ ØˆÀHƨÂܣƀÆÓÇÄÆ1̀ÄHňÆàÑ1ÁPÆP͈͐ҐÑPÒ1ƣǨÄÎÜ HňơܣÁÀÓÉĽÒ1ÁÓÇ@Ü ñ†Â‰õ ˟õ Ñú­÷¢Þ„õÆdoõî¨PÔ Â£ÌÆo÷¢ÕnïðÞ)eþgdÔ©9ge©ePøþ¨ÔHÞE¨½Ö­ïùþ¨ÔPÕPþc9Hý¨ÔÔHՐÕPø This program is fine as long as the quadratics we try to solve have real solutions. You may recall this dot notation from Chapter 1. ҇c Ê ½Á1ÌÄ ÊÎÂ1ÄHÅ ÜíPÌÄ from the math tells Python that we are using the math module. This tells Ü íPÌÄ  function that “lives” in the math module.´I¹ ҇Êc½Á1ÌÄ Ã¨ÆHÍ ÊÎÂ1ÄHÅ s@tvuxwzy|{I}3”Hs‚Hƒ„w€…†y 6 ŠŒ•’ 6 yèt †…xƒ ‡{I}‘ˆ ó€ö½Â"ÎˆÆ½Ü ÄHŽÆYÊÎÂ1Ä1ÅÿÀҀ˨̈£̐ÏРˆ W ÂÒ1ÀÂxË3ÀPÆoï ©¨  Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ Ä XHÅÎҨܨÌÁ)!ḦÂIÊàͽÒILjýÜYÄHŽÆc̨ƨÂPÀÐÜ£ÁÀÓÉĽÒ1ÁÓÇ@Ü Ä¨ÁÝÂEí1É3Â1ÃPÌÂ1Ä3ÒPÑQ ̽ҀÇÄ Â‰õ ˟õ Ñcß¡ÒIÇ©PÉĄñ"ŒØÀPƨÂÜ£ÆÈƣǨÄÆHÌWÄ1ŽÆàÑ£ÁÆPÍPͽÒPѐÒ1ÆÓÇÄ3Ü Ã½ÒÜP Ñ  ÁÁ1ĀßÈÊ4£ÄHńïôÜ"íH̐ĄñùËaY Ëv¨Ed¡Y€ÂSYÝÑú ÌÁPÁHÄ@Öªß ñ8¨ÓËàáWÈҨÜPÑ ˆÁPÁHÄ4ú§Ÿòñ†ÔSYc½ú ÌÁPÁHĈÔÈß ñ8¨ÓËa¨cÈҨÜPÑ ˆÁPÁHÄ4ú§Ÿòñ†ÔSYc½ú ̽ҀÇÄ ̽ҀÇÄXHňơܣÁÀÓÉĽÒ1ÁÓÇ@Ü ñz‰õ ˙õ Ѩú¬÷Óú £ÌÆo÷qÎõ ÌÁÁ1Ä@Ö@õlÌÁPÁHÄˆÔ Ê4¨ҀÇoñIú This program makes use of the square root function library module. we use Ê4£ÄHÅhïz" Ü íH̐ĉë ñ ¦Îú . Importing a module makes whatever is defined in it available to the program. However. some inputs will cause the program to crash. The line at the top of the program.

The natural (base ) logarithm of x The common (base 10) logarithm of x.2 shows some of the other functions that are available in the math library. í1É3Â1ÃPÌÂ1Ä3ÒPщb ï Ï did not need to use the math library. The inverse of cosine x. The inverse of tangent x. “ The smallest whole number 0 º The largest whole number Ó “ 9 9 Table . Table . and the function is unable to Ê4Â1Ä1ÅàèÁ€Ê4ÂÒIÇ compute the square root of a negative number. the math library is the first place to look. ! º . The sine of x. An approximation of . so we will just have to assume that the user gives us solvable equations.2: Some math library functions. Python prints a ÆHÌPÌÁ1̙ï This is telling us that negative numbers are not in the domain of the Ü íHÌÄ " function.”P rP ½ˆ 6 Š†²yètŒ{£ä²u†yèt«¾ 6 ‡}"u‡}‘ç HÅÎҨܨÌÁ)!ḦÂIÊàͽÒILjýÜYÄHŽÆc̨ƨÂPÀÐÜ£ÁÀÓÉĽÒ1ÁÓÇ@Ü %$  ´€¿ ĨÁÝÂEí1É3Â1ÃPÌÂ1Ä3ÒPÑ ØˆÀHƨÂܣƀÆÓÇÄÆ1̀ÄHňÆàÑ1ÁPÆP͈͐ҐÑPÒ1ƣǨÄÎÜ ñ†Â‰õ ˟õ Ñú­÷֓õ ԉõ Þ ÌÂѣƣË3¨ Ñ ÎòñpÊÎÁˆÜxÄW̨ƈÑ1ÆÓÇÄ¡Ñ1ÀPÀ€ÀÂÜxÄ4ú­÷ D3Ò1ÀP Æ Xí1É3Â1ÃPÌÂ1Ä3ÒPщb ï # Ï 3õ¢À¨Ò€ÇˆÆWÔ3Ö@õ Ò€Ï Ç P Ê4¨ҀÇnñ‡ú D3Ò1ÀP Æ Xí1É3Â1ÃPÌÂ1Ä3ÒPщb ï # Ï 3õ¢À¨Ò€ÇˆÆÿ Ö d„õ ҀÇcÊ4Â¨Ò€Ç Ã½ÒÜP Ñ  ÁÁ1ĀßÈÊ4£ÄHńïô" Ü íH̐Ąñùa Ë Y v Ë ¨Ed¡Y€S  YÝÑú ۈÂPÀÓÉˆÆ ÌPÌÁ1̙÷ŽÊÎÂ1Ä1ÅÐèÁ€Ê4ÂÒIÇàÆHÌPÌÁ1Ì Ü íHÌÄ " The problem here is that µ †¥ú©ù¥Óqw . The cosine of x. if your program requires a common mathematical ! function. (Can you see how?) Using Ê4£ÄHÅhïz" Ü íHÌÄ is somewhat more efficient. The inverse of sine x. In general. The tangent of x. G ( Python ÎÒ Æ ÜHҀÇnÒ ñ ¦Îú Ñ£Á½Ü“Ò ñ ¦Îú ÄÂÓÇnÒ ñ ¦Îú ÂÜPҀÇoë ñ ¦3ú ¨Ñ1Á½Ü@ë ñ ¦3ú £ĈÂÓÇoë ñ ¦3ú ÀH) Á !‰Ò ñ ¦Îú ÀH) Á !4րÕæÒ ñ ¦Îú Æ ¦nÒ g ñ ¦Îú ѣƈÒHÀ­ë ñ ¦3ú ͨÀPÁÁ1Ì„Ò ñ ¦Îú Mathematics 89 @BEGADF3C @ HBI)I!PQCER@QASC I)I)PQPQEREGHBEGI!F3C@ TSTUF!C V 9X W a` `Yb “ “ “ “ ¶s¹ “ “ “ “ “ “ English An approximation of pi. We could have Actually. Right now. and it allowed me to illustrate the use of the math library. The exponential of x. we don’t have the tools to fix this problem. Y)Y taken the square root using exponentiation .

What is actually going on here? We are doing repeated multiplications. we compute i º º Let’s write a program that will compute the factorial of a number entered by the user.´I⠝«”– Öfƒ¬ƒo¦•› s@tvuxwzy|{I}3”Hs‚Hƒ„w€…†y 6 ŠŒ•’ 6 yèt †…xƒ ‡{I}‘ˆ ¦„j io…‡peŸš dc ©¨  ‘Φ„j …‘'²SðŸiŸƒ“…™hg€‡i„j Suppose you have a root beer sampler pack containing six different kinds of root beer. this result is multiplied by 2 result is multiplied by three …‡" º y i"w§‚  ¡ „ ‡Ó" ¡ w . a final value piece by piece. the tricky part here is in the second step. or accumulate. we keep track of the running product. Given six items. but º ¡ w . In mathematics. ‚bi„X‚bx„X‚”)„X‚by„X‚  ¡ „X‚H…„ ‡Ó" ¡ w possible arrangements. Then we take that result and do another multiplication y"w§‚”)„ º ¡ w§‚by„ y i"w . If you wanted to try out every possible ordering. To accomplish this in a program. Let’s keep it in a . This y"w . and as we go along. we first multiply iC‚bx„ º …‡¡"w . The factorial of a whole number ø is defined as ø ød‚”ø‰† …q„X‚”øæ†U ¡ „%hžhžh‚H…q„ . According to the definition. we will use an accumulator variable and a loop structure. process. We build up. output pattern. In computing the factorial of 6. factorial is often denoted with an exclamation (!). How do we actually compute the factorial? Let’s try one by hand to get an idea for the process. that won’t change the final value of ‡Ó" Now let’s try to think about the algorithm more generally. This is a very common algorithmic pattern called an accumulator. Do you know where this number comes from? The value 720 is the factorial of 6. we just need to fill in the details. 720. The basic outline of our program follows an input. Drinking the various flavors in different orders might affect how good they taste. The general pattern looks like this: ¢IÇÎÒÓĽÒHÀ¨Ò ÆÈÄHňÆÝÂÑPрÉHʨÉ3ÀPÂ1ÄÁ1E Ì WÂ1Ì3Ò1ÂÓ˽ÀPÆ ¤ÁPÁ WÉPÇÄ3Ò1ÀUͽÒIÇ3ÂPÀÈÌƈÜIÉ3À£Ä¡Ò¨Ü ̨ƨÂÑIŽÆHÃ É ÃÂ1ĨÆUÄHňE © Æ WˆÂPÀÓɽÆcÁPÍÐÂÑPрÉ1ÊÉ3ÀPÂ1ĨÁHE Ì WÂ1̽ÒHÂÓ˽ÀPÆ !h Realizing this is the pattern that solves the factorial problem. how many different orders would there be? It turns out the answer is a surprisingly large number. we then multiply this result by … . ¢I) Ç É¨ÄUǐÉ1Ê˽Æ1̀ÄÁ€Ä ΈÆUÍÂÑxÄÁ1Ì3ÒHÂPÀcÁP̈́õîÇ ×Á€C Ê PÉÄÆUÍÂÑxÄÁ1Ì3ÒHÂPÀUÁHÍUǙõ˜Í¨ÑÓÄ Ä É¨g Ä PÉÄWͨÂÑÓÄ ge fe Obviously. This º happens to be the number of distinct arrangements for ø items. We will be accumulating the factorial. Finally.

so it really doesn’t matter what order we do the multiplications in. we need a loop that works like this: ͨÑÓÄÝß Ö Í¨Á1ÌÝͨÑÓÄÁ1Ì¡Ò€Ç û ø„Ò õ 9‰¡ õ d„õ–Þ‰õôԉõv Ö n÷ ͨÑÓÄÝßWͨÑÓa Ä YÈͨÂÑÓĨÁHÌ pi ´€é fq rq sq Take a minute to trace through the execution of this loop and convince yourͨÑÓÄ Ö self that it works. . The pattern continues loop. The next time through the ͨÑÓĨÁHÌ 9 ͨÂÑÓÄ º y"w . this is quite easy to do using the Python function. There are other variations of that can be used to ÌÂÓ§ Ç !ÆæñvÜxĈ£̐ÄoõpǓú produce different sequences. For example. Ç ÌˆÂÓC Ç !¨Æ but not including. the new value of is … i i . since multiplication by … does not change the result. Forgetting this is a common mistake of beginning programmers. make sure you include the proper initialization. to compute the factorial of 6. What we really want is a program that can compute the factorial of any given input ø . We have hand-coded the list of factors to compute the factorial of six. You might also notice that including in the list of factors is unnecessary. neither of these loops solves the original problem. Whenever you use the accumulator pattern. We need some way to generate an appropriate list from the value of ø . With two parameters. but does not . produces ÜxÄÂ1ÌÄ a sequence that starts with the value and continues up to. the current ͨÑÓÄ is used to compute the next value. Each time through the loop. Recall ÌÂÓC Ç !¨ÆæñùǓú that produces a list of numbers starting with 0 and continuing up to. and is updated to i x º for each successive factor until the final result of 720 has been accumulated. Of course. The initialization ensures that value of ͨÑÓÄ has a value on the very first iteration. We could just as Ö easily go the other direction. we need to multiply by ͐ÁHÌ one of the factors ø q‚”øî†T…q„ žhžhžh u… . there are many other ways we could have written this loop. ̈Âx§ Ç !Æ Luckily. multiplication is commutative and associative. As you know from math class. When the loop body first executes. Ö Í¨ÑÓÄ before the loop is essential to get the The initial assignment of to loop started. It looks like we should use a loop that iterates over this sequence of factors. Here is another version that computes the same result: ͨÑÓÄÝß Ö Í¨Á1ÌÝͨÑÓÄÁ1Ì¡Ò€Ç û ԉõèބ¡ õ d„ë õ 9æõ–) ø n÷ ͨÑÓÄÝßWͨÑÓa Ä YÈͨÂÑÓĨÁHÌ Unfortunately.”P ”P"Õ ³ô³ …€ƒ„…± u†y 6 ŠŒ {zˆ–…± y|ˆ8´xó‡u ³ y|‚Ó} 6 u± ͨÂÑxÄ Í¨ÂÑxÄ variable called . Each time through the loop body (including the first). So. will be . has the value and ͨÑÓĨÁHÌ ø ͨÑÓÄ is .

A third version is like the two-parameter ÜxÄ¨Æ  version.¹q7 s@tvuxwzy|{I}3”Hs‚Hƒ„w€…†y 6 ŠŒ•’ 6 yèt †…xƒ ‡{I}‘ˆ Ç ÌÂÓÇC!¨ÆæñvÜxÄÂ1̐Äoõ ǟõÜxÄ¨Æ “ú include. we could use ̈Âx§ Ç !Ææñ†ÔæõpÇá4ÖPú Çá4Ö . Another possibility is to generate the factors in the other direction (a la our first loop) using the three-parameter version of range and a negative step to ̈Âx§ Ç !¨Æ¬ñðǟõ‡Ö“Ò õ ¨3ÖHú cause the counting to go backwards: . We need the itself is included as the last factor. except that it uses as the increment between numbers. Here then is one possible version of the factorial program: óWͨÑÓĨÁHÌ3Ò1À„U ï Ï ó ØPÌ) Á !ḦÂIÊÐÄÁ¡Ñ£ÁxC Ê PÉĨÆÈÄHňƀͨÑÓÄÁ1Ì3Ò1ÀcÁHÍРǐÉHʨ˽Æ1Ì ó ¢£ÀÀÓÉ4ÜxÄP̈Â1ĨƽܪͨÁ1ÌàÀPÁ" Á ÝÛÎÒxÄHÅÿÂÓÇÿ¨ѐÑIÉHÊɽÀÂ£ÄÁHÌ Ã¨ÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ÇàßÿҀ© Ç PÉĉñ ŒØÀPƐˆܣÆÈƣǨÄÆ1ÌÐÂUÛPŽÁÀPÆ ÇPÉHʨ˽ÆH̟÷$£ú ͨÑÓÄÝß Ö Í¨Á1ÌÝÍÂÑxÄÁ1̡ҀÇÐÌÂÓǧ!ÆæñùǙõ‡Ö@õ먽ÖPú¬÷ ÍÂÑxÄWßÝͨÑÓa Ä YÈͨÑÓĨÁHÌ ̽ҀÇ Ä XHňƀͨÑÓÄÁ1Ì3Ò1ÀUÁH6 Í 3õ Ǚè õ xҐÜ%3õ¢Í¨ÑÓÄ Ê4¨ҀÇoñIú Of course. but not including . Notice how I used as the second parameter. since the range áÎÖ Ç to make sure that will go up to but not include this value. To generate them from smallest to largest (a la our second loop). This one produces a list Ç Ö starting with and counting down (step -1) to. Another possibility is to . . there are numerous other ways this program could have been written. Here are some examples: Ç !¨Æ¬ñ€Ö€Õ3ú (©()( ̈Âx§ û ՉõªÖ“õ Ôæõ Þ„Æ õ do˜ õ 9æõ ø„õ þ„Ô õ e‰õ ý) (©()( ©¨  ̈Âxǧ!¨Æ¬ñ39æõ‡ÖxÕ½ú ûæ 9 õ „ ø õ þ‰õÔe„õ ý) ̈Âxǧ!¨Æ¬ñ39æõÖxՉõ Þ3ú ûæ 9 õÔe) (©()( Ç ÌˆÂxǧ!Æ Given our input value we have a couple of different commands Ç that produce an appropriate list of factors for computing the factorial of . I have already mentioned changing the order of factors.

ؐÏPÄHňÁ£Ç ֆï¡9oïðÔ ñôóÎ֓õ Ú Ì ÞÝÔHՐՐԉõªÖeo÷ŒÖ€øn÷èÔHø3ú ïïï א" Á ÏPÌ3Ò !£ÅÄÿÖxýý3Ö"¨½Öxýý©9TÅ1ĽҐÑIÅÄ3ÒIǧ! ö½Â1Ä1ŽƀÊ4Â1ĽҨÜHрÅWאƣǨĐÌ1ÉHʄõ Ú Ê†Ü€ÄÆ1̨ÃÂIÊ (©()( ҇Êc½ÁHÌPÄWͨÑÓĨÁHÌ3Ò1À ؈ÀHƨÂܣƀÆÓÇÄÆ1ÌÐÂUÛPňÁ¨ÀPÆYǐÉHʨ˽Æ1̙÷lø HňƀͨÑÓÄÁ1Ì3Ò1ÀUÁHÍÝø¡Ò¨ÜÈþ¨ÔHÕ (©()( ͨÑÓÄÁ1Ì3Ò1ÀoïÊ4¨ҀÇnñ‡ú ؈ÀHƨÂܣƀÆÓÇÄÆ1ÌÐÂUÛPňÁ¨ÀPÆYǐÉHʨ˽Æ1̙÷ Ö€Õ HňƀͨÑÓÄÁ1Ì3Ò1ÀUÁHÍ ÖxÕ¡Ò¨ÜÈÞPø¨g Ô e©eÕPÕ Í Â¨ÑÓÄÁ1Ì3Ò1ÀoïÊ4¨ҀÇnñ‡ú  ؈ÀHƨÂܣƀÆÓÇÄÆ1ÌÐÂUÛPňÁ¨ÀPÆYǐÉHʨ˽Æ1̙÷ Ö€Þ ÌÂѣƣË3¨ Ñ ÎòñvҀÇPǽÆ1Ì£ÊÎÁˆÜxÄWÀÂˆÜ€Ä4ú­÷ D3Ò1ÀP Æ  ÜxĐýÒIÇ ( 3õ˜À¨Ò€Ç½Æ Ö@õ Ò€Ï Ç P F D3Ò1ÀP Æ ŒÍÂÑxÄÁ1Ì3ÒHÂPÀob ï # Ï 3õ¢À¨Ò€ÇˆÆ€ý„õҀÇcÊÎÂÒIÇ Í¨ÑÓÄÝßWͨÑÓa Ä YÈͨÂÑÓĨÁHÌ Ä W¨ÆH̐ÍÀPÁ£Û ̐ÌÁ1̙÷lҀǨÄ) Æ !ÆHÌ Ê¨É3À£Ä3 Ò ½ÀÒPÑHÂ1ĽÒ1ÁÓÇ (©()( G . here is what happens if we use our program to find the factorial of 100: Ê ½ÁHÌPÄWͨÑÓĨÁHÌ3Ò1À (©()( ҇c ؈ÀHƨÂܣƀÆÓÇÄÆ1ÌÐÂUÛPňÁ¨ÀPÆYǐÉHʨ˽Æ1̙÷ Ö€ÕÕ HňƀͨÑÓÄÁ1Ì3Ò1ÀUÁHÍ ÖxÕPÕàÒ¨ÜÈýÞPÞ¨ÔHø¨Ô3Ö9gd)d¨Þýgd©dÎÖ"9ÔHø©e3ÖxøýPý¨ÔHÞ©egec9PøÔHøPøþHՐÕgd¨ýHՐþÎÖ9HýPø©ePÔPø d¨) Þ eÎրø¨Ô3q Ö d¨) ø ec9PýÔPýPø© Þ ePc ý 9PÔ3Öx© þ 9PýHýýPýÞPԐÔPýPý3 Ö 9PøH© Õ eP) ý d3 Ö d¨øPÞPýPþø½" Ö 9Hc ø 9ˆ Ö e¨g Ô ePø© Ô 91ސøPýþHý¨ÔP) Õ eÔHþ¨ÔHÔPÞPþ 9)e© Ô 9½Ö Ö e©9Ô½ÖxՐý3Öx) ø e) ø dÕÕPՐՐÕPՐÕHՐÕPՐÕHՐՐÕPÕPÕPՐÕHՐÕPՐÕHÕÕ That’s a pretty big number! Although recent versions of Python have no difficulty with this calculation.”H ¯ £ã„t†{£¾ 6 ƒ 6 y|ˆæ‚‡åu Šzy ÍÂÑxÄ Ç initialize to and then use factors starting at ø †… (as long as øü0Vw ). To illustrate the point. here’s what happens when we test the program in an older version of Python. «”|µ —Y˜™‚ ¼™‡p› ‡ …‘W™hì£t–eo… ¹H~ It’s sometimes suggested that the reason “!” is used to represent factorial is because the function grows very rapidly. You might try out some of these variations and see which one you like best. older versions of Python (and modern versions of other languages such as C++ and Java) would not fare as well. For example.

the program prints out an G What is going on here? So far.” each of which can be in one of two possible states. bit 2 0 0 1 1 bit 1 0 1 0 1 Three bits allow us to represent eight different values by adding a zero or one to each of the four two-bit patterns. In general. There are infinitely many integers. A sequence of bits can be used to represent more possibilities. To make sense of this. bit 3 bit 2 bit 1 0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 You can see the pattern here. ut . but only a finite range of ints. I have talked about numeric data types as representations of familiar numbers such as integers and decimal fractions. The problem is that this program is representing whole numbers using Python’s int data type. ints are not exactly like mathematical integers. It is important to keep in mind. Unfortunately. …uy . Inside the computer. usually represented with the numerals w (for off) and … (for on). basically on or off. we need to look at what’s going on at the hardware level. Computer memory is composed of electrical “switches. At that point. that they do not always behave exactly like the numbers that they represent. One bit can encode two possibilities. Each switch represents a binary digit or bit of information. ints are stored in a fixed-sized binary representation. we can represent four things. everything seems fine until we try to compute the factorial of Ä W¨ÆH̐ÍÀPÁ£Û ̐ÌÁ1Ì message. however. ø bits can represent ¡ different values. Each extra bit doubles the number of distinct patterns.¹Ir s@tvuxwzy|{I}3”Hs‚Hƒ„w€…†y 6 ŠŒ•’ 6 yèt †…xƒ ‡{I}‘ˆ ©¨  In this example. With two bits.

Strategically subtracting one from each º  ¡ ¸¡¹ †¥… ¡ ¸¡¹ . Let’s go back to an older version of Python and try out some expressions to Y)Y test this analysis. we can ensure that the intermediate value never gets bigger than the final result. So.”H ¯ £ã„t†{£¾ 6 ƒ 6 y|ˆæ‚‡åu Šzy ¹€” The number of bits that a particular computer uses to represent an int depends on the design of the CPU. We need to be a little cleverer and sneak up on the value from underneath. We can use the fact that ¡ ¸3¶ ¡ ¸¡¹ ¡ ¸¡¹ . Suppose we try to display the largest int directly. but “blows up” trying to compute ¡ ¸3¶ . Now µ ¡ ¸3¶ . Remember that is the Python exponentiation operator. Ô Y©YcÞÎV Ö ¨ÿÖ (©()( S ÌÂѣƣË3¨ Ñ ÎòñvҀÇPǽÆ1Ì£ÊÎÁˆÜxÄWÀÂˆÜ€Ä4ú­÷ D3Ò1ÀP Æ  ÜxĐýÒIÇ ( 3õ˜À¨Ò€Ç½Æ Ö@õ Ò€Ï Ç P F Ä W¨ÆH̐ÍÀPÁ£Û ̐ÌÁ1̙÷lҀǨÄ) Æ !ÆH£ Ì ˆÁ1ۄñIú G Our first try didn’t work. ؐÏPÄHňÁ£Ç ֆ¡ ï 9oïðÔ ñôóÎ֓õ Ú Ì ÞÝÔHՐՐԉõª Ö eo÷ŒÖ€øn÷èÔHø3ú ïïPï א" Á ÏPÌ3Ò !£ÅÄÿÖxýý3" Ö ¨½Öxý© ý 9TÅ1ĽҐÑIÅÄ3ÒI§ Ç ! ö½Â1Ä1ŽƀÊ4Â1ĽҨÜHрÅWאƣǨĐÌ1ÉHʄõ Ú Ê†Ü€ÄÆ1̨ÃÂIÊ Ô Y©YcÞÕ (©()( S ÖxÕPþÞP) þ d4 Ö e¨ Ô d wvyx ÔSY©YcÞÎÖ ÌÂѣƣË3¨ Ñ ÎòñvҀÇPǽÆ1Ì£ÊÎÁˆÜxÄWÀÂˆÜ€Ä4ú­÷ D3Ò1ÀP Æ  ÜxĐýÒIÇ ( 3õ˜À¨Ò€Ç½Æ Ö@õ ҀÇÏP F Ä W¨ÆH̐ÍÀPÁ£Û ̐ÌÁ1̙÷lҀǨÄ) Æ !ÆH£ Ì ˆÁ1ۄñIú (©()( G Old Python can calculate ¡ ¸¡¹ . By subtracting one in the middle of the side gives us ¡ ¸3¶ †¥… º  computation. That calculation produces the error before Python has a chance to subtract one. the range of integers that µ º can be represented in a 32 bit int value is †•¡ ¸3¶ to ¡ ¸3¶ †ü… . That means there are ¡ ¸¡µ possible values. Typical PCs today use 32 bits. The reason for the †1… on the high end is to account for the representation of w in the top half of the range. You can see that the overflow happens somewhere between the 30th and 31st power of two. That is consistent with our analysis that the largest int is ¡ ¸3¶ †V… . Can you see why? Python evaluates this expression ÔSY)YUÞÎÖ by first trying to calculate . Here’s what Python says: Ô Y©Ycސ  Õ ¨ÿÖYáÐ@ Ô Y©YUÞPÕ (©()( S Ô3q Ö d¨g þ dceÞP) ø dþ . These values are centered at 0 to represent a range of positive and negative integers.

you might be wondering why our program seems to work quite well computing large numbers in modern Python. However. In normal arithmetic. Here is an example run of a modified factorial program that ͨÂÑxÄ initializes to the float …"h w . or scientific. A very large (or very small) floating point value is printed out using exponenÆHá4ÖxÔ tial. With this understanding of ints in mind. after switching to float. one is computable and the other is not! Representations of numbers do not always obey all the properties that we take for granted with numbers. there is no differ¡ ¸¡¹ . we can directly test our conjecture that this is the largest int. so we have “lost” the last three digits. this expression illustrates another way that Python ints differ from the integers that they represent.¹ ¯ s@tvuxwzy|{I}3”Hs‚Hƒ„w€…†y 6 ŠŒ•’ 6 yèt †…xƒ ‡{I}‘ˆ ©¨  By the way. however. However. notation. Now you know exactly why older versions of Python can’t compute …uy This value is larger than the 32-bit limit of ¡ u…X)‡ ¡ y ëi)‡ . You can think of the at the end as a marker that shows where the decimal point should be placed. it must move 12 places to the right to get the actual value. there are only 9 digits to the right of the decimal. The at the end means that the result is equal to áÎÖÓÔ …"hy"wg‡"i‡gy i 慞w ¶sµ . Ö d¨) þ d©eÞP) ø d¨þ (©()( Ô3q Ô3q Ö d¨g þ dceÞP) ø dþ (©()( Ä W¨ÆH̐ÍÀPÁ£Û Ô3Öqd¨þ)d©eÞPø)dce ̐ÌÁ1̙÷lҀǨÄÆ)!ÆHÌÐÀ¨ÒÓĨÆḦÂPÀÈÄÁPÁWÀÂ£Ìc!Æ G There you have it. we no longer get an exact answer. !&ƒ‚ . Now that we have a numeric value. In ence between ¡ ¸3¶ †è… and ¡ ¸¡¹ †è…  this example of computer arithmetic. it turns out that floats do not really solve this problem. They both represent the same value. The largest integer that can be represented in y£¡ bits is ¡ u…X)‡ ¡ y ëi)‡ . you might think that Python uses the float data type to get us around the size limitation of the ints. gq €q u& gq «”|º gq €q u& gq ge ¶ªi„e™·£j‡peŸš ¼Ÿiog‡š§‚ § ¦§›¥y²‚™gI‘'²W¼Ÿ™£enš t–en…¨‘ At first. ؈ÀHƨÂܣƀÆÓÇÄÆ1ÌÐÂUÛPňÁ¨ÀPÆYǐÉHʨ˽Æ1̙÷  Ö 9 HňƀͨÑÓÄÁ1Ì3Ò1ÀUÁHÍ " Ö 9àÒ¨ÜÐֆïðÞPՐþøP) þ dÞ© ø ePÆPáÎÖÓÔ Although this program runs just fine. In this case.

A long int is not a fixed size. there is no need for a long int. Python has a better solution for large. ints that grow too large to be represented with 32 bits are automatically converted into long ints instead of producing an overflow error. Of course. One integer represents the string of digits in the value. exact values in the form of a third numeric type long int. but 9¤ is a long int representation of the number five. and the second represents the exponent value that keeps track of where the whole part ends and the fractional part begins. The only limit is the amount of memory the computer has available to it. using a long int causes Python to use long int operations. Here are some examples that illustrate: Ô ¤ (©()(  Ô¤ Ô ¤aY)YUÞÎÖ (©()(  Ô3q Ö d¨g þ dceÞP) ø d©eg¤ Ï ½ÆæñIÖxÕPg Õ ¤4ú (©()( Đ ÄPg Ï ˆÆ ôÀHÁ£§ Ç !¡ÒIÇÄ ( F Õ ¤YáЩ Ô 9 (©()( ÖxÕPՐՐÕPՐÕPՐՐÕPՐÕPՐՐÕPՐÕPՐՐÕPՐÕPՐÕHՐՐÕPÕPÕPՐÕHՐÕPՐÕHՐՐ ÖxÕPՐÕPՐՐÕPՐÕPՐՐÕPՐÕPՐՐÕPՐÕPՐՐÕPՐÕHՐÕPՐÕHՐՐÕPÕPÕPՐÕHÕ¨Ô)9¤  … Notice how calculations involving a long int produce a long int result.”P ´P°4uxŠŒ‹g± 6 Š† ¾‡uI}‘€{ ­…xƒ ‡{‡}$ˆ8´æ¾v‚HŠ† u „¨  Šzy|ˆ ¹€´ Remember. Here is an interactive session that illustrates this conversion process: ؐÏPÄHňÁ£Ç¡Ô„ïðÞ¨ÂPÔ ñôóÎ֓õlöˆÂ1Ì»ÖxÞÝÔHՐÕPބõªÖÖ†÷èÔHøn÷ðÕPÞ3ú­ïïï  Ï ½ Æ ôŽƨ À 3 õ xÑ£Á ¨ÏÌ3" Ò !1Ũ# Ä Î$ õ xÑxÌÆPÈÒÓÄ3% Ü Á1& Ì IÀ¨ÒÑ1ÆÓÇ@ÜÓ' Æ ͐ÁHÌÈÊÎÁ1ÌÆÐÒILj͐ÁHÌ£ÊÎÂ1ĽÒ1Á£Çhï W ¦ à ß 3 Ô Ö   d þ ) © d  e  Þ ø g ¨ d þ (©()( (©()( ¦ Ô3Öqd¨þgdceÞPø)dþ ß ¦Wá (©()( ¦W  Ö (©()( ¦ Ô3Öqd¨þgdceÞPø)d©eg¤ Ä ¦ (©()( ̽ҀÇT . Fortunately. To get a long int. the literal is an int representation of the number five. for a number this small. and our value can grow to any size. Using long ints allows us to compute with really large numbers. but expands to accommodate whatever value it holds. floats are approximations. a computer stores floating point numbers as a pair of fixed-length (binary) integers. In fact. but the amount of precision is still fixed. So. you put an “L ” suffix on a 9 numeric literal. Using a float allows us to represent a much larger range of values. In newer versions of Python. However.

After adding to the value. an . Notice the last interaction. ints are preferable to long ints. There are other situations where a value may need to be converted from one data type into another. The downside of long ints is that these representations are less efficient than the plain old int data type. what should the value of be after this assignment statement? ¦W@ ß 9oïù  Õ ŸWÔ If this is floating point division. long int arithmetic is much slower than int arithmetic.¹I¹ Ô3Öqd¨þgdceÞPø)d©e s@tvuxwzy|{I}3”Hs‚Hƒ„w€…†y 6 ŠŒ•’ 6 yèt †…xƒ ‡{I}‘ˆ ©¨  I started by assigning the value of the largest 32-bit int. Taking advantage of the fact that Python now converts large ints into long ints on demand. Long ints are obviously a cool feature of Python. «”–ê — ín¤²‚© ¢™£eŸ‰„‚™gI‘ˆ‡™£eŸ‘ ¦ In the previous section you saw that Python sometimes converts numbers represented as ints into long ints. Except when very large values are needed. fixedlength int operations. The operations needed to do arithmetic on ints is built right into the CPU of the computer. the result is ¡ . when a long int is ¨Ì3Ò€Ç¨Ä ed. it displays as a long int literal. our simple factorial program can compute interestingly large results. converting a float to an int is a dangerous step. because some information (the fractional part) will be lost. Before reading ahead for the answer. As a result. If integer division is performed. In fact. take a minute to consider how you think Python should handle this situation. the trailing “L ” is automatically omitted so that the result looks actually just like an ordinary number. You already know that combining an int with an int produces an int (or a long int). Ö Python displayed the value as an int literal. then the result should be the float value ¡©hx . But what happens if we write an expression ¦ that mixes an int with a float? For example. 9oïðÕ ŸWÔ In order to make sense of the expression . In general. you might wonder why Python even has a separate int data type. Python has to employ algorithms in software that simulate long arithmetic using the computer’s built-in. and combining a float with a float creates another float. Python must either change 9oïùÕ 9 Ô Ô„ïðÕ to and perform integer division or convert to and perform floating point division. When evaluated. When doing operations on long ints. On the other hand.

 W¨ÆHÌg   !¨ÆUßWÍÀPÁÂ1ĉñ‡ÜIÉ1• Ê ŸxǓú ÜIÉ1Ê Ç In this form. The numbers to be averaged are the ints ø„õ þ ܇ÉHÊ ÔPÔ d . since it is being converted from an int. and dividing by gives the 9 9„¡ ï9 answer . Remember. So. we need to tell Python to convert one of the operands to a floating point value. ҀǨĄñ‡ú ÀHÁ£C Ç !‰ñIú Python also provides and functions that can be used to convert numbers into ints and longs. this line may not always produce the result we intend. The line of code to compute the average might look like this:  W¨ÆHÌg   !¨ÆUßÿÜIÉHÏ Ê ŸÈÇ Unfortunately. Sometimes we may want to perform a type conversion ourselves. suppose we are writing a program that finds the average of some numbers. The variable will hold . not . Here are a few examples: ñ dn¡ ï 9ˆú (©()( ҀǨĄë d Þ (©()( (©()( ҀǨĄñzÞoïðý½ú ÀPÁÓǧ!‰ñôÞnïùý3ú Þg¤ . an int divided by an int always produces an int. also an int.  W¨ÆHÌg   !¨ÆUßWÍÀPÁÂ1ĉñ‡ÜIÉ1Ê­§ ú ŸUÇ ÍÀPÁÂ1ĉñIú The function converts an int into a float. respectively. and could both be ints causing Python to perform an integer division and then convert the resulting quotient to a float. To solve this problem. Of course. Our program would first sum up the numbers and then divide by ø . this float would always end in h w . That is not what we want. in mixed-typed expressions. ÍÀHÁ¨Â£Ä„ñIú around the entire expression would not Notice that putting the work.”H ¹H£ãçxw‡{§s‚HŠ D {‡}$ˆ 6 ‚HŠ†ˆ ¹€¿ int can be safely turned into a float just by adding a fractional part of h w . the count of how many numbers there are. For example. This is called an explicit type conversion. because this produces a mixed-type expression. We only need to convert the numerator. doõ˜9æõ Consider a specific example. Python will automatically convert ints to floats and perform floating point operations to produce a float result. and Python will automatically convert the denominator.

if necessary. not rounded. you can add 0. Here is a quick summary of some key concepts: ’ The way a computer represents a particular kind of information is called a data type. float. The last example shows how the result can ÒIÇĉñIú then be turned into an int value. The data type of an object determines what values it can have and what operations it supports. and long int. converting to an int or long int simply discards the fractional part of a float. . «”sr  ˜Ÿi„¤n…‚™g © ¦§›¥› ingIí This chapter has filled in some important details concerning programs that do numerical computations. assuming the value is positive. ÌÁ£ÉPLjà A more general way of rounding off numbers is to use the built-in function which rounds a float off to the nearest whole value. ÞnïùÕ (©()( (©()( (©()( (©()( (©()( ¨PÞ ÌÁÓɐLjÃæñzÞoïŒÖd3ú ÌÁÓɐLjÃæñ3¨HÞnïŒÖqdÎú ÌÁÓɐLjÃæñzÞoï¡9½ú ÌÁÓɐLjÃæñ3¨HÞnï¡9ˆú ҀǨĄñ–̨Á£ÉPLjÉñ8¨PÞoïŒÖd3úú ¨PÞoïðÕ dŸïùÕ ¨gdnïðÕ Ì¨Á£ÉPLjà Notice that returns a float. If you want a rounded ҀǨĄñ‡ú result. including int. by using . ’ Python has several different data types for representing numeric values.¹Iâ (©()( (©()( s@tvuxwzy|{I}3”Hs‚Hƒ„w€…†y 6 ŠŒ•’ 6 yèt †…xƒ ‡{I}‘ˆ ÍÀHÁ¨Â1ĉñvÒIÇĄñôÞnïùÞ3úú ҀǨĄñôͨÀPÁÂ1ĄñôÞnïùÞ3úú ҀǨĄñôͨÀPÁÂ1ĄñôÞ3úPú ©¨  ÞnïùÕ Þ Þ (©()( As you can see. the value is truncated.5 to the value before using .

”P âPCŽŒ{I} ³Œ6 ˆ–{ôˆ ’ Whole numbers are generally represented using the int data type and fractional values are represented using floats. All of the Python numeric data types support standard, built-in mathematical operations addition á ¨ Y Ÿ ( ), subtraction ( ), multiplication ( ), division ( ), remainder ( ), exY)Y ÂÓË4ܓë ñ ¦3ú ponentiation ( ), and absolute value ( ).



’ Additional mathematical functions are defined in the Ê4£ÄHÅ library. To use ÒvÊC½Á1ÌÄ Ê4£ÄHÅ these functions, a program must first the library. ’ Numerical results are often calculated by computing the sum or product of a sequence of values. The loop accumulator programming pattern is useful for this sort of calculation. ’ Both ints and floats are represented in the computer using a fixed-length sequence of bits. This imposes certain limits on these representations. Ints must be in the range †•¡ ¸3¶ hžhžh‚ ¡ ¸3¶ †@…q„ . Floats have a finite amount of precision and cannot represent most numbers exactly. ’ Python long ints may be used to store whole numbers of arbitrary size. Int values are automatically converted to long ints when they become too large. Calculations involving long ints are less efficient that those that use only ints. ’ Python automatically converts numbers from one data type to another in certain situations. For example, in a mixed-type expression involving ints and floats, Python first converts the ints into floats and then uses float arithmetic. ’ Programs may also explicitly convert one data type into another using the ͨÀPÁÂ1Ąñ‡ú ÒIÇĉñIú ÀHÁ£Ç§!æñIú functions , , and . «”s‘

hjiCkmlniCoqpIrQi§sutqlnvxw%s y{zH|c})~Q©€cˆ‚3}

1. Information that is stored and manipulated by computers is called data. 2. Since floating point numbers are extremely accurate, they should generally be used instead of ints.


s@tvuxwzy|{I}3”Hs‚Hƒ„w€…†y 6 ŠŒ•’ 6 yèt †…xƒ ‡{I}‘ˆ ÊÎÂ1ÄHÅ


3. Operations like addition and subtraction are defined in the

4. The number of possible rearrangements of n items is equal to 5. The


library. .

function computes the squirt of a number.

6. The int data type is identical to the mathematical concept of integer. 7. Computers represent numbers using base 2 representations. 8. A float can represent a larger range of values than an int. 9. An int can represent indefinitely large numbers. 10. In Python,
ƒ |§„3…‡†§ˆ}Iˆj‰cŠ§…Œ‹"} dCŸ)9

is the same as



1. Which of the following is not a Python numeric data type? a) int b) float c) rational d) long int 2. Which of the following is not a built-in operation? á ÂÓË4ܓñIú ÜíP̐ĉñIú b) c) d) a)
Ê4£ÄHÅ 3. In order to use functions in the library, a program must include a) a comment b) a loop c) an operator d) an import statement


4. The value of  is a) 9 b) 24 


c) 41

d) 120

5. The most appropriate data type for storing the value of pi is a) int b) float c) long int d) string 6. The number of distinct values that can be represented using 5 bits is a) 5 b) 10 c) 32 d) 50 7. In a mixed-type expression involving ints and floats, Python will convert a) floats to ints b) ints to long ints c) floats and ints to long ints d) ints to floats 8. Which of the following is not a Python type-conversion function? ÍÀHÁ¨Â1Ä ÌÁÓɐLjà ÒIÇÄ ÀPÁÓǧ! a) b) c) d)

”P âPCŽŒ{I} ³Œ6 ˆ–{ôˆ


9. The pattern used to compute factorial is a) accumulator b) input, process, output c) counted loop d) plaid 10. In modern Python, an int that grows too large a) causes an overflow b) converts to float d) converts to long int
 …Œ‚3‹|c‚8‚X…ŒŠm

c) breaks the computer

1. Show the result of evaluating each expression. Be sure that the value is in the proper form to indicate its type (int, long int, or float). If the expression is illegal, explain why. dŸïù  Õ Ÿ ÖxÕnïùÕcáÐÞnH ï 9SYcÔ (a) ÖxÕ  dWáР ø ŸÝÔ (b) ÂÓË4Ü“Ò ñ dS¨WÔP  Õ ŸWÞ3E ú Y)YUÞ (c) Ü íH̐ĉë " ñ dŸH ï 9T¨¥9oïùÕ3úYáÝ¡ þ YUÞ (d) Þ YàÖx  ¡ Õ ŸWހá»ÖxÕ ÝÞ (e) Þ ¤aY)YcÞ g (f)



2. Translate each of the following mathematical expressions into an equivalent Python expression. You may assume that the math library has been ҇C Ê ˆÁHÌPÄÈÊ4Â1Ä1Å imported (via ). (a) (b) (c)

(d) (e)

t€8 †‡t ‰ˆ  EGF3@ W‘ W‘
‚by  ö µ µ ·B¶ ö§‚ µ3· µ · 3 ¶ ¶


úC„ µ Â



úC„ µ

3. Show the list of numbers that would be generated by each of the following ̈ÂÓC Ç !¨Æ expressions. ̈Âx§ Ç !Ææ3 ñ 9ˆú (a) ̈Âx§ Ç !ÆæñzމõfÖxÕ½ú (b) ̈Âx§ Ç !Ææë ñ d„õfÖxމõ Þ3ú (c)


s@tvuxwzy|{I}3”Hs‚Hƒ„w€…†y 6 ŠŒ•’ 6 yèt †…xƒ ‡{I}‘ˆ ̈Âxǧ!Ææñ€Ö9‰õÔ9æõԈú ̈Âxǧ!Ææñ39æõ˜Þ3ú


(d) (e)

4. Show the output that would be generated by each of the following program fragments. (a) (b)
ͨÁ1ÌÿÒÝҀÇÐ̈Âxǧ!Ææñ€Ö@õÖPÖPú¬÷ ¨Ì3ÒIÇÄÿ© Ò YPÒ Í¨Á1ÌÿÒÝÒ€Ç û Ö@õ–Þ‰õë9‰õèþ„õèý)Ÿ÷ ¨Ì3ÒIÇÄÿÒ¬õè4÷q3õÒ©Y)Y1Þ Ì3ÒIÇÄÿÒ Ïàß Í¨ÁHÌ


ÒIÇÐ̈ÂÓÇC!¨Æ¬ñzՄõîÏnõÔ¦Îú­÷ ¨Ì3ÒIÇÄ õ ï ¨Ì3ÒIÇ  Ä ¦Wá€Ï Ì3ÒIÇ& Ä ŒÃ¨Á£Çˆ' Æ 





1. Write a program to calculate the volume and surface area of a sphere from its radius, given as input. Here are some formulas that might be useful:


º ÿ º

)ý"y 



ö ¸ ö µ

2. Write a program that calculates the cost per square inch of a circular pizza, ö µ given its diameter and price. The formula for area is ÿ


3. Write a program that determines the molecular weight of a hydrocarbon based on the number of hydrogen, carbon, and oxygen atoms. You should use the following weights:

”P âPCŽŒ{I} ³Œ6 ˆ–{ôˆ


Atom H C O

Weight (grams / mole) 1.0079 12.011 15.9994

4. Write a program that determines the distance to a lightning strike based on the time elapsed between the flash and the sound of thunder. The speed of sound is approximately 1100 ft/sec and 1 mile is 5280 ft. 5. The Konditorei coffee shop sells coffee at $10.50 a pound plus the cost of shipping. Each order ships for $0.86 per pound + $1.50 fixed cost for overhead. Write a program that calculates the cost of an order. 6. Two points in a plane are specified using the coordinates (x1,y1) and (x2,y2). Write a program that calculates the slope of a line through two (non-vertical) points entered by the user.

“ •” 9 —– –
û 8õ





7. Write a program that accepts two points (see previous problem) and determines the distance between them.

˜ “™ 9 ed
÷ úgø'ù º Á ‚ ý)„ † Á

‚”“4¡–†‰“x…q„ µ Â


8. The Gregorian epact is the number of days between January … and the previous new moon. This value is used to figure out the date of Easter. It is calculated by these formulas (using int arithmetic):

– –
† Â

…q„ µ


Write a program that prompts the user for a 4-digit year and then outputs the value of the epact. 9. Write a program to calculate the area of a triangle given the length of its three sides a, b, and c using these formulas:

9 ™ 0&
õ%ú)ù º ‚

º ‚¡‚



0& –


úgögý©…žw w …uy„¡ýÓ¡ x„ … …‚



9 u1 w1
úgö 5…u€„¡„


ÿ º

º ‚





“ h( “
† X„X‚





¿ ¯

s@tvuxwzy|{I}3”Hs‚Hƒ„w€…†y 6 ŠŒ•’ 6 yèt †…xƒ ‡{I}‘ˆ


10. Write a program to determine the length of a ladder required to reach a given height when leaned against a house. The height and angle of the ladder are given as inputs. To compute length use

9 ji ™lk @BASk C 9 0ijki ™ 9
ø º ú)ø )û ÷súgø º … "w gö

Note: the angle must be in radians. Prompt for an angle in degrees and use this formula to convert:
ö ú

˜ “ 8 ˜ 9 i m9 9 “ &

11. Write a program to find the sum of the first value of ø is provided by the user.

natural numbers, where the

12. Write a program to find the sum of the cubes of the first ø natural numbers where the value of ø is provided by the user. 13. Write a program to sum a series of numbers entered by the user. The program should first prompt the user for how many numbers are to be summed. It should then input each of the numbers and print a total sum. 14. Write a program that finds the average of a series of numbers entered by the user. As in the previous problem, the program will first ask the user how many numbers there are. Note: the average should always be a float, even if the user inputs are all ints. 15. Write a program that approximates the value of by summing the terms )ý"xd†I)ý ‡ )ý"€d†I)ý©… … hžhžh The program should of this series: )ý©…x† )ý"y   number  of terms to sum, and then output the prompt the user for ø , the sum of the first ø terms of this series. Have your program subtract the Ê4£ÄHńb ï 4Ò to see how accurate it is. approximation from the value of 16. A Fibonacci sequence is a sequence of numbers where each successive number is the sum of the previous two. The classic Fibonacci sequence begins: 1, 1, 2, 3, 5, 8, 13, hžhžh . Write a program that computes the nth Fibonacci number where ø is a value input by the user. For example, if ø i , then the result is 8.


17. You have seen that the math library contains a function that computes the square root of numbers. In this exercise, you are to write your own

”P âPCŽŒ{I} ³Œ6 ˆ–{ôˆ


algorithm for computing square roots. One way to solve this problem is to use a guess-and-check approach. You first guess what the square root might be and then see how close your guess is. You can use this information to make another guess and continue guessing until you have found the square root (or a close approximation to it). One particularly ¦ good way of making guesses is to use Newton’s method. Suppose is the !£É½Æ½ÜPÜ number we want the root of and is the current guessed answer. The guess can be improved by using Write a program that implements Newton’s method. The program should ¦ prompt the user for the value to find the square root of ( ) and the num!£É½ÆˆÜÜ ¦CŸPÔ ber of times to improve the guess. Starting with a value of , your program should loop the specified number of times applying New!1É½ÆˆÜÜ . You should also subtract ton’s method and report the final value of Ê4Â1Ä1ńïô" Ü íPÌPÄ„Ò ñ ¦Îú your estimate from the value of to show how close it is.

uqvQs w•x•x nBomp fqf‰rt

as the next guess.








¢ ¤£
¥1¨ ¥4¦ëvh

x€y31‚„ƒ†…ˆ‡‰„‚„‘ ’ To understand the string data type and how strings are represented in the computer. ’ To be familiar with various operations that can be performed on strings through built-in functions and the string library. ’ To understand the basic idea of sequences and indexing as they apply to Python strings and lists. ’ To be able to apply string formatting to produce attractive, informative program output. ’ To understand basic file processing concepts and techniques for reading and writing text files in Python. ’ To understand basic concepts of cryptography. ’ To be able to understand and write programs that process textual information. µa”–“ —Y˜™‚©©²…Îg€‡penš


So far, we have been discussing programs designed to manipulate numbers. These days we know that computers are also useful for working with other kinds



s@tvuxwzy|{I} ¯  sˆ‚1ƒ•w€…†y 6 Š†²’ 6 yèt”˜xyè} 6 ŠŒIˆ

of data. In fact, the most common use for most personal computers is word processing. The data in this case is text. Text is represented in programs by the string data type. You can think of a string as a sequence of characters. In Chapter 2 you learned that a string literal is formed by enclosing some characters in quotation marks. Python also allows strings to be delimited by single quotes (apostrophes). There is no difference; just be sure to use a matching set. Strings can also be stored in variables, just like numbers. Here are some examples illustrating these two forms of string literals: ß 3¢ƨÀPÀP' Á  (©()( ÜxÄPÌ@Ö A x Ü P Ä ˆ Ì c Ô ß Œ Ü u 3  I Â Ê (©()( (©()( ̽ҀÇÄ¡ÜxĐÌ4֓õÜ€ÄÌˆÔ ¢ˆÆÀÀHÁàq Ü ½Â€Ê Ï ½ÆæñvÜxÄPÌ@ÖPú (©()( Đ ÄPg Ï ˆÆ ŒÜ€ÄÌ3ÒI§ Ç ! ( F Ï ½ÆæñvÜxÄP̈Խú (©()( Đ ÄPg Ï ˆÆ ŒÜ€ÄÌ3ÒI§ Ç ! (

|  } }


You already know how to print strings. Some programs also need to get string input from the user (e.g., a name). Getting string-valued input requires a ÒI© Ç É¨Ä statement treats whatever the user types bit of care. Remember that the as an expression to be evaluated. Consider the following interaction: Ä ÐˆÂIÊÎÆUßÿÒI© Ç É¨Ä„" ñ ŒØˆÀHƨÂÜ£ÆÈÆ£ÇĨÆH̀ϨÁ£É¨ÌcÇ3€Ê3Æn$ ÷ Óú (©()( ͽÒxÌÎÜx) ؈ÀHƨÂܣƀÆÓÇÄÆ1̀ÏÁÓÉÌcǽ€ÊÎÆoÔ ÷ R1ÁÓÅÇ ÌÂѣƣË3¨ Ñ ÎòñvҀÇPǽÆ1Ì£ÊÎÁˆÜxÄWÀÂˆÜ€Ä4ú­÷ D3Ò1ÀP Æ  Ï3ÜIňƨÀÀ1c ó e ( ÎõlÀÒIÇ½Æ Ö@õ Ò€Ï Ç P F ͽÒxÌÎÜx) Ä ÐˆÂIÊÎÆUßÿÒI© Ç É¨Ä„" ñ ŒØˆÀHƨÂÜ£ÆÈÆ£ÇĨÆH̀ϨÁ£É¨ÌcÇ3€Ê3Æn$ ÷ Óú D3Ò1ÀP Æ  ÜxÄPÌ3ÒI§ Ç ! ( Îõ¢ÀҀLjƀՄõÒIÏ Ç P F ЈÂIÊÎÆ ÌÌ¨ÁHÌŸÆ ÷ R1ÁÓŐÇ

Something has gone wrong here. Can you see what the problem is? ÒIÇ©PÉÄ Remember, an statement is just a delayed expression. When I entered the name, “John,” this had the exact same effect as executing this assignment statement: ͽÒxÌÎ܀© Ä ÐˆÂIÊÎÆÈv ß R£Á£ÅPÇ
R1ÁÓÅÇ This statement says, “look up the value of the variable and store that value ͽÒÓÌ3ÜxÄ)Ј€Ê3Æ R1ÁÓÅÇ in .” Since was never given a value, Python cannot find any ЈÂIÊÎÆ ÌÌ¨ÁHÌ variable with that name and responds with a . G

The input is simply handed to the program as a string of text. we need some string operations. What kinds of things can we do with strings? For starters. illustrates with the string “Hello Bob. While the idea of numeric operations may be old hat to you from your math studies. If you want to get textual input from the user. we’ll put these ideas to work in some example programs. assign them to variables. this can be done through the operation of indexing. For that.” Indexing is used in string expressions to access a specific character position in the string. We shouldn’t have to burden the users of our programs with details like typing quotes around their names. In the following section. and how to print them out. here ̈ÂÓÛ Ò€© Ç PÉÄ is how it looks with : Ä ÐˆÂIÊÎÆUßWÌ£m Û Ì¨Ò€) Ç Éĉñ †ØˆÀPƐˆÜÓÆÈÆÓÇĨÆH̀ϨÁ£ÉÌcǽ€Ê3Æn$ ÷ Óú (©()( ͽÒxÌÎÜx) ؈ÀHƨÂܣƀÆÓÇÄÆ1̀ÏÁÓÉÌcǽ€ÊÎÆoÔ ÷ R1ÁÓÅÇ Ä 3¢ˆÆÀÀH' Á ÎõlͽÒÓÌ3Üx) Ä ÐˆÂ€Ê3Æ (©()( ̽ҀÇ ¢ˆÆÀÀHS Á R1ÁÓÅÇ Notice that this example works as expected without having to type quotes around ÌÂ£Û Ò€Ç)ÉÄ the input. is the way to do it. #  Figure . In Python. ̈ÂÓÛ ÒI© Ç PÉÄ Python provides a better mechanism. starting from the left with 0. Ä ÐˆÂIÊÎÆUßÿÒIÇ©É¨Ä„ñ"ŒØˆÀHƨÂÜ£ÆÈÆ£ÇĨÆH̀ϨÁ£É¨ÌcÇ3€Ê3Æn÷$Óú (©()( ͽÒxÌÎÜx) ؈ÀHƨÂܣƀÆÓÇÄÆ1̀ÏÁÓÉÌcǽ€ÊÎÆo$ ÷ R£Á£ÅP Ç  Ä 3¢ˆÆÀÀH' Á ÎõlͽÒÓÌ3Üx) Ä ÐˆÂ€Ê3Æ (©()( ̽ҀÇ ¢ˆÆÀÀHS Á R1ÁÓÅÇ This works. The rest of this section takes you on a tour of the more important Python string operations. The value of the expression determines F which character is selected from the string. we have seen how to get strings as input. That’s enough to write a parrot program. So far. Revisiting our example. We can think of the positions in a string as being numbered. you may not have thought about string operations. but it is not a very satisfactory solution. One thing we might want to do is access the individual characters that make up the string. The function is exactly like Ҁ) Ç É¨Ä except it does not evaluate the expression that the user types. Here are some interactive indexing examples: . but not to do any serious text-based computing. remember what a string is: a sequence of characters.˜ yè} 6 Š† @ é u†y–u•ãçxw‡{ ¯  ~€£ã‰tŒ{ x ¿€é One way to fix this problem is to type quotes around a string input so that it evaluates as a string literal. The general ܀ĐÌ3ÒI§ Ç ! ( û ) Æ ¦ Ì (  form for indexing is F .

: Indexing of the string (©()( (©()( f¢ (©()( (©()( ¨Á£Ëx   !P̨ƐÆHĀßò8¢ˆÆÀÀPÁ !P̨ƐÆHÄ û Õg ¤ Á£Ëx ¢¡ÀWÁ ̽ҀÇÄT!PÌÆPÆHÄ ¦WßSe û Õ)„õç!P̨ƐÆ1Ä û Ôoõ5!PÌÆPÆHÄ û û ¦C¨PÔg d©  (©()( ̽ҀÇÄT!PÌÆPÆHÄ Notice that. position . In Python. here are some slices: Þ  (©()( !P̨ƐÆHÄ û Õo÷ð) f¢ƨÀ ý  (©()( !P̨ƐÆHÄ û 9„÷ð) ÁÓË  6  ‘ . A slice produces the substring starting at the position ÜxÄÂ1ÌPÄ Æ£Çà given by and running up to. Continuing with our interactive example. It is also possible to access a contiguous sequence of characters or substring from a string. Both and should be 0 Ó 0 Ó 0 int-valued expressions. the last character is at position øü† … . because the indexes start at w . Slicing û ܀ĈÂ1ÌPÄ ÷ ÆÓLjà  Ü€ÄˆÂ£ÌÄ Æ£Çà ÜxÄPÌ3ҀC Ç ! takes the form Ó . Indexing returns a string containing a single character from a larger string. By the way. You can think of slicing as a way of indexing a range of positions in the string. in a string of ø characters. Ö  (©()( Ü û ¨3 pË Þ  (©()( Ü û ¨P)   l… This is particularly handy for getting at the last character of a string.âq7 s@tvuxwzy|{I} ¯  sˆ‚1ƒ•w€…†y 6 Š†²’ 6 yèt”˜xyè} 6 ŠŒIˆ ~ ƒ   €  € ‚ „ ‰ … † Š ‡ ‹ ˆ Œ Ž #  8¢ˆÆ¨ÀPÀPÁ Figure . but not including. Python also allows indexing from the right end of a string using negative indexes. this is accomplished through an operation called slicing.

The string data type also supports operations for putting strings together. Here are some examples of various string operations: Ü 3€{ Ê A á ‡g Æ !©!½% Ü  (©()( Óu Œu Ü 3ÂIÊÎ) Æ !)!3Ü Ê A á  Ú Çˆ' à fA á  !)!3m Ü  (©()( qÅ3€{ G ëÅ3ÂIÊ Ú Çà !©!3Ü G Þ YÏÓq Ü ½Â€{ Ê  (©()( @ Œu Ü 3ÂIʆq Ü ½Â€Ê“q Ü 3ÂIÊ Ü 3€{ Ê §YE9 (©()( Óu Œu Ü 3ÂIʆq Ü ½Â€Ê“q Ü 3ÂIʆu Ü 3€ʓq Ü ½Â€Ê Þ YÏÓu Ü 3ÂIÊ £úªá©ñ ‡g Æ !©!½% Ü §YE9ˆú (©()( ñz@ Œu Ü 3ÂIʆq Ü ½Â€Ê“q Ü 3ÂIÊÎg Æ !©!3ÜÓ) Æ !)!3Ü£g Æ !©!ˆÜ£g Æ !©!ˆÜ£) Æ !)!½Ü Ü ½Â€Ê Óú (©()( ÀPÆÓÇnñ xq      ’ ’   ’ d (©()( ÖÖ ÀPÆÓÇnñ uÅ"½Â€Ê Ú ÇˆÃ G !©!½Ü%Óú (©()( ÅV (©()( ͨÁ1ÌÿрŠҀdzuÅ"½Â€Êgž@÷  Ì3ÒIÇÄ¡ÑIřõ   q Ê  # These basic string operations are summarized in Table . which tells how many characters are in a string. Finally. . since strings are sequences of characters. Another useful function is ÀPÆÓÇ . the start and end of the string are the assumed defaults.1. Indexing and slicing are useful operations for chopping strings into smaller pieces. you can iterate through the characters using a Python ͨÁ1Ì loop. á Y Two handy operators are concatenation ( ) and repetition ( ). Concatenation builds a string by “gluing” two strings together. The final expression actually hands back the entire string. Repetition builds a string by multiple concatenations of a string with itself.˜ yè} 6 Š† @ é u†y–u•ãçxw‡{ ¯  ~€£ã‰tŒ{ x âH~ (©()( (©()( (©()(  }  ‘  Ž ‘ f¢ƨÀPÀPÁ !P̨ƐÆHÄ !P̨ƐÆHÄ !P̨ƐÆHÄ û ÷H9g û„ 9 ÷f û ÷p ÁÓË f¢ƨÀPÀPÁ ¨Á£Ë The last three examples show that if either expression is missing.

Our program will follow the basic input. we’re ready to write some programs. usernames are derived from the user’s actual name.” We want to write a program that reads a person’s name and computes the corresponding username. óUÉ@ÜÓÆHÌ1Ç3€Ê3Ænb ï Ï ó Ũ҇C Ê ½ÀPÆà܀Đ̽Ҁ§ Ç !VÌÁÑ1ƈܐÜPÒI§ Ç !èÌg Á !PÌ€ÊàĨT Á !¨Æ£ÇˆÆHÌÂ1ÄÆ É@ÜÓÆHÌHǽ€Ê3ƽÜæï èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ Ä XHÅÎҨܨÌÁ)!ḦÂIÊ@!¨ÆÓǽÆ1̈Â1ĨƽÜcÑ£ÁxÊcÉĨÆHÌ ̽ҀÇÄ É@Ü£Æ1ÌHǽ€ÊÎƈÜæïu ó¥!¨Æ1ÄcÉ@Ü£Æ1Ì †ÜYͽÒxÌÎÜxÄàÂxLjÃÐÀPˆÜxÄÈÇ3€Ê3Æ½Ü Í½ÒxÌÎÜxĀßÝÌ£ۧÌҀÇ)É¨Ä„ñ †ØˆÀHƨˆÜÓÆ Æ£ÇĨÆH̀ϨÁ£É¨ÌÝͽÒÓÌ3ÜxÄUǽ€Ê3Æòñ†ÂÀPÀ€ÀPÁ£ÛˆÆ1Ì3ÑHÂܣƽú¬÷æÓú ÀÂÜxÄÝ߀̈ÂÓm Û Ì¨Ò€© Ç PÉĉñ ŒØÀPÆÂˆÜ£Æ ÆÓÇÄÆ1̀ÏÁÓÉÌàÀPˆÜxÄcǽ€Ê3Æ ñ†ÂPÀÀWÀPÁ£ÛˆÆ1Ì3ÑHÂܣƽú¬÷æÓú  . The system administrator must assign a unique username to each user. Often. the username for Elmer Thudpucker would be “ethudpuc. output pattern. µa”–• ©«‡p›¥¤§j ‚ ©²…Îg€‡penš —˜gI™qƒ¬‚„‘‘ˆ‡penš Now that you have an idea what various string operations can do. For brevity. The outline of the algorithm is included as comments in the final program.” and John Smith would just be “jsmith. Our first example is a program to compute the usernames for a computer system. process. I will skip discussion of the algorithm development and jump right to the code. One scheme for generating usernames is to use the user’s first initial followed by up to seven letters of the user’s last name.1: Python string operations. Many computer systems use a username and password combination to authenticate system users.âIr s@tvuxwzy|{I} ¯  sˆ‚1ƒ•w€…†y 6 Š†²’ 6 yèt”˜xyè} 6 ŠŒIˆ Operator Meaning + Concatenation * Repetition Ó string 0 [ ] Indexing Slicing Ó string 0 [ : ] len( Ó string 0 ) Length for Ó var 0 in Ó string 0 Iteration through characters # Table . Using this method.

it might seem that this program is beyond your current ability. we could easily extract the abbreviation. and the output is the abbreviation for the corresponding month. Suppose we want to print the abbreviation of the month that corresponds to a given month number. The trick is computing where to slice. based on the number given by the user. if we knew where a given month started in the string. we can write the program now by some clever use of string slicing. ÊÎÁÓÇÄ1Å@ÜYß&R1ÂÓÇcDƣːö½Â£Ì Ú ¨  ÌPöˆÂ1Ï%RIɐÇQR€É3À Ú ÉC!CÅ1Æ  Ä Ñ€Ä©ÐÁW ƈÑm u We can lookup a particular month by slicing out the appropriate substring. for March. computing with strings is very similar to computing with numbers. slicing. if the input is 3. Since each month is represented by three letters. however. Then indexing. We will not cover decision structures until later. At first. ÊÎÁÓÇÄ1Å Ú ËPĘ̈ÆgW€ß Ê3Á£Ç¨ÄHÅ@Ü û ˆ  Á½Üæ÷b½ÁˆÜÓá¨Þg . öˆÂ1Ì For example. Here is another problem that we can solve with string operations. Here’s an example run: HÅÎҨܨÌÁ)!ḦÂIÊ@!¨ÆÓǽÆ1̈Â1ĨƽÜcÑ£ÁxÊcÉĨÆHÌ G“ É@Ü£Æ1ÌHǽ€ÊÎƈÜæï ؈ÀHƨÂܣƀÆÓÇÄÆ1̀ÏÁÓÉÌÝ͈ÒÓÌÎ܀ÄUÇ3ÂIÊÎÆòñzÀÀWÀHÁ1ÛÆHÌ3Ñ1ˆÜÓÆ3ú¬÷ ¨ Æ ÀIÊÎÆ1Ì ØˆÀHƨÂܣƀÆÓÇÄÆ1̀ÏÁÓÉÌàÀPˆÜxÄcǽ€Ê3Æ ñ†ÂPÀÀWÀPÁ£ÛˆÆ1Ì3ÑHÂܣƽú¬÷ Ä1Ő É ÃÉÎÑÎÆHÌ ÁÓÉÌcÉ4Ü£ÆHÌ1Ç3ÂIÊÎÆÝҐÜæ÷¢Æ1ÄHŐÉ à PÉ4Ñ “ As you can see. The input to the program is an int that represents a month number (1–12). and concatenation are combined to produce the username.˜ yè} 6 ŠŒ ½}$‚ ³ {ôˆpˆ 6 ŠŒ ¯  rH˜ 6 ƒ„w± { x — ó¡Ñ1ÁÓÇ4ÑH£ÄÆÓÇ3Â1ĨÆU͈ÒÓÌÎ܀ġҀÇÎÒÓĽÒHÀYÛÎÒÓÄ1Å¡þàрŽÂ1ÌÎÜÈÁH̀ÄHňÆÝÀÂˆÜ€ÄUÇ3ÂIÊÎÆoï ɐǽ€ÊÎÆUßÐ͈ÒÓÌ3ÜxÄ û Õ)Uá¡ÀPÂˆÜ€Ä û ÷ùþ) ó Á£É¨ÄgÉ¨Ä€ÄHňÆÈÉ@ÜÓÆHÌHǽ€Ê3Æ Ý ̽ҀÇÄ ÁÓÉÌcÉ4Ü£ÆHÌ1Ç3ÂIÊÎÆÝҐÜæ÷uÎõ ɐǽ€Ê3Æ Ê4¨ҀÇoñIú ÌÂ£Û Ò€) Ç É¨Ä This program first uses to get strings from the user. Experienced programmers recognize that this is a decision problem. we have to decide which of 12 different outputs is appropriate. The basic idea is to store all the month names in a big string. then the output should be . That is.

for 1 we get ‚H… †ü…q„ y º º º º Now we’re ready to code the program. the comments document the algorithm we’ve developed. To get the correct multiple. the final result is short and sweet. Again. So w y w and for 12 we have ‚H…‡¡ †ü…q„ y … … y y y . ó ÊÎÁÓÇÄ1ńU ï ¨Ï Ú ¨Ì) ó Á !ḦÂIÊÐÄ£ Á ¨Ì3ҀǨĀÄHňÆÝÂÓËPËÌ Æ W3Ò1Â1Ä3Ò£Á£ÇWÁPÍà ÊÎÁÓÇÄ1řç õ !ˆ" Ò WÆÓÇ ÒÓÄ3Ü ÇÉ1Ê˽Æ1Ì Ã¨ÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ó ÊÎÁÓÇÄHÅ4ÜcÒ¨Ü É4Ü£ÆPÃWˆÜUÂÝÀPÁPÁÎPÉ)ÝĈÂxË3ÀHÆ ÊÎÁÓÇÄHÅ4ÜYA ß R1ÂÓÇcDƣːö½Â£Ì Ú ¨ÌPöˆÂ1Ï%RIɐÇQR€É3À Ú ÉC!CÅ1Æ ÇàßÿҀǩPÉĉñ  G ½ÁˆÜ  Ä ÑxÄ)ÐÁ W € ƈÑm ÇĨÆH̀ Ê3Á£Ç¨ÄHŀÇPÉHÊˈÆHÌ ñIÖ"¨½ÖÓÔ½ú­÷$£ú ÊÎÁÓÇÄ1ÅWÇ Ò€ÇcÊÎÁÓÇÄ1Å@Ü ó¡Ñ1Á€ÊCÉ¨ÄÆà܀Ĉ£̐Ä3ÒIǧ!`ˆÁ½ÜHÒÓÄ3Ò£Á£ÇÝÁPÍ ß ñð% Ç ¨½ÖPE ú YUÞ ó ü ÌÂÓËÐÄHňÆÝÂ")ÌÁ"̽ÒHÂ1ĨÆÐÜ£ÀҐѣÆcÍP̨ÁxÊWÊ3Á£ÇÄ1Å@Ü ÊÎÁÓÇÄHÅ Ú ËPËÌÆW€ß Ê3Á£ÇÄ1Å@Ü û ½ÁˆÜæ÷b½Á½Üxá¨Þg ̽ҀÇÄXHňÆYÊÎÁÓÇÄHÅàÂÓː˨ÌÆW3ÒH£Ä3Ò£Á£ÇÿҐÜ%3õ ó£̽ҀÇÄWÄ1ŽÆc̨ƽÜIɽÀ1Ä ÊÎÁÓÇÄHÅ Ú ËPËÌÆW€á&@ïu Ê4¨ҀÇoñIú Notice the last line of this program uses string concatenation to put a period at the end of the month abbreviation. How do we compute this position? Let’s try a few examples and see what we find. Here is a sample of program output: . the positions all turn out to be multiples of 3. Remember that string indexing starts at 0. month Jan Feb Mar Apr number 1 2 3 4 position 0 3 6 9 Of course. we just subtract 1 from the month number and then multiply by 3.â ¯ s@tvuxwzy|{I} ¯  sˆ‚1ƒ•w€…†y 6 Š†²’ 6 yèt”˜xyè} 6 ŠŒIˆ This would get us the substring of length three that starts in the position indiˆÁ½Ü cated by .

dice. rectangles. You can create a list of numbers or a list of strings.˜ yè} 6 Š†€ˆ ¾ 6 ˆ–y|ˆ £uxŠv‹1˜Ó{ H…†{IŠ ³ {ôˆ ¯  ”H x r” r” r• ‴ G HňÆYÊÎÁÓÇÄHÅàÂÓː˨ÌÆW3ÒH£Ä3Ò£Á£ÇÿÒÜ Ç¨ÄÆ1ÌÐÂYÊÎÁ£Ç¨ÄHŀÇPÉHʨ˽ÆHÌòñ€Ö"¨½ÖÓԈú¬÷5d Ú ¨Ì™ï One weakness of the “string as lookup table” approach used in this example is that it will only work when the substrings all have the same length (in this case. Suppose we want to write a program that outputs the complete month name for a given number. and even students! Using a list of strings. and concatenate lists. slice. As you know from the discussion in Chapter 2. Strings are always sequences of characters. we’ll put all sorts of things into lists like points.1 are not really just string operations. buttons. you can even mix it up and create a list that contains both numbers and strings: ʽÏ)¤3ҐÜxÄWß û Ö@õ§qÅ3ÂIÊ Î  õ°doõèzÙxž In later chapters. . whereas lists can be sequences of arbitrary values. In fact. They are operations that apply to sequences. Python lists are also a kind of sequence. we can rewrite our month abbreviation program from the previous section and make it even simpler. How could that be accomplished? µa”– ©²…Îg€‡penš§‘ ˜¼™‡‘…¨‘ îi„e™·p©q‚ q¦Ÿ‚heŸƒ¬‚„‘ —– —– …˜ # Strictly speaking the operations in Table . three). That means we can also index. as the following session illustrates: û Ö@õôÔgcá û ބõHd© û Ö@õ ԉõ މõÆd© û Ö@õôÔg§Y1Þ (©()( û Ö@õ ԉõªÖ@õ ԉõªÖ“õÔ û Ú Põ (©()( !PÌÂHèƈÜYß Õ  (©()( !PÌÂHÃ¨ÆˆÜ û ) Ú ÷ d) (©()( !PÌÂHÃ¨ÆˆÜ û Ôof û è× Põ ¡ ñ !ḦÂ1èƽܐú (©()( ÀPÆÓÇnë (©()(   } #q   gl… € } g‰ € … õ –× Põ õ HD ¡ 9 One of the nice things about lists is that they are more general than strings.

In general. cannot be changed “in place. the nth month is at position . Lists are mutable. All we need is a new definition of the lookup list. The code that creates the list is split over two lines. but in this case Python knows that the list isn’t finished until  the closing bracket “ ” is encountered. there is an important difference between lists and strings that I should mention. I didn’t even bother to put it in a sepÊÎÁÓÇÄ1Å@Ü û % Ç ¨½ Ö  is used directly in the print statement.âI¹ ó ó s@tvuxwzy|{I} ¯  sˆ‚1ƒ•w€…†y 6 Š†²’ 6 yèt”˜xyè} 6 ŠŒIˆ ÊÎÁÓÇÄ1Å3ÔoïbÏ Ú ¨Ì) Á !ḦÂIÊÐÄÁ£¨Ì3ҀǨĀÄHňÆYÊÎÁÓÇÄHÅàÂÓː˨ÌÆW3ÒH£Ä3Ò£Á£Ç™õI!½ÒWÆÓÇ Ã¨ÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ó ÊÎÁÓÇÄHÅ4ÜcÒ¨ÜcÂWÀ¨Ò¨ÜxÄcÉ4Ü£ÆHÃ݈ÜcÂWÀPÁPÁÎHÉ©ÝÄÂÓË3ÀHÆ Ê ÁÓÇÄHÅ4ÜYß û RHÂxÇÎõXDÆÓË3õ§†öˆÂ1Ì#3õ§ Ú Ì6Îõè†öˆÂ1Ï6Îõ§R€ÉÇxÎõ Î R€É½B À Î õ  Ú C É !63§ õ qÅHÆ 3§ õ  Ä ÑÓ6 Ä Îè õ XШg Á W6Χ õ  ˆÆˆ% Ñ ž ÒÓÄÎÜ ÇPÉHʨ˽ÆH̟ï r ÇàßÿҀǩPÉĉñ  G ÇĨÆH̀ Ê3Á£Ç¨ÄHŀÇPÉHÊˈÆHÌ ñIÖ"¨½ÖÓÔ½ú­÷$£ú ÊÎÁÓÇÄHÅ4Ü û Ç%¨3Öqcá&@ïu ̽ҀÇÄXHňÆYÊÎÁÓÇÄHÅàÂÓː˨ÌÆW3ÒH£Ä3Ò£Á£ÇÿҐÜ%3õ Ê4¨ҀÇoñIú There are a couple of things you should notice about this program. on the other hand. I have creÊÎÁÓÇÄHÅ4Ü ated a list of strings called to use as the lookup table. it is also more flexible. Strings. That means that the value of an item in a list can be modified with an assignment statement. the expression Not only is this solution to the abbreviation problem a bit simpler. Normally a Python statement is written on a single line. Lists. it would be trivial to change the program so that it prints out the entire name of the month. arate step. so in this list the value ÊÎÁÓÇÄ1Å@Ü û ) Õ  RHÂx Ç  Ç ¨3Ö % is the string . ÊÎÁÓÇÄHÅ4ÜYß û RHÂxǐÉ3£̐6 Ï Î õ 3DÆÓËÌHɽÂ1ÌP# Ï Î$ õ †öˆÂ1Ì3ÑI Å 3 õ  Ú ̽ÒHB À 3õ Ú zö½Â£# Ï Î õ R€ÉPǽB Æ Χ õ R€É3À£# Ï 3§ õ  § É !1É4Üx6 Ä Îõ uÅP" Æ ÄƀÊˈÆH# Ì 3 õ  Ä ÑÓĨÁ£ËˆÆH# Ì 3 õ 3Ðg Á W¨Æxʨ˽ÆH6 Ì Îæ õ  ƈÑ1ƀÊˈÆH# Ì X  Before we leave the topic of lists and strings as sequences. For example. are indexed starting with 0. Since this computation is straightforward. Allowing the statement to go across two lines like this makes the code more readable. just like strings.” Here is an example interaction that illustrates the difference: .

After the assignment. Unfortunately. the computer CPU contains circuitry to do arithmetic with these representations. you are starting to get the hang of computing with textual (string) data. the note must pass through the hands. Textual information is represented in exactly the same way.¯  ¯ ˜Óyè} 6 ŠŒIˆ‰uxŠv‹2˜Ó{ ³ }‘{ôy‰sˆ‚£‹I{zˆ (©()( (©()( ‿ ʽÏ)¤3Ò¨Ü€Ä û ÔgcßÐÕ Ï ¤3Ò¨Ü€Ä (©()( ʽ) û Þgdoõ ÔHø„õ ՄõªÖ€Õ) Ï Å1Đ̽ҀC Ç !c& ß 3¢ƨÀÀHÁ`4ˆÁ1̈À1Ã6 (©()( ʽC Ï Å1Đ̽ҀC Ç ! û Ô  (©()( ʽC ôÀ Ï Å1Đ̽ҀC Ç ! û Ô cß (©()( ʽC ÌÂѣƣË3¨ Ñ ÎòñvҀÇPǽÆ1Ì£ÊÎÁˆÜxÄWÀÂˆÜ€Ä4ú­÷ D3Ò1ÀP Æ  ÜxĐýÒIÇ ( 3õ˜À¨Ò€Ç½Æ Ö@õ Ò€Ï Ç P F  Ï ½Æ ̨̐ÁH̟÷ Á£Ë ÆÑÓÄWÐÁÆ½Ü‡Ç ùÄÿÜI) É ©½Á1̐ġÒxÄÆ€Ê (©()( Ö"9 ʽÏ)¤3Ҩ܀ÄWß û Þgdoõ ÔHø„õªÖ"9æõªÖxÕg ʽ) Ï ¤3Ò¨Ü€Ä û Ôg  6 |lh… G ï ‘ ˆÜPÜPÒ £ ! ÇHÊ3Æ£ÇÄ The first line creates a list of four numbers. So you and your friend need to design a scheme for encoding the contents of your message. You are sitting in class and want to pass a note to a friend across the room. of many classmates before it reaches its final destination. Underneath. However. . indexes start at 0). you saw that numbers are stored in binary notation (sequences of zeros and ones). evaluating the list shows that the new value has replaced the old. and in front of the curious eyes. To understand this. of course. Indexing position 2 returns the value 15 (as usual. The next command assigns the value 0 to the item in position 2. you might think in terms of messages and secret codes. And. it is really no different from number crunching. Strings are not mutable. Attempting a similar operation on a string produces an error. Consider the age-old grade school dilemma. we haven’t yet discussed how computers actually manipulate strings. µa”|µ È ÈƒÊ ™™ ©²…Îg€‡penš§‘Wi„e™·p©q‚„ƒogI‚æ…¡ ¢™q·•‚„‘ Ø t"“¡l™wm•¡hjiBÍ%“Hi§sqi•w%tu–§tqlnvxw Hopefully. lists are. In the previous chapter. there is always the risk that the note could fall into enemy hands (the teacher’s). when the computer is manipulating text.

18. and the lowercase versions have codes 97–122. Extended ASCII encodings have been developed by the International Standards Organization to remedy this situation. The ÑIÅÌ character string. You can imagine what a headache this was for people transferring data between different systems. 15. 17.âIâ s@tvuxwzy|{I} ¯  sˆ‚1ƒ•w€…†y 6 Š†²’ 6 yèt”˜xyè} 6 ŠŒIˆ One approach is to simply turn the message into a sequence of numbers. 20. It does not have symbols that are needed in many other languages. One problem with the ASCII encoding. you might use the numbers 1-26 to represent the letters a–z. it represents a word. a much larger standard that includes support for the characters of nearly all written languages. Consider a situation that would result if. Then. This is how a computer represents strings.” To those who don’t know the code. 18. Without too much imagination. and the entire string is stored as a sequence of (binary) numbers in computer memory. 14. PCs and Macintosh computers each used their own encoding. Python provides a couple of built-in functions that allow us to switch back and forth between characters and the numeric values used to represent them ÁH̐à function returns the numeric (“ordinal”) code of a singlein strings. Instead of the word “sourpuss. while goes the other direction. as well as certain special values known as control codes that are used to coordinate the sending and receiving of information. Here are some interac- . is that it is American-centric. however. For you and your friend. It doesn’t really matter what number is used to represent any given character as long as the computer is consistent about the encoding/decoding process. The result would be gibberish! To avoid this sort of problem. the capital letters A–Z are represented by the values 65–90. as its name implies. Newer versions of Python include support for Unicode as well as ASCII. Most modern systems are moving to the support of Unicode. You could choose a number to correspond to each letter of the alphabet and use the numbers in place of letters. different designers and manufacturers used different encodings. computer systems today use industry standard encodings. 20. if the file was read into your instructor’s Macintosh computer. say. ASCII uses the numbers 0 through 127 to represent the characters typically found on an (American) computer keyboard. One important standard is called ASCII (American Standard Code for Information Interchange). In the early days of computing.” you would write “18. the characters in your paper are represented as a certain sequence of numbers. For example. the numbers would be displayed on the screen as different characters from the ones you typed. this looks like a meaningless string of numbers. If you type a term paper on a PC and save it as a text file. Each character is translated into a number.

Using the Python and functions. Since a string is a kind of sequence. !¨Æ1ÄWÄHňÆYÊÎƽÜPÜ1  !¨ÆUĨÁWÆ£Ç4Ñ£ÁPÃÆ Í¨Á1ÌÐƨ¨рŠрŽÂ1ÌÂÑÓĨÆHÌÐҀÇÐÄHňÆYÊÎƈܐÜ1  !¨Æo÷ ̽ҀÇÄcÄHŽÆÝÀHÆHÄPÄÆHÌÈǐÉHʨ˽Æ1ÌÝÁPÍWÄHňÆÐрŽÂ1ÌÂÑÓĨÆHÌ ÌÂ£Û Ò€) Ç É¨Ä Getting the message from the user is easy. we can just use a through all the characters of the message. The algorithm for encoding the message is simple. The simplest apÁ1̨à proach is to use the ASCII number (provided by ) for each character in the message. We need to do something for ͐ÁHÌ each character of the message. ÊÎƈܐܣg  !¨ÆU߀̈£§ Û ÌÒI© Ç É¨Ä„" ñ ŒØˆÀHƨÂÜ£Æ Æ£Ç¨ÄÆHÌWÄ1ŽÆYÊ3ƽܐܣÂg!ÆÈÄÁÝÆÓÇ4Ñ1ÁHèÆo÷æ£ú Implementing the loop requires a bit more effort. we need to convert each character to a number. ͨÁ1ÌÿрŠÒIÇcÊÎƽÜPÜ1  !¨Æn÷ Finally. Here is the final program for encoding the message: ó€Äg Æ ¦PÄÔÓǐÉ1ÊˈÆHÌÎܬU ï ¨Ï Ú Ìg ó Á !PÌ€ÊàĨÁàÑ1Á£c Ç WÆ1̐ÄÐÂUĨ) Æ ¦PÄ1É3ÂPÀ ÊÎƈܐÜ1  !¨ÆÐÒIÇĨÁW¡ܣÆ)í£É½ÆÓÇ4Ñ1ÆUÁPÍ ó ǐÉHʨ˽Æ1ÌÎÜ­õ ÉÄ3Ò1ÀÒ ½Ò€C Ç !UÄ1ŽÆÈɐÇèÆ1̈À1ϽҀC Ç ! Ú ÅHm × ¢)¢ Æ£ÇÎÑ1ÁPÈҀC Ç !Ÿï )h .¯  ¯ ˜Óyè} 6 ŠŒIˆ‰uxŠv‹2˜Ó{ ³ }‘{ôy‰sˆ‚£‹I{zˆ â€é tive examples:  Óú (©()( ÁH̐Éñ ‡B ýþ (©()( ÁH̐Éñ  Ú Óú øc9 (©()( рŨ̄ñzýPþ3ú ô (©()( рŨ̄ñzýPÕ3ú  6 Bšf ™™ È È‘Ç ’”“Hv••“f–B—$—˜l™wm•£–Bw š w•œ)v Bi•“ 6› ÁH̐à ÑIÅÌ Let’s return to the note-passing example. we can write some simple programs that automate the process of turning messages into sequences of numbers and back again. Recall that a loop iterates over a sequence ͨÁ1Ì loop to run of objects. a will take care of that for us.

éq7 s@tvuxwzy|{I} ¯  sˆ‚1ƒ•w€…†y 6 Š†²’ 6 yèt”˜xyè} 6 ŠŒIˆ èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ Ä XHÅÎҨܨÌÁ)!ḦÂIÊ Ñ1ÁÓÇCW¨ÆH̐Ä3ÜÈÂUÄÆg¦PÄ1É3ÀªÊÎƽÜPÜ1Â!¨ÆÐÒIÇÄÁÝÂàÜÓÆ)í£É½Æ£ÇÎÑ1ÆB ̽ҀÇ Ä ‡ÁPÍUÇPÉHʨ˽ÆHÌ3Ü ÌÆ"̨ƽܣÆÓÇĽҀǧ! ÄHÅˆÆ Ú ÅH×m¢©¢ÈÆÓÇ4Ñ£ÁPýÒIǧ!cÁP̀ÄHňÆYÊÎƈܐÜ1Â!¨Æoïq ̽ҀÇÄ ó ü Æ1ÄWÄHŽÆYÊ3ƽÜPÜ1Âg!ÆUÄÁWÆÓÇ4Ñ£ÁPÃ¨Æ Ê ÆˆÜÜ1Â!¨Æc߀Ì£ۧÌҀÇ)É¨Ä„ñ †ØˆÀHƨˆÜÓÆ Î ̽ҀÇÄ ̽ҀÇÄ3¢ˆÆ1ÌÆÝ£ÌÆcÄHÅˆÆ Æ£ÇĨÆHÌWÄ1ŽÆYÊÎƈܐܣÂg!¨Æ ÄÁÝÆ£ÇÎÑ1ÁHèÆn÷ü£ú Ú H Å ×m¢)¢€Ñ1ÁPÐƽܬ÷q óT¤ÁPÁ ÐÄHŨÌÁÓɧ!1ÅWÄHŽÆYÊ3ƽÜPÜ1Âg!ÆWÂÓÇÃ`̽ҀǨÄÐÁ£ÉÄWÄ1Å½Æ Ú ÅP×m¢)¢§WˆÂPÀÓÉˆÆ½Ü Í¨Á1ÌÿрŠҀÇcÊ3ƽÜPÜ1Âg!Æn÷ Ì3ÒIÇÄÝÁ1̨ÃæñvрÅ@ú†õ ócÉ4Ü£ÆàÑ1Á€ÊÊÎÂÈÄÁ`¨Ì3ҀǨÄАÀPÀ€Á£ÇÿÁ£ÇˆÆWÀÒIǽÆoï ̽ҀÇÄ Ê4¨ҀÇoñIú We can use the program to encode important messages. It is represented by the value y£¡ . HÅÎҨܨÌÁ)!ḦÂIÊ Ñ1ÁÓÇCW¨ÆH̐Ä3ÜÈÂUÄÆg¦PÄ1É3ÀªÊÎƽÜPÜ1Â!¨ÆÐÒIÇÄÁÝÂàÜÓÆ)í£É½Æ£ÇÎÑ1Æ ÁPÍUÇPÉHʨ˽ÆHÌ3Ü Ì" Æ ̨ƽܣÆÓÇĽҀ§ Ç ! ÄHÅˆÆ Ú ÅHm × ¢©¢ÈÆÓÇ4Ñ£ÁPýÒI§ Ç !cÁP̀ÄHňÆYÊÎƈܐÜ1Â!¨Æoï ؈ÀHƨÂܣƀÆÓÇÄÆ1̀ÄHňÆYÊÎƈܐÜ1Â!¨ÆUĨÁWÆ£ÇÎÑ1ÁPÐÆn÷ H 4 Å3£ÄàÂ¥ÅPÁ£É¨ÌgPÉ@ܐܝ ¢ˆÆ1ÌÆÝ£ÌÆcÄHÅˆÆ eþ րÕ)dÝýPþ Ú ÅHm × ¢)¢€Ñ1ÁPÐƽܬ÷ ֐ÖxøWސԀýþÝÞ¨ÔTePÞ ÖÖPÖW֐Öxþ ÖPÖd ÖPÖÓÔÿ֐րþÿ֐Ö9ÿ֐Ö9€ÞÞ One thing to notice about this result is that even the space character has a corresponding ASCII code. Our decoder program will prompt the user for a sequence of numbers representing ASCII codes and then print out the text message corresponding to those codes. it would be nice if our friend on the other end had a similar program to turn the numbers back into a readable message. . ™™ È È‘É ’”“Hv••“f–B—$—˜l™wm•£– #œ 6› imœ©v Bi•“ Now that we have a program to turn a message into a sequence of numbers. Let’s solve that problem next.

To do this. but even the first step presents us with a problem. each of which represents one of the numbers. we are going to rely on some more string manipulation operations. a pattern we saw in the factorial program from the previous chapter. the accumulator variable is initialized to be an empty © string. To solve this problem. The algorithm seems simple enough. First. How exactly do we get the sequence of numbers to decode? We don’t even know how many numbers there will be. but Python provides some functions that do just what we need. convert each into a number. we can iterate through the list of smaller strings. . we need to use an accumulator variable.¯  ¯ ˜Óyè} 6 ŠŒIˆ‰uxŠv‹2˜Ó{ ³ }‘{ôy‰sˆ‚£‹I{zˆ éH~ This program presents us with a couple of challenges. that is a string that contains no characters ( ). we’ll address these as we go along. Here is the decoding algorithm: !¨Æ1ÄWÄHňơܣ) Æ í£É½ÆÓÇ4Ñ1ÆUÁPÍcǐÉ1ÊˈÆHÌÎܪÄÁWèÆÑ1ÁHÃ¨Æ ÊÎƈܐܣg  !¨ÆUA ß © ͨÁ1ÌÐƨ¨рÅWǐÉ1ÊˈÆHÌ¡ÒIÇÐÄHŽÆàÒI© Ç PÉę÷ Ñ1ÁÓC Ç WÆ1̐ĀÄ1ŽÆÈÇPÉHÊˈÆH̀ĨÁcÄHňÆÝ"  ©¨Ì" Á Ì3Ò1Â1ĨÆÝрŽÂ1ÌÂÑÓĨÆHÌ ÂHÃPÀÄHŽÆàÑIÅ3£̈ÂÑxÄÆ1ÌcÄÁcÄ1ŽÆWÆÓLjÃÝÁPÍ Ê3ƽÜPÜ1g  !Æ ̽ҀǨĀÄHňÆYÊÎƽÜPÜ1  !¨Æ Ê3ƽÜPÜ1g  !Æ Before the loop. Each time through the loop a number from the input is converted into an appropriate character and appended to the end of the message constructed so far. Here is the complete algorithm: !¨Æ1ÄWÄHňơܣ) Æ í£É½ÆÓÇ4Ñ1ÆUÁPÍcǐÉ1ÊˈÆHÌÎÜYˆÜcÂàÜxÄPÌ3ÒI§ Ç !oõ Ҁ% Ç Å£ÄÌ½Ò€§ Ç ! Ü ½ÀÒxġҀm q Ç Å1Đ̽ҀC Ç !àҀǨÄÁÝÂàÜ£g Æ í1ɈƣÇ4ѣƀÁPÍÿ܌Ê4ÂPÀÀPÆ1ÌÿÜxÄPÌ3ÒI§ Ç !3Ü ÊÎƈܐܣg  !¨ÆUA ß © ͨÁ1ÌÐƨ¨рšÁP̀Ä1Žơ܌Ê4ÀPÀPÆ1Ì¡ÜxÄPÌ3ÒI§ Ç !3ܬ÷ рŽÂÓ§ Ç !ÆUÄHňơÜxÄPÌ3ҀC Ç !WÁPÍWÃˆÒ !ˆÒÓÄÎÜUҀÇĨÁcÄHňÆÈǐÉHʨ˽Æ1Ì¡ÒÓÄWÌ¨Æ ̨ƽÜÓÆ£ÇÄ3Ü Â )½Æ£ÇÃcÄHÅˆÆ Ú ÅHm " × ¢©¢UрÅ3£̈¨ÑÓÄÆ1ÌWͨÁ1̀ÄHŽÂ1ÄcÇPÉHÊˈÆH̀ĨÁYÊÎƈܐÜ1  !¨Æ Ì½Ò€Ç¨Ä ÊÎƈܐÜ1  !¨Æ This looks complicated. Finally. The overall outline of the decoder program looks very similar to the encoder program. we will read the entire sequence of numbers as a single string using ̈ÂÓÛ ÒI© Ç PÉÄ . and use that number to produce the corresponding ASCII character. Then we will split the big string into a sequence of smaller strings. One change in structure is that the decoding version will collect the characters of the message in a string and print out the entire message at the end of the program.

All that we need now is a way of converting a string containing digits into a Æ WˆÂPÀ  function. This function is For our decoder. we will make use of the used to split a string into a sequence of substrings. we could split on the commas. Æ WÀ g : Here are some interactive examples of Ê Å1ÄPÌWA ß q9HՐB Õ  (©()( ǐÉ1• Æ WÀ¬ñùǐÉ1• Ê Å1ÄPÌ4ú (©()( g 9PÕPÕ Æ WÀ¬" ñ ‡g Þ dC9oïùøB þ £ú (©()( g Þ dc9oïùøþ ) . Python number. One way to accomplish this is with the Python This function takes any string and evaluates it as if it were a Python expression. Similarly. Ç !Ÿïôq Ü 3À¨ÒÓĉñ ‡ÞÔ‰õ–g Ô doõ–© Ô 9æë õ 91' þ Îî õ Î õ Óú (©()( ÜxÄPÌ3ҀC û èÞ¨Ô õ –g Ô d Põ ô) Ô 9 Põ ë9Pþ ¡  6 # … # f  f Since our decoder program should accept the same format that was produced by the encoder program. it will split the string wherever a space occurs. . if we have a string of numbers separated by commas. the contains many functions that are useful in string-manipulation programs. It just so happens these strings contain only digits and could be interpreted as numbers. Here’s an example: Ê ½ÁHÌPÄÿÜxÄPÌ3ÒI§ Ç ! (©()( ҇c Ç !Ÿïôq Ü 3À¨ÒÓĉñ 3¢ƨÀPÀPÁcÜxÄPÌ3ÒI§ Ç !ÐÀÒIËÌÂ1̐j Ï uÓú (©()( ÜxÄPÌ3ҀC û p¢ˆÆÀÀPÁ õ ŒÜxÄPÌ3ÒI§ Ç ! Põ ôÀ¨Ò€Ë¨ÌˆÂ1ÌPå Ï  ¡  f Ž … # ! Ü ½ÀÒxÄ q 3¢ƨÀÀHÁàÜxÄPÌ3ÒIǧ!ÝÀ¨Ò€ËÌÂ1ÌPÏåu You can see how has turned the original string 3¢ƨÀPÀPÁ' xÜxĐ̽ҀÇC!6 ‡ÀҀ˨̈£̐Ï坞 into a list of three strings: . For example. Ç !Ÿïôq Ü 3À¨ÒÓĉñ uePþÝÖx) Õ dÝýPþ ֐րøWިԀýþÝސÔTeÞ ֐ÖPÖW֐րþ ֐Öd ÖPÖÓÔÿÖPÖxþ'Óú (©()( ÜxÄPÌ3ҀC û ¡eþ õ vÖx) Õ d õ èýþ õ ‡ÖPÖxø õ èÞ¨Ô Põ –ýPþ Põ –ÞÔ õ ¡eÞ õ vÖÖÖ õ v֐րþ õ ‡ÖP Ö d õ v֐ÖÓÔ õ v֐րþ ¡ f #  } # } 6 # # f}    f # f # } # f  f # — # } Notice that the resulting list is not a list of numbers. namely a sequence of numbers with spaces between. the than spaces by supplying the character to split on as a second parameter. Ü 3À¨ÒÓÄ u function.éIr s@tvuxwzy|{I} ¯  sˆ‚1ƒ•w€…†y 6 Š†²’ 6 yèt”˜xyè} 6 ŠŒIˆ ÊÎÂ1ÄHÅ We saw in Chapter 3 that Python provides a standard library containing ܀ĐÌ3ÒIǧ! library useful functions for computing with numbers. and . it is a list of strings. the default version of split works nicely. Ü ½ÀÒÓÄ q function can be used to split a string at places other By the way. By default.

and evaluates whatever string it is given. Remember.¯  ¯ ˜Óyè} 6 ŠŒIˆ‰uxŠv‹2˜Ó{ ³ }‘{ôy‰sˆ‚£‹I{zˆ (©()( 途 þ ÆgWÀ¬ñ"‡ÞHá©d6Óú ¦WßÐÞn¡ ï9 ÏÝß dŸïðþ Æ WÀ¬" g ñ ž¦@Y (©()( (©()( (©()( Ï £ú 6 Öxøoïfdc9 ¦ ßÐÆgWˆÂPÀ¬ñè̈£ۧÌÒIÇ©É¨Ä„ñ" ǨÄÆ1ÌU (©()( W G ǨÄÆ1ÌÐÂÈǐÉHʨ˽Æ1ÌÝÞnï† Ö d G Ä ¦ (©()( ̽ҀÇT Þnï†Öd ǐÉHʨ˽Æ1ÌA£úPú Æ WÀ g ̈ÂÓÛ Ò€Ç©PÉÄ The last pair of statements shows that the of a produces exactly ÒIÇ©É¨Ä ÒIÇ©PÉÄ expression. evaluates what we would expect from an Æ WˆÂPÀ  what the user types. Ü 3À¨ÒÓÄ q Æ WÀ g Using and we can write our decoder program. óUǐÉ1ÊˈÆHÌÎÜ£Ô1ĨÆ)¦PğïU¨Ï Ú Ìg ó Á !PÌ€ÊàĨÁàÑ1Á£ÇcWÆ1̐ÄÐÂàÜÓÆ)í1ɈƣÇÎÑ1ƀÁHÍ ó Âÿ܀Đ̽Ҁ§ Ç !€ÁP̀Äg Æ ¦Pğï ҇Êc½Á1̐Äÿ܀ĐÌ3ÒIǧ! èÆHÍ Ú P Šק¢©¢ªÇPÉHʨ˽ÆHÌ3ÜcҀǨÄÁ ó¡Ò€ÇÎÑHÀÓÉèÆà܀Đ̽Ҁǧ!WÀҀ˨̈£̐ÏW͐ÁHÌWÄHňơÜq½ÀÒÓĀÍ1ɐÇÎÑÓĽÒ1Á£Çhï Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ Ä XHÅÎҨܨÌÁ)!ḦÂIÊ Ñ1ÁÓÇCW¨ÆH̐Ä3ÜÈÂàÜ£Ægí1ɈƣÇ4ѣƀÁPÍ Ú ÅPק¢©¢ ǐÉ1ÊˈÆHÌÎÜÈҀǨÄÁ' ̽ҀÇ Ä ŒÄHňơÜxÄPÌ3ҀC Ç !WÁP̀ĨÆ)¦HÄWÄHÅ3£ġÒÓÄÝÌ¨Æ ̨ƽÜÓÆ£ÇÄ3Üæïu ̽ҀÇÄ ó ü 1 Æ ÄWÄHŽÆYÊ3ƽÜPÜ1Âg!ÆUÄÁWÆÓÇ4Ñ£ÁPÃ¨Æ Ò€ÇmÅ1Đ̽ҀÇC!cßẄÂÓÛmÌÒIÇ©PÉĄñ"ŒØÀPƨÂÜ£Æ Æ£Ç¨ÄÆ1̀ÄHÅˆÆ Ú P Šק¢©¢ P ¨ Æ£ÇÎÑ1ÁHèÆPêÊÎƈܐܣÂg!¨Æo÷$£ú ó ¤ÁPÁ ÐÄHŨÌÁÓ§ T É !1ÅÐƨÂÑIÅ ÜIÉPË@܀ĐÌ3ÒIǧ!ÝÂxLjÃUËPÉ4ÒHÀ1Ã Ú ÅH×m¢)¢ÊÎƈܐÜ1Â!¨Æ ÊÎƈܐÜ1Â!¨ÆcßA) ͨÁ1ÌcǐÉHQ Ê Å1ÄP̡Ҁǻ܀ĐÌ3ÒIǧ!nïzÜq½ÀÒxĄñvÒIÇ%ţĐÌ3ÒIǧ!3ú¬÷ ˆÜPÑPҐ Ò ÐHÉHÊÐßÐg Æ WˆÂPÀ¬ñùǐÉHQ Ê Å1ÄPÌ4ú ó¡Ñ1ÁÓÇCW¨ÆHÌÄ€Ã½Ò !ˆÒÓÄ3Ü ÄÁÝÂÈǐÉ1ÊˈÆHÌ ÊÎƽÜPÜ1  !¨Æcß Ê3ƽܐܣg  !Æcá¡Ñ€Å¨Ì„ñ†ÂÜPÑPҐ" Ò Ð1ÉHʆú óÐ"  )½ÆÓLjÃàÑIÅ3Â1ÌÂÑxÄÆHÌUÄÁ ÊÎƈܐܣÂg!¨Æ ̽ҀÇÄXHňƀèÆÑ1ÁPÐÆPÃYÊ3ƽÜPÜ1Âg!ÆÐҨܬ÷q3õ ÊÎƈܐÜ1Â!¨Æ Ê4¨ҀÇoñIú .

These programs turned out to be quite simple due to the power both of Python’s string data type and its built-in operations as well as ܀Đ̽Ҁ§ Ç ! extensions that can be found in the library. and takes on each ǐÉ1ʕÅ1ÄPÌ successive (sub)string in the sequence. This number is converted to the corresponding ASCII character via ÊÎƈܐÜ1  !¨Æ appended to the end of the accumulator.2 lists some of the other useful functions of the library. Python is a very good language for writing programs that manipulate textual # ÜxĐ̽ҀC Ç ! data. Here is an example of the program in action: Ê ½ÁHÌPÄUǐÉ1ÊˈÆHÌÎÜ£Ô1Ĩ) Æ ¦PÄ (©()( ҇c HÅÎÒ¨ Ü ¨Ì) Á !ḦÂIÊ Ñ1ÁÓC Ç W¨ÆH̐Ä3ÜÈÂàÜ£g Æ í1ɈƣÇ4ѣƀÁPÍ Ú ÅP§ × ¢©¢ ǐÉ1ÊˈÆHÌÎÜÈҀǨÄÁ ÄHňơÜxÄPÌ3ҀC Ç !WÁP̀Ĩ) Æ ¦HÄWÄHÅ3£ġÒÓÄÝÌ¨Æ ̨ƽÜÓÆ£ÇÄ3Üæï ؈ÀHƨÂܣƀÆÓÇÄÆ1̀ÄHÅˆÆ Ú ÅH×m¢©¢ ¨PÆÓÇ4Ñ1ÁHèÆHà ÊÎƈܐܣÂg!¨Æo÷ eÞ ÖPÖxø ÖP Ö d Öx© Õ 9ÿÖÖ€Õ ÖxÕÞ ÖPÖ"9€ÞÔ€ýþ ֐Öqd ÖxÕ3ÖYިԀþÕ HňƀèÆÑ1ÁPÐÆPÃYÊ3ƽÜPÜ1g  !ÆÐҨܬ÷çÅ1ÄPÌ3ÒIǧ!3Ü Â1ÌÆED1ÉÇ  ÖPÖxþ ÖPÖxÕWÞÞ ™ ™ ™ Ÿ )  È È t %i•“ Ø t"“¡l™wm• ¡Ÿ 5Í'i•“H–§tqlnvxw%s Now we have a couple of programs that can encode and decode messages as sequences of ASCII values. A good way to learn about these functions is to try them out interactively. evÒI% Ç Å£ÄÌ3ÒI§ Ç ! ÊÎƈܐܣg  !¨Æ has been processed and contains the decoded ery number in text. ͨÁ1ÌcǐÉ1ʕÅ1ÄP̡Ҁǻ܀Đ̽Ҁǧ!nïzÜu3ÀÒxĄñŒÒ€Ç%ţĐ̽Ҁǧ!3ú¬÷ ˆÜHѐҐ Ò ÐHÉ1ÊàßÐg Æ WÀ¬ñùǐÉ1• Ê Å1ÄPÌ4ú ÊÎƈܐÜ1  !¨Æcß Ê3ƽÜPÜ1g  !Æcá¡Ñ€Å¨Ì„ñzˆÜPÑPҐ Ò ÐHÉHʆú Ü 3ÀÒxÄ u ǐÉ1Ê•Å£ÄÌ The function produces a sequence of strings. When the loop is finished. the next substring is converted to a number by ing рÅÌ and it. and you should be able to understand exactly how it accomplishes its task. Ê ½ÁHÌPÄÿÜxÄPÌ3ÒI§ Ç ! (©()( ҇c ß 3¢ˆÆÀÀHÁ„‰ õ ¢€Ñ1€ÊÎÆÈňÆH̨ÆcͨÁ1ÌàÂÓÇÿÂ1© Ì !1É1ÊÎƣǨ# Ä  (©()( Ü & Ç !Ÿï–ÑH"  ÎÒÓĐÀÒ ¨Æ¬ñ‡Ü¨ú (©()( ÜxÄPÌ3ҀC f¢ƨÀPÀPÁ„õ ÒWÑH€Ê3ÆÈŽÆ1ÌƀͨÁ1ÌÐÂÓÇ Â£c Ì !1É1ÊÎÆÓÇÄ Ç !Ÿï–ÑH"  ÛˆÁ1̨Ã3Ü@ñ‡Üú (©()( ÜxÄPÌ3ҀC  )h  . The heart of the program is the loop. I called the loop variable to emphasize that its value is a string of digits that represents some number. . Table . Each Æ WˆÂPÀ  time through the loop.é ¯ s@tvuxwzy|{I} ¯  sˆ‚1ƒ•w€…†y 6 Š†²’ 6 yèt”˜xyè} 6 ŠŒIˆ Study this program a bit.

The study of encryption methods is an increasingly important sub-field of mathematics and computer science known as cryptography. In fact. For example.¯  ¯ ˜Óyè} 6 ŠŒIˆ‰uxŠv‹2˜Ó{ ³ }‘{ôy‰sˆ‚£‹I{zˆ Ú Ç Ú Ìc!1É1ÊÎÆÓÇÄ Ü x P Ä 3 Ì € Ò C Ç Ÿ ! ð ï P À 1 Á  Û H Æ ‰ Ì ‡ ñ ¨ Ü ú (©()( pňƨÀPÀPÁ„õ ÒWÑH€Ê3ÆÈŽÆ1ÌƀͨÁ1ÌÐÂÓÇ Â£Ìc!1É1ÊÎÆÓÇÄ Ç !Ÿï © É ©ˆÆH̉ñ‡Ü¨ú (©()( ÜxÄPÌ3ҀC f¢ ¤)¤ Ä ˜ õ ¢È× Ú ö ¢   D Ä   Ú Ð Ú   ü ِö Щ G G G G G Ç !Ÿï–ÌÆ ½ÀÂ¨Ñ1ÆæñvÜ­ õ "¢%3‰ õ ŒÏ¨Á£ÉÓú (©()( ÜxÄPÌ3ҀC f¢ƨÀPÀPÁ„õ ÏÁ£É Ñ1€Ê3Æ Å½Æ1ÌƀͨÁ1ÌàÂÓÇÿ£c Ì !1É1ÊÎÆÓÇÄ Ç !Ÿï–Ñ1ƣǨÄÆ1̄ñ‡Ü†õ–ÞPÕ3ú (©()( ÜxÄPÌ3ҀC f¢ƨÀPÀPÁ„˜ õ ¢€ÑH€Ê3ÆÈŽÆ1ÌƀͨÁ1ÌÐÂÓÇ Â£c Ì !1É1ÊÎÆÓÇÄ x Ü P Ä 3 Ì € Ò Ç C Ÿ ! – ï 1 Ñ £ Æ ¨ Ç  Ä 1 Æ „ Ì ‡ ñ † Ü õ ë H 9 3 Õ ú (©()( ¢ˆÆÀÀHÁ„‰ õ ¢€Ñ1€ÊÎÆÈňÆH̨ÆcͨÁ1ÌàÂÓÇÿÂ1© Ì !1É1ÊÎÆ£Ç¨Ä Ç !Ÿï–Ñ1Á£ÉPÇĉñ‡Ü­õ –Æ vú (©()( ÜxÄPÌ3ҀC f¢ƨÀPÀPÁ„õ˜¢Èר€Ê3Æ£¢ˆÆ1ÌÆEDÁ1Ì é€´              9 (©()( 9 (©()( (©()( ÜxÄPÌ3ҀÇC!ŸïpͽҀÇÉñvÜ­õ Põ Œú ÜxÄPÌ3ҀÇCŸ ! ï ÁˆÒIÇnñ û X1 Ð ÉHʨ˽ÆHÌ6Îõ‰vÁ£Ç½Æ‰õ3õŒÄ1ŽÆBÎõèX¤Â1̽рÅXÎú ï HÐ1ÉHʨ˽ÆHÌWÁ£Ç½Æ‰õlÄHňÆE¤ˆÂ£Ì3Ñ€Å Ü ÄPÌ3ҀÇC!Ÿï ÁˆÒIÇnñ û XÐ1ÉHʨ˽ÆHÌ6Îõ‰vÁ£Ç½Æ‰õ3õŒÄ1ŽÆBÎõèX¤Â1̽рÅXoõvͨÁPÁ'Óú x ï HÐ1ÉHʨ˽ÆH̐ͨÁPÁÁ£ÇˆÆ„õðͨÁÁ1ÄHňÆPͨÁPÁg¤¨Â1̽рŠ€ f g g    Ü 3ÀÒxÄ u I should mention that many of these functions. we are simply using an industrystandard mapping of characters into numbers. like . Python also has a number of other standard libraries for text-processing that are not covered here. You can consult the online documentation or a Python reference to find out more. if you shop over the Internet. You should realize that there is nothing really secret about this code at all. it is important that your personal information such as social security number or credit card number . The process of encoding information for the purpose of keeping it secret or transmitting it privately is called encryption. accept additional parameters to customize their operation. ™™ È È‘× ¢ “fvx— šdwQœ©v 'l™w%•VtuvSšdwQœm“ QÍmtqlnvxw £› q¤ We have looked at how computers represent strings as a sort of encoding problem. Each character in a string is represented by a number that is stored in the computer as a binary representation. Anyone with a little knowledge of computer science would be able to crack our code with very little effort.

éI¹ s@tvuxwzy|{I} ¯  sˆ‚1ƒ•w€…†y 6 Š†²’ 6 yèt”˜xyè} 6 ŠŒIˆ Function ÑH  4ÒxĈÀ¨Ò Ææñ‡Üú ÑH  ¨ÛÁH̨ýܓñvܨú Ñ1ÆÓÇĨÆH̄ñvÜ­õ ÛÎÒ£ÃHÄHÅ@ú Ñ1ÁÓɐǨĄñ‡Ü†õÜ‡ÉË“ú ͽÒILjÃæñ‡Ü­õÜIɐË@ú ÁҀÇoñ†ÀҐÜxÄÎú ï À É@܀Ąñ‡Ü†õîÛ3Ò£ÃPÄ1œú ï ÀPÁ£ÛˆÆ1̄ñ‡Üú ÀˆÜ€ÄÌ½ Ò nñvܨú Ì" Æ 3ÀPÂÑ1Ƭñ‡Ü†õ–Á¨À1Ã3܇ɐ˙õ–ǽƣÛ4ÜIÉP˓ú ̨͈ҀÇÉñ‡Ü†õÜ‡ÉË“ú Ì É@܀Ąñ‡Ü†õùÛ3Ò£ÃPÄ1œú ï ÌÎ܀Đ̽ Ò nñvܨú Ü ½ÀÒxĄñ‡Üú q É©)½Æ1̄ñ‡Üú !h Meaning Ü Copy of with only the first character capitalized Ü Copy of . Each character of the original message. it would still be easy to discover the original message. first character of each word capitalized Ü ÛÎÒÓÃPÄHÅ Center in a field of given ÜIÉPË Ü Count the number of occurrences of in Ü‡ÉË Ü Find the first position where occurs in ÀÒ¨Ü€Ä Concatenate of strings into one large string ѣƣǨÄÆHÌ Ü Like . Usually. but is right-justified Ü Copy of with trailing whitespace removed Ü Split into a list of substrings (see text) Ü Copy of . the transformation is based on combining the message with some other special value called the key. Our simple encoding/decoding programs use a very weak form of encryption known as a substitution cipher. much like our encoding program. is replaced by a corresponding symbol (in our case a number) from a cipher alphabet. Then sophisticated mathematical algorithms are employed to transform these numbers into other numbers. Even if our cipher were not based on the well-known ASCII encoding. but returns the rightmost position ѣƣǨÄÆHÌ Ü Like . the party on the receiving . Since each letter is always encoded by the same symbol. a code-breaker could use statistical information about the frequency of various letters and some simple trial and error testing to discover the original message. The resulting code is called the ciphertext. but is left-justified Ü Copy of in all lowercase characters Ü Copy of with leading whitespace removed ÁÀHÃ3Ü‡ÉË Ü Ç½Æ£Û4Ü‡ÉË Replace occurrences of in with ͈ҀÇà Like . Modern approaches to encryption start by translating a message into numbers. but they are certainly not up to the task of securing communication over global networks. In order to decrypt the message. Such simple encryption methods may be sufficient for grade-school note passing.2: Some components of the Python string library be transmitted using encodings that keep it safe from potential eavesdroppers on the network. called the plaintext. all characters converted to uppercase # Table .

let’s extend our month abbreviation program to do date conversions. 2003. Only the party holding the decryption key will be able to decipher it.” and the program will display the date as “May 24. charts. This is the usual system that people think of when considering secret codes. ™ ȑ×ÈƒÊ š#›§–B—$ٌ͕i§Ú Í'ÍBÙnl‡œ)–mtqlnvxw ©¨œ ¤ª –§tui vxwmk§i•“Hslnvxw As a concrete example. consider a program that does financial analysis. After doing some number crunching. For example. For example. the encryption key can be made publicly available. String operations are needed to handle these basic input and output tasks. The user will input a date such as “05/24/2003. Then only the company that is requesting the information will be able to decrypt and read it using the proper private key. In a public key system. while the decryption key is kept private.g. Encryption approaches come in two flavors: private key and public key. the results of the analysis will typically be a nicely formatted report including textual information that is used to label and explain numbers. All parties that wish to communicate need to know the key. In public key systems. In a private key system the same key is used for encrypting and decrypting messages. but it must be kept secret from the outside world. tables. Knowing the encryption key does not allow you to decrypt messages or discover the decryption key.” Here is the algorithm for our program: Å"½ÀÒxÄWãÄÆcţĐ̡ÒIÇĨÁYÊÎÁ£Ç¨ÄHşõ¢Ã£ÏàÂÓLjÀϨƨ£ÌÿÜxÄPÌ3ҀÇC!3Ü ¢IÇ)É¨Ä€ÄHňƀÃÂ1ĨÆàҀÇcÊPʕŸHÃPÃCŸ£ÏÏÏPπ͐ÁHÌ£ÊÎÂ1Ä ñ–ãÄÆcţĐÌÎú × ÁÓÇCW¨ÆH̐ÄcÄHŽÆYÊ3Á£Ç¨ÄHŠ܀ĐÌ3ÒIǧ!àÒIÇĨÁÝ ÊÎÁ£Ç¨ÄHÅWÇPÉHÊˈÆHÌ  Ù@ÜÓÆcÄHňÆYÊÎÁ£Ç¨ÄHŀÇPÉHʨ˽ÆHÌcÄÁÝÀPÁPÁÎHÉ©ÐÄHÅˆÆ ÊÎÁÓÇÄ1ÅWÇ3€Ê3Æ . dates) must be entered as strings.. a secure web site can send your web browser its public key. and figures. there are separate but related keys for encrypting and decrypting. and the browser can use it to encode your credit card information before sending it on the Internet. µa”|º t–e„¤²¦o… §¦ „xW¦o…3¤§¦n…€iŸ‘Щ²…Îg€‡penš kmi„eh‡–¤§¦„j io…ˆ‡™£e Even programs that we may not view as primarily doing text manipulation often need to make use of string operations.¯  ´Pcu Šxw€…†y qџ…zyèwx…zy¬uŒˆd˜xyè} 6 ŠŒ ä§uxŠ 6 wx…± u†y 6 ‚HŠ q¥ 逿 end needs to have an appropriate key so that the encoding can be reversed to recover the original message. Some of the information (e. Anyone can safely send a message using the public key for encryption.

It’s the Swiss army knife of string conversion. It is very general and can be used to turn strings into nearly any other Python data type. otherwise you will get an error. If the string to be converted has a leading zero. You can also convert strings into numbers using the Python numeric type ÒIÇĉñIú ͨÀPÁÂ1Ąñ‡ú ÀHÁ£C Ç ! . ãĩ Æ Å1Đ̀߀̈£ۧÌÒIÇ©É¨Ä„ñ" ǨÄÆ1ÌWÂcèÂ1ÄÆòñ–ʐÊQŸHÐÃcŸ1ÏPϐϐÏÎú¬÷‰£ú G ÊÎÁÓÇÄ1% Å Å1ÄPÌnõ ÃÂ1C Ï Å1ÄPÌnõlϨƨÂ1C Ì Å1ÄPÌWßÿÜxÄPÌ3ҀC Ç !Ÿïôq Ü 3À¨ÒÓĉñôãĩ Æ Å1ĐÌo‰ õ qŸ•£ú Here I have gotten the date as a string and split it at the slashes. Þ Óú (©()( ҀǨĄñ v' Þ Þ £ú (©()( ÍÀHÁ¨Â1ĉñ v' ÞnïùÕ ï 9•£ú (©()( ÍÀHÁ¨Â1ĉñ vÞn¡ ÞnïH9 ï 9B£ú (©()( ҀǨĄñ vÞnH ÌÂѣƣË3¨ Ñ ÎòñpÊÎÁˆÜxÄW̨ƈÑ1ÆÓÇÄ¡Ñ1ÀPÀ€ÀÂÜxÄ4ú­÷ D3Ò1ÀP Æ  ÜxĐýÒIÇ ( 3õ˜À¨Ò€Ç½Æ Ö@õ Ò€Ï Ç P F ۈÂPÀÓÉˆÆ ÌPÌÁ1̙÷˜ÒIC Ç WÀÒÓÃÝÀÒxÄÆ1̈À ͨÁ1ÌÿҀÇĉñIú­÷lÞnH ï9 G As the last example shows. the string passed to these conversion functions must be a numeric literal of the appropriate form. In the Æ WˆÂÀ  ASCII decoding program. . strange things can happen. I then Ê3Á£ÇÄ1Å%Å£ÄÌ ÃÂ£Ï§Å£ÄÌ “unpacked” the list of three strings into the variables . ()) that were covered in Chapter 3. conversion functions ( Here are some quick examples. and ÏƐÂ1C Ì Å1ÄÌ using simultaneous assignment. we used the function to convert from a string Æ WÀ g data type into a numeric data type. Æ WˆÂPÀ¬ñIú  There is one subtle “gotcha” to consider when choosing between and ҀǨĄñ‡ú to convert strings into numbers. . Recall that evaluates a string as a Python expression. ÊÎÁÓÇÄHm Å Å1ÄPÌ The next step is to convert into an appropriate number.éIâ s@tvuxwzy|{I} ¯  sˆ‚1ƒ•w€…†y 6 Š†²’ 6 yèt”˜xyè} 6 ŠŒIˆ ×H̨ƨ£ÄÆWÂÈǽƣÛÝãÄơ܀ĐÌ3ÒIǧ!àÒIÇàͨÁ1Ì£ÊàöˆÁÓÇÄ1Å Ä É¨g Ä PÉĀÄ1ŽÆÈǽƣÛÐãÄÆ¡ÜxÄPÌ3ÒI§ Ç !  “ ½Â£Ïnõ ƐÂ1Ì We can implement the first two lines of our algorithm directly in code using string operations we have already discussed. Õ 9•£ú (©()( ҀǨĄñ vc 9 (©()( ҀǨĄñ v  ÕÎրþ'£ú . Take a look at these examples.

and ¡ ¸ . computer scientists and engineers sometimes find it convenient to uses number systems with bases that are powers of 2. The octal value wC…q‡ is equal to the decimal value …ux . when using the leading zeroes are simply ignored. ÆWˆÂPÀ¬ñIú ? It turns out that Python allows int literals to But what’s going on with be expressed in other number systems in addition to the usual base 10 (decimal).g. don’t ҀǨĄñ‡ú º worry about it. and octal uses only the digits w – ‡ . Just be sure that you use when converting strings (e. If this seems weird to you. As you know. So why does Python support number systems other than decimal? Contrary to what you might think. Python interprets it as a base 8 (octal) number. Here is the code: ÊÎÁÓÇÄ1Å@ÜYß û RHÂxǐÉ3£̐6 Ï Îæ õ XDÆÓËÌ1É3Â1ÌP# Ï 3 õ †öˆÂ1̽р Å 3§ õ  Ú ̽ÒHB À 3õ †ö½Â£# Ï 3§ õ RIɐǽB Æ Χ õ R€É½À1# Ï 3§ õ  Ú § É !£É@Üx6 Ä Îõ qÅP" Æ ĨÆxÊˈÆH6 Ì Î õ  Ä ÑxÄÁ£ËˆÆH6 Ì Î õ 3Ð Á WÆxʨ˽Æ1# Ì Îæ õ  ƈѣÆxÊˈÆH6 Ì ž û ÊÎÁÓÇÄ1% Å Å1ÄPÌWß ÊÎÁÓÇÄ1Å@Ü Ò€Ç¨Ä„ñpÊ3Á£Ç¨ÄH% ŠţĐÌÎú ¨3q Ö  3& &  ҀÇĉñpÊ3Á£ÇÄ1% ŠţĐÌ4" ú ¨3Ö Remember the indexing expression is used because indexing of lists starts with 0.¯  ´Pcu Šxw€…†y qџ…zyèwx…zy¬uŒˆd˜xyè} 6 ŠŒ ä§uxŠ 6 wx…± u†y 6 ‚HŠ Öxþ (©()( e (©()( 9 (©()( q¥ é€é ҀǨĄñ v  Õ©eB£ú ÆgWÀ¬ñ"‡Õ©9B£ú ÆgWÀ¬ñ"‡Õ3Öxþ'Óú ÆgWÀ¬ñ"‡Õ)e'£ú F F Ö"9 ÌÂѣƣË3¨ÑÎòñpÊÎÁˆÜxÄW̨ƈÑ1ÆÓÇÄ¡Ñ1ÀPÀ€ÀÂÜxÄ4ú­÷ D3Ò1ÀPÆ D3Ò1ÀPÆ (©()( Õ©e Å1Ï1ÇÄÂg¦ G « ÜxĐýÒIÇ ( 3õ˜À¨Ò€Ç½Æ Ö@õ ҀÇÏP ÜxÄPÌ3ÒIǧ! ( ΢ õ ÀҀLjÆÿÖ ÌÌ¨ÁH̙÷lҀÇcWˆÂPÀÒ£ÃUÄÁÎÆ£Ç Ò€Ç¨Ä„ñIú As you might expect. The last step in our program is to piece together the date in the new format. computers represent numbers using binary (base 2). it isn’t just to trip up new programmers. we can turn into a ÒIÇÄ number using and then use this value to look up the correct month name. so w is an illegal number. If an int literal starts with a 0. . Ê3Á£ÇÄ1% Å Å£ÄÌ Returning to the date conversion algorithm. dates) that may contain leading zeroes. Because of this.

the output looks like this: ǨÄÆ1ÌЀÃÂ1Ä¨Æ ñpÊPʕŸ1ÐÃCŸ£ÏÏPϐÏ4ú­÷ Õ©9©ŸÔdCŸPÔPՐÕPÞ G HňÆàÑ1ÁÓC Ç WÆ1̐ĨÆPÃcèÂ1ĨÆàÒ¨Üæ÷îöˆÂ1Ïà Ô doõ ÔPÕPÕÞ This simple example didn’t really show it. most data types can be converted into Ü€ÄÌ function. but often it is also necessary to turn a number into a string. Here’s the complete program: óWãÄÆÑ1Á£c Ç WÆ1̐ęb ï Ï ó ×PÁ£C Ç W¨ÆHÌPÄÎÜ Â€Ã¨Â1ÄÆÝҀÇàͨÁ1Ì£Ê èʐ• Ê Ÿ1Ðc à Ÿ1ϐÏPϐ6 Ï Ä Á èÊÎÁÓÇÄHÅÝÃÂ1ÏoõlÏƐÂ16 Ì  ҇Êc½Á1̐Äÿ܀ĐÌ3ÒIǧ! èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ó !¨Æ1ÄWÄHŽƀèÂ1Ä¨Æ ¥ ãÄc Æ Å£ÄÌW߀Ì£§ Û ÌҀÇ)É¨Ä„ñ  G ǨÄÆH̀ÂcãÄÆòñ–ʐʕŸ1ÐÃcŸ1ϐÏPϐÏÎú¬÷‰£ú óÿq Ü ½ÀÒÓÄÿÒIÇĨÁÐÑ1Á€C Ê ½ÁÓǽÆÓÇÄÎÜ ÊÎÁÓÇÄHÅmÅ1ÄPÌnõlèÂ1ÏCÅ1ĐÌoõlÏƐÂ1ÌCÅ1Đ̀ßÿÜxĐ̽ҀÇC!ŸïzÜu3À¨ÒÓĄñ–ãÄÆcţĐÌoõ‰qŸBÓú ó¡Ñ1ÁÓC Ç WÆ1ÌÄ 3 Ê Á£Ç¨ÄHÅ%ţĐ̀ĨÁcÄHňÆYÊÎÁ£Ç¨ÄHŀǽ€Ê3Æ ÊÎÁÓÇÄHÅ4ÜYß û RHÂxǐÉ3£̐Ï6Îõ3DÆÓËÌHɽÂ1ÌPÏ#Îõ$†öˆÂ1Ì3ÑIÅ3õ Ú ̽ÒHÀB3õ zö½Â£Ï#ÎõR€ÉPǽÆBÎõ§R€É3À£Ï#3õ§ Ú É§!1É4ÜxÄ6Îõ uÅP" Æ ÄƀÊˈÆH# Ì 3 õ  Ä ÑÓĨÁ£ËˆÆH# Ì 3 õ 3Ðg Á W¨Æxʨ˽ÆH6 Ì Îõæ ƈÑ1ƀÊˈÆHÌ#X û ÊÎÁÓÇÄHm Å Å1ÄP̀ßÈÊÎÁÓÇÄHÅ4Ü Ò€ÇĉñpÊ3Á£ÇÄ1% ŠţĐÌ4" ú ¨3q Ö   ó Á£É¨ÄgÉ¨Ä€ÌƈÜIɽÀ1ÄÿҀÇcÊ3Á£Ç¨ÄHÅÐèÂ1Ïnõ¢Ï¨Æ¨Â£ÌWͨÁ1Ì£Ê4Â£Ä Ý ̽ҀÇÄXHňÆàÑ1ÁÓÇCWÆ1̐ĨÆPÃcèÂ1ĨÆàÒ¨Üæ÷uÎõ Ê3Á£Ç¨ÄHÅ%ţĐÌoõlãϧţĐ̨á'ÎõÎõ Ϩƨ£̧Å1ÄPÌ Ê4¨ҀÇoñIú When run. In Python. Here are a couple of simple examples: strings using the ñ 9HՐսú (©()( ÜxÄP̄3 ë9HÕÕ Ö d (©()( WˆÂPÀÓɽÆUßàÞoïŒq ñ WÀxɽÆ3ú (©()( ÜxÄPÌ„Ò  f .~877 s@tvuxwzy|{I} ¯  sˆ‚1ƒ•w€…†y 6 Š†²’ 6 yèt”˜xyè} 6 ŠŒIˆ ̽ҀǨÄAX1ŽÆàÑ1ÁÓÇCW¨ÆH̐ĨÆPÃUÃÂ1ĨÆàҨܬ÷qÎõ ÊÎÁ£Ç¨ÄHÅmÅ1ĐÌoõ¢Ã£ϧţĐ̨á'ÎõÎõ ÏÆ¨Â£Ì§Å£ÄÌ Notice how I have used concatenation for the comma immediately after the day.

If we didn’t first WˆÂÀxÉ½Æ á turn into a string.3 summarizes these five Python type conversion functions:  … q¥ ~87H~ Function ͨÀPÁÂ1Ąñ Æg¦Ì ( ú F ÒIÇĉñ g Æ ¦¨Ì ( ú F ÀHÁ£C Ç !‰ñ ) Æ ¦ Ì ( F ܀Đ̉ñ g Æ ¦¨Ì ( ú F Æ WˆÂPÀ¬ñ ÜxÄPÌ3ҀC  Ç ! ( ú F Meaning Æ ¦ Ì ) Convert to a floating point value. because “. Just for fun. day. # Table . For nicely formatted output. a program performing date calculations would have to manipulate the month. By turning into a string. ܀ĐÌ3ÒI§ Ç ! Evaluate as an expression. we can use string concatenation to put a period at the end of a sentence.” is not a number. Python would interpret the as a numerical operation and produce an error. Table .¯  ´Pcu Šxw€…†y qџ…zyèwx…zy¬uŒˆd˜xyè} 6 ŠŒ ä§uxŠ 6 wx…± u†y 6 ‚HŠ –ÞoïŒÖqd  ̽ҀÇÄXHňÆEWˆÂPÀÓɽÆÝÒ¨Ü%3õÜxÄP̄ñÒWÀxɽÆ3úªáA@ïu (©()(  HňE Æ WˆÂPÀÓɽÆÝÒ¨ÜÈÞnï† Ö dnï WÀxÉ½Æ Notice particularly the last example. these numbers would be converted back to strings. here is a program that inputs the day. Æ ¦ Ì ) Convert to an integer value. For example. Æ)¦ Ì Return a string representation of . and year as numbers. and year as numbers and then prints out the date in two different formats: óWãÄÆÑ1Á£c Ç WÆ1̐ĈԄU ï ¨Ï ó אÁÓC Ç WÆ1̐Ä3ÜYãÏÈÊÎÁ£Ç¨ÄHÅ¡ÂxLjÀϨƨÂ1ÌcÇPÉHʨ˽ÆHÌ3ÜcҀǨÄÁUÄHۈÁ€Ã¨Â1Äƀ͐ÁHÌÓÊ4Â1Ä3Ü Ò‡Êc½Á1̐Äÿ܀ĐÌ3ÒIǧ! èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ó !¨Æ1ÄWÄHŽƀèÂ1ÏÈÊ3Á£ÇÄ1Å¡ÂÓÇÀÏƐÂ1Ì ¥ ãÏnõ ÊÎÁÓÇÄ1řõlϨƨÂ1Ì€ß ÒI© Ç PÉĄ" ñ ŒØÀPƨÂÜ£ÆÈƣǨÄÆH̀ÃÂ1Ïoõ ÊÎÁÓÇÄHşõ ÂÓÇÀÏƐÂ1ÌcǐÉ1ÊˈÆHÌÎܬ÷æÓú ãÄÆÎÖªß Ü€ÄÌ‰ñpÊÎÁÓÇÄ1œúxá'qŸ•vá3܀Đ̉ñôãÏ4úIá6uŸB†á3ÜxÄP̉ñèÏÆPÂ1ÌÎú . We now have a complete set of operations for converting values among var# ious Python data types. Æ ¦ Ì ) Convert to a long integer value. month.3: Type Conversion Functions One common reason for converting a number into a string is so that string operations can be used to control the way the value is printed.

This technique is useful for simple formatting. Here is how the result looks: ؈ÀHƨÂܣƀÆÓÇÄÆ1ÌWãÏnõ Ê3Á£ÇÄ1řõ ÂxLjÀϨƨÂ1ÌcÇPÉHʨ˽ÆHÌ3Üæ÷ Ôgdoõî9æõ ÔPÕPÕÞ HňƀãÄÆàÒ¨£ Ü 9)Ÿ Ô dCŸÔHՐÕPÞcÁH̀öˆÂ1Ïà Ô doõ ÔPÕPՐÞoï ™ ȑ×È‘Ç Ø t"“¡l™wm• ¢ vB“8—î–mtžtql™wm• As you have seen. We can fix this problem by changing the very last line of the program as follows: ¬ . Let’s start with a simple example.~87€r s@tvuxwzy|{I} ¯  sˆ‚1ƒ•w€…†y 6 Š†²’ 6 yèt”˜xyè} 6 ŠŒIˆ û RHÂxǐÉ3£̐Ï6Îõ3DÆÓËÌHɽÂ1ÌPÏ#Îõ$†öˆÂ1Ì3ÑIÅ3õ Ú ̽ÒHÀB3õ zö½Â£Ï#ÎõR€ÉPǽÆBÎõ§R€É3À£Ï#3õ§ Ú É§!1É4ÜxÄ6Îõ uÅP" Æ ÄƀÊˈÆH# Ì 3 õ  Ä ÑÓĨÁ£ËˆÆH# Ì 3 õ 3Ðg Á W¨Æxʨ˽ÆH6 Ì Îõæ ƈÑ1ƀÊˈÆHÌ#X û ÊÎÁÓÇÄHÅmÅ1ÄP̀ßÈÊÎÁÓÇÄHÅ4Ü ÊÎÁ£Ç¨ÄHm Å ¨3 Ö  ãÄƨÔÈßUÊ3Á£Ç¨ÄH% ŠţĐ̐6 á Efá ܀Đ̄ñ–ãÏ4ú & á 3è õ fá ܀Đ̉ñ–ÏƐÂ1ÌÎú ÊÎÁÓÇÄHÅ4ÜYß  ̽ҀÇÄXHňƀãÄÆàÒ¨ÜmÎõ¢Ã¨Â1ĨÆÎ֓õ‡ÁHÌ6Îõ˜Ã¨Â1ÄƐÔHá'@ïq Ê4¨ҀÇoñIú Notice how string concatenation is used to produce the required output. Here is a run of the change counting program from last chapter: ףŽÂÓC Ç !¨Æ€×PÁ£ÉÇ¨ÄÆ1Ì ØˆÀHƨÂܣƀÆÓÇÄÆ1̀ÄHňÆàÑ1ÁÓɐÇÄÐÁHÍÝƨ¨рŠÑ1ÁҀÇÝÄPÏgˆÆnï ÐÁcÏÁ£ÉWŽ  W¨§ Æ PUø ¢ˆÁ£ÛUÊ4ÂxÇÏÝýÒvÊÎƈÜYèÁcϨÁ£ÉWÅ3 WC Æ PÈÕ ¢ˆÁ£ÛUÊ4ÂxÇÏcÇ4ÒP Ñ ÎƨÀˆÜ èÁ€ÏÁÓɀÅ3 WC Æ PUÕ ¢ˆÁ£ÛUÊ4ÂxÇE Ï ½ÆÓǐÇÎÒ1Æ½Ü Ã¨Á€ÏÁÓɀÅ3 WC Æ PUÕ HňÆcÄÁ1ĈV À WˆÂÀxɽÆWÁH̀ÏÁ£É¨Ì¡Ñ€Å½ÂÓC Ç !¨ÆàÒ¨ÜÐֆ¡ ï9 ¢ˆÁ£ÛUÊ4ÂxÇÏ í1ɽÂ1ÌPÄÆHÌ3Ü Notice that the final value is given as a fraction with only one decimal place. since we expect the output to be something like . Ö­ïH9PÕ This looks funny. but building up a complex output through slicing and concatenation of smaller strings can be tedious. basic string operations can be used to build nicely formatted output. Python provides a powerful string formatting operation that makes the job much easier.

” ̨ؐƈÑPÒ¨ÜPÒ£Á£Ç is used with floating-point values to indicate the desired number of ¨ÕoïèÔ1Í digits after the decimal. There must be exactly one slot for each value. The value of will be inserted into the template in place of the end: ĨÁHĐÀ specifier. Û3Ò£ÃPÄ1Å ̨ƈÑPÒ¨ÜPÒ£Á£Ç The and portions of a specifier are optional. Returning to the example. float. The specifier also tells Python that is a floating point number that should be rounded to two decimal places. (Python also allows ints to be printed using a number of different bases. ÛÎÒÓÃPÄ1Å tells how many spaces to use in displaying the value. we will only use the normal decimal representation. the percent sign is the remainder operation. If a value requires Û3Ò£ÃHÄHÅ ÛÎÒÓÃPÄHÅ . If present. Decimal mode is used to display ints as base-10 numbers. With strings. and string. In general. the template contains a single specifier at the ÕnïèÔ1Í ÄÁ1ĈÀ . " " . the percent sign is a string formatting operator. obviously. We will use three different format types: decimal. we need to look at the structure of the specifier. Python will just expand the so that more room than is given in ÛÎÒÓÃPÄ1Å the value fits. You can use a 0 to indicate “use as much space as needed.¯  ´Pcu Šxw€…†y qџ…zyèwx…zy¬uŒˆd˜xyè} 6 ŠŒ ä§uxŠ 6 wx…± u†y 6 ‚HŠ ̽ҀǨÄAX1ŽÆcÄÁ1ĈÂPÀ`WˆÂPÀÓɽÆWÁH̀ÏÁÓÉÌÿрŽÂÓÇC!¨ÆÐÒÜ q¥ ~87€” ñèÄÁHĐÀˆú ¬ " ­" ¨ÕoïèÔ1Í6 Now the program prints this message: HňÆcÄÁ1ĈÀVWˆÂÀxɽÆWÁH̀ÏÁ£É¨Ì¡Ñ€Å½ÂÓÇC!¨ÆàÒ¨Ü Let’s try to make some sense of this. A formatting specifier has this general form: Û3Ò£ÃPÄ1Å ( ï ¨ÌÆѐҨÜHÒ1ÁÓÇ ( ÄÏ ½© Æ ¨чÅ3Â1Ì ( " " F F F The specifier starts with a and ends with a character that indicates the data type of the value being inserted. Each of the slots is described by a format specifier that tells Python how the value for that slot should appear.) Float and string formats are used for the corresponding data types. The example specifier tells Python to insert a floating-point value using as much space as necessary and rounding it to two decimal places. The easiest way to get the hang of formatting is just to play around with some examples in the interactive environment. To understand the formatting. When used with numbers. the string formatting operator is used like this: ĨÆxc Ê 3ÀÂ£Ä© Æ ¨ˆÜxÄPÌ3ÒI§ Ç ! ( ©ñ WˆÂPÀÓÉ½ÆˆÜ ( ú F " ¬ Ö­ïH9PÕ " F ĨÆxÊc3ÀÂ£ÄÆ©¨ˆÜxÄPÌ3ÒIǧ! WˆÂPÀÓÉˆÆ½Ü Percent signs inside the mark “slots” into which the are inserted.

Suppose you are writing a computer system for a bank.56.g.. Given what you have learned about floating point numbers.” They want to know that the bank is keeping precise track of . you might be a little uneasy about using them to represent money. If the width in the specifier is larger than needed. Your customers would not be too happy to learn that a check went through for an amount “very close to $107. Using explicit formatting allows you to see the full result down to the last bit. You can left-justify the value in the field by preceding the width with a minus sign (e.~87 ¯ (©()( s@tvuxwzy|{I} ¯  sˆ‚1ƒ•w€…†y 6 Š†²’ 6 yèt”˜xyè} 6 ŠŒIˆ (©()( (©()( (©()( (©()( (©()( ž" ®"  ° "   ° "    "  "   Ž" "   3¢ƨÀÀHÁ f¢ƨÀPÀPÁÈöÌ™ïÆŀÊ@ÒÓÄ1řõlϨÁ£ÉcÊ4£ÏcÅ3 WÆݐÀ£ÌƐÂHÃPÏÈۈÁÓÇ H1Å4Ò¨ÜUҀÇÄoõ 3Ü ½Ü­õ¢Ï¨Á£ÉcÊ4£ÏcÅ3  W ÆUۈÁÓÇ H1Å4ҐÜcҀǨÄnõ C91ÃoõlÛ½ÂÜ$3ÀPÂÑ£ÆPáҀÇÿÂc͈Ò1ƐÀHÃÝÁPÍcÛ3Ò£ÃHÄHÅ¡9 ¬ " ¯" ¬ PÃjž ñ †öÌ™ïuÎõ§uŀʓÒxÄHÅxÎõfրՐՐÕPÕ3ú ÖxÕPՐÕPÕ  ñôþ3ú ñôþ3ú ñôÞnï†Öd4Ö9PýÔPø3ú þ„õlۈˆÜ3ÀPÂÑ£ÆPÃàÒIÇÿÂW͈Ò1ƐÀHÃWÁHÍcÛÎÒ£ÃHÄHÅa9 H1Å4ҐÜcҀǨÄnõ H1Å4Ò¨Ü H1Å4Ò¨ÜUҀÇÄoõ 4րÕPÃoõî۽ˆÜ½ÀÂ¨Ñ1ÆPÃÐҀÇÿ€ͽңƨÀHÀÁPÍcÛÎÒÓÃPÄ1Å¥ÖxÕ þ„õlۈˆ Ü ½ÀÂÑ£ÆPÃàÒIÇÿÂcͽңƨÀHÃÝÁHÍcÛÎÒÓÃPÄHÅ»ÖxÕ ÖxÕÐÂxLją̃ƈÑPÒ¨ÜPÒ£Á£ÇS9oï ÖxÕÐÂxLj£ à ̨ƈÑPÒ¨ÜPÒ£Á£S Ç 9oï Í ÀPÁÂ1Äoõ 4րÕnï¡91ÍoõîÅ½ÂˆÜ 3  Û Ò£ÃPÄ1Å H1Å4ҐÜYÍÀHÁ¨Â1Äoõ ÞoïŒ Ö dÎÖ"9Hý„õ Å½ÂˆÜ 3 Û Ò£ÃPÄ1Å H1Å4ҐÜYÍÀHÁ¨Â1Äoõ˜Þnï†ÖdÎÖ"9Pý‰õîÅ3ÂÜ H1Å4Ò¨Ü ÍÀPÁÂ1Äoõ ¨Õoï¡9Ḧ́õîÅ3ÂÜ ÛÎÒÓÃPÄHÅ¡ÕÝÂxLjã¨ÌƈÑPÒ¨ÜHÒ1Á£ÇS9oï ÛÎÒÓÃPÄHÅÐÕàÂxLjã¨ÌƈÑPÒ¨ÜHÒ1Á£ÇS9oï ‡×PÁxC Ê ½Â1Ì¨Æ ÍàÂxLjà ¨ÕoïèÔHÕP6 Í  ©ñzÞnï† Ö d„õ˜Þnï† Ö dÎú –×PÁxÊc3Â1̨ƀÞnï†ÖdÕÕÕPՀÂxLjÃÝÞnï†ÖdÕÕÕPՐÕPՐՐÕPՐÕPՐՐÕ3ÖÓÔd¨Þ)d ±" 3 6 °  " 6 }°}"  uu° "  3 3°" ñôÞnï†Öd4Ö9PýÔPø3ú } A couple of points are worth noting here. If not given an explicit precision. " ™ ȑ×È‘É ² iCtžtui•“ pª³  ®ª %–'wm•'i vxr6wmtui•“ Let’s close our formatting discussion with one more example program.14 exactly as a floating-point number. The slight extra amount shows up if you print lots of digits. The last example shows that if you print enough digits of a floating-point number.” The computer can’t represent 3.14. Python will print the number out to a few decimal places. The closest value it can represent is ever so slightly larger than 3. C¨genïùÞPÍ ). you will almost always find a “surprise. Python only displays a closely rounded version of a float. the value is right-justified in the field by default. Generally.

¯  ´Pcu Šxw€…†y qџ…zyèwx…zy¬uŒˆd˜xyè} 6 ŠŒ ä§uxŠ 6 wx…± u†y 6 ‚HŠ q¥ ~87€´ their money. and the resulting error could add up to some real cash. then we can get ĨÁHĈÂP¥ À ŸÿÖxÕPÕ ÄÁ1ĈÂPÀ »ÖxÕÕ the number of dollars by and the cents from . We can do that by keeping track of the money in cents and using an int (or long int) to store it. If represents the value in cents. Notice that the backslash must appear outside of the quotes. We can then convert this into dollars and ÄÁHĐÀ cents in the output step. Even though the amount of error in a given value is very small. Sometimes it is nicer to break a long statement into smaller pieces. Both of these are integer calculations and. This example also illustrates one additional twist on format specifiers. Here is the updated program: ó¡Ñ€Å½ÂÓC Ç !¨Æ¨Ô„U ï ¨Ï Ú ̨) ó Á !PÌ€ÊàĨÁàÑHÂPÀрɽÀÂ£ÄÆUÄ1ŽE Æ WˆÂPÀÓɈƀÁPÍÿÜÓÁxÊÎÆàÑIÅ3Âx§ Ç !¨ÆÝҀÇàèÁÀÀPÂ1ÌÎÜ ó HÅÎÒ¨è Ü WÆ1ÌÎÜHÒ1Á£Ç€Ì" Æ ÌƈܣÆÓÇÄÎܪÄHňÆcÄÁHĐÀÐÑ1ˆÜIÅÿÒ€Ç Ñ1ÆÓÇÄ3Üæï Ž" èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ Ä ‡×£Å½ÂÓÇC!¨Æ€×PÁ£ÉÇ¨ÄÆ1Ì# ̽ҀÇÄ ̽ҀÇ Ä ŒØˆÀHƨÂܣƀÆÓÇÄÆ1̀ÄHňÆàÑ1ÁÓɐÇÄÐÁHÍÝƨ¨рŠÑ1ÁҀÇÝÄPÏgˆÆnïq í1ɽÂ1̐ĨÆHÌ3Ü ßÿҀ) Ç Éĉñ  ÓÉ3£̐ĨÆHÌÎܬ˜ ÷ £ú ýÒvÊÎÆ½Ü ß ÒI© Ç PÉĄ" ñ  3҇ÊÎƈÜæ‰ ÷ £ú Ç4ÒP Ñ ÎˆÆÀˆÜYß¡ÒI© Ç PÉĄ" ñ XнҐ Ñ ÎƨÀÜæ‰ ÷ £ú ½ÆÓǐÇ4ңƽÜYß¡ÒI© Ç PÉĄ" ñ ŒØ¨Æ£ÇÇÎÒ1ƈÜæ‰ ÷ £ú ÄÁ1ĈÀÈS ß í£É3£̐ÄÆ1ÌÎ` Ü YW) Ô 9cáWýÒvÊÎƽT Ü YàրՀácÇ4ҐÑΈƐÀˆÜEYE9€á£½ÆÓǐÇÎÒ1Æ½Ü ̽ҀÇÄ ̽ҀÇ Ä XHňÆcÄÁ1ĈV À WˆÂÀxɽÆWÁH̀ÏÁ£É¨Ì¡Ñ€Å½ÂÓC Ç !¨ÆàÒ¨Ü Ãnï ¨ÕÔH' à  ñ–ĨÁHĐ© À Ÿ½ÖxÕPՄõ ĨÁHĐÀ ÎÖxÕPÕ3ú   " u" ¬ " q" ¯´ Ê4¨ҀÇoñIú Ì½Ò€Ç¨Ä I have split the final statement across two lines. A better approach would be to make sure that our program used exact values to represent money. The value of cents is printed with the specifier . it would be considered part of the string literal. one for dollars as an int and one for cents as an int. Normally a statement ends at the end of the line. the small errors can be compounded when doing lots of calculations. A backslash at the end of a line is one way to indicate that a statement is continued on the following line. hence. will give us exact results. The string formatting in the print statement contains two slots. That’s not a satisfactory way of doing business. otherwise.

Of course. Files can contain any data type. One critical feature of any word processing program is the ability to store and retrieve documents as files on disk. is really just another form of string processing. cents prints as èÂ1ĨƈÑ1ÁÓÇCW¨ÆH̐ÄÔoïbÏ By the way. a file is a sequence of data that is stored in secondary memory (usually on a disk drive). " ¨ÕÔHà ¬ ¬ µa”–ê 𧇖j ‚p—¢gI™qƒ¬‚„‘‘ˆ‡peŸš I began the chapter with a reference to word-processing as an application of the string data type. string formatting would also be useful in the program. for Ó Let’s take a look at a concrete example. This ensures that a value like 10 dollars and 5 ÖxÕoïðÕc9 րÕnï 9 rather than . You can think of newline as the character produced when you press the ǨÄÆHÌ ÓåG 0 key on your keyboard. Files of text have the advantage that they can be read and understood by humans.~87€¹ s@tvuxwzy|{I} ¯  sˆ‚1ƒ•w€…†y 6 Š†²’ 6 yèt”˜xyè} 6 ŠŒIˆ . text files can be very flexible. as it turns out. A special character or sequence of characters is used to mark the end of each line. (e. You might want to try redoing that program using string formatting in ÜxĐ̉ñIú place of and concatenation. You can think of a text file as a (possibly long) string that happens to be stored on disk. it is represented in Python (and many other computer languages) using the special ‡Ç notation . ™ Sµ È ÈƒÊ ¶ ‡·)¸ r•Ùˆtql Ql™w%i Ø t"“Hl™w%•'s Conceptually. we’ll take a look at file input and output.. but the easiest files to work with are those that contain text. In this section. a typical file generally contains more than a single line of text. Although a newline is a single character. There are numerous conventions for end-of-line markers. which. Other special characters are represented using a similar notation €Ä ÂÓË 0 ). Suppose you type the following lines into a text editor exactly as shown here: B¹ B ¹ ‘ ¢ˆÆÀÀHÁ . In Python. and they are easily created and edited using general-purpose text editors and word processors. Python uses a single character called newline as a marker.g. since it is easy to convert back and forth between strings and other types. The zero in front of the width tells Python to pad the field (if necessary) with zeroes instead of spaces.

Once a file has been opened. this includes operations that allow us to read the information from a file and write new information to a file. it is manipulated through the variable we assign to it. Here is the example from above printed interactively: Ä 3¢ˆÆÀÀHÁ Ó© Ç 4ˆÁ1̈ÀHà ÓÇ ÓÇ ü ÁÁHÃ1ËÏ¨Æ Þ¨Ô Óx Ç  (©()( ̽ҀÇ ¢ˆÆÀÀHÁ 4ˆÁ1̈À1à %´ %´ º´ €´ %´ %´ º´ €´ ü ÁPÁPãËÏÆcÞ¨Ô (©()( If you simply ask Python to evaluate a string containing newline characters. you can ¨Ì3ÒIÇÄ produce multiple lines of output with a single statement. Typically. First. Second. you will just get the embedded newline representation back again. the reading and writing operations for text files are similar to the operations for text-based. ¢ l‘ÙŒi¥’”“Hvxœ©i§ssl™wm• The exact details of file-processing differ substantially among programming languages. we need a set of operations that can manipulate the file variable.¯  ¹Pcó 6 ± {q3}‘‚ ³ {ôˆ–ˆ 6 Š† 4ˆÁ1̈À1à ~87€¿ ü ÁPÁPãËÏÆcÞ¨Ô When stored to a file. you get this sequence of characters. but virtually all languages share certain underlying file manipulation concepts. we need some way to associate a file on disk with a variable in a program. by embedding newline characters into output strings. At the very least. (©()( 8¢ˆÆ¨ÀPÀPÁ ÓÇc4ÁHÌÀHà xÇ xÇ ü ÁPÁPÃÓËÏ¨Æ Þ¨Ô ÓÇ f¢ƨÀPÀPÁ xc Ç 4ÁḦÀ1à xÇ ÓÇ ü ÁPÁPÃ1˨ÏÆ ÞÔ xÇ  %´ g´ ´ `´ ´ `´ ™ Sµ È È‘Ç g´ ‘€ ´ It’s only when a string is printed that the special characters affect how the string is displayed. By the way. . ¢ˆÆÀÀHÁ ÓÇ©4ˆÁ1̈ÀHà ÓÇ ÓÇ ü ÁÁHÃ1ËÏ¨Æ Þ¨Ô ÓÇ Notice that the blank line becomes a bare newline in the resulting file/string. interactive input and output. This process is called opening a file.

we could use a statement like the following: ҀÇͽÒ1ÀPÆcßÐÁ ˆ  Æ£Çoñ z  ÇPÉHʨ˽ÆHÌ3ÜæïpÃÂ1Ä6Îõ‰†Ì#£ú ÒILj͈ÒHÀPÆ ÇÉHʨ˽Æ1ÌÎÜæïpÃ壀 Now we can use the variable to read the contents of from the disk. the file is closed (again in the programming sense). The changes will not show up in the file on the disk until you tell the application to “save” it. As you “edit the file. The ŒÌ6 zÛx parameter is either the string or depending on whether we intend to read from the file or write to the file.~87€â s@tvuxwzy|{I} ¯  sˆ‚1ƒ•w€…†y 6 Š†²’ 6 yèt”˜xyè} 6 ŠŒIˆ Finally. read its contents into memory. closed the file. the file is opened for reading and the contents of the file are then read into memory via file reading operations. you have actually opened a file. this time in a mode that allows it to store information—the file on disk is opened for writing. First. However. File writing operations are then used to copy the current contents of the in-memory version into the new file on the disk. When you open a file in a program like Microsoft Word. Python provides three related operations for reading information from a file: . The first step is to associate a file Á ½Æ£Ç " function. the original file on the disk is reopened. to open a file on our disk called “numbers. the file is actually read from the disk and stored into RAM. when we are finished with a file. In programming terminology. it is closed. Closing a file makes sure that any bookkeeping that was necessary to maintain the correspondence between the file on disk and the file variable is finished up. the changes might not show up on the disk version until the file has been closed. the concepts are not exactly the same. At this point. created a new file (having the same name). and closed the new file. Working with text files is easy in Python.dat” for reading. Saving a file also involves a multi-step process. Doing so actually erases the old contents of the file. not the file itself. From your perspective. with a variable using the F ͈ÒHÀHÆgWˆÂ£Ì ( ßàÁ"½ÆÓÇnñ Ç3ÂIÊÎÆ F ( õ F ÊÎÁHÃ¨Æ ( ú Ç3ÂIÊÎÆ ÊÎÁHÃ¨Æ Here is a string that provides the name of the file on the disk. For example. From the program’s perspective. For example.” you are really making changes to data in memory. if you write information to a file variable. it appears that you have edited an existing file. This idea of opening and closing files is closely related to how you might work with files in an application program like a word processor. written the (modified) contents of memory into the new file.

whereas discards the newline character. is that the string returned by will always end with ÌÂ£Û Ò€) Ç ÉÄ a newline character. This is analogous to ̈ÂÓÛ ÒI© Ç PÉÄ ÇĨÆHÌ . which reads characters interactively until the user hits the ÓåG 0 ̈ÂÓÛ ÒI© Ç PÉÄ key. multi-line) string. As a quick example. Each list item is a single line including the newline character at the end. 0 ï–ÌƐÂHÉñ‡ú Here’s an example program that prints the contents of a file to the screen ÌƐÂHà using the operation: ó ̽ҀǨĨͽÒ1ÀPÆoïUÏ £ ó ؐ̽ҀÇÄ3ÜÈ€ͽÒ1ÀPÆcÄÁcÄ1ŽơÜHÑÓÌÆPÆ£Çhï èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ Í1ǽ€ÊÎÆUßÝÌ£ۧÌҀÇ)É¨Ä„ñ  ¨ Ç ÄÆHÌÈ͈ÒHÀPÆÓÇ3ÂIÊÎÆn÷ü£ú G ҀÇͽÒHÀHÆcßÝÁ ˆÆ£ÇoñôÍ1ǽ€Ê3Ƅõ ùÌ Œú ãĈÂcߡҀÇͽÒ1ÀPÆnï–ÌƐÂHÉñ‡ú ̽ҀÇĀÃÂ1Ä g  Ê4¨ҀÇoñIú The program first prompts the user for a file name and then opens the file for ҀÇͽÒ1ÀPÆ reading through the variable . ÒILjͽÒ1ÀPÆ I used to emphasize that the file was being used for input. ̨ƨÂHèÀÒIÇ½Æ The operation can be used to read the next line from a file. Printing causes the contents to be displayed. You could use any name for the variable. ͽÒ1ÀPÆgWÂ1Ì ï–ÌƐÂHÃÀ¨Ò€ÇˆÆæñIú Returns the next line of the file. One thing to keep ÌƐÂHÃÀ¨Ò€ÇˆÆ in mind. this fragment of code prints out the first five lines of a file: ҀÇͽÒ1ÀPÆcßÐÁ ˆÆ£Çoñ‡Ü£Á€ÊÎ Æ D3ÒHÀHƄõ ðÌ vú ͨÁ1ÌÿÒWҀÇà̈Âx§ Ç !Ææ3 ñ 9ˆú¬÷ ÀÒIǽƀߡҀÇͽÒ1ÀPÆnï–ÌƐÂHÃÀ¨Ò€ÇˆÆæñIú ̽ҀÇÄÝÀÒ€ÇˆÆ û ¡ ÷ ¨3q Ö  ® … . each call to gets another line from the user.¯  ¹Pcó 6 ± {q3}‘‚ ³ {ôˆ–ˆ 6 Š† ͽÒ1ÀPÆgWÂ1Ì Ó ~87€é Ó Ó Returns the entire remaining contents of the file as a single (potentially large. That is all text up to 0 and including the next newline character. The entire contents of the file is then read as one large string and stored in the variable ãĈ Ã£Ĉ . Suc̨ƨÂHèÀÒIÇ½Æ cessive calls to get successive lines from the file. however. ͽÒ1ÀPg Æ WÂ1Ì ï–ÌƐÂHÃÀ¨Ò€ÇˆÆ½Ü“ñ‡ú 0 Returns a list of the remaining lines in the file.

a new file will be created. and writes that string to the file. If you want to start a new line in the file. make sure you do not clobber any files you will need later! Here is an example of opening a file for output: Á£É¨Ä¨ÍˆÒHÀPÆUßÝÁ ½  ÆÓÇnñ"–ʽϐãĈÂoïùÁ£É¨Ä#ÎõüzÛx£ú ېÌ3ÒxÄÆ We can put data into a file. Python will delete it and create a new. One way to loop through the entire contents of a file is to read in all of the ÌƨÂ1ÃÀ¨Ò€Ç½ÆˆÜ file using and then loop through the resulting list. When writing to a file.~I~37 s@tvuxwzy|{I} ¯  sˆ‚1ƒ•w€…†y 6 Š†²’ 6 yèt”˜xyè} 6 ŠŒIˆ Notice the use of slicing to strip off the newline character at the end of the line. Fortunately.. which must be a string. So looping through the lines of a file can be done directly like this: Ò ÇͽÒ1ÀPÆcßÐÁ ˆÆ£Çoñ‡Ü£Á€ÊÎÆD3ÒHÀHƄõ ðÌ vú € ͨÁ1ÌàÀÒIǽÆàÒ€Ç ÒILj͈ÒHÀPÆo÷ ó ̨ÁˆÑ1ÆˆÜÜ Ä1ŽÆÝÀ¨Ò€Ç½ÆÈňÆHÌ¨Æ £ ҀÇͽÒ1ÀPÆnï–ÑHÀHÁ½Ü£Æ¬ñIú ® … This is a particularly handy way to process the lines of a file one at a time. except that is a little less flexible.e. and reading it into a list all at once may take up too much RAM. ͈ÒHÀHÆc¨WÂ1Ì ( ï–ېÌ3ÒxÄÆæñ ܀ĐÌ3ÒIǧ! F ( ú ̽ҀÇÄ Û¨Ì½ÒÓÄÆ ÛÌ3ÒÓÄ¨Æ This is similar to . A word of warning: if a file with the given name does exist. ҀÇͽÒ1ÀPÆcßÐÁ ˆÆ£Çoñ‡Ü£Á€ÊÎÆD3ÒHÀHƄõ ðÌ vú ͨÁ1ÌàÀÒIǽÆàÒ€Ç ÒILj͈ÒHÀPÆoïp̨ƨÂHèÀÒIǽƽÜ@ñIú­÷ ó ̨ÁˆÑ1ÆˆÜÜ Ä1ŽÆÝÀ¨Ò€Ç½ÆÈňÆHÌ¨Æ £ ҀÇͽÒ1ÀPÆnï–ÑHÀHÁ½Ü£Æ¬ñIú ® … Of course. you must explicitly provide the newline character. Python treats the file itself as a sequence of lines. printing with the explicit newline at the end would put an extra blank line of output between the lines of the file. Here’s a silly example that writes two lines to a file: . using the F operation. Opening a file for writing prepares that file to receive data. a potential drawback of this approach is the fact that the file may be very large. The operation takes a single parameter. it outputs a newline). ̽ҀÇÄ Since automatically jumps to the next line (i. If no file with the given name exists. there is a simple alternative. empty file.

program input and output is done through files. you must first convert it. its old contents would be destroyed. This code will produce a file on disk called “example.¯  ¹Pcó 6 ± {q3}‘‚ ³ {ôˆ–ˆ 6 Š† Á£É¨Ä¨ÍˆÒHÀPÆUßÝÁ ½ÆÓÇnñ"‡Æ)¦¨Â€Êc3ÀPÆoïðÁÓÉÄ#3õ ùÛ Œú Ñ1ÁÓɐǨÄWᯙ Á£É¨Ä¨ÍˆÒHÀPÆoï–ېÌ3ÒÓĨÆæñ"XHÅÎÒ¨ÜYÒ¨ÜYÄ1Žƀ͈ÒÓÌÎ܀ÄÐÀÒIÇ½Æ ÓÇÓú Ñ1ÁÓɐǨÄWßÿÑ1Á£ÉPÇÄWá»Ö Á£É¨Ä¨ÍˆÒHÀPÆoï–ېÌ3ÒÓĨÆæ" ñ XHÅÎÒ¨ÜYÒ¨ÜUÀ¨Ò€ÇˆÆ ǐÉ1Ê˽Æ1Ì ' à  ©ñvÑ1ÁÓɐǨÄ4úú Á£É¨Ä¨ÍˆÒHÀPÆoïôÑ1ÀPÁ½ÜÓÆæñ‡ú ~I~€~ ®  " ¯" g´ Ñ£Á£ÉPÇÄ Notice the use of string formatting to write out the value of the variable . If you want to output something that is not a string.out” containing the following two lines: HÅÎҨ܀ҐÜYÄHŽƀ͈ÒÓÌ3ÜxÄÐÀ¨Ò€Ç½Æ HÅÎҨ܀ҐÜUÀÒ€ÇˆÆ ÇÉ1ÊˈÆHÌàÔ If “example. the process would probably not be done interactively. The program produces an output file containing a line for each generated username. Our previous version created usernames interactively by having the user type in his or her name. Our new program is designed to process a file of names. ™ Sµ È È‘É š#›§–B—$ٌ͕iT’”“fv••“f–'— »§ ² ºŸ¼ –mtqœ –si•“ëwQ–B—îims To see how all these pieces fit together.out” existed before executing this fragment. In batch processing. the string-formatting operator is often a handy way to do this. but in batch mode. óUÉ@ÜÓÆH̐ͽÒHÀHÆnb ï Ï ó ØPÌ) Á !ḦÂIÊÐÄÁ¡ÑxÌƨ£ÄÆWÂc͈ÒHÀHÆWÁPÍUÉ@ÜÓÆHÌ1Ç3€Ê3ƽÜÈҀÇWË3£Ä3ÑIÅcÊÎÁPÐÆnï ҇Êc½Á1̐Äÿ܀ĐÌ3ÒIǧ! èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ Ä XHÅÎҨܨÌÁ)!ḦÂIÊ ÑǪ́ƨ£ÄÆ½Ü ̽ҀÇ Ä vͽÒ1ÀPÆWÁHÍUÇ3€Ê3ƽܬïq ó¥!¨Æ1ÄWÄHŽƀ͈ÒHÀHÆÈÇ3€Ê3Æ½Ü ÂW͈ÒHÀHƀÁPÍcÉ@ÜÓÆHÌ1Ç3€Ê3Æ½Ü ÍPÌÁ€Ê ÂB . If we were setting up accounts for a large number of users. Each line of the input file will contain the first and last names of a new user separated by one or more spaces. let’s redo the username generation program.

It’s not unusual for a program to operate on several files simultaneously. you should also notice the line that writes the username to the file. Without this. one for input ( ) and one for output ( ). Á£ÉĐͽÒ1ÀPÆnï|ۨ̽ÒÓÄƬñðÉPÇ3€Ê3ÆPá ÓÇ Œú }Q´  Concatenating the newline character is necessary to indicate the end of line. I have two files open ҀLj͈ÒHÀHÆ ÁÓÉĐͽÒHÀHÆ at the same time. I used the function from the library. we use dot notation. For example. all of the usernames would run together in one giant line. Also.~I~†r s@tvuxwzy|{I} ¯  sˆ‚1ƒ•w€…†y 6 Š†²’ 6 yèt”˜xyè} 6 ŠŒIˆ ҀÇͽÒHÀHg Æ Ð€ÊÎÆÈ߀̈ÂÓm Û ÌÒI© Ç PÉĄ" ñ 34HÅ3Â1ÄUͽÒ1ÀPÆÝ£ÌÆcÄHÅˆÆ Ç3ÂIÊÎƈ܀ҀǕPvÓú Á£É¨Ä¨Í½Ò1ÀPÆЈ€Ê3ÆU߀Ì£Ûm̨ҀÇ)Éĉñ 84PÅ3£Äc͈ÒHÀHÆàÜIňÁ£É3À1ÃcÄHňÆÈÉ@ÜÓÆHÌHǽ€Ê3ƽÜè!ÁàҀǕPvÓú óÝÁ ˆÆ£ÇÐÄHňƀͽÒ1ÀPÆ½Ü Ò€ÇͽÒHÀHÆcßÝÁ ˆÆ£ÇoñvҀÇͽÒ1ÀPÆgЀÊ3Ƅõ ðÌ Œú Á£É¨Ä¨Í½Ò1ÀPÆcßÝÁ"½ÆÓÇnñzÁÓÉĐͽÒHÀHÆgЀÊÎƉõ ùÛ Œú ó£̨ÁˆÑ1ÆˆÜÜ ÆÂÑIÅÿÀҀLjƀÁPÍWÄ1ŽÆàҀÇ)É¨ÄWͽÒ1ÀPÆ Í¨Á1ÌàÀҀLjÆÐҀǻÒILjͽÒ1ÀPÆo÷ ó !¨ÆHÄWÄ1Žƀ͈ÒÓÌÎ܀ÄÐÂÓÇÃÐÀÂÜxÄcÇ3ÂIÊÎƈÜYÍP̨ÁxÊ  ¥ À ÒIÇ½Æ Í½ÒÓÌ3ÜxÄoõ ÀÂÜxÄÝßÿÜxÄPÌ3ÒI§ Ç !Ÿïôq Ü ½ÀÒÓĉñ†À¨Ò€Ç½Æ½ú ó¡ÑÓÌƐÂ1ĨÆUÄHňÆÈÉ@Ü£Æ1ÌHǽ€ÊÎÆ ÉÇ3ÂIÊÎÆcß Ü€ÄÌ3ÒI§ Ç !nïèÀPÁ£ÛˆÆ1̄ñô͈ÒÓÌ3ÜxÄ û ) Õ PáÀHˆÜxÄ û ÷ù) þ ½ú ócÛ¨Ì3ÒxÄÆàÒxÄWÄÁcÄHňÆWÁ£É¨g Ä É¨ÄWͽÒ1ÀPÆ Á£ÉĐͽÒ1ÀPÆnï|ۨ̽ÒÓÄƬñðÉPÇ3€Ê3ÆPá ÓÇ Œú ¤®   }Q´  ó¡ÑHÀHÁ½Ü£ÆÈˈÁHÄ1ÅÐͽÒ1ÀPÆ½Ü Ò€ÇͽÒHÀHÆnï–ÑHÀPÁˆÜ£Æ¬ñIú Á£É¨Ä¨Í½Ò1ÀPÆoïôÑHÀHÁ½ÜÓÆæñIú ̽ҀÇÄzÙ@ÜÓÆHÌ1Ç3€Ê3ƽÜÅ3ÂW¨ÆÈ˽ÆPÆ£ÇÝۨ̽ÒÓÄPÄƣǀÄÁBÎõ Á£É¨Ä¨ÍˆÒHÀPÆЈÂIÊÎÆ Ê4¨ҀÇoñIú There are a few things worth noticing in this program. ™ Sµ ™ ª È È vx—‰l™wm•£Úgtžt"“f–Qœ)tqlnvxw ©¨½Ÿƒ¾s¿ 3imœ)tus Have you noticed anything strange about the syntax of the file processing examples? To apply an operation to a file. even if the input names are mixed case. Finally. when ÀHÁ1ÛÆHÌ ÜxÄPÌ3ҀÇC! creating the username. to read . This ensures that the username is all lower case.

ʽC Ï Å1ÄPÌ3ҀC Ç !Ÿïôq Ü 3À¨ÒÓĉñIú ~I~†” is equivalent to ÜxÄPÌ3ÒIǧ!ŸïôÜq½ÀÒÓĉñpʈϧÅ1ÄPÌ3ÒIǧ!Îú We’ll discuss list methods in detail in Chapter 11. slicing ( ).  )½ÆÓLjà " the method can be used to add an item at the end of a list. String literals can be delimited with either single or double quotes. Just to whet your appetite. Here’s a fragment of code that creates a list of the squares of the first 100 natural numbers: Ü í£É3£ÌÆ½Ü ß û  " ͨÁ1  Ì ¦¡Ò€Çà̈Âx§ Ç !Ææñ€Ö@õ‡Ö€ÕÎÖPú­÷ Ü í£É3Â1̨ƽܬïè" "  )½ÆÓÇˆÃ‰Ò ñ ¦mY"¦Îú û In this example we start with an empty list ( ) and each number from 1 to 100 Ü"í£É3£ÌÆ½Ü is squared and appended to the list. will be the û Ö@Æ õ doõ ý‰õÐïïï1õªÖxÕPՐՐg Õ  list: . For example. or lines of a file. strings and lists are also objects in Python. µa”sr  ˜Ÿi„¤n…‚™g © ¦§›¥› ingIí This chapter has covered important elements of the Python sequence types: strings. don’t worry. to take the absolute value of a ¦ ÂÓË@Ü@ñë¦3ú ¦nïèÂÓË4ܓñ‡ú . . A loop can be used to iterate through the characters of a string. not . This is different from the normal function application that we have used before. Here is a summary of the highlights: ’ Strings are sequences of characters. ’ Strings and lists can be manipulated with the built-in sequence operaû û ÷f á Y tions for concatenation ( ). items in a list. and files. After all. are invoked using the dot notation. An object’s operations.¯  ¿HHs@tŒuxw†y|{‡}Q˜¨…€ƒ„ƒŸu‡}‘ç ÒILjͽÒ1ÀPÆ Ò€ÇͽÒHÀHÆnï–ÌƨÂ1Éñ‡ú from we type . variable . we type In Python. This is often used to build a list one item at a time. By the way. called methods. a file is an example of an object. too). Objects combine both data and operations together. Chapter 5 is all about the power of objects (and pretty pictures. When the loop is done. ÀPÆÓÇnñ‡ú ͐ÁHÌ and length ( ). lists. indexing ( ). repetition ( ). In modern Python. you can use string methods in place of the string library functions that we discussed earlier. That’s why the syntax looks a bit different. If this object stuff sounds confusing right now.

’ Files. ASCII and Unicode are compatible standards that are used for specifying the correspondence between characters and the underlying codes. – Strings are always sequences of characters. whereas lists can contain values of any type. ’ Python has a string library that can be imported to provide an extended set of useful string manipulation functions. which means that items in a list can be modified by assigning new values. There are two different kinds of encryption systems: private key and public key. Python provides the ÁH̨à рÅÌ and functions for translating between ASCII codes and characters. strings. When opened for writing. " ’ Text files are multi-line strings stored in secondary memory. and . – Lists are mutable. String methods can be used in place of functions from the string  ©ˆÆ£ÇÉñIú " library. Python provides three file reading operaÌƐÂHÃæñIú ÌƨÂ1ÃÀ¨Ò€Ç½Æ¬ñIú ÌƐÂHÃÀ¨Ò€ÇˆÆ½Ü“ñ‡ú tions: . . ’ The process of encoding data to keep it private is called encryption. When processing is finished. Data is written to a file using a Û¨Ì3ÒxÄƬñIú operation. ’ Lists are more general than strings. A file may be opened for reading or writing. The string formatting operator ( ) is particularly useful for producing nicely formatted output.~I~ ¯ s@tvuxwzy|{I} ¯  sˆ‚1ƒ•w€…†y 6 Š†²’ 6 yèt”˜xyè} 6 ŠŒIˆ ’ One way of converting numeric information into string information is to use a string or a list as a lookup table. a file should be closed. ’ Program input and output often involve string processing. Python provides numerous operators for converting back and forth between numbers and strings. the existing contents of the file are erased. Methods are applied to objects using dot notation. and lists are examples of Python objects that combine data and operations (called methods). ’ Strings are represented in the computer as numeric codes. One particularly useful list method is . which adds an item to the end of a list. It is also possible to iterate ͨÁ1Ì through the lines of a file with a loop.

5. but strings are not. A Python string literal is always enclosed in double quotes. What function gives the ASCII value of a character? ÁH̐à ˆÜHѐÒPÒ Ñ€ÅÌ ÆWˆÂÀ b) c) d) a) 4. 9.¯  âPCŽŒ{I} ³Œ6 ˆ–{ôˆ µa”s‘ egf„‚™gIƒæ‡‘‚„‘ ~I~†´ hjiCkmlniCoqpIrQi§sutqlnvxw%s y{zH|c})~Q©€cˆ‚3} 1. 8. is the best way to get string data from the user. Which of the following is the same as û û û Ü ¨3Ö Ü ÷f Ü ÷ðÀPÆÓÇnñ‡Üú ¨½Ö Ü û Õn÷ðÀPÆÓÇnñ‡Üú a) b) c) d) 3. ƒ |§„3…‡†§ˆ}Iˆj‰cŠ§…Œ‹"} 1. ASCII is a standard for representing characters using numeric codes. Accessing a single character out of a string is called: a) slicing b) concatenation c) assignment d) indexing Ü û Õo÷¡¨½Ö ? 2. In Python žd6fáAu9B . The process of associating a file with a variable in a program is called “reading” the file. Which of the following can not be used to convert a string of digits into a number? Ò€Ç¨Ä ÍÀHÁ¨Â£Ä ÜxÄÌ ÆgWÀ a) b) c) d) . A substitution cipher is a good way to keep sensitive information secure. 10. Python lists are mutable. 2. Python uses the percent sign as a string-formatting operator. 6. Ü ½ÀÒxÄ q ÁˆÒ€Ç function breaks a string into a list of substrings. Using ÒIÇ©PÉÄ Ü is at position ÀPÆÓÇnñvܨú ½ ¨ Ö . equals ždc9B 4. The last character of a string 3. The the opposite. and ï does 7.

~I~†¹ s@tvuxwzy|{I} ¯  sˆ‚1ƒ•w€…†y 6 Š†²’ 6 yèt”˜xyè} 6 ŠŒIˆ 5. A successor to ASCII that includes characters from all written languages is a) TELLY b) ASCII++ c) Unicode d) ISO 6. Given the initial statements: ҇ÊCˆÁHÌPÄÿÜxÄPÌ3ҀÇC! ÜÖ & ß Óu Ü 3€{ Ê  Ü1Ôc& ß zÇÎÒ u Show the result of evaluating each of the following string expressions. A function that “lives” in an object is called a(n) a) method b) intern c) module d) library  …Œ‚3‹|c‚8‚X…ŒŠm " !h " " " 1. Which of the following is not a legal format specifier? ¨ÞHÍ ¨ÞÀ C¨)eoïðÞHÍ ¨Õc91à a) b) c) d) 8. Which string library function converts all the characters of a string to upper case? ÑH  4ÒÓĐÀ¨Ò ¨Æ ÑH  ¨ÛÁHÌ¨Ã½Ü É ©½Æ1Ì3Ñ1ÂˆÜ£Æ ) É ©ˆÆHÌ ) a) b) c) d) 7. (a) (b) (c) (d) (e) (f) (g) (h) X1Å½Æ Þ¡YÝÜÖ áàÔSYÐÜ1Ô ÜÖ û Öq ÜÖ û ֆ÷ðÞ) ÜÖ û ÔWáÿÜ1Ô û ÷èÔ ÜÖ á Ü£Ô û ½ ¨ Ö É@Üxĉñ‡Ü€ÄÌ3ÒIǧ!nï|É©)½Æ1̉ñvÜ1Ô½ú@õ¡d3ú$YcÞ ï ŽÀ HÇ4Ò £ ! ÅÄ3Ü ÛPňÁ¡Ü1Â1Ïoõ§ªáÿÜ1Ô ÜxÄPÌ3ÒIǧ!Ÿï É©)½ÆH̉ñ‡Ü¨ÖPú ÜxÄPÌ3ÒIǧ!ŸïðÀ . The term for a program that does its I/O to files is a) file-oriented b) multi-line c) batch d) lame 10. Which of the following is not a file reading method in Python? ÌƐÂHà ̨ƨÂ1ÃÀÒIÇ½Æ Ì¨Æ¨Â1ÐÀPÀ ÌƐÂHÃÀ¨Ò€ÇˆÆ½Ü a) b) c) d) 9.

Show the output that would be generated by each of the following program fragments: ͨÁ1ÌÿрŠÒIÇ ‡ÂÂ£Ì¨Ã)WÂ1ÌgÎx@÷ (a) ¨Ì3ÒIÇÄÿрŠ(b) (c) (d) ͨÁ1Ì€Û Ò€Ç»ÜxÄPÌ3ÒIǧ!ŸïôÜq½ÀÒÓĉñ 3ÐÁ1ÛÝҐÜYÄHŽÆUÛ3ҀǨÄÆHÌWÁPÍÝÁ£É¨ÌÝýҐÜPÑ1ÁÓÇĨƣÇğïïPïq£ú­÷  Ì3ÒIÇÄ€Û ¨ ͨÁ1Ì€Û Ò€Ç»ÜxÄPÌ3ÒIǧ!ŸïôÜq½ÀÒÓĉñ z  öÎÒ¨ÜPÜPҐܐÜPÒq©3ÒQ3õ˜xÒ%£ú¬÷  Ì3ÒIÇĀ۟õ ¨ ʆÜ!Wß&© ͨÁHÌ ÜWÒIÇ»ÜxĐ̽ҀÇC!ŸïzÜu3À¨ÒÓĄñ"ÓÜÓƈÑǪ́ÆHÄ6ÎõvÆBÓú¬÷ ʓ" Ü !WßÈʆ Ü !€á Ü Ì3ÒIÇÄÈʓ" Ü ! ʆÜ!Wß&© ͨÁHÌÿÑIŠҀǽÓÜÓƈÑxÌÆHÄ6@÷ ʓ" Ü !WßÈʆ Ü !€áÿрŨ̄ñzÁ1̨ÃæñvрÅ@úxáÎÖPú Ì3ÒIÇÄÈʓ" Ü ! (e) 4. Given the same initial statements as in the previous problem. show a Python expression that could construct each of the following results by ÜÖ Ü£Ô and . Show the string that would result from each of the following string formatting operations. explain why. If the operation is not legal.¯  âPCŽŒ{I} ³Œ6 ˆ–{ôˆ ~I~†¿ 2. performing string operations on (a) (b) (c) (d) (e) (f) XÐ%¢% zÇÎÒ –Üq3ÂIÊÇÎÒ u qÅ3ÂIÊ¡Ð3Ò  ÓÜu3ÂIÊ  Å"½Â€Ê¡Ð½Ò  Å3ÂIÊ@Ð3Ò{u û x  ÜqxÎõèÊ ÓÜuHÊ{ X 3. X¤¨ÁÁ Î4ÜÈÀ¨ Ò ÎˆÆ ½ÜUÂÓÇà 3Ü Í¨Á1ÌcĘ̈ƨ ΨÍÂÜxÄ# ©ñ ÓÜu3ÂIÊ Îõ$‡Æg!©!3Üm£ú (a) X1ŽÆ1ÌÆÐÒÜ Pà 3Ü Pà 3% Ü  ñI֓ õ Óq Ü ½Â€{ Ê ΰ õ d„V õ ŒÏÁÓ É Óú (b) 3¢ƨÀPÀPÁ ½% Ü  ©ñ uÅÓÉ@Ü£ÂÓx Ç Î õ vאÁ€C Ê É¨ÄƣۈƨÀPB À Óú (c)  ÕnïðÔHÍ ÕnïèÔ16 Í  ©ñzÔoïðމõ Ôoïù) Þ d© ø e3ú (d)  þnH ï 9HÍ þn¡ ï 916 Í  ©ñzÔoïðމõ Ôoïù) Þ d© ø e3ú (e) #" " Ž" " ®" " ¯" ž" ¯" R" #" ­" R" #" ­" ±" .

Explain why public key encryption is more useful for securing communications on the Internet than private (shared) key encryption. 4. Ó 60:F.~I~†â X½Ò‡Ê3ÆÝÀPÆPÍHÄ s@tvuxwzy|{I} ¯  sˆ‚1ƒ•w€…†y 6 Š†²’ 6 yèt”˜xyè} 6 ŠŒIˆ (f) (g)  R" ¯" ÞPÃ' ñ 1  Öqd6Óú " q" ¨ÕÔHÃn÷ ¨Õ©9oïðÔHÍ6 ±" ñ€Ö@õ ސþnïùސþgdÎú 5. 60–69:D. Write a program that accepts a quiz score as an input and prints out the corresponding grade. . using an empty string then be formed by ï between the characters. One way to avoid recopying the message over and over again is to use a list. A certain CS professor gives 100-point exams that are graded on the scale 90–100:A. this is somewhat inefficient. As discussed in the chapter. 4-B. The statement ÊÎƽÜPÜ1Â!¨ÆcßÈÊÎƈܐܣÂg!¨ÆÈáÿрÅ̉ñ†ÂÜPѐÒPÒ"Ð1ÉHÊ­ú essentially creates a complete copy of the message so far and tacks one more character on the end. 1-F. 2. ’”“fv••“H–B—$—˜l™wm•Sš#›§i•“¡œ©lnsi§s ÇPÉHÊˈÆHÌ3Ü1Ô1ĨÆ)¦HęïU¨Ï 1. A certain CS professor gives 5-point quizzes that are graded on the scale 5-A. string formatting could be used to simplify the ÃÂ1ĨƈѣÁ£ÇCW¨ÆHÌPĈÔoïbÏ program. Write a program that accepts an exam score as input and prints out the corresponding grade. 2-D. 0-F. Go back and redo this program making use of the string-formatting operator. 70–79:C. Because strings are immutable. ÜxĐ̽ҀÇC!Ÿï ÁˆÒIÇnñpʓÜ"!g¤3Ҩ܀Änõ©£ú ï Use this approach to redo the decoder program. The message can be accumulated as a list of characters where each Â"©ˆÆ£Çà new character is ed to the end of the existing list. 3. The decoder program uses a string variable as an accumulator for the output. The message can ÁÒ€Ç ing the characters in the list. 80–89:B. 3-C.

8.” The original message can be recovered by “reencoding” it using the negative of the key. Modify your solution to the previous problem to make it circular. 6. 7. the word “Sourpuss” would be encoded as “Uqwtrwuu. A Caesar cipher is a simple substitution cipher based on the idea of shifting each letter of the plaintext message a fixed number (called the key) of positions in the alphabet. by the way). For example.” The total value is just the sum of the numeric values of all the names. RAM is an acronym for “random access memory. Write a program that can encode and decode Caesar ciphers. The input to the program will be a string of plaintext and the value of the key. The output will be an encoded message where each character in the original characters in the ASCII character set. if the key value is 2. . up to ’z’ being 26. An acronym is a word formed by taking the first letters of the words in a phrase and making a word from them. A true Caesar cipher does the shifting in a circular fashion where the next character after “z” is “a”. Note: the acronym should be all uppercase. the name “Zelle” would have the value ¡ i x …‡¡ …‡¡ x i"w (which happens to be a º     very auspicious number. One problem with the previous exercise is that it does not deal with the case when we “drop off the end” of the alphabet (or ASCII encodings). For example. Expand your solution to the previous problem to allow the calculation of a complete name such as “John Marvin Zelle” or “John Jacob Jingleheimer Smith.¯  âPCŽŒ{I} ³Œ6 ˆ–{ôˆ ~I~†é 5. Write a program that calculates the numeric value of a single name provided as input. The value of a name is determined by summing up the values of the letters of the name where ’a’ is 1.. For example. You may assume that the input consists only of letters and spaces. if is a character in the string and ÑIŠрŨ̄ñôÁH̨ÃæñvÑIœúfá then the character that replaces can be calculated as: ΈÆHÏÎú . For example. ’c’ is 3 etc.” Write a program that allows the user to type in a phrase and then outputs the acronym for that phrase. even if the words in the phrase are not capitalized. 9 – 9. ’b’ is 2. Numerologists claim to be able to determine a person’s character traits based on the “numeric value” of a name. message is replaced by shifting it ’ рŠΈÆ1Ï is the amount to shift.

12. the table might look like this: ҀLjÐÆ)¦ Ô Þ d 9 ÕnïèÔ)9 ÕnïùþÞÎÖxÔ©9HÕ Õnïùþøg ø d©dÎÖ Õnïùø© ý e3Öx© Þ 9 Õnf ï e¨Ô3 Ö eýPø ÕnH ï 9Pþ) Õ eg ý d Õnïùc ý 9©9HސýPý Õnï†Öxøø3 Ö ePþ ÕnH ï 9gd¨g Õ d4 Ö e Õnïùý© ø ePø¨ÔHý Õnï†Ö Ö e©9PÕPý ÕnïèÔHø Õnïðþ©9PÕPސøÕ ÕnïðþPސ© Õ 9gd¨þ ÕnïðþPøþPþÕþ ÕnïðøPc ý 9d¨ýý ÕnH ï e© Ô 9H) ý dÔ Õn¡ ï 9HøÕPøþÎÖ ÕnïðýPøÕP) ø d©d ÕnïŒq Ö d¨g þ d©d¨þ Õnf ï dýÕ© Ô 9©9 ÕnïðýP) þ døÞÕ ¨©¨©¨)¨©¨)¨©¨©¨)¨©¨)¨©¨©¨)¨©¨)¨©¨©¨)¨©¨)¨©¨©¨)¨©¨g¨©¨)¨ Ö ø þ e ÖxÕ ý 13. Write an improved version of the future value program from Chapter 2. and the number of years of the investment. if the starting values were tions. Your output might look something like this: “ Æ¨Â£Ì Õ Þ d 9 ۈÀxÉ½Æ ¨©¨©¨)¨©¨)¨©¨©¨)¨©¨)¨©¨©¨)¨©¨)¨ Ô Ö ¬¬ ¬¬ ¬¬ ÔPՐÕPÕnïùÕÕ ÔÔPÕPÕnïùÕÕ ÔgdÔHÕnïùÕÕ ÔPøøÔoïùÕÕ ÔPý¨g Ô enïðÔPÕ Þ¨ÔÔ½Ö­ïùÕ¨Ô . Write a program that counts the number of words in a sentence entered by the user. the annualized interest rate. Write a program that calculates the average word length in a sentence entered by the user. The program will then output a nicely formatted table that tracks the value of the investment year by year.~zr7 s@tvuxwzy|{I} ¯  sˆ‚1ƒ•w€…†y 6 Š†²’ 6 yèt”˜xyè} 6 ŠŒIˆ 10. Your program will prompt the user for the amount of the investment. 11. Write an improved version of the Chaos program from Chapter 1 that allows a user to input two initial values and the number of iterations and then prints a nicely formatted table showing how the values change over ïèÔ)9 ïðÔPø ÖxÕ and with iteratime. For example.

15. words. .” This program analyzes a file to determine the number of lines. A common utility on Unix/Linux systems is a small program called “wc. and characters in the file. The program should accept a file name as input and then print three numbers showing the count of lines. Redo any of the previous programming problems to make them batch oriented (using text files for input and output).¯  âPCŽŒ{I} ³Œ6 ˆ–{ôˆ ø þ ~zrH~ ¬¬ Þc9gd¨Ôoï†ÖÓÔ Þ©eýPþnp ï d¨Þ 14. and characters contained therein. Write your own version of wc. Word count. words.


This is a traditional way to view computation.QSRUTWVYXa`cb ÂÁ à ¦ÅÄ |Æ Ç È£ Æ î Ш  i«rsf ¥ rs¦t ÿ x€y31‚„ƒ†…ˆ‡‰„‚„‘ ’ To understand the concept of objects and how they can be used to simplify programs. especially the role of coordinate systems and coordinate transformations. Basically. ºa”–“ x ‰„‚™g‡‰o‡‚‰œ So far we have been writing programs that use the built-in Python data types for numbers and strings. ­ q !É . To build complex systems. ’ To understand how to work with both mouse and text-based input in a graphical programming context. ’ To understand the fundamental concepts of computer graphics. We saw that each data type could represent a certain set of values. ’ To be familiar with the various objects available in the graphics library. ’ To be able to write simple interactive graphics programs using the graphics library. ’ To be able to create objects in programs and call appropriate methods to perform graphical computations. and each had a set of associated operations. we viewed the data as passive entities that were manipulated and combined via active operations.

Graphical programming is a lot of fun and provides a great vehicle for learning about objects. Python comes with its own standard GUI module called Tkinter. This library is a ( wrapper around Tkinter that makes it more suitable for beginning programmers. To make learning these basic concepts easier. It is freely available as a Python module file 1 and you are welcome to use it as you see fit. Part of the challenge of OO programming is figuring out the 1 See Appendix B for information on how to obtain the graphics library and other supporting materials for this book. Object orientation is not easily defined. buttons and menus. This chapter provides a basic introduction to object concepts by way of some computer graphics. and Python is a great language for developing real-world GUIs. As GUI frameworks go. we will use a graphics library !P̈  ÅÎҐѨܬU ï ¨Ï ) specifically written for use with this textbook. icons (representative pictures). it helps to take a richer view of the relationship between data and operations. which are to introduce you to objects and the fundamental principles of computer graphics. Industrialstrength GUI applications are usually developed using a dedicated graphics programming framework. It encompasses a number of principles for designing and implementing software. principles that we will return to numerous times throughout the course of this book. In the process. you may want to study the code for the library itself as a stepping stone to learning how to program directly in Tkinter.~zr ¯ s4tvuxw†y|{‡}3´PîÑ ‰Ê { ³ y|ˆ‰uxŠŒ‹ †}$uxwxt 6 ³ ˆ ÌË however. . Eventually. entire textbooks are devoted to the intricacies of graphics and graphical interfaces. you will also learn the principles of computer graphics that underlie many modern computer applications. Most modern computer programs are built using an object-oriented (OO) approach. Most of the applications that you are familiar with probably have a so-called Graphical User Interface (GUI) that provides visual elements like windows. and doing so would not contribute much to the main objectives of this chapter. Interactive graphics programming can be very complicated. Tkinter is one of the simplest to use. Still. at this point in your programming career. The word objects is being used here in a specific technical sense. ºa”–• —Y˜™‚ x€y31‚„ƒ†…€™„ìfx€y΁£‚oƒ“…‘ The basic idea of object-oriented development is to view a complex system as the interaction of simpler objects. it would be a challenge to learn the intricacies of any GUI framework.

To put it simply. ID number. In our example. As a beginning programmer. Course objects would know things such as who the instructor is. and they can do stuff (they have operations). courses taken. Using the graphics library is as easy as placing !Ḧ"  PÅ4ÒPѨÜæb ï Ï a copy of the file in the same folder as your graphics program(s). GPA. home address. and when and where the course meets. and even times. For example. what students are in the course. Each student could be represented in the program as an object. Suppose we want to develop a data processing system for a college or university. A student object would contain certain data such as name. we’ll study objects in the context of some simple graphics programming. objects know stuff (they contain data). . Consider a simple example. You can see how successive refinement of these ideas could lead to a rather sophisticated model of the information structure of the college. you’re probably not yet ready to tackle a college information system. which causes a student to be enrolled in the course. When a particular student object is sent the ̽ҀǨÄרÂIC Ê PÉ@Ü Ú ÃÃHÌƽÜPÜ message. Instructors would be another kind of object. we must keep records on the students who attend the school. each course in the college might also be represented by an object. etc. Alternatively. Objects interact by sending each other messages. send each one in turn the Objects may refer to other objects. it prints out its own address. as well as rooms.´H ”H˜ 6 ƒ„w± { †}"uxw€t 6 ³ ˆ™3}‘‚€1}"uxƒ„ƒ 6 ŠŒ ÍË ~zr€´ vocabulary. campus address. This task might be handled by ¨Ì3ÒIÇÄא€c Ê É@Ü Ú ÃPÃPÌÆˆÜÜ a operation. We will need to keep track of considerable information. you can place it in a system directory where other Python libraries are stored so that it can be used from any folder on the system. The student being enrolled would be represented by the appropriate student object. You can think of an OO object as a sort of active data type that combines both data and operations. to send out a mailing. One example operation might be ÂHÃPC à ţÄHÉˆÃÆ£Ç¨Ä . we would need to print an address for each student. For now. a program would loop through the collection of student objects and ¨Ì3ҀǨÄא€C Ê PÉ@Ü Ú ÃÃHÌÆˆÜÜ message. A message is simply a request for an object to perform one of its operations. you will need a copy of the file that is supplied with the supplemental materials. ºa”– ©«‡p›¥¤§j ‚ ÏÎ ªgIi„¤§˜h‡ƒ­‘ —˜gI™hšqgIi•› ›»‡penš In order to run the graphical programs and examples in this chapter (and the !PÌÂ"PÅ4ҐѐÜæïbÏ rest of the book). To print out all the addresses. what the prerequisites are. Each student object would also be able to respond to certain requests. For starters.

As you do. to import everything defined in the module. We can manipulate the window object through this variable. similar to the way that file objects are manipulated through file variables. !Ḧ"  PÅ4ÒPѨÜæï and it gets tedious having to type the notation every time we use ÒvC Ê ˆÁHÌÄ one. as shown. shows an example screen view. and we have assigned it to the variable called The ÛÎÒIÇ . !Ḧ  Å4ÒPѨܬU ï Ï Assuming you have placed in an appropriate place. the best way to start learning new concepts is to roll up your sleeves and try out some examples. The imported commands become directly available without having to preface them with the ü ̈Åc43Ò€Ç module name. (©()( ÛÎÒIDŽïôÑ1ÀPÁˆÜ£Ææñ‡ú Typing this command causes the window to vanish from the screen. ü ÌÂ"PÅc4ÎÒIÇ !PÌÂ"ÅÎÒÑÜ .” The may overlap your Python interpreter window. Figure . so you might have to resize the Python window to make both fully %  visible. You can either list the names of definitions to be imported or use an asterisk. we can create a more simply. Here we’ll concentrate on a basic hands-on introduction to whet your appetite. which is provided by the That place is a graphics window or module. ü ̈"  Pc Å 43Ò€Ç is an object. . we can destroy it. The first step is to import the graphics module. For example. ÍP̨Áxa Ê !Ḧ"  PÅ4ÒPѨÜUÒvC Ê ˆÁH̐@ Ä Y ÍHÌÁ€Ê The statement allows you to load specific definitions from a library module. when we are finished with a window. After doing this import. This is done by issuing the ÑHÀHÁ½ÜÓÆ command. Python has an alternative form of that can help out. ß !P̈  ÅÎҐѨܬï ü ̈"  Pc Å 43ҀÇnñ‡ú (©()( ÛÎÒIÇॠThis command creates a new window on the screen. you will be learning principles of object-oriented programming and computer graphics that can be applied in more sophisticated graphical programming environments. As usual. Ê ½ÁHÌP¥ Ä !PÌ"  PÅ4ÒÑÜ (©()( ҇c Next we need to create a place on the screen where the graphics will appear. The window will have the ü ̈Åc43Ò€Ç title “Graphics Window.~zr€¹ s4tvuxw†y|{‡}3´PîÑ ‰Ê { ³ y|ˆ‰uxŠŒ‹ †}$uxwxt 6 ³ ˆ ÌË The graphics library makes it easy to experiment with graphics interactively and write simple graphics programs. you can import the graphics commands into an interactive Python session. The details of the !PÌ"  PÅ4ÒÑÜ module will be explored in later sections. !P̈ÅÎÒÑ¨Ü We will be working with quite a few commands from the library.

A graphics window is actually a collection of tiny points called pixels (short for picture elements). graphics programmers locate the point ‚ƒw Òwg„ in the upper-left – – ’q – %q . ÛÎÒIÇàß ü ÌÂ"Å©4ÎÒIÇnñIú !P̈  ÅÎÒÑ¨Ü All of the rest of the graphics examples will assume that the entire ÍP̨ÁxÊ module has been imported using . we will rely on a library of graphical objects. it can represent a location in a . we control what is displayed in the window. : Screen shot with a Python window and a GraphWin. By default. a ü Ì"  Pc Å 4ÎÒIÇ is 200 pixels tall and 200 pixels wide. By controlling the color of each pixel. Our ü Ì" ØÁҀÇÄ Â © Å 4ÎÒIÇ graphics object is similar. !Ḧ"  PÅ4ÒPÑ¨Ü Ø¨ÁˆÒ€Ç¨Ä module is a . We define a point by supplying “ and coordinates ‚”“ „ . A point is located by reference to a coordinate system.´H ”H˜ 6 ƒ„w± { †}"uxw€t 6 ³ ˆ™3}‘‚€1}"uxƒ„ƒ 6 ŠŒ ÍË ~zr€¿ %  Figure . a point The simplest object in the is a location in space. In geometry. Each type of object does its own bookkeeping and knows how ü ̈  c Å 43Ò€Ç to draw itself into a . Traditionally. The “ value represents the horizontal location of the point. Instead. and the value represents the vertical. That means there are 40. Drawing a picture by assigning a color to each individual pixel would be a daunting challenge.000 ü ̈"  Pc Å 43Ò€Ç pixels in the . Let’s try our hand at some drawing.

The default color for drawing is black. the graphics library contains commands for drawing lines. ØÁˆÒIÇÄ3Ü Here is a sample interaction with Python illustrating the use of : gq – (©()( (©()( 9PÕ (©()( (©()( (©()( (©()( (©()( àßWØÁˆÒIÇĉñ39PՉõ–øPÕ3ú „ïp!¨ÆHÄ „ïp!¨ÆHÄ øÕ gÐ €“ ‰ñ‡ú „ñ‡ú ü ̈ũ4ÎҀÇoñIú „ïpÃP̈ÂÓÛoñðÛÎҀÇ@ú ÛÎÒIÇàß 3ÔcßWØÁҀǨĄñ€Öqd¨Õ‰õ‡ÖxÕPÕ3ú 3ԄïùÃPÌ£ۄñèÛÎÒIǓú ØÁÒ€Ç¨Ä ØÁҀÇÄ The first line creates a located at ‚bx"w ëi"wg„ . %q %Ð g“ %  Figure . After the has been cre!¨Æ1Ä !ÆHÄ ated. the lower-right ØÁÒ€Ç¨Ä corner has the coordinates ‚H…u€ € u…u€ €„ .~zr€â s4tvuxw†y|{‡}3´PîÑ ‰Ê { ³ y|ˆ‰uxŠŒ‹ †}$uxwxt 6 ³ ˆ ÌË corner of the window. Each of these objects is cre- . بÁˆÒIÇÄ ÃP̈ÂÓÛ A is drawn into a window using the operation. and values ü ̈Åc43Ò€Ç increase from top to bottom. its coordinate values can be accessed by the operations and . ü ̈Â"PÅc43Ò€Ç  3Ô two different point objects ( and ) are created and drawn into the %  ÛÎÒIÇ called . In addition to points. In the default ¡"w w x ¡"w w . Drawing a sets the color of the ü Ì"  PÅc4ÎÒIÇ corresponding pixel in the . : Graphics window with two points drawn. polygons and text. rectangles. shows the resulting graphical output. In this example. ovals. Thus “ values increase from left to right. circles. Figure .

In the interactive examples above. . If you type them in as % ! shown. .´H ¯  ½ˆ 6 Š† †}"uxw€t 6 ³ u±gÑ g$ ©Ë ‰Ê { ³ y|ˆ ~zr€é ated and drawn in a similar fashion. you need to know how to create them and how to request operations. we need to take an object-oriented point of view. . ºa”|µ d ‘ˆ‡penš ÈÎ ªgIi„¤§˜h‡ƒ­i„j x€y31‚„ƒ†…¨‘ Some of the examples in the above interactions may look a bit strange to you. These are examples of classes. and . . objects combine data with operations. . and the class describes the properties the instance will have. Remember. we manipulated several different kinds ü Ì"  © Å 4ÎÒIÇ ØÁÒ€Ç¨Ä ×ˆÒÓ̽ÑHÀHÆ Ä WˆÂPÀ ¤3ÒIÇ½Æ g Æ ¦PÄ  ˆÆÑÓÄÂÓ§ Ç !¨ÀPÆ of objects: . !PÌÂ"ÅÎÒÑÜ To really understand the module. the final result will look like Figure . In order to make use of objects. . Computation is performed by asking an object to carry out one of its operations. Every object is an instance of some class. Here is a sample interaction to draw various ü ̈ũ4ÎÒ€Ç shapes into a : (©()( (©()( (©()( (©()( (©()( (©()( (©()( (©()( (©()( (©()( (©()( (©()( (©()( (©()( (©()( (©()( (©()( (©()( (©()( óóPóó Ä ˆÆ£Ç¡ÂT!ḦÂ"PÅ4ÒPѨܪÛ3ҀÇèÁ1Û ÛÎÒIÇàß ü ̈ũ4ÎҀÇoñ ÒÅÓÅ3Â½ÆˆÜ vú óóPóó ¨Ì£ÛàÂc̨ÆPáѐÒxÌ3Ñ1ÀPÆÐѣƣÇĨÆH̨ÆPÃW£ÄE½ÁҀÇÄ©ñIÖxÕPՄõ‡Ö€ÕÕ½úfÛÎÒxÄHÅÐÌÂHýÒIÉ@Ü Ñ1ÆÓÇÄÆ1ÌW߀ØÁҀǨĄñ€Ö€ÕÕ‰õ‡ÖxÕPÕ3ú ѐÒxÌ3ÑÈßÝ׈ÒxÌ3Ñ1ÀPÆæñŒÑ1ÆÓÇÄÆ1Ìnõ ސսú ѐÒxÌ3щïôÜ£Æ1© Ä D3Ò1ÀÀ­ñ ð̨ÆPà vú ѐÒxÌ3щïpÃPÌ£ÛoñðÛÎÒIǓú óóPóó€ØHɨÄÐÂcÄg Æ ¦PÄHɽÀ€ÀPÂÓˈƨÀÝÒIÇÐÄHŽÆàѣƣǨÄÆHÌWÁP̀ÄHňÆàѐÒxÌ3ÑHÀHÆ ÀÂx˽ƨÀÈ  ß ¨) Æ ¦HĄñvѣƣǨÄÆHÌo$ õ 8 ˆÆHÃÝ׈ÒÓ̽ÑHÀH' Æ £ú ÀÂx˽ƨÀ„ïùÃḦ£ۄñèÛ3ҀǓú óóPóó ¨Ì£Ûà¡ Ü í1É3£ÌÆ É4ÜPÒI§ Ç !Ý£   ˆÆÑÓÄÂÓ§ Ç !¨ÀPÆUÁ£Ë ƈÑxÄ ï ÌÆÑÓÄÝE ß  ˆÆÑÓÄÂÓ§ Ç !¨ÀPƬñ–ØÁҀǨĄñzÞPՄõèސÕ3ú“õ ØÁҀǨĄñzþPՄõèþÕ3úPú ÌÆÑÓęïpÃPÌ£ÛoñðÛÎÒIǓú óóPóó ¨Ì£ÛàÂÝÀ¨Ò€Ç½ÆÐÜ£) Æ !xÊÎÆÓÇÄUÉ4ÜPҀC Ç !ÝE  ¤3ÒIǽÆWÁ£Ë ÆÑÓÄ ï ÀÒIǽƀT ß ¤3ÒIǽƬñ–ØÁҀǨĄñ†ÔHՄõèސÕ3ú“õ ØÁˆÒIÇĉñ€ Ö ePՄõ Öxc ø 9ˆúú ÀÒIǽÆnïpÃPÌ£ÛoñðÛÎÒIǓú óóPóó ¨Ì£ÛàÂxÇ¡g Á WÀ É@ÜHҀC Ç !cÄHÅˆÆ Ä WˆÂPÀ€Á£Ë ƈÑxÄ ï Á WÀcß Ä WÀ­ñ–ØÁҀǨĄñ†ÔHՄõv" g Ö 9PÕ½ú†õ ØÁҀǨĄñ€ Ö eÕ‰õ‡ÖxýPý3úPú Á WÀoïpÃPÌ£ÛoñðÛÎÒIǓú g ž ž ž ž  © ÞPÕ  } Try to figure out what each of these statements does. .

Fido has four legs. The same ideas hold for our computational objects. or . different instances can vary in specific details such as the values of their coordinates. even though Fido and Rex may differ in specific details such as size or color. Borrowing a biological metaphor. we are actually saying that Fido is a specific individual in the larger class of all dogs. To create a new instance of a class. Fido is an instance of the dog class.. and the resulting .~z”7 s4tvuxw†y|{‡}3´PîÑ ‰Ê { ³ y|ˆ‰uxŠŒ‹ †}$uxwxt 6 ³ ˆ ÌË % ! ! ̈ÅÎÒÑ¨Ü P Figure . a cold. Because Fido is an instance of this class. we expect that he will have similar properties. rate instances of !ÆHÄ ÃPÌÂ£Û and they both support the same set of operations like and . We can create two sepaØÁÒ€Ç¨Ä  ½Ô . Each of these points has an “ and value. : Various shapes from the module. a constructor is used on the right side of an assignment statement. we expect certain things. A requires two numeric values. The expressions in the parentheses are any parameters that are required to initialize the object. However. a tail.g. Often. These ØÁҀÇÄ properties hold because the objects are s. we use a special operation called a constructor. ü ̈  © Å 4ÎÒ€Ç while a can be constructed without any parameters. A call to a constructor is an expression that creates a brand new object. say and . wet nose and he barks. The number and type of بÁˆÒ€Ç¨Ä the parameters depends on the class. The general form is as follows: Ñ1ÀÂܐ Ü ¨xÇ3ÂIÊÎÆ ( ñ 3Â1ÌÂ€Ê­Ö ( õ 3£̈€ÊÎÔ ( õWïïPï†ú gÐ – F F F Ñ1ÀÂˆÜP Ü ¨xÇ3€Ê3Æ ( Here F is the name of the class that we want to create a new in׈ÒxÌ3Ñ1ÀPÆ Ø¨ÁˆÒ€Ç¨Ä stance of. In OO terminology. If Rex is a dog. when we say that Fido is a dog. e.

These values are stored as instance variables ØÁҀÇÄ inside of the object. The variable  ØÁÒ€Ç¨Ä refers to a freshly created having the given coordinates. The set of messages that an object responds to are called the methods of the object. in this diagram as well as similar ones later on.´H ¯  ½ˆ 6 Š† †}"uxw€t 6 ³ u±gÑ g$ ©Ë ‰Ê { ³ y|ˆ ~z”H~ object is immediately assigned to a variable on the left side that is then used to manipulate the object. You can find numerous examples of method invocation in the interactive examples above. consider these two expressions: . A method is invoked using dot-notation. You can think of methods as functions that live inside of the object. In this case. Most of this information is set to default ØÁˆÒIÇÄ values when the is created. As examples of parameterless methods. Some methods require no parameters at all. Here is a constructor statement from the interactive example above. only the most salient details بÁˆÒ€Ç¨Ä s also contain other information such as their color and which are shown. àßWØÁҀÇĉ3 ñ 9HՄõ–øPÕ3ú ØÁˆÒIÇÄ The constructor for the class requires two parameters giving the “ and coordinates for the new point. Python creates an instance of having an “ value of 50 and a value of 60. To perform an operation on an object. . Note that. To take a concrete example. The resulting point is then assigned to the % #  variable . we send the object a message. ÁÓË ÆˆÑÓÄ ( ï ÊÎÆ1ÄHňÁPC à ¨xÇ3ÂIÊÎÆ ( ñ 3Â£ÌˆÂ‡Ê¬Ö ( õ ½Â1Ì€Ê4Ô ( õ€ïïïzú F ï F F F The number and type of the parameters is determined by the method being used. – – p: x: y: Point 50 60 % # ¡ß€Ø¨ÁˆÒ€Ç¨Ä„ñ89PՄõèøÕ½ú Figure . A conceptual diagram of the result is shown in Figure . : Conceptual picture of the result of . let’s look at what happens when we create a graphical point. window (if any) they are drawn in.

All of the graphical objects have a method.~z”€r „ïp!¨Æ1Ä „ïp!¨Æ1Ä s4tvuxw†y|{‡}3´PîÑ %g“Ð ‰Ê { ³ y|ˆ‰uxŠŒ‹ †}$uxwxt 6 ³ ˆ ÌË ‰ñ‡ú „ñ‡ú !ÆHÄ !¨ÆHÄ The and methods return the “ and values of a point. If the point is ü ̈Â"PÅc43Ò€Ç Ê3ÁgW¨Æ currently drawn in a . hence Ê3g Á W¨Æ changing the state of the object. Some methods require parameters that are themselves complex objects. the method lives inside the object. the ÃPÌÂ£Û method issues an appropriate sequence of low-level drawing commands  %q %q . we could use this statement. respectively. gÐ €“ – To move the point „ïÊÎÁWÆæñIÖxՉõ–Õ3ú –  to the right 10 units. The second line creates a for the first parameter to the ü Ì"  Pc Å 4ÎÒIÇ . Ê3g Á W¨Æ The method must be supplied with two simple numeric parameters indicating the distance to move the object along each dimension. The visible ü Ì"  Pc Å 4ÎÒIÇ effect of this statement is a circle in the centered at ‚H…žw w u…žw wg„ and having a radius of 30. drawing ü ̈  © Å 4ÎÒ€Ç ×ˆÒxÌ3ÑHÀHÆ into a involves two objects. Methods such as these are sometimes called accessors. Here is a specification: ÊÎ Á WƬñô© à ¦„õ¢ÃPÏÎú à ¦ © ÃPÏ : Moves the object units in the “ direction and units in the direction. because they allow us to access information from the instance variables of the object. Using information about the center and radius of the circle from the instance variables. Other methods change the values of an object’s instance variables. Behind the scenes. ѐÒxÌ3ÑÈßÝ×ÒÓÌ3Ñ1ÀPƬñ–ØÁҀǨĄñ€Ö€ÕÕ‰õ‡ÖxÕPÕ3ú“õ ސÕ3ú ÛÎÒIÇàß ü Ì"  © Å 4ÎÒIÇnñIú ѐÒxÌ3ÑæïùÃPÌ£ۄñèÛÎÒIǓú ׈ÒÓ̽ÑHÀHÆ Ø¨ÁˆÒ€Ç¨Ä ‚H…žw w u…žw wg„ and The first line creates a with a center located at the بÁˆÒ€Ç¨Ä a radius of 30. ÃPÌÂ£Û ÑPÒÓÌ½Ñ Remember. will also take care of erasing the old image and drawing it in its new position. Let’s examine a sequence of a commands that does this. Notice that we used the constructor to create a location ׈ÒxÌ3ÑHÀHÆ constructor. Do you see what is happening in the third line? This is a request for ü ̈ ׈ÒxÌ3ÑHÀHÆ ÑÒÓÌ½Ñ Â © Å 4ÎÒ€Ç ÛÎÒ€Ç the object to draw itself into the object . Methods that change the state of an object are sometimes called mutators. For example. a lot more is happening. This changes the x instance variable of by adding 10 units.

. and let them do the work. call the appropriate methods. Here is a sequence of code intended to draw the eyes. Low-level drawing commands win: . we don’t usually have to worry about these kinds of details. . óa ó ¢‡Ç4Ñ£ÁH̨̐ƈÑxÄU۽£ÏWÄÁ¡ÑǪ́ƨ£ÄÆUÄHۈÁàѐÒxÌ3Ñ1ÀPƽܬï ÀPÆHÍPÄ ÏÆUßÝ׈ÒÓ̽ÑHÀHÆæñ–بÁˆÒIÇĄë ñ eÕ‰ç õ 9HÕ3ú†Æ õ 9½ú G ÀPÆHÍPÄ ÏÆoïzÜÓÆH© Ä D½ÒHÀPÀ¬ñ ùÏƐÀÀPÁ£Û †ú G ÀPÆHÍPÄ ÏÆoïzÜÓÆHÄ Ä ÉÄÀҀLjÆæñ ðÌÆHà †ú G Ì3" Ò !1Å¨Ä Ï¨ÆcßÐÀPÆHÍPÄ ÏÆ  %  … G G . It is possible for two different variables to refer to exactly the same object. and objects is shown in % % Figure . A conceptual picture of ü ÌÂ"PÅc4ÎÒIÇ Ø¨ÁˆÒ€Ç¨Ä ×ÒÓ̽ÑHÀPÆ the interactions among the . That’s the power of object-oriented programming. . GraphWin 30 x: y: Point 100 100 % % Figure . . We just create objects. they’re all taken care of by the graphical objects.´H ¯  ½ˆ 6 Š† †}"uxw€t 6 ³ u±gÑ g$ ©Ë ‰Ê { ³ y|ˆ ~z”€” ü Ì"  PÅc4ÎÒIÇ (a sequence of method invocations) to the . There is one subtle “gotcha” that you need to keep in mind when using objects. : Object interactions to draw a circle. Fortunately. changes made to the object through one variable will also be visible to the other. circ: Circle center: radius: draw( ) . Suppose we are trying to write a sequence of code that draws a smiley face. We want to create two eyes that are 20 units apart. .

but it’s not . and it can sometimes produce rather unexpected results. G G ×ÒÓÌ3Ñ1ÀPÆ shows the situation. When the is moved in the last line of code. : Variables ÑÒ ÓuԀՀր×gØ%Ô Ù`Ú)Û3Üր×gØ%Ô and are aliases. The problem here is that only one ated. ÝgݝÞeß!à ß ß àã ß àäß ß à Ùgç¡ Ù%Ô èé֎ áºâ!Óu؝ Öë ÚíìÙ%Ö} Öuñuáï`ò’ð°ñºÚsÙò ӀԺå£æ à Ô%êQâ!îgÖïfԎ ӀӀÔuÔuՀՀրր×g×gØ Ž Ô ) Ú Ù 6 Ô B ê  ð ԅ ærærå)å)ÔuÔuÖgÖéóºõsöÚuÖӀßÓ£ êìéôqØÔ6Ôgê%àÓgôlÙÓ ÔuᏠôòò ÓÙ` €ÔuÚ)ՀÛ3Ü%ր×gÖgØ Ø … Ô  Ó m Ú … ÷  ô à êmømïgï}ðƒñuï`ò’ðùñéò g × % Ø ž Ô ¡ ç é è s Ú Ù € Ó 6 Ô w ê ë m Ú  ì f Ö Ù` Ù`Ú)Ú)Û3Û3Ü%Ü%ÖgÖg×g×gØ%Ø%Ô ÔæQæQå!å!ÔuÔuրÖó` õ)ö%Ú3ÖéÓgÓ£ ÓÚíê%ìºôlØ%Ô£Ô%êÓgôlÙ%Ó Ô€á… ÷fôRôRòò This will certainly work. This situation where two variables refer to the same object is called aliasing.~z” ¯ Ì3Ò"!1Å¨Ä G s4tvuxw†y|{‡}3´PîÑ Ï¨ÆnïÊÎÁgW¨ÆæñzÔPՄõèÕ3ú ‰Ê { ³ y|ˆ‰uxŠŒ‹ †}$uxwxt 6 ³ ˆ ÌË The basic idea is to create the left eye and then copy that into a right eye which is then moved over 20 units. both Ì3" Ò !1Å¨Ä Ï¨Æ ÀPÆPÍHÄ ÏÆ G G and refer to it in its new location on the right side. leftEye: Circle center: radius: 10 x: y: Point 80 50 rightEye: Figure . We had to write duplicated code for the two eyes. Figure . but it’s cumbersome. One solution to this problem would be to create a separate circle for each eye. ׈ÒÓ̽ÑHÀHÆ object is creThis doesn’t work. That’s easy to do using a “cut and paste” approach. The assignment Ì3Ò"!1Å¨Ä G ϨÆcßÐÀPÆHÍPÄ G ÏÆ % & Ì3" Ò !1ÅÄ Ï¨Æ ÀPÆPÍHÄ ÏÆ simply makes refer to the very same circle as .

óóÝ×PÁHÌPÌƈÑxÄc۽£ÏWÄÁàÑxÌƨ£ÄÆUÄHۈÁàÑPÒÓÌ3Ñ1ÀPƈܭõîÉ4ÜPҀÇC!àÑHÀHÁ£ÇˆÆnï ÀPÆHÍPÄ ÏÆUßÝ׈ÒÓ̽ÑHÀHÆæñ–بÁˆÒIÇĄë ñ eÕ‰ç õ 9HÕ3ú†Æ õ 9½ú G ÀPÆHÍPÄ ÏÆoïzÜÓÆH© Ä D½ÒHÀPÀ¬ñ ùÏƐÀÀPÁ£Û †ú G ÀPÆHÍPÄ ÏÆoïzÜÓÆHÄ Ä ÉÄÀҀLjÆæñ ðÌÆHà †ú G Ì3" Ò !1Å¨Ä Ï¨ÆcßÐÀPÆHÍPÄ ÏÆoïôÑ1ÀPÁ£ÇˆÆæñ‡úªó€Ì½Ò !1Å¨Ä ÏÆÐҐÜUÂÓÇ¡) Æ ¦¨ÂÑxÄ¡Ñ1Á"ÏÐÁP̀Ä1ŽÆÝÀHÆPÍPÄ G G G Ì3" Ò !1Å¨Ä Ï¨ÆnïÊÎg Á W¨ÆæñzÔPՄõèÕ3ú  %  … G Strategic use of cloning can make some graphics tasks much easier. we’re ready to try some real graphics programming. it is almost certainly better than a thousand numbers. the output will be a ten-year bar graph where the height of successive bars represents the value of the principal in successive years.´H ´H †}"uxw€t 6 Š†¦óӅ†y腀}${jô@u±7…†{ uË ~z”€´ very elegant. Remember the program in Chapter 2 that computed the future value of a ten year investment? Let’s try our hand at creating a graphical summary. One of the most important uses of graphics is providing a visual representation of data. Few programs that manipulate numeric data couldn’t be improved with a bit of graphical output. Using these inputs. ºa”|º Î ªgIi„¤§˜h‡penšqð•¦o…Φ•gI‚òñ i„j|¦Ÿ‚ !Ḧ"  PÅ4ÒPÑ¨Ü Now that you have some idea of how to use objects from the module. Suppose we invest $2000 at 10% interest. º  In the graphical version. Using . we begin by considering the specification of exactly what the program will do. Í£É) Ä WˆÂÀ„U ï ¨Ï The original program had two inputs. !PÌ"  PÅ4ÒÑÜ library provides a better solution. the amount of money to be invested and the annualized rate of interest. You’ll probably want pencil and paper handy to draw some diagrams and scratch out calculations as we go along. As usual. the program calculated the change in principal year by year for ten years using the formula principal principal ‚H… apr „ . Let’s use a concrete example for illustration. all graphical objects support The ÑHÀPÁÓÇ½Æ Ñ1ÀPÁÓÇ½Æ a method that makes a copy of the object. If we decide to change the appearance of the eyes. Programming with graphics requires careful planning. we will have to be sure to make the changes in two places. This table shows the growth of the investment over a ten-year period: . It then printed out the final value of the principal. we can rescue the original approach. They say a picture is worth a thousand words.

00 $2.43 $4.~z”€¹ s4tvuxw†y|{‡}3´PîÑ ‰Ê { ³ y|ˆ‰uxŠŒ‹ †}$uxwxt 6 ³ ˆ ÌË Years 0 1 2 3 4 5 6 7 8 9 10 Value $2.00 $2. let’s number these bars according to the number of years of interest accrued. Figure .49 % ' Our program will display this information in a bar graph. For reference.221. shows the original value of the principal.287. Here is a rough design for the program: ؐ̽ҀǨÄÐÂÓǻҀǨĐ̨ÁPÃ1ÉÎÑÓĽÒ1Á£Ç ü Æ1¥ Ä WˆÂPÀÓɽÆcÁP£ Í ̽ҀÇÎѐ Ò ½ÂÀ€ÂxLjÃÐ  ÌÝÍP̨ÁxÊÝÉ4Ü£Æ1Ì .00 $2.90 $5.02 $3.420.200.00 $2.12 $3.897.20 $3.715.542.928. 0–10.187. The first bar % ' Figure .662.000 at 10% interest.18 $4.000. : Bar graph showing growth of $2. The graph actually contains eleven bars. shows the data in graphical form.

The number of pixels or resolution of the screen is determined by the monitor and graphics card in the computer you use. Most screens are considerably ü ̈  c Å 43Ò€Ç larger. a bar for year five with height corresponding to $3. what does it mean to draw. We must decide exactly how big the graphics window will be and how we will position the objects that appear in this window. Without such a pause. That should allow all users to see the graphical output as well as the textual output from our program. or 320 x 240.02? ü ̈  © Å 4ÎÒ€Ç . To simplify the problem. we can flesh out a bit of our design. Thus. You may also supply width and height parameters to control the size of the window. the command to create the output window will be: ÛÎÒIÇàß ü ÌÂ"Å©4ÎÒIÇnñ ¢IÇcWƽ܀ģÊ3Æ£ÇÄ ü ÌÁ1ېÄHÅà×ÓÅ3£̐Ä#3õ˜Þ¨ÔHՄõ Ôd¨Õ½ú Next we turn to the problem of printing labels along the left edge of our window. The third line of the design should now read: ×H̨ƨ£ÄÆWÂWÞ¨ÔHÕE¦àÔgdÕ ü ̈ũ4ÎҀǀÄ3ÒxĈÀPÆHà 3¢IÇcWƽ܀ģÊ3Æ£ÇÄ ü ̨Á1Û¨Ä1ÅàףŽÂ1ÌPÄ —úgú g You may be wondering how this will translate into Python code. there are some very important details that have been glossed over. the program ü ̈"  Pc Å 43Ò€Ç would end and the would vanish with it. For example. While this design gives us the broad brush strokes for our algorithm.´H ´H †}"uxw€t 6 Š†¦óӅ†y腀}${jô@u±7…†{ uË ~z”€¿  ×H̨ƨ£ÄÆW ü ÌÂ"PÅc4ÎÒIÇ ¨ÌÂ£Û ÜHÑHÀHÆWÀÂx˽ƐÀˆÜ ÁÓÇÿÀPÆPÍHÄ ÜPÒÓèÆWÁPÍcÛ3ҀÇèÁ1Û ¨Ì£ۀ˽Â1ÌàÂ1ÄEˆÁ½ÜHÒÓÄ3Ò£Á£ÇÝՀÛ3ÒÓÄ1ŀŽÆÒ !1ŨġÑ1Á1̨̐ƽÜqˆÁ£ÇýҀÇC!UĨÁ`Ì3ÒIÇ4ÑPÒ3ÂPÀ DÁ1Ì ÜIÉÎѐÑ1ƈܐÜH" Ò WÆ ÏƐÂ1ÌÎÜWÖYÄ1Ą̊Á£§ É !£Å ÖxÕ ×¨ÂPÀрɽÀÂ£Äè Æ ¨Ì3ÒIÇ4ѐq Ò 3ÂPÀÈE ß ̽ҀÇ4ÑP Ò ½Â¥ À Y ñIÖ áÐ"  ÌÎú ¨Ì£ۡ Ë3£ÌÝͨÁ1ÌWÄHÅ4ÒÜ ÏƐÂ1ÌcŽ  W3ÒI§ Ç !ÝÂÈÅˆÆˆÒ !£ÅÄ¡Ñ£ÁHÌPÌƽu Ü ½ÁÓLjýÒI§ Ç ! Ä` Á ¨Ì3ҀÇÎѐÒq3À 4½Â¨ÒÓÄÝ͐ÁHÌcÉ@ÜÓÆH̀Ĩ` Á Ì¨Æ½ÜÜ ÇĨÆH̙ï  G The pause created by the last step is necessary to keep the graphics window displayed so that we can interpret the results. Computer screens are also measured in terms of pixels. The lowest resolution screen you are likely to encounter these days is a so-called standard VGA screen that is 640 x 480 pixels.221. You have alü ̈Åc43Ò€Ç ready seen that the constructor allows an optional parameter to specify the title of the window. Recall that the size of a window Let’s start with the size of the is given in terms of the number of pixels in each dimension. we will assume the graph is always scaled to . Given this analysis. say. Let’s make the one quarter the size of a 640 x 480 screen.

0K” to “10.000 leaves ¡ w¦†Y"  ¡ w w w pixels to split between the top and bottom margins. This leaves just a bit of whitespace at the margin. That means our five labels should be spaced 50 pixels apart.~z”€â s4tvuxw†y|{‡}3´PîÑ ‰Ê { ³ y|ˆ‰uxŠŒ‹ †}$uxwxt 6 ³ ˆ ÌË a maximum of $10. the height of the bar is determined by the value of .000 with the five labels “0. we specify the anchor point (the point some the text is centered on) and the string to use as the label. we determined that 100 pixels is equal to $5.000.000. we have just over 200 pixels to work with. In the vertical direction. The question is how should the labels be drawn? We will need g Æ ¦PÄ Æg¦PÄ objects. A little experimentation suggests that putting the “ 0. the single step ¨ÌÂ£Û ÜHÑHÀHÆWÀÂx˽ƐÀˆÜ ÁÓÇÿÀPÆPÍHÄ ÜPÒÓèÆWÁPÍcÛ3ҀÇèÁ1Û     becomes a sequence of steps ¨Ì£ۡÀPÂÓ˽ƐÀϪÕnïùÕ # Â1Ä©ñ†ÔHՄõ ÔHސÕ3ú ¨Ì£ۡÀPÂÓË½ÆÏ À  ÔoH ï 9 # Â1Ä©ñ†ÔHՄõªÖeÕ3ú ¨Ì£ۡÀPÂÓË½ÆÏ À 9oïùÕ # Â1Ä©ñ†ÔHՄõªÖ€ÞÕ3ú ¨Ì£ۡÀPÂÓË½ÆÏ À ªþnH ï 9 # Â1Ä©ñ†ÔHÕ„Ô õ ePÕ3ú ¨Ì£ۡÀPÂÓË½ÆÏ À 1րÕnïùÕ xfÂ1Ä©ñ†ÔHՄõ ÞPÕ3ú The next step in the original design calls for drawing the bar that corresponds to the initial amount of the principal.0 is located vertically at pixel 230. Now we just need to figure out where the opposite (upper right) corner of the bar should be so that we can draw an appropriate rectangle.000. Using 200 pixels for the range 0–10. The placement of the labels is chosen with a bit of calculation and some trial and error. and the labels are centered 20 pixels in from the left edge. The value of $0. A simple scaling would be to have 100 pixels represent $5.0K” as shown in the example window. When creating . We might º want to leave a little more margin at the top to accommodate values that grow beyond $10. In the ¨Ì3ÒIÇ4ѐq Ò 3ÂPÀ vertical direction. This 3!ÀÀ 3!ÀÀ 3À %q . Our longest label is five characters. and the labels should all line up on the right side of a column. Playing with some interactive examples. it seems that a string of length five looks nicely positioned in the horizontal direction placing the center 20 pixels in from the left edge. Elaborating our algorithm to include these details. In drawing the scale. Adding another 20 pixels gets us to the right edge of the labels. The label strings are easy. so the shorter strings will be padded on the left with spaces. Thus the lower left corner of the 0th bar should be at location ‚”w ô¡ y"wg„ .0K” label 10 pixels from the bottom (position 230) seems to look nice. It is easy to see where the lower left corner of this bar should be.

All that remains is to percolate these details into the rest % ( of the algorithm. (0.0K 7. We chose a bar width of 25. This tells us. We can use a variable to represent the year number and calculate the “ coordinate of the lower left corner . for º example.´H ´H †}"uxw€t 6 Š†¦óӅ†y腀}${jô@u±7…†{ uË ~z”€é means that we have …žw wgý"x"w w w wch w1¡ pixels to the dollar. Let’s figure out where the lower-left corner of each bar is going to be located. Figure .000 should produce a bar of height ¡"w w w§‚fh w1¡„ º w pixels. we have made all the major decisions and calculations required to finish out the problem. but 40 pixels are eaten up by the labels on the left.0K 2. that a principal of $2.230) (319. º  We can now fill the details for drawing the first bar into our algorithm. That leaves us with 280 pixels for 11 bars: ¡ "wgý©… … ¡ x©h gxgx . the position of the upper-right corner will be given by ¡ y"w6†5‚ principal „X‚ƒwch w1 ¡ „ .0) 10.5K 240 5. : Position of elements in future value bar graph.239) % ( Figure . ¨Ì£ۡÂŲƈÑÓÄÂÓC Ç !ÀPÆÈÍP̨ÁxÊ ë ñ dÕ„õ ÔHސÕ3úªÄÁòñz© ø 9‰õ ÔHސ  Õ ¨V̽ҀÇÎѐ Ò ½Â  À YUÕoïðՐԽú – – !&  At this point. so the bar for each successive year will start ÏƐÂ1Ì 25 pixels farther right than the previous year.0K 10 40 320 (40.230) 25 (315. the right edge of our first bar will be at position w ¡ x i x . shows the general layout of the window with some of the dimensions we have chosen. Let’s just make each bar 25 pixels. In general. How wide should the bar be? The window is 320 pixels wide. (Remember that ¡ y"w is the w point. and the coordinates decrease going up). So. that will give us a bit of º margin on the right side.5K 50 0.

but we are finally ready to translate this algorithm into actual Python code. Putting all of this together produces the detailed algorithm shown below: ؐ̽ҀǨÄÐÂÓǻҀǨĐ̨ÁPÃ1ÉÎÑÓĽÒ1Á£Ç ü Æ1¥ Ä WˆÂPÀÓɽÆcÁP£ Í ̽ҀÇÎѐ Ò ½ÂÀ€ÂxLjÃÐÂÌÝÍP̨ÁxÊÝÉ4Ü£Æ1Ì ×H̨ƨ£ÄÆWÂWÞ¨ÔH) Õ ¦¨g Ô d¨Õ ü Ì"  © Å 4ÎÒIÇÝÄ3ÒxĈÀPÆHà 3¢Ic Ç Wƽ܀ģÊ3Æ£ÇÄ ü ̨Á1ېÄHšףŽÂ1ÌPÄ ¨Ì£ۡÀPÂÓË½ÆÏ À ªÕnïùÕ # Â1Ä©ñ†ÔHՄõ–ÔPސսú ¨Ì£ۡÀPÂÓË½ÆÏ À  ÔoH ï 9 # Â1Ä©ñ†ÔHՄõª Ö eÕ3ú ¨Ì£ۡÀPÂÓË½ÆÏ À 9oïùÕ # Â1Ä©ñ†ÔHՄõªÖ€ÞÕ3ú ¨Ì£ۡÀPÂÓË½ÆÏ À ªþnH ï 9 # Â1Ä©ñ†ÔHÕ„Ô õ ePÕ3ú ¨Ì£ۡÀPÂÓË½ÆÏ À 1րÕnïùÕ xfÂ1Ä©ñ†ÔHՄõ ÞPÕ3ú ¨Ì£ۡÂŲƈÑÓÄÂÓC Ç !ÀPÆÈÍP̨ÁxÊ ë ñ dÕ„õ ÔHސÕ3úªÄÁòñz© ø 9‰õ ÔHސ  Õ ¨V̽ҀÇÎѐҽÀ YUÕoïðՐԽú ͨÁ1ÌWÏƐÂ1ÌWÌHÉPǐÇÎҀ§ Ç !UÍP̨ÁxÊ £  WˆÂPÀÓɈÆWÁPÍ Öf© É àÄ1ÅÌÁÓ§ É !£Å»ÖxÕo÷ רÂPÀрɽÀÂ£Äè Æ ¨Ì3ÒIÇ4ѐq Ò 3ÂPÀÈE ß ̽ҀÇ4ÑP Ò ½Â¥ À Y ñIÖ áÐ"  ÌÎú רÂPÀрɽÀÂ£Ä£ Æ ¦¨ÀÀcßà© Ô 9SY Ϩƨ£ÌÝ¥ á d¨Õ ¨Ì£ۡÂUÌÆÑÓÄÂÓ§ Ç !¨ÀPÆÈÍPÌÁ€Ê ë ñ ¦¨ÀÀ‰õ˜ÔPސսú ÄÁòÒ ñ ¦ÀÀ1á) Ô 9‰õ ÔHސ  Õ ¨V̽ҀÇÎѐ Ò ½ÂÀTY€ÕoïðՐԽú 4½Â¨ÒÓÄÝ͐ÁHÌcÉ@ÜÓÆH̀Ĩ` Á Ì¨Æ½ÜÜ ÇĨÆHÌ    3!ÀÀ 3!ÀÀ 3À —úgú g  G Whew! That was a lot of work. The translation is straightforward using objects !P̈ÅÎÒÑ¨Ü from the module. (The   course. Here’s the program: óWÍ1ɨĩWÀ©Ì!PÌÂ"ÅhïU¨Ï ÍP̨ÁxÊa!ḦÂ"PÅ4ÒPѨÜUÒvÊCˆÁH̐Ä@Y . Here is the refined algorithm: – – ͨÁ1ÌWÏƐÂ1ÌWÌHÉPǐÇÎҀǧ!UÍP̨ÁxÊ Â£WˆÂPÀÓɈÆWÁPÍ ÖfÉ©àÄ1ÅÌÁÓɧ!£Å»ÖxÕo÷ רÂPÀрɽÀÂ£Äè Æ ¨Ì3ÒIÇ4ѐq Ò 3ÂPÀÈßE̽ҀÇ4ÑPҽÀ¥Y ñIÖ áÐÂ"ÌÎú רÂPÀрɽÀÂ£Ä£ Æ ¦¨ÀÀcßà© Ô 9SY Ϩƨ£ÌÝ¥ á d¨Õ רÂPÀрɽÀÂ£ÄÆYňƈ" Ò !1ÅĀT ß ¨Ì3ÒIÇ4ѐq Ò 3ÂP¥ À YUÕnïùÕ¨Ô ¨Ì£ۡÂUÌÆÑÓÄÂÓ§ Ç !¨ÀPÆÈÍPÌÁ€Ê ë ñ ¦¨ÀÀ‰õ˜ÔPސսú ÄÁòÒ ñ ¦ÀÀ1á) Ô 9‰õ ÔHސՠ¨  ŽÆÒ £ ! ÅÄ4ú ¦¨ÀÀ The variable stands for “ lower left—the “ value of the lower left corner of the bar. The value of the upper right corner is ¨Ì3ÒIÇ4ѐq Ò 3ÂPÀ determined from the (updated) value of exactly as we determined it for the first bar.~ ¯ 7 s4tvuxw†y|{‡}3´PîÑ ‰Ê { ³ y|ˆ‰uxŠŒ‹ †}$uxwxt 6 ³ ˆ ÌË w leaves space on the left edge for the labels. the coordinate of this point is still ¡ y"w (the bottom of the graph). we add 25 (the width of the bar) to the “ value of the lower-left corner. To find the upper-right corner of a bar.) Of as ‚ year „X‚ ¡ x„ w .

´H ´H †}"uxw€t 6 Š†¦óӅ†y腀}${jô@u±7…†{ èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ó ¢IǨĐÌÁHÃ1ÉÎÑÓÄ3Ò£Á£Ç a ̽ҀÇ Ä XHÅÎÒ¨ Ü ¨ÌÁ)!ḦÂIÊ¥3ÀHÁHÄ3ÜYÄHŽÆT!HÌÁ£Û¨ÄHÅÐÁPÍÐÂÿÖxÕ©¨1ϨƨÂ1ÌàҀÇCW¨Æ½Ü€Ä£ÊÎÆÓÇğïq ó ü Æ1ÄEÌ3ÒIÇ4ÑPÒ3ÂPÀ€ÂÓÇÃàҀǨÄÆ1Ìƽ܀Ā̈£ÄÆ  ̽ҀÇ4ÑPҽÀÈßÿÒIÇ©É¨Ä„ñ" ǨÄÆ1ÌUÄ1ŽÆàҀÇÎÒÓĽÒHÀ§Ì3ÒIÇ4ÑPÒ3ÂPÀo÷ü£ú  G  ¨ÌÝߡҀ© " Ç PÉĉñ  ÇĨÆHÌcÄ1ŽÆÝÂxǐǐɽÀ¨Ò ¨ÆHÃÐÒIÇÄÆ1ÌƈÜxÄcÌÂ1ĨÆn÷£ú G uË ~ ¯ ~ !h óÝ×H̨ƨÂ1ĨÆWÂT!PÌÂ"ÅÎҐѐܪÛÎÒILjÐÁ1ÛWÛÎÒxÄHÅ¡ÀPÂÓˈƨÀˆÜYÁ£ÇÿÀPÆHÍPÄÐÆHé!¨Æ ÛÎÒIÇàß ü ̈ũ4ÎҀÇoñ ¢IÇCW¨Æ½Ü€Ä£ÊÎÆÓÇÄ ü ̨Á1ېÄHÅà×ÓÅ3Â1ÌPÄ#3õ¢Þ¨ÔHՄõ Ôd¨Õ3ú ÛÎÒIDŽïzÜÓÆHÄ ˆÂÑÎC!HÌÁ£ÉPLjÃæñ †ÛHÅ4ÒxÄƕ£ú g Æ ¦PĄñèØÁҀÇĉñ†ÔHՄõlÔPސսú†õ ÕoïðÕ vú­ïùÃPÌ£ۄñèÛÎÒIǓú g Æ ¦PĄñèØÁҀÇĉñ†ÔHՄõ Ö eÕ½ú†õ Ô„¡ ï 9 vú­ïùÃPÌ£ۄñèÛÎÒIǓú g Æ ¦PĄñèØÁҀÇĉñ†ÔHՄõÖxސսú†õ ˜9„ïðÕ vú­ïùÃPÌ£ۄñèÛÎÒIǓú g Æ ¦PĄñèØÁҀÇĉñ†ÔHՄ5 õ eÕ3ú“õ þnH ï 9 Œú¬ïpÃP̈ÂÓÛoñðÛÎҀÇ@ú g Æ ¦PĄñèØÁҀÇĉñ†ÔHՄõ ސÕ3ú“õ ‡Ö€ÕnïùÕ Œú¬ïpÃP̈ÂÓÛoñðÛÎҀÇ@ú € ó ¨Ì£ۀË3£ÌÝͨÁ1ÌÿҀÇ4ÒxÄ3Ò1Àè¨Ì3ҀÇÎѐÒq3À ŽÆÒ !1ŨÄWߣ̽ҀÇÎѐҽÀ YUÕoïðÕÔ Ë3£ÌÝßE ˆÆˆÑxĈÂxǧ!ÀHÆæñèØÁˆÒIÇĉñëd¨Õ‰õ ÔPސսú†õlبÁˆÒIÇĄñôøc9æõ˜ÔPÞPÕc¨xŽƈÒ"!1ŨÄ4úú Ë3£̙ïzÜÓÆH) Ä D3ÒHÀPÀ¬" ñ ž!P̨ƐÆÓ Ç £ú Ë3£̙ïzÜÓÆHg Ä 4ÎÒ£ÃHÄHÅoñ†Ô½ú Ë3£̙ïùÃḦÂÓÛoñèÛ3ҀÇ@ú ž ž ó #  #  # #  # 3!À À 3À  !3À À ¨Ì£ۀË3£ÌÎÜ ÍÁHÌ ÜIÉÎѐѣƽܐÜHÒ"W¨ÆÈÏƐÂ1Ì3Ü Í¨Á1ÌWÏƨ£̡ҀÇàÌÂÓǧ!ÆæñI֓õ‡ÖPÖPú­÷ ó¡ÑHÀ¨Ñ€É½ÀÂ1Ĩ£ Æ WˆÂPÀÓɈÆcͨÁ1ÌWÄHŽÆÈLjÆ)¦HĀÏƐÂ1Ì Ì3ÒIÇ4ÑP Ò 3ÂPÀÈE ß ̽ҀÇÎѐ Ò ½ÂT À Y¥ñ€Ö áà"  ¨Ì4ú óWÃP̈ÂÓۀË3£ÌÝͨÁHÌWÄ1Å4Ґ§ Ü WˆÂPÀÓÉ½Æ ¦ÀÀc߀Ϩƨ£a Ì Yc© Ô 9c  á d¨Õ Žƈ" Ò !1ŨÄW£ ß ̽ҀÇ4ÑP Ò ½Â  À YUÕoïðÕ¨Ô Ë3Â1ÌÝE ß  ƈÑxĈÂÓC Ç !ÀHÆæñ–بÁˆÒIÇÄ„Ò ñ ¦ÀPÀ‰õîÔPÞPÕ3ú“õ¢ØÁˆÒIÇĉñë¦ÀPÀHá¨Ô©9‰õlÔPÞPÕc¨xŽƈÒ"!1ŨÄ4úú Ë3Â1̟ïzÜÓÆH© Ä D½ÒHÀPÀ¬ñ X!P̨Ɛƣx Ç £ú Ë3Â1̟ïzÜÓÆH) Ä 43Ò£ÃHÄHÅnñzÔ½ú Ë3Â1̟ïùÃḦ£ۄñèÛ3ҀǓú ̈ÂÓÛmÌÒIÇ©PÉĄñ"ŒØPÌƽÜPÜ Ç¨ÄÆ1Ì ( FG ĨÁTí1É4ÒxÄ#Óú .

you know): Ë3£̙ïôÜ£ÆH) Ä D3Ò1ÀÀ¬" ñ ž!HÌƐÆÓ Ç Óú Ü£Æ1Ä Ä É¨ÄˆÀ¨Ò€Ç½Æ You can also change the color of a shape’s outline using the method. So. you will see that I added a number of features to spruce it up a bit. saving them into a variable is unnecessary. ¦ÀPÀc߀ÏƐÂ1a Ì Yc© Ô 9€¥ á dÕ I hope you are starting to get the hang of graphics programming. ¨Æ)¦HÄ We can just create a object. ̈ÂÓÇC!¨Æ¬ñ€Ö“õv֐ÖHú The expression produces a sequence of ints 1–10. then 3. and be done with it. ÛÎÒIDŽïôÜ£ÆHÄ ˆÂ¨ Ñ ÎC!HÌÁÓɐLjÃæñ zÛPÅ4ÒxÄ• Æ £ú € Ë3Â£Ì I have also changed the color of the object. etc. In this case. Since we don’t ever change the labels. It’s a bit strenuous. Here is an example: g Æ ¦Pĉñ–ØÁҀǨĄñ†ÔHՄõ–ÔPސսú†õ ÕnïùÕ vú¬ïpÃPÌ£ÛoñðÛÎÒIǓú ® 3À Finally. but very addictive. To enhance this effect. then 2. this code makes the outline wider (two pixels instead of the default one). . up to 10. tell it to draw itself. I have set the background color of the window to white (by default it’s gray). The ÏÆ¨Â£Ì value of is then used to compute the proper position of the lower left corner of each bar. Ë3£̙ïôÜ£ÆHg Ä 4ÎÒÓÃPÄHÅoñ†Ôˆú You might also have noted the economy of notation in drawing the labels.~ ¯ r ÛÎÒIDŽïôÑ1ÀPÁˆÜ£Ææñ‡ú Ê4¨ҀÇoñIú s4tvuxw†y|{‡}3´PîÑ ‰Ê { ³ y|ˆ‰uxŠŒ‹ †}$uxwxt 6 ³ ˆ ÌË If you study this program carefully.. take a close look at the use of the ͨÁ1ÌWÏƐÂ1ÌÿҀÇÐÌÂÓÇC!¨ÆæñI֓õv֐ÖPú­÷ ÏÆ¨Â£Ì variable in the loop. I have chosen to leave the outline the default black so that the bars stand out from each other. the first time through is 1. All graphical objects support methods for changing color. The loop inÏƐÂ1Ì marches through this sequence on successive iterations of the dex variable ÏÆ¨Â£Ì loop. The following line asks the bar to color its interior green (because it’s money.

but it would require a bit of arithmetic. but it makes for tedious programming. It doesn’t take too much mathematical savvy to see that the transformation process always follows the same general pattern. the !PÌ"  PÅ4ÒÑÜ module provides a simple mechanism to do it for you. You can then use this coordinate system to place graphical objects in the window. Tic-Tac-Toe fashion. suppose we just want to divide the window into nine equal squares. The problem becomes trivial if we first change the coordinates of the window to run from 0 to 3 in both dimensions. In our example. ó¡ÑǪ́ƨ£ÄÆÝÂcèÆHÍÂxÉ3À1ÄÝÔPՐg Õ ¦ÔHՐÕÈÛ3ҀLjÐÁ1Û ÛÎÒIÇàß ü Ì"  © Å 4ÎÒIÇnñ 33ÒPg Ñ ¨Â Ñ ¨ÁP' Æ Óú – óÿÜ£Æ1ÄÿÑ1ÁPÁH̨ÈҀǽÂ1ÄÆˆÜ Ä¨ÁT!¨Á€ÍP̨ÁxÊ ñôՄõ–Õ½úUҀÇàÄ1ŽÆÝÀPÁ£ÛˆÆ1ÌÐÀPÆHÍPÄ ó ÄÁ ñzމõ–Þ½úUҀÇÐÄ1ŽÆÈÉ©)½Æ1̀Ì3Ò"!1Åğï ÛÎÒIDŽïôÜ£ÆHĨאÁPÁH̨ýܓñôÕnïðՉõîÕnïðՉõ˜ÞnïùՄõ ÞoïðÕ3ú ó ¨Ì£۠W¨ÆH̐ĽҐÑ1À€À¨Ò€Ç½ÆˆÜ ¤ ÒIǽƬñ–ØÁҀǨĄñ€Ö@õ–Õ½ú†õ ØÁҀÇĉñ€Ö@õ–Þ3úPú¬ïpÃP̈ÂÓÛoñðÛÎҀÇ@ú 3 ¤3ÒIǽƬñ–ØÁҀǨĄñ†Ôæõ–Õ½ú†õ ØÁҀÇĉñ†Ôæõ–Þ3úPú¬ïpÃP̈ÂÓÛoñðÛÎҀÇ@ú ž ž ó ¨Ì£ۀňÁHÌ3Ò ¨ÁÓÇĈÂPÀcÀ¨Ò€Ç½ÆˆÜ )h .000).´H ¹HHs@tŒ‚x‚€ˆ 6 ŠŒqsˆ‚Ó‚Ó}$‹ 6 Švu†y|{ôˆ ºa”–ê  ˜Ÿ™q™„‘ˆ‡peŸšs l™q™„gI·§‡pe™i„…‚„‘ ~ ¯ ” Í£ÉÄ)WˆÂÀ !ḦÂ"PÅ The lion’s share of the work in designing the program was in determining the precise coordinates where things would be placed on the screen. the problem domain called for “ values representing the year (0–10) and values representing monetary amounts ($0–$10. The method requires four parameters specifying the coordinates of the lower-left and upper-right corners. To take a simple example. When you creü ̈"  Pc Å 43Ò€Ç ate a you can specify a coordinate system for the window using the Ü£Æ1Ä×PÁÁH̐Ã3Ü method. respectively. We had to transform these values to be represented in a 320 x 240 window. It’s nice to work through an example or two to see how this transformation happens. In order to save you the trouble of having to explicitly convert back and forth between coordinate systems. This could be done without too much trouble using the default 200 x 200 window. Most graphics programming problems require some sort of a coordinate transformation to change values from a real-world problem into the window coordinates that get mapped onto the computer screen. Coordinate transformation is an integral and well-studied component of computer graphics. Anything that follows a pattern can be done automatically.

Basically. Because the same coordinates span Ü£Æ1ÄאÁPÁH̐Ã3Ü the window (due to ) the objects will scale appropriately to the new window size. We can apply this idea to simplify our graphing future value program. Each bar starts at the given year and a baseline of 0 and grows to the next year ¨Ì3ҀÇÎѐq Ò 3À and a height equal to . we can locate the left side labels at -1.000 (representing dollars) in the dimension. Since our bars start at 0. This is easily fixed by expanding the coordinates of the window slightly. We could create just such a window like this. using the alternative coordinate system: óWÍ1ɨĩWÀ©Ì!PÌÂ"Å½ÔoïbÏ ÍP̨ÁxÊa!ḦÂ"PÅ4ÒPѨÜUÒvÊCˆÁH̐Ä@Y èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ .~ ¯€¯ ¤3ÒIǽƬñ–ØÁҀǨĄñzՉõ‡ÖHú†õ ¤3ÒIǽƬñ–ØÁҀǨĄñzՉõôԈú†õ s4tvuxw†y|{‡}3´PîÑ ‰Ê { ³ y|ˆ‰uxŠŒ‹ †}$uxwxt 6 ³ ˆ ÌË ØÁҀÇĉñzމõ‡ÖPúPú¬ïpÃP̈ÂÓÛoñðÛÎҀÇ@ú ØÁҀÇĉñzމõôÔ½úPú¬ïpÃP̈ÂÓÛoñðÛÎҀÇ@ú Another benefit of this approach is that the size of the window can be changed Û3Ò€Ç by simply changing the dimensions used when the window is created (e. We can add a bit of whitespace around the graph by expanding the coordinates slightly beyond that required for our graph. we want our graphics window to go from 0 through 10 (representing years) in the “ dimension and from 0 to 10.g. we haven’t left any room for labels or margins around the edges. Using “raw” window coordinates would require changes in the definitions of the lines. Ë3£ÌÝßE ˆÆÑÓĈÂxǧ!¨ÀPÆæñèØÁҀÇĉñ–ϨƨÂ1Ìoõ Õ3ú“õ¢ØÁˆÒIÇĉñ–ÏƐÂ1̐á4֓õ   ̽ҀÇÎѐҽÀˆúú There is a small problem with this scheme. ÛÎÒIÇàß ü ÌÂ"Å©4ÎÒIÇnñ ¢IÇcWƽ܀ģÊ3Æ£ÇÄ ü ÌÁ1ېÄHÅà×ÓÅ3£̐Ä#3õ˜Þ¨ÔHՄõ Ôd¨Õ½ú ÛÎÒIDŽïôÜ£ÆHĨאÁPÁH̨ýܓñôÕnïðՉõîÕnïðՉõfÖxÕoïðՉõªÖxՐÕPՐÕoïðÕ3ú – ÏÆ¨Â£Ì ¨Ì3ÒIÇ4ѐq Ò 3ÂPÀ Then creating a bar for any values of and would be simple. A little experimentation leads to this window definition: ÛÎÒIÇàß ü ÌÂ"Å©4ÎÒIÇnñ ¢IÇcWƽ܀ģÊ3Æ£ÇÄ ü ÌÁ1ېÄHÅà×ÓÅ3£̐Ä#3õ˜Þ¨ÔHՄõ Ôd¨Õ½ú ÛÎÒIDŽïôÜ£ÆHĨאÁPÁH̨ýܓ8 ñ ¨3Ö­ïùc þ 9æë õ ¨ÔHՐÕæõ ֐ֆ¡ ï 9‰õÖx) Õ dÕÕ½ú Here is the program again. Can you see what I have forgotten? The bars will fill the entire window. ß ü Ì"  Pc Å 4ÎÒIÇnñ"X3ÒPÑg¨ ˆÂѨ¨ÁÆ'3õ ސÕPՄõ ސÕPÕ3ú ).

This ü ÌÂ"Å©4ÎÒIÇ version also makes it easy to change the size of the .´H ¹HHs@tŒ‚x‚€ˆ 6 ŠŒqsˆ‚Ó‚Ó}$‹ 6 Švu†y|{ôˆ óa¢IǨĐÌÁHÃ1ÉÎÑÓÄ3Ò£Á£Ç ~ ¯ ´ ̽ҀÇÄXHÅÎҨܨÌÁ)!ḦÂIÊ¥3ÀHÁHÄ3ÜYÄHŽÆT!HÌÁ£Û¨ÄHÅÐÁPÍÐÂÿÖxÕ©¨1ϨƨÂ1ÌàҀÇCW¨Æ½Ü€Ä£ÊÎÆÓÇğïq ó ü Æ1ÄEÌ3ÒIÇ4ÑPÒ3ÂPÀ€ÂÓÇÃàҀǨÄÆ1Ìƽ܀Ā̈£ÄÆ  ̽ҀÇ4ÑPҽÀÈßÿÒIÇ©É¨Ä„ñ" ǨÄÆ1ÌUÄ1ŽÆàҀÇÎÒÓĽÒHÀ§Ì3ÒIÇ4ÑPÒ3ÂPÀo÷ü£ú  G  ¨ÌÝߡҀ© " Ç PÉĉñ  ÇĨÆHÌcÄ1ŽÆÝÂxǐǐɽÀ¨Ò ¨ÆHÃÐÒIÇÄÆ1ÌƈÜxÄcÌÂ1ĨÆn÷£ú G !h óÝ×H̨ƨÂ1ĨÆWÂT!PÌÂ"ÅÎҐѐܪÛÎÒILjÐÁ1ÛWÛÎÒxÄHÅ¡ÀPÂÓˈƨÀˆÜYÁ£ÇÿÀPÆHÍPÄÐÆHé!¨Æ ÛÎÒIÇàß ü ̈ũ4ÎҀÇoñ ¢IÇCW¨Æ½Ü€Ä£ÊÎÆÓÇÄ ü ̨Á1ېÄHÅà×ÓÅ3Â1ÌPÄ#3õ¢Þ¨ÔHՄõ Ôd¨Õ3ú ÛÎÒIDŽïzÜÓÆHÄ ˆÂÑÎC!HÌÁ£ÉPLjÃæñ †ÛHÅ4ÒxÄƕ£ú ÛÎÒIDŽïzÜÓÆHĨאÁÁ1̨ýܓ3 ñ ¨½Ö­ïùc þ 9‰Ò õ ¨ÔHՐÕæõ ֐֭H ï 9‰õfր) Õ dÕÕ3ú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“õ Õ3ú†õ ÕoïðÕ vú­ïùÃḦ£ۄñèÛ3ҀǓú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“õl© Ô 9PÕPÕ3ú“õ ÔoH ï 9 Œú¬ïpÃP̈ÂÓÛoñðÛÎҀÇ@ú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“° õ 9PՐÕPÕ3ú“õ î9oïùÕ Œú¬ïpÃP̈ÂÓÛoñðÛÎҀÇ@ú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“õ c þ 9PÕPÕ3ú“õ þnH ï 9 Î Œú¬ïpÃP̈ÂÓÛoñðÛÎҀÇ@ú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“õÖxՐÕPՐսú†õ vÖxÕnïùÕ vú¬ïpÃPÌ£ÛoñðÛÎÒIǓú € ó ¨Ì£ۀË3£ÌÝͨÁ1ÌÿҀÇ4ÒxÄ3Ò1è À ¨Ì3ҀÇÎѐq Ò 3À Ë3£ÌÝßE ˆÆˆÑxĈÂxǧ!ÀHÆæñèØÁˆÒIÇĉñzՄõîÕ½ú†õ¢ØÁҀǨĄñ€Ö@õI̽ҀÇÎѐҽÀˆúú Ë3£̙ïzÜÓÆH) Ä D3ÒHÀPÀ¬" ñ ž!P̨ƐÆÓ Ç £ú Ë3£̙ïzÜÓÆHg Ä 4ÎÒ£ÃHÄHÅoñ†Ô½ú Ë3£̙ïùÃḦÂÓÛoñèÛ3ҀÇ@ú ž ž ó  # !À !À #  ##  3À  3À ¨Ì£ۡ Ë3£ÌÝͨÁ1ÌÐƨÂÑIÅ»ÜIÉPË@Ü£Ægí1ɈƣÇÄUÏƐÂ1Ì Í¨Á1ÌWÏƨ£̡ҀÇàÌÂÓǧ!ÆæñI֓õÖPÖPú­÷ Ì3ÒIÇ4ÑP Ò 3ÂPÀÈE ß ̽ҀÇÎѐ Ò ½ÂT À Y¥ñ€Ö áàÂ"¨Ì4ú Ë3Â1ÌÝE ß  ƈÑxĈÂÓC Ç !ÀHÆæñ–بÁˆÒIÇĄñèÏƐÂ1Ìnõ Õ½ú†õ¢Ø¨ÁˆÒ€Ç¨Ä„ñèÏƨ£̨áÎ֓õ   Ì3ÒIÇ4ÑPÒ3ÂPÀ½úPú Ë3Â1̟ïzÜÓÆH© Ä D½ÒHÀPÀ¬ñ X!P̨Ɛƣx Ç £ú Ë3Â1̟ïzÜÓÆH) Ä 43Ò£ÃHÄHÅnñzÔ½ú Ë3Â1̟ïùÃḦ£ۄñèÛ3ҀǓú ̈ÂÓm Û ÌÒI© Ç PÉĄ" ñ ŒØPÌƽÜPÜ ÛÎÒIDŽïôÑ1ÀPÁˆÜ£Ææñ‡ú Ê4¨ҀÇoñIú FG ǨÄÆ1Ì ( ĨÁTí1É4Òxęïu£ú Notice how the cumbersome coordinate calculations have been eliminated. In . Changing the window size to 640 x 480 produces a larger. but correctly drawn bar graph.

The hides the underlying event-handling mechanisms and provides two simple ways ü Ì"  © Å 4ÎÒIÇ of getting user input in a . When the user moves the mouse. ºa”sr t–eo…‚™gIiŸƒ“…ˆ‡‰„‚ |Î ªgIi„¤§˜h‡ƒ­‘ Graphical interfaces can be used for input as well as output. Event-driven programming can be tricky for novice programmers. which would then perform the appropriate action corresponding to that button. this generates an event. Obviously. Basically. the program pauses and waits for the user to click the mouse somewhere in the graphics window. The event object is then sent off to an appropriate part of the program to be processed. In a GUI environment. When you are doing graphics programming. For example. This event would be passed to the button handling code. and then waits for the user to do something. all of the calculations would have to be redone to accommodate the new scaling factors in the larger window. Here is a The spot where the user clicks is returned to the program as a bit of code that reports the coordinates of ten successive mouse clicks: ÍP̨ÁxÊa!ḦÂ"PÅ4ÒPѨÜUÒvÊCˆÁH̐Ä@Y ÛÎÒIÇàß ü ÌÂ"Å©4ÎÒIÇnñ vרÀ¨ÒÑÎÈöˆÆ ͨÁ1ÌÿÒWҀÇà̈Âxǧ!Ææñ€Ö€Õ3ú­÷ uÓú . clicks a button or types a key on the keyboard.~ ¯ ¹ s4tvuxw†y|{‡}3´PîÑ ‰Ê { ³ y|ˆ‰uxŠŒ‹ †}$uxwxt 6 ³ ˆ ÌË the original program. When is invoked on a . ØÁҀÇÄ . since it’s !P̈  ÅÎÒÑ¨Ü module hard to figure out “who’s in charge” at any given moment. ×È ÈƒÊ Sû ü iCtžtql™wm• ¶ Ū `ý vxr%si gÙnl‡œ cs !ÆHÄHöˆÁ£É4Ü£Æ We can get graphical information from the user via the method of the ü Ì" ü ÌÂ"PÅc4ÎÒIÇ Â PÅc4ÎÒIÇ !¨Æ1ÄPöˆÁÓÉ@ÜÓÆ class. an event is an object that encapsulates data about what just happened. users typically interact with their applications by clicking on buttons. the program draws a set of interface elements (often called widgets) on the screen. and typing information into on-screen text boxes. the second version of our program is much easier to develop and understand. give some consideration to choosing a coordinate system that will make your task as simple as possible. choosing items from menus. These applications use a technique called event-driven programming. a click on a button might produce a button event. Basically.

No interaction completely graphical. Then when environment. you can name this program using a the program is run. If you are programming in a Windows ï ÏHÛ b extension. ó€ØÌ¨) Á !Ḧ€ʕ÷îĐ̽ÒHÂx§ Ç !ÀHÆnb ï ÏPÛ ÍP̨Áxa Ê !Ḧ"  PÅ4ÒPѨÜUÒvC Ê ˆÁH̐@ Ä Y G“ ÁÓÉ ÑHÀ¨ÒÑÎÆPÃòñ Ã„õ Ã3úm B" " ¯" gÐ ñHhïf!ÆHÄ æñIú“õ „  ïp!¨Æ1Ä „ñ‡úú %Ð €“ g“ èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ÛÎÒIÇàß ü ̈ũ4ÎҀÇoñ  ¨ÌˆÂÓÛÝÂEPÌ3ÒHÂxǧ!¨ÀPÆ'Óú ÛÎÒIDŽïzÜÓÆHĨאÁÁ1̨ýܓñzÕoïðՉõ ÕoïðՉõfÖxÕoïðՄõªÖ€ÕnïùÕ3ú ÊÎƈܐÜ1  !¨ÆcT ß ¨) Æ ¦HĄñ–بÁˆÒIÇĄñ89‰õ ÕnïH9½ú†õèvרÀ¨ÒÑÎÝÁ£ÇÐÄHŨÌÆPÆV½ÁҀÇÄ3Ü%Óú ÊÎƈܐÜ1  !¨ÆoïùÃPÌ£ۄñèÛÎÒIǓú ó ü Æ1ÄàÂÓLjÃWÃḦÂÓÛÝÄHĄ̊ƐƣW¨ÆHÌPÄ3ÒÑ£Æ½Ü  Ö ß€ÛÎÒIDŽïp!¨ÆHÄHöˆÁÓÉ@ܣƬñIú †  ֆïùÃPÌ£ۄñèÛÎÒIǓú † 3Ôc߀ÛÎÒIDŽp ï !¨ÆHÄHöˆÁÓÉ@ܣƬñIú 3ԄïùÃPÌ£ۄñèÛÎÒIǓú ½Þ€ß€ÛÎÒIDŽp ï !¨ÆHÄHöˆÁÓÉ@ܣƬñIú ½ÞoïùÃPÌ£ۄñèÛÎÒIǓú ÁH̀Đ̽ÒHÂÓÇC!ÀHÆ r ó Ù@ÜÓÆcØÁ¨À£Ïc!Á£ÇàÁÓË ÆÑÓĀĨÁ€ÃPÌ£ÛÝÄHňÆcĐ̽ÒHÂÓÇC!ÀHÆ U ï Đ̽ÒHÂÓÇC!ÀHÆUßWØÁÀ1Ïc!Á£ÇoñH†Ö@õp½Ô‰õpˆÞ3ú Đ̽ÒHÂÓC Ç !ÀHÆnïzÜÓÆH) Ä D3ÒHÀPÀ¬" ñ 8½ÆÂÑI© Å HɈ͐' Í Óú Đ̽ÒHÂÓC Ç !ÀHÆnïzÜÓÆHÄ Ä ÉÄÀÒIǽÆæ" ñ xÑxψ€ Ç £ú Đ̽ÒHÂÓC Ç !ÀHÆnïùÃḦÂÓÛoñèÛ3ҀÇ@ú ó 4½Â¨ÒÓÄÝͨÁ1ÌàÂÓLjÁHÄHňÆHÌ¡Ñ1ÀÒPÑÎWĨÁWÆ)¦½ÒxÄ E ÊÎƈܐÜ1Â!¨ÆoïzÜ£Æ1Ä©¨Æ)¦Pĉñ vרÀÒPÑÎcÂxÇÏPÛHŽÆ1ÌÆÈĨÁTí1ÉÎÒÓęïu£ú ÛÎÒIDŽf ï !ÆHÄHöˆÁ£É4ܣƬñIú Ê4¨ҀÇoñIú . We can use it like !ÆHÄ !ÆHÄ and or other methods such as any other point using accessors such as ÃPÌÂ£Û Ê3g Á WÆ and . making use of with a Python text window is required. Here is an example of an interactive program that allows the user to draw a triangle by clicking on three points in a graphics window. This example is g Æ ¦PÄ objects as prompts. it will not even display the Python shell window.´P ¿Pcu Š†y|{‡}"u ³ y 6 D { †}"uxw€t 6 ³ ˆ à߀ÛÎҀÇhïf!ÆHÄPöÁ£É4Ü£Ææñ‡ú ̽ҀÇÄ 4Ë ~ ¯ ¿ !¨Æ1ÄPöÁ£É@ÜÓÆæñ‡ú ØÁˆÒIÇÄ The value returned by is a ready-made .

closed shape. Once we have three 3Ô ˆÞ . all of the input was provided through mouse clicks. Đ̽ÒHÂx§ Ç !ÀHÆc߀ØÁÀ1© Ï !¨Á£ÇoH ñ “Ö“õ ½Ô‰5 õ ˆÞ3ú g Æ ¦PÄ You should also study how the object is used to provide prompts. A triangle is just a three-sided polygon. The derstands ÇÄPÌÏ can be edited by the user.~ ¯ â s4tvuxw†y|{‡}3´PîÑ ‰Ê { ³ y|ˆ‰uxŠŒ‹ †}$uxwxt 6 ³ ˆ ÌË !P̈  ÅÎÒÑ¨Ü The three-click triangle illustrates a couple new features of the ØÁÀ1Ï©!¨Á£Ç module. creating the triangle is a snap. and . It unAn G ÜÓÆH) Ä ) Æ ¦HÄ !¨Æ1© Ä ¨) Æ ¦PÄ Æ)¦HÄ and methods just like the object does. single ÊÎƈܐܣg  !¨ÆUT ß ) Æ ¦HĄñèØÁˆÒIÇĉ3 ñ 9‰õ ÕnH ï 9½ú“è õ ‡×¨À¨Ò Ñ ÎÐÁ£ÇÐÄ1ÅÌÆPV Æ ½ÁҀǨÄÎ% Ü Óú ÊÎƈܐܣg  !¨ÆoïùÃḦ£ۄñèÛ3ҀǓú g Æ ¦PÄ To change the prompt. ×È È‘Ç Sû þ j› ÿ –Bw 6Ùnl™wm• i§›Ct"r%–QÙ äbw'Í6rmt In the triangle example. we can just change the text that is displayed. This is done near the end of the program with Ü£Æ1© Ä ¨) Æ ¦PÄ method. A ¨Æ)¦PÄ object is created and drawn near the beginning of the program. !ḦÂ"PÅ4ÒPÑ¨Ü Ç¨ÄÌÏ module also includes a simple G object that can be used to The ü ̈Åc43Ò€Ç . The constructor for accepts any number of points and creates a polygon by using line segments to connect the points in the order given and to connect the last point back to the ØÁҀÇÄ32 Ü “Ö . however there is a general class بÁ¨À£Ïc!¨ÁÓÇ that can be used for any multi-sided. the method of provides a simple way of interacting with the user in a graphics-oriented program. the ÊÎƈܐܣg  !¨ÆoïzÜÓÆH© Ä ¨) Æ ¦HĄñ vרÀ¨Ò Ñ ÎcÂxÇÏHÛPŽÆ1ÌÆ ÄT Á í1ÉÎÒÓğq ï £ú ü ̈  c Å 43Ò€Ç !¨Æ1ÄPöÁ£É@ÜÓÆ As you can see. There is no triangle class. Here’s a difference is that the contents of an G version of the temperature conversion program from Chapter 2 with a graphical user interface: ó¡Ñ1ÁÓÇCW¨ÆH̐ÄCÌg!£É4҉ïbÏHÛ ó€ØÌ¨) Á !Ḧ€ÊÐÄÁàÑ1ÁÓC Ç W¨ÆH̐ÄWאƨÀÜPÒIÉ@Ü Ä¨ÁEDˆÂÓŨÌÆÓǐŽÆÒÓÄ ó !PÌ"  ÅÎҐÑ1ÀWÒIÇĨÆH̨ͨÂÑ£Ænï ÍP̨ÁxÊa!ḦÂ"PÅ4ÒPѨÜUÒvÊCˆÁH̐Ä@Y É@ÜPÒIǧ!ÐÂàÜH҇ÊC½ÀPÆ . get keyboard input in a ÇÄPÌÏ object draws a box on the screen that can contain text. first. we don’t need to create a new object.

this produces a window with an entry box for typing in a Celsius temperature and a “button” for doing the conversion. The button is just for show. Ҁ) Ç ÉÄ entry box is set to contain the value 0. The program actually just pauses for a mouse click anywhere in the window. The user can Initially. % ) Figure . shows how the window looks when the program starts.0. the .´P ¿Pcu Š†y|{‡}"u ³ y 6 D { †}"uxw€t 6 ³ ˆ 4Ë ~ ¯ é èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ÛÎÒIÇàß ü ̈ũ4ÎҀÇoñ vאƨÀÜPÒIÉ@ܪאÁÓÇCWÆ1̐ĨÆHÌ#3õ¢ÞPՐՄõ ÔHՐսú ÛÎÒIDŽïzÜÓÆHĨאÁÁ1̨ýܓñzÕoïðՉõ ÕoïðՉõ˜ÞnïùՄõÆdŸïùÕ3ú × Æ¨ÀÜPҀÉ4ܧƀÊCˆÆḦ£ÄHɨÌÆn÷u£ú­ïùÃPÌ£ۄñèÛÎÒIǓú P Æg¦PĄñèØÁҀÇĉñ€Ö@õ‡ÖPú“õüXDˆÂxĄ̊ƣǐňƈÒxÄEƀÊCˆÆḦ£ÄHɨÌÆn÷u£ú­ïùÃPÌ£ۄñèÛÎÒIǓú ҀÇ)ÉÄ€ß ÇÄP̐τñèØÁҀÇĉñ†Ôæõ–Þ3ú“5 õ 9½ú G ҀÇ)ÉğïzÜÓÆHÄ©¨Æ)¦HĄñ vÕnïù' Õ £ú ҀÇ)ÉğïùÃḦ£ۄñèÛ3ҀǓú Á£É¨ÄgÉ¨ÄWßTg Æ ¦Pĉñ–ØÁҀǨĄñ†Ôæõ‡ÖHú† õ )£ú Á£É¨ÄgÉ¨Ä™ïpÃP̈ÂÓÛoñðÛÎҀÇ@ú ːɨĐÄÁÓÇÐT ß g Æ ¦Pĉñ–ØÁҀǨĄñ€Ö†¡ ï 9æõôÔoïùÕ3ú“ õ ‡×PÁ£c Ç Wƣ̐¥ Ä ¢x6 Ä £ú ːɨĐÄÁÓDŽïpÃP̈ÂÓÛoñðÛÎҀÇ@ú  ˆÆÑÓĈÂx§ Ç !¨ÀPÆæñèØÁҀÇĉñ€Ö@õ‡Ö­H ï 9½ú“õ ØÁҀÇĉñ†ÔæõôÔoH ï 9½úPú¬ïùÃḦÂÓÛoñèÛ3ҀÇ@ú óc۽¨ÒÓÄÝͨÁ1Ìà ÊÎÁÓÉ@Ü£ÆàÑ1ÀÒPÑÎ ÛÎÒIDŽïf!ÆHÄHöˆÁ£É4ܣƬñIú ó¡Ñ1ÁÓÇCWÆ1̐ġÒIÇ©PÉÄ Ñ1ƐÀˆÜPÒIÉ@ÜYßÝ Æ WˆÂPÀ¬ñvÒIÇ©PÉęïp!¨Æ1Ä©Æg¦PĉñIúú ÍÂxÅÌÆÓǐňƈÒÓÄcßÝýnïùc Õ Ÿ©9„ïðS Õ YÝѣƨÀˆÜHҀÉ4Ü áÐÞ¨Ô óWýҐÜq3ÀPÂ1ÏÝÁÓÉĐÉÄÝÂÓLjáÑIÅ3Âxǧ!¨ÆYːÉÄPÄÁÓÇ Á£É¨g Ä É¨Ä™ïôÜ£ÆH) Ä g Æ ¦PĄ" ñ  ÕnïŒÖI6 Í  WͨÂÓĄ̊ƣÇPŽƈÒxÄ4ú ːɨĐÄÁÓDŽïôÜ£ÆH) Ä g Æ ¦PĄ" ñ  xÉ4ÒÓ6 Ä £ú óc۽¨ÒÓÄÝͨÁ1ÌÿÑHÀ¨ÒÑÎÐÂÓLjÀÄ1ŽÆÓÇ@í1É4ÒxÄ ÛÎÒIDŽïf!ÆHÄHöˆÁ£É4ܣƬñIú ÛÎÒIDŽïôÑ1ÀPÁˆÜ£Ææñ‡ú Æg¦PĄñèØÁҀÇĉñ€Ö@õ–Þ3ú“õü ž ó ¨Ì£ÛÝÄHňÆàҀǨÄÆH̐ͨÑ1Æ Rí" °" Ê4¨ҀÇoñIú When run.

~z´7 s4tvuxw†y|{‡}3´PîÑ ‰Ê { ³ y|ˆ‰uxŠŒ‹ †}$uxwxt 6 ³ ˆ ÌË % ) Figure . (via the string formatting operator) for display in the % 10 Figure . This number is then converted input box is converted into a number (via to degrees Fahrenheit. delete this value and type in another temperature. sizes and line widths of the various widgets. This example could be made much prettier using some of the options in the graphics library for changing the colors. : Initial screen for graphical temperature converter. !ÆHÄPöÁ£É4Ü£Æ ÇÄPÌÏ and G do not provide a full-fledged Although the basic tools GUI environment. the has a chance to enter a value in the input box. The code for the program is deliberately Spartan to illustrate just the essential elements of GUI design. Notice that the point where the user clicks is not even !¨Æ1ÄPöˆÁÓÉ@ÜÓÆ function is just used to pause the program until the user saved. and the label on the button has changed to “Quit” to show that clicking again will exit the program. . shows how the window looks after the user has typed an input and clicked the mouse. we will see in later chapters how these simple mechanisms can support surprisingly rich interactions. Finally. the text in the ÆWˆÂÀ ). Notice that the converted temperature shows up in the output area. The program pauses until the user clicks the mouse. the resulting number is turned back into a string Á£É Ä É¨Ä text area. The program then processes the input in four steps. First.

This section provides a complete reference to the objects and functions provided in the graphics library. you will probably want to refer back to this section often when you are writing your own graphical programs. A may be drawn.´H âH †}"uxw€t 6 ³ ˆ„䧂£‹1…± { P{ôå {‡}${‡Š ³ { uË „i ~z´H~ % 10 Figure . The set of objects and functions that are provided by a module is sometimes called an Applications Programming Interface or API. You should probably read this section over once to see what the graphics library has to offer. the default title is “Graphics Window. ×È¡ ÈƒÊ ü   ŽŸƒ¾s¿ “f–'Í £¢³l™w 3imœ)tus ü ̈ũ4ÎÒ€Ç A object represents a window on the screen where graphical images ü ÌÂ"Å©4ÎÒIÇ ü ÌÂ"Å©4ÎÒIÇ s. Draws the pixel at ‚”“ black is the default. After that. Experienced programmers study APIs to learn about new libraries.” and the default size is 200 x 200. 3ÀHÁHĉë ñ ¦oõ Ïnõ Ñ1ÁÀPÁ1Ì4ú „ in the window. : Graphical temperature converter after user input. A program may define any number of understands the following methods: ü Ì"  Pc Å 4ÎÒIÇnñèÄ3ÒÓÄÀPƉõ Û3Ò£ÃPÄ1řõîňƈ" Ò !1ÅÄÎú Constructs a new graphics window for drawing on the screen. The parameters are optional. ºa”s‘ Î ªgIi„¤§˜h‡ƒ­‘»km™q·q¦„j ‚ c 쇂hgI‚™eŸƒ¬‚ The examples in this chapter have touched on most of the elements in the !PÌ"  PÅ4ÒÑÜ module. ’q – . Color is optional.

(Does not work for ü Ì"  Pc Å 4ÎÒIÇ ÃPÌ£ۄñ†Â ü ̈  c Å 43ҀÇ@ú Draws the object into the given .5 for information on specifying colors. – . All subsequent drawing will be done with respect to the altered coordinate 3ÀHÁHÄPØ3Ò ¦Æ¨À ). and . Ü£Æ1Ä Ä ÉĈÀ¨Ò€ÇˆÆæñvÑ£Á¨ÀHÁHÌ4ú Sets the outline of the object to the given color. ÊÎ Á WƬñô© à ¦„õèÃHÏ4ú à ¦ © ÃHÏ Moves the object units in the “ direction and units in the direction. ɐÇÃPÌ£Ûoñ‡ú Undraws the object from a graphics window. where the mouse was clicked as a Ü£Æ1Ä×PÁÁH̐Ã3Ü@ë ñ ¦ÀPÀ‰õ ψÀPÀ‰Æ õ ¦1ɨÌnõlÏ1ÉÌÎú Sets the coordinate system of the window. The lower left corner is ‚”“%ûƒû ûƒûU„ and the upper right corner is ‚”“£¤%ö ¤mög„ . . ׈ÒxÌ3Ñ1ÀPÆ Ä WˆÂÀ  ƈÑxĈÂÓÇC!ÀHÆ ØÁÀ1Ï©!¨Á£Ç Æg¦PÄ . All graphics objects support the following generic set of methods: Ü£Æ1© Ä D½ÒHÀÀ­ñvÑ£Á¨ÀPÁ1Ì4ú Sets the interior of the object to the given color. .8. system (except for g ’q – qq – mq – ×È¡ È‘Ç ü Ÿ ž½¾)¿ “f–'Í Ql‡œ©s 8i%œgtus بÁˆÒIÇÄ ¤½Ò€Ç½Æ The module provides the following classes of drawable objects: . !¨Æ1ÄPöÁ£É@ÜÓÆæñ‡ú Pauses for the user to click a mouse in the window and returns ØÁҀÇÄ object. See Section 5. they are identical to the cloned object. . . ÑHÀHÁ½ÜÓÆæñIú Closes the on-screen window. ÑHÀHÁ£ÇˆÆæñIú Returns a duplicate of the object. any coordinate transformations set up by Ü£Æ1Ä Â Ñ Îc!P̨Á£ÉÇÉñŒÑ1Á¨ÀHÁHÌÎú Sets the window background to the given color. the image is adjusted to the new position.~z´€r 3ÀHÁHÄPØ3Ò ¦Æ¨À­ñë¦oõ s4tvuxw†y|{‡}3´PîÑ Ïnõ ×PÁ¨ÀPÁ1Ì4ú ‰Ê { ³ y|ˆ‰uxŠŒ‹ †}$uxwxt 6 ³ ˆ ÌË Draws the pixel at the “raw” position ‚”“ „ ignoring Ü£Æ1Ä×PÁÁH̐Ã3Ü . If the object is currently drawn.) els. Other than that. All objects are initially created unfilled with a black outline. Clones are always created in an undrawn state. The initial background is gray. Ü£Æ1) Ä 43Ò£ÃPÄ1Ånf ñ 4Ò ¦Æ¨Àܨú Sets the width of the outline of the object to this many pixØÁˆÒIÇÄ .

These are opposite corner points of a square that circumscribes the circle. Possible values of è͈ÒÓÌÎÜ€Ä ôÀPˆÜxÄ p˽Á1ÄHÅ pLjÁ£Ç½Æ pLjÁ£Ç½Æ are . at !¨Æ1Ä×PÆ£ÇĨÆH̉ñIú Returns a clone of the center point of the rectangle. or both. !¨Æ1ĐØ4Ö4ñIú“ç õ !¨Æ1ĐØÔ¬ñIú Returns a clone of corner points originally used to construct the rectangle. Returns the radius of the circle. . æñIú Returns the “ coordinate of a point. and . !¨Æ1ĐØ4Ö4ñIú“õç!¨Æ1ĐØÔ¬ñIú Returns a clone of the corresponding corner of the circle’s bounding box.´H âH †}"uxw€t 6 ³ ˆ„䧂£‹1…± { P{ôå {‡}${‡Š ³ { ¥ uË „i ~z´€” Š§…‡©„ ƒ } „X‰CŠ§¦§‚ ØÁҀǨĄñ름õðÏÎú !¨Æ1Ä !¨Æ1Ä ¨ %Ð g“ Constructs a point having the given coordinates. the last point. ¤3ÒIǽƬñH½ÁҀǨÄ@֓õ ½ÁҀǨĈԽú Constructs a line segment from ½ÁҀÇÄ4Ö to ½ÁҀÇÄÔ . . Ü£Æ1Ä Ú ÌÌÁ£ÛoñvÜxĐ̽ҀÇC!Îú    …    f  f ˆ …‡zs‹ˆ} ƒ }„X‰cŠ©¦§‚ ׈ÒxÌ3Ñ1ÀPÆæñŒÑ1ÆÓÇÄÆ1̐بÁˆÒ€Ç¨Änõ ̈Â1ýÒIÉ@ܨú Constructs a circle with given center point and radius. !¨Æ1Ä×PÆ£ÇĨÆH̉ñIú Returns a clone of the midpoint of the line segment. !¨Æ1ĐØ4Ö4ñIú“ç õ !¨Æ1ĐØÔ¬ñIú Returns a clone of the corresponding endpoint of the segment. Sets the arrowhead status of a line. !¨Æ1Ä×PÆ£ÇĨÆH̉ñIú !¨Æ1Ä) ˆÂHýÒIÉ@Ü@ñIú Returns a clone of the center point of the circle. Arrows may be drawn ܀Đ̽Ҁǧ! at either the first point. The default setting is . Returns the } „ž‰cŠ©¦§‚ ‰ñIú ƒ …nC} – coordinate of a point.  }‹„8€C%ˆ} ƒ }„X‰cŠ©¦§‚ ˆÁˆÒ€Ç¨ÄˆÔˆú  ˆÆÑÓÄÂÓǧ!¨ÀPƬñH½ÁҀǨÄ@֓õ Constructs a rectangle having opposite corners ˆÁˆÒIÇÄ@Ö ½ÁˆÒIÇÄÔ and . .

Returns the current string. Ü£Æ1Ä§Å¨Ò ¨Æ¬ñHˆÁˆÒ€Ç¨Ä4ú !h  Returns a clone of the anchor point. !¨Æ1ĐØ4Ö4ñIú“õç!¨Æ1ĐØÔ¬ñIú Returns a clone of the corresponding point used to construct the oval. Possible values pňƨ À W¨ÆHĽҐÑH †Ñ£Á£É̽Ò1Æ1Ì ðĽ҇ÊΈ Æ Ü ÌÁ€Ê4x Â Ç –Â1Ì3Ò1À are: . Sets the color of the text to Ñ1ÁÀPÁHÌ . Note: Ü£Æ1Ä©D3Ò1ÀÀ has the same effect. Ü£Æ1Ä©¨Æ)¦PĨאÁÀPÁH̉ñvÑ£Á¨ÀPÁ1Ì4ú  }   ©  f . ƒ } „X‰cŠ©¦§‚ ¥ Šm§Šm ØÁÀ1Ï©!¨Á£ÇoñHˆÁˆÒ€Ç¨Ä@Ö@õ ˆ  ÁˆÒ€Ç¨ÄˆÔæõ ½  ÁҀǨÄބõWïïïzú Constructs a polygon having the given points as vertices. The text is displayed horizontally. Also accepts a single parameter that is a list of the vertices. ƒ } „X‰CŠ§¦§‚ !¨Æ1ĐبÁˆÒ€Ç¨ÄÎÜ@ñIú yx}  „ Æg¦Pĉñ†ÂÓÇÎрňÁH̐بÁˆÒIÇÄnõ˜Ü€ÄÌ3ÒIǧ!3ú ÜxĐ̽ҀÇC! Constructs a text object that displays the given ÂxÇ4ÑIŽÁHÌPØÁҀÇÄ centered at .~z´ ¯  s4tvuxw†y|{‡}3´PîÑ €C ƒ } „ž‰cŠ©¦§‚ ½ÁҀǨĈԽú ‰Ê { ³ y|ˆ‰uxŠŒ‹ †}$uxwxt 6 ³ ˆ ÌË Ä WÀ­ñH½ÁҀǨÄ@֓õ ½ÁˆÒIÇÄ4Ö and ½ÁҀÇÄÔ Constructs an oval in the bounding box determined by . and . Ú Ç4рňÁH̉ñIú Ü£Æ1Ä©DÂÑ1Ƭñôͨ€ʓÒ1À1ÏÎú ÍÂIʓÒHÀ£Ï Changes the font face to the given . . !¨Æ1Ä×PÆ£ÇĨÆH̉ñIú Returns a clone of the point at the center of the oval. . Returns a list containing clones of the points used to construct the polygon. . Sizes from 5 to Ü£Æ1ħţĐψÀHÆæñvÜxĐÏÀPƽú ܀ĐÏÀPÆ pǽÁ1Ì£ÊΐÀ Changes font to the given . 6  £   ‘  6 Changes the font size to the given 36 points are legal. Possible values are p˽ÁÀHà zÒÓĐÀÒPÑ –˽ÁÀHÃàÒxĈÀ¨ÒÑ . Sets the text of the object to ÜxÄPÌ3ҀÇC! Ü£Æ1Ä©¨Æ)¦Pĉñ‡Ü€ÄÌ3ÒIǧ!3ú !¨Æ1Ä©¨Æ)¦PĉñIú !¨Æ1Ä . . ˆÁˆÒIÇÄ size. and .

Image specific methods are given below. centered at the given center point. . . Display is done with an object. ͽÒHÀHƣǽ€ÊÎƽú !¨Æ1Ä Ú Ç4рňÁH̉ñIú . and . Ü£Æ1Ä©¨Æ)¦Pĉñ‡Ü€ÄÌ3ÒIǧ!3ú Ü£Æ1Ä§Å¨Ò ¨Æ¬ñHˆÁˆÒ€Ç¨Ä4ú  !h Sets the text in the entry box to the given string. !¨Æ1Ä Ú Ç4рňÁH̉ñIú Returns a clone of the point where the entry box is centered. Returns a clone of the point where the image is centered. . . G ǨĐÌPτñvѣƣǨÄÆHÌPØÁҀÇÄoõ ÛÎÒ£ÃHÄHÅ@ú Ç¨ÄÌÏ Constructs an G having the given center point Û3Ò£ÃHÄHÅ ÛÎÒÓÃPÄ1Å and . The is specified in number of characters of text that can be displayed. ×È¡ È ™ œ g¤ ¦lns ÍBٌ– §l™w%•aäU—î–m•'i§s The graphics module also provides minimal support for displaying certain image formats into a GraphWin. Ü£Æ1Ä©¨Æ)¦PĨאÁÀPÁH̉ñvÑ£Á¨ÀPÁ1Ì4ú  }  £   f . and . . and . the font face to the given †Ñ1ÁÓÉ̽Ò1ÆHÌ ðĽ‡ Ò ÊÎÆˆÜ ÌÁ€Ê4ÂxÇ ô£Ì3Ò1À . Most platforms will support JPEG. . and . ¢vÊÎÂg!ÆæñvѣƣǨÄÆHÌPØÁҀÇÄoõ Constructs an image from contents of the given file.×È¡ È‘É šdwmt"“ l¤ÅŸƒ¾s¿ ´H âH †}"uxw€t 6 ³ ˆ„䧂£‹1…± { P{ôå {‡}${‡Š ³ { 3imœ)tus uË „i ~z´€´ ÇĐÌPÏ Objects of type G are displayed as text entry boxes that can be edited by Ç¨ÄÌÏ the user of the program. …  ‘  f ©  f Changes the font size to the given 36 points are legal. The ǨĐÌPÏ G specific methods are given below. G objects support the generic graphics methÊÎg Á W¨Ææñ‡ú ÃP̈ÂÓÛoñÒ!P̈ŐÛÎҀÇ@ú ÉPLjÃḦ£ۄñIú ÜÓÆHÄ)D3ÒHÀPÀ¬ñŒÑ1Á¨ÀHÁHÌÎú Ñ1ÀPÁ£ÇˆÆæñ‡ú ods . . Possible values are: . Possible values are: p˽ÁÀHà zÒÓĐÀÒPÑ –˽ÁÀHÃàÒxĈÀ¨ÒÑ . Changes ͨ€Ê@ÒHÀ1Ï –ŽƐÀWÆ1Ä3ÒPÑH . Sizes from 5 to Ü£Æ1ħţĐψÀHÆæñvÜxĐÏÀPƽú ܀ĐÏÀPÆ –ǽÁHÌÓÊ4ÂPÀ Changes font to the given . Sets the color of the text to Ñ£Á¨ÀHÁHÌ . ˆÁˆÒIÇÄ size. PPM and GIF im¢vÊÎÂg!Æ ages. Images support the generic methods ÊÎ Á WƬñô© à ¦„õèÃHÏ4ú ÃPÌ£ۄë ñ !PÌ"  PŨÛÎÒIǓú ÉPLjÃPÌ£ۄñIú Ñ1ÀPÁÓǽÆæñ‡ú . !¨Æ1Ä©¨Æ)¦PĉñIú Returns the string of text that is currently in the entry box.

’ The graphics module supplied with this book provides a number of classes ü ̈Åc43Ò€Ç that are useful for graphics programming. . . . which are increasingly darker shades of red. Various graphØÁˆÒIÇÄ ¤½Ò€ÇˆÆ ׈ÒÓ̽ÑHÀHÆ  ˆÆÑÓĈÂx§ Ç !¨ÀPÆ Ä WˆÂPÀ ØÁ¨À£c Ï !Á£Ç ical objects such as . and ü ̈ ü ̈"  c Å 43Ò€Ç Â Pc Å 43Ò€Ç ) Æ ¦HÄ may be drawn in a . a bright red. ’ An object is a computational entity that combines data and operations. Many colors come in various shades. The graphics library provides a way of automating certain coordinate transformations. . . The graphics module also provides a function for mixing your own colors nuÑ£Á¨ÀHÁHÌ c Ì !£Ënñ–̨ÆPÄ° õ !P̨ƐÆÓǙõ Ë3Àxɽƽú merically. Mutator methods change the value(s) of instance variables. etc. The function will return a string representing a color that is a mixture of the intensities of red. . . A is an object that represents a window on the screen for displaying graphics.~z´€¹ ×È¡ È‘× ùÌÆHà pPÉ Ì 3ÀPÆ Colors are indicated by strings. It is the class that determines what methods an object will have. Accessor methods return information about the instance variables of an object. Users may interact with a ÇÄPÌÏ by clicking the mouse or typing into an G box. An instance is created by calling a constructor method. An object’s data is stored in instance variables. should be available. ’ An object’s attributes are accessed via dot notation. while ºa”s—  ˜Ÿi„¤n…‚™g © ¦§›¥› ingIí  ‘       f  f  } ü s4tvuxw†y|{‡}3´PîÑ i•w%i•“H–§tql™wm• ª ‰Ê { ³ y|ˆ‰uxŠŒ‹ †}$uxwxt 6 ³ ˆ ÌË v6ٌvB“Hs  …  f This chapter introduced computer graphics and object-based programming. Generally computations with objects are performed by calling on an object’s methods. green and blue specÑ1Á¨ÀHÁHÌ c Ì !£Ënñz© Ô 9©9æõ¢Õ‰õ Õ3ú ified. These should be ints in the range 0–255. . Here is a summary of some of the important concepts. ’ Every object is an instance of some class. ’ An important consideration in graphical programming is the choice of an appropriate coordinate system. ¡!HÌÆPÆ£Ç †Ó Ñ ÏÂÓÇ . Thus is Ñ1ÁÀPÁ1Ì © Ì !1Ëoñ€ÖxÞPՄõlՄõªÖxÞPÕ3ú is a medium magenta. Most normal colors such as . ð̨ÆPÃÎÖ ùÌÆHÃÔ ð̨ÆPÃ¨Þ ðÌÆHéd such as . and its operations are called methods. . . . Objects know stuff and can do stuff.

Ñ1" Á Ï 8. A graphics window always has the title “Graphics Window. Aliasing occurs when two variables refer to the same object. ʈ§ Ï ÅÓŽ"  ˆÆnïÊ3g Á W¨Ææñ€Ö€Õ„õ–ÔPÕ3ú ʈ§ Ï ÅÓŽ"  ˆÆ moves to the point (10. Instance variables are used to store data inside an object. 4. A method that returns the value of an object’s instance variable is called a(n) a) mutator b) function c) constructor d) accessor 2.0). The method is provided to make a copy of a graphics object. Using dow. 5. Use of the method in the graphics library can help prevent these situations. 1.” 10. the upper-left corner of a graphics window has coordinates (0. A method that changes the state of an object is called a(n) a) stator b) mutator c) constructor d) changor 3. A single point on a graphics screen is called a pixel.20). 6. What graphics class would be best for drawing a square? Ågí£É3Â1Ì¨Æ Ø¨Á¨À1Ï©!¨ÁÓÇ ¤3ÒIÇ½Æ  ˆÆÑÓĈÂxǧ!¨ÀPÆ a) b) c) d) . 9. Traditionally. The statement 7.´P ~37HcŽŒ{I} ³Œ6 ˆ–{zˆ ’ The situation where two variables refer to the same object is called aliasÑHÀHÁ£ÇˆÆ ing. It can sometimes cause unexpected results. A function that creates a new instance of a class is called an accessor. 3. !P̈ÅÎҐѨܬïU¨Ï allows graphics to be drawn into a Python shell win- 2. The method in the graphics library used to get a mouse click is ƒ |§„3…‡†§ˆ}Iˆj‰cŠ§…Œ‹"} ÌƐÂHÃHöÁ£É4Ü£Æ . ºa”–“d™ egf„‚hgIƒ¬‡‘‚„‘ ~z´€¿ hjiCkmlniCoqpIrQi§sutqlnvxw%s y{zH|c})~Q©€cˆ‚3} 1.

Which of the following computes the horizontal distance between points †Ö 3Ô and ? ÂÓË4ܓH ñ “" Ö ¨3Ô½ú a) ½Ôop ï !¨ÆHÄ ‰ñ‡V ú ¨V†Ö†ïf!¨Æ1Ä æñIú b) ÂÓË4ܓf ñ †Ö­p ï !¨Æ1Ä „ñ‡§ ú ¨`½Ôof ï !ÆHÄ „ñIúPú c) ÂÓË4ܓH ñ “Ö­p ï !¨ÆHÄ ‰ñ‡§ ú ¨V½Ôof ï !ÆHÄ ‰ñIúPú d) gÐ g“ gÐ %Ð €“ gÐ 8.5)? ¤3ÒIǽÆæñzԉõlބõÔdoõî9ˆú a) ¤½Ò€ÇˆÆæññzԉõèÞ3ú†õ ë ñ d„ë õ 9½úPú b) ¤3ÒIǽƬñ†Ô‰° õ doõ ބî õ 9ˆú c) ¤3ÒIǽÆæñèØÁҀÇĉñ†Ôæõ–Þ3ú“õ ØÁˆÒIÇĉë ñ doÒ õ 9½úPú d) 6. A user interface organized around visual elements and user actions is called a(n) a) GUI b) application c) windower d) API Ñ£Á¨ÀHÁHÌ Ìc!£ËnñzՉõôÔ)9©9‰õ–Ô©9)9½ú ? 10. what it “knows”) and its methods (behaviors.~z´€â s4tvuxw†y|{‡}3´PîÑ ‰Ê { ³ y|ˆ‰uxŠŒ‹ †}$uxwxt 6 ³ ˆ ÌË ÛÎÒIÇ 4. . what it can “do”). What expression would create a line from (2. What command would be used to draw the graphics object ÛÎÒIÇ ? graphics window ÛÎÒIDŽïùÃḦÂÓÛoñ‡Ü‡Å3  ½Æ3ú Û3ҀÇhïzÜIňÁ1ۄñ‡ÜIŽ"  ˆÆ3ú a) b) ÜIŽ"  ˆÆnïùÃḦÂÓÛoñIú ÜIÅ3  ½ÆoïùÃPÌ£ۄñèÛÎÒIǓú c) d) ܇Å3Â"ˆÆ into the 7. What color is a) yellow b) cyan c) magenta  …Œ‚3‹|c‚8‚X…ŒŠm À d) orange 1.0) in the lower-left corner to (10. What kind of object can be used to get text input in a graphics window? g Æ ¦PÄ ÇÄPÌÏ ¢IÇ)É¨Ä ÆHÏ1˽Á¨Â£Ì¨Ã a) b) G c) d) 9. What command would set the coordinates of to go from (0.10) in the upper-right? ÛÎÒIDŽïzÜÓÆHĽÑ1ÁÁ1̨ýܓñ–بÁˆÒIÇĄñôՄõèÕ½ú“õ ØÁҀÇĉñ€Ö€Õ„õ‡Ö€Õ3úPú a) Û3ҀÇhïzÜ£Æ1Ä3Ñ£ÁÁH̐Ã3Ü@ññzՉõ–Õ½ú†õ ñ€Ö€Õ„õ‡Ö€Õ3úPú b) ÛÎÒIDŽïôÜ£ÆHĽÑ1ÁPÁH̨ýܓñôՄõîՄõ ÖxՉõfÖxÕ½ú c) ÛÎÒIDŽïzÜÓÆHĽÑ1ÁÁ1̨ýܓñ–بÁˆÒIÇĄñIÖxՉõ‡ÖIÕ3ú†õŽØÁˆÒIÇĉñzՄõèÕ3úPú d) 5. Pick an example of an interesting real-world object and describe it as a programming object by listing its data (attributes.3) to (4.

position. Be sure to mention such things as the size. ØÁҀǨĄñ€Ö€ÞÕ‰õ‡ÖxÞPÕ3ú (a) ÑUßÝ׈ÒxÌ3ÑHÀHÆæñèØÁˆÒIÇĉñzސՉ¡ õ dÕ3ú†õ–© Ô 9ˆú (b) щïzÜÓÆH) Ä D3ÒHÀPÀ¬ñ pË3ÀxÉ½Æ vú щïzÜÓÆHÄ Ä ÉÄÀÒIǽÆæñ ð̨ÆPà Œú (c) ÌÐßE ˆÆÑÓĈÂxǧ!¨ÀPÆæñèØÁҀÇĉñ†ÔHՄõôÔHÕ3ú“õ ØÁˆÒIÇĉñëd¨Õ‰õ¡dÕ3úú ̙ïzÜÓÆH) Ä D3ÒHÀPÀ¬ñŒÑ1Á¨ÀHÁHC Ì Ì1c Ì !£ËnñôՄõô) Ô 9©9¬õ‡ Ö 9PՈúú ̙ïzÜÓÆHg Ä 4ÎÒ£ÃHÄHÅoñzÞ3ú À€ßT¤3ÒIǽÆæñèØÁҀÇĉñ€Ö€ÕÕ„õvÖxÕPÕ3ú†õ بÁˆÒIÇĄñIÖxÕPՄõôÔHՐսúú ÀoïzÜÓÆHÄ Ä ÉÄÀÒIǽÆæñ ð̨ÆP© à d vú ÀoïzÜÓÆHÄ Ú ÌÌ¨Á1ۄñ è͈ÒÓÌ3ÜxÄ Œú Ä WÀ­ñ–ØÁҀǨĄñ39HՄõÒ9PÕ3ú“õ % % f … (d) %  }     (e) (f) (g) ØÁˆÒIÇĉñzøÕ‰õ‡Ö€ÕÕ3úPú ÜIŽÂ"ˆÆ€ß€ØÁ¨À£Ïc!Á£ÇnñèØÁҀÇĉñ39æõë9½ú“õ ØÁˆÒIÇĉñ€ÖxՉõ‡Ö€Õ3ú†õ ØÁҀǨĄñ39æõ‡Ö€Õ3ú†õ ØÁҀǨĄñ€Ö€Õ„õÒ9½úú ÜIÅ3  ½ÆoïzÜ£Æ1© Ä D½ÒHÀÀ­ñ èÁḦÂx§ Ç !Æ vú ÄÐßTÆg¦PĄñèØÁҀÇĉñ€Ö€ÕÕ„õvÖxÕPÕ3ú†õ‰8¢ˆÆÀÀPÁ£4ÁHÌÀHÃjž£ú ęïzÜÓÆH) Ä DˆÂÑ£Ææ" ñ xÑ1ÁÓÉ̽Ò1ÆH6 Ì £ú ęïzÜÓÆHC Ä ÅÒ ÆæñIÖxø3ú ęïzÜÓÆHC Ä Å1ĐÏÀPƬñ xÒxĈÂPÀҐ% Ñ £ú } !h 3. Describe what happens when the following interactive graphics program runs: ÍPÌÁ€Êa!PÌÂ"ÅÎҐѐÜU҇Êc½Á1̐ÄaY èÆPÍ ÊÎÂÒIÇnñIú­÷ Û3ҀÇàß ü ÌÂ"PÅc4ÎÒIÇnñ‡ú ܇Å3  ½Æ€ßÝ׈ÒxÌ3Ñ1ÀPÆæñèØÁҀÇĉñ39HՄõë9HÕ3ú“õîÔPÕ3ú ܇Å3  ½ÆnïôÜ£Æ1Ä Ä É¨ÄˆÀ¨Ò€Ç½Æ¬ñ †ÌÆP' à £ú ܇Å3  ½ÆnïôÜ£Æ1© Ä D3Ò1ÀÀ­ñ ŒÌ¨ÆP' à £ú ܇Å3  ½ÆnïpÃPÌ£ÛoñðÛÎÒIǓú ͐ÁHÌÿÒÝҀÇÐÌÂÓC Ç !¨ÆæñIÖxÕ½ú¬÷ ¡ßcÛÎÒIDŽp ï !¨ÆHÄHöˆÁÓÉ@ܣƬñIú ÑUßÿÜIŽ"  ˆÆnf ï !ÆHĨאƣǨÄÆ1̄ñIú à ¦WT ) ß hf ï !ÆHÄ æñI§ ú ¨¡Ñæf ï !ÆHÄ æñIú %Ð %Ð . and appearance of the various objects. Describe in your own words the object produced by each of the following operations from the graphics module. You may include a sketch if that helps.´P ~37HcŽŒ{I} ³Œ6 ˆ–{zˆ ~z´€é 2. Be as precise as you can.

” which is the same as the radius of the yellow circle. blue. (b) Have each successive click draw an additional square on the screen (rather than moving the existing one). Input: Radius of the circle and the -intercept of the line. 6. 6). 3. Alter the program from the last discussion question in the following ways: (a) Make it draw squares instead of circles. 3. apr) also are done in a graphical fashion using G 7. 5 or 2. Write a program that draws 5 dice on the screen depicting a straight (1.-10 to 10. 2. %– q .10. Write a program that draws a winter scene with a Christmas tree and a snowman. black and white. Each ring has the same “width. Modify the graphical future value program so that the input (principal and ÇĐÌPÏ objects. and wait for a final click before closing the window. 5. Write a program that draws such a target. Circle Intersection. 4. 4. 2. Write a program that draws some sort of face. An archery target consists of a central circle of yellow surrounded by concentric rings of red. 5. Draw a horizontal line across the window with the given y-intercept. Hint: Objects drawn later will appear on top of objects drawn earlier. Output: Draw a circle centered at ‚ƒw Òwg„ with the given radius in a window with coordinates running from -10. (c) Print a message on the window ”Click again to quit” after the loop. 4.~z¹7 s4tvuxw†y|{‡}3´PîÑ ÃHÏÝßThïf!ÆHÄ ‰ñIú§¨¡Ñæïf!ÆHÄ ‰ñIú ܇Å3"  ˆÆnïÊÎg Á W¨Ææñ–é¦oõðÃPÏÎú Û3ҀÇhïôÑHÀHÁ½ÜÓÆæñIú Ê4ÂÒIÇnñ‡ú ’”“fv••“H–B—$—˜l™wm•Sš#›§i•“¡œ©lnsi§s g“ ‰Ê { ³ y|ˆ‰uxŠŒ‹ †}$uxwxt 6 ³ ˆ g“ ÌË 1. Write a program that computes the intersection of a circle with a horizontal line and displays the information textually and graphically. 3.

This program allows the user to draw a line segment and then displays some graphical and textual information about the line segment. Print the length and the slope of the line. Same as previous problem. Formulas: – µ û ˜˜ 9 ji “ ™w•k ” – “ ø º º º û ëõ 9. Five-click house. and ù are the lengths of ú)ö ú ‚ †üúC„X‚ † ž„X‚ †üùu„ where ú % º '& '( the sides and º µ 9  “ “ “ ¯( “ “ r yr `q§(mq 11. Triangle Information. 9 – ˜˜ – ˜ ˜  – – “ µ †‰“ ý µ † ¶ ¶ º “ “ µ  µ This program displays information about a rectangle drawn by the user. . Formulas: õ ˜ 9 9 ™ l k j i 9 9 ™ 9 9 ji w™ k l™ k ˜ ™wk úgö ú ö÷$# ö º ‚ƒû ø „X‚"! ÷ „ º ¡C‚ƒû ø  ! ÷ „ 10. Line Segment Information. Print out the “ values of the points of intersection. Output: Draw the midpoint of the segment in cyan. see length from line problem. Print the perimeter and area of the rectangle. Formula: “ º 5 ö µ † 8.´P ~37HcŽŒ{I} ³Œ6 ˆ–{zˆ ~z¹H~ Draw the two points of intersection in red. Input: 2 mouse clicks for the opposite corners of a rectangle. Draw the line. Output: Draw the rectangle. Input: 2 mouse clicks for the end points of the line segment. Rectangle Information. Formulas: For perimeter. but with 3 clicks for the verticies of a triangle.

The edges of the roof will extend from the point at the peak to the corners of the top edge of the house frame. Write a program to plot a horizontal bar chart of student exam scores. 5 2 3 4 1 12. The fourth click will indicate the center of a square window. The first line of the file contains the count of the number of students in the file. Bonus: label the bars at the left end with the student name.~z¹€r s4tvuxw†y|{‡}3´PîÑ ‰Ê { ³ y|ˆ‰uxŠŒ‹ †}$uxwxt 6 ³ ˆ ÌË You are to write a program that allows the user to draw a simple house using five mouse-clicks. The door should have a total width that is ¶ of the width of the house frame. The sides of the door should ¾ extend from the corners of the top down to the bottom of the frame. and each subsequent line contains a student’s last name followed by a score in the range 0 to 100. The first two clicks will be the opposite corners of the rectangular frame of the house. Computewell Dibblebit Jones Smith . Your program should get input from a file. The third click will indicate the center of the top edge of a rectangular door. Your program should draw a horizontal rectangle for each student where the length of the bar represents the student’s score. The window is half as wide as the door. The bars should all line up on their left-hand edges. The last click will indicate the peak of the roof. Hint: use the number of students to determine the size of the window and its coordinates.

For example.´P ~37HcŽŒ{I} ³Œ6 ˆ–{zˆ ~z¹€” 13. Your program must count the number of occurrences of each score and then draw a vertical bar chart with a bar for each possible score (0–10) with a height corresponding to the count of that score. Hint: use a list that stores the count for each possible score. if 15 students got an 8. Your program should read data from a file. 0 1 2 3 4 5 6 7 8 9 10 . then the height of the bar for 8 should be 15. Write a program to draw a quiz score histogram. Each line of the file contains a number in the range 0–10.


Here is the program as we left it: óWÍ1ɨ© Ä W© À Ì!PÌ"  Å½Ôob ï Ï ÍP̨Áxa Ê !Ḧ"  PÅ4ÒPѨÜUÒvC Ê ˆÁH̐@ Ä Y gÐ ® q65 .g. ’ To write programs that use functions to reduce code duplication and increase program modularity. ’ To be able to define new functions in Python.g. ÊÎÂ1Ä1ńïzÜíPÌPÄ ÜxĐ̽ҀÇC!ŸïzÜu3À¨ÒÓÄ dard libraries (e. We have also been using pre-written functions and methods inÂÓË4Ü ). ’ To understand the details of function calls and parameter passing in Python... and object methods from the !PÌ"  PÅ4ÒÑÜ ÊˆÏØÁҀǨęf ï !ÆHÄ ‰ñIú module (e.g. usually Ê4ÂÒIÇ called . ꫔–“ —Y˜™‚ 𕦕eŸƒ†…ˆ‡™£e ™hìV𕦕e™ƒ“…ˆ‡™£e™‘ The programs that we have written so far comprise a single function. This program makes use of the library to draw a bar chart showing the growth of an investment. we looked at a graphic solution to the future value !Ḧ  Å4ÒPÑ¨Ü problem. In the previous chapter. ). Functions are an important tool for building sophisticated programs.. functions from the Python stancluding built-in Python functions (e. ). . This chapter covers the whys and hows of designing your own functions to make your programs easier to write and understand.QSRUTWVYXa`cb0) 1 32 ¦ ¥@¦ v 4 g ¦ Æ Ð¨§¥¥§¦m x€y31‚„ƒ†…ˆ‡‰„‚„‘ ’ To understand why programmers divide programs up into sets of cooperating functions.

~z¹€¹ s@tŒuxw†y|{‡}½¹Pæé4{ÒêŠ 6 ŠŒ Ó ó …xŠ ³ y 6 ‚1ŠŒˆ èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ó ¢IǨĐÌÁHÃ1ÉÎÑÓÄ3Ò£Á£Ç a ̽ҀÇ Ä XHÅÎÒ¨ Ü ¨ÌÁ)!ḦÂIÊ¥3ÀHÁHÄ3ÜYÄHŽÆT!HÌÁ£Û¨ÄHÅÐÁPÍÐÂÿÖxÕ©¨1ϨƨÂ1ÌàҀÇCW¨Æ½Ü€Ä£ÊÎÆÓÇğïq ̽ҀÇ4ÑPҽÀÈßÿÒIÇ©É¨Ä„ñ" G ó ü Æ1ÄEÌ3ÒIÇ4ÑPÒ3ÂPÀ€ÂÓÇÃàҀǨÄÆ1Ìƽ܀Ā̈£ÄÆ Ç¨ÄÆ1ÌUÄ1ŽÆàҀÇÎÒÓĽÒHÀ§Ì3ÒIÇ4ÑPÒ3ÂPÀo÷ü£ú G Â"¨ÌÝߡҀ© Ç PÉĉñ  ÇĨÆHÌcÄ1ŽÆÝÂxǐǐɽÀ¨Ò ¨ÆHÃÐÒIÇÄÆ1ÌƈÜxÄcÌÂ1ĨÆn ÷ £ú !h ó ×H̨ƨÂ1ĨÆWÂT!PÌÂ"ÅÎҐѐܪÛÎÒILjÐÁ1ÛWÛÎÒxÄHÅ¡ÀPÂÓˈƨÀˆÜYÁ£ÇÿÀPÆHÍPÄÐÆHé!¨Æ Ý ÛÎÒIÇàß ü ̈ũ4ÎҀÇoñ ¢IÇCW¨Æ½Ü€Ä£ÊÎÆÓÇÄ ü ̨Á1ېÄHÅà×ÓÅ3Â1ÌPÄ#3õ¢Þ¨ÔHՄõ Ôd¨Õ3ú ÛÎÒIDŽïzÜÓÆHÄ ˆÂ Ñ ÎC!HÌÁ£ÉPLjÃæñ †ÛHÅ4ÒxÄ• Æ £ú ÛÎÒIDŽïzÜÓÆHĨאÁÁ1̨ýܓ3 ñ ¨½Ö­ïùc þ 9‰Ò õ ¨ÔHՐÕæõ ֐֭H ï 9‰õfր) Õ dÕÕ3ú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“õ Õ3ú†õ ÕoïðÕ vú­ïùÃḦ£ۄñèÛ3ҀǓú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“õl© Ô 9PÕPÕ3ú“õ ÔoH ï 9 Œú¬ïpÃP̈ÂÓÛoñðÛÎҀÇ@ú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“° õ 9PՐÕPÕ3ú“õ î9oïùÕ Œú¬ïpÃP̈ÂÓÛoñðÛÎҀÇ@ú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“õ c þ 9PÕPÕ3ú“õ þnH ï 9 Î Œú¬ïpÃP̈ÂÓÛoñðÛÎҀÇ@ú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“õÖxՐÕPՐսú†õ vÖxÕnïùÕ vú¬ïpÃPÌ£ÛoñðÛÎÒIǓú € ó ¨Ì£ۀË3£ÌÝͨÁ1ÌÿҀÇ4ÒxÄ3Ò1Àè¨Ì3ҀÇÎѐÒq3À Ë Â£ÌÝßE ˆÆˆÑxĈÂxǧ!ÀHÆæñèØÁˆÒIÇĉñzՄõîÕ½ú†õ¢ØÁҀǨĄñ€Ö@õI̽ҀÇÎѐҽÀˆúú 3 Ë3£̙ïzÜÓÆH) Ä D3ÒHÀPÀ¬" ñ ž!P̨ƐÆÓ Ç £ú Ë3£̙ïzÜÓÆHg Ä 4ÎÒ£ÃHÄHÅoñ†Ô½ú Ë3£̙ïùÃḦÂÓÛoñèÛ3ҀÇ@ú ž ž ó  # !À !À #  ##  3À  3À ¨Ì£ۡ Ë3£ÌÝͨÁ1ÌÐƨÂÑIÅ»ÜIÉPË@Ü£Ægí1ɈƣÇÄUÏƐÂ1Ì Í¨Á1ÌWÏƨ£̡ҀÇàÌÂÓǧ!ÆæñI֓õÖPÖPú­÷ Ì3ÒIÇ4ÑP Ò 3ÂPÀÈE ß ̽ҀÇÎѐ Ò ½ÂT À Y¥ñ€Ö áàÂ"¨Ì4ú Ë3Â1ÌÝE ß  ƈÑxĈÂÓC Ç !ÀHÆæñ–بÁˆÒIÇĄñèÏƐÂ1Ìnõ Õ½ú†õ¢Ø¨ÁˆÒ€Ç¨Ä„ñèÏƨ£̨áÎ֓õ   Ì3ÒIÇ4ÑPÒ3ÂPÀ½úPú Ë3Â1̟ïzÜÓÆH© Ä D½ÒHÀPÀ¬ñ X!P̨Ɛƣx Ç £ú Ë3Â1̟ïzÜÓÆH) Ä 43Ò£ÃHÄHÅnñzÔ½ú Ë3Â1̟ïùÃḦ£ۄñèÛ3ҀǓú ̈ÂÓm Û ÌÒI© Ç PÉĄ" ñ ŒØPÌƽÜPÜ ÛÎÒIDŽïôÑ1ÀPÁˆÜ£Ææñ‡ú FG ǨÄÆ1Ì ( ĨÁTí1É4Òxęïu£ú This is certainly a workable program. The initial bar is drawn just before the loop. Notice that this program draws bars in two different places. and the subsequent . but there is a nagging issue of program style that really should be addressed.

one issue is having to write the code twice. let’s take look at what functions have to offer. Having similar code like this in two places has some drawbacks. You might want to fire up Python and try some of this out yourself. we say that the definition is called or invoked. A more subtle problem is that the code has to be maintained in two different places. we would have to make sure these changes occur in both places. Before fixing up the future value program. Obviously. When a function is subsequently used in a program. Functions can be used to reduce code duplication and to make programs more understandable and easier to maintain. ¨Ì3Ò€Ç¨Ä A simple approach to this problem is to use four statements. Should we decide to change the color or other facets of the bars. (©()( èÆHÍ Ê4ÂÒIÇnñ‡ú¬÷ Ì3ÒIÇA Ä 8¢½  ©ÏÈË4ÒÓÌPÄHÅÃÂ1ÏcÄÁcÏÁÓÉ ž Ì3ÒIÇA Ä 8¢½  ©ÏÈË4ÒÓÌPÄHÅÃÂ1ÏcÄÁcÏÁÓÉ ž Ì3ÒIÇA Ä 8¢½  ©ÏÈË4ÒÓÌPÄHÅÃÂ1Ïoõ¢Ã¨ÆÂ1T Ì DPÌÆHßq ï  . The instructions can then be executed at any point in the program by referring to the function name. The part of the program that creates a function is called a function definition. Suppose you want to write a program that prints out the lyrics to the “Happy Birthday” song. Let’s take a concrete example. The basic idea of a function is that we write a sequence of statements and give that sequence a name. The standard lyrics look like this.¹H rHcóӅxŠ ³ y 6 ‚1ŠŒˆ r” ©u Š†å ‚Ó}ƒnu± ± ç ~z¹€¿ bars are drawn inside of the loop. ¢½  ©¨ÏUË4Òx̐ÄHÅãπÄÁcϨÁ£É  ¢½  ©¨ÏUË4Òx̐ÄHÅãπÄÁcϨÁ£É  ¢½  ©¨ÏUË4Òx̐ÄHÅãÏnõ¢ÃÆ¨Â1Ì Ò€Ç4Ü£Æ1̐§ Ä ¨xÇ3ÂIÊÎÆ ( ï F ¢½  ©¨ÏUË4Òx̐ÄHÅãπÄÁcϨÁ£É  We’re going to play with this example in the interactive Python environment. A single function definition may be called at many different points of a program. Failing to keep related parts of the code in sync is a common problem in program maintenance. ꫔–• 𕦕eŸƒ†…ˆ‡™£eŸ‘ üt–en쇙„g£› —– i„j j í You can think of a function as a subprogram—a small program inside of a program. Here’s an interactive session that creates a program for singing “Happy Birthday” to Fred.

Let’s try . Let’s introduce a function that prints the lyrics of the first.~z¹€â s@tŒuxw†y|{‡}½¹Pæé4{ÒêŠ 6 ŠŒ Ó ó …xŠ ³ y 6 ‚1ŠŒˆ Ì3ÒIÇÄA8¢½Â©ÏÈË4ÒÓÌPÄHÅÃÂ1ÏcÄÁcÏÁÓÉ ž We can then run this program to get our lyrics. Ç !)DPÌÆPÃæñIú­÷ (©()( èÆHÍÿÜPҀC Å3"  )ωñIú Å3"  )ωñIú Ì3ÒIÇA Ä 8¢½  ©ÏÈË4ÒÓÌPÄHÅÃÂ1Ïoõ¢Ã¨ÆÂ1T Ì DPÌÆHßq ï  Å3"  )ωñIú This version required much less typing. Ç !)DPÌÆHÉñIú (©()( ÜPÒI§ ¢½  ©¨ÏUË4Òx̐ÄHÅãπÄÁcϨÁ£É  ¢½  ©¨ÏUË4Òx̐ÄHÅãπÄÁcϨÁ£É  ¢½  ©¨ÏUË4Òx̐ÄHÅãÏnõ¢ÃÆ¨Â1E Ì DÌÆHÃŸï ¢½  ©¨ÏUË4Òx̐ÄHÅãπÄÁcϨÁ£É  Å3©¨Ï command. For such a simple program. there is some duplicated code in this program. Here is an example of what it Å3"  )Ï Invoking the command causes Python to print a line of the song. (©()( Ê4¨ҀÇnñ‡ú ¢½  ©¨ÏUË4Òx̐ÄHÅãπÄÁcϨÁ£É  ¢½  ©¨ÏUË4Òx̐ÄHÅãπÄÁcϨÁ£É  ¢½  ©¨ÏUË4Òx̐ÄHÅãÏnõ¢ÃÆ¨Â1E Ì DÌÆHÃŸï ¢½  ©¨ÏUË4Òx̐ÄHÅãπÄÁcϨÁ£É  Obviously. second. and fourth lines. that’s not a big deal. thanks to the printing the lyrics for Fred just to make sure it works. Now we can redo the verse for Fred using happy. Let’s call our new version ÜPÒI§ Ç !gDÌÆHà .  )ωñIú¬÷ (©()( èÆHÍUÅ3" Ì3ÒIÇA Ä 8¢½  ©ÏÈË4ÒÓÌPÄHÅÃÂ1ÏcÄÁcÏÁÓÉ ž ŽÂ")Ï We have defined a new function called does:  ©ωñIú (©()( Å3 ¢½  ©¨ÏUË4Òx̐ÄHÅãπÄÁcϨÁ£É  . but even here it’s a bit annoying to keep retyping the same line.

Ç !)¤1É4ÑÓωñIú­÷ (©()( èÆHÍÿÜPҀC Å3"  )ωñIú Å3"  )ωñIú Ì3ÒIÇA Ä 8¢½  ©ÏÈË4ÒÓÌPÄHÅÃÂ1Ïoõ¢Ã¨ÆÂ1T Ì ¤1É4Ñxϙq ï  Å3"  )ωñIú Ê4ÂÒIÇ Now we can write a program that sings to both Fred and Lucy. Can’t G we do something about the proliferation of verses? ÜHҀ§ Ç !gDÌ¨ÆPà ÜHҀ§ Ç !g¤HÉÎÑÓÏ Notice that the only difference between and is the name Ì3ÒIÇÄ at the end of the third statement. and we want to sing a verse for Fred followed by a verse for Lucy. And here’s the final product in action: (©()( Ê4¨ҀÇnñ‡ú ¢½  ©¨ÏUË4Òx̐ÄHÅãπÄÁcϨÁ£É  ¢½  ©¨ÏUË4Òx̐ÄHÅãπÄÁcϨÁ£É  ¢½  ©¨ÏUË4Òx̐ÄHÅãÏnõ¢ÃÆ¨Â1E Ì DÌÆHÃŸï ¢½  ©¨ÏUË4Òx̐ÄHÅãπÄÁcϨÁ£É  ¢½Â©¨ÏUË4Òx̐ÄHÅãπÄÁcϨÁ£É  ¢½Â©¨ÏUË4Òx̐ÄHÅãπÄÁcϨÁ£É  ¢½Â©¨ÏUË4Òx̐ÄHÅãπÄÁcϨÁ£É  ¢½Â©¨ÏUË4Òx̐ÄHÅãÏnõ¢ÃÆ¨Â1ÌE¤HÉ4Ñxϙï Well now. Following this approach. and we’ve removed some of the Å3©¨Ï duplication by defining the function.¹H rHcóӅxŠ ³ y 6 ‚1ŠŒˆ r” ©u Š†å ‚Ó}ƒnu± ± ç ~z¹€é So far. something still doesn’t feel ÜPҀÇC!)DPÌÆPà ÜHҀÇC!)¤HÉÎÑÓÏ quite right. that certainly seems to work. We can collapse these two functions together by ÜHҀ§ Ç ! using a parameter. that are almost identical. we can prepare one for Lucy as well. and . The verses are exactly the same except for this one changing part. Let’s write a generic function called . We’ve already got the verse for Fred. Now suppose that it’s also Lucy’s birthday. adding a verse for Elmer would have us ÜPҀC Ç ! À€ÊÎÆ1Ì create a function that looks just like those for Fred and Lucy. . (©()( èÆHÍ Ê4ÂÒIÇnñ‡ú¬÷ ÜPҀC Ç !)DPÌÆPÃæñIú Ì3ÒIÇÄ ÜPҀC Ç !)¤1É4ÑÓωñIú Ì3ÒIÇÄ The bare between the two function calls puts a space between the verses in our output. However. We have two functions. so good.

Here is the complete program as a module file. We just need to supply the name as a parameter when we invoke the function.~z¿7 (©()( s@tŒuxw†y|{‡}½¹Pæé4{ÒêŠ 6 ŠŒ Ó ó …xŠ ³ y 6 ‚1ŠŒˆ èÆHÍÿÜPҀÇC!‰ñf½ÆHÌ3Ü£ÁÓǓú¬÷ Å3"  )ωñIú Å3"  )ωñIú Ì3ÒIÇA Ä 8¢½  ©Ï 3ÒÓÌPÄHÅÃÂ1Ïoõ¢Ã¨ÆÂ1Ì6ÎõIˆÆHÌÎÜÓÁ£ÇÐáA4ïq Å3"  )ωñIú ž ½Æ1ÌÎÜÓÁ£Ç This function makes use of a parameter named . We can use the function to print a verse for either Fred or Lucy. A parameter is a variable ÜHҀǧ! that is initialized when the function is called. óUÅ3  ©¨Ï™U ï ¨Ï èÆHÍUÅ3©ωñIú­÷ ̽ҀÇ Ä 3¢½Â©¨Ï # 3Òx̐ÄHÅãπÄÁcϨÁ£É ž èÆHÍÿÜPÒIǧ!‰ñf½Æ1ÌÎÜ£ÁÓǓú­÷ . èÆHÍ Ê4ÂÒIÇnñ‡ú¬÷ ÜPҀC Ç !‰" ñ XDÌ¨ÆP' à £ú Ì3ÒIÇÄ ÜPҀC Ç !‰" ñ X¤HÉÎÑÓ6 Ï £ú Ì3ÒIÇÄ ÜPҀC Ç !‰" ñ  ÀIÊÎÆ1# Ì £ú G It doesn’t get much easier than that. Ç !‰" ñ XDPÌÆP' à £ú (©()( ÜPÒI§ ¢½  ©¨ÏUË4Òx̐ÄHÅãπÄÁcϨÁ£É  ¢½  ©¨ÏUË4Òx̐ÄHÅãπÄÁcϨÁ£É  ¢½  ©¨Ï 3Òx̐ÄHÅãÏnõ¢ÃÆ¨Â1E Ì DÌÆHÃŸï ¢½  ©¨ÏUË4Òx̐ÄHÅãπÄÁcϨÁ£É  # # ¢½Â©¨ÏUË4Òx̐ÄHÅãπÄÁcϨÁ£É  ¢½Â©¨ÏUË4Òx̐ÄHÅãπÄÁcϨÁ£É  ¢½Â©¨Ï (©()( ÜPÒIǧ!‰ñ"X¤1É4ÑÓÏ6£ú 3Òx̐ÄHÅãÏnõ¢ÃÆ¨Â1ÌE¤HÉ4ÑxÏ™ï ¢½Â©¨ÏUË4Òx̐ÄHÅãπÄÁcϨÁ£É  (©()( Let’s finish with a program that sings to all three of our birthday people.

Specifically. Remember. Ë3£ÌÝßE ˆÆÑÓĈÂxǧ!¨ÀPÆæñèØÁҀÇĉñ–ϨƨÂ1Ìoõ Õ3ú“õ¢ØÁˆÒIÇĉñ–ÏƐÂ1̐á4֓õ   ̽ҀÇÎѐҽÀˆúú Ë3£̙ïôÜ£ÆH) Ä D3Ò1ÀÀ¬" ñ ž!HÌƐÆÓ Ç Óú Ë3£̙ïôÜ£ÆHg Ä 4ÎÒÓÃPÄHÅoñ†Ôˆú Ë3£̙ïpÃP̈ÂÓÛoñðÛÎҀÇ@ú Let’s try to combine these two into a single function that draws a bar on the screen. Here’s the function definition: . In order to draw the bar. and what window the bar will be drawn in. we need some information. the problem is that bars of the graph are printed at two different places in the program.¹P ”PcóӅzyè…x}‘{jô@u±7…Œ{n’ 6 yèt•u2óӅxŠ ³ y 6 ‚1Š Å3©ωñIú Å3  ©ωñIú ̽ҀÇ Ä 3¢½Â©¨ÏUË4Òx̐ÄHÅãÏnõ¢ÃÆ¨Â1Ì6ÎõIˆÆHÌ3Ü£Á£ÇÝáA@ïq Å3  ©ωñIú èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ÜPÒI§ Ç !‰" ñ XDPÌÆPÃ'£ú ̽ҀÇÄ ÜPÒI§ Ç !‰" ñ X¤1É4ÑÓ6 Ï £ú ̽ҀÇÄ ÜPÒI§ Ç !‰" ñ  À€ÊÎÆ1# Ì Óú G ð•¦o…Φ•gI‚&ñ ~z¿H~ ꫔– ihj|¦™‚ œ ‡ …3˜ëi 𕦕e™ƒ“…ˆ‡™£e Now that you’ve seen how defining functions can help solve the code duplication problem. These three values will be supplied as parameters for the function. The code just before the loop looks like this: ó ¨Ì£ۀ˽Â1ÌÝͨÁ1ÌÿҀÇÎÒÓÄ3Ò1è À ¨Ì3ÒIÇ4ѐÒq3ÂPÀ Ë3£ÌÝßE ˆÆÑÓĈÂxǧ!¨ÀPÆæñèØÁҀÇĉñzՉõ Õ½ú†õ¢Ø¨ÁˆÒ€Ç¨Ä„ñI֓õI¨Ì3ҀÇÎѐÒq3Àˆúú Ë3£̙ïôÜ£ÆH) Ä D3Ò1ÀÀ¬" ñ ž!HÌƐÆÓ Ç Óú Ë3£̙ïôÜ£ÆHg Ä 4ÎÒÓÃPÄHÅoñ†Ôˆú Ë3£̙ïpÃP̈ÂÓÛoñðÛÎҀÇ@ú ž And the code inside of the loop is as follows. let’s return to the future value graph. we need to know what year the bar will be for. how tall the bar will be.

000 by invoking ÃPÌÂ£Û ˆÂ1̉ñèÛ3ҀǙõ ՄõÔHՐՐսú g % ÃHÌˆÂ£Û ˆÂ£Ì Incorporating the function. we just need to supply values for the three parameters.~z¿€r s@tŒuxw†y|{‡}½¹Pæé4{ÒêŠ 6 ŠŒ Ó ó …xŠ ³ y 6 ‚1ŠŒˆ èÆHÍWÃPÌÂ£Û Â1̉ñèÛÎÒILjÐÁ1۟õ ÏƐÂ1ÌoõîŽÆÒ !1ŨÄ4ú­÷ ó ¨Ì£ۡ Ë3£ÌÿҀÇÐÛÎÒILjÐÁ1ÛÝ͐ÁHÌ !½ÒWÆÓÇÝÏƐÂ1̀ÛÎÒxÄHÅS!ˆÒ"W¨Æ£ÇWŽÆÒ !£ÅÄ Ë3£ÌÝE ß  ˆÆˆÑxĈÂxǧ!ÀHÆæñèØÁˆÒIÇĉñ–ÏƐÂ1Ìoõ Õ3ú†õ¢Ø¨ÁˆÒIÇĄñèÏƐÂ1̨áÎ֓õ ŽÆÒ !1ŨÄ4úPú Ë3£̙ïzÜÓÆH) Ä D3ÒHÀPÀ¬" ñ ž!P̨ƐÆÓ Ç £ú Ë3£̙ïzÜÓÆHg Ä 4ÎÒ£ÃHÄHÅoñ†Ô½ú Ë3£̙ïùÃḦÂÓÛoñèÛ3ҀÇèÁ1Û4ú ž % To use this function. we can draw a bar for year 0 and a principal of ÃPÌÂ£Û Â1Ì like this: $2. For ü ̈ũ4ÎÒ€Ç ÛÎÒ€Ç example. if is a . here is the latest version of our future value program: óWÍ1ɨ© Ä W© À Ì!PÌ"  ÅˆÞnïbÏ ÍP̨Áxa Ê !Ḧ"  PÅ4ÒPѨÜUÒvC Ê ˆÁH̐Ä@Y èÆHÍWÃPÌÂ£Û Â1̉ñèÛÎÒILjÐÁ1۟õ ÏƐÂ1ÌoõîŽÆÒ !1ŨÄ4ú­÷ ó ¨Ì£ۡ Ë3£ÌÿҀÇÐÛÎÒILjÐÁ1Û Ü€ÄˆÂ1ÌPÄ3ÒIǧ!W£ÄWÏƐÂ1̀ÛÎÒxÄHÅ@!ˆÒ"WÆÓǀŽÆÒ £ ! ÅÄ Ë3£ÌÝE ß  ˆÆˆÑxĈÂxǧ!ÀHÆæñèØÁˆÒIÇĉñ–ÏƐÂ1Ìoõ Õ3ú†õ¢Ø¨ÁˆÒIÇĄñèÏƐÂ1̨áÎ֓õ ŽÆÒ !1ŨÄ4úPú Ë3£̙ïzÜÓÆH) Ä D3ÒHÀPÀ¬" ñ ž!P̨ƐÆÓ Ç £ú Ë3£̙ïzÜÓÆHg Ä 4ÎÒ£ÃHÄHÅoñ†Ô½ú Ë3£̙ïùÃḦÂÓÛoñèÛ3ҀÇèÁ1Û4ú èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ó ¢IǨĐÌÁHÃ1ÉÎÑÓÄ3Ò£Á£Ç a ̽ҀÇ Ä XHÅÎÒ¨ Ü ¨ÌÁ)!ḦÂIÊ¥3ÀHÁHÄ3ÜYÄHŽÆT!HÌÁ£Û¨ÄHÅÐÁPÍÐÂÿÖxÕ©¨1ϨƨÂ1ÌàҀÇCW¨Æ½Ü€Ä£ÊÎÆÓÇğïq ó ü Æ1ÄEÌ3ÒIÇ4ÑPÒ3ÂPÀ€ÂÓÇÃàҀǨÄÆ1Ìƽ܀Ā̈£ÄÆ  ̽ҀÇ4ÑPҽÀÈßÿÒIÇ©É¨Ä„ñ" ǨÄÆ1ÌUÄ1ŽÆàҀÇÎÒÓĽÒHÀ§Ì3ÒIÇ4ÑPÒ3ÂPÀo÷ü£ú  G  ¨ÌÝߡҀ© " Ç PÉĉñ  ÇĨÆHÌcÄ1ŽÆÝÂxǐǐɽÀ¨Ò ¨ÆHÃÐÒIÇÄÆ1ÌƈÜxÄcÌÂ1ĨÆn÷£ú G g ž % !h óÝ×H̨ƨÂ1ĨÆWÂT!PÌÂ"ÅÎҐѐܪÛÎÒILjÐÁ1ÛWÛÎÒxÄHÅ¡ÀPÂÓˈƨÀˆÜYÁ£ÇÿÀPÆHÍPÄÐÆHé!¨Æ ÛÎÒIÇàß ü ̈ũ4ÎҀÇoñ ¢IÇCW¨Æ½Ü€Ä£ÊÎÆÓÇÄ ü ̨Á1ېÄHÅà×ÓÅ3Â1ÌPÄ#3õ¢Þ¨ÔHՄõ Ôd¨Õ3ú ÛÎÒIDŽïzÜÓÆHÄ ˆÂÑÎC!HÌÁ£ÉPLjÃæñ †ÛHÅ4ÒxÄƕ£ú ÛÎÒIDŽïzÜÓÆHĨאÁÁ1̨ýܓ3 ñ ¨½Ö­ïùc þ 9‰Ò õ ¨ÔHՐÕæõ ֐֭H ï 9‰õfր) Õ dÕÕ3ú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“õ Õ3ú†õ ÕoïðÕ vú­ïùÃḦ£ۄñèÛ3ҀǓú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“õl© Ô 9PÕPÕ3ú“õ ÔoH ï 9 Œú¬ïpÃP̈ÂÓÛoñðÛÎҀÇ@ú €  # !À !À .

it doesn’t seem to change. However. % g % g . Remember each function is its own little subprogram. Obviously. Don’t worry yet if you don’t understand every detail of this example. it is not directly accessible in . You still have some things to learn about functions. the definition of . Û3ҀÇèÁ1Û a parameter has to do with the scope of variThe reason for making ables in function definitions. the year for which a bar is being drawn and the height of the bar are ÛÎÒILjèÁ£Û the changeable parts in the drawing of a bar. The only way for a function to see a variable from another function is for that ü ̈"  Pc Å 43Ò€Ç ÛÎÒIÇ variable to be passed as a parameter.¹H ¯ cóӅxŠ ³ y 6 ‚1ŠŒˆæuxŠŒ‹ŽHuI}"uxƒo{–y|{I}‘ˆ3´@ã‰tŒ{ 4 é {ôy–u 6 ± ˆ Æg¦PĄñèØÁҀÇĉñ3¨½Ö“õ°9PՐÕPÕ3ú“õ Æg¦PĄñèØÁҀÇĉñ3¨½Ö“õ ~z¿€” þ 9PÕPÕ3ú“õ c Æg¦PĄñèØÁҀÇĉñ3¨½Ö“õÖxՐÕPՐսú†õ ÃPÌÂ£Û Â1̉ñèÛÎÒIǙõ Մõ°̽ҀÇÎѐҽÀˆú ͨÁ1ÌWÏƨ£̡ҀÇàÌÂÓǧ!ÆæñI֓õÖPÖPú­÷ Ì3ÒIÇ4ÑP Ò 3ÂPÀÈE ß ̽ҀÇÎѐ Ò ½ÂT À Y¥ñ€Ö áàÂ"¨Ì4ú ÃP̈ÂÓÛ Â1̄ñðÛÎÒIǙõ Ïƨ£Ìn5 õ ¨Ì3ҀÇÎѐq Ò 3Àˆú % #  ##  3À  3À î9oïùÕ Œú¬ïpÃP̈ÂÓÛoñðÛÎҀÇ@ú þ ïH9 Î Œú¬ïpÃP̈ÂÓÛoñðÛÎҀÇ@ú n vÖxÕnïùÕ vú¬ïpÃPÌ£ÛoñðÛÎÒIǓú % Ì ÂÓÛmÌÒIÇ©PÉĄñ"ŒØPÌƽÜPÜ ˆ ÛÎÒIDŽïôÑ1ÀPÁˆÜ£Ææñ‡ú Ê4¨ҀÇoñIú FG ǨÄÆ1Ì ( ĨÁTí1É4Òxęïu£ú ÃḦÂÓÛ ˆÂ£Ì You can see how has eliminated the duplicated code. To see how this happens. Scope refers to the places in a program where a given variable may be referenced. the ÛÎÒILjÐÁ1Û ÃP̈ÂÓÛ Â1Ì Û3Ò€Ç ÊÎÂÒ€Ç parameter in gets assigned the value of from when ÃPÌÂ£Û ˆÂ1Ì is called. Since the (in the variable ) Ê4Â¨Ò€Ç ÃPÌÂ£Û ˆÂ1Ì is created inside of . The variables used inside of one function are local to that function. even if they happen to have the same name as variables that appear inside of another function. But why is also a parameter to this function? After all. we need to take a more detailed look at the function invocation process. Should we wish to change the appearance of the bars in the graph. we will be drawing all of the bars in the same window. % g ꫔|µ 𕦕eŸƒ†…ˆ‡™£eŸ‘Ýi•eŸ· —ŽiogIi•› ‚æ…‚™gI‘'²Y—Y˜™‚ «ª‚æ…¨i™‡–j ‘ ÃP̈ÂÓÛ Â1Ì You may be wondering about the choice of parameters for the function. we only need to change ÃHÌˆÂ£Û ˆÂ£Ì the code in one spot.

and is a (possibly empty) list of variable names (also identifiers). A function is called by using its name followed by a list of actual parameters or arguments. let’s trace through the singing of ÊÎÂÒ€Ç two verses. èÆHÍ F F ǽ€ÊÎÆ ËˆÁPÃPÏ ( ( ñ ͨÁ1Ì£ÊΐÀ©¨3£̈€Ê3ÆHĨÆHÌ½Ü F ( ú­÷ Ç3€Ê3Æ ÍÁHÌ£ÊΐÀ)¨"3£̈ÂIÊÎÆHĨÆHÌ3Ü The of the function must be an identifier. . ÜPҀÇC! At this point. Returning to the Happy Birthday example. execution of is temporarily suspended. 2. 4. The formal parameters of the function get assigned the values supplied by the actual parameters in the call. are only accessible in the of the function.~z¿ ¯ s@tŒuxw†y|{‡}½¹Pæé4{ÒêŠ 6 ŠŒ Ó ó …xŠ ³ y 6 ‚1ŠŒˆ A function definition looks like this. The formal parameter is assigned the value of the actual. Here is part of the body from : Ì½Ò€Ç¨Ä ÜPÒIǧ!æñ XDPÌÆHÃ6£ú ÜPÒIǧ!æñ X¤1É4ÑxÏ#£ú ïïPï ÜPÒI§ Ç !‰" ñ XDPÌÆP' à £ú ÊÎÂÒ€Ç When Python gets to . Python looks up the definition of and sees that it has a single ˆÆHÌÎÜÓÁ£Ç formal parameter. F ǽ€Ê3Æ ( ñ ¨ÑÓÄHɽÀ)¨"3£̈ÂIÊÎÆHĨÆHÌ½Ü F ( ú When Python comes to a function call. ˈÁPÃHÏ like all variables used in the function. it initiates a four-step process: 1. The formal parameters. Control returns to the point just after where the function was called. The body of the function is executed. 3. so it is as if we had executed this statement: ½Æ1ÌÎÜÓÁ£ÇÐß&XDPÌÆHÃ6 . The calling program suspends execution at the point of the call. Variables with identical names elsewhere in the program are distinct ˽ÁHÃPÏ from the formal parameters and variables inside of the function .

person + ". This time the formal & # X¤HÉÎÑÓ6 Ï  ÜHҀ§ Ç ! parameter is . . This statement is executed. This produces a blank line in the output. : Illustration of control transferring to . this one to . Python suspends execution of Ž"  )Ï and transfers control to the called function.¹H ¯ cóӅxŠ ³ y 6 ‚1ŠŒˆæuxŠŒ‹ŽHuI}"uxƒo{–y|{I}‘ˆ3´@ã‰tŒ{ 4 é {ôy–u 6 ± ˆ def def main(): person = "Fred" sing("Fred") print sing("Lucy") sing(person): happy() happy() print "Happy birthday. Local variables do not retain any values from one function execution to the next. The memory occupied by local function variables is reclaimed when the function finishes. shows where we are at that point. ¨Ì3Ò€Ç¨Ä ÊÎÂÒIÇ The next statement to execute is the bare statement in . Then Python encounters another call to ÜPÒI§ Ç ! . &  ½ÆHÌ3Ü£ÁÓÇ A snapshot of this situation is shown in Figure . shows the situation as begins to execute . Notice that the ÜPҀC Ç ! variable in has disappeared. dear". When Python gets to the end back to ÜHҀC Ç ! Ê4ÂÒIÇ of . Python begins executing the body of Ž"  ©¨Ï ÜHҀÇC! is another function call. dear". ÜPÒIǧ! . As before. shows a snapshot of the execution so far. Execution continues in this manner with Python making two more side trips Å3Â")Ï ÜPҀÇC! to complete the execution of . Figure . The first statement At this point. Figure . def def main(): person = "Fred" sing("Fred") print sing("Lucy") def happy(): sing(person): print "Happy Birthday to you!" happy() happy() print "Happy birthday. : Snaphot of completed call to ." happy() person: "Fred" &  Å3©¨Ï Figure . control then returns to and continues immediately after the func& ! ˆÆHÌ3Ü£Á£Ç tion call. The body of consists of a ¨Ì3Ò€Ç¨Ä . Figure ." happy() ~z¿€´ person: "Fred" &  ÜPÒIǧ! Figure . control transfers to the function definition. and then control returns to where it single &  ÜPÒI§ Ç ! left off in . person + ". Notice the variable ÜPÒIǧ! inside of has just been initialized.

as illustrated by Figure . These three statements in have ÜPÒI§ Ç ! Å3  ©Ï caused to execute twice and to execute six times.~z¿€¹ s@tŒuxw†y|{‡}½¹Pæé4{ÒêŠ 6 ŠŒ Ó ó …xŠ ³ y 6 ‚1ŠŒˆ def def main(): person = "Fred" sing("Fred") print sing("Lucy") sing(person): happy() happy() print "Happy birthday. dear". : Snaphot of second call to . for the second time. def def main(): y" "Luc sing("Fred") = on print pers sing("Lucy") sing(person): happy() happy() print "Happy birthday. Hopefully you’re getting the hang of how function calls actually work. . ÜHҀÇC! is executed Now we’ll fast forward to the end. person + ". The first actual parameter is assigned . person + ". : Completion of second call to . When a function definition has several parameters. The function body of ŽÂ"©¨Ï ÊÎÂÒIÇ for Lucy (with three side trips through ) and control returns to just after the point of the function call. the actual parameters are matched up with the formal parameters by position. dear"." happy() & ! ÜHҀǧ! Figure . person + ". One point that this example did not address is the use of multiple parameters. Overall. : Snaphot of completed call to . Now we have reached the bottom of our & % ÊÎÂÒIÇ code fragment." happy() & % ÜPÒIǧ! Figure . nine total lines of output were generated. def def main(): cy" u L " sing("Fred") on = print pers sing("Lucy") sing(person): happy() happy() print "Happy birthday." happy() person: "Lucy" & # ÜPÒIǧ! Figure . dear".

꫔|º Î ‚‰…P…ˆ‡penš dc ‘Φ•j …¨‘€ìÓgI™q› i¬ð•¦§eŸƒ†…‡™£e You have seen that parameter passing provides a mechanism for initializing the variables in a function. consider this call to the function from the library: ýҐÜPÑ ¨ÄWßÈÊ4£ÄHÅhïzÜ"íH̐ĉñð˕YIËS¨Ed§YHÂcYÑú 1 Python also allows parameters to be matched up by name rather than position. You have already seen numerous examples of this type of function. For Ü"íHÌÄ ÊÎÂ1ÄHÅ example. see the Python documentation for details. . Here is the call to draw the initial bar: % ÃPÌÂ£Û ˆÂ1̉ñèÛ3ҀǙõ Մõ°¨Ì3ҀÇÎѐÒq3Àˆú g ÃPÌÂ£Û ˆÂ1Ì When Python transfers control to .1 ÃPÌÂ£Û Â1Ì function from the future As an example. parameters act as inputs to a function. look again at the use of the value program.¹H ´H 3{–y y 6 ŠŒ {ôˆ–…± y|ˆ¬å }‘‚Hƒ uãóӅxŠ ³ y 6 ‚1Š uË 2i ~z¿€¿ to the first formal parameter. the second actual is assigned to the second formal. Sometimes we also want to get information back out of a function. µ ȑ×ÈƒÊ ¢ r'wQœ)tqlnvxw%s ÿ  %–§t˜hjiCt"r'“ëw87––QÙ r%ims One way to get information from a function is by having it return a value to the caller. ÛÎÒILjÐÁ1ÛÝ߀ÛÎÒIÇ ÏƐÂ1ÌÝßÝÕ Å½ÆÒ !£ÅÄWE ß ̽ҀÇÎѐҽÀ You must always be careful when calling a function that you get the actual parameters in the correct order to match the function definition. etc. èÆHÍWÃPÌÂ£Û Â1̉ñèÛÎÒILjÐÁ1۟õ ÏƐÂ1ÌoõîŽÆÒ 1 ! ŨÄ4ú­÷ g % The net effect is as if the function body had been prefaced with three assignment statements. In a way. but that approach is not used in this textbook. these parameters are matched up to the formal parameters in the function heading. We can call a function many times and get different results by changing the input parameters.

The ÈҨÜP Ñ  ¨Ä Ü íPÌPÄ " . In addition. the distance between between two points. µ ¶ ØÁҀ ¶  ÇÄ µ objects: Here is a Python function to compute the distance between two q – q – èÆHÍWýҐÜxĈÂxÇ4Ñ£ÆæñH“Ö“õ 3Ԉú¬÷ ýҐÜxÄÝß Ê4£ÄHÅhïzÜ"íH̐ĉñ‡Ü"í£É3£ÌÆæñf3Ԅïf!¨Æ1Ä ¬ñIúæ¨V“Ö­ïf!ÆHÄ ‰ñIúPú á  Ü í1ɽÂ1ÌƬH ñ ½Ôof ï !ÆHÄ „ñIú$¨`†Ö†ïf!ÆHÄ ‰ñIúPúú ÌÆ1ÄHÉÌ1ÇÐýҐÜxÄ %Ð €“ gÐ g“ – – . that means it Ê4£ÄHÅhïz" Ü íHÌÄ function must somehow produce a value that is an expression.~z¿€â s@tŒuxw†y|{‡}½¹Pæé4{ÒêŠ 6 ŠŒ Ó ó …xŠ ³ y 6 ‚1ŠŒˆ Ë Y€a • Ë ¨Ed§YHc  YÑ Ê4£ÄHńïô" Ü íHÌÄ Here the value of is the actual parameter of . Ü í£É3Â1Ì¨Æ " function any place that an expression would be legal. it exits the function and returns control to the point where encounters ̨ÆHÄHɨÌHÇ statethe function was called. We can use our Here are some interactive examples: ý (©()( (©()( Ü"í£É3Â1̨ÆæñôÞ3ú ̽ҀÇÄ¡Ü"í1ɽÂ1̨Ææñëd3ú ¦W@ ß 9 Ï ß Ü"í1ɽÂ1̨Ææñë¦3ú Ý ̽ҀÇÄcÏ ̽ҀÇÄ¡Ü"í1ɽÂ1̨Ææñë¦3ú Öxø (©()( (©()( (©()( Ô©9 Þ)d (©()( áÿÜ"í£É3£ÌÆæñôÞ3ú Let’s use the square function to write another function that finds the distance „ and ‚”“ „ . Technically. Here’s an example valueÜ íHÌÄ " . It’s very easy to write functions that return values. we say that returns is then assigned to the variable the square root of its argument. When Python ̨ÆHÄ1ÉÌHÇ . This function call occurs on the right side of an assignment statement. Given two points ‚”“ ¶ ¶ µ µ them is calculated from the Pythagorean Theorem as ‚”“ †ü“ „ µ ‚ † „ µ . the value(s) provided in the ment are sent back to the caller as an expression result. it returns the square of its returning function that does the opposite of argument: èÆHÍÿÜ"í£É3Â1̨ÆæñÒ¦Îú¬÷ ÌÆ1ÄHÉÌ1ÇS¦¡Y£¦ ̨ÆHÄHɨÌHÇ The body of this function consists of a single statement.

we can augment the interactive triangle program from the last chapter to calculate the perimeter of the triangle.¹H ´H 3{–y y 6 ŠŒ {ôˆ–…± y|ˆ¬å }‘‚Hƒ uãóӅxŠ ³ y 6 ‚1Š ÈҨ܀ĈÂÓÇÎÑ1Æ Using the function. Here’s the complete program: ó€ØÌ¨Á)!Ḧ€ʕ÷îĐ̽ÒHÂxǧ!ÀHƨԄïUÏ Ò‡c Ê ½Á1ÌÄ ÊÎÂ1ÄHÅ ÍP̨Áxa Ê !Ḧ"  PÅ4ÒPѨÜUÒvC Ê ˆÁH̐@ Ä Y èÆHÍÿ" Ü í£É3Â1̨ÆæÒ ñ ¦Îú¬÷ ÌÆ1ÄHÉÌ1ÇS¦¡Y£¦ èÆHÍWýҐÜxĈÂxÇ4Ñ£ÆæñH“Ö“õ 3Ԉú¬÷ ýҐÜxÄÝß Ê4£ÄHÅhïzÜ"íH̐ĉñ‡Ü"í£É3£ÌÆæñf3Ԅïf!¨Æ1Ä ¬ñIúæ¨V“Ö­ïf!ÆHÄ ‰ñIúPú á  Ü í1ɽÂ1ÌƬH ñ ½Ôof ï !ÆHÄ „ñIú$¨`†Ö†ïf!ÆHÄ ‰ñIúPúú ÌÆ1ÄHÉÌ1ÇÐýҐÜxÄ Ã¨ÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ÛÎÒIÇàß ü ̈ũ4ÎҀÇoñ  ¨ÌˆÂÓÛÝÂEPÌ3ÒHÂxǧ!¨ÀPÆ'Óú ÛÎÒIDŽïzÜÓÆHĨאÁÁ1̨ýܓñzÕoïðՉõ ÕoïðՉõfÖxÕoïðՄõªÖ€ÕnïùÕ3ú ÊÎƈܐÜ1  !¨ÆcT ß ¨) Æ ¦HĄñ–بÁˆÒIÇĄñ89‰õ ÕnïH9½ú†õèvרÀ¨ÒÑÎÝÁ£ÇÐÄHŨÌÆPÆV½ÁҀÇÄ3Ü%Óú ÊÎƈܐÜ1  !¨ÆoïùÃPÌ£ۄñèÛÎÒIǓú ó ü Æ1ÄàÂÓLjÃWÃḦÂÓÛÝÄHĄ̊ƐƣW¨ÆHÌPÄ3ÒÑ£Æ½Ü  Ö ß€ÛÎÒIDŽïp!¨ÆHÄHöˆÁÓÉ@ܣƬñIú †  ֆïùÃPÌ£ۄñèÛÎÒIǓú † 3Ôc߀ÛÎÒIDŽp ï !¨ÆHÄHöˆÁÓÉ@ܣƬñIú 3ԄïùÃPÌ£ۄñèÛÎÒIǓú ½Þ€ß€ÛÎÒIDŽp ï !¨ÆHÄHöˆÁÓÉ@ܣƬñIú ½ÞoïùÃPÌ£ۄñèÛÎÒIǓú ÁH̀Đ̽ÒHÂÓÇC!ÀHÆ uË 2i ~z¿€é %Ð €“ gÐ g“ r ó Ù@ÜÓÆcØÁ¨À£Ïc!Á£ÇàÁÓË ÆÑÓĀĨÁ€ÃPÌ£ÛÝÄHňÆcĐ̽ÒHÂÓÇC!ÀHÆ U ï Đ̽ÒHÂÓÇC!ÀHÆUßWØÁÀ1Ïc!Á£ÇoñH†Ö@õp½Ô‰õpˆÞ3ú Đ̽ÒHÂÓC Ç !ÀHÆnïzÜÓÆH) Ä D3ÒHÀPÀ¬" ñ 8½ÆÂÑI© Å HɈ͐' Í Óú Đ̽ÒHÂÓC Ç !ÀHÆnïzÜÓÆHÄ Ä ÉÄÀÒIǽÆæ" ñ xÑxψ€ Ç £ú Đ̽ÒHÂÓC Ç !ÀHÆnïùÃḦÂÓÛoñèÛ3ҀÇ@ú ½Æ1Ì3҇ÊàßÐÈҨ܀ĈÂÓÇÎÑ1ƬñH†Ö@õp½Ô½úáÝýҨ܀ĈÂxÇ4Ñ1ƬñH½Ô‰õpˆÞ3úáÝýҐÜxĈÂxÇ4Ñ£ÆæñHˆÞ„õs†ÖPú E½Æ1Ì3҇ʆú óÝרÂPÀрɽÀÂ£ÄÆUÄ1ŽÆ`½Æ1Ì3ÒvÊÎÆHĨÆH̀ÁP̀ÄHňÆcĐ̽ÒHÂÓÇC!ÀHÆ ÊÎƈܐÜ1Â!¨ÆoïzÜ£Æ1Ä©¨Æ)¦Pĉñ 3HŽÆæˆÆH̽҇ÊÎÆ1ÄÆ1ÌàҨܬ÷ ¨ÕoïèÔHÍ' " ¬" .

denoted value for variables that don’t currently hold anything useful. and will get the second value ( ). they Ü are assigned to variables by position. èÆHÍÿÜIÉ1Ê ÎÒÓ͐Íæë ñ ¦oõùÏ4ú­÷ ÜIÉ1Êÿ¥ ß ¦Ðá€Ï ýÒÓ͐ÍW¥ ß ¦S¨cÏ ÌÆ1ÄHÉÌ1Ç ÜIÉ1ʄõ˜ÃˆÒ£ÍÍ é ÌÆHÄ1ÉÌ1Ç As you can see. This object is often used as a sort of default a special object. This can be done ̨ÆHÄ1ÉÌHÇ statement. èÆHÍWýҐÜxĈÂxÇ4Ñ£ÆæH ñ “Ö“õ 3Ԉú¬÷ ýҐÜxÄÝß Ê4£ÄHÅhïz" Ü íH̐ĉñ‡" Ü í£É3£ÌÆæf ñ 3Ԅf ï !¨Æ1Ä ¬ñIæ ú ¨V“Ö­f ï !ÆHÄ ‰ñIúPú á  Ü í1ɽÂ1ÌƬH ñ ½Ôof ï !ÆHÄ „ñI$ ú ¨`†Ö†f ï !ÆHÄ ‰ñIúPúú %Ð €“ gÐ g“ . When calling this function. all functions in Python return a value. There is one “gotcha” to warn you about. Using a function here saves quite a bit of tedious coding. A common mistake that new (and not-so-new) programmers make is writing what should be ÌÆ1ÄHÉÌ1Ç statement at the a value-returning function but forgetting to include a end.~zâ7 s@tŒuxw†y|{‡}½¹Pæé4{ÒêŠ 6 ŠŒ Ó ó …xŠ ³ y 6 ‚1ŠŒˆ ó 4½Â¨ÒÓÄÝͨÁ1ÌàÂÓLjÁHÄHňÆHÌ¡Ñ1ÀÒPÑÎWĨÁWÆ)¦½ÒxÄ E ÛÎÒIDŽïf!ÆHÄHöˆÁ£É4ܣƬñIú ÛÎÒIDŽïôÑ1ÀPÁˆÜ£Ææñ‡ú ýҐÜxĈÂxÇ4Ñ£Æ You can see how is called three times in one line to compute the perimeter of the triangle. this hands back two values. Sometimes a function needs to return more than one value. here is a function that computes both the sum and the difference of two numbers. regardless of whether or not the function actually ÌÆ1ÄHɨÌHÇ ÌÆHÄ1ÉÌ1Ç statement. will get the first value ÌÆHÄ1ÉÌ1Ç ÜIÉ1Ê Ã Ã½Ò£ÍPÍ ( ). In this example. As a silly by simply listing more than one expression in the example. Technically. listed in the That’s just about all there is to know about value-returning functions in Python. we would place it in a simultaneous assignment. ÌÆ1ÄHÉÌ1Ç Ã½ÒÜxĈÂxÇ4Ñ£Æ statement at the end of the Suppose we forget to include the function. ǐÉ1ʬÖ@õîǐÉ1Ê4ÔcߡҀ) Ç É¨Ä„ñ †ØˆÀHƨˆÜÓÆcÆÓÇÄÆ1̀ÄPÛÁÈǐÉ1Ê˽Æ1ÌÎÜ»ñùǐÉ1ʬ֓õ ǐÉHÊÎÔ½ú@Óú Ü­õ˜Ã ß ÜIÉHÊ ÎÒÓ͉͐ñùǐÉ1ʬ֓õ ǐÉ1Ê4Ԉú ̽ҀǨA Ä X1ŽơÜIÉ1Ê Ò¨m Ü ÎõÜ­è õ ‡ÂÓÇÃcÄHňƀýңÍPͨÆ1ÌÆ£ÇÎÑ1ÆWÒ¨% Ü 3õ˜Ã  As with parameters. Functions without a always hand back contains a ШÁ£ÇˆÆ . when multiple values are returned from a function.

In some cases. . Addition is not defined for . ÐÁ£ÇˆÆ ÐÁÓÇ½Æ it always hands back the value . Let’s try out our function by writing a very small test program. Understanding when and how this is possible requires the mastery of some subtle details about how assignment works in Python and the effect this has on the relationship between the actual and formal parameters used in a function call. µ ȑ×È‘Ç ¢ r'wQœ)tqlnvxw%sIt %–mt )  ¶ 6› l¤ v 'l@9 £’d–m“H–B—˜iCtui•“fs Return values are the main way to send information from a function back to the part of the program that called the function. Let’s start with a simple example. functions can also communicate back to the calling program by making changes to the function parameters. check to make sure you remembered to include the . We might consider writing a function that automatically adds the interest to the account balance.¹H ´H 3{–y y 6 ŠŒ {ôˆ–…± y|ˆ¬å }‘‚Hƒ uãóӅxŠ ³ y 6 ‚1Š ÈҨÜxÄÂÓÇÎÑ1Æ uË 2i ~zâH~ Running the revised triangle program with this version of this Python error message: ÌÂѣƣË3¨ÑÎòñvҀÇPǽÆ1Ì£ÊÎÁˆÜxÄWÀÂˆÜ€Ä4ú­÷ D3Ò1ÀPÆ generates ÜxĐýÒIÇ ( 3  õ˜À¨Ò€Ç½Æ Ö@õ F D3Ò1ÀPƆĐÌ3Ò1ÂÓÇC!ÀPƐÔPÆ1̙̐ïbÏ6Îõ D3Ò1ÀPƆĐÌ3Ò1ÂÓÇC!ÀPƐÔPÆ1̙̐ïbÏ6Îõ À ÒIǽÆWސþ‰õÒ€Ç€ÊÎÂÒ€Ç  ½Æ1Ì3҇ÊàßÐÈҨ܀ĈÂÓÇÎÑ1ƬñH†Ö@õp½Ô½úáÝýҨ܀ĈÂxÇ4Ñ1ƬñH½Ô‰õpˆÞ3úáÝýҐÜxĈÂxÇ4Ñ£ÆæñHˆÞ„õs†ÖPú Ï½Æ ̨̐ÁH̟÷ Ë3Â1ÃÝÁ ˆÆḦÂxLjÃcÄPÏgˆÆæñ‡Üú ͨÁ1ÌWá G Ê4¨ҀÇnñ‡ú ҀÇÏP ÀÒIǽÆTd©d„õÒ€ÇâP ýҐÜxĈÂxÇ4Ñ£Æ The problem here is that this version of does not return a number. One of the common tasks that must be performed is to accumulate interest on an account (as we did in the future value program). Suppose you are writing a program that manages bank accounts or investments. and so Python complains. If your value-returning functions are producing strange error ̨ÆHÄHɨÌHÇ messages. Here is a first attempt at such a function: óÐÂHÃPýÒIÇÄÆ1ÌƈÜxÄ@ֆïU¨Ï èÆHÍÐÂHÃP% à ¢IǨÄÆ1Ìƽ܀ĄñùË3ÀPÂÓÇÎÑ1Ƅõ ÌÂ1ĨÆ3ú¬÷ Ç½Æ£Û ˆÂPÀÂxÇ4Ñ1ÆÈßUË3ÂPÀÂÓÇÎÑ1ÆSY ñIրáPÌÂ1ĨÆ3ú Ë3ÂPÀÂÓÇÎÑ1ÆcßULjÆ1Û ˆÂÀPÂÓÇÎÑ1Æ % g The intent of this function is to set the balance of the account to a value that has been updated by the amount of interest.

Of course. If you consider carefully what we have discussed so far regarding functions and parameters. the formal parameters of a function only receive the values of the actual parameters. ÂIÊÎÁ£ÉPÇÄ ÌÂ1Ä¨Æ Ä¨Æ½ÜxÄ but and in the function still refer to the initial values of 1000 ÂIÊÎÁ£ÉPÇÄ and 0. The function does not have any access to 31 % % % . is unchanged! What has gone wrong? Actually. giving a result of …žwx"w . The result is shown in Figure . but this had no effect €Ê3Á£ÉPÇÄ Ä¨Æ½Ü€Ä on in the function. Let’s trace the execution of this example Ä¨Æ½Ü€Ä function create two local to see what happens. The formal parameters Ë3ÂPÀÂxÇ4Ñ1Æ ÌˆÂ£ÄÆ ÂIÊÎÁ£ÉPÇÄ and are assigned the values from the actual parameters ̈£ÄÆ ÌˆÂ£ÄÆ and . Here’s what actually happens: 1   à ½ à I Ò  Ç ¨ Ä H Æ  Ì ˆ Æ x Ü Ÿ Ä ïpÄƈÜxĉñIú (©()( ÖxÕPÕÕ ÂIÊÎÁÓɐÇÄ As you can see. control transfers to the function. . To summarize the situation. The local variables (including parameters) in go away. execution of has completed and control returns ÄÆ½Ü€Ä Â1Ð% à ¢‡ÇĨÆHÌƈÜxÄ to . respectively. Notice Ë3ÂPÀÂÓÇÎÑ1Æ Ç½Æ£Û ˆÂPÀÂxÇ4Ñ1Æ that now refers to the same value as . The next statement in assigns & ' LjÆ1Û ÀPÂÓÇ4Ñ£Æ to have the same value as . . The first two lines of the €ÊÎÁÓÉÇ¨Ä ÌÂ1Ä¨Æ variables called and which are given the initial values of …žw w w and wch wx . even though the name appears in both functions. Â1Ð% à ¢‡ÇĨÆHÌƈÜxÄ Next. nothing has gone wrong. Notice that the assignment of parameters causes the Ë3ÂPÀÂÓÇÎÑ1Æ ÌÂ1ÄÆ ÂHÐm à ¢IǨÄÆHÌ¨Æ½Ü€Ä variables and in to refer to the values of the actual parameters.05. ÂHÐm à ¢IǨÄÆHÌ¨Æ½Ü€Ä these are two separate variables. you will see that this is exactly the result that we should expect. respectively. The situation as begins to exe& & cute is shown in Figure .~zâ€r s@tŒuxw†y|{‡}½¹Pæé4{ÒêŠ 6 ŠŒ Ó ó …xŠ ³ y 6 ‚1ŠŒˆ èÆH̀ÄƈÜxĄñ‡ú¬÷ €Ê3Á£ÉÇ¨ÄWß ÖxÕPÕÕ ÌˆÂ£ÄƀßÝÕnïùÕc9 ÂHÃP% à ¢IǨÄÆ1Ìƽ܀Ąñz€ÊÎÁÓɐǨÄnõ ̈£Äƽú ̽ҀÇÄÝ€ÊÎÁÓÉÇ¨Ä ÄƈÜxĉñIú What to you think this program will print? Our intent is that x should be €Ê3Á£ÉÇ¨Ä added to . ÂHÐm à ¢IǨÄÆHÌ¨Æ½Ü€Ä Ë3ÀPÂÓÇÎÑ1Æ Now comes the key step. the program prints the value of as …žw w w . ÂHÐm à ¢IǨÄÆHÌ¨Æ½Ü€Ä At this point. Â1Ð% à ¢‡ÇĨÆHÌƈÜxÄ Ç½Æ£Û ÀÂxÇ4Ñ£Æ Executing the first line of creates a new variable . Remember.

rate): newBalance = balance * (1 + rate) balance = newBalance balance amount 1000 rate rate 0. rate): newBalance = balance * (1 + rate) balance = newBalance balance amount 1000 rate rate 0.05 rat addInterest(amount.rate) print amount def addInterest(balance.05 r addInterest(amount. .rate) print amount def addInterest(balance.05 & & ÂHÐÃm¢IǨÄÆHÌ¨Æ½Ü€Ä Figure . t def test(): oun =am nce ate amount = 1000 a l ba e=r rate = 0. : Transfer of control to . : Assignment of .05 newBalance 1050 & ' ˽ÀPÂÓÇ4Ñ£Æ Figure .¹H ´H 3{–y y 6 ŠŒ {ôˆ–…± y|ˆ¬å }‘‚Hƒ uãóӅxŠ ³ y 6 ‚1Š uË 2i ~z— t def test(): oun =am amount = 1000 nce rate a l ba ate= rate = 0.

Here’s a working version: óÐÂHÃPýÒIÇÄÆ1ÌƈÜxĈԄU ï ¨Ï % èÆHÍÐÂHÃPÃ%¢IǨÄÆ1Ìƽ܀ĄñùË3ÀPÂÓÇÎÑ1Ƅõ ÌÂ1ĨÆ3ú¬÷ Ç½Æ£Û ˆÂPÀÂxÇ4Ñ1ÆÈßUË3ÂPÀÂÓÇÎÑ1ÆSY ñIրáPÌÂ1ĨÆ3ú ÌÆ1ÄHÉÌ1Ç€Ç½Æ£Û ÀÂxÇ4Ñ£Æ % % èÆH̀ÄƈÜxĄñ‡ú¬÷ €Ê3Á£ÉÇ¨ÄWß ÖxÕPÕÕ ÌˆÂ£ÄƀßÝÕnïùÕc9 €Ê3Á£ÉÇ¨ÄWßÐÂHÃPÃ%¢‡ÇÄÆ1ÌƈÜxĄñz€Ê3Á£ÉÇ¨Änõ ̈£Äƽú ̽ҀÇÄÝ€ÊÎÁÓÉÇ¨Ä ÄƈÜxĉñIú You should easily be able to trace through the execution of this program to see how we get this output. (©()( Â1ÐýÒIÇĨÆHÌƈÜxÄÔoïpĨƽ܀ĄñIú Öx© Õ 9PÕ Now suppose instead of looking at a single account. Such a mechanism is called passing parameters by reference. We could store the account balances Â1ÐÃ%¢‡ÇĨÆHÌƈÜxÄ in a Python list. therefore. assigning a new value to a formal parameter has no effect on the variable that contains the actual parameter.. When a variable is passed by reference. Some programming languages (e. we are writing a program that deals with many bank accounts. do allow variables themselves to be sent as parameters to a function. Since Python does not allow passing parameters by reference. It would be nice to have an function that adds the Ë3ÂPÀÂxÇ4Ñ1ÆˆÜ accrued interest to all of the balances in the list.~zâ ¯ s@tŒuxw†y|{‡}½¹Pæé4{ÒêŠ 6 ŠŒ Ó ó …xŠ ³ y 6 ‚1ŠŒˆ the variable that holds the actual parameter. an obvious alÂHÃP% à ¢IǨÄÆ1ÌÆ½Ü€Ä Ç½Æ£Û ˆÂPÀÂxÇ4Ñ1Æ function so that it returns the . If is a list of account balances. C++ and Ada). we can update the first amount in the list (the one at index 0) with a line of code like this: . In programming language parlance. Python is said to pass all parameters by value. ternative is to change our ÂIÊÎÁÓɐÇÄ ÄÆ½Ü€Ä This value can then be used to update the in the function. assigning a new value to the formal parameter actually changes the value of the parameter variable in the calling program.g.

So what’s going on here? . “multiply the value in the 0th position of the list by ‚H…  the result back into the 0th position of the list. Ë3ÂPÀÂxÇ4Ñ1ÆˆÜ û  Ö cßU˽ÀPÂÓÇ4Ñ£Æ½Ü û  Ö  Y¥ñ€ÖYá€ÌˆÂ£Äƽú A more general way of updating all the balances in a list is to use a loop that †E… . the value of €Ê3Á£ÉPÇÄÎÜ is printed out. (©()( ÂHÃPýҀǨÄÆ1Ìƽ܀ÄÞoïpÄƈÜxĉñIú û րc Õ 9HÕnïðՉõ ÔPÞ3ÖxÕoïðՄ° õ e)dÕnïðՉõ˜Þ) þ enïù) Õ  ™9 %q )q sq 9 ji ™wk Isn’t that interesting? In this example.¹H ´H 3{–y y 6 ŠŒ {ôˆ–…± y|ˆ¬å }‘‚Hƒ uãóӅxŠ ³ y 6 ‚1Š Ë3ÂPÀÂxÇ4Ñ1ÆˆÜ û Õ)cßU˽ÀPÂÓÇ4Ñ£Æ½Ü û Õ) Y¥ñ€ÖYá€ÌˆÂ£Äƽú uË 2i ~z‴ Remember. The function starts by setting €Ê3Á£ÉPÇÄÎÜ Â1ÐÃm¢IÇĨÆH̨ƽÜxÄ to be a list of four values. a very similar line of code would work to update the balance of the next location in the list. this works because lists are mutable. so the variable itself ( ) can’t be changed by the function. But I just told you that Python passes parameters €Ê3Á£ÉPÇÄÎÜ by value. the function seems to change the ÂIÊÎÁ£ÉPÇÄ3Ü value of the variable. After the function call. we just Õ Ö replace the s with s. óÐÂHÃPýÒIÇÄÆ1ÌƈÜxÄÞoU ï ¨Ï èÆHÍÐÂHÃPÃ%¢IǨÄÆ1Ìƽ܀ĄñùË3ÀPÂÓÇÎÑ1ƽ܆õ ̈£ÄÆ3ú­÷ ͨÁ1ÌÿÒWҀÇÐ̈Âx§ Ç !Ææñ†ÀHÆ£ÇoñðË3ÂPÀÂxÇ4Ñ1ƈܨúPú¬÷ Ë3ÀPÂÓÇÎÑ1Æ½Ü û " Ò cßUË3ÂPÀÂxÇ4Ñ1ÆˆÜ û Ò SY¥ñIրáḦÂ1ĨÆ3ú èÆH̀ÄƈÜxĄñ‡ú¬÷ €Ê3Á£ÉÇ¨ÄÎÜYß û ÖxÕPՐՄõ˜ÔÔPÕPՄõÔePՐՄõ¢ÞøÕg ̈£ÄƀßÝÕnïùÕc9 ÂHÃP% à ¢IǨÄÆ1Ìƽ܀Ąñz€ÊÎÁÓɐǨÄÎÜ­õ ÌÂ1ĨÆ3ú ̽ҀÇÄÝ€ÊÎÁÓɐǨÄÎÜ ÄƈÜxĉñIú ĨƽÜxÄ Take a moment to study this program. What do you expect to see? Let’s run this little program and see what happens.” Of course. Here is a program that implements goes through positions w u… žhžhžh Òû ø this idea. This line of code essentially ö ú „ and store says. Then the function is called ÂIÊÎÁÓɐÇÄ3Ü sending as the first parameter.

. The result is shown in w u… žhžhžh Òû ø †T… and updates that item in & ) Figure .05 balances amounts [ .05 addInterest(amounts. When terminates. The situation at this point is & ( ÂIÊÎÁ£ÉPÇÄ3Ü depicted in Figure . and the assignments into the list cause it to refer to the new values. and that is what gets printed.800. 2200.2150.3275] rate = 0. if %q )q sq 9 ji ™wk . The old values will actually get cleaned up when Python does garbage collection. I did this to emphasize that the numbers in the value boxes have not changed. What has happened is that the state of that list has changed. It still refers to the same list that ÂHÐm à ¢IǨÄÆHÌ¨Æ½Ü€Ä it did before the call to . and then Â1ÐÃm¢IÇĨÆH̨ƽÜxÄ control transfers to the function. rate): for i in range(len(balances)): balances[i] = balances[i] * (1+rate) rate rate 0. Now you really know everything there is to know about how Python passes parameters to functions. You’ll notice in the diagram that I left the old values (1000. list object that itself contains four int values. the list stored €ÊÎÁÓɐǨÄÎÜ in now contains the new balances. ] 1000 2200 800 360 & ( Â1ÐÃ%¢‡ÇĨÆHÌƈÜxÄ Figure . . Notice €Ê3Á£ÉÇ¨ÄÎÜ that the variable was never changed.~z‹ s@tŒuxw†y|{‡}½¹Pæé4{ÒêŠ 6 ŠŒ Ó ó …xŠ ³ y 6 ‚1ŠŒˆ ÄƈÜxÄ Â€ÊÎÁÓɐǨÄÎÜ ÌˆÂ£ÄÆˆÜ The first two lines of create the variables and . Parameters are always passed by value. 360) just hanging around. . Instead what has happened is that new values were created. However. 800. The loop goes through each index in the range Ë3ÂPÀÂxÇ4Ñ1ÆˆÜ . to ÂHÃP% à ¢‡ÇÄÆ1ÌƈÜxÄ Next executes. . It is this list object that gets passed Â1ÐÃ%¢‡ÇĨÆHÌƈÜxÄ Ë½ÂÀÂxÇ4Ñ£Æ½Ü and is therefore also the value of . : Transfer of list parameter to . ÂHÃP% à ¢IǨÄÆ1ÌÆ½Ü€Ä It should be clear now why the list version of the program ÂHÃP% à ¢IǨÄÆ1ÌÆ½Ü€Ä produces the answer that it does.rate) print amounts def addInterest(balances. and this change is visible back in the calling program. Notice that the value of the variable is now a def test(): amounts = [1000.

thus shortening and simplifying our programs.800. Humans are pretty good at keeping track of eight to ten things at a time. Surprisingly. When presented with an algorithm that is hundreds of lines long. ꫔–ê 𕦕eŸƒ†…ˆ‡™£eŸ‘Ýi•eŸ· —¢gI™„šqgIi„› ©²…Îg£¦Ÿƒ†…3¦§gI‚ So far. even the best programmers will throw up their hands in bewilderment. each of which makes sense on its own. : List modified in . A second reason for using functions is to make programs more modular. I’ll have a lot more to say about this later when we discuss program design in Chapter 9. it gets more and more difficult to make sense out of programs. ] 1050 2310 840 378 1000 2200 800 360 & ) ÂHÃPÃ%¢‡ÇÄÆ1ÌƈÜxÄ Figure .¹H ¹HcóӅxŠ ³ y 6 ‚1ŠŒˆæuxŠŒ‹Ž3}‘‚€1}"uxƒ`˜xyè} … ³ yè…x}${ ~z‿ def test(): amounts = [1000.05 addInterest(amounts. As the algorithms that you design get more complex. we’ll . then changes to the state of the object will be visible to the calling program.3275] rate = 0. we have been discussing functions as a mechanism for reducing code duplication.2150. functions are often used even when doing so actually makes a program longer.rate) print amounts def addInterest(balances. . rate): for i in range(len(balances)): balances[i] = balances[i] * (1+rate) rate rate 0. the value of the variable is a mutable object (like a list or graphics object). One way to deal with this complexity is to break an algorithm into smaller subprograms. . For now.05 balances amounts [ . This latter situation is another example of the aliasing issue discussed in Chapter 5.

The comments help to explain things.~zâ€â s@tŒuxw†y|{‡}½¹Pæé4{ÒêŠ 6 ŠŒ Ó ó …xŠ ³ y 6 ‚1ŠŒˆ just take a look at an example. Let’s return to the future value problem one ÊÎÂÒ€Ç more time. Here is the program as we left it: èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ó ¢IǨĐÌÁHÃ1ÉÎÑÓÄ3Ò£Á£Ç a ̽ҀÇ Ä XHÅÎÒ¨ Ü ¨ÌÁ)!ḦÂIÊ¥3ÀHÁHÄ3ÜYÄHŽÆT!HÌÁ£Û¨ÄHÅÐÁPÍÐÂÿÖxÕ©¨1ϨƨÂ1ÌàҀÇCW¨Æ½Ü€Ä£ÊÎÆÓÇğïq ó ü Æ1ÄEÌ3ÒIÇ4ÑPÒ3ÂPÀ€ÂÓÇÃàҀǨÄÆ1Ìƽ܀Ā̈£ÄÆ  ̽ҀÇ4ÑPҽÀÈßÿÒIÇ©É¨Ä„ñ" ǨÄÆ1ÌUÄ1ŽÆàҀÇÎÒÓĽÒHÀ§Ì3ÒIÇ4ÑPÒ3ÂPÀo÷ü£ú  G  ¨ÌÝߡҀ© " Ç PÉĉñ  ÇĨÆHÌcÄ1ŽÆÝÂxǐǐɽÀ¨Ò ¨ÆHÃÐÒIÇÄÆ1ÌƈÜxÄcÌÂ1ĨÆn÷£ú G !h óÝ×H̨ƨÂ1ĨÆWÂT!PÌÂ"ÅÎҐѐܪÛÎÒILjÐÁ1ÛWÛÎÒxÄHÅ¡ÀPÂÓˈƨÀˆÜYÁ£ÇÿÀPÆHÍPÄÐÆHé!¨Æ ÛÎÒIÇàß ü ̈ũ4ÎҀÇoñ ¢IÇCW¨Æ½Ü€Ä£ÊÎÆÓÇÄ ü ̨Á1ېÄHÅà×ÓÅ3Â1ÌPÄ#3õ¢Þ¨ÔHՄõ Ôd¨Õ3ú ÛÎÒIDŽïzÜÓÆHÄ ˆÂÑÎC!HÌÁ£ÉPLjÃæñ †ÛHÅ4ÒxÄƕ£ú ÛÎÒIDŽïzÜÓÆHĨאÁÁ1̨ýܓ3 ñ ¨½Ö­ïùc þ 9‰Ò õ ¨ÔHՐÕæõ ֐֭H ï 9‰õfր) Õ dÕÕ3ú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“õ Õ3ú†õ ÕoïðÕ vú­ïùÃḦ£ۄñèÛ3ҀǓú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“õl© Ô 9PÕPÕ3ú“õ ÔoH ï 9 Œú¬ïpÃP̈ÂÓÛoñðÛÎҀÇ@ú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“° õ 9PՐÕPÕ3ú“õ î9oïùÕ Œú¬ïpÃP̈ÂÓÛoñðÛÎҀÇ@ú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“õ c þ 9PÕPÕ3ú“õ þnH ï 9 Î Œú¬ïpÃP̈ÂÓÛoñðÛÎҀÇ@ú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“õÖxՐÕPՐսú†õ vÖxÕnïùÕ vú¬ïpÃPÌ£ÛoñðÛÎÒIǓú € ž % ž ó ó  # !À !À #  3  À  ##   3À  ¨Ì£ۀË3£ÌÝͨÁ1ÌÿҀÇ4ÒxÄ3Ò1Àè¨Ì3ҀÇÎѐÒq3À ÃPÌÂ£Û Â1̉ñèÛÎÒIǙõ Մõ°̽ҀÇÎѐҽÀˆú ¨Ì£ۡ Ë3£ÌÝͨÁ1ÌÐƨÂÑIÅ»ÜIÉPË@Ü£Ægí1ɈƣÇÄUÏƐÂ1Ì Í¨Á1ÌWÏƨ£̡ҀÇàÌÂÓǧ!ÆæñI֓õÖPÖPú­÷ Ì3ÒIÇ4ÑP Ò 3ÂPÀÈE ß ̽ҀÇÎѐ Ò ½ÂT À Y¥ñ€Ö áàÂ"¨Ì4ú ÃP̈ÂÓÛ Â1̄ñðÛÎÒIǙõ Ïƨ£Ìn5 õ ¨Ì3ҀÇÎѐq Ò 3Àˆú % ̈ÂÓm Û ÌÒI© Ç PÉĄ" ñ ŒØPÌƽÜPÜ ÛÎÒIDŽïôÑ1ÀPÁˆÜ£Ææñ‡ú Ê4¨ҀÇoñIú FG ǨÄÆ1Ì ( ĨÁTí1É4Òxęïu£ú Although we have already shortened this algorithm through the use of the ÃPÌÂ£Û ˆÂ1Ì function. it is still long enough to make reading through it awkward. there are g . For example. One way to make the program more readable is to move some of the details into a separate function. but—not to put too fine a point on it— this function is just too long.

It is a self-contained entity that performs this one well-defined task. Using our new function. èÆHÍ¡ÑǪ́ƨÂ1ĨÆg¤ÂÓ˽ƐÀPÆHÃg4ÎÒILjÐÁ1Ûoñ‡ú¬÷ ó  ˆÆ1ÄHÉÌ1Ç@ÜÈ ü ̈" E  Pc Å 43ҀǀÛ3ÒÓÄ1ÅÐÄ3ÒÓÄÀPÆWÂxLjÃÐÀPÂÓ˽ƐÀˆÜYÃḦÂÓÛPÇ ÛÎÒILjèÁ£ÛÝß ü Ì"  Pc Å 4ÎÒIÇn" ñ "¢Ic Ç WƈÜxÄ£Ê3Æ£Ç¨Ä ü ÌÁ£Û¨ÄHÅÐ×£Å3£̐6 Ä Îõ˜ÞÔPՄõ˜Ôgd¨Õ½ú ÛÎÒILjèÁ£ÛhïôÜ£ÆHÄ ˆÂ¨ Ñ ÎC!HÌÁÓɐLjÃæñ zÛPÅ3ÒÓÄB Æ Óú ÛÎÒILjèÁ£ÛhïôÜ£ÆHĨאÁPÁH̨ýܓ8 ñ ¨3Ö­ïùc þ 9æë õ ¨HÔPՐՉõ˜ÖÖ†¡ ï 9æõfÖxg Õ d¨ÕÕ½ú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“õ Õ3ú†õ ÕoïðÕ vú­ïùÃḦ£ۄñèÛ3ҀLjÐÁ1Û4ú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“õl© Ô 9PÕPÕ3ú“õ ÔoH ï 9 Œú¬ïpÃP̈ÂÓÛoñðÛÎҀÇèÁ£Û@ú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“° õ 9PՐÕPÕ3ú“õ î9oïùÕ Œú¬ïpÃP̈ÂÓÛoñðÛÎҀÇèÁ£Û@ú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“õ c þ 9PÕPÕ3ú“õ þnH ï 9 Î Œú¬ïpÃP̈ÂÓÛoñðÛÎҀÇèÁ£Û@ú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“õÖxՐÕPՐսú†õ vÖxÕnïùÕ vú¬ïpÃPÌ£ÛoñðÛÎÒILjèÁ£Û@ú ÌÆ1ÄHÉÌ1ÇWÛÎÒILjÐÁ1Û €  # !À !À #  ##  3À  3À As its name implies. this function takes care of all the nitty-gritty details of drawing the initial window. We could put these steps into a value returning function. the code has become nearly self-documenting. the èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ Ä XHÅÎҨܨÌÁ)!ḦÂIÊ¥3ÀHÁHÄ3ÜYÄHŽÆT!HÌÁ£Û¨ÄHÅÐÁPÍÐÂÿÖxÕ©¨1ϨƨÂ1ÌàҀÇCW¨Æ½Ü€Ä£ÊÎÆÓÇğïq ̽ҀÇ4ÑPҽÀÈßÿÒIÇ©É¨Ä„ñ" Â"¨ÌÝߡҀǩPÉĉñ  G Ç ÄÆ1ÌUÄ1ŽÆàҀÇÎÒÓĽÒHÀ§Ì3ÒIÇ4ÑPÒ3ÂPÀo÷ü£ú ¨ ÇĨÆHÌcÄ1ŽÆÝÂxǐǐɽÀ¨Ò ¨ÆHÃÐÒIÇÄÆ1ÌƈÜxÄcÌÂ1ĨÆn÷£ú G !h ÛÎÒIÇàß¡ÑÓÌƐÂ1ĨÆg¤ˆÂx˽ƐÀPÆPÃ4ÎÒILjèÁ£Ûoñ‡ú ÃPÌÂ£Û Â1̉ñèÛÎÒIǙõ Մ° õ ̽ҀÇÎѐ Ò ½ÂÀˆú ͨÁ1ÌWÏƨ£̡ҀÇàÌÂÓ§ Ç !ÆæñI֓õÖPÖPú­÷ Ì3ÒIÇ4ÑP Ò 3ÂPÀÈE ß ̽ҀÇÎѐ Ò ½ÂT À Y¥ñ€Ö áàÂ"¨Ì4ú ÃP̈ÂÓÛ Â1̄ñðÛÎÒIǙõ Ïƨ£Ìn5 õ ¨Ì3ҀÇÎѐq Ò 3Àˆú % % ̈ÂÓm Û ÌÒI© Ç PÉĄ" ñ ŒØPÌƽÜPÜ ÛÎÒIDŽïôÑ1ÀPÁˆÜ£Ææñ‡ú FG ǨÄÆ1Ì ( ĨÁTí1É4Òxęïu£ú Notice that I have removed the comments. Ê4Â¨Ò€Ç algorithm seems much simpler. With suitably named functions.¹H ¹HcóӅxŠ ³ y 6 ‚1ŠŒˆæuxŠŒ‹Ž3}‘‚€1}"uxƒ`˜xyè} … ³ yè…x}${ ~zâ€é eight lines in the middle that simply create the window where the chart will be drawn. Here is the final version of our future value program: óWÍ1ɨĩWÀ©Ì!PÌÂ"ÅCdŸïbÏ . the intent of the algorithm is now clear.

~zé7 s@tŒuxw†y|{‡}½¹Pæé4{ÒêŠ 6 ŠŒ Ó ó …xŠ ³ y 6 ‚1ŠŒˆ ÍP̨ÁxÊa!ḦÂ"PÅ4ÒPѨÜUÒvÊCˆÁH̐Ä@Y èÆHÍ¡ÑǪ́ƨÂ1ĨÆg¤ÂÓ˽ƐÀPÆHÃg4ÎÒILjÐÁ1Ûoñ‡ú¬÷ ÛÎÒILjèÁ£ÛÝß ü Ì"  Pc Å 4ÎÒIÇn" ñ "¢Ic Ç WƈÜxÄ£Ê3Æ£Ç¨Ä ü ÌÁ£Û¨ÄHÅÐ×£Å3£̐Ä6Îõ˜ÞÔPՄõ˜Ôgd¨Õ½ú ÛÎÒILjèÁ£ÛhïôÜ£ÆHÄ ˆÂ¨ Ñ ÎC!HÌÁÓɐLjÃæñ zÛPÅ3ÒÓÄB Æ Óú ÛÎÒILjèÁ£ÛhïôÜ£ÆHĨאÁPÁH̨ýܓ8 ñ ¨3Ö­ïùc þ 9æë õ ¨HÔPՐՉõ˜ÖÖ†ï¡9æõfÖxÕgd¨ÕÕ½ú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“õ Õ3ú†õ ÕoïðÕ vú­ïùÃḦ£ۄñèÛ3ҀLjÐÁ1Û4ú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“õl© Ô 9PÕPÕ3ú“õ ÔoH ï 9 Œú¬ïpÃP̈ÂÓÛoñðÛÎҀÇèÁ£Û@ú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“° õ 9PՐÕPÕ3ú“õ î9oïùÕ Œú¬ïpÃP̈ÂÓÛoñðÛÎҀÇèÁ£Û@ú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“õ c þ 9PÕPÕ3ú“õ þnH ï 9 Î Œú¬ïpÃP̈ÂÓÛoñðÛÎҀÇèÁ£Û@ú g Æ ¦PĄñèØÁҀÇĉ3 ñ ¨½Ö“õÖxՐÕPՐսú†õ vÖxÕnïùÕ vú¬ïpÃPÌ£ÛoñðÛÎÒILjèÁ£Û@ú ÌÆ1ÄHÉÌ1ÇWÛÎÒILjÐÁ1Û €  # !À !À #  3  À  ##   3À  èÆHÍWÃPÌÂ£Û Â1̉ñèÛÎÒILjÐÁ1۟õ ÏƐÂ1ÌoõîŽÆÒ !1ŨÄ4ú­÷ Ë3£ÌÝßE ˆÆˆÑxĈÂxǧ!ÀHÆæñèØÁˆÒIÇĉñ–ÏƐÂ1Ìoõ Õ3ú†õ¢Ø¨ÁˆÒIÇĄñèÏƐÂ1̨áÎ֓õ ŽÆÒ 1 ! ŨÄ4úPú Ë3£̙ïzÜÓÆH) Ä D3ÒHÀPÀ¬" ñ ž!P̨ƐÆÓ Ç £ú Ë3£̙ïzÜÓÆHg Ä 4ÎÒ£ÃHÄHÅoñ†Ô½ú Ë3£̙ïùÃḦÂÓÛoñèÛ3ҀÇèÁ1Û4ú èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ Ä XHÅÎҨܨÌÁ)!ḦÂIÊ¥3ÀHÁHÄ3ÜYÄHŽÆT!HÌÁ£Û¨ÄHÅÐÁPÍÐÂÿÖxՀϨƨÂ1ÌàҀÇCW¨Æ½Ü€Ä£ÊÎÆÓÇğïq ̽ҀÇ4ÑPҽÀÈßÿÒIÇ©É¨Ä„ñ" % Â"¨ÌÝߡҀǩPÉĉñ  G ǨÄÆ1ÌUÄ1ŽÆàҀÇÎÒÓĽÒHÀ§Ì3ÒIÇ4ÑPÒ3ÂPÀo÷ü£ú G ÇĨÆHÌcÄ1ŽÆÝÂxǐǐɽÀ¨Ò ¨ÆHÃÐÒIÇÄÆ1ÌƈÜxÄcÌÂ1ĨÆn÷£ú !h ÛÎÒIÇàß¡ÑÓÌƐÂ1ĨÆg¤ˆÂx˽ƐÀPÆPÃ4ÎÒILjèÁ£Ûoñ‡ú ÃPÌÂ£Û Â1̉ñèÛÎÒIǙõ Մ° õ ̽ҀÇÎѐ Ò ½ÂÀˆú ͨÁ1ÌWÏƨ£̡ҀÇàÌÂÓ§ Ç !ÆæñI֓õÖPÖPú­÷ Ì3ÒIÇ4ÑP Ò 3ÂPÀÈE ß ̽ҀÇÎѐ Ò ½ÂT À Y¥ñ€Ö áàÂ"¨Ì4ú ÃP̈ÂÓÛ Â1̄ñðÛÎÒIǙõ Ïƨ£Ìn5 õ ¨Ì3ҀÇÎѐq Ò 3Àˆú % % Ì ÂÓÛmÌÒIÇ©PÉĄñ"ŒØPÌƽÜPÜ ˆ ÛÎÒIDŽïôÑ1ÀPÁˆÜ£Ææñ‡ú FG ǨÄÆ1Ì ( ĨÁTí1É4Òxęïu£ú Although this version is longer than the previous version. experienced programmers would find it much easier to understand. . you too will learn to appreciate the elegance of more modular code. As you get used to reading and writing functions.

Local variables are distinct from variables of the same name that may be used elsewhere in the program. 2. ’ Functions can communicate information back to the caller through return values. Once a function is defined. The calling program is suspended. Formal parameters and other variables inside function definitions are local to the function. The values of actual parameters are assigned to the formal parameters. and the expressions appearing in a function call are known as actual parameters. 4. . 3. ꫔s‘ egf„‚™gIƒæ‡‘‚„‘ ÿ hjiCkmlniCoqpIrQi§sutqlnvxw%s “ër%iBA ¢ –•ÙŒsqi 1. it may be called multiple times from many different places in a program.¹H ¿HHs@tŒuxw†y|{‡}Q˜¨…€ƒ„ƒŸu‡}‘ç ꫔sr  ˜Ÿi„¤n…‚™g © ¦§›¥› ingIí ~zéH~ ’ A function is a kind of subprogram. ’ The scope of a variable is the area of the program where it may be referenced. Programmers rarely define their own functions. Programmers use functions to reduce code duplication and to help structure or modularize programs. Python functions may return multiple values. Functions ÐÁÓÇ½Æ . ’ A call to a function initiates a four step process: 1. Parameters allow functions to have changeable parts. that don’t explicitly return a value return the special object ’ Python passes parameters by value. Control returns immediately following the function call in the calling program. Value returning functions should generally be called from inside of an expression. The body of the function is executed. If the value being passed is a mutable object. then changes made to the object may be visible to the caller. The parameters appearing in the function definition are called formal parameters.

Every Python function returns some value. Information can be passed into a function through parameters. 6. A Python function definition begins with èÆHÍ Ã¨ÆHͽÒIÇ½Æ Í1ÉPÇ4ÑxÄ3Ò1ÁÓÇ a) b) c) èÆHÍ1ÉÇ d) 3. Formal and actual parameters are matched up by a) name b) position c) id d) interests 5. The part of a program that uses a function is called the a) user b) caller c) callee d) statement 2. Variables defined in a function are local to that function. 4. 6. actual parameters are passed to functions a) by value b) by reference c) at random d) by networking . In Python.~zé€r s@tŒuxw†y|{‡}½¹Pæé4{ÒêŠ 6 ŠŒ Ó ó …xŠ ³ y 6 ‚1ŠŒˆ 2. A function can send output back to the program with a(n) ÌÆ1ÄHÉÌ1Ç ¨Ì3Ò€Ç¨Ä a) b) c) assignment d) SASE 4. Python functions can never modify a parameter. ¶ 10. 8. a function can return only one value. In Python. In Python. Which of the following is not a step in the function calling process? a) the calling program suspends b) the formal parameters are assigned the value of the actual parameters c) the body of the function executes d) control returns to the point just before the function was called. 3. 9. some parameters are passed by reference. rBوtql™Í•ÙŒi Žª³  %v'l‡œ©i 1. 5. A function may only be called at one place in a program. It’s a bad idea to define new functions if it makes a program longer. One reason to use functions is to reduce code duplication. 7.

describe the two motivations for defining functions in your programs. Which of the following is not a reason to use functions? a) to reduce code duplication b) to make a program more modular c) to make a program more self-documenting d) to demonstrate intellectual superiority 8. Do programs that contain functions fit this model? Explain your answer. it should generally be called from a) an expression b) a different program Ê4Â¨Ò€Ç c) d) a cell phone ÌÆ1ÄHɨÌHÇ 9. we can think of functions as having input and output to communicate with the main program. (a) How does a program provide “input” to one of its functions? (b) How does a function provide “output” to the program? . Parameters are an important concept in defining functions. A function can modify the value of an actual parameter only if it’s a) mutable b) a list c) passed by reference d) a variable œ ¦lnsœmr%sslnvxw 1. In your own words. Functions can be thought of as miniature (sub)programs inside of other programs. If a function returns a value. A function with no statement returns ÐÁÓÇ½Æ a) nothing b) its parameters c) its variables d) 10. 2. 3. (a) What is the purpose of parameters? (b) What is the difference between a formal parameter and an actual parameter? (c) In what ways are parameters similar to and different from ordinary variables? 4. Like any other program.¹P âPCŽŒ{I} ³Œ6 ˆ–{ôˆ ~z途 7. We have been thinking about computer programs as sequences of instructions where the computer methodically executes one instruction and then moves on to the next one.

but be sure to choose something that makes the rhyme work (or almost work). Write a program to print the lyrics for ten verses of “The Ants Go Marching. The little one stops to suck his thumb.” Your program should print the lyrics for five different animals. there a moo. moo. The ants go marching one by one. Old MacDonald had a farm. Consider this very simple function: èÆPÍ¡ÑIɐˈÆæñë¦3ú¬÷ ÂxÇ@ÜIۈÆH̀ßS¦¡Y£¦¡Y£¦ ̨ÆHÄ1ÉÌHÇàÂÓÇ@ÜIۈÆ1Ì (a) What does this function do? (b) Show how a program could use this function to print the value of Ï assuming is a variable. Ee-igh. moo there. Ee-igh. moo here and a moo. Oh! With a moo. Ee-igh. dÐÔHþ The output from this fragment is . similar to the example verse below. Oh! 2. Ee-igh. hurrah! hurrah! The ants go marching one by one. Ee-igh.. Old MacDonald had a farm. Write a program to print the lyrics of the song “Old MacDonald.~zé ¯ s@tŒuxw†y|{‡}½¹Pæé4{ÒêŠ 6 ŠŒ Ó ó …xŠ ³ y 6 ‚1ŠŒˆ 5. You may choose your own activity for the little one in each verse. everywhere a moo. even though seems to change the value of to . ’”“fv••“H–B—$—˜l™wm•Sš#›§i•“¡œ©lnsi§s 1. Oh! And on that farm he had a cow. And they all go marching down.” A couple of sample verses are given below. Here a moo. . hurrah! hurrah! The ants go marching one by one.. Ee-igh. Explain why the output is not ÔPþÝÔPþ Ñ€ÉËˆÆ ÂÓÇ4܀ÛÆHÌ ÔHþ . (c) Here is a fragment of a program that uses this function: ÂÓÇ@ÜIۈÆ1ÌWß d Ìƽ܇É3À£ÄWßÿрɐˈÆæñôÞ3ú Ì3ÒIÇÄàÂxÇ@܀ÛÆHÌoõ ÌƈÜIɽÀ1Ä – ¸ .

hurrah! hurrah! The ants go marching two by two.. To get out.. Use two functions—one to compute the area of a pizza..¹P âPCŽŒ{I} ³Œ6 ˆ–{ôˆ ~z逴 In the ground. 6. Of the rain. Write definitions for the following two functions: ÜIÉHʧЄñùǓú returns the sum of the first n natural numbers. hurrah! hurrah! The ants go marching two by two.. In the ground. And they all go marching down.. ÜqÅˆÆH̨ÆgÛÁÀÓÉ1ÊÎÆæñè̈Â1ýҀÉ4ܨú radius. Write definitions for these functions: ÜqÅˆÆHÌ¨Æ Ú Ì¨Æ¨Â­ñ–̈Â1ýÒIÉ@ܨú Returns the surface area of a sphere having the Returns the volume of a sphere having the given given radius. To get out. The little one stops to tie his shoe. Then use these functions in a program that prompts a user for ø and prints out the sum of the first ø natural numbers and the sum of the cubes of the first n natural numbers. Of the rain. ÜIÉHʧÐ×Óɐ˽ƈܓñùǓú returns the sum of the cubes of the first n natural numbers... ÄPÌ3ÒHÂx§ Ç !¨ÀPƨԄU ï ¨Ï Use your function to augment so that it also displays the area of the triangle. Boom! Boom! Boom! The ants go marching two by two. Use your functions to solve Programming Exercise 1 from Chapter 3.. 4. 5. Write a function that computes the area of a triangle given the length of its three sides as parameters (see Programming Exercise 9 from Chapter 3)... and one to compute cost per square inch. . Redo Programming Exercise 2 from Chapter 3.. Boom! Boom! Boom! 3.

Demonstrate the function by writing a program that draws several faces of varying size in a single window. is an int. Modifies each entry in the list by converting it to a number. Write and test a function to meet this specification. 13. Solve Programming Exercise 17 from Chapter 3 using a function ǽ) Æ ¦HÄ ü ɽƽÜPܓñÒ!1ɽƈܐ܆õ5¦3ú that returns the next guess. and ü ̈  © Å 4ÎÒ€Ç ÛÎÒ€Ç ÛÎÒIÇ is a .~z逹 s@tŒuxw†y|{‡}½¹Pæé4{ÒêŠ 6 ŠŒ Ó ó …xŠ ³ y 6 ‚1ŠŒˆ 7. Modifies the list by squaring each entry. !h !h Your function can draw a simple smiley (or grim) face. ÃP̈ÂÓÛcDÂÑ1ƬñvѣƣÇĨÆHÌoõ ÜHÒ ¨Æ‰õ ÛÎÒIǓúYÑ1ÆÓÇÄÆ1Ì Ø¨ÁˆÒIÇÄ ÜPÒ Æ is a . 16. 10. Use your function to solve Programming Exercise 3 from Chapter 3. Do Programming Exercise 3 from Chapter 4 using a function that returns the letter grade for a score. . 11. 14. Write and test a function to meet this specification. Write and test a function to meet this specification. Write a function to compute the nth Fibonacci number. Use the functions from the previous three problems to implement a program that computes the sum of the squares of numbers read from a file. Your program should prompt for a file name and print out the sum of the ÌƨÂ1ÃÀ¨Ò€Ç½ÆˆÜ“ñ‡ú squares of the values in the file. Write and test a function to meet this specification. Hint: use 15. Write a function to meet this specification. 8. ÜIÉHʧ¤3ҐÜxĄñùǐÉ1ʆܨú ÇPÉHÊ“Ü is a list of numbers. 9. Do Programming Exercise 5 from Chapter 4 using a function that returns an acronym for a phrase supplied as a string. each of which represents a number. 12. ÄÁgÐ1ÉHʨ˽ÆHÌ3ܓñvÜxĐÌ)¤3ҐÜxÄ4úªÜxĐÌ)¤3ҐÜxÄ is a list of strings. Ü"í1ɽÂ1Ì¨Æ G !ḦÂHÐÆæñvÜPÑ1Á1Ìƽú ¨ÑǪ́Á£ÇÏÓʙñfÅ̈ÜÓÆ3ú ¨рÅoñðǐÉ1ʆܐú˜ÇÉ1栆 is a list of numbers. Draws a simple face of the given size in . Returns the sum of the numbers in the list.

Each time the user clicks. ~z逿 Use your function to write a program that draws a circle and then allows the user to click the window 10 times. the circle is moved where the user clicked. Moves so that ǽÆ1ÛאÆÓÇÄÆ1Ì is its center. .¹P âPCŽŒ{I} ³Œ6 ˆ–{ôˆ ÊÎÁgW¨Æg¨Áæñ‡Ü‡Å3½Ƅõ ½ Ç Æ£Ûˆ×PÆ£ÇĨÆHÌÎú ‡ Ü Å3Â½Æ is a graphics object that supports the !¨ÆHĨאÆÓÇÄÆ1Ì Ç½£ Æ Ûˆ×ÆÓÇĨÆHÌ Ø¨ÁˆÒ€Ç¨Ä ÜIŽÂ"ˆÆ method and is a .


we have mostly viewed computer programs as sequences of instructions that are followed one after the other. ’ To understand the concept of Boolean expressions and the ˽ÁÁÀ data type. but alone it is not sufficient to solve every problem. Sequencing is a fundamental concept of programming. and implement algorithms that employ decision structures. write. mentation using a Python ’ To understand the programming pattern multi-way decision and its impleÒ£Íc¨PƐÀÒ£Íc¨PƐÀˆÜ£Æ mentation using a Python statement.QSRUTWVYXa`cb0C 1 ¨S¨Èi g Æ —Æ  A¥襨¥§¦ ШÈg iqò x€y31‚„ƒ†…ˆ‡‰„‚„‘ ’ To understand the programming pattern simple decision and its impleÒ£Í mentation using a Python statement. Often it is necessary to alter the sequential flow of a program to suit the needs of q6D D . including those that employ sequences of decisions and nested decision structures. ’ To understand the programming pattern two-way decision and its impleÒ£Íc¨PƐÀˆÜ£Æ statement. ’ To be able to read. ’ To understand the idea of exception handling and be able to write simple exception handling code that catches standard Python run-time errors. r«”–“ ©«‡p›¥¤§j ‚ «ª‚„ƒæ‡‘ˆ‡™£eŸ‘ So far.

Susan Computewell is not a morning person. Here is the program as we left it: ó¡Ñ1ÁÓC Ç W¨ÆH̐ğU ï ¨Ï Ú Ìg ó Á !PÌ€ÊàĨÁàÑ1Á£c Ç WÆ1̐ÄÝ×PƨÀˆÜHҀÉ4Ü ÄƀC Ê 4ÜYÄE Á DˆÂxĄ̊ƣǐňƈÒxÄ óUËÏŸÆ ÷ ÅÓÉ4Ü1ÂÓÇ¡×PÁxc Ê ÉĨÆ1ÛƨÀÀ èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ Ñ1ƐÀˆÜPÒIÉ@ÜYß¡ÒIÇ©PÉĄñ"34HÅ3Â1ÄÐÒ¨ÜYÄ1ŽÆWאƐÀˆÜHҀÉ@Ü ÄÆxÊc½Æ1̈Â1Ä1Ę́ƧPS£ú ÍÂxÅÌÆÓǐňƈÒÓÄcßÝýnïù  Õ ŸS9„ïð@ Õ YWѣƨÀˆÜHҀÉ4ÜYáÝÞ¨Ô ̽ҀÇ Ä XHňÆcÄƀC Ê ½Æ1̈£ÄHĘ́ÆÝҐ% Ü ÎõlÍÂÓŨÌÆÓǐŽÆÒÓÄoõvÐÆ)!HÌƐƈÜYÍÂxĄ̊ƣǐňƈÒxęïq Ê4¨ҀÇoñIú This is a fine program as far as it goes. this was written by Susan Computewell to help her figure out how to dress each morning in Europe. Remember. sometimes she does not pay very close attention to the results. which are statements that allow a program to execute different sequences of instructions for different cases. we’ll take a look at decision structures. ¢I) Ç É¨Ä€ÄHňÆcÄÆxc Ê ½Æ1̈Â1Ä1Ę́ÆÝҀÇàÐ) Æ !HÌÆÆˆÜ ×ÆÀˆÜHҀÉ@Ü ñvÑHÂPÀÀÝÒxÄÿÑ1ƐÀˆÜPÒIÉ@ܐú רÂPÀÑIÉ3ÀÂ£ÄÆÈÍÂÓŨÌÆÓǐŽÆÒÓÄWˆÜÈc ý Ÿ)9ÐÑ1ƐÀˆÜPÒIÉ@ÜYáÐÞÔ Ä É¨g Ä PÉÄWͨÂÓĄ̊ƣÇPŽƈÒxÄ . For an easy example. With this specification in mind. we can design an enhanced algorithm. effectively allowing the program to “choose” an appropriate course of action. but we want to enhance it. Let’s say that any temperature over 90 degrees Fahrenheit deserves a heat warning. An extreme temperature is either quite hot or quite cold. Our enhancement to the program will ensure that when the temperatures are extreme. In this chapter. we’ll return to the Celsius to Fahrenheit temperature conversion program from Chapter 2. This is done with special statements known as control structures.rq77 s@tŒuxw†y|{‡}3¿Pæé4{ ³†6 ˆ 6 ‚HŠ x ˜ yè} … ³ yè…x}${ôˆ a particular situation. The first step is to fully specify the enhancement. and a temperature under 30 degrees warrants a cold warning. û ȃÊ'ÈƒÊ š#›§–B—$ٌ͕i ¨2ÿ i•—æÍ'i•“H–§t"r'“HiE¢â–%“8wQl™wm•'s Let’s start by getting the computer to make a simple decision. the program prints out a suitable warning so that Susan takes notice. and even though she has a program to convert the temperatures.

Once these instructions are done. is a flowchart showing the possible paths that can be taken through the algorithm. control passes to the next statement in the sequence (the one below).¿P ~x˜ 6 ƒ„w± { 4 é { ³†6 ˆ 6 ‚1ŠŒˆ Ò£ÍWͨÂÓŨÌÆ£ÇPŽÆÒÓÄ ( ýPÕ ¨Ì3ÒIÇÄà ŽƐÂ1ĀۈÂ1ÌHÇÎҀÇC! Ò£ÍWͨÂÓŨÌÆ£ÇPŽÆÒÓÄ ÞPÕ F ¨Ì3ÒIÇÄàÂÐÑ1ÁÀHÃcۈÂ1ÌHÇÎҀC Ç ! rq7H~ This new design has two simple decisions at the end. If the condition holds. Input Celsius Temperature Farenheit = 9/5 * celsius + 32 Print Fahrenheit fahrenheit > 90? yes no Print a Heat Warning fahrenheit < 30? yes no Print a Cold Warning Figure F . The indentation indicates that a step should be performed only if the condition listed in the previous line is met. The idea here is that the decision introduces an alternative flow of control through the program. If the condition is false. however. control then passes to the next statement. control transfers to the instructions in the box to the right. depend on the value of '  Figure . The exact set of steps taken by the algorithm will ͨÂÓŨÌÆ£ÇPŽÆÒÓÄ . Here is how the new design translates into Python code: . Ý : Flowchart of temperature conversion program with warnings. The diamond boxes show conditional decisions.

Notice that the body Ò£Í either executes or not depending on the condition. the condition in the heading is evaluated. our programs will use simple conditions that compare the values of two expressions. First. '  ÒÓÍ Figure . Ò£Í Ñ1ÁÓLjýÒxÄ3Ò£Á£Ç ( ÷ F ˈÁPÃPÏ ( F ˽ÁHÃPÏ Ò£Í The is just a sequence of one or more statements indented under the Ñ£Á£ÇcWÆHÌPĈԄïUÏ Ò£Í heading. û ȃÊ'È‘Ç ¢ vB“8—˜l™wm• Ø l™—æٌ͕i ¤ª §› vxw 'lŒtqlnvxw%s One point that has not yet been discussed is exactly what a condition looks like.rq7€r s@tŒuxw†y|{‡}3¿Pæé4{ ³†6 ˆ 6 ‚HŠ x ˜ yè} … ³ yè…x}${ôˆ ó¡Ñ1ÁÓÇCW¨ÆH̐ÄÔoïbÏ Ú ̨) ó Á !Ḧ€ÊÝÄÁ¡Ñ1ÁÓÇCW¨ÆH̐ĀאƐÀˆÜPÒIÉ@Ü Ä¨ÆxÊc@ÜYÄÁEDÂÓŨÌÆ£ÇPŽÆÒÓęï ó 1Å4Ò¨è Ü W¨ÆHÌ3ÜPÒ1ÁÓÇ Ò¨ÜPÜIɈƽܪňƨÂ1ÄÝÂÓLjáѣÁ¨À1ÃcÛ½Â1Ì1Ç4ÒIǧ!3ܬï èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ Ñ1ƐÀˆÜPÒIÉ@ÜYß¡ÒIÇ©PÉĄñ"34HÅ3Â1ÄÐÒ¨ÜYÄ1ŽÆWאƐÀˆÜHҀÉ@Ü ÄÆxÊc½Æ1̈Â1Ä1Ę́ƧPS£ú ÍÂxÅÌÆÓǐňƈÒÓÄcßÝýnïù  Õ ŸS9„ïð@ Õ YWѣƨÀˆÜHҀÉ4ÜYáÝÞ¨Ô ̽ҀÇ Ä XHňÆcÄƀC Ê ½Æ1̈£ÄHĘ́ÆÝҐ% Ü ÎõlÍÂÓŨÌÆÓǐŽÆÒÓÄoõvÐÆ)!HÌƐƈÜYÍÂxĄ̊ƣǐňƈÒxęïq ó€ØÌ½Ò€ÇĀۈÂ1Ì1Ç4ҀÇC!3Ü Í¨ÁHÌÐÆg¦PÄPÌÆxÊ3ÆUÄƀÊC4Ü Ò£ÍWͨÂÓĄ̊ƣÇPŽƈÒxÄ ( ýÕo÷ Ì3ÒIÇA Ä ¢xÄ ŒÜYÌƐÀPÀ1ÏUňÁHÄÐÁ£É¨Ä€ÄHňÆH̨Ƅõ ˽ÆàÑ1Â1̨ÆPÍ1ɽÀ Ò£ÍWͨÂÓĄ̊ƣÇPŽƈÒxÄ ÞÕo÷ F Ì3ÒIÇA Ä  ÌP̐̐ÌPÌ™ï ¨Æ¡ÜIɨÌÆcÄÁ€ÃHÌÆˆÜÜ ÛˆÂ1Ì£ÊÎÀ1Ïju  … ½ ž Ê4¨ҀÇoñIú Ò£Í You can see that the Python statement is used to implement the decision. of the Ò£Í control then passes to the next statement after the . ÒÓÍ The semantics of the should be clear from the example above. the statements in the body are skipped. and then control passes to the next statement in the program. In there are two statements. the sequence of statements in the body is executed. If the condition is true. ÒÓÍ The form of the is very similar to the pseudocode in the algorithm. This is a one-way or simple decision. shows the semantics of the as a flowchart. For the time being. If the condition is false. In either case. . both of which have a single statement in the body.

Ü : Control flow of simple if-statement .¿P ~x˜ 6 ƒ„w± { 4 é { ³†6 ˆ 6 ‚1ŠŒˆ rq7€” yes <condition> true? no <Statement> <Statement> <Statement> . GIH ÞQPSR£T HVUQW G R HVUQW P§T GIH ÞQPVRXT P©T is short for relational operator. shown in the following table. . That’s just a fancy name for the mathematical concepts like “less than” or “equal to. . Figure F . R G Python Y Y` `b` c` c e ` Mathematics Y a ` d c f` Meaning Less than Less than or equal to Equal to Greater than or equal to Greater than Not equal to .” There are six relational operators in Python.

I mentioned that there are several different ways of running Python programs. Some Python module files are designed to be run directly. Basically. º1º Conditions may compare either numbers or strings. When a Boolean expression is evaluated. Since Python uses the sign to º1º º indicate an assignment statement. this means that strings are put in alphabetic order according to the underlying ASCII codes. it produces a value of either true (the condition holds) or false (it does not hold). Other languages like Java and modern Python have a dedicated data type for Boolean expressions. after George Boole. these are often called “libraries. since “B” precedes “a”).” Other Python modules are designed primarily to be imported and used by other programs. “Bbbb” comes before “aaaa”. So all upper-case letters come before lower case letters (e.” Sometimes we want to create a sort of hybrid module . called a Boolean expression. the ordering is lexicographic. Boolean expressions are of type PÌHÉˆÆ DˆÂPÀˆÜÓÆ true and false are represented by the literals and . a different symbol is required for the concept in conditions. I should mention that conditions are actually a type of expression. Some languages such as C++ and older versions of Python just use the ints 1 and 0 to represent these values. a 19th century English mathematician. Here are a few interactive examples: Ì1É½Æ (©()( (©()( Þ F d Þ Y£d @ ހá d F DˆÂPÀˆÜÓÆ (©()( zňƨÀÀHÁ'ßPßAzňƨÀÀHÁ' Ì1É½Æ Á  ôŽƐÀÀPB Á  (©()( zňƨÀÀH' F DˆÂPÀˆÜÓÆ Á  ôŽƐÀÀPB Á  (©()( 3¢ƨÀÀH' F Ì1É½Æ û ȃÊ'È‘É š#›§–B—$ٌ͕i ¨ ª §› vxw 'lŒtqlnvxwQ–Qٔ’”“fv••“f–'— š#›§imœmrmtqlnvxw Back in Chapter 1. of equality. When comparing strings.g.rq7 ¯ s@tŒuxw†y|{‡}3¿Pæé4{ ³†6 ˆ 6 ‚HŠ x ˜ yè} … ³ yè…x}${ôˆ Notice especially the use of for equality. A common mistake in Python programs is using º where a is required.. ˽ÁPÁ¨À and the Boolean values In Python. These are usually referred to as “programs” or “scripts.

These programs are suitable for running directly. our current programs also run when they are imported into either an interactive Python session or into another Python program. when Python code is being run directly (not imported). the call to at the bottom must be made conditional. the variable inside the module |ÊÎÂ1Ä1Å . A simple decision should do the trick. Ê4Â¨Ò€Ç (or some the usual approach is to first import the module and then call its other function) each time we want to run it. Whenever a module is imported. it is nicer not to have modules run as they are imported. To see this in action. So far. Here is an example ÊÎÂ1ÄHÅ interaction showing what happens with the library: Ê ½ÁHÌPÄ Ê4£ÄHÅ (©()( ҇c ï Ì©ÌxÇ3€Ê3c Æ Ì)Ì (©()( Ê4£ÄHńH |ÊÎÂ1Ä1Å  ‘  Ç3ÂIÊÎÆ Ê4Â1Ä1Å You can see that. you just need to start Python and look at the value. Python Ç3ÂIÊÎÆ ÊÎÂÒ€Ç sets the value of to be . Python sets a special variable in the module Ç3ÂIÊÎÆ called to be the name of the imported module. when imported.¿P ~x˜ 6 ƒ„w± { 4 é { ³†6 ˆ 6 ‚1ŠŒˆ rq7€´ that can be used both as a stand-alone program and as a library that can be imported by other programs. Æ Ì)Ì (©()( Ì©ÌxÇ3€Ê3c ëÌ)̀ÊÎÂҀm Ç Ì©Ì  ‘   6 . Generally. most of our programs have had a line at the bottom to invoke the Ê4Â¨Ò€Ç function. Or you might type a command like ʈϨ͈ÒHÀPÆ ( b ï Ï F . When testing a program interactively. In a windowing environment. Ê4¨ҀÇoñIú As you know. you might run ¨ÏÄ1ŽÁ£Ç a file by (double-)clicking its icon. is assigned the string However. In a program designed to be either imported (without running) or run diÊ4ÂÒIÇ rectly. Since Python evaluates the lines of a module during the import process. this is what actually starts a program running. Ò£Í Ñ1ÁÓLjýÒxÄ3Ò£Á£Ç ( ÷ F Ê4¨ҀÇnñ‡ú We just need to figure out a suitable condition.

Putting the pieces together.rq7€¹ s@tŒuxw†y|{‡}3¿Pæé4{ ³†6 ˆ 6 ‚HŠ x ˜ yè} … ³ yè…x}${ôˆ So. the code in that module will see a variable called ǽ€Ê3Æ whose value is the name of the module. r«”–• —œ™hg£žSiæí «ª‚„ƒæ‡‘ˆ‡™£eŸ‘ Now that we have a way to selectively execute certain statements in a program using decisions. Here is the program as we left it: ó í1ɽÂHÃḦÂ1ĽҐÑæU ¥ ï Ï Ú ¨Ì) ó Á !ḦÂIÊàÄHŽÂ1ÄÿÑ1Á€C Ê PÉÄÆˆÜ Ä1ŽÆcÌƐÀŲÁÁHÄ3Ü ÁPÍÐT  í£É3ÂHÃḦ£Ä3ҐÑY) Æ í£É3Â1ĽÒ1ÁÓDŽï ó ¢£ÀÀÓÉ4ÜxÄP̈Â1Ä¨Æ½Ü É@ÜÓÆWÁP̀ÄHňÆYÊ4£ÄHÅÿÀÒIËÌÂ1̐ϟï ó ШÁHÄÆo÷îÄHÅÎÒ¨ Ü ¨Ì) Á !ḦÂIÊ ÑÓ̈܇ŽƽÜUң̀ÄHňÆW) Æ í£É3Â1ĽÒ1ÁÓǀÅ3ÂÜ Ç½ÁcÌƐÀŲÁÁHÄ3Üæï ҇Êc½Á1ÌÄ Ã¨ÆHÍ ÊÎÂ1ÄHÅ ó€ö½Â"ÎˆÆ½Ü ÄHŽÆYÊÎÂ1Ä1ÅÿÀҀ˨̈£̐ÏРˆ W ÂÒ1ÀÂxË3ÀPÆoï Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ Ä XHÅÎҨܨÌÁ)!ḦÂIÊàͽÒILjýÜYÄHŽÆc̨ƨÂPÀÐÜ£ÁÀÓÉĽÒ1ÁÓÇ@Ü Ä¨ÁÝÂEí1É3Â1ÃPÌÂ1Ä3ÒPÑQ ̽ҀÇÄ Â‰õ ˟õ Ñcß¡ÒIÇ©PÉĄñ"ŒØÀPƨÂÜ£ÆÈƣǨÄÆHÌWÄ1ŽÆàÑ£ÁÆPÍPͽÒPѐÒ1ÆÓÇÄ3Ü Ã½ÒÜP Ñ  ÁÁ1ĀßÈÊ4£ÄHńïôÜ"íH̐ĄñùËaY Ëv¨Ed¡Y€ÂSYÝÑú ÌÁPÁHÄ@Öªß ñ8¨ÓËàáWÈҨÜPÑ ˆÁPÁHÄ4ú§Ÿòñ†ÔSYc½ú ÌÁPÁHĈÔÈß ñ8¨ÓËa¨cÈҨÜPÑ ˆÁPÁHÄ4ú§Ÿòñ†ÔSYc½ú ̽ҀÇÄ ̽ҀÇÄXHňơܣÁÀÓÉĽÒ1ÁÓÇ@Ü ñz‰õ ˙õ Ѩú¬÷Óú £ÌÆo÷qÎõ ÌÁÁ1Ä@Ö@õlÌÁPÁHÄˆÔ . we can change the final lines of our programs to look like this: Ò£S Í Ì)ÌÓǽ€ÊΩ Æ Ì©ÌUßPß ëÌ)̀Ê4¨Ҁm Ç Ì©Ì ¨÷ Ê4¨ҀÇnñ‡ú   | f Ê4Â¨Ò€Ç This guarantees that will automatically run when the program is invoked directly. You will see a line of code similar to this at the bottom of virtually every Python program. the ǽ€ÊÎÆ Ê4Â¨Ò€Ç code will see that has the value . A module can determine how it is being used by inspecting this variable. When a file is run directly. if a module is imported. it’s time to go back and spruce up the quadratic equation solver from Chapter 3. but it will not run if the module is imported.

The problem with this code is that when µ †üú©ù is less than 0.¿P rP£ã@’“‚6i”¯ uôç1é4{ ³†6 ˆ 6 ‚1ŠŒˆ rq7€¿ Ê4¨ҀÇoñIú As noted in the comments. this program crashes when it is given coefficients of a quadratic equation that has no real roots. the program attempts to take the square root Ê4£ÄHÅ of a negative number. Here’s an example: Ê ½ÁHÌP¥ Ä í1ɽÂHÃḦÂ1Ä½ÒÑ (©()( ҇c HÅÎÒ¨ Ü ¨Ì) Á !ḦÂIÊàͽÒILjýÜYÄHŽÆc̨ƨÂPÀÐÜ£ÁÀÓÉĽÒ1ÁÓÇ@Ü Ä¨ÁÝE  í1É3Â1ÃPÌÂ1Ä3ÒPÑ ( ؈ÀHƨÂܣƀÆÓÇÄÆ1̀ÄHňÆàÑ1ÁPÆP͈͐ҐÑPÒ1ƣǨÄÎÜ ñ†Â‰õ ˟õ Ñú­÷֓õôÔæõ–Þ ÌÂѣƣË3¨ Ñ ÎòñvҀÇPǽÆ1Ì£ÊÎÁˆÜxÄWÀÂˆÜ€Ä4ú­÷ D3Ò1ÀP Æ  ÜxĐýÒIÇ ( 3õ˜À¨Ò€Ç½Æ Ö@õ Ò€Ï Ç P F D3Ò1ÀP Æ Xí1É3Â1ÃPÌÂ1Ä3ÒPщb ï # Ï 3õ¢À¨Ò€ÇˆÆWÔ3Ö@õ ҀÇÏP Ê4¨ҀÇnñ‡ú D3Ò1ÀP Æ Xí1É3Â1ÃPÌÂ1Ä3ÒPщb ï # Ï 3õ¢À¨Ò€ÇˆÆÿ Ö d„õ ҀÇcÊ4Â¨Ò€Ç Ã½ÒÜP Ñ  ÁÁ1ĀßÈÊ4£ÄHńïô" Ü íH̐Ąñùa Ë Y v Ë ¨Ed¡Y€S  YÝÑú ۈÂPÀÓÉˆÆ ÌPÌÁ1̙÷ŽÊÎÂ1Ä1ÅÐèÁ€Ê4ÂÒIÇàÆHÌPÌÁ1Ì G We can use a decision to check for this situation and make sure that the program can’t crash. Here’s a first attempt: ó í1ɽÂHÃḦÂ1ĽҐÑ1ÔoïU¨Ï ¥ ҇c Ê ½Á1ÌÄ ÊÎÂ1ÄHŠèÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ Ä XHÅÎҨܨÌÁ)!ḦÂIÊàͽÒILjýÜYÄHŽÆc̨ƨÂPÀÐÜ£ÁÀÓÉĽÒ1ÁÓÇ@Ü Ä¨ÁÝÂEí1É3Â1ÃPÌÂ1Ä3ÒPÑ xÇ ‰õ ˟õ Ñcß¡ÒIÇ©PÉĄñ"ŒØÀPƨÂÜ£ÆÈƣǨÄÆHÌWÄ1ŽÆàÑ£ÁÆPÍPͽÒPѐÒ1ÆÓÇÄ3Ü Ã½ÒÜPÑÓ̽҇ʡßUËâY Ëv¨Ed¡Y€ÂSYÝÑ Ò£ÍWÈҨÜPÑxÌ3ÒvÊ ( ßÝÕo÷ ýҨÜH Ñ  ÁÁHÄcßÈÊ4Â1Ä1ńïô" Ü íPÌPĄñ–ýҨÜHÑÓ̽҇ʭú ÌÁÁ1Ä@Ö ß©8 ñ ¨ÓËàáWýҐÜP Ñ  ˆÁÁ1Ä4§ ú Ÿ ñzS Ô Yc½ú ÌÁÁ1ĈÔUß©8 ñ ¨Óa Ë ¨cýҐÜP Ñ  ˆÁÁ1Ä4§ ú Ÿ ñzS Ô Yc½ú Ì3ÒIÇA Ä  Óc Ç HŽÆÐÜ£Á¨ÀxÉĽÒ1Á£Ç4ÜÈÂ1̨Ænu ÷ Îõl̨ÁÁHÄ4֓õl̨ÁÁ1ÄˆÔ ñz‰õ ˙õ Ѩú¬÷Óú u´ ´ Ê4¨ҀÇoñIú . the library reports an error. Since negative numbers do not have real roots.

We have two conditions in the program. when the program will simply skip the calculations and go to the next statement. ̽ҀÇÄ Incidentally. If is true then must be false and vice versa. Here’s what happens in an interactive session: ( ¹ HÅÎҨܨÌÁ)!ḦÂIÊàͽÒILjýÜYÄHŽÆc̨ƨÂPÀÐÜ£ÁÀÓÉĽÒ1ÁÓÇ@Ü (©()( í1ɽÂHÃPÌÂ1ĽҐÑHԄïÊÎÂҀÇoñIú ĨÁÝÂEí1É3Â1ÃPÌÂ1Ä3ÒPÑ ØˆÀHƨÂܣƀÆÓÇÄÆ1̀ÄHňÆàÑ1ÁPÆP͈͐ҐÑPÒ1ƣǨÄÎÜ (©()( ñ†Â‰õ ˟õ Ñú­÷֓õôÔæõ–Þ This is almost worse than the previous version. illustrates the situation. We could accomplish this by adding another simple decision at the end of the program. What happens when the equation has no real roots? Ò£Í Ë Y€a Q Ë ¨Ed§YHC  YPÑ is less than zero. Based on the value of the program should either print that there are no real roots or it should calculate and display the roots.rq7€â s@tŒuxw†y|{‡}3¿Pæé4{ ³†6 ˆ 6 ‚HŠ x ˜ yè} … ³ yè…x}${ôˆ This version first computes the value of the discriminant ( µ †Vú©ù ) and then checks to make sure it is not negative. you hadn’t yet learned about the first time we encountered this program. Only then does the program proceed to take the square root and calculate the solutions. a two-way decision can be implemented by attaching an Ò£Í ÒÓC Í ¨HƨÀˆÜÓÆ clause onto an clause. Study the program for a moment. This program will never Ê4£ÄHÅhïz" Ü íHÌÄ Ã½ÒÜPÑxÌ3Ò‡Ê attempt to call when is negative. According to the semantics for a simple . Ò£ÍWÈҨÜHÑÓÌ3ÒvÊ Õn÷ F ̽ҀÇ Ä XHňÆWÆ)í£É3Â1ĽÒ1ÁÓÇcÅ3ÂÜ Ç½Á€ÌƐÀĘ̀ÁÁ1ÄÎÜ{ž This will certainly solve our problem. but this solution just doesn’t feel right. because it does not give users any indication of what went wrong. We have programmed a sequence of two decisions. but there is really only ÈҨÜPÑxÌ3ÒvÊ one decision to make. this updated version is not really a complete solution. A better program would print a message telling users that their particular equation has no real solutions. Since there is no next statement. Figure . ' ! This is an example of a two-way decision. the program just quits. you might also notice that I have replaced the bare statements from the original version of the program with embedded newlines to put ‡Ç whitespace in the output. . ƨÀÜ£Æ In Python. The result is called an statement. but the two outcomes are ÈҨÜPÑxÌ3ÒvÊ ( ßÝÕ Ã½ÒÜPÑÓÌ½Ò‡Ê Õ F mutually exclusive. Unfortunately. it just leaves them hanging.

Ñ1ÁÓLjýÒxÄ3Ò£Á£Ç ( ÷ ܀ĈÂ1ĨÆxÊ3Æ£ÇÄ3Ü F ƨÀÜ£Æo÷ ܀ĈÂ1ĨÆxÊ3Æ£ÇÄ3Ü F ( ( F Ò£Í When the Python interpreter encounters this structure. Using a two-way decision in the quadratic solver yields a more elegant solution. ƨÀˆÜÓÆ are executed. If the condition is true. : Quadratic solver as a two-way decision. In either If the condition is false.¿P rP£ã@’“‚6i”¯ uôç1é4{ ³†6 ˆ 6 ‚1ŠŒˆ rq7€é no discrim < 0? yes Calculate roots Print “no roots” ' ! Figure . ó¥í1ɽÂHÃḦÂ1ĽҐѣÞnïU¨Ï ҇c Ê ½Á1ÌÄ ÊÎÂ1ÄHŠèÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ Ä XHÅÎҨܨÌÁ)!ḦÂIÊàͽÒILjýÜYÄHŽÆc̨ƨÂPÀÐÜ£ÁÀÓÉĽÒ1ÁÓÇ@Ü Ä¨ÁÝÂEí1É3Â1ÃPÌÂ1Ä3ÒPÑ xÇ ‰õ ˟õ Ñcß¡ÒI© Ç PÉĄ" ñ ŒØÀPƨÂÜ£ÆÈƣǨÄÆHÌWÄ1ŽÆàÑ£ÁÆPÍPͽÒPѐÒ1ÆÓÇÄ3Ü ñz‰õ ˙õ Ѩú¬÷Óú ýҐÜPÑÓ̽҇ʡßUËâY Ëv¨Ed¡Y€ÂSYÝÑ Ò£ÍWÈҨÜPÑxÌ3ÒvÊ Õn÷ F Ì3ÒIÇA Ä  Óc Ç HŽÆcÆ)í1ɽÂ1ĽÒ1Á£ÇcÅ3ÂˆÜ ÇˆÁcÌƐÀUÌÁPÁHÄ3Ü{u ƨÀÜ£Æn÷ u´ ´ . the statements under the are executed. control then passes to the statement following the . it will first evaluate the Ò£Í condition. the statements under the ÒÓÍC¨PƐÀˆÜÓÆ case.

However.r1~37 s@tŒuxw†y|{‡}3¿Pæé4{ ³†6 ˆ 6 ‚HŠ x ˜ yè} … ³ yè…x}${ôˆ ýҨÜH Ñ  ÁÁHÄcßÈÊ4Â1Ä1ńïôÜ"íPÌPĄñùËaY Ëa¨Td¡Y€ÂSYÐѨú ÌÁÁ1Ä@Ö ß©ñ8¨ÓËàáWýҐÜPÑ ˆÁÁ1Ä4ú§Ÿ ñzÔSYc½ú ÌÁÁ1ĈÔUß©ñ8¨ÓËa¨cýҐÜPÑ ˆÁÁ1Ä4ú§Ÿ ñzÔSYc½ú Ì3ÒIÇÄ Ì3ÒIÇA Ä  Óc Ç HŽÆÐÜ£Á¨ÀxÉĽÒ1Á£Ç4ÜÈÂ1̨Æn÷uÎõl̨ÁÁHÄ4֓õl̨ÁÁ1ÄˆÔ Ê4¨ҀÇoñIú ´ This program fills the bill nicely. the output might be confusing to some users. Perhaps the program should be a bit more informative to avoid confusion. It looks like the program has mistakenly printed the same number twice. Here is a sample session that runs the new program twice: HÅÎҨܨÌÁ)!ḦÂIÊàͽÒILjýÜYÄHŽÆc̨ƨÂPÀÐÜ£ÁÀÓÉĽÒ1ÁÓÇ@Ü (©()( í1ɽÂHÃPÌÂ1ĽҐÑ1ÞoïÊÎÂҀÇoñIú ĨÁÝÂEí1É3Â1ÃPÌÂ1Ä3ÒPÑ ØˆÀHƨÂܣƀÆÓÇÄÆ1̀ÄHňÆàÑ1ÁPÆP͈͐ҐÑPÒ1ƣǨÄÎÜ HňÆWÆ)í£É3Â1ĽÒ1ÁÓÇcÅ3ÂÜ ñ†Â‰õ ˟õ Ñú­÷֓õôÔæõ–Þ Ç Á€ÌƐÀĘ̀ÁÁ1ÄÎÜ{ ½ (©()( í1ɽÂHÃPÌÂ1ĽҐÑ1ÞoïÊÎÂҀÇoñIú HÅÎҨܨÌÁ)!ḦÂIÊàͽÒILjýÜYÄHŽÆc̨ƨÂPÀÐÜ£ÁÀÓÉĽÒ1ÁÓÇ@Ü Ä¨ÁÝÂEí1É3Â1ÃPÌÂ1Ä3ÒPÑ ØˆÀHƨÂܣƀÆÓÇÄÆ1̀ÄHňÆàÑ1ÁPÆP͈͐ҐÑPÒ1ƣǨÄÎÜ HňơܣÁÀÓÉĽÒ1ÁÓÇ@Ü r«”– ñ†Â‰õ ˟õ Ñú­÷˜Ô‰õ¡d„õ‡Ö £ÌÆo÷ƨPÕnïðÔPýÔ)eýPÞ¨Ô½Öe©e3ÖxÞ`¨3ֆïðþPՐþÎրՐøPþ©eÎÖPÖxý «ª‚„ƒæ‡‘ˆ‡™£eŸ‘ kp¦•j …‡pg1žSiæí The newest version of the quadratic solver is certainly a big improvement. but it still has some quirks. . Here is another example run: HÅÎҨܨÌÁ)!ḦÂIÊàͽÒILjýÜYÄHŽÆc̨ƨÂPÀÐÜ£ÁÀÓÉĽÒ1ÁÓÇ@Ü (©()( í1ɽÂHÃPÌÂ1ĽҐÑ1ÞoïÊÎÂҀÇoñIú ĨÁÝÂEí1É3Â1ÃPÌÂ1Ä3ÒPÑ ØˆÀHƨÂܣƀÆÓÇÄÆ1̀ÄHňÆàÑ1ÁPÆP͈͐ҐÑPÒ1ƣǨÄÎÜ HňơܣÁÀÓÉĽÒ1ÁÓÇ@Ü ñ†Â‰õ ˟õ Ñú­÷֓õ ԉõªÖ £ÌÆo÷ƨ3Ö­ïùÕ¥¨3ֆïðÕ This is technically correct. the given coefficients produce an equation that has a double root at -1.

There is another way to write multi-way decisions in Python that preserves the semantics of the nested structures but gives it a more appealing look.) The ÒÓC Í ¨PƐÀˆÜÓÆ Æ¨ÀÜ£Æ dashed box contains the second nested comfortably inside the part of the top-level decision. In this case. . ýҐÜPÑ ˆÁÁ1Ä is also 0. Here’s a quick sketch of the design: ïïPï ףňƈ Ñ ÎWÄHňE Æ WˆÂÀxɽÆWÁHÍWýҨÜHÑÓÌ½Ò‡Ê ÛPÅˆÆ£Ç Õn÷ ŽÂÓÇÃÀPÆÈÄHŽÆàÑ1ˆÜÓÆWÁPÍUǽÁc̨ÁÁ1ÄÎÜ F ÛPňƣÇàßÝÕn÷ ŽÂÓÇÃÀPÆÈÄHŽÆàÑ1ˆÜÓÆWÁPÍÐÂcèÁÓɐ˽ÀPÆcÌÁPÁHÄ ÛPÅˆÆ£Ç ( Õn÷ ŽÂÓÇÃÀPÆÈÄHŽÆàÑ1ˆÜÓÆWÁP̀ÄPÛÁ€Ã½ÒÜxÄ3ÒIÇ4ÑxÄcÌÁPÁHÄ3Üæï ÒÓC Í ¨HƨÀˆÜÓÆ One way to code this algorithm is to use two statements. (Treat the dashed box as one big statement. and both roots have the value · % & . but the implementation doesn’t feel quite right. The resulting code does not reflect the true three-fold decision of the original problem. you will see that there are exactly ÈҨÜPÑxÌ3ÒvÊ three possible paths. including other Ò£Í ÒÓC Í ¨PƐÀˆÜÓÆ or statements. If we want to catch this µ special case.A ' # flowchart of this solution is shown in Figure . Putting one compound statement inside of another is called nesting. our program actually needs a three-way decision. We have finessed a three-way decision by using two two-way decisions. The body Ò£Í ÆÀˆÜ£Æ of an or clause can contain any legal Python statements. we have a working solution. You can see that the top-level Ò£c Í ¨PƐÀˆÜ£Æ structure is just an . Once again. Here’s a fragment of code that uses nesting to achieve a three-way decision: : Ò£ÍWÈҨÜHÑÓÌ3ÒvÊ Õn÷ F ̽ҀÇ Ä  í£É3£Ä3Ò1ÁÓǀÅ3ÂܪǽÁ€Ì¨Æ¨ÂÀ ÌÁÁ1ÄÎm Ü  G ƨÀÜ£Æo÷ Ò£ÍWÈҨÜPÑxÌ3ÒvʡߐßÝÕo÷ ÌÁÁ1ÄW@ ß ¨Óa Ë Ÿòñ†S Ô Ycˆú Ì3ÒIÇA Ä 3HňÆHÌÆÝÒ¨ÜUۏÁÓɐË3ÀHÆUÌÁPÁHÄà£# Ä Îõ ÌÁÁ1Ä Æ¨ÀÜ£Æn÷ ó ˆÁ¡ÜxÄ1ɈÍPÍWͨÁHÌWÄHۈÁc̨ÁÁHÄ3Ü r1~€~ ž If you trace through this code carefully. The sequencing is determined by the value of . Imagine if we needed to make a five-way decision using this Ò£c Í ¨PƨÀÜ£Æ technique.¿H ”H¨äa…± y 6 i”¯ uôç2é4{ ³Œ6 ˆ 6 ‚1ŠŒˆ ÈҨÜPÑxÌ3ÒvÊ The double-root situation occurs when is exactly 0. The . The structures would nest four levels deep. and the Python code would march off the right-hand edge of the page.

. the statements under the are performed. ƨÀˆÜÓÆ Ò£Í idea is to combine an followed immediately by an into a single clause ƐÀÒÓÍ (pronounced “ell-if”). and control passes to the next statement after the entire . Python will evaluate each condition in turn looking for the first one that is true. it is possible that no indented statement block will be executed. ƨÀÜ£Æ If none of the conditions are true. the statements indented under that condition are exÒ£C Í ¨HƨÀ¨Ò£C Í ¨HƨÀÜ£Æ ecuted. ƐÀˆÜÓÆ The clause is optional. if omitted. called an Ò£Í Ñ1ÁÓLjýÒxÄ3Ò£Á£Ç†Ö ( ÷ F Ñ1ˆܣÆ3ÖUÜxÄÂ1ĨÆxÊÎÆÓÇÄ3Ü ( F ƨÀ¨Ò£Í Ñ1Á£ÇýÒxÄ3Ò1ÁÓÇ3Ô ( ÷ F Ñ1ˆܣƐÔÐÜxÄÂ1ĨÆxÊÎÆÓÇÄ3Ü ( F ƨÀ¨Ò£Í Ñ1Á£ÇýÒxÄ3Ò1ÁÓÇ½Þ ( ÷ F Ñ1ˆܣÆPÞàÜxÄÂ1ĨÆxÊÎÆÓÇÄ3Ü ( F ïïPï ƨÀÜ£Æo÷ ÐÆPÍÂxÉ3À£Ä¡ÜxÄÂ1ĨÆxÊÎÆÓÇÄ3Ü ( F This form is used to set off any number of mutually exclusive code blocks. If a true condition is found.r1~†r s@tŒuxw†y|{‡}3¿Pæé4{ ³†6 ˆ 6 ‚HŠ x ˜ yè} … ³ yè…x}${ôˆ yes discrim < 0? no Print "no roots" yes discrim == 0? no Do Double Root Do Unique Roots ' # Ò£Íc¨PƨÀÜ£Æ Figure . : Three-way decision for quadratic solver using nested .

ó í1ɽÂHÃḦÂ1ĽҐ" ¥ Ñ dŸU ï ¨Ï ҇c Ê ½Á1ÌÄ ÊÎÂ1ÄHŠèÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ Ä XHÅÎҨܨÌÁ)!ḦÂIÊàͽÒILjýÜYÄHŽÆc̨ƨÂPÀÐÜ£ÁÀÓÉĽÒ1ÁÓÇ@Ü Ä¨ÁÝÂEí1É3Â1ÃPÌÂ1Ä3ÒPÑ xÇ ‰õ ˟õ Ñcß¡ÒIÇ©PÉĄñ"ŒØÀPƨÂÜ£ÆÈƣǨÄÆHÌWÄ1ŽÆàÑ£ÁÆPÍPͽÒPѐÒ1ÆÓÇÄ3Ü Ã½ÒÜPÑÓ̽҇ʡßUËâY Ëv¨Ed¡Y€ÂSYÝÑ Ò£ÍWÈҨÜPÑxÌ3ÒvÊ Õn÷ F Ì3ÒIÇA Ä  Óc Ç HŽÆcÆ)í1ɽÂ1ĽÒ1Á£ÇcÅ3ÂˆÜ ÇˆÁcÌƐÀUÌÁPÁHÄ3Ü{u ƨÀ¨Ò£ÍWýҐÜPÑxÌ3҇ÊÐߐßÐÕn÷ ÌÁÁ1ÄW@ ß ¨Óa Ë Ÿòñ†S Ô Ycˆú Ì3ÒIÇA Ä  Óc Ç HŽÆ1ÌÆÐҐÜUÂcèÁÓɐË3ÀHÆUÌÁPÁHÄà£Ä#Îõ¢Ì¨ÁÁ1Ä Æ¨ÀÜ£Æn÷ ýҨÜH Ñ  ÁÁHÄcßÈÊ4Â1Ä1ńïô" Ü íPÌPĄñùa Ë Y a Ë ¨Td¡Y€S  YÐѨú ÌÁÁ1Ä@Ö ß©8 ñ ¨ÓËàáWýҐÜP Ñ  ˆÁÁ1Ä4§ ú Ÿ ñzS Ô Yc½ú ÌÁÁ1ĈÔUß©8 ñ ¨Óa Ë ¨cýҐÜP Ñ  ˆÁÁ1Ä4§ ú Ÿ ñzS Ô Yc½ú Ì3ÒIÇA Ä  Óc Ç HŽÆÐÜ£Á¨ÀxÉĽÒ1Á£Ç4ÜÈÂ1̨Ænu ÷ Îõl̨ÁÁHÄ4֓õl̨ÁÁ1ÄˆÔ Ê4¨ҀÇoñIú ñz‰õ ˙õ Ѩú¬÷Óú r1~†” u´ ´ ´ ´ r«”|µ egf„ƒ¬‚Ÿ¤n…ˆ‡™£e ¶ªi„e™·£j‡penš Our quadratic program uses decision structures to avoid taking the square root of a negative number and generating an error at run-time. In the case of the quadratic solver. Sometimes functions themselves check for possible errors and return a special value to indicate that the operation was unsuccessful. ýҐÜP Ñ  ¨ÄWßÐÁHÄ1ŽÆ1§ Ì ÅgíH̐ĉñð• Ë YIS Ë ¨Ed§YHc  YÑú . The program would check the result of the operation with a decision. For example. we checked the data before the call to the Ü íHÌÄ " function. a different square root operation might return a negative number (say. †1… ) to indicate an error. Since the square roots of real numbers are never negative. this value could be used to signal that an error has occurred. This is a common pattern in many programs: using decisions to protect against rare but possible errors.¿H ¯ CŽ ³ {Iwzy 6 ‚HŠq°4uxŠv‹± 6 ŠŒ ÒÓC Í ¨HƨÀÒÓC Í ¨HƨÀˆÜÓÆ Using an to show the three-way decision in our quadratic solver yields a nicely finished program.

” We’re not going to discuss all the details of the Python exception handling mechanism here. and if any problem crops up. exception handling is done with a special control structure that is similar to a decision.r1~ ¯ s@tŒuxw†y|{‡}3¿Pæé4{ ³†6 ˆ 6 ‚HŠ x ˜ yè} … ³ yè…x}${ôˆ Ò£ÍWÈҨÜHÑ ¨Ä Õo÷ F ̽ҀÇÄXÐÁc̨ƨÂPÀUÌÁÁ1ÄÎܬïq ƨÀÜ£Æo÷ ïïPï Sometimes programs become so peppered with decisions to check for special cases that the main algorithm for handling the run-of-the-mill cases seems completely lost. but I do want to give you a concrete example so you can see how exception handling works and understand programs that use it. a program with exception handling can in essence say. Programming language designers have come up with mechanisms for exception handling that help to solve this design problem. handle it this way. The idea of an exception handling mechanism is that the programmer can write code that catches and deals with errors that arise when the program is running. In Python. “Do these steps. Rather than explicitly checking that each step in the algorithm was successful. Let’s start with a specific example and then take a look at the general approach. Here is a version of the quadratic program that uses Python’s exception Ê4£ÄHÅhïz" Ü íHÌÄ function: mechanism to catch potential errors in the ó í1ɽÂHÃḦÂ1ĽҐ ¥ Ñ 9oU ï ¨Ï ҇c Ê ½Á1ÌÄ ÊÎÂ1ÄHŠèÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ Ä XHÅÎҨܨÌÁ)!ḦÂIÊàͽÒILjýÜYÄHŽÆc̨ƨÂPÀÐÜ£ÁÀÓÉĽÒ1ÁÓÇ@Ü Ä¨ÁÝÂEí1É3Â1ÃPÌÂ1Ä3ÒPÑ xÇ ĐÌPϙ÷ u´ ‰õ ˙õ ÑUß¡ÒI© Ç É¨Ä„" ñ ŒØˆÀHƨÂÜ£ÆÈÆ£ÇĨÆHÌWÄ1ŽÆàÑ1ÁPÆPÍPͽҐÑPÒ1ÆÓÇÄÎÜÿñ†Âæõ ™ Ë õ Ѩú¬÷£ú à ҨÜHÑ ÁÁHÄcßÈÊ4Â1Ä1ńïôÜ"íPÌPĄñùËaY Ëa¨Td¡Y€ÂSYÐѨú ½ ÌÁÁ1Ä@Ö ß©ñ8¨ÓËàáWýҐÜPÑ ˆÁÁ1Ä4ú§Ÿ ñzÔSYc½ú ÌÁÁ1ĈÔUß©8 ñ ¨Óa Ë ¨cýҐÜP Ñ  ˆÁÁ1Ä4§ ú Ÿ ñzÔSYc½ú Ì3ÒIÇA Ä  Óc Ç HŽÆÐÜ£Á¨ÀxÉĽÒ1Á£Ç4ÜÈÂ1̨Ænu ÷ Îõl̨ÁÁHÄ4֓õl̨ÁÁ1ÄˆÔ Æ)¦ˆÑ1Æ ¨T Ä ÛˆÂPÀÓÉˆÆ ÌPÌÁ1̙÷ G Ì3ÒIÇA Ä  Óc Ç ÐÁcÌƐÀĘ̀ÁÁ1ÄÎ% Ü  Ê4¨ҀÇoñIú ´ ´ Notice that this is basically the very first version of the quadratic program .

ېÀÓÉˆÆ ÌÌÁ1Ì Æg¦½Ñ£Æ Ä G . control then passes ÄP̐ϙïPïïùÆ)¦½Ñ£Æ ¨Ä to the next statement after the . the exception handler catches the error and prints a message indicating that the equation does not have real roots. The original program without the exception-handling produced the following error: ÌÂѣƣË3¨ Ñ ÎòñvҀÇPǽÆ1Ì£ÊÎÁˆÜxÄWÀÂˆÜ€Ä4ú­÷ D3Ò1ÀP Æ  ÜxĐýÒIÇ ( 3õ˜À¨Ò€Ç½Æ Ö@õ Ò€Ï Ç P F D3Ò1ÀP Æ Xí1É3Â1ÃPÌÂ1Ä3ÒPщb ï # Ï 3õ¢À¨Ò€ÇˆÆÿÖxމõ Ò€Ï Ç P ýҐÜP Ñ  ÁÁ1ĀßÈÊ4£ÄHńïô" Ü íH̐Ąñùa Ë Y v Ë ¨Ed¡Y€S  YÝÑú ۈÂPÀÓÉˆÆ ÌPÌÁ1̙÷ŽÊÎÂ1Ä1ÅÐèÁ€Ê4ÂÒIÇàÆHÌPÌÁ1Ì G The last line of this error message indicates the type of error that was generated. there are lots of other things that could go wrong besides having a bad set of coefficients. in the quadratic solver. For example. If these statements execute without error. If an error occurs somewhere in Æ ¦ˆÑ1Æ ¨Ä ) the body. Python looks for an clause with a matching error type. and hopefully. provide a graceful exit. the program generates a differېÀÓÉˆÆ ÌÌÁ1Ì ent kind of (“unpack tuple of wrong size”). If the user accidentally G . A statement has the general form: ĐÌPϙ÷ ˈÁPÃPÏ ( F Æ ¦ˆÑ1" ) Æ Ä ÌÌ¨ÁH) Ì g Ï ˆÆ ( ÷ F G ŽÂÓLjèÀPÆ1Ì ( F r1~†´ ĐÌPÏ When Python encounters a statement. the handler code is executed. ĐÌPϙïïPïðg Æ ¦½Ñ1" Æ Ä The nice thing about the statement is that it can be used to catch any kind of error. If a Æ ¦ˆÑ1Æ ¨Ä ) suitable is found. even ones that might be difficult to test for. If the user fails to type the correct number of inputs.¿H ¯ CŽ ³ {Iwzy 6 ‚HŠq°4uxŠv‹± 6 ŠŒ Đ̐ϟïïPïð) Æ ¦ˆÑ1Æ"Ä ÄÌÏ with the addition of a around the heart of the program. G Here is the error handling version in action: HÅÎÒ¨ Ü ¨Ì) Á !ḦÂIÊàͽÒILjýÜYÄHŽÆc̨ƨÂPÀÐÜ£ÁÀÓÉĽÒ1ÁÓÇ@Ü Ä¨ÁÝE  í1É3Â1ÃPÌÂ1Ä3ÒPÑ ØˆÀHƨÂܣƀÆÓÇÄÆ1̀ÄHňÆàÑ1ÁPÆP͈͐ҐÑPÒ1ƣǨÄÎÜ ÐÁc̨ƨÂPÀUÌÁÁ1ÄÎÜ ñ†Â‰õ ˟õ Ñú­÷֓õôÔæõ–Þ Instead of crashing. The updated version of the program provides an namely an ۈÀxÉ½Æ ÌÌ¨ÁHÌ clause to catch the . it attempts to execute the statements inside the body.

If G the user types in a valid Python expression that produces non-numeric results. Å£ÏHǨĈÂg¦ ÌPÌÁHÌ If the input is not a valid Python expression. If an error occurs. A single statement can have multiple G Æ ¦ˆÑ1" ) Æ Ä clauses to catch various possible classes of errors.r1~†¹ s@tŒuxw†y|{‡}3¿Pæé4{ ³†6 ˆ 6 ‚HŠ x ˜ yè} … ³ yè…x}${ôˆ ЈÂIÊÎÆ ÌÌ¨ÁHÌ types an identifier instead of a number. it generates a . PÏg½Æ ÌPÌÁHÌ ÄÌÏ the program generates a . Here’s one last version of the program designed to robustly handle any possible errors in the input: ó í1ɽÂHÃḦÂ1ĽҐѣønU ¥ ï ¨Ï ҇c Ê ½Á1ÌÄ ÊÎÂ1ÄHŠèÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ Ä XHÅÎҨܨÌÁ)!ḦÂIÊàͽÒILjýÜYÄHŽÆc̨ƨÂPÀÐÜ£ÁÀÓÉĽÒ1ÁÓÇ@Ü Ä¨ÁÝÂEí1É3Â1ÃPÌÂ1Ä3ÒPÑ xÇ ĐÌPϙ÷ ‰õ ˙õ ÑUß¡ÒI© Ç É¨Ä„" ñ ŒØˆÀHƨÂÜ£ÆÈÆ£ÇĨÆHÌWÄ1ŽÆàÑ1ÁPÆPÍPͽҐÑPÒ1ÆÓÇÄÎÜÿñ†Âæõ ˙õ Ѩú¬÷£ú à ҨÜHÑ ÁÁHÄcßÈÊ4Â1Ä1ńïôÜ"íPÌPĄñùËaY Ëa¨Td¡Y€ÂSYÐѨú ½ ÌÁÁ1Ä@Ö ß©ñ8¨ÓËàáWýҐÜPÑ ˆÁÁ1Ä4ú§Ÿ ñzÔSYc½ú ÌÁÁ1ĈÔUß©8 ñ ¨Óa Ë ¨cýҐÜP Ñ  ˆÁÁ1Ä4§ ú Ÿ ñzÔSYc½ú Ì3ÒIÇA Ä  Óc Ç HŽÆÐÜ£Á¨ÀxÉĽÒ1Á£Ç4ÜÈÂ1̨Ænu ÷ Îõl̨ÁÁHÄ4֓õl̨ÁÁ1ÄˆÔ ¨T Ä ÛˆÂPÀÓÉˆÆ ÌPÌÁ1Ìnõ¢g Æ ¦½Ñ Ä Ë ÷ G ï ʆ" Ü !Wßÿ܀Đ̉ñz) Æ ¦ˆÑ Ä Ë ú ï Ò£Í Ê† Ü !WߐA ß èÊ4Â1Ä1ÅÐèÁ€Ê4¨ҀǡÆHÌPÌÁ1# Ì @÷ ¨Ì3ÒIÇA Ä 3У Á  ˆÆÂ` À  ÁÁHÄ3% Ü  ƨÀÒÓÍYʆ Ü !Wߐ& ß zÉP© Ç ½Â Ñ ÎcÄH) É 3ÀPÆWÁHÍc̨ۨÁ£§ Ç !àÜPÒ ' Æ 4÷ ¨Ì3ÒIÇA Ä  Á£ÉàÃˆÒ£Ã£Ç ðT Ä !½" Ò W¨Æ ÊÎƀÄ1ŽÆcÌ3" Ò !1ŨÄUǐÉ1Ê˽Æ1ÌÝÁPÍ¡Ñ£ÁÆH͐ͽÒPѐңƣÇÄ3Üæïu ƨÀˆÜÓÆn÷ ¨Ì3ÒIÇA Ä uÅPÁxÊ3ÆHÄ1Å4ҀC Ç !ÈÛÆ£ÇĀېÌÁÓ§ Ç !oõÜ£ÁHÌP̐j Ï u ¨T Ä ÐˆÂIÊÎÆ ÌÌ¨ÁH̟÷ G Ì3ÒIÇA Ä  ÓÇ Á£ÉÝÃ½Ò£Ã£Ç ùÄÝƣǨÄÆHÌWÄ1ÅÌ¨ÆÆ ÇPÉHÊˈÆHÌ3Üæq ï  ¨T Ä  Ï ½Æ ̨̐ÁH̟÷ G Ì3ÒIÇA Ä  ÓÇ Á£É¨Ì¡Ò€) Ç É¨ÄÎÜ ÛÆHÌÆÈLjÁHÄàÂPÀÀ ǐÉ1ÊˈÆHÌÎܬq ï  ¨S Ä Å1Ï1ÇÄg  ¦ ̨̐ÁH̙÷ G Ì3ÒIÇA Ä  ÓÇ Á£É¨Ì¡Ò€) Ç É¨ÄcÛ½ÂÜ Ç½ÁHÄÿÒIÇÐÄHňÆàÑ1ÁHÌPÌÆÑÓÄW͐ÁḤʕï öÎҐܐÜHҀ§ Ç !ÐÑ1ÁxÊPÊ4c  PQ ¨Ä™÷ Ì3ÒIÇA Ä  Óm Ç ÅPÁxÊ3ÆHÄ1Å4ҀC Ç !ÈÛÆ£ÇÄUÛ¨ÌÁÓ§ Ç !„õ Ü£Á1̐̐j Ï u u´ Æ)¦ˆÑ1Æ ´ “ ‘ !h Æ)¦ˆÑ1Æ Æ)¦ˆÑ1Æ Æ)¦ˆÑ1Æ Æ)¦ˆÑ1Æ Ê4¨ҀÇoñIú ´ %“ ´ %“ ´ %“ ´ ‘ The multiple Æg¦½Ñ1Æ"Ä s are similar to ƐÀÒ£Í½Ü . the program generates a G . Python will try .

In this section. we’ll step through the design of a more difficult decision problem to illustrate some of the challenge and excitement of the design process. If you follow the error type with an identifier in Æ ¦½Ñ1" g Æ Ä an clause.. you might not worry too much about bad input. our algorithms are liberated from the monotony of step-by-step. This is both a blessing and a curse. however. The negative side is that designing these more sophisticated algorithms is much harder. professional quality software should do whatever is feasible to shield users from unexpected results. This algorithm could be part of a larger problem such as determining grades or computing taxes. Suppose we need an algorithm to find the largest of three numbers. how can a computer determine which of three user inputs is the largest? Here is a program outline. In this case. Whether Python prints and designing you need to go to this much trouble depends on the type of program you are writing. the program just prints a general apology. That is. Exceptions G are actually a kind of object. then the program crashes and Python reports the error. but we are not interested in the final details. The bare Æ ¦ˆÑ1" ) Æ Ä Æ¨ÀˆÜÓÆ at the bottom acts like an and will be used if none of the others Æg¦½Ñ1Æ"Ä match.¿H ´H˜xyè…v‹Iç 6 Šãé4{ôˆ 6 1Š ¬ ´ ä²u8Ž•‚‡å@ã‰tx}${ô{ Æg¦½Ñ1Æ"Ä each in turn looking for one that matches the type of error. We need to fill in the missing part. If the message doesn’t match one of the two known error messages. r«”|º r1~†¿ ©²…ΦŸ·§í ‡peq«ª‚„‘ˆ‡šqe–²àkëi f ™hì—Y˜§gI‚„‚ Now that we have decisions that can alter the control flow of a program. You can use this same technique by observing the error messages that Æ ¦½Ñ1" g Æ Ä clauses to catch and handle them. In your beginning programs. ۈÀxÉ½Æ ÌÌ¨ÁHÌ Notice how I handled the two different kinds of s. As a challenge. I turned that exception into a string and looked at the message to ۈÂPÀÓÉˆÆ ÌPÌÁ1Ì G see what caused the .g. Python will assign that identifier the actual exception object. The positive side is that we can now develop more sophisticated algorithms. just the crux of the problem. Notice that this text is exactly what Python prints out if the error is not caught (e. If there is no default at the bottom and none of the types match the error. ĐÌPϙïïPïðg Æ ¦½Ñ1" Æ Ä statement allows us to write bullet-proof You can see how the programs. èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ¦4Ö@Æ õ ¦Ô‰Æ õ ¦Þ€ß¡Ò€Ç)Éĉñ †  ؈ÀPƐˆÜÓÆcƣǨÄÆ1̀ÄHŨÌƐÆ`WˆÂÀxɽƈÜæ÷$Óú . “ValueError: math domain error”). strictly sequential processing. you might see if you can find an erroneous input that produces the apology. as we did for our quadratic solver.

û ȑ×ÈƒÊ Ø t"“H–§tuiC• ¤ ¨ª Ê vx—æÍ%–%“fiEšx–%œ $tuvEÚ º  ه٠Obviously. That is. . we need to execute one of the following assignments: Ê4  ¦W¥ ß ¦4Ö Ê4  ¦W¥ ß ¦Ô Ê4  ¦W¥ ß ¦¨Þ It would seem we just need to preface each one with the appropriate condition(s). We need a seÊÎÂg¦ to the largest of the three inputs quence of statements that sets the value of ¦4Ö ¦¨Ô ¦Þ . It turns out that Python does allow this compound condition. First. ¦4Ö ¦¨Ô ¦¨Þ 0 0 The condition does not match the template for conditions º º shown above. and it ¡ q`“•y . Whenever you write a decision. Here is a first attempt: Ò£¥ Í ¦ÎÖ (   ß ¦Ô ( ¥ ß ¦¨Þo÷ Ê4  ¦W¥ ß ¦4Ö Your first concern here should be whether this statement is syntactically correct. To determine that ¦4Ö is actually the largest. are you absolutely certain that executing the body of the decision is the right action to take? In this case. this looks like a three-way decision. you should ask yourself two crucial questions. so that it is executed only in the proper situation. the conbehaves exactly like the mathematical relations “x…bq£“Îr ¦4Ö ¦¨Ô ¦Ô ¦Þ dition is true when is at least as large as and is at least as large as .r1~†â s@tŒuxw†y|{‡}3¿Pæé4{ ³†6 ˆ 6 ‚HŠ x ˜ yè} … ³ yè…x}${ôˆ ó ʓҐܐÜPÒIǧ!àÑ£ÁPÐơܣÆHÄ3ÜÊ4¦€ÄÁ€ÄHňƣWˆÂPÀÓɈÆWÁP̀ÄHňÆÝÀÂ£Ìc!¨ÆˆÜxÄ ÊÎÂg¦ ̽ҀÇÄXHňÆÝÀÂ£Ìc!¨ÆˆÜxÄTWÀxɽÆÐҐÜ%Îõ Before reading the following analysis. Notice that our condition includes equal as well as greater. Most computer languages would not accept this as a valid expression. that is the largest. Always pay particular attention to borderline values. Python has no problem with this condition. and . the condition ¦4Ö ¦Ô ¦¨Þ is at least as large as and . this program presents us with a decision problem. when the condition is true. we just need to check that it is at least as large as the other two. ¦4Ö Let’s consider the first possibility. We should convince . At first glance. so assigning its value to clearly states that Ê4  ¦ should be correct. you might want to try your hand at solving this problem.

Python allows us to test multiple conditions that ÂÓÇà like this by combining them with the keyword . the following condition seems to be what we are looking for: Ò£¥ Í ¦ÎÖ (   ß ¦ÔWÂxLj¥ à ¦ÎÖ ( ¥ ß ¦¨Þo÷ ó ¦4ÖUÒ¨V   Ü !HÌƐÂ1ÄÆ1̀ÄHŽÂÓǡƐÂрÅÐÁP̀ÄHňÆWÁHÄ1ŽÆHÌ3Ü Ê4  ¦W¥ ß ¦4Ö r1~†é To complete the program. Are we certain that ¦4Ö this condition is true in all cases where is the max? Unfortunately. our algorithm is basically checking each possible value against all the others to determine if it is the largest. and 4. . ƨÀÜ£Æ and finally execute the . this condition will return true. Suppose that . but not greater than . What we really need is two separate tests to determine ¦ÎÖ ( ¥ ß ¦Ô ¦¨Ô ( ¥ ß ¦¨Þ and that . The second question to ask is the converse of the first. discover it to be false. . The complex expressions result from the fact that each decision is designed to stand on its own. 2. and hence. With just three values the result is quite simple. Intuitively. At this ¦¨Þ point. Suppose the first ¦4Ö ¦¨Ô ¦Þ decision discovers that is greater than . we just need to implement analogous tests for the other possibilities. the first is at least as big as the others. the max. Unfortunately. Suppose the values are 5. That’s OK because it doesn’t matter which we choose. Python will go ahead and evaluate the next expression.¿H ´H˜xyè…v‹Iç 6 Šãé4{ôˆ 6 1Š ¬ ´ ä²u8Ž•‚‡å@ã‰tx}${ô{ ¦4Ö ¦¨Ô ¦¨Þ ourselves that this is correct. We’ll discuss the exact seÂÓÇà mantics of in Chapter 8. but how would this solution look if we were trying to find the max of five values? Then we would need four ÂÓLjà Boolean expressions. but our condition returns false since the relationship xsqÈs ¡ qè does not hold. ¦ÎÖ We want to ensure that is the largest. information from one test is ignored in the subsequent tests. Clearly. and are all the same. but we don’t care about the relative ¦Ô ¦¨Þ ordering of and . each consisting of four conditions ed together. our code ignores this. Ò£¥ Í ¦ÎÖ (   ß ¦ÔWÂxLj¥ à ¦ÎÖ ( ¥ ß ¦¨Þo÷ Ê4  ¦W¥ ß ¦4Ö Æ¨À¨Ò£¥ Í ¦¨Ô ( ¥ ß ¦4Ö ÂxLj¥ à ¦¨Ô ( ¥ ß ¦¨Þo÷ Ê4  ¦W¥ ß ¦Ô ƨÀÜ£Æo÷ Ê4  ¦W¥ ß ¦¨Þ Summing up this approach. look back at our simple max of three code. our con¦4Ö dition does not meet this test. we know that must be the max. To see what I mean. is the largest. We need to fix this.

ңͥ¦ÎÖ ( ß ¦Ԅ÷ ңͥ¦ÎÖ ( ߥ¦¨Þo÷ Ê4Âg¦Wߥ¦ÎÖ Æ¨ÀÜ£Æn÷ Ê4g  ¦W¥ ß ¦Þ ƨÀÜ£Æo÷ Ò£¥ Í ¦¨Ô ( ¥ ß ¦¨Þo÷ Ê4g  ¦W¥ ß ¦¨Ô ƨÀÜ£Æn÷ Ê4g  ¦W¥ ß ¦Þ yes x1 >= x2 no yes x1 >= x3 no yes x2 > =x3 no max = x1 max = x3 max = x2 max = x3 ' % Figure . As you can see. Suppose we start with a simple test . or . the result boils down to a choice between and . Should the initial condition be ¦¨Ô ¦¨Þ false.rIr7 û ȑ×È‘Ç Ø t"“H–§tuiC• ¤ ¨œ Ç s@tŒuxw†y|{‡}3¿Pæé4{ ³†6 ˆ 6 ‚HŠ x ˜ yè} … ³ yè…x}${ôˆ ãi%œ©lnslnvxw Åÿ “Hi§i One way to avoid the redundant tests of the previous algorithm is to use a ¦4Ö ¦¨Ô 0 decision tree approach. Figure . This ¦ÎÖ ¦Ô º knocks either or out of contention to be the max. shows the situation in a flowchart. : Flowchart of the decision tree approach to max of three . If the condition is true. ' % hence the name decision tree. the first decision “branches” into two possibilities. each of which is another decision. . This ÒÓC Í ¨HƨÀˆÜÓÆ flowchart translates easily into nested statements. ¦4Ö ¦¨Þ we just need to see which is larger.

and it suffers a similar complexity explosion should we try this design with more than three values. this strategy has us look through the list sequentially.¿H ´H˜xyè…v‹Iç 6 Šãé4{ôˆ 6 1Š ¬ ´ ä²u8Ž•‚‡å@ã‰tx}${ô{ rIrH~ The strength of this approach is its efficiency. Continue scanning. the structure of this approach is more sign the correct value to complicated than the first. Perhaps there is yet a third way. move your finger to the new one. A computer doesn’t have fingers. keeping track of the largest number seen so far. but we can use a variable to keep track ÊÎg  ¦ to do this of the max so far. As a challenge. In a nutshell. containing only two simple decisions. The code itself is quite simple. the easiest approach is just to use Ê4  ¦ job. Further- . when we get to the end. When designing an algorithm. this algorithm will make exactly two comparisons and asÊ4Âg¦ . In fact. Here is the translation into Python code: Ê4¦Wߥ¦4Ö Ò£¥ Í ¦¨Ô ( Ê4Âg¦n÷ Ê4  ¦Wߥ¦Ô Ò£¥ Í ¦Þ ( Ê4g  ¦n÷ Ê4  ¦W¥ ß ¦¨Þ Clearly. automatically contains the value of the largest. if you find a number bigger than the one your finger is on. A flowchart depicting this strategy for the max of three problem is ' & shown in Figure . For finding the max of three numbers. you probably don’t have a very good intuition about the steps you go through. You’d just look at the numbers and know which is the largest. and the sequencing is easier to understand than the nesting used in the previous algorithm. you might see if you can design a decision tree to find the max of four values. a good starting place is to ask yourself how you would solve the problem if you were asked to do the job. That way.) û ȑ×È‘É Ø t"“H–§tuiC• ¤ ¨ É Ø i£txr%iBwmtqln–Qٔ’”“fvœ©i§sqsl™wm• So far. most people develop a simple strategy. and put your finger on it. we have designed two very different algorithms. the sequential approach is the best of our three algorithms. However. but neither one seems particularly elegant. (You will need Ò£c Í ¨PƐÀˆÜ£Æ s nested three levels deep leading to eight assignment statements. But what if you were handed a book containing hundreds of numbers in no particular order? How would you find the largest in this collection? When confronted with the larger problem. When you get to the end of the list. Scan through the numbers until you find a big one. . your finger will remain on the largest value. No matter what the ordering of the three values.

adding a fourth item adds only one more statement.rIr€r s@tŒuxw†y|{‡}3¿Pæé4{ ³†6 ˆ 6 ‚HŠ x ˜ yè} … ³ yè…x}${ôˆ max = x1 x2 > max max = x2 x3 > max max = x3 ' & Figure . the idea scales well to larger problems. we invented the algorithm by explicitly considering how to solve a more complex problem. In fact. you can see that the code is very repetitive. more. : Flowchart of a sequential approach to the max of three problem. Ê4  ¦W¥ ß ¦4Ö Ò£¥ Í ¦¨Ô ( Ê4g  ¦n÷ Ê4  ¦W¥ ß ¦Ô Ò£¥ Í ¦Þ ( Ê4g  ¦n÷ Ê4  ¦W¥ ß ¦¨Þ Ò£¥ Í ¦)d ( Ê4g  ¦n÷ Ê4  ¦W¥ ß ¦©d It should not be surprising that the last solution scales to larger problems. We can easily write .

û ™ ȑ×È Ø t"“H–§tuiC• ¤h™f¨ ¼ ‘¤ )  –sqiT’ ct %vxw Before leaving this problem. I really should mention that none of the algorithm development we have so painstakingly pursued was necessary. .. ¦ ÊÎÂg¦ Each time. etc. we compare the newest against the current value of to see if it is larger. Here is the simplest version of our program: èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ¦4Ö@Æ õ ¦Ô‰Æ õ ¦Þ€ß¡Ò€Ç)Éĉñ †ØˆÀPƐˆÜÓÆcƣǨÄÆ1̀ÄHŨÌƐÆ`WˆÂÀxɽƈÜæ÷$Óú ̽ҀÇ Ä XHňÆÝÀÂ£c Ì !¨ÆˆÜxT Ä WÀxɽÆÐҐÜ%Îõ ÊÎÂg¦æñë¦4Ö@õç¦Ôæõ禨޽ú .¿H ´H˜xyè…v‹Iç 6 Šãé4{ôˆ 6 1Š ¬ ´ ä²u8Ž•‚‡å@ã‰tx}${ô{ rIr€” a program that allows the user to find the largest of ø numbers by folding our ¦ÎÖ ¦¨Ô ¦Þ algorithm into a loop. Rather than having separate variables for . ó£̨Á)!Ḧ€ʕ÷ 4 Ê Â¦1ÇhïUÏ ó D3ÒILjÃ3Ü ÄH½ Å ÆYÊÎÂg¦ˆÒ‡ÊÉ1ÊÿÁPÍСÜÓÆHÌ3Ò£Æ½Ü Ã¨ÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ÇàßÿҀ© Ç PÉĉñ 3¢Á1ÛYÊ4ÂÓǨÏUǐÉ1ÊˈÆHÌÎÜ ÁHÍUǐÉ1Ê˽Æ1ÌÎÜ Â1ÌÆcÄ1ŽÆ1ÌƧP¡£ú ó ÅPÆ1ÄÈÊ4g S  ¦€Ä¨ÁÈ˽ƀÄHňÆcͽÒxÌÎ܀ĥWˆÂÀxÉ½Æ Ê4¦WߡҀǩPÉĉñ  ÇĨÆHÌÝ ÇPÉHʨ˽ÆHÌ (©( £  ú G óTÐÁ£Û Ñ1ÁxÊc3£ÌÆUÄ1ŽÆÈÇ%¨½ÖcÜIÉÎѐÑ1ƈܐÜHÒ"WÆVWˆÂPÀÓÉ½ÆˆÜ Í¨Á1ÌÿÒWҀÇÐ̈Âxǧ!ÆæñðÇm¨3ÖHú¬÷ ¦Wß ÒI© Ç PÉĄ" ñ  ÇÄÆ1ÌWÂÈÇPÉHÊˈÆHÌ ()( £ú G Ò£¥ Í ¦ ( Ê4  ¦Ÿ÷ ÊÎg  ¦W¥ ß ¦ ̽ҀÇÄXHňÆÝÀÂ£Ìc!¨ÆˆÜxÄTWÀxɽÆÐҐÜ%Îõ ÊÎÂg¦ Ê4¨ҀÇoñIú This code uses a decision nested inside of a loop to get the job done. Python actually Ê4¦ has a built-in function called that returns the largest of its parameters. ¦ we can just get the values one at a time and keep reusing a single variable . On each Ê4Âg¦ iteration of the loop. . contains the largest value seen so far.

There are other techniques for designing good algorithms (see Chapter 13). Similarly. Our fourth solution was to use Python’s Ê4Âg¦ function. many beginning programmers do not really take this point to heart. That way you get the maximum utility from your programming effort. simplicity. ’ Be the computer. you may as well write the more general program because it is more likely to be useful in other situations. They are a pleasure to read and maintain. We arrived at the best solution to the max of three problem by considering the more general max of ø numbers problem. efficiency. Your first task is to find a correct algorithm. If the max of ø program is just as easy to write as max of three. After that. Especially for beginning programmers. ask yourself again if there might be a better way. however. there are many ways to approach the problem. It is not unusual that consideration of a more general problem can lead to a better solution for some special case. ask yourself if there is a better way to approach the problem. and efficient enough. Good algorithms and programs are like poems of logic. scalability. ’ Don’t reinvent the wheel. strive for clarity. one of the best ways to formulate an algorithm is to simply ask yourself how you would solve the problem. which rather defeats the point of the exercise! Sometimes Python is just too simple for our own good. ’ There is more than one way to do it. ’ Generality is good. Once you have written the code. You may think that was cheating. and elegance. you should always have an eye toward making your program more generally useful. clear. this version didn’t require any algorithm development at all. but the attempt to solve this problem has illustrated some important ideas in algorithm and program design. when designing programs. While this may seem obvious. For any non-trivial computing problem. but this example illustrates an . What does this mean for you? Don’t rush to code up the first idea that pops into your head. Think about your design.rIr ¯ s@tŒuxw†y|{‡}3¿Pæé4{ ³†6 ˆ 6 ‚HŠ x ˜ yè} … ³ yè…x}${ôˆ Of course. Don’t be afraid to step back and think about the overarching problem. the straightforward approach is often simple. û ȑ×È‘× Ø vx—˜i Ž¸ %i§sqsvxw%s The max of three problem is not particularly earth shattering.

designing from scratch is great experience. which are simple Boolean expressions. ’ Algorithms that incorporate decisions can become quite complicated as decision structures are nested. you might begin by finding out if the problem has already been solved for you. F . . know when to borrow. . ’ Decisions are implemented in Python with Ò£Í statements. A lot of very smart programmers have designed countless good algorithms and programs. A simple decision can be implemented with an ÒÓÍ statement. r«”–ê  ˜Ÿi„¤n…‚™g © ¦§›¥› ingIí This chapter has laid out the basic control structures for making decisions. Python ˽ÁPÁ¨À Ì1É½Æ DÀÜ£Æ has a dedicated data type with literals and . . Multi-way decisions are implemented with . and understandable program. Truly expert programmers. efficient. .” Python provides a Đ̐C Ï ¨Pg Æ ¦½Ñ1" Æ Ä statement for exception handling. and careful thought should be given to produce a correct. ’ Decisions are based on the evaluation of conditions. Usually a number of solutions are possible. Conditions ß pß ßß ( ( ß are formed using the relational operators: F . ’ Decision structures are control structures that allow a program to execute different sequences of instructions for different cases. and .¿H ¹HHs@tŒuxw†y|{‡}Q˜¨…€ƒ„ƒŸu‡}‘ç rIr€´ important point. Simple decisions Ò£Í are implemented with a plain . As you are learning to program. A Boolean expression is either true or false. however. ’ Some programming languages provide exception handling mechanisms which help to make programs more “bulletproof. If the problem you are trying to solve seems to be one that lots of others must have encountered. r«”sr egf„‚™gIƒæ‡‘‚„‘ hjiCkmlniCoqpIrQi§sutqlnvxw%s y{zH|c})~Q©€cˆ‚3} 1. Two-way decisions generally use an Ò£C Í ¨HƨÀÜ£Æ Ò£C Í ¨HƨÀ¨Ò£C Í ¨HƨÀÜ£Æ . Here are the key points.


s@tŒuxw†y|{‡}3¿Pæé4{ ³†6 ˆ 6 ‚HŠ x ˜ yè} … ³ yè…x}${ôˆ

2. In Python conditions,


is written as


3. Strings are compared by lexicographic ordering. 4. A two-way decision is implemented using an


ÊÎÂ1ÄHÅhïzÜíPÌÄ 5. The function cannot compute the square root of a negative number.

6. A single


statement can catch multiple kinds of errors.

7. Multi-way decisions must be handled by nesting multiple ments.


8. There is usually only one correct solution to a problem involving decision structures. 9. The condition
¦ F



is allowed in Python.

10. Input validation means prompting a user when input is required.
ƒ |§„3…‡†§ˆ}Iˆj‰cŠ§…Œ‹"}

1. A statement that controls the execution of other statements is called a a) boss structure b) super structure c) control structure d) branch 2. The best structure for implementing a multi-way decision in Python is Ò£Í ÒÓÍC¨HƨÀˆÜÓÆ Ò£Íc¨PƐÀÒ£Íc¨PƐÀˆÜ£Æ ÄÌÏ a) b) c) d) 3. An expression that evaluates to either true or false is called a) operational b) Boolean c) simple d) compound 4. When a program is being run directly (not imported),the value of Ç3ÂIÊÎÆ is ÜPÑxÌ3 Ò ¨Ä ÊÎÂÒ€Ç Ê4ÂÒIÇ Ì1É½Æ a) b) c) d)
ˈÁÁ¨À 5. The literals for type are  D ÌHÉˆÆ DÀˆÜÓÆ a) , b) ,





Ö Õ d) ,

6. Placing a decision inside of another decision is an example of a) cloning b) spooning c) nesting d) procrastination

¿P ¿PCŽŒ{I} ³Œ6 ˆ–{ôˆ


7. In Python, the body of a decision is indicated by a) indentation b) parentheses c) curly braces

d) a colon

8. A structure in which one decision leads to another set of decisions, which leads to another set of decisions, etc., is called a decision a) network b) web c) tree d) trap Ê4Â1Ä1ńïô" Ü íPÌPÄ 9. Taking the square root of a negative value with produces a(n) a) ValueError b) imaginary number c) program crash d) stomachache 10. A multiple choice question is most similar to a) simple decision b) two-way decision c) multi-way decisions d) an exception handler
 …Œ‚3‹|c‚8‚X…ŒŠm

1. Explain the following patterns in your own words: (a) simple decision (b) two-way decision (c) multi-way decision 2. The following is a (silly) decision structure:
‰õ ˙õÑÈßÿҀÇ)É¨Ä„ñ ǨÄÆHÌÈÄHŨÌÆPÆ ÇÉ1Ê˽Æ1ÌÎܬ÷ G Ò£ÍР( ˄÷ ÒÓÍUË ( щ÷ ¨Ì3ҀǨA Ä qÅ3ÂIʡ؈ÀPƐˆÜÓÆ u ƐÀˆÜÓÆn÷ ¨Ì3ҀǨA Ä "¢€Ä †ÜUÂWÀÂ1Ĩ` Æ 3£̐ÌÁ1Ä坞 ƨÀÒÓÍUË ( щ÷ ¨Ì3ÒIÇ& Ä ‡×ÓŽÆPƽܣE Æ ÅÓňÁ ©ˆ' Æ  ÒÓÍР( ߡщ÷ ¨Ì3ҀǨA Ä ‡×ÓŽÆHÐã# Ì  ƐÀÒÓÍРËh÷ F ¨Ì3ҀǨA Ä  ü Á£ÉÃB   ƐÀÒÓÍ¡ÑÈߐßU˄÷ ¨Ì3ҀǨA Ä qÅÓÛÎҐܐ% Ü  ƨÀˆÜÓÆn÷ 




s@tŒuxw†y|{‡}3¿Pæé4{ ³†6 ˆ 6 ‚HŠ x ˜ yè} … ³ yè…x}${ôˆ 



Show the output that would result from each of the following possible inputs: (a) 3, 4, 5 (b) 3, 3, 3 (c) 5, 4, 3 (d) 3, 5, 2 (e) 5, 4, 7 (f) 3, 3, 2
ĐÌPϧŸHÆ)¦½Ñ£Æ ¨Ä 3. How is exception-handling using similar to and different from handling exceptional cases using ordinary decision structures (variations Ò£Í on )?

1. Many companies pay time-and-a-half for any hours worked above 40 in a given week. Write a program to input the number of hours worked and the hourly rate and calculate the total wages for the week. 2. A certain CS professor gives 5-point quizzes that are graded on the scale 5-A, 4-B, 3-C, 2-D, 1-F, 0-F. Write a program that accepts a quiz score as an input and uses a decision structure to calculate the corresponding grade. 3. A certain CS professor gives 100-point exams that are graded on the scale 90–100:A, 80–89:B, 70–79:C, 60–69:D, Ó 60:F. Write a program that accepts an exam score as input and uses a decision structure to calculate the corresponding grade. 4. A certain college classifies students according to credits earned. A student with less than 7 credits is a Freshman. At least 7 credits are required to be a Sophomore, 16 to be a Junior and 26 to be classified as a Senior. Write a program that calculates class standing from the number of credits earned.

¿P ¿PCŽŒ{I} ³Œ6 ˆ–{ôˆ


5. The body mass index (BMI) is calculated as a person’s weight (in pounds) times 720, divided by the square of the person’s height (in inches). A BMI in the range 19–25, inclusive, is considered healthy. Write a program that calculates a person’s BMI and prints a message telling whether they are above, within, or below the healthy range. 6. The speeding ticket fine policy in Podunksville is $50 plus $5 for each mph over the limit plus a penalty of $200 for any speed over 90 mph. Write a program that accepts a speed limit and a clocked speed and either prints a message indicating the speed was legal or prints the amount of the fine, if the speed is illegal. 7. A babysitter charges $2.50 an hour until 9:00 PM when the rate drops to $1.75 an hour (the children are in bed). Write a program that accepts a starting time and ending time in hours and minutes and calculates the total babysitting bill. You may assume that the starting and ending times are in a single 24 hour period. Partial hours should be appropriately prorated. 8. A person is eligible to be a US senator if they are at least 30 years old and have been a US citizen for at least 9 years. To be a US representative these numbers are 25 and 7, respectively. Write a program that accepts a person’s age and years of citizenship as input and outputs their eligibility for the Senate and House. 9. A formula for computing Easter in the years 1982–2048, inclusive, is as ú)ö 5…u€ , ú)ö  , ù úgö ‡ , ‚H…u€"ú ¡)„ y"w , follows: let ú º º º º  (which ‚ ¡ ù i x„ ‡ . The date of Easter is March ¡£¡ º      could be in April). Write a program that inputs a year, verifies that it is in the proper range, and then prints out the date of Easter that year.

9 !(

9 9 u 1 ( ˜ – w1 – u1


9 u1 ˜

˜ 9 w1

10. The formula for Easter in the previous problem works for every year in the range 1900–2099 except for 1954, 1981, 2049, and 2076. For these 4 years it produces a date that is one week too late. Modify the above program to work for the entire range 1900–2099. 11. A year is a leap year if it is divisible by 4, unless it is a century year that is not divisible by 400. (1800 and 1900 are not leap years while 1600 and 2000 are.) Write a program that calculates whether a year is a leap year. 12. Write a program that accepts a date in the form month/day/year and outputs whether or not the date is valid. For example 5/24/1962 is valid, but 9/31/2000 is not. (September has only 30 days.)


s@tŒuxw†y|{‡}3¿Pæé4{ ³†6 ˆ 6 ‚HŠ x ˜ yè} … ³ yè…x}${ôˆ

13. The days of the year are often numbered from 1 through 365 (or 366). This number can be computed in three steps using int arithmetic: (a)



(b) if the month is after February subtract






” ™lk 

†V…q„ Â





(c) if it’s a leap year and after February 29, add 1

” ™lk 
ø Â



Write a program that accepts a date as month/day/year, verifies that it is a valid date (see previous problem), and then calculates the corresponding day number. 14. Do Programming Exercise 7 from Chapter 5, but add a decision to handle the case where the line does not intersect the circle. 15. Do Programming Exercise 8 from Chapter 5, but add a decision to prevent the program from dividing by zero if the line is vertical. 16. Archery Scorer. Write a program that draws an archery target (see Programming Exercise 2 from Chapter 5) and allows the user to click five times to represent arrows shot at the target. Using five-band scoring, a bulls-eye (yellow) is worth 9 points and each successive ring is worth 2 fewer points down to 1 for white. The program should output a score for each click and keep track of a running sum for the entire series. 17. Write a program to animate a circle bouncing around a window. The basic idea is to start the circle somewhere in the interior of the window. Use à ¦ © ÃPÏ and (both initialized to 1) to control the movement of the variables circle. Use a large counted loop (say 10000 iterations), and each time à ¦ © ÃHÏ through the loop move the circle using and . When the x-value of the à ¦ ) center of the circle gets too high (it hits the edge), change to -1. When à ¦ ) ÃHÏ it gets too low, change back to 1. Use a similar approach for . Note: Your animation will probably run too fast. You can slow it down by Ü£ÀPÆPÆ  Ľ҇ÊÎÆ using the function from the library module.

18. Take a favorite programming problem from a previous chapter and add decisions and/or exception handling as required to make it truly robust

¿P ¿PCŽŒ{I} ³Œ6 ˆ–{ôˆ


(will not crash on any inputs). Trade your program with a friend and have a contest to see who can “break” the other’s program.


¥§¥Sf r ¦pt


g ¥§¥



iq r ¦m 

x€y31‚„ƒ†…ˆ‡‰„‚„‘ ’ To understand the concepts of definite and indefinite loops as they are ͨÁ1Ì ÛPÅÎÒHÀPÆ realized in the Python and statements. ’ To understand the programming patterns interactive loop and sentinel ÛHÅ4ÒHÀHÆ statement. loop and their implementations using a Python ’ To understand the programming pattern end-of-file loop and ways of implementing such loops in Python. ’ To be able to design and implement solutions to problems involving loop patterns including nested loop structures. ’ To understand the basic ideas of Boolean algebra and be able to analyze and write Boolean expressions involving Boolean operators.
‘«”–“ ðŸ™hgȼŸ™q™²¤™‘'²èÖ




' Ò£Í In Chapter , we looked in detail at the Python statement and its use in implementing programming patterns such as one-way, two-way, and multi-way decisions. In this chapter, we’ll wrap up our tour of control structures with a detailed look at loops and Boolean expressions. ͨÁHÌ You already know that the Python statement provides a kind of loop. It allows us to iterate through a sequence of ­ values.


rI” ¯ ͨÁ1Ì

s@tŒuxw†y|{‡}½âP¾v‚Ó‚1w”˜Óyè} … ³ yè…x}‘{zˆ„uxŠŒ‹Ž±‚Ó‚g± {zuxŠŒˆ ҀÇ



WˆÂ1Ì The loop index variable takes on each successive value in the sequence, and the statements in the body of the loop are executed once for each value. Suppose we want to write a program that can compute the average of a series of numbers entered by the user. To make the program general, it should work for any size set of numbers. You know that an average is calculated by summing up the numbers and dividing by the count of how many numbers there are. We don’t need to keep track of all the numbers that have been entered; we just need a running sum so that we can calculate the average at the end. This problem description should start some bells ringing in your head. It suggests the use of some design patterns you have seen before. We are dealing with a series of numbers—that will be handled by some form of loop. If there are ø numbers, the loop should execute ø times; we can use the counted loop pattern. We also need a running sum; that calls for a loop accumulator. Putting the two ideas together, we can generate a design for this problem. ¢I) Ç É¨Ä€ÄHňÆàÑ1Á£ÉPÇÄÐÁH̀ÄHŽÆÈÇPÉHʨ˽ÆHÌ3Ü­õ Ç ¢IÇÎÒÓĽÒHÀ¨Ò ÆÐÜIÉ1Ê¡ÄÁWÕ ¤ÁPÁ WÇÐĽ҇ÊÎÆˆÜ ¢I) Ç ÉÄÝÂUÇPÉHʨ˽ÆHÌoç õ ¦ Ú ÃP¥ à ¦€ÄÁ¡ÜIÉ1Ê Ä É¨g Ä PÉÄРWÆHÌg  !ÆWˆÜW܇ÉHÏ Ê Ÿ Ç


Hopefully, you see both the counted loop and accumulator patterns integrated into this design. We can translate this design almost directly into a Python implementation. óÐ  W¨ÆHÌg  !¨Æ3Ö­b ï Ï
èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ÇàßÿҀ© Ç PÉĉñ 3¢Á1ÛYÊ4ÂÓǨÏUǐÉ1ÊˈÆHÌÎÜ Ã¨ÁcÏÁÓÉWÅ3 WƧPvÓú ÜIÉ1ÊÿßÝÕnïðÕ Í¨Á1ÌÿÒWҀÇÐ̈Âxǧ!ÆæñðÇ@ú¬÷ ¦Wß ÒI© Ç PÉĄ" ñ  ÇÄÆ1ÌWÂÈÇPÉHÊˈÆHÌ ()( £ú G ÜIÉHÊÿßÿ܇ÉHÊÿ  á ¦ ̽ҀÇ Ä  Óc Ç HňÆW  W¨ÆḦ  !¨Æ€ÁH̀ÄHňÆÈǐÉHʨ˽Æ1ÌÎÜcҐÜ%Îõ܇ÉHÊϟ

܇ÉHÊ The running sum starts at 0, and each number is added in turn. Notice that ÜIÉ1ÊvŸÈÇ is initialized to a float 0.0. This ensures that the division on the last line returns a float even if all the input values were ints.



âH rHcu Šv‹I{ëêŠ 6 y|{£¾v‚Ó‚1wŒˆ



Here is the program in action. èÁ€ÏÁÓɀÅ3 WC Æ PE9 ǨÄÆ1ÌÐÂÈǐÉHʨ˽Æ1Ì (©( ÞÔ Ç¨ÄÆ1ÌÐÂÈǐÉHʨ˽Æ1Ì (©( dc9 ǨÄÆ1ÌÐÂÈǐÉHʨ˽Æ1Ì (©( g Þ d ǨÄÆ1ÌÐÂÈǐÉHʨ˽Æ1Ì (©( þPø ǨÄÆ1ÌÐÂÈǐÉHʨ˽Æ1Ì (©( dc9 


Well, that wasn’t too bad. Knowing a couple of common patterns, counted loop and accumulator, got us to a working program with minimal difficulty in design and implementation. Hopefully, you can see the worth of committing these sorts of programming clich´ es to memory.
‘«”–• t–eŸ·§‚{ìŽe™‡


Our averaging program is certainly functional, but it doesn’t have the best user interface. It begins by asking the user how many numbers there are. For a handful of numbers this is OK, but what if I have a whole page of numbers to average? It might be a significant burden to go through and count them up. It would be much nicer if the computer could take care of counting the numͨÁ1Ì loop is a definite loop, bers for us. Unfortunately, as you no doubt recall, the and that means the number of iterations is determined when the loop starts. We can’t use a definite loop unless we know the number of iterations ahead of time, and we can’t know how many iterations this loop needs until all of the numbers have been entered. We seem to be stuck. The solution to this dilemma lies in another kind of loop, the indefinite or conditional loop. An indefinite loop keeps iterating until certain conditions are met. There is no guarantee ahead of time regarding how many times the loop will go around. ÛHÅ4ÒHÀHÆ statement. SynIn Python, an indefinite loop is implemented using a ÛHÅ4Ò1ÀPÆ tactically, the is very simple. ÛPÅÎÒHÀHÆ Ñ£Á£ÇˆÃˆÒÓĽÒ1Á£Ç ( ÷ F ˈÁPÃPÏ (

Ñ£Á£ÇýÒÓĽÒ1ÁÓÇ Ò£Í Here is a Boolean expression, just like in statements. The body is, as usual, a sequence of one or more statements.

Figure . If the loop condition is initially false. This kind of structure is called a pre-test loop. the loop body will not execute at all. Here is an example of a simple ÒÈßÐÕ ÛPÅÎÒHÀHÆÐÒ ß ÖxÕo÷ F ̽ҀÇÄàÒ ÒÈßÿÒÈá Ö ÛPÅ4Ò1ÀPÆ loop that counts from 0 to 10: This code will have the same output as if we had written a ͨÁ1ÌÿÒWҀÇà̈Âxǧ!Ææñ€ÖPÖPú­÷ ̽ҀÇÄàÒ Í¨ÁHÌ loop like this: ÛHÅ4ÒHÀHÆ Ò Notice that the version requires us to take care of initializing before the Ò ÍÁHÌ loop and incrementing at the bottom of the loop body. the loop variable is handled automatically. In the loop. Notice that the loop terminates. The body of the loop executes repeatedly as long as the condition remains true. When the condition is false. shows a flowchart for the the condition is always tested at the top of the loop. : Flowchart of a loop.rI”€¹ s@tŒuxw†y|{‡}½âP¾v‚Ó‚1w”˜Óyè} … ³ yè…x}‘{zˆ„uxŠŒ‹Ž±‚Ó‚g± {zuxŠŒˆ ÛHÅ4ÒHÀHÆ The semantics of is straightforward. <condition>? no yes <body> (  ÛHÅ4Ò1ÀPÆ Figure . (  ÛHÅ4ÒHÀHÆ . before the loop body is executed. .

printing a 0. which is less than 10. it can do more than just iterate through sequences.Ó Alt 0 Ó Delete 0 on a PC). If all else fails. ‘«”–  ȑÉÈƒÊ rI”€¿  ¢™£› › ™qep¼n™q™£¤ äUwmtui•“H–%œ)tqlŒk§i ž¸ —Ži„……¨‚hg£eŸ‘ %vxvxÍ%s One good use of the indefinite loop is to write interactive loops. printing a 0. This is an example of an infinite loop. We want to modify the program .. Ò printing a 0. Now control returns to the condition. Even more experienced programmers have been known to do this from time to time. Recall that the previous version of the program forced the user to count up how many numbers there were to be averaged. this might not work. and you’ll have to resort to more drastic means (such as Ó Ctrl 0 . Rinse. Ò Suppose we forget to increment at the bottom of the loop body in the counting example. you can break out of a loop by pressing Ó Ctrl 0 -c (holding down the Ó Ctrl 0 key and pressing “c”). Repeat. The best idea is to avoid writing infinite loops in the first place.âP ”P1s‚Hƒ„ƒo‚1Š«¾v‚Ó‚Hw«Hu†y y|{‡}Š†ˆ ÛPÅÎÒHÀHÆ The simplicity of the statement makes it both powerful and dangerous. Usually. there is always the trusty reset button on your computer. Because it is less rigid. it is more versatile. so the loop body executes again. Clearly this version of the program does nothing useful. so the loop body executes.. will be 0. That reminds me.. The idea behind an interactive loop is that it allows the user to repeat certain portions of a program on demand. is still 0. But it is also a common source of errors. You get the picture. Let’s take a look at this loop pattern in the context of our number averaging problem. did you hear about the computer scientist who died of exhaustion while washing his hair? The instructions on the bottle said: “Lather. ÒÈßÐÕ ÛPÅÎÒHÀHÆÐÒ ß ÖxÕo÷ F ̽ҀÇÄàÒ Ò What will the output from this program be? When Python gets to the loop. infinite loops are a bad thing.” As a beginning programmer. is still 0. it would be surprising if you did not accidentally write a few programs with infinite loops—it’s a rite of passage for programmers. so the loop body executes again. Now Ò control returns to the condition. If your loop is really tight. Usually.

We can do this with Ñ1Á£ÉPÇÄ another accumulator—call it —that starts at zero and increases by 1 each time through the loop. each iteration of the loop will ask whether there is more data to process.rI”€â s@tŒuxw†y|{‡}½âP¾v‚Ó‚1w”˜Óyè} … ³ yè…x}‘{zˆ„uxŠŒ‹Ž±‚Ó‚g± {zuxŠŒˆ so that it keeps track of how many numbers there are. Here is the corresponding Python program: óÐÂW¨ÆHÌÂg!¨ÆÔoïbÏ Ã¨ÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ÜIÉ1ÊÿßÝÕnïðÕ Ñ1ÁÓɐÇĀßàÕ ÊÎÁ1ÌÆPèÂ1ÄÂÈß&ŒÏ¨Æ½Ü% ÛPÅÎÒHÀPÆ ÊÎÁH̨ÆPèÂ1Ĉ û ÕgcߐßA†Ï#4÷ ¦Wß ÒI© Ç PÉĄ" ñ  ÇÄÆ1ÌWÂÈÇPÉHÊˈÆHÌ G ÜIÉHÊÿßÿ܇ÉHÊÿ  á ¦ Ñ1Á£ÉPÇÄWßÿÑ£Á£ÉÇ¨ÄWá Ö ()( £ú . To allow the user to stop at any time. The general pattern for an interactive loop looks like this: Ü£Æ1ÄÈÊÎÁ1ÌÆPèÂ1Ä ÄÁA†ÏƽÜm ÛPÅÎÒHÀHÆ ÊÎÁ1ÌÆPèÂ1ÄÂÝÒ¨Üa†ÏƽÜm !¨Æ1ÄWÄHŽÆÈLjÆ)¦HÄWãĈÂÐÒÓĨÆxÊ ̨ÁˆÑ1ÆˆÜÜ Ä1ŽÆàÒxÄÆxÊ Âˆq Ü Î€É@Ü£Æ1Ì¡Ò£ÍWÄ1ŽÆH̨ÆÐÒ¨ÜfÊ3ÁH̨ÆPãĈ Combining the interactive loop pattern with accumulators for the sum and count yields this algorithm for the averaging program: ҀÇÎÒÓĽÒHÀ¨Ò ÆÐÜIÉ1Ê¡ÄÁWÕoïðÕ Ò€ÇÎÒÓĽÒHÀ¨Ò ÆÝÑ1ÁÓɐǨĀÄÁÝÕ Ü£Æ1ÄÈÊÎÁ1ÌÆPèÂ1Ä ÄÁA†ÏƽÜm ÛPÅÎÒHÀHÆ ÊÎÁ1ÌÆPèÂ1ÄÂÝÒ¨a Ü †ÏƽÜm Ҁ) Ç ÉÄÝÂUÇPÉHʨ˽ÆHÌoç õ ¦ ÂHÃP¥ à ¦€ÄÁ¡ÜIÉ1Ê ÂHÃPÃ Ö ÄÁàÑ1ÁÓÉÇ¨Ä Âˆq Ü Î€É@Ü£Æ1Ì¡Ò£ÍWÄ1ŽÆH̨ÆÐÒ¨ÜfÊ3ÁH̨ÆPãĈ Á£É¨g Ä PÉÄÿ܇ÉHÏ Ê ŸÐÑ1ÁÓÉÇ¨Ä !!hh Notice how the two accumulators are interleaved into the basic structure of the interactive loop.

The user will almost certainly be annoyed by the constant prodding for more data.” Also note the use of ̈ÂÓÛ ÒI© Ç PÉÄ ÌˆÂÓÛ ÒIÇ©PÉÄ to get this value. Remember you should use to get string data. A sentinel loop continues to process data until reaching a special value that signals the end. Here is a general pattern for designing sentinel loops: !¨Æ1ÄWÄHňƀͽÒÓÌ3ÜxÄWèÂ1ÄÂÐÒÓÄÆ€Ê ÛPÅÎÒHÀHÆÐÒÓĨÆxÊ Ò¨Ü ÇˆÁHÄWÄ1ŽơܣÆÓÇĽҀǽƐÀ .  ȑÉÈ‘Ç Ø iBwmtql™w%i%Ù mvxvxÍ%s 4¸ A better solution to the number averaging problem is to employ a pattern commonly known as a sentinel loop. All that matters is that the first letter is a “y. The only restriction is that it be distinguishable from actual data values. Here is sample output from this program: ǨÄÆ1ÌÐÂÈǐÉHʨ˽Æ1Ì (©( ÞÔ G ˆÁcϨÁ£ÉWŽ  WÆYÊ3ÁHÌ¨Æ ÇÉ1Ê˽Æ1ÌÎÜ»ñèÏƈÜÈÁHÌcǽÁ½g ú P Ï¨Æ½Ü Ç¨ÄÆ1ÌÐÂÈǐÉHʨ˽Æ1Ì (©( dc9 G ˆÁcϨÁ£ÉWŽ  WÆYÊ3ÁHÌ¨Æ ÇÉ1Ê˽Æ1ÌÎÜ»ñèÏƈÜÈÁHÌcǽÁ½g ú P Ï Ç¨ÄÆ1ÌÐÂÈǐÉHʨ˽Æ1Ì (©( Þgd G ˆÁcϨÁ£ÉWŽ  WÆYÊ3ÁHÌ¨Æ ÇÉ1Ê˽Æ1ÌÎÜ»ñèÏƈÜÈÁHÌcǽÁ½g ú P Ï Ç¨ÄÆ1ÌÐÂÈǐÉHʨ˽Æ1Ì (©( þPø G ˆÁcϨÁ£ÉWŽ  WÆYÊ3ÁHÌ¨Æ ÇÉ1Ê˽Æ1ÌÎÜ»ñèÏƈÜÈÁHÌcǽÁ½g ú P Ï Ç¨ÄÆ1ÌÐÂÈǐÉHʨ˽Æ1Ì (©( dc9 G ˆÁcϨÁ£ÉWŽ  WÆYÊ3ÁHÌ¨Æ ÇÉ1Ê˽Æ1ÌÎÜ»ñèÏƈÜÈÁHÌcǽÁ½g ú P LjÁ ½Æ      HňÆÝÂW¨ÆḦÂ!¨Æ€ÁH̀ÄHňÆÈǐÉHʨ˽Æ1ÌÎÜcҐÜVd¨ønïH9 In this version.” “y. This allows for varied responses such as “yes. this is not one of them.” “yeah. The sentinel is not processed as part of the data.” etc.âP ”P1s‚Hƒ„ƒo‚1Š«¾v‚Ó‚Hw«Hu†y y|{‡}Š†ˆ rI”€é ̽ҀÇÄ ÊÎÁH̨ÆPèÂ1Ĉ ßẄ£ۧÌÒIÇ©É¨Ä„ñ" ˆÁYÏÁÓÉWÅ3 WÆYÊÎÁ1ÌÆ ÇPÉHʨ˽ÆHÌ3Ü»ñ–ϨƽÜÈÁ1ÌcǽÁ3úPa£ú Óc Ç HňÆWÂW¨ÆḦÂ!¨Æ€ÁH̀ÄHňÆÈǐÉHʨ˽Æ1ÌÎÜcҐÜ%Îõ܇ÉHÊϟÐÑ£Á£ÉÇ¨Ä í´  ÊÎÁ1ÌÆPèÂ1Ä û Õg Notice this program uses string indexing ( ) to look just at the first letter of the user’s input. Any value may be chosen for the sentinel. the user doesn’t have to count the data values. The special value is called the sentinel. The interactive loop has many good applications. but the interface is still not good.

This is sometimes called the priming read. The first item is retrieved before the loop starts. The loop test at the top ensures this next item is not the sentinel before processing it. as it gets the process started. When the sentinel is reached. The user can enter a negative number to signal the end of the data. If the first item is the sentinel. the loop immediately terminates and no data is processed. óÐ  W¨ÆHÌg  !¨ÆPÞnb ï Ï Ã¨ÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ÜIÉ1ÊÿßÝÕnïðÕ Ñ1ÁÓɐÇĀßàÕ ¦WßÿҀ© Ç PÉĉñ  ÇĨÆH̀ÂUÇPÉHʨ˽ÆHÌòñðǽÆg!£Ä3Ò"W¨ÆÈĨÁTí1É4ÒxÄ4ú ()( £ú G ÛPÅÎÒHÀP£ Æ ¦ ( ßÝÕn÷ ÜIÉHÊÿßÿ܇ÉHÊÿá ¦ Ñ1Á£ÉPÇÄWßÿÑ£Á£ÉÇ¨ÄWá Ö ¦Wß ÒI© Ç PÉĄ" ñ  ÇÄÆ1ÌWÂÈÇPÉHÊˈÆHÌ ñùǽg Æ !Â1Ľ" Ò W¨ÆÈÄT Á í£É4ÒxÄ4ú (©( Ó  ú G ̽ҀÇ Ä  Óc Ç HňÆW  W¨ÆḦ  !¨Æ€ÁH̀ÄHňÆÈǐÉHʨ˽Æ1ÌÎÜcҐ% Ü Îõ܇ÉHÏ Ê ŸÐÑ£Á£ÉÇ¨Ä í´ I have changed the prompt so that the user knows how to signal the end of the data. Combining the sentinel loop with the two accumulators from the interactive loop version yields this program.r ¯ 7 s@tŒuxw†y|{‡}½âP¾v‚Ó‚1w”˜Óyè} … ³ yè…x}‘{zˆ„uxŠŒ‹Ž±‚Ó‚g± {zuxŠŒˆ ̨ÁˆÑ1ÆˆÜÜ !¨Æ1ÄWÄHŽÆÈLjÆ)¦HÄWãĈÂÐÒÓĨÆxÊ Ä1ŽÆàÒxÄÆxÊ Notice how this pattern avoids processing the sentinel item. Suppose we are using the program to average exam scores. Here it is in action: ǨÄÆ1ÌÐÂÈǐÉHʨ˽Æ1Ì ñðLj) Æ !£Ä3 Ò WÆÈĨT Á í1ÉÎÒÓÄ4ú ()( Þ¨Ô G ǨÄÆ1ÌÐÂÈǐÉHʨ˽Æ1Ì ñðLj) Æ !£Ä3 Ò WÆÈĨT Á í1ÉÎÒÓÄ4ú ()( dC9 G ǨÄÆ1ÌÐÂÈǐÉHʨ˽Æ1Ì ñðLj) Æ !£Ä3 Ò WÆÈĨT Á í1ÉÎÒÓÄ4ú ()( ) Þ d G ǨÄÆ1ÌÐÂÈǐÉHʨ˽Æ1Ì ñðLj) Æ !£Ä3 Ò WÆÈĨT Á í1ÉÎÒÓÄ4ú ()( þø G ǨÄÆ1ÌÐÂÈǐÉHʨ˽Æ1Ì ñðLj) Æ !£Ä3 Ò WÆÈĨT Á í1ÉÎÒÓÄ4ú ()( dC9 G ǨÄÆ1ÌÐÂÈǐÉHʨ˽Æ1Ì ñðLj) Æ !£Ä3 Ò WÆÈĨT Á í1ÉÎÒÓÄ4ú ()( ¨3Ö G HňÆÝÂW¨ÆḦÂ!¨Æ€ÁH̀ÄHňÆÈǐÉHʨ˽Æ1ÌÎÜcҐÜVd¨ønïpd . the loop terminates. We can apply the sentinel pattern to our number averaging problem. the item is processed and the next one is read. Notice that the prompt is identical at the priming read and the bottom of the loop body. The first step is to pick a sentinel. Otherwise. Now we have a useful form of the program. we can safely assume that no score will be below 0. In that case.

We can use this as a simple way to terminate input. all others would be converted into numbers and treated as data. We can have a distinctive. The sentinel loop is a very handy pattern for solving all sorts of data processing problems. it is always possible that some data set may contain such a number. Remember. One simple solution is to have the sentinel value be an empty string.âP ”P1s‚Hƒ„ƒo‚1Š«¾v‚Ó‚Hw«Hu†y y|{‡}Š†ˆ r ¯ ~ This version provides the ease of use of the interactive loop without the hassle of having to type “yes” all the time. we need to broaden the possible inputs. Suppose that we get the input from the user as a string. This sentinel loop solution is quite good. an empty string is © (quotes with no space between). What we need is a sentinel value that is distinct from any possible valid number. If the user types represented in Python as ̈ÂÓÛ Ò€© Ç PÉÄ Ç¨ÄÆHÌ (just hits ÓåG 0 ). but there is still a limitation. The design looks like this: ¢IÇÎÒÓĽÒHÀ¨Ò ÆÐÜIÉ1Ê¡ÄÁWÕoïðÕ ¢IÇÎÒÓĽÒHÀ¨Ò ÆÝÑ1ÁÓɐǨĀÄÁÝÕ ¢I) Ç É¨ÄWãĈÂÐÒÓĨÆxÊ ÂÜUÂàÜxĐ̽ҀC Ç !oç õ ¦cÅ1ÄÌ ÛPÅÎÒHÀHE Æ ¦CţĐÌÿÒ¨Ü ÇˆÁHÄÐƀC Ê ÄPÏ ×ÁÓC Ç WÆ1̐¥ Ä ¦cÅ1ÄP̀ÄÁРǐÉ1ÊˈÆHÌn° õ ¦ Ú ÃP¥ à ¦€ÄÁ¡ÜIÉ1Ê Ú ÃPÃ Ö ÄÁàÑ1ÁÓÉÇ¨Ä ¢I) Ç ÉÄÈǽ) Æ ¦HÄÝãĈÂÐÒÓĨÆxÊ ÂÜU¡ÜxĐ̽ҀC Ç !oç õ ¦cÅ1ÄÌ Ä É¨g Ä PÉÄÿ܇ÉHÏ Ê ŸÐÑ1ÁÓÉÇ¨Ä !!hh Comparing this to the previous algorithm. It’s another clich´ e that you should commit to memory. non-numeric string that indicates the end of the input. this is impossible as long as we restrict ourselves to working with numbers. positive or negative. you can see that converting the string to a number has been added to the processing section of the sentinel loop. Python returns an a blank line in response to a empty string. The program can’t be used to average a set of numbers containing negative as well as positive values. In order to have a truly unique sentinel. No matter what number or range of numbers we pick as a sentinel. Let’s see if we can’t generalize the program a bit. Of course. Translating it into Python yields this program: óÐ  W¨ÆHÌg  !¨g Æ dŸb ï Ï Ã¨ÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ÜIÉ1ÊÿßÝÕnïðÕ Ñ1ÁÓɐÇĀßàÕ .

The data in the file can be perused and edited before sending it to a program that generates a report. showing that it is now possible to average arbitrary sets of numbers: G G G G G G G ǨÄÆ1ÌÐÂÈǐÉHʨ˽Æ1Ì Ç¨ÄÆ1ÌÐÂÈǐÉHʨ˽Æ1Ì Ç¨ÄÆ1ÌÐÂÈǐÉHʨ˽Æ1Ì Ç¨ÄÆ1ÌÐÂÈǐÉHʨ˽Æ1Ì Ç¨ÄÆ1ÌÐÂÈǐÉHʨ˽Æ1Ì Ç¨ÄÆ1ÌÐÂÈǐÉHʨ˽Æ1Ì Ç¨ÄÆ1ÌÐÂÈǐÉHʨ˽Æ1Ì ñ ñ ñ ñ ñ ñ ñ F G F G F G F G F G F G F G ÇĨÆHÌ ÇĨÆHÌ ÇĨÆHÌ ÇĨÆHÌ ÇĨÆHÌ ÇĨÆHÌ ÇĨÆHÌ ( ( ( ( ( ( ( ÄÁ¥í£É4ÒÓÄÎú Ä¥ Á í£É4ÒÓÄÎú Ä¥ Á í£É4ÒÓÄÎú Ä¥ Á í£É4ÒÓÄÎú Ä¥ Á í£É4ÒÓÄÎú Ä¥ Á í£É4ÒÓÄÎú Ä¥ Á í£É4ÒÓÄÎú (©( (©( (©( (©( (©( (©( (©( Þgd ÔHÞ Õ ¨PÔ©9 ¨HÞ)dnïfd ÔPÔoïùþ HňÆÝÂW¨ÆḦÂ!¨Æ€ÁH̀ÄHňÆÈǐÉHʨ˽Æ1ÌÎÜcҐÜÈÞnïðÞ)eÞPސސÞPސÞPÞÞÞ We finally have an excellent solution to our original problem.r ¯ r s@tŒuxw†y|{‡}½âP¾v‚Ó‚1w”˜Óyè} … ³ yè…x}‘{zˆ„uxŠŒ‹Ž±‚Ó‚g± {zuxŠŒˆ ¦CţĐÌÝ߀̈ÂÓm Û Ì¨Ò€Ç©PÉĉñ  ÇĨÆHÌcÂÈǐÉHʨ˽Æ1Ì ñ ÇĨÆHÌ ( ÄÁ¥í£É4ÒÓÄÎú (©( Ó  ú G F G ÛPÅÎÒHÀPÆ£¦CÅ1ÄPÌ pßA)@÷ ¦Wßà Æ WˆÂPÀ¬ñë¦cÅ1ÄPÌ4ú ÜIÉHÊÿßÿ܇ÉHÊÿ  á ¦ Ñ1Á£ÉPÇÄWßÿÑ£Á£ÉÇ¨ÄWá Ö ¦CÅ1ÄPÌWßẄÂÓm Û ÌÒI© Ç PÉĄñ" ÇÄÆ1ÌcÂUÇPÉHʨ˽ÆHÌòñ ÇĨÆHÌ ( ÄÁ¥í1ÉÎÒÓÄÎú (©( G FG ̽ҀÇ Ä  Óc Ç HňÆW  W¨ÆḦ  !¨Æ€ÁH̀ÄHňÆÈǐÉHʨ˽Æ1ÌÎÜcҐ% Ü Îõ܇ÉHÊϟÐÑ£Á£ÉÇ¨Ä í´ Óú Æ WˆÂÀ  This code makes use of (from Chapter 4) to convert the input string into a number.  ȑÉÈ‘É ¢ ¸ l‘ÙŒi %v#vxÍQs One disadvantage of all the averaging programs presented so far is that they are interactive. Back in Chapter 4. Imagine you are trying to average 87 numbers and you happen to make a typo near the end. We can apply this technique directly to . you will need to start all over again. You should study this solution so that you can incorporate these techniques into your own programs. With our interactive program. This file-oriented approach is typically used for data processing applications. Here is an example run. we looked at reading data from files by treating the file ͨÁ1Ì variable as a sequence in a loop. A better approach to the problem might be to type all of the numbers into a file.

you may be concerned that this loop stops prematurely if it encounters an empty line in the file. and the  ‡ÇxpßA) method includes the newline character in its return value. Remember. óÐÂW¨ÆHÌÂg!¨Æ©9oïbÏ Ã¨ÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ͽÒ1ÀPg Æ Ð€Ê3ÆUßẄÂÓÛmÌÒIÇ©PÉĄñ"34HÅ3Â1ÄUͽÒ1ÀPÆW£ÌÆcÄ1ŽÆÈǐÉ1ÊˈÆHÌÎÜUҀǕPvÓú ҀÇͽÒHÀHÆcßÝÁ ˆÆ£ÇoñôͽÒ1ÀP Æ ÐˆÂ€Ê3Ƅõ ðÌ Œú ÜIÉ1ÊÿßÝÕnïðÕ Ñ1ÁÓɐÇĀßàÕ Í¨Á1ÌàÀҀLjÆÐҀǻÒILjͽÒ1ÀPÆo÷ ÜIÉHÊÿßÿ܇ÉHÊÿáÐg Æ WÀ­ñ†ÀÒIǽƽú Ñ1Á£ÉPÇÄWßÿÑ£Á£ÉÇ¨ÄWá Ö ̽ҀÇ Ä  Óc Ç HňÆW  W¨ÆḦ  !¨Æ€ÁH̀ÄHňÆÈǐÉHʨ˽Æ1ÌÎÜcҐ% Ü Îõ܇ÉHÏ Ê ŸÐÑ£Á£ÉÇ¨Ä €  í´ ÀÒIÇ½Æ In this code. a blank  ‡Çx ̨ƨÂHèÀÒIÇ½Æ line in a text file contains a single newline character ( ). At the end of the file. Here is a general pattern for an end-of-file ÌƐÂHÃÀ¨Ò€ÇˆÆæñIú loop using in Python. returns an empty string. We can illustrate this method in Python by ̨ƨÂ1ÃÀÒIǽƬñIú ÌƨÂ1ÃÀ¨Ò€Ç½Æ¬ñIú . Assuming that the numbers are typed into a file one per line. Here is the code that results from applying the end-of-file sentinel loop to our number averaging problem: í¹ í¹ óÐÂW¨ÆHÌÂg!¨ÆPønïbÏ . Many programming languages do not have a special mechanism for looping through files like this. In these languages. Remember. the lines of a file can be read one at a time using a form of sentinel loop. the loop variable iterates through the file as a sequence of lines. the method gets the next line from using ÌƐÂHÃÀ¨Ò€ÇˆÆæñIú a file as a string. which we can use as a sentinel value.âP ”P1s‚Hƒ„ƒo‚1Š«¾v‚Ó‚Hw«Hu†y y|{‡}Š†ˆ r ¯ ” the number averaging problem. Since . we can compute the average with this program. This is not the case. each line is converted to a number and added to the running sum. ÀÒIǽƀߡÒILjͽÒ1ÀPÆoïpÌƐÂHèÀҀLjÆæñ‡ú ÛPÅÎÒHÀHÆWÀÒIÇ½Æ pßA)@÷ ó ̨ÁˆÑ1ƈܐÜÈÀ¨Ò€ÇˆÆ £ ÀÒIǽƀߡҀÇͽÒ1ÀPÆnï–ÌƐÂHÃÀ¨Ò€ÇˆÆæñIú At first glance. the loop will continue.

r ¯€¯ èÆHÍ s@tŒuxw†y|{‡}½âP¾v‚Ó‚1w”˜Óyè} … ³ yè…x}‘{zˆ„uxŠŒ‹Ž±‚Ó‚g± {zuxŠŒˆ Ê4¨ҀÇnñ‡ú¬÷ ͽÒ1ÀPg Æ Ð€Ê3ÆUßẄÂÓÛmÌÒIÇ©PÉĄñ"34HÅ3Â1ÄUͽÒ1ÀPÆW£ÌÆcÄ1ŽÆÈǐÉ1ÊˈÆHÌÎÜUҀǕPvÓú ҀÇͽÒHÀHÆcßÝÁ ˆÆ£ÇoñôͽÒ1ÀP Æ ÐˆÂ€Ê3Ƅõ ðÌ Œú ÜIÉ1ÊÿßÝÕnïðÕ Ñ1ÁÓɐÇĀßàÕ ÀÒIǽƀߡҀÇͽÒ1ÀPÆnï–ÌƐÂHÃÀ¨Ò€ÇˆÆæñIú ÛPÅÎÒHÀPƀÀÒ€ÇˆÆ pA ß )@÷ ÜIÉHÊÿßÿ܇ÉHÊÿáÐg Æ WÀ­ñ†ÀÒIǽƽú Ñ1Á£ÉPÇÄWßÿÑ£Á£ÉÇ¨ÄWá Ö ÀҀLjÆcßÿҀÇͽÒHÀHÆnï–ÌƨÂ1ÃÀ¨Ò€Ç½Æ¬ñIú ̽ҀÇ Ä  Óc Ç HňÆW  W¨ÆḦ  !¨Æ€ÁH̀ÄHňÆÈǐÉHʨ˽Æ1ÌÎÜcҐ% Ü Îõ܇ÉHÏ Ê ŸÐÑ£Á£ÉÇ¨Ä €  í´ ÍÁHÌ Obviously. let’s use an end-of-file loop. At the top level. you saw how control structures such as decisions and loops could be nested inside one another to produce sophisticated algorithms.  ȑÉÈ ™ Ë i§sqtui º›ä¸ %vxvxÍ%s In the last chapter. the basic algorithm will be some sort of file-processing loop that computes a running sum and count. but it is still good to know about end-of-file loops in case you’re stuck programming in a less elegant language. this version is not quite as concise as the version using the loop. 1 Suppose we modify the specification of our file averaging problem slightly. This time. you might as well use the latter. One particularly useful. we’ll allow any number of values on a line. How about one last version of our number averaging problem? I promise this is the last time I’ll use this example. . but somewhat tricky technique is the nesting of loops. For practice. Here is the code comprising the top-level loop: ÜIÉ1ÊÿßÝÕnïùÕ Ñ1ÁÓɐǨÄWßÐÕ ÀÒIǽƀߡÒILjͽÒ1ÀPÆoïpÌƐÂHèÀҀLjÆæñ‡ú ÛPÅÎÒHÀHÆWÀÒIÇ½Æ pA ß )@÷ óU© É ÃÂ1ĨÆàÜIÉ1Ê ÂÓÇáÑ1Á£ÉPÇÄÝ͐ÁH¥ Ì WˆÂPÀÓɈƽÜcÒIÇÿÀÒ€ÇˆÆ ÀÒIǽƀߡҀÇͽÒ1ÀPÆnï–ÌƐÂHÃÀ¨Ò€ÇˆÆæñIú ̽ҀǨA Ä  xC Ç HňÆW  W¨ÆHÌg  !¨ÆcÁP̀ÄHňÆÈǐÉ1Ê˽Æ1ÌÎÜcҐ% Ü 3õÜIÉHÏ Ê ŸÐÑ£Á£ÉPÇÄ í´ 1 until Chapter 11. When multiple values appear on a line. Let’s take a look at an example program. In Python. instead of typing the numbers into the file one-per-line. they will be separated by commas.

and the outer loop goes through its next iteration. Then we need to loop through these substrings. here is our program: óÐ  W¨ÆHÌg  !¨ÆPþnb ï Ï Ò‡c Ê ½Á1̐Äÿ܀ĐÌ3ÒI§ Ç ! èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ͽÒ1ÀPg Æ Ð€Ê3ÆUßẄÂÓÛmÌÒIÇ©PÉĄñ"34HÅ3Â1ÄUͽÒ1ÀPÆW£ÌÆcÄ1ŽÆÈǐÉ1ÊˈÆHÌÎÜUҀǕPvÓú ҀÇͽÒHÀHÆcßÝÁ ˆÆ£ÇoñôͽÒ1ÀP Æ ÐˆÂ€Ê3Ƅõ ðÌ Œú ÜIÉ1ÊÿßÝÕnïðÕ Ñ1ÁÓɐÇĀßàÕ ÀÒIǽƀߡҀÇͽÒ1ÀPÆnï–ÌƐÂHÃÀ¨Ò€ÇˆÆæñIú ÛPÅÎÒHÀPƀÀÒ€ÇˆÆ pA ß )@÷ óU© É ˆÃ¨Â1ĨÆàÜIÉ1Ê ÂÓLjáѣÁ£ÉPÇÄÝͨÁ1T Ì WˆÂPÀÓɈƽ܀ҀÇÿÀ¨Ò€ÇˆÆ ͨÁH  Ì ¦cÅ1ÄPÌ¡Ò€Ç ÜxÄPÌ3ÒI§ Ç !Ÿïôq Ü ½ÀÒÓĉñ†À¨Ò€Ç½Æ½ú¬÷ ܇ÉHÊÿßÿ܇ÉHÊÿáÝg Æ WÀ­ë ñ ¦CţĐÌÎú Ñ£Á£ÉPÇÄWßÿÑ1ÁÓɐǨÄWá Ö ÀҀLjÆcßÿҀÇͽÒHÀHÆnï–ÌƨÂ1ÃÀ¨Ò€Ç½Æ¬ñIú ̽ҀÇ Ä  Óc Ç HňÆW  W¨ÆḦ  !¨Æ€ÁH̀ÄHňÆÈǐÉHʨ˽Æ1ÌÎÜcҐ% Ü Îõ܇ÉHÏ Ê ŸÐÑ£Á£ÉÇ¨Ä r ¯ ´ €  í´ As you can see. and add it to . We also need to add 1 to for each number. The outer loop iterates once for each line of ͨÁ1Ì the file. The individual fragments of this problem are not complex when taken separately. Since each individual line of the file contains one or more numbers separated by commas. the inner loop iterates as many times as there are numbers on that line. which just happens to be the loop-control variable for the fileprocessing loop we outlined above. but the final result is fairly intricate. convert each to ܇ÉHÊ Ñ£Á£ÉPÇÄ a number. Here is a code fragment that processes a line: ͨÁ1  Ì ¦CţĐÌÿҀǻ܀Đ̽Ҁ§ Ç !nïzu Ü 3ÀÒxĄñzÀҀLjƄ õ Î õ Óú¬÷ ÜIÉ1ÊÿßÿÜIÉHÊÿáÐ Æ WˆÂÀ­ë ñ ¦cÅ1ĐÌÎú Ñ1ÁÓɐÇÄ€ß Ñ£Á£ÉPÇÄWáÎÖ Í¨Á1Ì Notice that the iteration of the loop in this fragment is controlled by the ÀÒIÇ½Æ value of .âP ”P1s‚Hƒ„ƒo‚1Š«¾v‚Ó‚Hw«Hu†y y|{‡}Š†ˆ ܇ÉHÊ Ñ1ÁÓɐÇÄ Now we need to figure out how to update the and in the body of the loop. On each iteration of the outer loop. the loop that processes the numbers in a line is indented inside ÛPÅÎÒHÀPÆ of the file processing loop. The best way to design nested loops . each of which represents a number. When the inner loop finishes. we can split the line into substrings. the next line of the file is read. Knitting these two loops together.

g. Let’s take a look at these three operators and then see how they can be used to simplify our problem. trust it. ÂÓÇà ÁHÌ The Boolean operators and are used to combine two Boolean expressions and produce a Boolean result. we have used simple Boolean expressions that compare ÛHÅ4Ò1ÀPE Æ ¦ ( ßàÕ two values (e. put the pieces together. and . which are Boolean expressions. In Python. . If the individual loops are correct. One way of handling this would be a nested decision. Python provides three Boolean ÂÓÇà Á1Ì ÇˆÁHÄ operators: . Conceptually.. ‘«”|µ  ¢™£›¥¤§¦o…ˆ‡penšmœ ‡ …Θ ¸¢™q™²j ‚„i•eŸ‘ Ò£Í ÛPÅÎÒHÀHÆ We now have two control structures.r ¯ ¹ s@tŒuxw†y|{‡}½âP¾v‚Ó‚1w”˜Óyè} … ³ yè…x}‘{zˆ„uxŠŒ‹Ž±‚Ó‚g± {zuxŠŒˆ is to follow the process we did here. ). even triple-nested loops with ease. another approach would be to construct a more complex expression using Boolean operations.  È ™ ÈƒÊ ² v#v6ٌim–Bw žŸ IÍ'i•“H–§tuv'“fs Sometimes the simple conditions that we have been using do not seem expressive enough. that use conditions. ignoring the outer loop(s). Then design what goes inside. So far. they have equal x coordinates and equal y coordinates. For example. Like most programming languages. Instead of working around this problem with a decision structure. With a little practice. a Boolean expression evaluates to one of two values: false or true. you’ll be implementing double-. and . First design the outer loop without worrying about what goes inside. these values are represented by the literals DˆÂPÀˆÜÓÆ Ì1É½Æ and . taking care to preserve the nesting. ңͣ“Ö­ïp!¨ÆHÄ ‰ñ‡ú ߐßE½Ôoïf!ÆHÄ ‰ñIú­÷ Ò££ Í “Ö­ïf!ÆHÄ „ñIúªßßE3Ԅïf!ÆHÄ ‰ñIú­÷ ó ½ÁˆÒIÇÄ3ÜÈÂ1̨ÆcÄHŽơܣ€Ê3Æ £ ƨÀÜ£Æn÷ ó ½ÁˆÒIÇÄ3ÜÈÂ1̨ƀýңÍPͨÆ1ÌÆ£Ç¨Ä £ ƨÀÜ£Æo÷ ó ½ÁҀÇÄ3ÜÈÂ1̨ƀýÒÓ͐ͨÆ1ÌÆÓÇÄ £ gÐ €“ gÐ g“ You can see how awkward this is. Finally. the nested result will work just fine. suppose you need to determine whether two point objects are in the same position—that is.

Notice espeThe only time the ÁHÌ is true when both expressions are true. The last column gives the value of „ ÂÓÇà for each possible combination. ƒ ÂÓÇà each shown as one row in the table. there are four possible combinations of values. The truth table is very simple. By definition. but the word “or” is sometimes used in an exclusive sense in everyday English. As with arithmetic operators. Here is the Á1Ì truth table defining : ƒ „ ƒ Á1Ì „ T T F F T F T F T T T F Á1Ì is false is when both expressions are false. the is true only in the case ƒ „ where both and are true. This is the mathematical cially that Á1Ì definition of .âH ¯ Hsˆ‚1ƒ„wx…zy 6 ŠŒ§’ 6 yèt«±‚Ó‚± {†uxŠ†ˆ Æg¦¨Ì Æg¦¨Ì F F ( ( r ¯ ¿ ÂxLjà Á1Ì F Æ ¦¨Ì g F Æ)¦ Ì ( ( ÂÓÇà The of two expressions is true exactly when both of the expressions are true. Since each exIn this table. We can represent this definition in a truth table. meaning that it operates on a single expression. the exact meaning of a complex ex- . It is a unary operator. If your mom said that you could have cake or cookies for dessert. ƒ „ ƒ ÂÓLjà „ T T F F ƒ „ T F T F T F F F and represent smaller Boolean expressions. it is possible to build arbitrarily complex Boolean expressions. ǽÁHÄ The operator computes the opposite of a Boolean expression. she would probably scold you for taking both. ÁHÌ The of two expressions is true when either expression is true. pression has two possible values. ƒ ǽÁ1Ä ƒ T F F T Using Boolean operators.

we are ready to return to our ÂxLjà example problem. As long as both conditions remain false (neither player has reached 15) the entire expression is false.r ¯ â s@tŒuxw†y|{‡}½âP¾v‚Ó‚1w”˜Óyè} … ³ yè…x}‘{zˆ„uxŠŒ‹Ž±‚Ó‚g± {zuxŠŒˆ pression depends on the precedence rules for the operators. To test for the co-location of two points. by definition of . we will develop a simulation for the game of racquetball. Part of the simulation will ÜHÑ1Á1ÌÆ Ú ÜHÑ1Á1ÌÆ need to determine when a game has ended. Consider this expression: €ÁH̀LjÁHÄcËÿÂÓÇÃ¡Ñ How should this be evaluated? Python follows a standard convention that the order of precedence from ǽÁHÄ ÂÓÇà Á1Ì . we could use an operation. followed by . This ensures that both the x and y coordinates have to match for the points to be the same. ÁHÌ and. Here is a Boolean expression that is true when the game is over: u ÜPÑ£ÁHÌ¨Æ Ú ßPß Ö"9€ÁHÌ ÜHÑ1ÁHÌ¨Æ WßPß u Ö"9 When either score reaches 15. The game is over as soon as either of the players has reached 15 points. Suppose that and represent the scores of two racquetball players. the entire Boolean expression is true. I suggest that you always parenthesize your complex expressions to prevent confusion. one of the two simple conditions becomes true. . followed by . this is much simpler and clearer than the Ò£Í nested s from the previous version. Now that we have some Boolean operators. most people don’t tend to know or remember the precedence rules for Booleans. In the next chapter. Obviously. however. So the expression would be high to low is equivalent to this parenthesized version: ñ†Â€Á1Ì©ññùǽÁHÄcË@úÈÂÓÇáÑúú Unlike arithmetic. Let’s look at a slightly more complex example. ңͣ“Ö­ïp!¨ÆHÄ ‰ñ‡ú ߐßE½Ôoïf!ÆHÄ ‰ñIú ÂÓÇã3Ôoïp!¨Æ1Ä „ñ‡ú ßPߣ†Ö­ïp!¨Æ1Ä „ñ‡ú¬÷ ó ½ÁҀÇÄ3ÜÈÂ1̨ÆcÄHňơÜ1€Ê3Æ £ ƨÀÜ£Æo÷ ó ½ÁҀÇÄ3ÜÈÂ1̨ƀýÒÓ͐ͨÆ1ÌÆÓÇÄ £ gÐ gÐ g“ g“ Here the entire expression will only be true when both of the simple conditions are true.

Suppose we were writing a simulation for volleyball. Volleyball does not have shutouts. . rather than racquetball. Some racquetball players play shutouts (sometimes called a skunk).âH ¯ Hsˆ‚1ƒ„wx…zy 6 ŠŒ§’ 6 yèt«±‚Ó‚± {†uxŠ†ˆ r ¯ é Our simulation will need a loop that continues as long as the game is not over. but it requires a team to win by at least two points. If the score is 15 to 14. While we’re at it. Here is another way to do it: ñ†Â ( ß Ö"9WÁHÌcË ( ß Ö"9ˆúÈÂÓLjÃÐÂxË@Ü@ñ†Â¥¨ ˓ú ( ßÐÔ This version is a bit more succinct. It states that the game is over when one of the teams has reached a winning total and the difference in the scores is at least ÂxË@Ü 2. and each requires checking both scores. The result is a fairly complex expression. Here’s one approach: ñ†Â ( ß Ö"9ÝÂÓÇÃÝ ¨ Ë ( ßÐÔ½ú Á1Ì©ñðË ( ß Ö9WÂÓÇÃUËa¨Ð ( ßÐÔ½ú Do you see how this expression works? It basically says the game is over when team A has won (scored at least 15 and leading by at least 2) or when team B has won. I’ll use for ÜPÑ£ÁHÌ¨Æ Ú Ë ÜPÑ1Á1ÌÆ and for . For brevity. Remember that returns the absolute value of an expression. let’s try one more example. a game also ends when one of the play ers reaches 7 and the other has not yet scored a point. or even 21 to 20. For these players. Let’s write a condition that computes when a volleyball game is over. ÛPÅÎÒHÀHÆ Ç½Á1Ä©ñ‡ÜPÑ£ÁHÌ¨Æ Ú ßPß Ö"9€ÁHÌ ó¡Ñ1ÁÓÇÄ3ÒIǐɈÆV3ÀPÂ1Ï3ÒIǧ! ÜHÑ1ÁHÌ¨Æ WßPß u Ö"9ˆú¬÷ We can also construct more complex Boolean expressions that reflect different possible stopping conditions. the game continues. We can construct an appropriate loop condition by taking the negation of the game-over condition. Here is an expression for game-over when shutouts are included: 3 Âcߐ߻Ö9€ÁHÌcËàߐ߻Ö9€ÁHÌ©ñ†ÂcßPßÝþÐÂÓLjÃUËàßPßÝÕ3úÈÁHÌ©ñùËàߐßÝþÐÂÓÇÃÝ€ߐßÝÕ½ú Do you see how I have added two more situations to the original condition? The new parts reflect the two possible ways a shutout can occur.

let’s go back to the racquetball game one more time. while 0 and 1 correspond to false and true. and reason with these expressions is an important skill for programmers and computer scientists. you can see that has similarities to multiplication.rI´7  È ™ È‘Ç ² s@tŒuxw†y|{‡}½âP¾v‚Ó‚1w”˜Óyè} … ³ yè…x}‘{zˆ„uxŠŒ‹Ž±‚Ó‚g± {zuxŠŒˆ v#v6ٌim–BwVÚ Ùˆ•'i Q“f– j¾ All decisions in computer programs boil down to appropriate Boolean expressions. €ÁHÌ ù ñ ËÿÂÓLjáѨúYßß ñz€ÁHÌc˓úUÂxLjà ñ†Â€Á1ÌÿÑú ÂWÂÓÇà ð ñ ËÿÁHÌÿѨúYßß ñzÂWÂÓLjÃUË@ú ÁHÌ ñ†ÂWÂxLjáѨú Algebra A double negative cancels out. The ability to formulate. Anything ÁHÌ ed with true is just true. One application of Boolean algebra is the analysis and simplification of Boolean expressions inside of programs. ǽÁ1ĄñzÂcÁH̀˓úYßPß ñðLjÁHÄà½úÈÂxLjà ñùǽÁHÄÈ˓ú ǽÁ1Ąñz€ÂÓÇÃU˓úYߐߩñùǽÁHÄݽú ÁHÌ ñùǽÁHÄÈ˓ú ÂÓLjà ÁHÌ Ç½Á1Ä Notice how the operator changes between and when the is pushed into an expression. €ÁHÌÝÄPÌHɽÆUߐ߀ĐÌ1É½Æ ÂxLjà ÁHÌ Both and distribute over each other. manipulate. These laws are called Boolean logic or Boolean algebra. ǽÁ1ĄñùǽÁHÄݽúYߐßРThe next two identities are known as DeMorgan’s laws. Here are some other interesting properties of Boolean operations. and ÁHÌ has similarities to addition. The following table shows some rules of algebra with their correlates in Boolean algebra: Boolean algebra ÂÓÇà ú w w ú false == false ÂÓÇà º ú … ú ú true == a ÁHÌ º false == a ú w ú ú º  ÂÓÇà From these examples. For example. we developed a loop condition for continuing the game that looked like this: . Let’s look at a few examples. Boolean expressions obey certain algebraic laws similar to those that apply to numeric operations. Above.

An application or two of DeMorgan’s condition and then put a laws can then get you to a simpler but equivalent version suitable for use in a ÛPÅÎÒHÀHÆ statement. continue playing. can be expressed using just these. This condition is no better than the first. we have to change the to when “distributing” the . This particular example illustrates a generally useful approach to loop conditions. alternative structures can sometimes be convenient. for certain kinds of problems. in principle. but negating complex conditions like this can be somewhat awkward. However. to say the least. we can transform this result. In that case. We’re pretty sure that’s correct. the program asks . rather than when the loop should continue. ‘«”|º xY…3˜™‚™g  ¢™£› › ™qe멲…Îg£¦Ÿƒ†…3¦§gI‚„‘ Ò£Í ÛPÅ4Ò1ÀPÆ Taken together. ÛPÅÎÒHÀHÆàÜPÑ£ÁHÌÆ Ú pß» Ö 9WÂÓLjÃÿÜHÑ1Á1ÌÆ pß " Ö 9„÷ ó¡Ñ1ÁÓÇÄ3ÒIǐɈV Æ 3ÀPÂ1Ï3ÒI§ Ç ! 3 u Now we have a version that is much easier to understand. If the user types an incorrect input. the decision structure ( ) along with a pre-test loop ( ) provide a complete set of control structures. simply write the loop termination LjÁHÄ in front of it.âP ´PgÑ­yètŒ{‡}Îsˆ‚1ƒ„ƒo‚HŠ”˜xyè}… ³ y腀}${ôˆ ÛPÅÎÒHÀHÆ Ç½Á1Ä©ñ‡ÜPÑ£ÁHÌ¨Æ Ú ßPß Ö"9€ÁHÌ ó¡Ñ£Á£ÇĽҀÇPɽÆV½ÀÂ1ϽҀÇC! ÜHÑ1ÁHÌ¨Æ WßPß rI´H~ u Ö"9ˆú¬÷ You can read this condition as something like: While it is not the case that player A has 15 or player B has 15. we know that the expression is equivalent to this: ñðLjÁHÄ ÜHÑ1ÁHÌ¨Æ Ú ßPß " Ö 9ˆú ÂÓÇà ñùǽÁ1Ä ÜPÑ1Á1ÌÆ Wßß  Ö 9½ú ÁHÌ ÂÓLjà ǽÁ1Ä Remember.  ȑ×ÈƒÊ ’dvBsut G·Gÿ ù¸ i§sqt %v#vxÍ Suppose you are writing an input algorithm that is supposed to get a nonnegative number from the user. Sometimes it’s easier to figure out when a loop should stop. This means that every algorithm ÛHÅ4Ò1ÀPÆ ÒÓÍ and the . continue playing. Once you’ve mastered the you can write every conceivable algorithm. Using a little Boolean algebra. This section outlines some of those alternatives. This reads simply as while player A has not reached 15 and player B has not reached 15. but we can go one step farther by pushing ǽÁ1Ä the s into the conditions themselves. Applying DeMorgan’s law.

this algorithm can be implemented with ‘ ” a by “seeding” the loop condition for the first iteration. Notice how this algorithm contains a loop where the condition test comes after the loop body. (  The flowchart depicting this design in shown in Figure . Well-engineered programs validate inputs whenever possible. † : Flowchart of a post-test loop. This is a post-test loop. You might notice that this is similar to the structure given earlier . Python does not have a statement that directly implements a post-test loop. Here is a simple algorithm: Ì" Æ ½ÆÂ1Ä !¨Æ1Äà ǐÉHʨ˽Æ1ÌWÍP̨ÁxÊ¡ÄHňÆÈÉ@ÜÓÆHÌ ÉÇ¨Ä3Ò1ÀYǐÉ1Ê˽Æ1Ì¡Ò¨Ü ( ßÝÕ The idea here is that the loop keeps getting inputs until the value is acceptable.rI´€r s@tŒuxw†y|{‡}½âP¾v‚Ó‚1w”˜Óyè} … ³ yè…x}‘{zˆ„uxŠŒ‹Ž±‚Ó‚g± {zuxŠŒˆ for another value. A post-test loop must always execute the body of the loop at least once. à à à€à €á ܧÚuÓuÔ Ý ìgá€Ü§ ö ÚuéÓuÔ® Ôuٝ ç º`Ô3ø Ù ï Öâ3Ùg֎á§Ú)Ö3Üeâ)ì ºàÚ3ÓgӀÔuÛâ€Ó éâ€Ó)öºÔ¤Ö Û%Ô3ÖeÚmì%Ö ÖuÜéÔ¡Ó æ g ì ö ìgö ºÔ3ٝçãÚmì ö%Ö}ê ×uì%ÖÔuٝâ å€Ú)ÖºÚ %Ô®ìgö ºÔ3Ù )ò Q‡Vˆ ‰ ” ” “’ Q‡Vˆ –• ˜— Q‡Vˆ ™ ’ Q‡Vˆ h—d™ This forces the loop body to execute at least once and is equivalent to the posttest algorithm. This process is called input validation. Unlike some other languages. It continues to reprompt until the user enters a valid value. However. Get a number number < 0? yes no Figure … . .

In the version ÒÓÍ of the post-test loop. Remember that a while loop continÌ1É½Æ ues as long as the expression in the loop heading evaluates to true. ˨Ìƨ" Â Î Ò£Í Notice that I placed the on the same line as the . which terminates the loop. when the value ¦ ˨Ìƨ"  Πof is nonnegative. However. Often a statement is used to leave what looks syntactically like an infinite loop. ÛPÅÎÒHÀH£ Æ Ì1ɽÆn÷ ǐÉ1Ê˽Æ1ÌWߡҀ) Ç É¨Ä„ñ  ǨÄÆHÌWV  ½ÁˆÜPÒÓĽ" Ò W¨Æ ǐÉ1Ê˽Æ1̙$ ÷ Óú G Ò£¥ Í ¦ ( ßÝÕo÷ ËÌƐ ÎÝó ¦½ÒÓÄÝÀPÁ" Á  Ò£ÍUÇPÉHÊˈÆH̡Ґè Ü WˆÂPÀÒ£Ãnï G ƨÀÜ£Æn÷ Ì3ÒIÇA Ä 3HňÆÈǐÉHʨ˽Æ1̀ÏÁÓÉ¡Æ£ÇĨÆH̨ÆPÃUÛˆÂˆÜ Ç½Á1£ Ä ½ÁˆÜPÒxÄ3" Ò W¨Æ' . This is legal when ÒÓÍ the body of the only contains one statement. the statement executes. ǐÉ1ÊˈÆHÌWß@¨3Ö ó@Å1ÄÂ1̐ÄUÛÎÒÓÄ1ÅÿÂÓÇ Ò1ÀÀPÆg!ÂPÀ`WˆÂPÀÓɽÆÈÄÁT!¨Æ1ÄÿҀǨÄÁcÄHňÆÝÀPÁPÁ „  ï ÛPÅÎÒHÀHÆ ÇÉ1Ê˽Æ1Ì Õn÷ F ǐÉ1Ê˽Æ1ÌWߡҀÇ)É¨Ä„ñ  ǨÄÆHÌWÂV½ÁˆÜPÒÓĽÒ"W¨Æ ǐÉ1Ê˽Æ1̙÷$Óú G Ò£ÍUÇPÉHÊˈÆHÌ Õo÷ F Ì3ÒIÇA Ä 3HňÆÈǐÉHʨ˽Æ1̀ÏÁÓÉ¡Æ£ÇĨÆH̨ÆPÃUÛˆÂˆÜ Ç½Á1Ä£½ÁˆÜPÒxÄ3Ò"W¨Æ' Do you see how the validity check gets repeated in two places? ˨Ìƨ"  ΠƨÀÜ£Æ Adding a warning to the version using only requires adding an Ò£Í to the existing . Some programmers prefer to simulate a post-test loop more directly by us˨ÌƐ ΠĘ̈ƨ Πing a Python statement. We need to add an so that the warning is not displayed for valid inputs. this is a bit awkward. Since is always true. It’s common to see a one-line Ò£c Í ¨Ó˨Ìƨ"  Πcombination used as a loop exit. It would be nice if the program ÛPÅ4Ò1ÀPÆ issued a warning explaining why the input was invalid. Interactive loops are naturally suited to a posttest implementation. Executing causes Python to immediately ˨ÌƐ Πexit the enclosing loop. Even this small example can be improved.âP ´PgÑ­yètŒ{‡}Îsˆ‚1ƒ„ƒo‚HŠ”˜xyè}… ³ y腀}${ôˆ rI´€” for the interactive loop pattern. this appears to be an infinite loop. ËÌƐ Π: Here is the same algorithm implemented with a ÛPÅÎÒHÀH£ Æ Ì1ɽÆn÷ ǐÉ1Ê˽Æ1ÌWߡҀ) Ç É¨Ä„ñ  ǨÄÆHÌWV  ½ÁˆÜPÒÓĽ" Ò W¨Æ ǐÉ1Ê˽Æ1̙$ ÷ Óú G Ò£¥ Í ¦ ( ßÝÕo÷ Ę̈ƨ ÎWó ¦½ÒxÄÐÀPÁPÁ  Ò£ÍUÇPÉHʨ˽ÆHÌàÒ¨è Ü WˆÂPÀÒÓßï G The first line may look a bit strange to you.

we have talked about Boolean expressions only within the context of other control structures. Either style is acceptable. Consider writing an interactive loop that keeps going as long as the user response starts with a “y.  ȑ×È‘É ² v#v6ٌim–Bw š6›•ÍQ“fimsqslnvxwQs –%s ±œ imœclnslnvxw%s So far. you could use a loop like this: . shows a flowchart of this approach to sentinel loops. However. One temptation that should generally be ˨Ìƨ"  Πavoided is peppering the body of a loop with multiple statements. You can see that this implementation is faithful to the first rule of sentinel loops: avoid processing the sentinel value. In fact. The loop and a half is an elegant way to avoid the priming read in a sentinel loop. Here is the general pattern of a sentinel loop implemented as a loop and a half: ÛPÅÎÒHÀH£ Æ Ì1ɽÆn÷ ü Æ1Äcǽ) Æ ¦HÄWãĈÂÐÒxÄÆxÊ Ò£Í€Ä1ŽÆàÒÓĨÆxÊ ÒÜYÄHŽơÜÓƣǨÄ3ҀLjƨÀ„÷ Ę̈ƨÂ"Î ̨ÁˆÑ1ÆˆÜÜ Ä1ŽÆàÒxÄÆxÊ ( ! Figure . This is called a loop and a half. there are times when even this rule should be broken to provide the most elegant solution to a problem. The logic of a loop is easily lost when there are multiple exits. Boolean expressions are so flexible in Python that they can sometimes lead to subtle programming errors.” To allow the user to type either an upper or lower case response.rI´ ¯  ȑ×È‘Ç ¸ %v#vxͧ–Bw £– §› þ s@tŒuxw†y|{‡}½âP¾v‚Ó‚1w”˜Óyè} … ³ yè…x}‘{zˆ„uxŠŒ‹Ž±‚Ó‚g± {zuxŠŒˆ –QÙ9 Some programmers would solve the warning problem from the previous section using a slightly different style. but the pattern can be quite handy. Boolean expressions themselves can act as control structures. ˨Ìƨ"  Πstatements or not is largely a matter The choice of whether to use of taste. Sometimes. Some purists frown on exits in the midst of a loop like this. ÛPÅÎÒHÀH£ Æ Ì1ɽÆn÷ ǐÉ1Ê˽Æ1ÌWߡҀ) Ç É¨Ä„ñ  ǨÄÆHÌWV  ½ÁˆÜPÒÓĽ" Ò W¨Æ ǐÉ1Ê˽Æ1̙$ ÷ Óú G Ò£¥ Í ¦ ( ßÝÕo÷ ËÌ¨Æ¨Â Î ó ¤¨Á" T Á ¡) Æ ¦½ÒxÄ ̽ҀÇ Ä XHňÆÈǐÉ1Ê˽Æ1̀ÏÁÓɡƣǨÄÆH̨ÆPÃUÛˆÂˆÜ ÇˆÁHE Ä ½ÁˆÜPÒxÄ3" Ò W¨' Æ  Here the loop exit is actually in the middle of the loop body.

For numbers (ints. and long ints) a zero value is considered as false.e. : Loop-and-a-half implementation of sentinel loop pattern.3). However. Python just used the ints 1 and 0 to represent true and false. Python is actually very flexible about what data type can appear as a Boolean expression. floats. Ì1É½Æ DˆÂÀÜ£Æ We have been using the bool literals and to represent the Boolean ßß values true and false. In fact. Actually. this is an infinite loop. Understanding why this condition is always true requires digging into some idiosyncrasies of Python Boolean expressions. ÛPÅÎÒHÀHÆUÌƈÜq½ÁÓÇ@ÜÓÆ û ÕgcßPßAŒÏ#ªÁ1ÌWÌƈÜq½ÁÓÇ@ÜÓÆ û ÕgcßPßA G“ #4÷ You must be careful not to abbreviate this condition as you might think of it in English: “While the first letter is ’y’ or ’Y”’.. ÛPÅÎÒHÀHÆUÌƈq Ü ½ÁÓÇ@ÜÓÆ û g Õ cßPA ß Œ# Ï ªÁ1& Ì  6@÷ G“ In fact. respectively. anything other than zero is taken as true. Before that. You can see how a value will be interpreted when used as a Boolean expression by explicitly converting the value to type bool. You already know that Python has a bool type.âP ´PgÑ­yètŒ{‡}Îsˆ‚1ƒ„ƒo‚HŠ”˜xyè}… ³ y腀}${ôˆ rI´€´ Get next Data item yes Item is the sentinel? no Process the item ( ! Figure . ) always evaluate to a value of type bool. You can test this out by where the values of 0 and 1 print as Ì1ɽÆc¥ á PÌHÉ½Æ evaluating the Expression . Any built-in type can be interpreted as a Boolean. this is a fairly recent addition to the language (version 2. The Python condition operators (i. the bool type is just a “special” int DˆÂPÀˆÜÓÆ Ì1É½Æ and . Here are a few examples: . The following form does not work.

Whatever the false value of “ was. the whole result is false. they have operational definitions that make them useful for other purposes as well. Python looks at the expressions left-to-right. Python should return a false result. –– – – – – – – . then the truth or falsity of the whole expression turns on the result of . It might take a bit of thinking to conÂÓLjà Á1Ì vince yourself that these descriptions of and faithfully reflect the truth tables you saw at the beginning of the chapter. return . return “ . Otherwise. Otherwise. the party is over. If “ is true. Although the main use of these operators is forming Boolean expressions. Simply returning guarantees that if is true. return . Ì1É½Æ DˆÂÀÜ£Æ If “ is false. return . the whole result is true. In order for this to be true. return . both expressions “ and must be true. Otherwise. that is what is returned. If “ turns out to be true. return “ . This table summarizes the behavior of these operators: operator ÂxLjà “ Á1Ì “ ǽÁ1Ä “ ǽÁ1Ä The definition of is straightforward. –– operational definition If “ is false. and if is false. The flexibility of Python Booleans extends to the Boolean operators. for sequence types. As soon as one of them is discovered to be false. If “ is false. an empty sequence is interpreted as false whereas any non-empty sequence is taken to indicate true.rI´€¹ (©()( (©()( (©()( (©()( (©()( (©()( (©()( s@tŒuxw†y|{‡}½âP¾v‚Ó‚1w”˜Óyè} … ³ yè…x}‘{zˆ„uxŠŒ‹Ž±‚Ó‚g± {zuxŠŒˆ ˽ÁPÁ¨À¬ñôÕ3ú ˽ÁPÁ¨À¬ñIÖPú ˽ÁPÁ¨À¬ñôިԈú ˽ÁPÁ¨À¬ñ"zňƨÀÀHÁ'Óú ˽ÁPÁ¨À¬ñ"©Óú ˽ÁPÁ¨À¬ñ û Ö@õôԉõèÞ)3ú DˆÂPÀˆÜÓÆ Ì1É½Æ Ì1É½Æ Ì1É½Æ DˆÂPÀˆÜÓÆ Ì1É½Æ Ë ÁPÁ¨À¬ñ û 3 ½  ú DˆÂPÀˆÜÓÆ As you can see. Similar reasoning can be Á1Ì ÁHÌ used to show that the description of is faithful to the logical definition of given in the truth table. ÂÓÇà Consider the expression “ .

this will always evaluate to true. sometimes listed in square brackets. the must always be true as well. so Python will always interpret it as true. the condition in this code can be simplified as follows: . and the second is a string. Á1Ì of the expressions Since at least one of the two expressions is always true. yet the flexibility of Python allows for certain succinct programming idioms that many programmers find useful. Now let’s take a look at our infinite loop problem: ÌƈÜqˆÁ£Ç@ÜÓÆ û Õ)cßPßAŒÏ6ªÁHÌ& G“ 6 Treated as a Boolean expression.âP ´PgÑ­yètŒ{‡}Îsˆ‚1ƒ„ƒo‚HŠ”˜xyè}… ³ y腀}${ôˆ rI´€¿ These operational definitions show that Python’s Boolean operators are shortcircuit operators. You may wonder about the wisdom of this design. The first thing to notice is that the Boolean operator is combining two expressions. Let’s look at an example. Here is an example code fragment: ÂÓÇ4Ü ß€ÌˆÂÓÛmÌÒIÇ©PÉĄñ"34HÅ3Â1ÄUÍÀPÂW¨ÁHÌWÐÁcÏÁ£ÉÝۈÂÓÇ¨Ä Ò£ÍÐÂxÇ@ܽ–ßA©@÷ ÍÀP  WÁ1ÌWßÐÂÓÇ4Ü Æ¨ÀÜ£Æo÷ ÍÀP  WÁ1ÌWA ß XWÂÓÇÎÒHÀÀPB   ûˆ W ÂxÇ4Ò1ÀÀÂŸ÷ü£ú “ ÂÓÇ4Ü Exploiting the fact that the string in can be treated as a Boolean. Frequently. this expression returns either (reßß ÌƈÜqˆÁ£Ç@ÜÓÆ û Õ)  # ̨ƽÜqˆÁ£Ç4Ü£Æ û Õ) turned by when is “y”) or (when is not a “y”). programs prompt users for information but offer a default value for the response. It is a nonempty string. That means that a true or false value is returned as soon as the ÂÓLjà ÁHÌ where the first expression is false and in an where result is known. the strange behavior of this example is due to some quirks in the definitions of the Boolean operators. So. Here is an equivalent parenthesized version: ñ–̨ƽÜu½Á£Ç4Ü£Æ û Õ)Èߐß&†Ï#£ú ÁHÌ©ñ “  #Óú¬÷ Á1Ì PÌHÉ½Æ By the operational description of . This is one of the few places where the design of Python has a potential pitfall for the beginning programmer. A more logic-oriented way to think about this is to simply look at the second expression. In an the first expression is true. Either of these results is interpreted by Python as true. Python will not even evaluate the second expression. The default value. the first is a simple condition. is used if the user simply hits the Ó Enter 0 key.

An interactive loop allows portions of a program to be repeated according to the wishes of the user. When using an indefinite loop. XWÂÓÇ4Ò1ÀÀPB   ƨÀÜ£Æ as false. any nonempty answer is interpreted as “true. The same idea can be more succinctly coded by treating the strings themÁ1Ì selves as Booleans and using an . which Python interprets 0 . by all means. If you like this style. this task can easily be accomplished in a single line of code. ‘«”–ê  ˜Ÿi„¤n…‚™g © ¦§›¥› ingIí This chapter has filled in details of Python loops and Boolean expressions. It continues to iterate as long as the loop condition remains true. feel free to use it. Just make sure that your code doesn’t get so tricky that others (or you) have trouble understanding it. ÂÓÇ4Ü ß€ÌˆÂÓm Û ÌÒI© Ç PÉĄ" ñ 34HÅ3Â1ÄUÍÀP  W¨ÁHÌWÐÁcÏÁ£ÉÝۈÂÓÇ¨Ä û WˆÂxÇ4Ò1ÀÀ  Ÿü ÷ £ú ÍÀP  W¨ÁHÌWßàÂÓÇ4Ü ÁHò Ì 3WˆÂÓÇÎÒHÀPÀB   Á1Ì ÒÓÍC¨HƨÀˆÜÓÆ The operational definition of guarantees that this is equivalent to the version. Remember. Here are the highlights: ’ A Python ͨÁ1Ì loop is a definite loop that iterates through a sequence. programmers must guard against the possibility of accidentally writing an infinite loop.rI´€â s@tŒuxw†y|{‡}½âP¾v‚Ó‚1w”˜Óyè} … ³ yè…x}‘{zˆ„uxŠŒ‹Ž±‚Ó‚g± {zuxŠŒˆ ÂÓÇ4Ü ß€ÌˆÂÓÛmÌÒIÇ©PÉĄñ"34HÅ3Â1ÄUÍÀPÂW¨ÁHÌWÐÁcÏÁ£ÉÝۈÂÓÇ¨Ä Ò£ÍÐÂxÇ@ܬ÷ ÍÀP  WÁ1ÌWßÐÂÓÇ4Ü Æ¨ÀÜ£Æo÷ ÍÀP  WÁ1ÌWA ß XWÂÓÇÎÒHÀÀPB   ûˆ W ÂxÇ4Ò1ÀÀÂŸ÷ü£ú Here a Boolean condition is being used to decide how to set a string variable. ’ One important use for an indefinite loop is for implementing the programming pattern interactive loop. ÍÀP  W¨ÁHÌWßẄÂÓm Û Ì¨Ò€© Ç PÉĉñ 34HÅ3£ÄUͨÀÂ WÁH̀èÁcÏÁÓÉÝÛ½ÂxÇÄ û WÂÓÇÎÒHÀÀPg  næ ÷ £ú Á1& Ì XWÂÓÇ4Ò1ÀÀPÂB I don’t know whether it’s really worthwhile to save a few lines of code using Boolean operators this way. ’ A Python ÛHÅ4Ò1ÀPÆ statement is an example of an indefinite loop. . In this case. If ǨÄÆ1Ì ÂÓÇ4Ü the user just hits ÓåG will be an empty string. the empty string will be replaced by in the clause.” In fact.

’ Loops are useful for reading files. and . int) may also be used where Boolean expressions are expected. can be nested. When designing nested loop algorithms. 2. a file loop is generally implemented using a sentinel loop pattern. it is best to consider the loops one at a time. Even though Python has a built-in data type. In so it is particularly easy to process a file line-by-line using a other languages. like other control structures.âP ¿PCŽŒ{I} ³Œ6 ˆ–{ôˆ ’ A sentinel loop is a loop that handles input until a special value (the sentinel) is encountered. . ‘«”sr egf„‚™gIƒæ‡‘‚„‘ rI´€é hjiCkmlniCoqpIrQi§sutqlnvxw%s y{zH|c})~Q©€cˆ‚3} 1. Sentinel loops are a common programming pattern. ’ Python Boolean operators ÂÓÇà and Á1Ì employ short-circuit evaluation. The counted loop pattern uses a definite loop. ’ Nonstandard loop structures such as a loop-and-a-half can be built using a ÛPÅ4Ò1ÀPÆ Ì1É½Æ Ë¨ÌƐ Πloop having a loop condition of and using a statement to provide a loop exit. 3. a programmer must be careful that the sentinel is not processed. . ’ Complex Boolean expressions can be built from simple conditions using ÂÓLjà ÁHÌ Ç½Á1Ä the Boolean operators . They also have operational definitions that allow them to be used in cerˈÁÁÀ tain decision contexts. DeMorgan’s laws describe how to negate Boolean ÂxLjà Á1Ì expressions involving and . other data types (e. A sentinel loop should not actually process the sentinel value.g. Python treats a file as a sequence of lines. 4. A Python ÛHÅ4ÒHÀHÆ implements a definite loop.. A sentinel loop asks the user whether to continue on each iteration. ’ Loops. In writing a sentinel loop. ͨÁ1Ì loop. Boolean operators obey the rules of Boolean algebra.

The easiest way to iterate through the lines of a file in Python is to use a ÛPÅ4Ò1ÀPÆ loop. The Boolean operator returns when both of its operands are true. ÁHÌ Ì1É½Æ 7. A is a post-test loop. Ì1ɽÆWÁ1¥ Ì DˆÂÀÜ£Æ 10. ǽÁ1Ąñ†Â€Á1Ìc˓úYßPß ñðǽÁ1Äà½ú Á1ÌcǽÁHĉñðË@ú 9. Which of the following is not a valid rule of Boolean algebra? ñ PÌHɽÆcÁHÌ ¦ÎúYßPßTÌ1É½Æ Ò a) ñ DˆÂPÀˆÜ£ÆÝÂxLjT ¡ à ¦3ú ߐT ß DˆÂPÀˆÜÓÆ b) ǽÁ1Ąñz€ÂÓÇÃU˓úYߐßcLjÁHĄñz½ú ÂxLjÃULjÁHĄñù˓ú c) ñ PÌHɽÆcÁH¥ Ò Ì DˆÂPÀˆÜÓÆ3ú ßP  ß PÌHÉˆÆ d) . ƒ |§„3…‡†§ˆ}Iˆj‰cŠ§…Œ‹"} 1. What statement can be executed in the body of a loop to cause it to terminate? Ò£Í ÒI© Ç PÉÄ Ę̈ƨ" Â Î Æ ¦½ÒxÄ ) b) c) d) a) 6. A priming read is part of the pattern for a(n) a) interactive loop b) end-of-file loop c) sentinel loop d) infinite loop 5. A loop structure that tests the loop condition after executing the loop body is called a a) pre-test loop b) loop-and-a-half c) sentinel loop d) post-test loop 4.rI¹7 s@tŒuxw†y|{‡}½âP¾v‚Ó‚1w”˜Óyè} … ³ yè…x}‘{zˆ„uxŠŒ‹Ž±‚Ó‚g± {zuxŠŒˆ 5. ÂÝÂÓLjà ñùË¡ÁHÌÿѨúYßß ñ†ÂÝÂxLjÃÈË@úUÁ1Ì©ñ†ÂWÂxLjáÑú 8. ÛHÅ4ÒHÀHÆ 6. A loop pattern that asks the user whether to continue on each iteration is called a(n) a) interactive loop b) end-of-file loop c) sentinel loop d) infinite loop 2. A loop pattern that continues until a special value is input is called a(n) a) interactive loop b) end-of-file loop c) sentinel loop d) infinite loop 3.

Hint: including columns for intermediate expressions is helpful.e.. Compare and contrast the following pairs of terms: (a) Definite loop vs. Indefinite loop (b) For loop vs. for every possible combination of “input” values. Note: 999 should not be part of the sum. (d) The number of times a whole number ø can be divided by 2 (using integer division) before reaching 1 (i. Write a loop fragment that calculates the following values: (a) Sum of the first n ù g¤%ø ÷Uø numbers: (b) Sum of the first n odd numbers: … y …   x   ” ™ ji ¡  y hžhžh  hžhžh  ø  ¡øç†V… (c) Sum of a series of numbers entered by the user until the value 999 is entered.âP ¿PCŽŒ{I} ³Œ6 ˆ–{ôˆ rI¹H~ 7. û ø ). A loop that never terminates is called a(n) a) busy b) indefinite c) tight d) infinite ÂxLjà 8. Which line would not be found in a truth table for ? a) T T T b) T F T c) F T F d) F F F 10. The term for an operator that may not evaluate one of its subexpressions is a) short-circuit b) faulty c) exclusive d) indefinite  …Œ‚3‹|c‚8‚X…ŒŠm 1. End-of-file loop 2. Sentinel loop (d) Sentinel loop vs. ǽÁ1Ä©ñ ƒ ÂxLjà „ ú (a) ñðLjÁHÄ ƒ úÈÂÓÇà „ (b) ñðLjÁHÄ ƒ ú ÁHÌ ñùǽÁHÄ „ ú (c) ñ ƒ ÂÓLjà „ ú ÁHf Ì e (d) ñ ƒ ÁHf Ì e úÈÂÓÇà ñ „ Á1f Ì e ú (e) ÛPÅÎÒHÀHÆ 3. Give a truth table that shows the (Boolean) value of each of the following Boolean expressions. While loop (c) Interactive loop vs. µ ”mi . Which line would not be found in a truth table for ? a) T T T b) T F T c) F T F d) F F F Á1Ì 9.

The input will be an annualized interest rate. where ø is a value entered by the user. ’ ’ ¹kj ¶$l „ is the wind speed Write a program that prints a nicely formatted table of windchill values. The National Weather Service computes the windchill index using the following formula: y x©hˆ‡  wchi£¡c…uxih †æy x©hˆ‡"xC‚ )q )q gq gq gqQ&gq ’ ¹kj ¶$l „  wch H¡‡"xih¦‚ Where h is the temperature in degrees Fahrenheit. 4. you can use $1. Each number in the sequence (after the first two) is the sum of the previous two. Write a program that uses a loop to determine how long it takes for an investment to double at a given interest rate. The Fibonacci sequence starts … u… ô¡ ëy ëx žhžhžh . – ö§‚”“•„ º “BýÓ¡ y“  … if x is even if x is odd gq gqQ&gq q gq 7 . The Syracuse (also called Collatz or Hailstone) sequence is generated by starting with a natural number and repeatedly applying the following function until reaching 1: “ m For example. ÛPÅÎÒHÀHÆ 3. 5. It is an open question in mathematics whether this sequence will always go to 1 for every possible starting value. and the columns represent temperatures from -20 to +60 in 10-degree increments. Write a program that computes and outputs the nth Fibonacci number. If ø is not prime. and the output is the number of years it takes an investment to double. 2. and in miles per hour.rI¹€r ’”“fv••“H–B—$—˜l™wm•S’”“Hv •ÙŒi•—îs £¾ s@tŒuxw†y|{‡}½âP¾v‚Ó‚1w”˜Óyè} … ³ yè…x}‘{zˆ„uxŠŒ‹Ž±‚Ó‚g± {zuxŠŒˆ 1. Write a program that gets a starting value from the user and then prints the Syracuse sequence for that starting value. the Syracuse sequence starting with x is: x u…ui ¡ ô¡ u… . Rows should represent wind speed for 0 to 50 in 5 mph increments. Write a program that accepts a value of ø as input and determines if the value is prime. Note: the amount of the initial investment does not matter. your program should quit as soon as it finds a value that evenly divides ø . A positive whole number øè0С is prime if no number between ¡ and ø (inclusive) evenly divides ø .

The program should print these two totals after all the data has been processed. 10. " 9. The program will first prompt for the starting odometer reading and then get information about a series of legs. To find the end of input. 11. The program should print out the miles per gallon achieved on each leg and the total MPG for the trip. The user signals the end of the trip with a blank line. If the temperature is above 80. that is. the line with the best fit through a collection of points. the amount over 80 is added to the cooling degree-days. place a small rectangle labeled “Done” in the lower left corner of the window. 8. 7. Modify the previous program to get its input from a file. Starting with the values # and ø .âP ¿PCŽŒ{I} ³Œ6 ˆ–{ôˆ rI¹€” 6. If the average temperature for a day is below 60. For each leg. checks to make sure that it is even. 13. Write a program that computes the fuel efficiency of a multi-leg journey. The Goldbach conjecture asserts that every even number is the sum of two prime numbers. and then finds two prime numbers that sum to the number. Write a program that gets a number from the user. we repeatedly apply Ǚõ ÊÿßÈʄõ Ç ÓÊ the formula: until # is 0. the program will stop gathering points when the user clicks inside that rectangle. then the number of degrees below 60 is added to the heating degree-days. The greatest common divisor (GCD) of two values can be computed using Euclid’s algorithm. Write a program that finds the GCD of two numbers using this algorithm. the user enters the current odometer reading and the amount of gas used (separated by a space). Heating and cooling degree-days are measures used by utility companies to estimate energy requirements. ø is the GCD of the original # and ø . Modify the previous program to find every prime number less than or equal to ø . Modify the previous program to get its input from a file. . At that point. Write a program that accepts a sequence of average daily temps and computes the running total of cooling and heating degree-days. Write a program that graphically plots a regression line. 12. First ask the user to specify the data points by clicking on them in a graphics window.

When the user clicks inside the “Done” rectangle. . the program should draw them in the graphics window and keep track of the count of input values and the running sum of “ . the program then computes value of (using the equations above) corresponding to the “ values at the left and right edges of the window to compute the endpoints of the regression line spanning the window.rI¹ ¯ s@tŒuxw†y|{‡}½âP¾v‚Ó‚1w”˜Óyè} … ³ yè…x}‘{zˆ„uxŠŒ‹Ž±‚Ó‚g± {zuxŠŒˆ The regression line is the line with the following equation: where # – – – n ºon  #悔“ † “•„ n “§r ºqp “ rµ †‰ø “ µ n is the mean of the x-values. and – rQ†‰ø “ n – n ø is the As the user clicks on points. “ µ and “ values. the program will pause for another mouse click before closing the window and quitting. – – – . n number of points. After the line is drawn. “ p is the mean of the y-values.

By interesting. ’ To understand and be able to apply top-down and spiral design techniques in writing complex programs. You now have all the tools to write programs that solve interesting problems. ’ To understand unit-testing and be able to apply this technique in the implementation and debugging of complex programs. ’ To understand pseudorandom numbers and their application in Monte Carlo simulations. but you have reached a significant milestone in the journey to becoming a computer scientist. One particularly powerful technique for solving real-world problems is simulation. but you can do some nontrivial computing. I mean problems that would be difficult or impossible to solve without the ability to write and implement computer algorithms.QSRUTWVYXa`cb0s ¨ ¥4e gq©Hr ¨§¥¥§¦ 1 rs¦t òV¥Hv ¦ x€y31‚„ƒ†…ˆ‡‰„‚„‘ ’ To understand the potential applications of simulation as a way to solve real-world problems. Computers can model real-world processes to provide otherwise unobtainable information. Computer simulation ­ ® is used every day to perform myriad 5 . —«”–“ ©«‡p› ¦•j i„…ˆ‡penš dc ©˜ îiŸƒ «¦Ÿ‚æ…3y™i„j j You may not realize it. You are probably not yet ready to write the next great killer application.

rI¹€¹ s4tvuxwzy|{I}3éHî˜ 6 ƒ„…± u†y 6 ‚1Š„uxŠv‹ 4 é {ôˆ 6 1Š tasks such as predicting the weather. they could let the computer model thousands of games between players of differing skill levels. plays racquetball. Maybe it is the nature of the game itself that small differences in ability lead to lopsided matches on the court. Or perhaps the other players are really much better than he is. he didn’t want to waste money on an expensive sports psychologist if it wasn’t going to help. Over years of playing. Along the way. but against Denny. One obvious possibility is that Denny Dibblebit’s problem is in his head. Let’s write our own racquetball simulation and see what Susan and Denny discovered. but even relatively modest simulations can sometimes shed light on knotty problems. Since there would not be any mental aspects involved. Denny Dibblebit. he has noticed a strange quirk in the game. Denny was discussing racquetball with Susan. It has aspects similar to many other ball and racquet . and entertaining video game players. you will learn some important design and implementation strategies that will help you in tackling your own problems. designing aircraft. One day. Most of these applications require extremely complex programs. he always seems to get thumped. On the surface. Denny was intrigued by the idea. He often competes with players who are just a little bit better than he is. they seem to win the lion’s share. one would think that players who are slightly better should win slightly more often. This has led him to question what is going on. Maybe his mental game isn’t up to par with his physical skills. and he just refuses to see it. In the process. But how could he figure out if the problem was mental or just part of the game? Susan suggested she could write a computer program to simulate certain aspects of racquetball. Using the simulation. the simulation would show whether Denny is losing more than his share of matches. when she suggested another possibility. to name just a few. In this chapter we are going to develop a simple simulation of the game of racquetball. creating special effects for movies. losing the vast majority of matches. tȃÊ'È‘Ç Ú w%–QÙ Cslns°–Bw ¤ §› Ø Í'imœcl@u{œ)–mtqlnvxw Racquetball is a sport played between two players using racquets to strike a ball in a four-walled court. tȃÊ'ÈƒÊ Ú Ø l™—$r•ÙŒ–§tqlnvxw ’”“fv Bٌi•— £¾ Susan Computewell’s friend.

one of the players puts the ball into play—this is called serving. Here is an example: ü €Ê3ƽܣŨ҇ÊɽÀÂ£ÄÆPÃn÷°9HÕÕ 4ÎҀÇ4Ü Í¨Á1Ì Ú ÷˜ÔPø)eòñ39HÞnïðø Îú 4ÎҀÇ4Ü Í¨Á1Ì ™÷˜ÔPÞÔ ñ dønf ë ï d Îú  €u"" Notes: All inputs are assumed to be legal numeric values. If the server wins the rally. To start the game. the ability-level of the players will be represented by the probability that the player wins the rally when he or she serves. In our simulation. The program will prompt the user to enter the service probability for both players and then simulate multiple games of racquetball using those probabilities. The program will then print a summary of the results. The rally ends when one of the players fails to hit a legal shot. no error or validity checking is required. squash. then service passes to the other player. badminton. player A serves first. a point is awarded. Here is a detailed specification: Input The program first prompts for and gets the service probabilities of the two players (called “Player A” and “Player B”). etc. Players can only score points during their own service. this is a rally. table tennis. just the basic outline of the game. players with a 0. Output The program will provide a series of initial prompts such as the following: Ú ÛÎÒIÇ@ÜUÂàÜ£Æ1Ì©W¨Æ§P WÛÎÒIÇ@ÜUÂàÜ£Æ1Ì©W¨Æ§P ¢ˆÁ1ÛUÊÎÂÓǨϠ!€Ê3Æ½Ü Ä¨Á¡ÜPÒvÊÉ3ÀPÂ1Ĩ§ Æ P 4PÅ3£ÄÿÒ¨ÜYÄ1ŽÆ`̨Á£Ëhï 4PÅ3£ÄÿÒ¨ÜYÄ1ŽÆ`̨Á£Ëhï 3ÀPÂ1ÏÆ1Ì 3ÀPÂ1ÏÆ1Ì # The program will print out a nicely formatted report showing the number of games simulated and the number of wins and winning percentage for each player. The players then alternate hitting the ball to keep it in play. The player who misses the shot loses the rally. In each simulated game. If the loser is the player who served. . volleyball. Thus. The first player to reach 15 points wins the game.éP ~x"˜ 6 ƒ„…± u†y 6 ŠŒ ¨u ³ H…†{ôy Œu± ± 2i • w rI¹€¿ games such as tennis.6 probability win a point on 60% of their serves. Then the program prompts for and gets the number of games to be simulated. We don’t need to understand all the rules of racquetball to write the program.

The service probability provides a likelihood that a given serve will be won. A driving simulation must model the unpredictability of other drivers. With a carefully chosen function. Of course. A similar approach can be used to generate random (actually pseudorandom) numbers. the current value is fed back into the function to produce a new number. A pseudorandom number generator works by starting with some seed value. Overall. so you get a different seed value each time the program is run. This apparent randomness came from repeatedly applying a function to generate a sequence of numbers. a bank simulation has to deal with the random arrival of customers. if you start the process over again with the same seed value. Remember the chaos program from Chapter 1? The numbers produced by that program seemed to jump around randomly between zero and one. It’s more like a coin toss. When we say that a player wins 50% of the serves. you end up with exactly the same sequence of numbers. This means that you will also get a unique sequence of pseudorandom values. we expect that half the time the coin will come up heads and half the time it will come up tails. Many simulations share this property of requiring events to occur with a certain likelihood. they are instruction-following machines. How can computer programs model seemingly random happenings? Simulating randomness is a well-studied problem in computer science. nudge. our racquetball player should win or lose rallies randomly. 1 Of course.rI¹€â —«”–• —î‘‚™¦Ÿ·§™ îi„e™·•™£› ©c s4tvuxwzy|{I}3éHî˜ 6 ƒ„…± u†y 6 ‚1Š„uxŠv‹ 4 é {ôˆ 6 1Š § ¦•›¥y²‚™gI‘ Our simulation program will have to deal with uncertain events. . but there is nothing to prevent a run of five tails in a row. Python provides a library module that contains a number of useful functions for generating pseudorandom numbers. These sorts of simulations are sometimes called Monte Carlo algorithms because the results depend on “chance” probabilities. Similarly. that does not mean that every other serve is a winner. It’s all determined by the generating function and the value of the seed. but there is no set pattern. The two functions of ÌÂÓLjÃḦÂx§ Ç !¨Æ ̈ÂÓÇèÁ€Ê and . greatest interest to us are 1 So probabilistic simulations written in Python could be called Monte Python programs (nudge.wink). The next time a random number is needed. The functions in this module derive an initial seed value from the date and time when the module is loaded. This value is fed to a function to produce a “random” number. wink. you know that there is nothing random about computers. the resulting sequence of values looks essentially random.

returns some exactly as with the û Ö@õôԉõèބõHdoõë9 ÌÂÓLjÃḦÂxǧ!¨Æ¬ñ39æõ‡ÖxÕ©9‰õÒ9½ú number from the range . For example. (Remember.éH rH¨ˆ–{I…Œ‹€‚ ¨uxŠv‹I‚Hƒ €i Ž¨ Í ­…€ƒ ‡{‡}$ˆ rI¹€é ÌÂÓLjÃḦÂxǧ!¨Æ The function is used to select a pseudorandom int from a given range. Over the long haul. Here is an inter̈ÂÓÇÃPÌÂÓ§ Ç !Æ active session that shows in action: Ê ½Á1̐ĀÌÂÓÇÃP̈Âx§ Ç !Æ (©()( ÍP̨Áxʡ̈ÂxLjÐÁxÊ»ÒvC ˆ Ì x  ˆ Ç P à  Ì Ó Â Ç C ¨ ! æ Æ I ñ “ Ö è õ 3 ø ú (©()( Þ Ç !¨ÆæñI֓õèø3ú (©()( ̈ÂxLjÃPÌÂÓC Þ Ç !¨ÆæñI֓õèø3ú (©()( ̈ÂxLjÃPÌÂÓC 9 (©()( 9 (©()( 9 (©()( ̈ÂxLjÃPÌÂÓÇC!¨ÆæñI֓õèø3ú ̈ÂxLjÃPÌÂÓÇC!¨ÆæñI֓õèø3ú ̈ÂxLjÃPÌÂÓÇC!¨ÆæñI֓õèø3ú ̈ÂxLjÃPÌÂÓÇC!¨ÆæñI֓õèø3ú ̈ÂxLjÃPÌÂÓÇC!¨ÆæñI֓õèø3ú ̈ÂxLjÃPÌÂÓÇC!¨ÆæñI֓õèø3ú Ö (©()( 9 (©()( d (©()( Ô ÌˆÂÓÇÃPÌÂÓǧ!Æ Notice it took nine calls to to eventually generate every number in the range 1–5.) ÌÂÓLjÃḦÂx§ Ç !¨Æ Each call to generates a new pseudorandom int. which means that all values will appear an (approximately) equal number of times. It can be used with one. two. Here are some interactive examples: Ê ½Á1̐ĀÌÂÓÇèÁxÊ (©()( ÍP̨Áxʡ̈ÂxLjÐÁxÊ»ÒvC (©()( ̈ÂxLjèÁ€Ê™ñ‡ú . inclusive. this function produces a uniform distribution. or three parameters to specify a range ̈Âxǧ!¨Æ ÌÂÓÇÃP̈Âxǧ!Ææñ€Ö@õ–ø½ú function. ranges go up to. The value 5 came up almost half of the time. This shows the probabilistic nature of random numbers. It takes no parameters and returns values uniformly distributed between 0 and 1 (including 0. the stopping value. but excluding 1). and returns a multiple of 5 between 5 and 100. but do not include. ÌÂÓLjÐÁxÊ The function can be used to generate pseudorandom floating point values.

(The goes on the upper º end.7 the other 30% of the time. Let’s look at a specific example.7. ̈ÂÓÇèÁ€Ê Our racquetball simulation can make use of the function to determine whether or not a player wins a serve. which gives rise to the funny-looking import line. . Suppose a player’s service probability is 0. because the random generator can produce a 0. This means that they should win 70% of their serves. I’ll wait.7.70. the condition ̈ÂxLjÐÁxʙñ‡ú ̨Á£Ë will succeed with just the right probability. Go ahead and take a few minutes to write up the program. but never a 1.rI¿7 ÕnïH9gdc93Ödø)dÕøþÔ©9 (©()( ̈ÂxLjèÁ€Ê™ñ‡ú ÕnïðԐԽÖxø¨Ô½Öx© ø 9©9)e3 Ö d (©()( ̈ÂxLjèÁ€Ê™ñ‡ú Õnïùý¨g Ô e©eþPþÞPc Þ 93 Ö 9Pþ (©()( ̈ÂxLjèÁ€Ê™ñ‡ú Õnïð© Ô 9geøøP© Õ e) Ô ec9H© Þ e (©()( ̈ÂxLjèÁ€Ê™ñ‡ú Õnf ï ec9Hý) Þ døþPý) Þ dÞø s4tvuxwzy|{I}3éHî˜ 6 ƒ„…± u†y 6 ‚1Š„uxŠv‹ 4 é {ôˆ 6 1Š ̈ÂÓÇèÁ€Ê The name of the module ( ) is the same as the name of the function.) In general. Exactly 70% of the interval 0 hžhžh 1 is to the left of 0. ̨Á£Ë if represents the probability that the player wins a serve. Suppose we generate a random value between 0 and 1. and it will be q 0. So 70% of the time the random number will be Ó 0. Here is how the F decision will look: ң̀ÌÂÓÇèÁxʟñIú ÜPÑ£ÁHÌÆUß F —«”– ¨ÌÁÓ˄÷ ÜHÑ1Á1ÌÆcá»Ö — ™²¤˜g•«ª™„œce «ª‚„‘ˆ‡šqe Now you have the complete specification for our simulation and the necessary knowledge of random numbers to get the job done. You can imagine a decision in the program something like this: Ò£Í F 3ÀPÂ1ÏÆ1ÌcÛÎÒIÇ@ÜWÜÓÆHÌ©W¨Æ ( ÜPÑ£ÁHÌÆUß ÜHÑ1Á1ÌÆcá»Ö ÷ We need to insert a probabilistic condition that will succeed 70% of the time.

Then you just put all the pieces back together and. Let’s give it a try on our racquetball simulation and see where it takes us. As always. You may not even know where to begin. a good start is to study the program specification. but I don’t really want to bother with it right now.éP ”P£ã¨‚1wkiHé4‚Œ’nŠ 4 é {zˆ 6 1Š rI¿H~ OK. It seems an unimportant part of the algorithm. Whatever we don’t know how to do. voil` a. Imagine that all of the components you need to implement the algorithm have already been written for you. The basic idea is to start with the general problem and try to express a solution in terms of smaller problems. Here is a basic algorithm: ؐ̽ҀǨÄÐÂÓ Ç ¢IǨĐ̨ÁPÃ1ÉÎÑÓĽÒ1Á£Ç ü Æ1ÄWÄHňÆàҀ© Ç PÉÄ3Üæ÷ ¨ÌÁ£Ë Ú I õ ¨ÌÁÓË nõ Ç ÅÒvÊɽÀÂ1Ä¨Æ @ Ç !ÂIÊÎÆˆÜ ÁPÍWÌˆÂ¨Ñ í£É½ÆHÄ1Ë3ÂPÀÀªÉ@ÜPÒI§ Ç !£¨ÌÁ£Ë Ú ÂÓÇ£ à ̨Á£Ë ؐ̽ҀǨÄÐÂcÌÆ ˆÁHÌPÄÝÁ£ÇÐÄ1ŽÆUÛÎÒIÇ@Ü ÍÁHE Ì 3ÀPÂ1ϨÆHÌ Ú ÂÓÇ£ à 3ÀÂ£ÏÆ1Ì  g  Now that we’ve got an algorithm. seriously. I know what you’re thinking: this design is too high-level. It just requires a few print statements. I’ll procrastinate and pretend that someone else will do it for me. we’ll just ignore for now. First we have to print an introduction. and print out a report. you don’t have any idea yet how it’s all going to work. Your job is to finish this toplevel algorithm using those components. I think I know how to do this. we’re ready to write a program. Eventually the problems get so small that they are trivial to solve. If you’re going to make it through with minimal frustration. output pattern. this is a more complicated program than you’ve probably attempted so far. Here’s the beginning of the program: èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ% Ä ¢IǨĐÌÁ¬ñIú ¨Ì3ҀǨÄQ¢‡ÇĐ̨Á Do you see how this works? I’m just assuming there is a function that takes care of printing the instructions. you’ll need a systematic approach. simulate a bunch of games. One proven technique for tackling complex problems is called top-down design. this program follows the basic input. process. That’s OK. you’ve got a program. . Then each of the smaller problems is attacked in turn using the same technique. In very broad brush strokes. We need to get the simulation inputs from the user. tȑÉÈƒÊ ÿ é·!¸ vxÍ miCk§iQÙ œ i§slŒ•w Top-down design is easier to illustrate than it is to define. That step was easy! Let’s move on.

let’s move on to the next line. that doesn’t seem very interesting. What information do you need to get back from your friend? Well. We need to simulate games of ̨Á£Ë Ú ̨Á£Ë racquetball using the values of and . and I feel like putting off the details. . Here’s the complete program: . I need to get some inputs from the user. Remember in the discussion of functions in Chapter 6. èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ% Ä ¢IǨĐÌÁ¬ñIú ̨Á£Ë Ú I õ ̨Á£Ë nõîÇ¡¥ ß !¨Æ1Q Ä ¢‡© Ç É¨ÄÎÜ@ñIú ÛÎÒIÇ@Ü Ú õ ÛÎÒIÇ@Ü Wß ÜP҇§ Ê Ð ü €ÊÎƈܓñùǙõ ÌÁÓË Ú I õ ̨Á£Ë Îú %  %m  Are you getting the hang of this? The last step is to print a report. What information would you have to give him? Your friend would need to know how many games he was supposed to simulate and what the values of ̨Á£Ë Ú ÌÁÓË and should be for those simulations. (Maybe we can get someone else to ÊÎÂÒIÇ ? Let’s call our write that part for us later. The function must return these values for the main program to use. Given this analysis. in a sense. and . Ç Here we’ve hit the crux of the problem. I really don’t have a very good idea how that will even be accomplished. Here is our program so far: èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ% Ä ¢IǨĐÌÁ¬ñIú ̨Á£Ë Ú I õ ̨Á£Ë nõîÇ¡¥ ß !¨Æ1Q Ä ¢‡© Ç É¨ÄÎÜ@ñIú  % We’re making progress.rI¿€r s4tvuxwzy|{I}3éHî˜ 6 ƒ„…± u†y 6 ‚1Š„uxŠv‹ 4 é {ôˆ 6 1Š Next. Ç Suppose you were asking a friend to actually carry out a simulation of games. I also know how to do that—I just need a few input statements. you would have to tell him how many wins there were for each player. If you told your friend to type up the report. Let’s procrastinate again and push the details off into a function. Again.) But what should we put into ÜPÒvm Ê Ð ü €Ê3Æ½Ü function . These must be ÜP҇§ Ê Ð ü €ÊÎÆˆÜ outputs from the function. these values are inputs to the function. We’ll call the function . I said that parameters were used as function inputs. and return values serve as function outputs. The point of this function ÌÁÓË Ú ÌÁÓË Ç is to get values for variables . This time. Let’s assume that a component already exists to !¨Æ1Q Ä ¢I) Ç É¨ÄÎÜ solve that problem. be inputs to the function. in order to finish out the program (print a report) you need to know how many games were won by player A and how many games were won by Player B. we now know how the next step of the algorithm can be coded. We need to figure out what the call of this function looks like. These three values will.

it must ÊÎÂÒIÇ function only hand back the correct number of wins for each player. Figure . and the program looks like a more precise formulation of the rough algorithm.éP ”P£ã¨‚1wkiHé4‚Œ’nŠ 4 é {zˆ 6 1Š èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ% Ä ¢IǨĐÌÁ¬ñIú ̨Á£Ë Ú I õ ̨Á£Ë nõîǡߥ!¨Æ1ÄQ¢‡Ç©É¨ÄÎÜ@ñIú ÛÎÒIÇ@Ü Ú õ ÛÎÒIÇ@Ü Wß ÜP҇§ Ê Ð ü €ÊÎƈܓñùǙõ ÌÁÓË Ú õĮÁ£Ë Îú ̽ҀÇC Ä ÅÓÉ1ʐÊ4£̐ωñèÛÎÒIÇ@Ü Ú õ ÛÎÒIÇ@Ü 4ú rI¿€” %m m  Ê4ÂÒIÇ That wasn’t very hard. parameters. of when given the number of games to simulate and the two probabilities. For the purposes Ê4Â¨Ò€Ç ÜP҇§ Ê Ð ü €ÊÎÆˆÜ . In fact. Abstraction is the fundamental tool of design. Further. The only concern is that. and . illustrates this. the function alone won’t do very much. but that is far from true. The function should print . Each component in the design is a rectangle. Anything else can be ignored (for the moment). You might view the entire process of top-down design as a systematic method for discovering useful abstractions. Let’s take them in order. Ì3ÒIÇÄ%¢IÇÄPÌÁ . A line connecting two rectangles indicates that the one above uses the one below. and expected return values of the functions that perform these tasks. you may think that we have not yet accomplished anything at all. Our work so far can be represented as a structure chart (also called a module )  hierarchy chart). The cares what each (sub-)function does. The general process of determining the important characteristics of something and ignoring other details is called abstraction. We have broken the original problem into four independent tasks: !¨Æ1Q Ä ¢‡© Ç É¨ÄÎÜ ÜPÒvm Ê Ð ü €Ê3Æ½Ü Ì3ÒIÇC Ä ÅÓÉHÊPÊ4Â£ÌÏ . At each level of a design. The arrows and annotations show the interfaces between the components in terms of information flow. This information is called the interface or signature of a function. we have specified the name. Having signatures allows us to tackle pieces independently. The function is only five lines long. tȑÉÈ‘É Ø i%œ)vxw j›§·)¸ ‘œ %iCk§i%Ù i§slŒ•w Now all we need to do is repeat the design process for each of the remaining Ì3ÒIÇÄ%¢IÇP Ä ÌÁ components. we’ve put off all of the interesting details. we don’t care how does its job. the interface tells us which details of the lower level are important. tȑÉÈ‘Ç Ø iBÍ%–%“f–§tqlnvxwVv'9 ̪ vxwQœ©i•“8w%s ÊÎÂÒ€Ç Of course.

¨Ì3Ò€Ç¨Ä an introduction to the program. I wanted to put double quotes around “A” and “B” so that the entire string is enclosed in apostrophes. We need to prompt for and get three values. Since we didn’t introduce any new functions. Let’s compose a suitable sequence of statements. Now let’s tackle which are returned to the main program. variables inside of a function are local to that function. Again. èÆH£ Í ̽ҀÇ% Ä ¢IǨĐÌÁ¬ñIú­÷ ̽ҀÇ Ä XHÅÎÒ¨ Ü ¨ÌÁ)!ḦÂIÊ»ÜPÒvÊɽÀÂ1ĨƽÜÈÂE!¨Â€Ê3ÆWÁPÍ€ÌˆÂ¨Ñ í£É½ÆHÄ1Ë3ÂPÀÀ ˈÆHÄHۈƐÆÓÇÝÄPÛÁ' ̽ҀÇÄ p3ÀPÂ1ϨÆHÌÎÜUÑHÀPÀPÆH à  Ú  ÂÓLjA à  #4ï 1ŽÆÝÂÓËÎÒHÀ¨ÒÓÄ3Ò£Æ½Ü ÁPÍÝƨ¨рť½ÀÂ1ϨÆHÌ¡ÒÜ ̽ҀÇ Ä xҀÇýÒPÑHÂ1ĨÆPÃYËÏà`  ̨Á£Ë3ÂxË4Ò1ÀÒÓÄPÏòñz ǐÉHʨ˽Æ1ÌU˽Æ1ÄPۈÆPÆ£ÇàÕÝÂxLjà ÖHú ÄHÅ3£# Ä  ̽ҀÇ Ä ŒÄHň` Æ 3ÀPÂ1ÏÆ1ÌcÛÎÒIÇ@ÜYÄ1Ž` Æ ½ÁҀǨÄcÛPňƣǻܣÆ1© Ì W½Ò€§ Ç !nï ØÀÂ1ϨÆHÌ Ú ÂPÀ£Û½Â£ÏÎm Ü  ̽ҀÇ Ä zÅ3ÂÜYÄHňƀͽÒÓÌ3ÜxÄÿÜÓÆH) Ì WÆnu ï  —  © Notice the second line. Remember. This function comprises only primitive Python instructions. èÆH¥ Í !¨Æ1Q Ä ¢I) Ç É¨ÄÎܓñ‡ú¬÷ ó  ˆÆ1ÄHÉÌ1Ç@Ü Ä1ŽÆcÄ1ÅÌÆPÆàÜPÒvÊɽÀÂ1ĽÒ1ÁÓE E Ç 3£̈ÂIÊÎÆHĨÆHÌ3æ Ü ̨Á£Ë Ú 5 õ ̨Á£Ë ÐÂÓÇÃUÇ ÂcßÿҀ© Ç PÉĉñ 34HÅ3£ÄàÒ¨ÜYÄ1Ž` Æ ¨ÌÁ£Ëhï 3ÀPÂ1ϨÆHÌ Ú ÛÎÒIÇ@ÜÈ¡ÜÓÆH© Ì W¨§ Æ PaÓú ËàßÿҀ© Ç PÉĉñ 34HÅ3£ÄàÒ¨ÜYÄ1Ž` Æ ¨ÌÁ£Ëhï 3ÀPÂ1ϨÆHÌ WÛÎÒIÇ@ÜÈ¡ÜÓÆH© Ì W¨§ Æ PaÓú ÇàßÿҀ© Ç PÉĉñ 3¢Á1ÛYÊ4ÂÓǨ¥ Ï !ÂIÊÎƈÜYÄÁ¡ÜPÒvÊɽÀÂ1Ĩ§ Æ P@£ú ÌÆ1ÄHÉÌ1ǡ‰õ ˟õ Ç # % Notice that I have taken some shortcuts with the variable names. this is simple to code.rI¿ ¯ s4tvuxwzy|{I}3éHî˜ 6 ƒ„…± u†y 6 ‚1Š„uxŠv‹ 4 é {ôˆ 6 1Š main winsA winsB probA probB n probA probB n winsA winsB printIntro getInputs simNGames printSummary )  Figure . This function is so short. there is no change to our structure chart. The main concern here . !ÆHQ Ä ¢‡© Ç PÉÄÎÜ . : First-level structure chart for racquetball simulation. it’s very easy to see what the three values represent.

we already have the signature for our function. so as usual. In order to accurately simulate a game. Remember. . This one requires Ç a bit more thought. and tracking wins sounds like the job for a couple of accumulators. I’m not quite sure how to do that. ÜP҇ʧРü €ÊÎÆˆÜ we are ready to try our hand at the real problem. we can piece together an algorithm. but then so was our top-level algorithm. tȑÉÈ ™ œ !h i§slŒ•wQl™wm•£sl™— Ë ü –B—îims Now that we are getting some experience with the top-down design technique. Well. The basic idea is to simulate games and keep track of how Ç many wins there are for each player. Let’s just ÜHÒ‡Ê Ä Ç½Æ ü ÂIÊÎÆ assume there’s a function called to take care of this. The inputs for the function seem straightforward. ¢IÇÎÒÓĽÒHÀ¨Ò Æ ÛÎÒIÇ@Ü Ú ÂÓÇÃcÛÎҀÇ4Ü WĨÁWÕ ÀPÁPÁ WÇÐĽ҇ÊÎÆˆÜ ÜPÒvÊÉ3ÀPÂ1ĨƀT  !ÂIÊÎÆ Ò££ Í ½ÀÂ1ϨÆHÌ Ú ÛÎÒIÇ@Ü Ú ÃÃÝÁÓǽÆcĨÁUÛÎҀÇ4Ü Ú Æ¨ÀÜ£Æ Ú ÃÃÝÁÓǽÆcĨÁUÛÎҀÇ4Ü s s It’s a pretty rough design. We’ll fill in the details by turning it into Python code. I’ll put off the details. èÆHÍÿÜPÒvm Ê Ð ü €Ê3ƽܓñùǙõ ̨Á£Ë Ú õĮÁ£Ë 4ú¬÷ ó ÅÒvÊÉ3ÀPÂ1Ĩƽܪ@ S Ç !¨Â€ÊÎƈÜÈÂÓÇÀÌÆ1ÄHÉÌ1Ç@Ü Û3ҀÇ4Ü Ú ÂÓÇÃUÛÎÒIÇ@Ü ÛÎÒIÇ@Ü Ú ßàÕ ÛÎÒIÇ@Ü €ßàÕ Í¨Á1ÌÿÒWҀÇÐ̈Âx§ Ç !ÆæñðÇ@ú¬÷ s The next step in the algorithm calls for simulating a game of racquetball. .éP ”P£ã¨‚1wkiHé4‚Œ’nŠ 4 é {zˆ 6 1Š rI¿€´ is to make sure the values are returned in the correct order to match with the !ÆHÄ%¢IÇ©PÉÄ3Ü Ê4Â¨Ò€Ç interface we established between and . Using our familiar patterns. We need to figure out what the interface for this function will be. èÆHÍÿÜPÒvm Ê Ð ü €Ê3ƽܓñùǙõ ̨Á£Ë Ú I õ ̨Á£Ë 4ú¬÷ ó ÅÒvÊÉ3ÀPÂ1Ĩƽܪ@ S Ç !¨Â€ÊÎƈÜÈÂÓÇÀÌÆ1ÄHÉÌ1Ç@Ü Û3ҀÇ4Ü Ú ÂÓÇÃUÛÎÒIÇ@Ü % % m m We’ll add to this by initializing the two accumulator variables and adding the counted loop heading. “simulate games” sounds like a counted loop.

Translating this structure into code yields this nearly completed function: èÆHÍÿÜPÒvÊmÐ ü €Ê3ƽܓñùǙõ ̨Á£Ë Ú õĮÁ£Ë 4ú¬÷ ó ÅÒvÊÉ3ÀPÂ1Ĩƽܪ@ S Ç !¨Â€ÊÎƈÜÈÂÓÇÀÌÆ1ÄHÉÌ1Ç@Ü Û3ҀÇ4Ü Ú ÂÓÇÃUÛÎÒIÇ@Ü ÛÎÒIÇ@Ü Ú ßàÕ ÛÎÒIÇ@Ü €ßàÕ Í¨Á1ÌÿÒWҀÇÐ̈Âx§ Ç !ÆæñðÇ@ú¬÷ ÜPÑ1Á1ÌÆ Ú õ ÜHÑ1ÁHÌ¨Æ WßÿÜHÒ‡Ê Ä Ç½Æ ü ÂIÊÎÆæf ñ ̨Á£Ë Ú õ ÌÁÓË Îú % s m u  main winsA winsB probA probB n probA probB n winsA winsB printIntro getInputs simNGames printSummary probA probB scoreA scoreB simOneGame )  Figure . . Here is the result: èÆHÍÿÜPÒvÊmÐ ü €Ê3ƽܓñùǙõ ̨Á£Ë Ú õĮÁ£Ë 4ú¬÷ ÛÎÒIÇ@Ü Ú ßWÛ3ҀÇ4Ü WßÐÕ Í¨Á1ÌÿÒWҀÇÐ̈Âx§ Ç !ÆæñðÇ@ú¬÷ s % . you look at the final score. we need to check the scores to see who won and update the appropriate accumulator. How do you know who won? Generally. ÜPÒvÊ Ä ÇˆÆ ü €ÊÎÆ Let’s have return the final scores for the two players.rI¿€¹ s4tvuxwzy|{I}3éHî˜ 6 ƒ„…± u†y 6 ‚1Š„uxŠv‹ 4 é {ôˆ 6 1Š we need to know what the probabilities are for each player. Finally. We can update our structure chart to reflect these decisions. : Level 2 structure chart for racquetball simulation. But what should the output be? In the next step of the algorithm. The result is shown in )  Figure . we will need to know who won the game.

The loop just keeps going until the game is over. We can quickly fill in the first couple of steps of the algorithm to get the following. That’s enough analysis to put together a rough algorithm. The scores will probably just be a couple of intvalued accumulators.éP ”P£ã¨‚1wkiHé4‚Œ’nŠ 4 é {zˆ 6 1Š ÜPÑ1Á1ÌÆ Ú õ Ò£ÍÿÜPÑ£ÁHÌ¨Æ Û3ҀÇ4Ü Æ¨ÀˆÜÓÆn÷ Û3ҀÇ4Ü ÌÆ1ÄHÉÌ1ÇWÛÎÒIÇ@Ü Ú tȑÉÈ‘× rI¿€¿ ÿ   l›j·)¸ œ Ql™“ %iCk§i%Ù u u s m m Ú i§slŒ•w ÜHÑ1ÁHÌ¨Æ WßÿÜHÒ‡Ê Ä Ç½Æ ü ÂIÊÎÆæñf̨Á£Ë Ú õ   ÌÁÓË Îú P Ü £ Ñ H Á ¨ Ì Æ ™ ÷ ( Ú ß€ÛÎÒIÇ@Ü Ú á Ö Ö  W߀ÛÎÒIÇ@Ü Wá õ Û3ҀÇ@Ü Everything seems to be coming together nicely. we need to keep track of the score(s). we don’t know how many rallies it will take before one of the players gets to 15. èÆHÍÿÜPÒvÊ Ä ÇˆÆ ü €ÊÎƬñH¨ÌÁ£Ë Ú õ   ̨Á£Ë 4ú¬÷ ÜPÑ£ÁHÌÆ Ú ßÝÕ ÜPÑ£ÁHÌÆ WßÝÕ Ü£Æ1© Ì W3ÒI§ Ç !€A ß  Ú  ÛPÅÎÒHÀPÆ Ñ1ÁÓLjÈÒÓÄ3Ò£Á£Ç ( ÷ 3 % F . Along the way. It’s also an accumulator of sorts. but to update its value we just switch it from one value to the other. and we also need to know who is currently serving. Let’s try this: G ÆÐÜPÑ£ÁHÌ¨Æ½Ü Ä¨ÁWÕ Ü Æ1Ì©W3ÒIǧ!cĨÁ Ú  £ ¤ÁPÁ ÝÛHÅ4ÒHÀHÆE!ÂIÊÎÆàÒÜ Ç½ÁHÄÐÁWÆ1̙÷ ÅÒvÊÉ3ÀPÂ1ĨÆcÁ£ÇˆÆ¡Ü£Æ1Ì©WÆWÁHÍcÛPÅÎҐрňÆgW¨ÆHÌ`½ÀÂ£ÏÆHÌàÒ¨ÜWÜ£Æ1Ì©W½Ò€Ç§! É ÃÂ1ĨÆUÄHňơÜxÄÂ1ÄHÉ4Ü ÁP̀Ä1ŽT © Æ !¨Â€ÊÎÆ  ˆÆ1ÄHɨÌHÇ ÜHÑ1ÁHÌ¨Æ½Ü ÅPÆ1Ä ¢IÇÎÒÓĽÒHÀ¨Ò !h It’s a start. One approach is to use a string variable that stores either  Ú   6 or . Let’s keep working on the guts ÜHÒ‡Ê Ä Ç½Æ ü ÂIÊÎÆ of the simulation. Players keep doing rallies until the game is over. That suggests some kind of indefinite loop structure. The next obvious point of attack is . at least. Here’s where we actually have to code up the logic of the racquetball rules. but how do we keep track of who’s serving? It’s either player A or player B. Clearly there’s still some work to be done on this one.

: Level 3 structure chart for racquetball simulation. that looks at the scores and Ì1É½Æ DˆÂPÀˆÜ£Æ returns if the game is over. We should be able to tell if the game is over by looking at the scores. ) ! Figure . !€Ê3Æ Ä WÆHÌ Let’s hide the details in another function. some of which were fairly complex. . and if it is not. .rI¿€â s4tvuxwzy|{I}3éHî˜ 6 ƒ„…± u†y 6 ‚1Š„uxŠv‹ 4 é {ôˆ 6 1Š The question at this point is exactly what the condition will be. We discussed a number of possibilities for this condition in the previous chapter. That gets us on to the rest of the loop for now. shows the structure chart with our new function. We need to keep looping as long as the game is not over. The code for ÜPÒvÊ Ä Ç½Æ ü €Ê3Æ now looks like this: èÆHÍÿÜPÒvÊ Ä ÇˆÆ ü €ÊÎƬñH¨ÌÁ£Ë Ú õ ̨Á£Ë 4ú¬÷ ÜPÑ£ÁHÌÆ Ú ßÝÕ ÜPÑ£ÁHÌÆ WßÝÕ Ü£Æ1© Ì W3ÒI§ Ç !€A ß  Ú  ÛPÅÎÒHÀPÆYǽÁH  Ä !¨Â€Ê3Æ Ä W¨H Æ Ì‰ñ‡ÜPÑ£ÁHÌ¨Æ Ú õ ÜPÑ£ÁHÌ¨Æ 4ú­÷ 3 % u main winsA winsB probA probB n probA probB n winsA winsB printIntro getInputs simNGames printSummary probA probB scoreA scoreB simOneGame scoreA scoreB true|false gameOver ) ! Figure .

It got a bit complicated. We ƐÀˆÜÓÆ just need to attach a mirror image clause. We will need a decision based on this value. based on the result of the serve. here is the result: èÆHÍÿÜPÒvÊ Ä ÇˆÆ ü €ÊÎƬñH¨ÌÁ£Ë Ú õ ̨Á£Ë 4ú¬÷ ÜPÑ£ÁHÌÆ Ú ßÝÕ ÜPÑ£ÁHÌÆ WßÝÕ Ü£Æ1© Ì W3ÒI§ Ç !€A ß  Ú  ÛPÅÎÒHÀPÆYǽÁH  Ä !¨Â€Ê3Æ Ä W¨ÆH̉ñ‡ÜPÑ£ÁHÌ¨Æ Ú õ ÜPÑ£ÁHÌ¨Æ 4ú­÷ Ò£ÍÿÜ£Æ1© Ì W½Ò€§ Ç !cߐA ß  Ú @÷ ÒÓ̀̈ÂxLjèÁ€Ê™ñ‡ú ̨Á£Ë Ú ÷ F ÜHÑ1ÁHÌ¨Æ Ú ßÿÜHÑ1Á1ÌÆ Ú á Ö ÆÀˆÜÓÆn÷ 3 % u . The correct probability to use is determined wins the point ( ÜÓÆH© Ì W½Ò€C Ç ! by the value of . and. Remember.éP ”P£ã¨‚1wkiHé4‚Œ’nŠ 4 é {zˆ 6 1Š rI¿€é Inside the loop. we need to do a single serve. Putting the function together. Here is the code: Ò£ÍÿÜÓÆHÌ)W3ҀÇC!€ßßA Ú 4÷ ң̀ÌÂÓLjÐÁxʟñIú ¨ÌÁ£Ë Ú ÷ ó Ú F ÜPÑ1Á1ÌÆ Ú ßÿÜPÑ£ÁHÌÆ Ú á»Ö ƨÀÜ£Æn÷ ó Ú Ü£ÆH) Ì W3ÒI§ Ç !€ßA # ÛÎҀÇ4Ü ÄHňơܣÆ1Ì©WÆ ÀPÁ½ÜÓÆ½Ü Ä1ŽơÜÓÆHÌ©W¨Æ  Of course. we are going to compare a random number to a probability in order to determine if the server ̈ÂxLjÐÁxʙñ‡ú ̨Á£Ë F ). but seems to reflect the rules of the simulation as they were laid out. only for B. if A is not serving. If A is serving. Ò£ÍÿÜÓÆHÌ)W3ҀÇC!€ßßA Ú 4÷ ң̀ÌÂÓLjÐÁxʟñIú ¨ÌÁ£Ë F ÜPÑ1Á1ÌÆ Ú ßÿÜPÑ£ÁHÌÆ Æ¨ÀÜ£Æn÷ Ü£ÆH) Ì W3ÒI§ Ç !€ßA # ƨÀÜ£Æo÷ ң̀ÌÂÓLjÐÁxʟñIú ¨ÌÁ£Ë F ÜPÑ1Á1ÌÆ WßÿÜPÑ£ÁHÌÆ Æ¨ÀÜ£Æn÷ Ü£ÆH) Ì W3ÒI§ Ç !€A ß  Ú  Ú ÷ Ú ó ó Ú Ú ÛÎÒIÇ@ÜYÄ1ŽơܣÆ1Ì©W¨Æ ÀPÁˆÜ£ÆˆÜ€Ü£Æ1Ì©WÆ  á»Ö 3 %3 ™÷ Wá»Ö ó   ó €ÛÎÒIÇ@ÜYÄ1ŽơܣÆ1Ì©W¨Æ àÀPÁˆÜ£ÆˆÜ ÄHňơܣÆHÌ)WÆ That pretty much completes the function. then we need to use A’s probability. we need to do the same thing. update either A’s score or change the service to B.

Here is the complete program from start to finish: ó€ÌH˽ÀPÀoU ï ¨Ï ÍP̨ÁxÊ¡ÌÂÓLjÐÁxÊ»ÒvC Ê ˆÁH̐Äc̈ÂÓÇèÁ€Ê èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ% Ä ¢IǨĐÌÁ¬ñIú ̨Á£Ë Ú I õ ̨Á£Ë nõîǡߥ!¨Æ1ÄQ¢‡Ç©É¨ÄÎÜ@ñIú ÛÎÒIÇ@Ü Ú õ ÛÎÒIÇ@Ü Wß ÜP҇§ Ê Ð ü €ÊÎƈܓñùǙõ ÌÁÓË Ú õĮÁ£Ë Îú ̽ҀÇC Ä ÅÓÉ1ʐÊ4£̐ωñèÛÎÒIÇ@Ü Ú õ ÛÎÒIÇ@Ü 4ú %m m  èÆHÍ£̽ҀÇÄ%¢IǨĐÌÁ¬ñIú­÷ . Let’s fill in the missing details and call it a wrap. . We can check this with a simple Boolean condition. the program is complete.rIâ7 s4tvuxwzy|{I}3éHî˜ 6 ƒ„…± u†y 6 ‚1Š„uxŠv‹ 4 é {ôˆ 6 1Š ÜÓÆH© Ì W½Ò€C Ç !cß& 6 ƨÀˆÜÓÆn÷ ÒÓ̀̈ÂxLjèÁ€Ê™ñ‡ú ̨Á£Ë Ÿ÷ F ÜHÑ1ÁHÌ¨Æ WßÿÜHÑ1Á1ÌÆ €á ƐÀˆÜÓÆn÷ ÜÓÆH© Ì W½Ò€C Ç !c& ß  Ú  ÌÆ1ÄHÉÌ1Ç ÜPÑ£ÁHÌ¨Æ Ú õÜPÑ1Á1ÌÆ G u u Ö tȑÉÈ Sµ ¢ !  ¼ l™w•lns Ql™wm• 3 Í !ÂIÊÎÆ Ä WÆ1Ì Whew! We have just one more troublesome function left. èÆH¥ Í !ÂIÊÎÆ Ä WÆ1̄ñ†ÂæõpË@ú¬÷ óÐÂÝÂÓLjÃUËÐÌ¨Æ ¨ÌƽÜÓƣǨġÜPÑ£ÁHÌ¨Æ½Ü Í¨Á1ÌÐÂcÌˆÂ¨Ñ í1ɈÆHÄ1Ë3ÀPÀ`!¨Â€ÊÎÆ ó  ˆÆ1ÄHÉÌ1Ç@§ E Ü PÌHɈÆàң̀ÄHňT Æ !ÂIÊÎÆàÒ¨ÜÈ Á WÆ1Ìn° õ DÀˆÜÓƀÁHÄ1ŽÆ1ÌPÛÎҐܣÆoï ÌÆ1ÄHÉÌ1Ç¡ÂHßPß4 Ö 9cÁH̀ˈßPß4 Ö 9 Notice how this function directly computes and returns the Boolean result all in one step. Here is what we know about it so far: èÆH¥ Í !ÂIÊÎÆ Ä WÆ1̄ñ†ÂæõpË@ú¬÷ óÐÂÝÂÓLjÃUËÐÌ¨Æ ¨ÌƽÜÓƣǨġÜPÑ£ÁHÌ¨Æ½Ü Í¨Á1ÌÐÂcÌˆÂ¨Ñ í1ɈÆHÄ1Ë3ÀPÀ`!¨Â€ÊÎÆ ó  ˆÆ1ÄHÉÌ1Ç@§ E Ü PÌHɈÆàң̀ÄHňT Æ !ÂIÊÎÆàÒ¨ÜÈ Á WÆ1Ìn° õ DÀˆÜÓƀÁHÄ1ŽÆ1ÌPÛÎҐܣÆoï According to the rules for our simulation. a game is over when either player reaches a total of 15. ¨Ì3ҀǨħÅxÉHʐÊÎÂ1ÌPÏ We’ve done it! Except for .


I had to use a double percent ( ). We started at the highest level of our structure chart and worked our way down. tȑÉÈ m  "" QQ"" gg"€€" "" ± ±"" | f ëÌ)̀Ê4¨ҀÇmÌ©Ì m m s ¨÷ŽÊÎÂҀÇoñIú Sû Ø r6—æ—î–%“ üv'9 t %i l¤ )  žœ "g" i§slŒ•w¥’”“Hvxœ©i§ss You have just seen an example of top-down design in action. This approach is sometimes called step-wise refinement. to get a normal percent sign at the end of the output. Now you can really see why it’s called top-down design. Since a percent sign normally marks the beginning of a slot specifier. 3. we began with a general algorithm and then gradually refined it into precise code. Detail the algorithm by expressing it in terms of its interfaces with the smaller problems. Develop an interface for each of the small problems. .rIâ€r s4tvuxwzy|{I}3éHî˜ 6 ƒ„…± u†y 6 ‚1Š„uxŠv‹ 4 é {ôˆ 6 1Š ÜÓÆH© Ì W½Ò€C Ç !cß& 6 ƨÀˆÜÓÆn÷ ÒÓ̀̈ÂxLjèÁ€Ê™ñ‡ú ̨Á£Ë Ÿ÷ F ÜHÑ1ÁHÌ¨Æ WßÿÜHÑ1Á1ÌÆ €á ƐÀˆÜÓÆn÷ ÜÓÆH© Ì W½Ò€C Ç !c& ß  Ú  ÌÆ1ÄHÉÌ1Ç ÜPÑ£ÁHÌ¨Æ Ú õÜPÑ1Á1ÌÆ G u u Ö 3 èÆHÍ¥!ÂIÊÎÆ Ä WÆ1̄ñ†Âæõ Ë@ú¬÷ óÐÂÝÂÓLjÃUËÐÌ¨Æ ¨ÌƽÜÓƣǨġÜPÑ£ÁHÌ¨Æ½Ü Í¨Á1ÌÐÂcÌˆÂ¨Ñ í1ɈÆHÄ1Ë3ÀPÀ`!¨Â€ÊÎÆ ó  ˆÆ1ÄHÉÌ1Ç@§ E Ü PÌHɈÆàң̀ÄHňÆT!ÂIÊÎÆàÒ¨ÜÈÁWÆ1Ìnõ°DÀˆÜÓƀÁHÄ1ŽÆ1ÌPÛÎҐܣÆoï ÌÆ1ÄHÉÌ1Ç¡ÂHßPß4 Ö 9cÁH̀ˈßPß4 Ö 9 èÆHÍ£̽ҀÇÄCÅÓÉ1ʐÊ4£̐ωñèÛÎÒIÇ@Ü Ú õ ÛÎÒIÇ@Ü 4ú¬÷ ó€ØÌ½Ò€ÇÄ3ÜÈ¡ÜIÉ1ʐÊ4£̐ÏÝÁHÍcÛÎÒIÇ@Ü Í¨Á1ÌÝƨ¨рť½ÀÂ1ϨÆH̟ï Çà߀ÛÎҀÇ4Ü Ú á€Û3ҀÇ@Ü ̽ҀÇ Ä  ÓÇ ü ÂIÊÎƽÜcÜP҇ʨÉ3ÀPÂ1ÄÆHßu ÷ Îõ Ç ̽ҀÇ Ä 34ÎÒIÇ@Ü ÍÁHÌ Ú ÷ Pà ñ ÕnïŒÖIÍ Îúm ñèÛ3ҀÇ@Ü Ú õ¢Í¨ÀPÁÂ1ĄñðÛÎÒIÇ@Ü Ú ú ŸxǕYˆÖ€ÕÕ½ú ̽ҀÇ Ä 34ÎÒIÇ@Ü ÍÁHÌ ™÷ Pà ñ ÕnïŒÖIÍ Îm ú  ñèÛ3ҀÇ@Ü nõ¢Í¨ÀPÁÂ1ĄñðÛÎÒIÇ@Ü Îú Ÿx• Ç YˆÖ€ÕÕ½ú í´ Ò£ÍSÌ)ÌÓǽ€ÊÎÆ©Ì©ÌUßPß ¨Ì3ÒIǧ Ä ÅxÉHÊPÊ4Â1ÌPÏ You might take notice of the string formatting in . Express the algorithm as a series of smaller problems. The whole process can be summarized in four steps: 1. At each level. 2.

type the whole thing in. Even if the code is flawless.éH ¯ ±‚‡y y|‚Hƒ‚i †w1u ƒ•w± {Iƒo{‡Š†y–u†y 6 ‚1Š q$ rI— 4. Stay with it—the more you do it. the result will probably be disappointment and frustration. Repeat the process for each smaller problem. tÈ ™ ÈƒÊ ¼ ƒÿ w•lŒt i§sqtql™wm• A good way to approach the implementation of a modest size program is to start at the lowest levels of the structure chart and work your way up. Even though we have been very careful in our design. When you first try it out for yourself. and soon expressing your own programs in terms of cooperating functions will become second nature. you’ll probably make some mistakes when you enter it. you may think writing all of those functions is a lot of trouble. Keep at it. the easier it will get. and give it a try. The truth is. we could start with the function. implementation is best approached in small doses. developing any sophisticated system is virtually impossible without a modular approach. testing each component as you complete it. Once this function is typed into a module file. Just as designing a program one piece at a time is easier than trying to tackle the whole problem at once. things probably won’t go quite so smoothly. though. Initially. —«”|µ ¸l™h…P…™£›vg4d¤qt–›¥¤•j ‚™› ‚™en…¨io…ˆ‡™£e Now that we’ve got a program in hand. Looking back at the structure chart for our !€Ê3Æ Ä WÆHÌ simulation. Here is a sample session testing out just this function: Ê ½ÁHÌPĀÌH˽ÀPÀ (©()( ҇c ï !€Ê3Æ Ä WÆH̉ñzՉõ–Õ3ú (©()( ÌH˽ÀÀ½Ö­p DˆÂPÀˆÜÓÆ ï !€Ê3Æ Ä WÆH̉3 ñ 9æõ‡ÖxÕ½ú (©()( ÌH˽ÀÀ½Ö­p DˆÂPÀˆÜÓÆ ï !€Ê3Æ Ä WÆH̉ñ€ Ö 9‰õ–Þ½ú (©()( ÌH˽ÀÀ½Ö­p Ì1É½Æ ï !€Ê3Æ Ä WÆH̉ñzމõ‡" Ö 9ˆú (©()( ÌH˽ÀÀ½Ö­p Ì1É½Æ . there is no guarantee that we haven’t introduced some silly errors. Top-down design is an invaluable tool for developing complex algorithms. The process may seem easy. since I’ve walked you through it step by step. your inclination might be to run off. we can immediately import the file and test it. If you do that.

The first time it is called. That squares with how we think this function should behave. the game is not over. Here is a sample session: Ò Êc½ÁHÌPĀÌH˽ÀPÀ ‡ (©()( ÌH˽ÀÀ½Ö­ïôÜPÒ‡Ê Ä ÇˆÆ ñ€Ö€Þ„õª Ö 9½ú H Ì ½ Ë ÂÀÀ½Ö­ïôÜPÒ‡Ê Ä ÇˆÆ (©()( ñ€ Ö 9‰õªÖPÖPú (©()( ÌH˽ÀÀ½Ö­ïôÜPÒ‡Ê Ä ÇˆÆ ñ€ Ö 9‰õªÖPÖPú (©()( ÌH˽ÀÀ½Ö­ïôÜPÒ‡Ê Ä ÇˆÆ ñ€ÖP֓õª Ö 9½ú (©()( ÌH˽ÀÀ½Ö­ïôÜPÒ‡Ê Ä ÇˆÆ ñ d„õª" ë Ö 9ˆú (©()( ÌH˽ÀÀ½Ö­ïôÜPÒ‡Ê Ä ÇˆÆ ñ€Ö@õª" Ö 9ˆú (©()( ÌH˽ÀÀ½Ö­ïôÜPÒ‡Ê Ä ÇˆÆ ñ€ Ö 9‰õ Þ½ú (©()( ÌH˽ÀÀ½Ö­ïôÜPÒ‡Ê Ä ÇˆÆ ñ€ Ö 9‰õ Õ½ú (©()( ÌH˽ÀÀ½Ö­ïôÜPÒ‡Ê Ä ÇˆÆ ñzý‰õª" Ö 9ˆú (©()( ÌH˽ÀÀ½Ö­ïôÜPÒ‡Ê Ä ÇˆÆ ñzø‰õª" Ö 9ˆú (©()( ü ÂIÊÎƬñ½ï¡9æõïH9½ú ü ÂIÊÎƬñ½ï¡9æõïH9½ú ü ÂIÊÎƬñ½ïðމõïùÞ3ú ü ÂIÊÎƬñ½ïðމõïùÞ3ú ü ÂIÊÎƬñ½ïfd„õïùý3ú ü ÂIÊÎƬñ½ïfd„õïùý3ú ü ÂIÊÎƬñ½ïðý‰õïpdÎú ü ÂIÊÎƬñ½ïðý‰õïpdÎú ü ÂIÊÎƬñ½ïfd„õïùø3ú ü ÂIÊÎƬñ½ïfd„õïùø3ú Notice that when the probabilities are equal. As the game progresses. The last two examples show that the function correctly identifies that the game is over when either player reaches 15. Software engineers call this process unit testing. The function correctly responds DÀˆÜÓÆ . the function will be with called with intermediate scores. The best we can do in testing it is to see that it behaves reasonably. the game is a rout. . When the probabilities are farther apart. The second example shows that the function again responded that the game is still in progress. !€Ê3Æ Ä WÆHÌ Having confidence that is functioning correctly. the scores are close. now we can go ÜPÒ‡Ê Ä ÇˆÆ ü ÂIÊÎÆ back and implement the function. We can continue this piecewise implementation. so I’m not sure exactly what the output will be.rIâ ¯ s4tvuxwzy|{I}3éHî˜ 6 ƒ„…± u†y 6 ‚1Š„uxŠv‹ 4 é {ôˆ 6 1Š I have selected test data that tries all the important cases for the function. the score will be 0 to 0. This function has some probabilistic behavior. testing out each component as we add it into the code.

By the time you get around to testing the entire program. How often should Denny win the game? Here’s an example run where Denny’s opponent always serves first. He should skip the shrink and work harder on his game. we can take a look at Denny Dibblebit’s question.éH ¯ ±‚‡y y|‚Hƒ‚i †w1u ƒ•w± {Iƒo{‡Š†y–u†y 6 ‚1Š q$ rI‴ Testing each function independently makes it easier to spot errors. tÈ ™ È‘Ç Ø l™—$r•ÙŒ–§tqlnvxwShji§sr•Ùˆtus Finally. Apparently. Separating concerns through unit testing makes it possible to implement and debug sophisticated programs. ˈÆHÄHۈƐÆÓÇÝÄPÛÁ Ú  ÂÓLjÃA #4ï 1ŽÆÝÂÓËÎÒHÀ¨ÒÓÄ3Ò£Æ½Ü ÁPÍÝƨ¨рť½ÀÂ1ϨÆHÌ¡ÒÜ Ò€ÇýÒPÑHÂ1ĨÆPÃYËÏàÂ`̨Á£Ë3ÂxË4Ò1ÀÒÓÄPÏòñz ǐÉHʨ˽Æ1ÌU˽Æ1ÄPۈÆPÆ£ÇàÕÝÂxLjà ÖHú ÄHÅ3壀 ÄHňÆ`3ÀPÂ1ÏÆ1ÌcÛÎÒIÇ@ÜYÄ1Ž` Æ ½ÁҀǨÄcÛPňƣǻܣÆ1Ì©W½Ò€Ç§!nï ØÀÂ1ϨÆHÌ Ú ÂPÀ£Û½Â£ÏÎÜ Å3ÂÜYÄHňƀͽÒÓÌ3ÜxÄÿÜÓÆH) Ì WÆnï 3ÀPÂ1ϨÆHÌÎÜUÑHÀPÀPÆHà HÅÎҨܨÌÁ)!ḦÂIÊ»ÜPÒvÊɽÀÂ1ĨƽÜÈÂE!¨Â€Ê3ÆWÁPÍ€ÌˆÂ¨Ñ í£É½ÆHÄ1Ë3ÂPÀÀ  Ú Û3ҀÇ@Ü ÿ  ÜÓÆHÌ)WƧP 4PŽÂ1ÄÿҐÜYÄHŽÆ`¨ÌÁÓ˄ï ½ÀÂ1ϨÆHÌ WÛ3ҀÇ@Ü ÿ  ÜÓÆHÌ)WƧP ¢ˆÁ£ÛUÊ4ÂxÇÏ !ÂIÊÎÆˆÜ ÄÁ¡ÜH҇ÊɽÀÂ£Ä§ Æ PV9PÕPÕÕ 4PŽÂ1ÄÿҐÜYÄHŽÆ`¨ÌÁÓ˄ï ½ÀÂ1ϨÆHÌ # ïðøc9 ïðø ü ÂIÊÎƈ܀ÜPÒvÊÉ3ÀPÂ1ĨÆPß÷59PÕPÕÕ ÍÁHÌ Ú ÷¢ÞPސøPÕ ñzøPþnïèÔ Îú 4ÎÒIÇ@Ü ÍÁHÌ ™÷ր) ø dÕ ñzސÔoH ï e Îú 4ÎÒIÇ@Ü  u3"" Even though there is only a small difference in ability. expanding this program to compute the probability of winning multi-game matches would be a great exercise. and you’ll see that you are getting your programs working with less overall effort and far less frustration. Is it the nature of racquetball that small differences in ability lead to large differences in the outcome? Suppose Denny wins about 60% of his serves and his opponent is 5% better. Why don’t you give it a try? . His chances of winning a three.or five-game match are pretty slim. Try these techniques for yourself. Denny should win only about one in three games. Speaking of matches. chances are that everything will work smoothly. Separating concerns through a modular design makes it possible to design sophisticated programs. Denny is winning his share.

Or the original specification might be so complicated that refining it level-by-level is just too daunting.rI‹ —«”|º s4tvuxwzy|{I}3éHî˜ 6 ƒ„…± u†y 6 ‚1Š„uxŠv‹ 4 é {ôˆ 6 1Š xY…3˜™‚™gE«ª‚„‘ˆ‡šqem— ‚„ƒo˜•eh‡ q¦Ÿ‚o‘ •˜ Top-down design is a very powerful technique for program design. Then new features are designed. Prototyping often leads to a sort of spiral development process. and testing. implemented. That leaves the crux of the problem. consider how we might have approached the racquetball simulation. and tested. we first design. implementation. The initial stripped-down version is called a prototype. Sometimes you may get stuck at a step and not know how to go about refining it. design. As an example. tȑ×ÈƒÊ ’”“Hv•tuv•t QÍQl™wm•E–Bw r¤ §› Ø ÍQl™“H–QÙ ãi§k§i%ٌvxÍ'—îiBwmt ͜ Another approach to design is to start with a simple version of a program or program component and then try to gradually add features until it meets the full specification. ÜPÒvÊ Ä Ç½Æ ü €Ê3Æ function. our prototype could assume that each player has a 50-50 chance of winning any given point and just play a series of 30 rallies. which is handling the awarding of points and change of service. Simplifying even We might have started with just the further. Here is an example prototype: ÍP̨ÁxÊ¡ÌÂÓLjÐÁxÊ»ÒvC Ê ˆÁH̐Äc̈ÂÓÇèÁ€Ê èÆHÍÿÜPÒvÊ Ä ÇˆÆ ü €ÊÎƬñIú­÷ ÜPÑ£ÁHÌÆ Ú ßÝÕ ÜPÑ£ÁHÌÆ WßÝÕ Ü£Æ1© Ì W3ÒI§ Ç !€A ß  Ú  ͨÁ1ÌÿÒWҀÇÐ̈Âx§ Ç !ÆæñzÞPÕ3ú­÷ Ò£ÍÿÜ£Æ1© Ì W½Ò€§ Ç !cߐA ß  Ú @÷ ÒÓ̀̈ÂxLjèÁ€Ê™ñ‡ú ï¡9„÷ F ÜHÑ1ÁHÌ¨Æ Ú ßÿÜHÑ1Á1ÌÆ Ú ÆÀˆÜÓÆn÷ ÜÓÆH© Ì W½Ò€C Ç !cß& 6 ƨÀˆÜÓÆn÷ 3 G á Ö . but it is not the only way to go about creating a program. We make many mini-cycles through the development process as the prototype is incrementally expanded into the final program. implement. The very essence of the problem is simulating a game of racquetball. Rather than taking the entire problem and proceeding through specification. and test a prototype.

Here’s a project plan: Phase 1 Initial prototype. Phase 3 Play the game until one of the players reaches 15 points. so prototyping might prove useful. Phase 4 Expand to play multiple games. Phase 5 Build the complete program. Add interactive inputs and a nicely formatted report of the results. try some spiral development. It’s helpful to “get your hands dirty” with a quick prototype just to see what you can do. . The output is the count of games won by each player. Play 30 rallies where the server always has a 50% chance of winning. Print out the scores after each serve. At this point. we have a working simulation of a single game. We could then work on augmenting the program in phases. If full-blown top-down design does not seem to be working for you. Spiral development is particularly useful when dealing with new or unfamiliar features or technologies. Printing out the scores as we go along allows us to see that the prototype is playing a game.éP ´PgÑ­yèt†{I}#é4{ôˆ 6 1Š„ã¨{ ³ t€Š 6 H…†{zˆ ÒÓ̀̈ÂxLjèÁ€Ê™ñ‡ú ï¡9„÷ F ÜHÑ1ÁHÌ¨Æ WßÿÜHÑ1Á1ÌÆ €á ƐÀˆÜÓÆn÷ ÜÓÆH© Ì W½Ò€C Ç !c& ß  Ú  Ì3ÒIÇÄÿÜHÑ1Á1ÌÆ Ú õ ÜPÑ£ÁHÌ¨Æ Ö Ò£ÍSÌ)ÌÓǽ€ÊÎÆ©Ì©ÌUßPß • rI‿ u u | ëÌ)̀Ê4¨ҀÇmÌ©Ì f u ¨÷ ÜHÒ‡Ê Ä Ç½Æ ü €Ê3Ææñ‡ú You can see that I have added a print statement at the bottom of the loop. As a novice programmer. everything may seem new to you. Phase 2 Add two parameters to represent different probabilities for the two players. Here is some example output: ÖYÕ ÖYÕ Ô€Õ ïïPï þWþ þ¥e It’s not pretty. but it shows that we have gotten the scoring and change of service working.

’ Top-down design is a technique for designing complex programs.rIâ€â tȑ×È‘Ç ÿ  s4tvuxwzy|{I}3éHî˜ 6 ƒ„…± u†y 6 ‚1Š„uxŠv‹ 4 é {ôˆ 6 1Š %i§Ú “ft v'9 œ i§slŒ•w It is important to note that spiral development is not an alternative to top-down design. Computers use pseudorandom numbers to perform Monte Carlo simulations. Express an algorithm in terms of smaller problems. Repeat the process for each of the smaller problems. Unit-testing and bottom-up implementation are useful in coding complex programs. —«”–ê  ˜Ÿi„¤n…‚™g © ¦§›¥› ingIí ’ Computer simulation is a powerful technique for answering questions about real-world processes. In Chapter 12. Rather. ’ Top-down design was illustrated by the development of a program to simulate the game of racquetball. 2. 4. as in almost anything. you will see yet another approach called object-oriented design. The basic steps are: 1. Prototyp- . 3. Express the algorithm in terms of its interfaces with the smaller problems. ’ Spiral development is the process of first creating a simple version (prototype) of a complex program and gradually adding more features. The best software designers seem to employ a variety of techniques. That you have to learn for yourself through experience. There is no “one true way” of design. you will still use top-down techniques. Simulation techniques that rely on probabilistic or chance events are known as Monte Carlo simulations. ’ Unit-testing is the process of trying out each component of a larger program independently. Develop an interface for each of the smaller problems. they are complementary approaches. When designing the prototype. the key to success is practice. but books can’t teach how and when to apply them. You can learn about techniques by reading books like this one. In design. The truth is that good design is as much a creative process as a science. but there are no hard and fast rules for producing a design. Designs can be meticulously analyzed after the fact.

8. but not both. Unit-testing is the process of trying out a component of a larger program in isolation. 9. 6. A developer should use either top-down or spiral design. 7. The best way to learn about design is to read design books. Which expression is true approximately 66% of the time? ̈ÂxLjèÁ€Ê™ñ‡ú ( ßÝøPø ̈ÂÓÇèÁ€Ê™ñIú øø F a) c) ÌÂÓÇèÁxʟñIú ÕoïðøPø ÌÂÓÇèÁxʟñIú ( ßÝÕnïùøø b) d) F . A simplified version of a program is called a simulation. The Python ̈ÂxLjÐÁxÊ function returns a pseudorandom int. Practice is the best way to become a better designer. 2.éP ¿PCŽŒ{I} ³Œ6 ˆ–{ôˆ rIâ€é ing and spiral development are often useful in conjunction with top-down design. ’ Design is a combination of art and science. A top-down design is best implemented from the top down. Computers can generate truly random numbers. 4. In top-down design. ƒ |§„3…‡†§ˆ}Iˆj‰cŠ§…Œ‹"} 1. the main algorithm is written in terms of functions that don’t yet exist. —«”sr egf„‚™gIƒæ‡‘‚„‘ hjiCkmlniCoqpIrQi§sutqlnvxw%s y{zH|c})~Q©€cˆ‚3} 1. 5. The Ê4Â¨Ò€Ç function is at the top of a functional structure chart. Top-down design is also called stepwise refinement. 10. 3.

A graphical view of the dependencies among components of a design is called a(n) a) flowchart b) prototype c) interface d) structure chart 4. In top-down design.rIé7 s4tvuxwzy|{I}3éHî˜ 6 ƒ„…± u†y 6 ‚1Š„uxŠv‹ 4 é {ôˆ 6 1Š 2. How is a percent sign indicated in a string formatting template? a) b) c) d) 10. In the racquetball simulation. Which of the following is not a step in pure top-down design? a) repeat the process on smaller problems b) detail the algorithm in terms of its interfaces with smaller problems c) construct a simplified prototype of the system d) express the algorithm in terms of smaller problems 3. A simulation that uses probabilistic events is called a) Monte-Carlo b) pseudorandom c) Monty-Python d) chaotic 7. The easiest place in a system structure to start unit-testing is Ê4Â¨Ò€Ç a) the top b) the bottom c) the middle d) the function  …Œ‚3‹|c‚8‚X…ŒŠm " ¹s" "g" ¹s"g" 1. Draw the top levels of a structure chart for a program having the following Ê4ÂÒIÇ function: èÆPÍ ÊÎÂÒIÇnñIú­÷ ¨Ì3ÒIÇQ Ä ¢‡ÇÄPÌÁæñ‡ú ÀHÆ£C Ç !PÄHşõ ÛÎÒÓÃPÄ1ÅÐß !¨ÆHÄ ÎÒvÊÎÆ£Ç4ÜPÒ£Á£Ç@Ü@ñIú ÂIʽ) Ä ÐƐÆHèÆHÃcßÿÑ1Á€C Ê É¨ÄÆ Ú ÊÎÓ Á ɐǨĄñ†ÀHÆ£ÇC!PÄHşõùÛ3Ò£Ã1ÄHœú u . The arrows in a module hierarchy chart depict a) information flow b) control flow c) sticky-note attachment d) one-way streets 5. The initial version of a system used in spiral development is called a a) starter kit b) prototype c) mock-up d) beta-version !€Ê3Æ Ä WÆHÌ 8. the subcomponents of the design are a) objects b) loops c) functions d) programs 6. what data type is returned by the function? a) bool b) int c) string d) float 9.

College volleyball is now played using rally scoring. Write an expression using either following: or ÌÂÓLjÃḦÂxǧ!¨Æ to calculate the ’ A random int in the range 0–10 ’ A random float in the range -0. and percentage of wins that are shutouts. Games are played to 15.éP ¿PCŽŒ{I} ³Œ6 ˆ–{ôˆ ¨Ì3ÒIÇÄ) Æ ˆÁH̐ĉñ†ÀHƣǧ!HÄHşõ rIéH~ Û3Ò£ÃHÄHřõ˜Â€Ê½Ä)ÐÆPÆPèÆHÃÎú ̈ÂÓÇèÁ€Ê 2. or has no effect on the relative advantage enjoyed by the better team. .5–0. Your updated version should report for both players the number of wins.0 3. but must be won by at least two points. Design and implement a simulation of volleyball using rally scoring. the team that wins a rally is awarded a point. ’”“fv••“H–B—$—˜l™wm•Sš#›§i•“¡œ©lnsi§s 1. 3. Revise the racquetball simulation to take shutouts into account. Design and implement a simulation of some other racquet sport (e. In this system. In your own words.. 5. reduces. describe what factors might lead a designer to choose spiral development over a top-down approach. 4. Games are played to a score of 30. even if they were not the serving team. 2. Revise the racquetball simulation so that it keeps track of results for best of ø game matches. Your program should be able to investigate whether rally scoring magnifies. Normal volleyball is played like racquetball. in that a team can only score points when it is serving.g. number of shutouts. 6.0–10. tennis or table tennis). percentage of wins.5 ’ A random number representing the roll of a six-sided die ’ A random number representing the sum resulting from rolling two six-sided dice ’ A random float in the range -10. Design and implement a simulation of the game of volleyball. Design and implement a system that compares regular volleyball games to those using rally scoring.

the player loses. 3. just the total so far (treating an ace as Å3ÂˆÜ Ú Ñ£Æ that tells whether or not the hand contains 1) and a bool variable an ace. Monte Carlo techniques can be used to estimate the value of pi. it will be counted as 11 when that results in a total between 17 and 21 inclusive. aces count as 1 or 11. the ace is counted as 1.” That is. the player wins. If the player re-rolls the initial value before rolling a 7. If the dealer busts (goes over 21). and all other cards count their numeric value. 9. Write a program to simulate multiple games of craps and estimate the probability that the player wins. or 12. Rolling a 7 first is a loss. Suppose you have a round dart board that just fits inside of a square cabinet. It would be useful for a player to know the dealer’s bust probability (see previous problem) for each possible starting value. For example. A hand containing an ace should have 10 points added to the total exactly when doing so would produce a stopping total (something between 17 and 21 inclusive). If the roll is 7 or 11. A blackjack dealer always starts with one card showing. All face cards count as 10 points. The dealer must always take cards according to a fixed set of rules. Craps is a dice game played at many casinos. Hints: treat the deck of cards as infinite (casinos use a “shoe” containing many decks). If the initial roll is 2. otherwise. Blackjack (twenty-one) is a casino game played with cards. The goal of the game is to draw cards that total as close to 21 points as possible without going over. The player tries to get closer to 21 (without going over) than the dealer. then the estimated probability of winning is ¡g€ý"x"w w wch g€ º !& 8. You do not need to keep track of the cards in the hand. The game is played against a dealer. If the dealer’s hand contains an ace. the player automatically wins (provided the player had not already busted). If . A player rolls a pair of normal six-sided dice. The dealer takes cards until he or she achieves a total of at least 17. if the player wins 249 out of 500 games. the player keeps rolling the dice until either rolling a 7 or re-rolling the value of the initial roll. Write a simulation program that runs multiple hands of blackjack for each possible starting value (ace–10) and estimates the probability that the dealer busts for each starting value. Any other initial roll causes the player to “roll for point. Write a program that simulates multiple games of blackjack and estimates the probability that the dealer will bust. it’s a win. 10.rIé€r s4tvuxwzy|{I}3éHî˜ 6 ƒ„…± u†y 6 ‚1Š„uxŠv‹ 4 é {ôˆ 6 1Š 7.

éP ¿PCŽŒ{I} ³Œ6 ˆ–{ôˆ rI途 you throw darts randomly. it is easy to show that k 8 xw m‚ k Write a program that accepts the “number of darts” as an input and then ÔcYÓÌÂÓLjÐÁxʟñIúè¨ÿÖ performs a simulation to estimate . If ø is the total number of darts randomly thrown (that land within the confines of the cabinet). A random walk is a particular kind of probabilistic simulation that models certain statistical systems such as the Brownian motion of molecules. Suppose you are standing on a very long straight sidewalk that extends both in front of and behind you. you take a step forward. tails means to take a step backward. You can generate a random direction as an angle off of the “ axis. ÂÓÇC!ÀHÆcßẄÂÓÇèÁ€Ê™ñIúVY€ÔSY ÊÎÂ1Ä1ńïUÎÒ – The new “ and – positions are then given by these formulas: . how far do you expect to be from your starting point? Write a program to help answer this question. In this simulation you should allow the step to be taken in any direction. those that hit the cabinet (in the corners not covered by the board) will be determined by the relative area of the dart board and the cabinet. Suppose you are doing a random walk (see previous problem) on the blocks of a city street. Write a graphical program to trace a random walk (see previous two problems) in two dimensions. left or right. %q – 8 ø „  11. how many steps away from the starting point will you end up? Write a program to help you investigate this question. You can think of a one-dimensional random walk in terms of coin flipping. 12. 14. You flip a coin. In ø steps. Hint: you can use to generate the “ and coordinates of a random point inside a 2x2 square centered at ‚ƒw Òwg„ . and is the number that hit the board. On average. backward. Suppose you take a random walk of ø steps. The point lies inside the inscribed circle if “ µ µzy … . Write a program that performs a simulation to estimate the probability of rolling five-of-a-kind in a single roll of five six-sided dice. 13. At each “step” you choose to walk one block (at random) either forward. the proportion that hit the dart board vs. If it comes up heads.

each wall of the cube would occupy ¶ of l your field of vision. Start your walker at the center of a 100x100 grid and draw a line that traces the walk as it progresses.rIé ¯ s4tvuxwzy|{I}3éHî˜ 6 ƒ„…± u†y 6 ‚1Š„uxŠv‹ 4 é {ôˆ 6 1Š ¦Ð¥ ß ¦Ýá¡Ñ£Á½Ü“ñzÂÓC Ç !ÀPƽú Ïà߀ÏÐáÿÜHҀÇnñzÂÓÇC!ÀPƽú The program should take the number of steps as an input. . Suppose you are located at the exact center of a cube. If you could look all around you in every direction. (Advanced) Here is a puzzle problem that can be solved with either some fancy analytic geometry (calculus) or a (relatively) simple simulation. Suppose you move toward one of the walls so that you are now half-way between it and the center of the cube. What fraction of your field of vision is now taken up by the closest wall? Hint: use a Monte Carlo simulation that repeatedly “looks” in a random direction and counts how many times it sees the wall. 15.

A collection of related information. “d™«”–“ € W¦™‡ƒ| c ‚„‰o‡‚‰œ ™hìfx€y΁1‚„ƒ“…‘ In the last three chapters. we have developed techniques for structuring the computations of a program.QSRUTWVYXa`cb d8{ 1 32 ¦ ¥4¦ v ¤ ©Hr©ªfò x€y31‚„ƒ†…ˆ‡‰„‚„‘ ’ To appreciate how defining new classes can provide structure for a complex program. ’ To be able to write interactive graphics programs involving novel (programmer designed) widgets. ’ To be able to read and write Python class definitions. Remember back in Chapter 5 I defined an object as an active data type that knows stuff and can do stuff. ’ To understand the concept of encapsulation and how it contributes to building modular and maintainable programs. you will learn how to write your own classes so that you can create novel objects. ­ ® D . In the next few chapters. More precisely. ’ To be able to write programs involving simple class definitions. So far. an object consists of 1. we will take a look at techniques for structuring the data that our programs use. our programs have made use of objects created from pre-defined classes such as ׈ÒxÌ3Ñ1ÀPÆ . In this chapter. You already know that objects are one important tool for managing complex data.

Collectively. baseball. The parameters to the constructor are used to initialize some of the ѣƣÇĨÆHÌ ÌˆÂ1ýÒIÉ@Ü Ê½Ï×ÒÓ̽ÑHÀPÆ instance variables (namely and ) inside of . which remembers the center point of the circle. and . a object will have instance variables ѣƣǨÄÆHÌ ÌˆÂ1ýҀÉ4Ü such as . A set of operations to manipulate that information. are functions that “live” inside the object. it is manipulated by calling on its methods: ʽϨ׈ÒxÌ3ÑHÀHÆnïpÃP̈ÂÓÛoñðÛÎҀÇ@ú ʽϨ׈ÒxÌ3ÑHÀHÆnïÊÎg Á W¨Ææñ–© à ¦oõ ÃHÏ4ú ïïPï “d™«”–• egf„i•›¥¤•j ׈ÒxÌ3Ñ1ÀPÆ ‚m—˜gI™hšqgIi•›½²Y ¢i•e•eŸ™qe„y™i„j j Before launching into a detailed discussion of how to write your own classes. You can think of the class itself as a sort of factory for stamping out new instances. let’s take a short detour to see how useful new classes can be. Basically a class is a description of what its instances will know and do. which stores the length of the circle’s radius. New objects are created from a class by invoking a constructor. called methods. This state׈ÒÓ̽ÑHÀHÆ ment creates a new instance and stores a reference to it in the variable ʽϨ׈ÒxÌ3ÑHÀHÆ . the instance variables and methods are called the attributes of an object. Ê£}ȑÇÈƒÊ ’”“Hv••“f–B— Ø Í'imœcl@u{œ)–mtqlnvxw Suppose we want to write a program that simulates the flight of a cannonball (or any other projectile such as a bullet. or shot put). The method Ñ1ÆÓÇÄÆ1Ì to reflect the new position of the circle.rI逹 s4tvuxwzy|{I}†~87Püé4{ÒêŠ 6 ŠŒ«sB± uŒˆ–ˆp{ôˆ 2. The class of the object determines what attributes the object will have. Consider making a new circle object: ʽϨ׈ÒxÌ3ÑHÀHÆcßÝ׈ÒxÌ3Ñ1ÀPÆæñèØÁҀÇĉñzՉõ–Õ3ú“õ ÔPÕ3ú . the name of the class. The methods of the circle will ÃPÌÂ£Û Ñ£Æ£ÇĨÆHÌ need this data to perform actions. We are particularly interested in finding out how far the cannonball will travel when fired at various . is used to invoke the constructor. The method examines the and ̈Â1ýÒIÉ@Ü Ê3g Á W¨Æ to decide which pixels in a window should be colored. Once the instance has been created. ׈ÒÓ̽ÑHÀHÆ To take a now familiar example. The information is stored inside the object in instance variables. The operations. will change the value of Recall that every object is said to be an instance of some class.

amount of time ( '& Ê£}ȑÇÈ‘Ç œ ˜ ™ º i§slŒ•wQl™wm•`t QiE’”“Hv••“f–B— )  Let’s start by designing an algorithm for this problem. The input to the program will be the launch angle (in degrees). Separating out the “ and components of the velocity makes the problem easier. In fact. We can think of the position of the cannonball as a point ‚”“ „ in a 2D graph where the value of gives the height above the ground and the value of “ gives the distance from the starting point. However. per second. its upward speed will have slowed to " ¡ w †£€©h …žwch ¡ meters per º second. it’s not hard to derive a formula that gives the position of our cannonball at any given moment in its flight. the speed will be only wch  meters per second. the “ velocity remains constant for the entire flight. Our simulation will have to update the position of the cannonball to account for its flight. Rather than take the calculus approach. For those who know a little bit of calculus. and the initial height (in meters) of the cannonball. Since we are ignoring wind resistance.. along with the obvious relationship that the distance an object travels in a given amount of time is equal to its rate times the ö ). After another second. after one second has passed.e. Given the problem statement.8 meters per second. The exact distance in each dimension is determined by its velocity in that direction. The acceleration of gravity near the earth’s surface is about 9. and we want to check its position. however. Suppose the ball starts at position ‚ƒw Òwg„ . so we know when it hits the ground. the velocity will start out being positive and then become negative as the cannonball starts back down. our program will use simulation to track the cannonball moment by moment. The output will be the distance that the projectile travels before striking the ground (in meters). say. to keep track of how far it goes. In that interval. ’q – – %q – – – – . That means if an object is thrown upward at a speed of 20 meters per second. the velocity changes over time due to the influence of gravity. every tenth of a second. and distance. the initial velocity (in meters per second). we’re not trying to put it into orbit). If we ignore the effects of wind resistance and assume that the cannonball stays close to earth’s surface (i. we can solve this problem algorithmically. and shortly thereafter it will start coming back down.~87H rHCŽ‡uxƒ„w± {£½}$‚IH}$uxƒ”´“s½uxŠ€ŠŒ‚1Š vu± ± s rI逿 launch angles and initial velocities. this is a relatively simple classical physics problem. it will have moved some distance upward (positive ) and some distance forward (positive “ ). it’s clear that we need to consider the flight of the cannonball in two dimensions: height. Using just a bit of simple trigonometry to get started.

Our input angle is in degrees.) If we consider the initial velocity as consisting of some amount of change in and some amount of change in “ . it’s pretty clear what our simulation will have to do. We’ll have to convert our angle before applying % ú the formulas. then these three components (velocity. ¦½ÁˆÜ ßÝÕnïùÕ Ï ½ÁˆÜ ßUÅ½Õ g Next we need to calculate the “ and components of the initial velocity. A similar formula (using Even if you don’t completely understand the trigonometry. the important thing is that we can translate these formulas into Python code. There’s still one Ê4Â1Ä1Å subtle issue to consider. so „ƒ . illustrates the situation. they told you you’d use that some day. and the Python library uses radian measures. Here is a rough outline: ¢I) Ç É¨Ä€ÄHňơÜP҇ʨÉ3ÀPÂ1Ä3Ò£Á£Ç£3Â1Ì€Ê3ÆHÄÆ1ÌÎܬ÷lÂÓÇC!ÀHƄõ°W¨Æ¨ÀPÁѐÒxĐÏnõ ŽÆÒ !1ŨÄnõÒIÇĨÆHÌ©WÀ„ï רÂPÀÑIÉ3ÀÂ£ÄÆ ÄHŽÆàÒIÇ4ÒxÄ3ÒHÂPè À ½ÁˆÜPÒxÄ3Ò1ÁÓÇàÁP̀Ä1ŽÆàÑ1ÂÓǐLjÁ£ÇPË3ÀPÀo÷ ¦ˆÁ½Ü­õ¢Ï½ÁˆÜ רÂPÀÑIÉ3ÀÂ£ÄÆ ÄHŽÆàÒIÇ4ÒxÄ3ÒHÂP` À WƐÀPÁѐÒÓĽÒ1ƈÜYÁP̀Ä1ŽÆàÑ1ÂÓǐLjÁ£ÇPË3ÀPÀo÷ ¦)WƐÀ‰õl) Ï WƐÀ 4PÅÎÒHÀHÆUÄHňÆàÑHÂÓÇPǽÁÓǐË3ÂPÀÀ€Ò¨ÜWÜxĽÒHÀPÀcÍÀ1ϽҀC Ç !Ÿ÷ É ÃÂ1ĨÆUÄHňE © Æ WˆÂPÀÓÉ½ÆˆÜ ÁP¥ Í ¦ ½ÁˆÜ­õ¢g Ï ˆÁ½Ü†õ ÂÓÇÀ© Ï WƐÀUͨÁ1ÌÿҀǨÄÆH) Ì WˆÂPÀÐÜ£ÆÑ1Á£ÇÃ3Ü Í1ÉÌPÄHňÆHÌ¡ÒIÇÄÁÈÄHŽƀͨÀ" Ò !1ÅÄ Ä É¨g Ä PÉĀÄ1ŽƀýҐÜxÄÂÓÇ4Ñ£ÆUĐÌ  W¨Æ¨ÀPÆHÃWÂV Ü ¦½ÁˆÜ Let’s turn this into a program using stepwise refinement. We’ll need a little high-school trigonometry. We just need a couple of assignment statements. There are ¡ radians in a circle (360 degrees). because the Greek letter ~ is often used as the measure of angles). (See. º ú ) provides  û . The first line of the algorithm is straightforward. º€ ‚ ¶s»¡¹ These three formulas give us the code for computing the initial velocities: – ™wk 9 ™ – – @QASC ™lk 9 ™ 9 8 – 9 9 9 •” ™ GE F3@ l™ k 9 ™ – ™lk 9 ™ t n 'p . Here’s a start: èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ÂÓC Ç !ÀPÆUß ÒI© Ç PÉĄ" ñ  ÇÄÆ1ÌUÄ1ŽÆÝÀPÂÓɐÇÎрšÂx§ Ç !¨ÀPÆòñvÒIÇÐèg Æ !P̨Ɛƽܐú¬$ ÷ Óú G WƐÀcߡҀ© Ç PÉĉñ  ÇĨÆHÌcÄ1ŽÆàÒIÇ4ÒÓĽÒHÂPV À WƐÀPÁѐÒÓÄPÏ ñvÒIÇcÊÎÆ1ÄÆHÌ3 Ü ŸܣƈѨú¬‰ ÷ £ú G ŽՀßÿҀ) Ç É¨Ä„ñ  ǨÄÆHÌÈÄHňÆàҀÇÎÒÓÄ3Ò1ÀYňƈ" Ò !1ÅÄòñvҀÇcÊ3ÆHĨÆHÌÎܐú¬ü ÷ £ú G Ä3ÒvÊÎƀߡҀ) Ç É¨Ä„ñ  ǨÄÆHÌÈÄHňÆcÄ3ÒvÊÎÆàҀǨÄÆ1© Ì WˆÂPÀY˽Æ1ÄPÛƐƣ£ Ç ½ÁˆÜPÒÓĽÒ1ÁÓÇ ÑHÂPÀрɽÀÂ£Ä3Ò1ÁÓÇ@ܬ÷üÓú G Calculating the initial position for the cannonball is also easy. 10  “ -velocity and -velocity) form a right triangle. we can easily calculate the magnitude of “£ û by the equation “§ û  û "ù3÷ ú . If we know the magnitude of the velocity and the launch angle (labeled ú . Figure . We just need an appropriate sequence of input statements. It will start at ÅˆÕ distance 0 and height .rIé€â s4tvuxwzy|{I}†~87Püé4{ÒêŠ 6 ŠŒ«sB± uŒˆ–ˆp{ôˆ Given this analysis.

The loop will quit as soon as the value of dips just below 0. To update the horizontal position. Now we arrive at the crux of the simulation. ” That brings us to the main loop” in our program. We want to keep updating the position and velocity of the cannonball until it reaches the ground.~87H rHCŽ‡uxƒ„w± {£½}$‚IH}$uxƒ”´“s½uxŠ€ŠŒ‚1Š vu± ± s rIé€é ty oci l e v theta yvel = velocity * sin(theta) xvel = velocity * cos(theta) Figure …Q† . suppose the ball is traveling at 30 meters per second and is currently 50 meters from the firing point. If the interval is only 0. You can see that the new distance traveled is always given by 6‡ fˆ ‹ ’ . then the cannonball will only fly another S‘¡’Q“•”I– ” ” Ž meters and be at a distance of — meters. In another second. we” need just one statement: ” Ø å éà àé ßß æ Ú žâ)ìÛÓ€Ô ß3àeømîgï…ælï Öuܺ 3 Ô é Ö ž â ç § 3 â u Ö Ü é à å êBêBÖ3Ö3ܺ Ø ÔgÔgӞ Ӟçç  ÔgÔgÓÓ Ú)Ú)րրØØ j j!â!â ÖuÖuÜ ÜææQå€Úíì ܺÔ3Ô3Öé Öé⺠âºòò ºà Ø å ºà á€ÜjÚ3Ó€ÔžØ å uç¡ïæqï ‡‡ ‰ˆ fŠ ‹ ’ ‰’ ‰’ vˆd‡ vˆd‡ ’ ‡Œ ˜— ÖºÚ `Ô ÔgÓ ºà ‹ Ö Ú §Ô ÔgÓ º å ç å #Ö`Ú §Ô %Ô%Ó ® ºà ‹ ‡˜ ™‡ ˆ ‹ ’ . the horizontal . We can do this by examining the value of . speed of the cannonball will remain constant and is given by the value of ‹ ’ As a concrete example. it will go 30 more meters and be 80 meters from the firing point.1 second (rather than a full second). Each time we go through the loop. we want to update the state of the cannonball to move it 6‡ seconds farther in its flight. Let’s start by considering movement in the horizontal direction. Since our specification says that we can ignore wind resistance. ” Ž I used as the relationship so that we can start with the cannonball on the ” ground (= 0) and still get the loop going. … : Finding the x and y components of velocity. indicating the cannonball has embedded itself slightly in the ground.

This is done to preserve the initial so that the Ï©W¨Æ¨À average velocity can be computed from the two values. Adding this step gives us the complete program. must decrease by 9. In 0. we need to know its average vertical velocity. Multiplying this average velocity by the amount of time in the interval gives us the change in height. Each second. the value of is assigned its value at the end of the loop. Since the acceleration due to gravity is constant. the average velocity will just be the average of the starting and ending ñè© Ï W¨Æ¨ÀHáH© Ï W¨Æ¨À3ÖHú ŸPÔoïðÕ velocities: .1 seconds the velocity will decrease by wch‘…‚b€©h „ meters per second. This represents the correct vertical velocity of the cannonball at the end of the interval.8 meters per second.”q77 s4tvuxwzy|{I}†~87Püé4{ÒêŠ 6 ŠŒ«sB± uŒˆ–ˆp{ôˆ The situation for the vertical component is slightly more complicated. the acceleration of gravity. The new velocity at wch€ º the end of the interval is calculated as – '& !& Ï)WƐÀ3Ö ß€Ï©W¨Æ¨À¥¨UĽ҇ÊÎÆ@YUýoïHe To calculate how far the cannonball travels during this interval. ó¡Ñ€Ë½ÂÀPÀ3Ö­ïbÏ ÍP̨ÁxÊWÊÎÂ1ÄHÅÿ҇ÊCˆÁHÌPÄ£4Ò­õÜPҀǟõ Ñ1ÁˆÜ èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ÂÓC Ç !ÀPÆUß ÒIÇ©PÉĄñ" ÇÄÆ1ÌUÄ1ŽÆÝÀPÂÓɐÇÎрšÂxǧ!¨ÀPÆòñvÒIÇÐèÆg!P̨Ɛƽܐú¬÷$Óú G WƐÀcߡҀǩPÉĉñ  ÇĨÆHÌcÄ1ŽÆàÒIÇ4ÒÓĽÒHÂPÀVWƐÀPÁѐÒÓÄPÏ ñvÒIÇcÊÎÆ1ÄÆHÌ3ÜŸܣƈѨú¬÷‰£ú G ŽՀßÿҀ) Ç É¨Ä„ñ  ǨÄÆHÌÈÄHňÆàҀÇÎÒÓÄ3Ò1ÀYňƈÒ"!1ÅÄòñvҀÇcÊ3ÆHĨÆHÌÎܐú¬÷ü£ú G Ä3ÒvÊÎƀߡҀ) Ç É¨Ä„ñ  ǨÄÆHÌÈÄHňÆcÄ3ÒvÊÎÆàҀǨÄÆ1© Ì WˆÂPÀY˽Æ1ÄPÛƐƣ£ Ç ½ÁˆÜPÒÓĽÒ1ÁÓÇ ÑHÂPÀрɽÀÂ£Ä3Ò1ÁÓÇ@ܬ÷üÓú G ó Ñ1ÁÓÇCWÆ1̐ÄÐÂxǧ!¨ÀPÆcÄÁcÌÂHÈÒHÂÓÇ4Ü ¡ ÄHňÆHĈÂÈß ñzÂÓÇC!ÀPÆ Y§4Òú"Ÿ3ÖeÕnïùÕ . since Ï©W¨Æ¨À gravity causes the -velocity to change over time. The last step of our program simply outputs the distance traveled. Finally. Here is the completed loop: ÛPÅ4Ò1ÀPÆcÏ)WƨÀ ( ßÝÕnïùÕn÷ ¦ ½ÁˆÜ ¥ ß ¦½ÁˆÜ á€Ä3ÒvÊÎÆ@Y`¦)W¨Æ¨À Ï WƐÀ3Ö ß€© ) Ï W¨Æ¨À¥¨UĽ҇ÊÎÆ@YUýoïHe Ï ½ÁˆÜ ߀g  Ï ½ÁˆÜ á€Ä3ÒvÊÎ@ Æ Y¥ñ–) Ï WƐÀcá€Ï©WƐÀ3ÖHú  Ÿ ԄïðÕ Ï WƐÀc߀© ) Ï WƐÀ3Ö Notice how the velocity at the end of the time interval is first stored in the Ï)WƐÀ3Ö Ï)WƨÀ temporary variable .

Let’s try dividing the program into functional pieces to see if that helps.~87H rHCŽ‡uxƒ„w± {£½}$‚IH}$uxƒ”´“s½uxŠ€ŠŒ‚1Š vu± ± s ”q7H~ óÿÜ£Æ1ÄWÄHŽÆàÒIÇ4ÒxÄ3ÒHÂPÀè½ÁˆÜPÒxÄ3Ò1ÁÓÇ¡ÂÓÇÃEWƐÀPÁѐÒÓĽÒ1ƈÜUҀǡ¦ÐÂxLjÀÏÝýÒxÌÆÑÓÄ3Ò£Á£Ç4Ü ¦ˆÁ½Ü ßÝÕ ÏgˆÁ½Ü ßUÅ½Õ ¦)W¨Æ¨ÀcT ß WƐS À YWÑ1ÁˆÜ“ñ–Ä1ŽÆ1Ĉ½ú Ï©W¨Æ¨ÀcT ß WƐS À YÝÜPÒIÇnñ–Ä1ŽÆ1Ĉ½ú óÐÀPÁPÁ WɐǨÄ3Ò1ÀÈÄHňÆÈË3ÀPÀ Å4ÒxÄÎÜYÄHňÆE!P̨Á£ÉPLjà ÛPÅÎÒHÀPÆÈÏg½ÁˆÜ ( ßÝÕo÷ ó¡ÑHÀ¨Ñ€É½ÀÂ1ĨÆV½ÁˆÜPÒxÄ3Ò1ÁÓÇàÂxLjÃTWƐÀPÁѐÒÓÄPϡҀÇÐĽ҇Ê3ÆàÜ£ÆÑ1Á£ÇÃ3Ü ¦½ÁˆÜY  ß ¦ˆÁ½Ü á€Ä3ÒvÊÎ@ Æ Y`¦gWƨÀ Ï WƐÀ3Ö ßW) © Ï WƨE À ¨€Ä½Ò‡Ê3S Æ YcýnH ïe Ï ½ÁˆÜYßWg g Ï ˆÁ½Ü á€Ä3ÒvÊÎ@ Æ Y¥ñè© Ï WƐÀUáW© Ï W¨Æ¨À3ÖHú ŸPÔoïðÕ Ï WƐÀUßW© © Ï W¨Æ¨À3Ö ̽ҀÇÄ Ê£}ȑÇÈ‘É í´ g ¶ £› ÓÇ ÎҐÜxĈÂxÇ4Ñ£ÆÈĐÌÂW¨Æ¨ÀPÆHß÷ ¨Õnï†Ö€Í v xrBٌ–m“¡l›š)l™wm•Tt %iE’”“fv••“H–B— )  " Ê3ÆHÄÆ1ÌÎܬïq ©ñÒ¦½ÁˆÜ¨ú " You may have noticed during the design discussion that I employed stepwise refinement (top-down design) to develop the program. but I did not divide the program into separate functions. we’ll use functions (a ´ la top-down design). First. You might take a couple of minutes to code up the three helper functions. it is fairly complex for its length. While the final program is not too long. Here’s a version of the main algorithm using helper functions: èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ÂÓC Ç !ÀPƉ° õ WƐÀ‰õ ňՄõ¢Ä3ÒvÊÎÆcß !ÆHÄQ¢‡Ç©PÉÄÎÜ@ñIú ¦ˆÁ½Ü­õ g Ï ½ÁˆÜ ßÝՄõlÅ½Õ ¦)W¨Æ¨À‰õ © Ï WƐÀcߥ!¨Æ1Ä ¨×Á€ÊC½ÁÓǽÆÓÇÄÎÜ@ñÒW¨Æ¨ÀPÁѐÒxĐÏnõ ÂÓǧ!¨ÀPƽú ÛPÅÎÒHÀPÆÈg Ï ½ÁˆÜ ( ßÝÕo÷ ¦½ÁˆÜ­õl Ï ½ÁˆÜ­õ¢© Ï W¨Æ¨ÀUßc) É ˆÃ£ÄÆPרÂÓÇPǽÁÓÇ ˆÂPÀÀ­ñ–Ä3ÒvÊÎƉõ ¦ˆÁ½Ü­õ¢Ï½ÁˆÜ­õç¦gWƨÀæõlÏ©W¨Æ¨Àˆú ̽ҀÇ Ä  ÓÇ ÎҐÜxĈÂxÇ4Ñ£ÆÈĐÌ  W¨Æ¨ÀPÆHß÷ ¨Õnï†Ö€Í Ê3ÆHÄÆ1ÌÎܬq ï  ©ñÒ¦½ÁˆÜ¨ú %Ѐ“ í´ g "  " It should be obvious what each of these functions does based on their names and the original program code. and that is a lot for the reader to keep track of. One cause of the complexity is that it uses ten variables. We are going to modularize the program in two different ways. .

An explosion of parameters is often an indication that there might be a better way to organize a program. . The original problem specification itself suggests a better way to look at the variables in our program. and . and are used as parameters to create a ̨ؐÁ ƈÑÓĽÒHÀHÆ Ñ€Ë½ÂÀPÀ р˽ÀÀ ï called . is asked to update Ä3ÒvÊÎÆ Ñ€Ë½ÂÀÀ its state to account for . is É ˆÃ¨Â1ĨƐרÂxǐLjÁ£Ç ÀPÀ © now local to . . Let’s try another approach. we could express the main algorithm in terms of creating and updating a suitable object stored in a Ê4Â¨Ò€Ç like this: single variable. three of which must change from moment to moment. this is a much simpler and more direct expression of the algorithm. Similarly. Do you see where they went? The value ÄHňÆHĈ !ÆHÄ ×PÁxC Ê ˆÁ£ÇˆÆ£ÇÄ3Ü Ï)WƨÀ½Ö of is only needed locally inside of . g“ gÐ g“ gÐ . Look especially at the loop. To make this work.  %Ðu“ Even this version seems overly complicated. we might write èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ÂÓC Ç !ÀPƉ° õ WƐÀ‰õ ňՄõ¢Ä3ÒvÊÎÆcß !ÆHÄQ¢‡Ç©PÉÄÎÜ@ñIú р˽ÀÀÈßÝØPÌÁ ƈÑxÄ3Ò1ÀPÆæñzÂÓÇC!ÀPƉõ WƨÀæõîŽսú ï ÛPÅÎÒHÀPÆÝрË3ÂPÀÀ„ïf!¨Æ1Ä ‰ñIú ( ßÝÕn÷ рË3ÂPÀÀ„ï|© É Ã£ÄÆæñèÄ3ÒvÊÎÆ3ú ̽ҀÇ Ä  ÓÇ ÎҐÜxĈÂxÇ4Ñ£ÆÈĐÌ  W¨Æ¨ÀPÆHß÷ ¨Õnï†Ö€Í Ê3ÆHÄÆ1ÌÎܬïq ©ñŒÑ€Ë3ÂPÀÀ„ïf!¨Æ1Ä æñIúú í´ g g“ " " %Ð Obviously. We can get the position of at any moment !ÆHÄ !ÆHÄ by using its and methods. but ¦ˆÁ½Ü . All four variables along Ľ҇Ê3Æ are needed to compute the new values of the three that with the value of change.”q7€r s4tvuxwzy|{I}†~87Püé4{ÒêŠ 6 ŠŒ«sB± uŒˆ–ˆp{ôˆ This second version of the main algorithm is certainly more concise. Using such a class. Keeping track of the state of the cannonball requires four pieces of information. . Suppose we had a class that “understood” ï the physics of objects like cannonballs. There is a single real-world cannonball object. Using this object-based approach. ÂÓÇC!ÀPÆ W¨Æ¨À Å½Õ The initial values of . and !¨Æ1Ä . describing it in the current program requires four pieces of information: Ï ˆÁ½Ü ¦gWƐÀ g Ï W¨Æ¨À © ؐÌÁ ÆÑÓÄ3Ò1ÀPÆ . That results in an ugly function call having five parameters and three return values. since and have been eliminated from the main algorithm. we just need to define ØPÌÁ ƈÑxÄ3ÒHÀHÆ É ÃÂ1Ä¨Æ !¨ÆHÄ © ï a suitable class that implements the methods . Being able to hide some of the intermediate variables is a major benefit of the separation of concerns provided by top-down design. Each time through the loop. The ÄHŽÆ1Ĉ Ï)WƐÀ3Ö number of variables has been reduced to eight.

thirteen) sides. Let’s design a general class ö Å ÎÒ£Æ m to model multi-sided dice. we specify how many sides it will have. How many sides it has. Its current value. and .g.. to set the Ü£Æ1ĩۈÂPÀÓÉˆÆ die to a random value between 1 and ø . 2. We could use such an object in any number of simulation or game programs. Ê£}ȑÉÈƒÊ š#›§–B—$ٌ͕i ¨ ¶ ‡· U› `›ãœ rBوtql Ø l Bi ¦l‡œ©i You know that a normal die (the singular of dice) is a cube. ø . Here is an interactive example showing what our class will do: (©()( (©()( ) Ö Ã½Ò£ÆÎÖ ßcömÅ ÎÒ£Ææñzø½ú ýңÆÎÖ­ïp!¨Æ1ĩۈÂPÀÓɈÆæñIú ýңÆÎÖ­ï–ÌÁÀÀ¬ñ‡ú ýңÆÎÖ­p ï !¨Æ1© Ä ÛˆÂPÀÓɈÆæñIú ýңƨÔcßcömÅ ÎÒ£Ææñ€Ö€Þ3ú ýңƨÔop ï !¨Æ1© Ä ÛˆÂPÀÓɈÆæñIú ýңƨÔoï–ÌÁÀÀ¬ñ‡ú ýңƨÔop ï !¨Æ1© Ä ÛˆÂPÀÓɈÆæñIú ýңƨÔoïôÜ£Æ1ĩۈÂPÀÓɈÆæñ8e½ú ýңƨÔop ï !¨Æ1© Ä ÛˆÂPÀÓɈÆæñIú ) (©()( (©()( d (©()( (©()( ) Ö (©()( (©()( ÖÓÔ (©()( (©()( e . four) or more (e. let’s take an even simpler example to examine the basic ideas. cheat). . ö Å ÎÒ1Æ m is created. inclusive. We When a new ÌÁ¨ÀPÀ can then operate on the die through three provided methods: .. Some games employ nonstandard dice that may have fewer (e.. to see what the current value is. ö Å ÎÒ£Æ m Each object will know two things: ) ) 1.e. and each face shows a number from one to six.g.“d™«”– «ª‚{ìŽeh‡penš § ~87P ”Pcé4{ÒêŠ 6 Š† Î{–’ªsB± uŒˆ–ˆ–{zˆ ª‚‰œ   j in‘‘‚„‘ 2¨ ”q7€” Before designing a Projectile class. to set the die to a !¨ÆH) Ä ÛˆÂPÀÓÉ½Æ specific value (i.

Here is the class definition ö Å ÎÒ1Æ m for : ó ʆÜxýңÆnU ï ¨Ï ó אÀÂˆÜPÜYèÆHͽÒIÇ4ÒÓĽÒ1ÁÓÇÝͨÁ1ÌàÂÓÇWm Ç ¨ˆÜPÒÓèÆHÀýңÆnï ! ) ! ÍP̨ÁxÊ¡ÌÂÓLjÐÁxÊ»ÒvÊCˆÁH̐Äc̈ÂÓÇÃPÌÂÓǧ!Æ ÑHÀPˆÜPÜ ömÅ ÎÒ1Æo÷ èÆHÍSÌ©ÌÒIÇ4Òxħ̩̭ñ‡ÜÓƨÀḦ́õ ÜHңÐƽܨú­÷ ܣƨÀ1͟ïôÜPÒ£ÃÆ½Ü ßÿÜPÒ£ÃÆ½Ü Ü£Æ¨À1͟s ï WˆÂÀxɽÆÈß Ö Ã¨ÆH̀ÌÁ¨ÀPÀ¬ñvܣƨÀ1ÍÎú­÷ ܣƨÀ1͟s ï WˆÂÀxɽÆÈ߀̈ÂÓÇÃPÌÂÓǧ!ÆæñI֓õŒÜÓƨÀ1͟ïzÜHңÐƽÜÓáÎÖPú èÆHÍ¥!¨ÆHÄ)ۈÂPÀÓɽƬñ‡ÜÓƨÀHÍ3ú¬÷ ÌÆHÄ1ÉÌ1Ç Ü£ÆÀH͟s ï WˆÂPÀÓÉ½Æ Ã¨ÆHÍÿÜ£ÆHÄ)ۈÂPÀÓɽƬñ‡ÜÓƨÀḦ́õIWÀxɽÆ3ú­÷ ܣƨÀ1͟s ï WˆÂÀxɽÆÈT ß WˆÂÀxÉ½Æ ) As you can see. The ̨Á¨ÀPÀ Ü£ÆHg Ä  ˆÁÀÀ value can be changed by the and methods and returned from the !¨Æ1© Ä ÛÀÓÉˆÆ method. Each die can be rolled independently and will always produce a random value in the proper range determined by the number of sides. Another instance variable will be used to store the current value of the die. Initially. Placing the func- . the value of the die will be set to be 1. A class is a colWriting a definition for the lection of methods. a class definition has a simple form: ÑHÀPˆÜPÜ Ñ1ÀÂˆÜPܨxÇ3€Ê3Æ ( ÷ F Ê3ÆHÄHňÁPc à ¨HèÆHͽÒIÇ4ÒÓĽÒ1ÁÓÇ@Ü ( F Each method definition looks like a normal function definition. ö Å 3Ò1Æ § Using our object-oriented terminology. ö Å 3Ò1Æ § class is really quite simple. and methods are just functions. since that is a legal value for any die. we create a die by invoking the constructor and providing the number of sides as a parameter.”q7 ¯ s4tvuxwzy|{I}†~87Püé4{ÒêŠ 6 ŠŒ«sB± uŒˆ–ˆp{ôˆ Do you see how this might be useful? I can define any number of dice having arbitrary numbers of sides. Our die object will keep track of this number internally using an instance variable.

Python executes a four-step sequence: Ê4ÂÒIÇ ) suspends at the point of the method applica1. in this ÈÒ1ÆÎֆïzÜÓÆHĩېÀxɽÆæñëe3ú case. we would say definition has two parameters. so is a parameter that represents an object. I will always refer to the first formal parameter of a method as the self parameter and any others as normal ÜÓÆH© Ä ÛÀxÉ½Æ uses one normal parameter.~87P ”Pcé4{ÒêŠ 6 Š† Î{–’ªsB± uŒˆ–ˆ–{zˆ 2¨ ”q7€´ tion inside a class makes it a method of that class. The parameter in the definition is a bookkeeping detail. In the case of a method call. The calling program ( tion. The first parameter of a method is special—it always contains a reference to the object on which the method is acting. it is as if the following assignments are done before executing the method body: Ü Æ¨À1ÍWßWýңÆÎÖ £ WˆÂÀxɽƀߠe 3. Suppose we have a Ê4Â¨Ò€Ç Ã½Ò1Æ3Ö­ïôÜ£ÆH) Ä ÛˆÂPÀÓɽƬ8 ñ e½ú function that executes . So. The formal parameters of the method get assigned the values supplied by the actual parameters of the call. Some languages do this implicitly. illustrates the method-calling sequence for this example. since is an transferring to the ö Å 3Ò1Æ § . but the method ܣƐÀHÍ . In our example. As usual. you can use any name you want for this parameter. The body of the method is executed. instance of ! ) 2. Notice how the method is called with one parameter (the value). Let’s take a look at the three methods defined in this class. 4. due to Ü£Æ1© Ä ÛÀÓÉˆÆ ÜÓƨÀ1Í requires one parameter. I would say ÜÓƨÀHÍ OK. Just as in normal function calls. ÜÓƨÀ1Í An example might be helpful in making sense of . Python locates the appropriate method definition inside the class of the object to which the method is being applied. Generally speaking. To avoid confusion. 10  Figure . But what exactly can we do with it? The main thing to remember is that objects contain their own . the statement immediately following . but the ÜÓƨÀHÍ traditional name is . Control returns to the point just after where the method was called. so that is what I will always use. A method invocation is a function call. rather than a stand-alone function. You’ll notice that ܣƐÀHÍ each method has a first parameter named . parameters. the first formal parameter corresponds to the object. control is Ü£ÆH) Ä ÛˆÂPÀÓÉ½Æ ö Å ÎÒ£Æ m ÈÒ1Æ3Ö method in the class. In this case. Python requires us to add the extra parameter.

. The net result is that £ž ᷟ¸¡¤ž ¡ is set to 6 and Xž ᷟ­¬ is set to 1. Ü : Flow of control in call: £ž H ᠟„¡ HI¢¤££¥¤Ug¦£H¨§„©£ª . data. the constructor is referred to by the class name. This is different from regular local function variables. £ž H á§ß³®£¯°©ž H´§¶µ§ª H ¢ When executing this statement. Python creates a new ®£¯°§ž and executes ži±©ž H H H ¥Ug¦XH on that object.value = value print die1.¡ refers to the instance variable ¬ that is stored inside ¡ Ÿ­¬ H the object. value=8 def setValue(self. instance variables are accessed by name. Look at the definition of HQ¢£X¥Ug¦XH HVU « ¥Ui¦£H ¥¤Ug¦XH . whose values disappear once the function terminates. Here is a simple illustration: TT¤T¹£ž H á§ß³°©ž ¢ £ž H H´§ ágº ª HI¢¤££¥¤Ug¦£H¨§6ª TT¤T»PVR£ži± ᠟­¼ á TT¤T¹£ž H ᠟„¡ ¢ HQ¢££¥¤Ug¦XH´§„©£ª £ž H TT¤T»PVR£ži± ᠟­¼ HI¢¤££¥¤Ug¦£H¨§6ª . Just as with regular variables. Python calls this method to initialize a new ž²±'ž H ¢ ®§¯g°©ž . instance-var . Each instance of a class has its own instance variables.”q7€¹ s4tvuxwzy|{I}†~87Püé4{ÒêŠ 6 ŠŒ«sB± uŒˆ–ˆp{ôˆ class MSDie: def main(): .value) die1. The power of instance variables is that we can use them to remember the state of a particular object.setValue(8) self. die1 = MSDie(12) self=die1. From outside the class.getValue() Figure ÝIœ . Certain methods in a class have special meaning to Python. Instance variables provide storage locations inside of an object. The special method ¢ is the object constructor. We can use Y c Y c our familiar dot notation: object . and this information then gets passed around the program as part of the object. The values of instance variables can be referred to again in other methods or even in successive calls to the same method. These methods have names that begin and end with two underscores. so each ®§¯°§ž ¥¤Ug¦XH object has its very own ¬ . The role of ž²±'ž is to provide initial values for the instance variables of an object..

so it is just a normal (local) function variable. we will create a cannonball from the initial angle. That’s just about all there is to know about defining new classes in Python. %Ð g“ р˽ÀPÀUßWؐÌÁ ï ÆÑÓÄ3Ò1ÀPƬñ†ÂÓÇC!ÀHƄõ  W ƐÀ‰õ Žսú ØPÌÁ ƈÑxÄ3Ò1ÀPÆ Ò€Ç4ÒxÄ The class must have an method that uses these values to ï р˽ÀÀ initialize the instance variables of . This class will need a constructor to initialize instance variables. even though the constructor is over and done with. velocity and height. an !ÆHÄ !¨Æ1Ä method to change the state of the projectile. we want a class that can represent projecÉ©ˆÃ¨Â1Ä¨Æ tiles. . Here is how our class looks with the constructor: ÑHÀPˆÜPÜ ØÌ¨Á ï ÆÑÓĽÒHÀPÆo÷ èÆHÍSÌ©ÌÒIÇ4Òxħ̩̭ñ‡ÜÓƨÀḦ́õ¢Âxǧ!¨ÀPƄõ5WƨÀHÁˆÑPÒÓĐÏoõ ÅˆÆˆÒ !£ÅÄÎú¬÷ ܣƨÀ1͟p ï ¦½ÁˆÜ ßÐÕnïùÕ Ü£Æ¨À1͟ï–g Ï ½ÁˆÜ ßcŽÆÒ !£ÅÄ ÄHŽÆ1ĈÂUßÈÊÎÂ1ÄHÅhU ï ÎE Ò Y€ÂÓC Ç !ÀPT Æ Ÿ  Ö eÕoïðÕ Ü£Æ¨À1͟p ï ¦)WƐÀÈ¥ ß WƐÀPÁѐÒÓÄP@ Ï Y Ê4£ÄHÅhïôÑ1ÁˆÜ“ñèÄHŽÆ1Ĉˆú ܣƨÀ1͟ Ï WƐÀÈ¥ ß WƐÀPÁѐÒÓÄP@ Ï Y Ê4£ÄHÅhïzÜPÒIÇnñèÄHŽÆ1Ĉˆú Notice how we have created four instance variables inside the object using the ܣƐÀHÍ ÄHňÆHÄ ҀÇÎÓ Ò Ä dot notation. . . and . In the main program. The value of is not needed after terminates.~87P ”Pcé4{ÒêŠ 6 Š† Î{–’ªsB± uŒˆ–ˆ–{zˆ e 2¨ ”q7€¿ ÈÒ1Æ3Ö­p ï WÀxÉ½Æ The call to the constructor sets the instance variable to 1. Ê£}ȑÉÈ‘Ç š#›§–B—$ٌ͕i ¨2ÿ   3¿ ¤ª %i£’”“Hv 8i%œgtql‘ÙŒi gٌ–mss Returning to the cannonball example. The value set by the constructor persists as part of the object. they will be the four pieces of information that characterize the ¦ˆÁ½Ü g Ï ˆÁ½Ü ¦)W¨Æ¨À Ï©W¨Æ¨À flight of the cannonball: . executing ýңÆÎֆïzÜ£Æ1© Ä ÛÀÓɈÆæë ñ e3ú changes the object by setting its value to 8. Similarly. But what should the instance variables be? Of course. The next line prints out this value. and and methods so that we can find the current position. We will calculate these values using the same formulas that were in the original program. Let’s start with the constructor. When the object is asked for its value the next time. Now it’s time to put this new knowledge to use. it responds with 8.

we come to the method. this is the same code that we used in the original program updated Ï©W¨Æ¨À½Ö to use and modify instance variables. We now have a complete object-based solution to the cannonball problem. ó¡Ñ€Ë½ÂÀPÀPÞnïbÏ ÍP̨ÁxÊWÊÎÂ1ÄHÅÿ҇ÊCˆÁHÌPÄ£4Ò­õÜPҀǟõ Ñ1ÁˆÜ ÑHÀPˆÜPÜ ØÌ¨Á ï ÆÑÓĽÒHÀPÆo÷ èÆHÍSÌ©ÌÒIÇ4Òxħ̩̭ñ‡ÜÓƨÀḦ́õ¢Âxǧ!¨ÀPƄõ5WƨÀHÁˆÑPÒÓĐÏoõ ÅˆÆˆÒ £ ! ÅÄÎú¬÷ ܣƨÀ1͟p ï ¦½ÁˆÜ ßÐÕnïùÕ Ü£Æ¨À1͟ï–g Ï ½ÁˆÜ ßcŽÆÒ !£ÅÄ ÄHŽÆ1ĈÂUE ß Î¥ Ò YcÂÓ§ Ç !¨ÀP  Æ Ÿÿ Ö eÕnïùÕ Ü£Æ¨À1͟p ï ¦)WƐÀÈ¥ ß WƐÀPÁѐÒÓÄP@ Ï YÝÑ1ÁˆÜ“ñèÄHŽÆ1Ĉˆú ܣƨÀ1͟ Ï WƐÀÈ¥ ß WƐÀPÁѐÒÓÄP@ Ï YÐÜPÒIÇnñèÄHŽÆ1Ĉˆú èÆHÍUÉ©ˆÃ¨Â1ĨÆæñ‡ÜÓƨÀ1Íoõ Ä3҇Ê3Æ3ú­÷ . That completes our projectile class. This method takes a single normal parameter that represents an interval of time. ¦½ÁˆÜ ϽÁˆÜ the current position is given by the instance variables and .”q7€â s4tvuxwzy|{I}†~87Püé4{ÒêŠ 6 ŠŒ«sB± uŒˆ–ˆp{ôˆ The methods for accessing the position of our projectiles are straightforward. This new value is saved by storing it into the object in the last line of the method. We just need a couple of methods that return these values. èÆPÍ¥!ÆHÄ ‰ñ‡ÜÓƨÀ1ÍÎú¬÷ ̨ÆHÄ1ÉÌHÇ Ü£Æ¨À1͟ïp¦½ÁˆÜ èÆPÍ¥!ÆHÄ „ñ‡ÜÓƨÀ1ÍÎú¬÷ ̨ÆHÄ1ÉÌHÇ Ü£Æ¨À1͟ï–Ïg½ÁˆÜ É ˆÃ¨Â1ÄÆ ) Finally. Here’s the code: èÆPÍUÉ)ˆÃ¨Â1ÄƬñ‡ÜÓƨÀḦ́õ Ľ҇ÊÎƽú¬÷ ÜÓƨÀ1͟f ï ¦ ½ÁˆÜ ß Ü£ÆÀH͟ïp¦ˆÁ½Ü áWĽ҇ÊÎÆ YàÜÓƨÀ1͟ïf¦gWƐÀ Ï WƐÀ3Ö ßÿܣƐÀHÍnïpÏ©W¨Æ¨À£¨€Ä½Ò‡Ê3ÆSYcýnïHe ) ÜÓƨÀ1͟ïp Ï ½ÁˆÜ ß Ü£ÆÀH͟ï–g Ï ˆÁ½Ü áWĽ҇ÊΠ Æ Y ñvܣƐÀH͟ï–Ï©W¨Æ¨ÀÈá€Ï)WƐÀ3ÖPú"ŸÔ„ïðÕ ÜÓƨÀ1͟ïp) Ï WƐÀÈßW© Ï W¨Æ¨À3Ö gÐ €“ Basically. Notice the use of as a temporary (ordinary) variable. We need to update the state of the projectile to account for the passage of that much time.

~87H ¯ cé@u†y–u ½}$‚ ³ {zˆ–ˆ 6 ŠŒ§’ 6 yèt£sB± uŒˆ–ˆ ܣƨÀ1͟p ï ¦½ÁˆÜ ß Ü£ÆÀHÍnïf¦ˆÁ½Ü á€Ä3҇Ê3Æ@YÝܣƐÀH͟ïp¦)W¨Æ¨À Ï©WƐÀ3Ö ß ÜÓƨÀHÍnïpÏ)WƨÀ£¨€ýnïfe@YUĽ҇Ê3Æ Ü£Æ¨À1͟ï–Ïg½ÁˆÜ ß Ü£ÆÀHÍnïpÏgˆÁ½Ü á€Ä3҇Ê3Æ@Y¥ñ‡ÜÓƨÀHÍnïpÏ)WƨÀ ܣƨÀ1͟ Ï WƐÀÈßW© Ï W¨Æ¨À½Ö èÆHÍ¥!¨ÆHÄ „ñvܣƨÀ1ÍÎú­÷ ÌÆHÄ1ÉÌ1Ç Ü£ÆÀH͟ï–ÏgˆÁ½Ü èÆHÍ¥!¨ÆHÄ ‰ñvܣƨÀ1ÍÎú­÷ ÌÆHÄ1ÉÌ1Ç Ü£ÆÀH͟ïp¦ˆÁ½Ü ”q7€é áWÏ©WƐÀ3ÖHúVŸWÔoïùÕ €“ gРèÆHÍ¥!¨Æ1ÄQ¢IÇ)É¨ÄÎܓñ‡ú¬÷ ÂcßÿҀ© Ç PÉĉñ  ÇĨÆHÌÈÄHŽÆÝÀPÂÓÉPÇ4рÅàÂÓǧ!¨ÀPÆòñŒÒ€ÇàèÆg!P̨Ɛƽܐú¬÷ü£ú G WÝßÿҀ© Ç PÉĉñ  ÇĨÆHÌÈÄHŽÆàÒIÇ4ÒxÄ3ÒHÂPÀ`WƐÀPÁѐÒÓÄPÏ ñvÒIÇUÊÎÆ1ÄÆ1ÌÎÜŸÜ£ÆÑú¬÷ü£ú G ÅàßÿҀ© Ç PÉĉñ  ÇĨÆHÌÈÄHŽÆàÒIÇ4ÒxÄ3ÒHÂPÀYŽÆÒ !£ÅÄ ñŒÒ€ÇcÊÎÆ1ÄÆ1ÌÎܨú­÷$£ú G ÄÝßÿҀ© Ç PÉĉñ  ÇĨÆHÌÈÄHŽÆcĽ҇Ê3ÆàҀÇĨÆHÌ)WˆÂÀ ˽Æ1ÄPۈÆPÆ£ÇTˆÁ½ÜHÒÓÄ3Ò£Á£Ç Ñ1À¨Ñ€É3ÀPÂ1ĽÒ1Á£Ç4Üæ÷‰£ú G ÌÆ1ÄHÉÌ1ǡ‰f õ Wnõ–Å™õðÄ Ã¨ÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ÂÓC Ç !ÀPƉ° õ WƐÀ‰õ ňՄõ¢Ä3ÒvÊÎÆcß !ÆHÄQ¢‡Ç©PÉÄÎÜ@ñIú р˽ÀÀÈßÝØPÌÁ ƈÑxÄ3Ò1ÀPÆæñzÂÓÇC!ÀPƉõ WƨÀæõîŽսú ï ÛPÅÎÒHÀPÆÝрË3ÂPÀÀ„ïf!¨Æ1Ä ‰ñIú ( ßÝÕn÷ рË3ÂPÀÀ„ï|© É Ã£ÄÆæñèÄ3ÒvÊÎÆ3ú ̽ҀÇ Ä  ÓÇ ÎҐÜxĈÂxÇ4Ñ£ÆÈĐÌ  W¨Æ¨ÀPÆHß÷ ¨Õnï†Ö€Í Ê3ÆHÄÆ1ÌÎܬïq ©ñŒÑ€Ë3ÂPÀÀ„ïf!¨Æ1Ä æñIúú í´ g g“ " " %Ð “d™«”|µ «ªio…¨i—˜gI™qƒ¬‚„‘‘ˆ‡penšœY‡ …Θ  j iŸ‘‘ The projectile example shows how useful a class can be for modeling a realworld object that has complex behavior. salary. In a typical university. Their personnel system might make use of an G object that contains data such as the employee’s name. department. social security number. and grade point averages are calculated on a 4 point scale where an “A” is 4 . Another common use for objects is simply to group together a set of information that describes a person or thing. etc. Let’s try our hand at some simple data processing involving university students. courses are measured in terms of credit hours. a company needs to keep track of information about all of its ÊC½ÀPÁHÏ¨ÆÆ employees. address. A grouping of information of this sort is often called a record. For example.

 ţÄHÉèƣǨÄWS © ß Å1Ä1ɈÐƣÇĉñ  Ú ÃÂIʆ܆õ ¢Æ£ÇÌP# Ï 3õÖÓÔHþ„õ ÔP) Ô e3ú Using objects allows us to store all of the information about an individual in a single variable. To calculate a student’s grade point average (GPA). but it is a very common style for this sort of class. For example. ints. We can store this information as instance variables that are initialized in the constructor. credit-hours. and quality points. the contents of the file might look something like this: Ú Ã¨Â€Ê“Ü­5 õ ¢Æ£ÇÌPÏ ÖxÔPþ ÔP) Ô e אÁ€C Ê PÉÄƣۈƐÀÀ‰° õ ÅÓÉ4Ü1ÂxÇ ÖxÕPÕ d¨ÕÕ ÎÒIː˽ÀPÆ ½ÒÓÄoõ ˆÆÓÇÇ¨Ï Ö e  d4Ö­H ï9 R1ÁÓǽƈܭ˜ õ RPÒ‡Ê d©en¡ ï9 Ö 9)9 " ŀÊ@ÒÓÄ1ř° õ DP̈ÂÓ© Ç Î ÞPþ ÖÓ) Ô 9oïùÞÞ  u ½ Our job is to write a program that reads through this file to find the student with the best GPA and print out his/her name. Grade point averages are generally computed using quality points. . Now that we have a constructor. we have three pieces of information: name. Each line of the file consists of a student’s name. we can make a record for Henry Adams like this. We can Å£ÄHÉˆÃÆ£Ç¨Ä Å£ÄHÉÃ¨Æ£Ç¨Ä class. ͨÀPÁ¨Â£Ä ŽÁÓÉÌÎÜ í½ÁҀǨÄÎÜ I have also ed the values of and . or even strings. These three values are separated by a tab character.” then he or she earns 3(4) = 12 quality points. An object of type will be a record of begin by creating a information for a single student. Suppose we have a data file that contains student grade information. and quality points.”1~37 s4tvuxwzy|{I}†~87Püé4{ÒêŠ 6 ŠŒ«sB± uŒˆ–ˆp{ôˆ points. If a class is worth 3 credit hours and the student gets an “A. For example. and GPA. credits-hours. a “B” is 3 points. we divide the total quality points by the number of credit hours completed. credit-hours. This looks a bit strange at first. ÑHÀPˆÜP` Ü Å1Ä1ɈèÆÓÇğ÷ èÆHS Í Ì©ÌÒIÇ4Òx§ Ä Ì©Ì­ñ‡ÜÓƨÀḦ́õ ǽ€Ê3ƄõîňÁ£ÉÌ3Ü­ç õ í ½ÁҀÇÄ3ܨú­÷ ܣƨÀ1͟ï Ç3€Ê3ÆUßcÇ3ÂIÊÎÆ Ü£Æ¨À1͟ï ŽÁ£É¨ÌÎÜ ßWÍÀPÁÂ1ĉñðŽÁÓÉÌ3ܨú ܣƨÀ1͟p ï í½ÁҀǨÄÎܪßÐͨÀPÁÂ1Ä„Ò ñ íˆÁˆÒ€Ç¨ÄÎܐú Notice that I have used parameter names that match the instance variable names. it’s easy to create student records. etc. In this case. This makes the constructor a bit more versatile by allowing it to accept parameters that may be floats.

so we should define a set of accessor methods. Obviously. but GPA is so handy that it probably warrants its own method. Our algorithm will be similar to the one used for finding the max of n numbers. èÆH¥ Í !½Â¬ñ‡ÜÓƨÀ1ÍÎú¬÷ ÌÆ1ÄHÉÌ1Ç Ü£ÆÀHÍnf ï íˆÁˆÒIÇÄÎÜ ŸˆÜÓƨÀHÍnï|ňÁ£ÉÌ3Ü With this class in hand. to print a student’s name we could write: ̽ҀǨÄЩ  ţÄHɈÐƣǨęf ï !ÆH) Ä ÐˆÂ€Ê3Ææñ‡ú One method that we have not yet included in our class is a way of comput!ÆH) Ä ¢Á£É¨ÌÎÜ !ÆHÄ £ØÁҀÇÄ3Ü ing GPA. We could compute it separately using the and methods. èÆH¥ Í !¨Æ1© Ä ÐˆÂIÊÎƬñ‡Ü£ÆÀHÍ3ú¬÷ ÌÆ1ÄHÉÌ1Ç Ü£ÆÀHÍnï|Ç3ÂIÊÎÆ Ã¨ÆHÍ¥!¨Æ1Ä)¢ˆÁÓÉÌ3ܓñ‡ÜÓƨÀ1ÍÎú¬÷ ÌÆ1ÄHÉÌ1Ç Ü£ÆÀHÍnï|ŽÁÓÉÌ3Ü Ã¨ÆHÍ¥!¨Æ1Ä 1بÁˆÒIÇÄÎÜ@ñ‡ÜÓƨÀHÍ3ú¬÷ ÌÆ1ÄHÉÌ1Ç Ü£ÆÀHÍnïfíˆÁˆÒIÇÄÎÜ é These methods allow us to get information back out of a student record. Here’s the algorithm for our program: ü Æ1ÄWÄHňƀͽÒHÀHÆ Ç3ÂIÊÎƀÍHÌÁxÊ¡Ä1ŽÆÈÉ4Ü£ÆHÌ Ä ˆÆ£ÇÐÄ1ŽƀͽÒ1ÀPÆc͐ÁHÌW̨ƨÂHÈҀC Ç ! ÅPÆ1Äc˽ƈÜxÄWÄÁÈˈÆcÄHňƀͽÒÓÌ3ÜxÄÿ܀ÄHÉÃ¨Æ£Ç¨Ä DÁ1ÌÐƨ¨рŻÜxÄ1ɈÐƣÇÄàÜWҀÇÐÄHňƀͽÒ1ÀPÆ Ò£Íÿܬf ï !½Â¬ñ‡ú ( ˽ƈÜxęp ï !½Â Ü£ÆHÄcˈƽ܀ĀÄÁÿÜ ̽ҀǨÄÝÁ£É¨ÄÿҀLj͐ÁHÌÓÊ4Â1ĽÒ1ÁÓÇàÂÓˈÁ£É¨ÄU˽ƈÜxÄ The completed program looks like this: ó¥!½ÂoïbÏ ó ØPÌ) Á !ḦÂIÊÐÄÁW͈ҀLjÃàÜxÄHÉèÆÓÇÄcÛ3ÒÓÄHÅWÅÎÒ £ ! Å½Æ½Ü€Ä é ü Ø Ú . we are ready to attack the problem of finding the best student.~87H ¯ cé@u†y–u ½}$‚ ³ {zˆ–ˆ 6 ŠŒ§’ 6 yèt£sB± uŒˆ–ˆ ”1~€~ Next we must decide what methods a student object should have. For example. We’ll look through the file of students one by one keeping track of the best student seen so far. we would like to be able to access the student’s information.


ǨÄÆ1ÌUÇ3ÂIÊÎÆcÄHňÆT!PÌÂHèÆUͽÒHÀHÆn÷Ü€ÄHɈÐƣǨÄÎÜæïpÃ壀 G HňÆÈ˽ƈÜxÄ ÜxÄ1ɈÐƣÇÄÐҨܬ÷¢×Áxc Ê É¨ÄÆ1ÛƨÀPÀ‰Æ õ ÅxÉ@Ü£ÂÓÇ Å½ÁÓÉÌ3Üæ÷ րՐÕnïùÕ ü Ø Ú ° ÷ dnïðÕ “d™«”|º Ê£}ȑ×ÈƒÊ x€y31‚„ƒ†…‘Wi„e™· šdwQœ©–BÍQs r•ÙŒ–mtql™wm• e¼ e e™ƒ­i„¤™‘Φ•j i„…ˆ‡™£e 1sqiV98r•Ù Ú ¾ %sqt"“f–%œ)tqlnvxw%s ؐÌÁ ÆÑÓÄ3Ò1ÀPÆ Å1Ä1ɈÐƣÇÄ Hopefully. Ü ßÈÊ4"  Έ© Æ Å1ÄHÉèÆÓÇĄñzÀÒIǽÆ3ú Here’s how it looks running the program on the sample data. you are seeing how defining new classes like ï and can be a good way to modularize a program. this function is used to create a record for the first student in the file: ˽ƈÜxÄÝß Ê4"  Έ© Æ Å1ÄHÉèÆÓÇĄñŒÒ€ÇͽÒHÀHÆnï–ÌƨÂ1ÃÀÒ€ÇˆÆæñvúú It is called again inside the loop to process each subsequent line of the file. This function takes a single line of the file.~87P ´P Ñ  Ê { ³ y|ˆ„uxŠv‹   Š ³ uxwŒˆ–…± u†y 6 ‚1Š ”1~†” Ü ßUÊΠÎc Æ Å1Ä1ɈÐƣÇĉñ†À¨Ò€Ç½Æ½ú ó¡Ò£Í€ÄHÅÎÒ¨ÜW܀ÄHÉˆÃÆ£Ç¨Ä¡Ò¨Ü ËˆÆ½ÜxÄ Ò£ÍÿÜæp ï !½Â¬ñIú ( ˽ƽ܀ęp ï !3­ñIú­÷ ˈƽ܀ÄWß Ü Ò€ÇͽÒHÀHÆnï–ÑHÀPÁˆÜ£Æ¬ñIú ÜÓÁ€Í£Ìnõ¢ÌƀÊÎƀÊ˽Æ1ÌàÒxęï ó£̽ҀÇÄÿÒILj͐ÁHÌ£ÊÎÂ1ĽÒ1Á£ÇÝÂÓˈÁ£É¨ÄWÄHŽÆÈˈƽ܀ÄÿÜxÄ1ɈèÆÓÇÄ ÜxÄ1ɈÐƣÇÄÐҨܬq ÷ Îõ ˈƽ܀ęf ï !ÆH) Ä ÐˆÂ€Ê3Ææñ‡ú ̽ҀÇ Ä zŽÁÓÉÌ3Üæq ÷ 3õî˽ƈÜxğf ï !¨Æ1) Ä ¢Á£ÉÌ3ܓñ‡ú ̽ҀÇ Ä  ü Ø Ú u ÷ ÎõîˈƽÜxğf ï ! 3¬ñ‡ú ̽ҀÇÄXHňÆÈ˽ƈÜxÄ Ò£ÍSÌ)ÌÓǽ€ÊÎÆ©Ì©ÌUßPß Ê4¨ҀÇnñ‡ú | ëÌ)̀Ê4¨ҀÇmÌ©Ì f ¨÷ Ê4"  Έ© Æ Å1ÄHÉèÆÓÇÄ You will notice that I added a helper function called . Once we identify some useful objects. Right before the loop. splits it into its three tab-separated fields. Å£ÄHÉÃ¨Æ£Ç¨Ä and returns a corresponding object. This gives us the same kind of . we can write an algorithm using those objects and push the implementation details into a suitable class definition.

respectively. that sim¦ˆÁ½Ü Ï ˆÁ½Ü g and . Our ply returned the values of instance variables Å1Ä1ɈÐƣÇÄ class has similar accessor methods for its instance variables.”1~ ¯ s4tvuxwzy|{I}†~87Püé4{ÒêŠ 6 ŠŒ«sB± uŒˆ–ˆp{ôˆ separation of concerns that we had using functions in top-down design. not about how they are implemented. The implementation details of an object are encapsulated in the class definition. For example. In Python. This is another application of abstraction (ignoring irrelevant details). and . I should mention that encapsulation is only a programming convention in Python. References to instance variables should remain inside the class definition with the rest of the implementation details. the rest of the program can’t even tell that a class has changed. these methods are not absolutely necessary. For completeness. As you begin to . One of the main reasons for using objects is to hide the internal complexities of those objects from the programs that use them. In our ̨ؐÁ ƈÑÓĽÒHÀHÆ !¨Æ1Ä !¨Æ1Ä ï class we included two short methods. ØPÌÁ ƈÑxÄ3ÒHÀHÆ ï we could test the constructor for the class interactively by creating an object and then directly inspecting the values of the instance variables. but it is generally considered poor practice to do this in programs. From outside the class. The main program only has to worry about what objects can do. Computer scientists call this separation of concerns encapsulation. per se. you can access the instance variables of any object with the regular dot notation. which insulates the rest of the program from having to deal with them. which is the essence of good design. all interaction with an object can be done using the interface provided by its methods. As long as the interface provided by the methods stays the same. It is not enforced by the language. %Ð g“ (©()( ÕnïùÕ ÔPÕ (©()( (©()( (©()( (©()( ÑÈßWؐÌÁ щp ï ¦½ÁˆÜ ï ÆÑÓÄ3Ò1ÀPƬñzøÕ‰õç9HՄõ ÔHÕ3ú щï–Ïg½ÁˆÜ щïp¦)WƐÀ Ñ ï–Ï©WƐÀ ‰ d¨ÞoïðÞPÕÎÖÓÔHþÕ Ô©9„ïðÕ Accessing the instance variables of an object is very handy for testing purposes. Strictly speaking. One immediate advantage to this approach is that it allows us to modify and improve classes independently without worrying about “breaking” other parts of the program.

Most of the Python library modules have extensive docstrings that you can use to get help on using the module or its contents. Ê£}ȑ×È‘Ç ’”rmtžtql™w%• ¡ª gٌ–mssqi§sçl™w ¶ 6› v xr•ÙŒi§s Often a well-defined class or set of classes provides useful abstractions that can be leveraged in many different programs. In fact. For example. it would be a good idea to add documentation that describes how the class can be used so that programmers who want to use the module don’t have to study the code to figure out (or remember) what the class and its methods do. You could get the same information using interactive help like this: Ê ½ÁHÌPĀ̈ÂxLjÐÁxÊ (©()( ҇c ½ ŠƐ" À nñè̈ÂxLjèÁ€Ê§ï–̈ÂÓÇèÁ€Ê­ú (©()( ¢ˆÆ" À ¡ÁÓÇWːÉ4Ò1À1C Ä ¨ҀÇWÍ1ÉPÇ4ÑÓĽÒ1ÁÓÇÝ̈ÂxLjèÁ€Ê§÷ . namely comments. Ê£}ȑ×È‘É ¶ £› žœ v xrBٌi vœ§r6—îi•wmtu–mtqlnvxw You are already familiar with one way of documenting programs. You can insert a plain string literal as the first line of a module. if you can’t ÌÂÓLjÐÁxÊ remember how to use the function. It’s always a good idea to provide comments explaining the contents of a module and its uses. you can print its docstring directly like this: Ê ½ÁHÌPĀ̈ÂxLjÐÁxÊ (©()( ҇c ï Ì)ÌHèÁg Ñ Ì)Ì (©()( ̽ҀÇÄc̈ÂÓÇèÁ€Ê§ïpÌÂÓÇèÁxʕ¡ ̈ÂxLjÐÁxʙñ‡V ú ¨ ( ¦¡ÒIÇÐÄHňÆàҀÇĨÆH) Ì WˆÂÀ û ՄõªÖHú¬ï Docstrings are also used by the Python online help system and by a utility called PyDoc that automatically builds documentation for Python modules. docstrings are actually carried ÐÁˆÑ along during execution in a special attribute called . comments of this sort are so important that Python incorporates a special kind of commenting convention called a docstring.~87P ´P Ñ  Ê { ³ y|ˆ„uxŠv‹   Š ³ uxwŒˆ–…± u†y 6 ‚1Š ”1~†´ design classes of your own. while ordinary comments are simply ignored by Python. These strings can be examined dynamically. we might want to turn our projectile class into its own module file so that it can be used in other programs. you should strive to provide each with a complete set of methods to make it useful. class or function to document that component. For example. The advantage of docstrings is that. In doing so.

try typing . ØPÌÁ ƈÑxÄ3Ò1ÀPÆ ï Here is a version of our class as a module file with docstrings included: ó£̨Á ï ƈÑÓĽÒHÀHÆnïU¨Ï ï Æ ÑxÄ3ÒHÀHÆnïbÏ ˆ ̨ؐÁgW½Ò£Ã¨ÆˆÜÈÂàÜPÒvÊC½ÀPÆÐÑ1ÀÂˆÜPÜYͨÁ1ÌÈÊÎÁHèƨÀ¨Ò€ÇC!cÄHÅˆÆ ÍÀ¨Ò !£ÅÄÝÁH£ Í ÌÁ ÆÑÓÄ3Ò1ÀPƈÜæq ï )© ï ©)8¨ÌÁ ÍP̨ÁxÊWÊÎÂ1ÄHÅÿ҇ÊCˆÁHÌPÄ£4Ò­õÜPҀǟõ Ñ1ÁˆÜ ÑHÀPˆÜPÜ ØÌ¨Á ï ÆÑÓĽÒHÀPÆo÷ Ü ÒvÊC½ÀPÆV¨ÌÁ ƈÑxÄ3ÒHÀHÆ½Ü ½ P Ç ÆÂ1ÌWÄHňÆWƨ£̐ÄHÅ ŒÜ ï ÜIɨ̨ͨÑ1Ɖõ Ò !£Ç½Á1Ì3ҀÇC!UÛÎÒILjĄ̀ƽÜPҐÜxÄÂÓÇ4Ñ£Ænï ÌÂÑÎ3ҀÇC!àÒ¨Ü  à Á£Ç½ÆàÒIÇÐÄPÛÁ ýÒvÊÎÆ£Ç4ÜPÒ£Á£Ç@܆õ ÅˆÆˆÒ !£ÅÄ ñèÏ4úÈÂxLjÃWýҐÜxÄÂÓÇ4Ñ£Æ Ò ñ ¦Îú¬u ï ©) èÆHÍSÌ©ÌÒIÇ4Òxħ̩̭ñ‡ÜÓƨÀḦ́õ¢Âxǧ!¨ÀPƄõ5WƨÀHÁˆÑPÒÓĐÏoõ ÅˆÆˆÒ !£ÅÄÎú¬÷ ©©v×H̨ƨÂ1Ĩƀ`  ̨Á ƈÑÓĽÒHÀHÆ ÛÎÒxÄHS Å !ˆ" Ò W¨Æ£ÇÿÀÂxɐÇÎрšÂxǧ!ÀHƄõÒIÇ4ÒxÄ3ÒHÂPÀ ï WƨÀHÁˆÑPÒÓĐÏWÂÓÇÃUŽƈ" Ò !1Ũęq ï )© ܣƨÀ1͟p ï ¦½ÁˆÜ ßÐÕnïùÕ Ü£Æ¨À1͟ï–g Ï ½ÁˆÜ ßcŽÆÒ !£ÅÄ ÄHŽÆ1ĈÂUE ß Î¥ Ò YcÂÓ§ Ç !¨ÀP  Æ Ÿÿ Ö eÕnïùÕ Ü£Æ¨À1͟p ï ¦)WƐÀÈ¥ ß WƐÀPÁѐÒÓÄP@ Ï YÝÑ1ÁˆÜ“ñèÄHŽÆ1Ĉˆú ܣƨÀ1͟ Ï WƐÀÈ¥ ß WƐÀPÁѐÒÓÄP@ Ï YÐÜPÒIÇnñèÄHŽÆ1Ĉˆú èÆHÍUÉ©ˆÃ¨Â1ĨÆæñ‡ÜÓƨÀ1Íoõ Ä3҇Ê3Æ3ú­÷ ©©ô© Ù ÃÂ1ĨÆÈÄ1ŽơÜxÄÂ1ĨƀÁPÍWÄHÅÎÒ¨Ü$¨ÌÁ ƈÑxÄ3Ò1ÀPÆÈĨÁYÊÎÁWÆàÒÓÄWĽ҇Ê3ơܣƈѣÁ£ÇÃ3Ü ï ÍÂ1ÌPÄHňÆHÌ¡ÒIÇÄÁÝÒÓÄÎÜ Í¨À" Ò !1Å6 Ä ©) ܣƨÀ1͟p ï ¦½ÁˆÜ ß Ü£ÆÀHÍnf ï ¦ˆÁ½Ü á€Ä3҇Ê3@ Æ YÝܣƐÀH͟ïp¦)W¨Æ¨À Ï WƐÀ3Ö ß ÜÓƨÀHÍnïp) © Ï Wƨ£ À ¨€ýnf ï e@YUĽ҇Ê3Æ Ü£Æ¨À1͟ï–g Ï ½ÁˆÜ ß Ü£ÆÀHÍnïpg Ï ˆÁ½Ü á€Ä3҇Ê3@ Æ Y¥ñ‡ÜÓƨÀHÍnïp) Ï WƨÀ áW© Ï WƐÀ3ÖHV ú ŸWÔoïùÕ Ü£Æ¨À1͟ Ï WƐÀÈßW© Ï W¨Æ¨À½Ö ©)qÅÒvÊɽÀÂ1ĨƽÜfÄHňƀÍÀÒ"!1ŨÄÝÁPÍ  .”1~†¹ s4tvuxwzy|{I}†~87Püé4{ÒêŠ 6 ŠŒ«sB± uŒˆ–ˆp{ôˆ ̈ÂxLjÐÁxʙñˆïïPï†ú ̈ÂxLjèÁ€Ê™ñ‡úè¨ ( ¦¡ÒIÇÐÄHŽÆàÒIÇĨÆHÌ©WÀ û ՄõªÖHú¬ï If you want to see a whole bunch of information about the entire random modŽƐÀ"nñè̈ÂxLjèÁ€Ê­ú ule.

Here is an example of how the docstrings appear when they are printed: Ä ÌÁ ÆÑÓÄ3Ò1ÀPÆoïp̨ؐÁ ƈÑÓĽÒHÀHÆn¡ ï Ì)ÌHÃPÁˆ Ñ Ì©Ì (©()( ̽ҀÇ` ï ï ÅÒvÊɽÀÂ1ĨƽܪÄHŽƀͨÀ" Ò !1ÅÄWÁPÍÿÜPÒvC Ê ½ÀP` Æ ̨Á ƈÑÓĽÒHÀHÆ½Ü Ç½Æ¨Â£ÌWÄHňÆWƨÂ1ÌPÄHÅ ŒÜ ï ÜIɨ̨ͨÑ1Ɖõ Ò !£Ç½Á1Ì3ҀC Ç !UÛÎÒILjĄ̀ƽÜPҐÜxÄÂÓÇ4Ñ£Ænï ÌÂ Ñ Î3ҀC Ç !àÒ¨Ü ÃÁ£Ç½ÆàÒIÇÐÄPÛÁ ýÒvÊÎÆ£Ç4ÜPÒ£Á£Ç@܆õ ÅˆÆˆÒ !£ÅÄ ñèÏ4úÈÂxLjÃWýҐÜxÄÂÓÇ4Ñ£Æ Ò ñ ¦Îú¬ï  ŽƐÀ"oñH̨Á You might try for this module. ó¡Ñ€Ë½ÂÀPg À dŸb ï Ï ÍP̨ÁxS Ê ¨ÌÁ ƈÑxÄ3ÒHÀHÆÝÒvC Ê ½Á1̐ĀØPÌÁ ƈÑxÄ3Ò1ÀPÆ ï ï ÆÑÓĽÒHÀPÆ module in order èÆHÍ¥!¨Æ1ÄQ¢IÇ)É¨ÄÎܓñ‡ú¬÷ ÂcßÿҀ© Ç PÉĉñ  ÇĨÆHÌÈÄHŽÆÝÀPÂÓÉPÇ4рÅàÂÓǧ!¨ÀPÆòñŒÒ€ÇàèÆg!P̨Ɛƽܐú¬÷ü£ú G WÝßÿҀ© Ç PÉĉñ  ÇĨÆHÌÈÄHŽÆàÒIÇ4ÒxÄ3ÒHÂPÀ`WƐÀPÁѐÒÓÄPÏ ñvÒIÇUÊÎÆ1ÄÆ1ÌÎÜŸÜ£ÆÑú¬÷ü£ú G ÅàßÿҀ© Ç PÉĉñ  ÇĨÆHÌÈÄHŽÆàÒIÇ4ÒxÄ3ÒHÂPÀYŽÆÒ !£ÅÄ ñŒÒ€ÇcÊÎÆ1ÄÆ1ÌÎܨú­÷$£ú G ÄÝßÿҀ© Ç PÉĉñ  ÇĨÆHÌÈÄHŽÆcĽ҇Ê3ÆàҀÇĨÆHÌ)WˆÂÀ ˽Æ1ÄPۈÆPÆ£ÇTˆÁ½ÜHÒÓÄ3Ò£Á£Ç Ñ1À¨Ñ€É3ÀPÂ1ĽÒ1Á£Ç4Üæ÷‰£ú G ÌÆ1ÄHÉÌ1ǡ‰f õ Wnõ–Å™õðÄ Ã¨ÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ÂÓC Ç !ÀPƉ° õ WƐÀ‰õ ˆ ŠՄõ¢Ä3ÒvÊÎÆcß !ÆHÄQ¢‡Ç©PÉÄÎÜ@ñIú р˽ÀÀÈßÝØPÌÁ ˆ Æ ÑxÄ3Ò1ÀPÆæñzÂÓÇC!ÀPƉõ WƨÀæõîŽսú ï . Triple quoting allows us to directly type multi-line strings. ï Ê£}ȑ×È ÆˆÑÓĽÒHÀHÆ3ú to see how the complete documentation looks ™ ¢âv'“ rý Cl™wm•Vo lŒt )  ¶ r•Ùˆtql™Í•ÙŒi ¶ £› v r•ÙŒi§s ̨Á ï Our main program can now simply import from the to solve the original problem.~87P ´P Ñ  Ê { ³ y|ˆ„uxŠv‹   Š ³ uxwŒˆ–…± u†y 6 ‚1Š ”1~†¿ èÆHÍ¥!¨ÆHÄ „ñvܣƨÀ1ÍÎú­÷ 3 ˆÆ1ÄHɨÌHÇ@ܪÄHňÆcÏ¥ˆÁ½ÜHÒÓÄ3Ò£Á£Ç ÌÆHÄ1ÉÌ1Ç Ü£ÆÀH͟ï–g Ï ˆÁ½Ü èÆHÍ¥!¨ÆHÄ ‰ñvܣƨÀ1ÍÎú­÷ 3 ˆÆ1ÄHɨÌHÇ@ܪÄHňÆT¦TˆÁ½ÜHÒÓÄ3Ò£Á£Ç ÌÆHÄ1ÉÌ1Ç Ü£ÆÀH͟p ï ¦ˆÁ½Ü €“ ñðŽÆÒ £ ! ÅÄ4ú ÁP̀ÄHÅÎҨܨÌÁ ï ƈÑxÄ3ÒHÀHÆnïu gÐ ñôýҐÜxÄÂÓÇ4Ñ£Æ3ú ÁP̀ÄHÅÎҨܨÌÁ ï ƈÑxÄ3ÒHÀHÆnïu You might notice that many of the docstrings in this code are enclosed in triple quotes (”””). This is a third way that Python allows string literals to be delimited.

executing . they just create additional references to the existing module object. details of projectile motion are now hidden in the projectile module file. In fact. you need to be aware of a subtlety in the Python module importing mechanism. but still refers to the class definition from ï ÊÎÂÒ€Ç the old module object. which is confusing to say the least. If a module imports successfully (it has no syntax errors). The G object defined in our library is one example of a widget. it creates a module object that contains all of the things defined in the module (technically. we can create our own custom widgets. That’s because ing a module doesn’t change the values of any identifiers in the current session that already refer to objects from the old version of the module. Hence. The simplest way to avoid this confusion is to make sure you start a new interactive session for testing each time any of the modules involved in your tests is modified. it’s pretty easy to create a situation where objects from both the old and new version of a module are active at the same time.”1~†â s4tvuxwzy|{I}†~87Püé4{ÒêŠ 6 ŠŒ«sB± uŒˆ–ˆp{ôˆ ÛPÅÎÒHÀPÆÝрË3ÂPÀÀ„ïf!¨Æ1Ä ‰ñIú ( ßÝÕn÷ рË3ÂPÀÀ„ï|© É Ã£ÄÆæñèÄ3ÒvÊÎÆ3ú ̽ҀÇ Ä  ÓÇ ÎҐÜxĈÂxÇ4Ñ£ÆÈĐÌ  W¨Æ¨ÀPÆHß÷ ¨Õnï†Ö€Í í´ g g“ " Ê3ÆHÄÆ1ÌÎܬïq ©ñŒÑ€Ë3ÂPÀÀ„ïf!¨Æ1Ä æñIúú " %Ð In this version. It is possible to interactively replace a module object using the built-in funcÌƨÀHÁ¨Â1Éñ Ê3ÁPÃ1ɽÀPÆ ú Ó 0 (consult the Python documentation for details). When Python first imports a given module. we talked about GUIs being composed of visual inÇĐÌPÏ !PÌÂ"ÅÎÒÑÜ terface objects called widgets. In the context of р˽À À d ÌƨÀHÁ¨Â1ÉH ñ ¨ÌÁ ƈÑxÄ3Ò1ÀPÆ3ú ¨ÌÁ ƈÑxÄ3Ò1ÀPÆ ï ï the code. causes to refer ØPÌÁ ƈÑxÄ3ÒHÀHÆ to a new module object. But tion ÌƐÀPÁÂHà often this won’t give you the results you want. Back in Chapter 5. “d™«”–ê ž ‡·„š•‚‰…¨‘ One very common use of objects is in the design of graphical user interfaces (GUIs). If you are testing multi-module Python projects interactively (a good thing to do). . That way you are guaranteed to get a fresh (updated) import of all the modules that you are using. Even if a module has been changed (its source ÒvC Ê ˆÁHÌÄ ing it into an ongoing interactive session will not get you file edited) rean updated version. the behavior of will not be affected by the ÌƐÀPÁÂHà . this is called a namespace). Now that we know how to define new classes. subsequent imports do not reload the module.

The best we can do is find out . usually having a 3-dimensional look and feel. Figure . one for rolling 10 ! the dice and one for quitting the program. and the class that provides a graphical view of the value of a 3Ò1ÆÛ3Ò1Æ£Û die will be . Modern buttons are very sophisticated. We can start by developing suitable classes. : Snapshot of dice roller in action. consider a program that rolls a pair of standard (six-sided) dice. The program will display the dice graphically and provide two buttons. Our simple graphics package does not have the machinery to produce buttons that appear to depress as they are clicked. of course. shows a snapshot of the user interface. Figure 10 ! .  Ê£}È È‘Ç Sµ  ² › ² rQl‘Ù 'l™wm• rmtžtuvxw%s Buttons. You can see that this program has two kinds of widgets: buttons and dice. As an example application.Ê£}È ÈƒÊ Sµ š#›§–B—$ٌ͕i£’”“Hv••“f–'— »¨ œ ~87P ¹P¯ 6 ‹€I{ôy|ˆ ¦l‡œ)iThjv6هٌi•“ ”1~†é Let’s try our hand at building a couple of useful widgets. The two buttons will be instances HɨĐÄÁÓÇ of a class. are standard elements of virtually every GUI these days.

our buttons will need a number of instance variables. Typically. getLabel Returns the label string of the button. Our buttons will be rectangular regions in a graphics window where user clicks can influence the behavior of the running application. if less pretty. deactivate Set the state of the button to inactive. This is provided so that we can identify a particular button. clicked Indicate if the button was clicked. For example. Once we have identified the relevant variables. We might start by implementing the various methods to see what other instance variables might be needed. We will need to create buttons and determine when they have been clicked. and the label that will be on the button. Here is the code ÜÓƨÀ1Í (remember the parameter refers to the button object): èÆHÍÐÂÑÓĽ" Ò WÂ1ÄƬñ‡ÜÓƨÀHÍ3ú¬÷ qÅPÆ1ÄÎÜ Ä1Å4ÒÜ ËÉÄPÄÁÓÇÝÄÁ –ÂÑÓĽ" Ò W¨Æ u ï  ܣƨÀ1͟ïðÀÂÓˈƨÀ„ïzÜ£Æ1© Ä D½ÒHÀÀ­ñ –Ë3ÀÂ¨ Ñ Î vú —  }    . Nevertheless. we can write a constructor that initializes these values. button class. We will have to specify the window in which the button will be displayed. the button itself will be drawn as a rectangle with ÂÑxÄ3ÒWˆÂ1Ä¨Æ Ã¨ÆÂÑÓĽÒ"WÂ1ÄÆ and methods will some text centered in it. We can signal that the button is active Let’s start with the by making the outline thicker and making the label text black. it is also nice to be able to activate and deactivate individual buttons.”Ir7 s4tvuxwzy|{I}†~87Püé4{ÒêŠ 6 ŠŒ«sB± uŒˆ–ˆp{ôˆ where the mouse was clicked after the click has already completed. our buttons will support the following methods: constructor Create a button in a window. an inactive button is grayed-out to show that it is not available. Saving the and objects as instance variables will allow us to change the width of the outline and the color of the label. Summarizing this description. activate Set the state of the button to active. If the button is active. this method will determine if the point clicked is inside the button region. ¨ÑÓĽ" Ò WˆÂ£ÄÆ method. In addition. Invoking the  ˆÆˆÑxĈÂxǧ!ÀHÆ Æg¦PÄ change the appearance of the button. The point will have to be sent as a parameter to the method. In order to support these operations. our applications can signal which options are available to the user at any given moment. the location/size of the button. we can make a useful. That way.

we Ñ1ÀÒP Ñ ÎˆÆHà can implement the method with a single Boolean expression. the instance variable stores a Boolean value to remember whether or not the button is currently active. . our constructor will ܣƐÀH͟ïðÀÂx˽ƨÀ Æ)¦HÄ Ü£ÆÀH͟ï–ÌÆÑÓÄ have to initialize as an appropriate object and as  ˆÆˆÑxĈÂxǧ!ÀHÆ ÜÓƨÀHÍnïè¨ÑÓÄ3ÒWÆ a object. the main point of a button is being able to determine if it has Ñ1ÀÒPÑΈÆHà !PÌÂ"ÅÎÒÑÜ been clicked. In addition. As you know. . èƨ¨ÑÓĽ" Ò WˆÂ£ÄÆ ÂÑxÄ3" Ò WÂ1Ä¨Æ Our method will do the inverse of . it will first have to call !¨Æ1ÄPöÁ£É@ÜÓÆ and then see which active button (if any) the point is inside of. èÆHÍ¡ÑHÀÒP Ñ ÎÆPÉñvܣƐÀHÍoõ “ú­÷ 3 ˆÆ1ÄHɨÌHÇ@ܪĐÌ1ɽÆàÒ£ÍUËPÉÄPÄÁ£ÇÿÒ¨ÜUÂÑxÄ3 Ò WÆÝÂÓÇ` à »Ò¨Ü€ÒIÇ@ÜPÒÓèB Æ  – – – . and . ¦ÓÊ@Ò€Ç ¦xÊ4g  ¦ ÏÓÊ“Ò€Ç Ï£ÊÎg  ¦ Assuming the existence of instance variables . It looks like this: èÆHÍWèƨ¨ÑÓĽ" Ò WˆÂ£ÄƬñ‡Ü£ÆÀHÍ3ú¬÷ qÅPÆ1ÄÎÜ Ä1Å4ÒÜ ËÉÄPÄÁÓÇÝÄÁ zҀÇ3¨ÑÓĽ" Ò WÆ u ï  ܣƨÀ1͟ïðÀÂÓˈƨÀ„ïzÜ£Æ1© Ä D½ÒHÀÀ­ñ ðÃÂ1g Ì Îc!HÌÆ£Ï Œú ܣƨÀ1͟ï–ÌƈÑxęïôÜ£ÆHg Ä 4ÎÒÓÃPÄHÅoñ€ÖHú ܣƨÀ1͟ïðÂÑÓĽ" Ò W¨ÆUT ß DˆÂPÀˆÜÓÆ —   f   Of course. We could imagine the button processing code looking something like the following: ÄÝ߀Û3ҀDŽp ï !¨Æ1ÄPöˆÁÓÉ@ÜÓÆæñIú Ò£ÍUËPÉÄPÄÁ£Ç“Ö­ï–ÑHÀÒP Ñ ÎÆPÉf ñ ÄÎú¬÷ ó ˆÁUːɨĐĨÁ£Ç†Ö ÜxÄ1ÉˆÍÍ Æ¨À¨Ò£ÍUËPÉĐĨÁ£Ç½ÔoïôÑ1ÀÒP Ñ ÎˆÆHÉf ñ Ä4ú­÷ ó ˆÁUːɨĐĨÁ£Ç3ÔWÜxÄ1ÉˆÍÍ Æ¨À¨Ò£ÍUËPÉĐĨÁ£Ç½ÔoïôÑ1ÀÒP Ñ ÎˆÆHÉf ñ Ä4ú ó ˆÁUːɨĐĨÁ£Ç½ÞÝÜxÄ1ÉˆÍÍ ïïPï ž ž ž ÑHÀÒP Ñ ÎÆPà The main job of the method is to determine whether a given point is inside the rectangular button. The point is inside the rectangle if its “ and coordinates lie between the extreme “ and values of the rectangle. Let’s try to write the method. the !ÆHÄHöˆÁ£É4Ü£Æ package provides a method that returns the point where the mouse was clicked. in order for this code to work. If an application needs to get a button click.~87P ¹P¯ 6 ‹€I{ôy|ˆ ܣƨÀ1͟ï–ÌƈÑxęïôÜ£ÆHÄg4ÎÒÓÃPÄHÅoñ†Ôˆú ܣƨÀ1͟ïðÂÑÓĽ" Ò W¨ÆUT ß Ì1É½Æ ”IrH~ As I mentioned above. This would be easiest to figure out if we just assume that the button object has instance variables that record the min and max values of “ and .

If is false. but it is a bit tedious. we just need a constructor to get all the instance variables properly initialized. It’s not hard. then will return false. The first of the three subexpressions simply retrieves the value of the inÜÓƨÀ1͟ïè¨ÑÓĽ" Ò WÆ stance variable . The second two subexpressions are compound conditions to check that the “ and values of the point fall between the edges of the button rectan¦ ß€Ï ß F means the same as the mathematical expression gle. “ y y‡½ (section Now that we have the basic operations of the button ironed out. F '3 %3 )). all three must be true for the function to return a true value.”Ir€r ÌÆHÄ1ÉÌ1Ç s4tvuxwzy|{I}†~87Püé4{ÒêŠ 6 ŠŒ«sB± uŒˆ–ˆp{ôˆ ܣƐÀH͟ïðÂÑxÄ3Ò"W¨Æ€ÂxLjà ܣƐÀH͟p ï ¦ÓÊ@Ò€Ç ß „ïp!¨ÆHÄ ‰ñ‡ú £ F ܣƐÀH͟ï–Ï£Ê@Ò€Ç ß „p £ ï !¨ÆHÄ „‡ ñ ú F F F ´ gÐ €“ ßÿÜÓƨÀHÍnïf¦xÊ4Âg¦€ÂÓÇà ßÿÜÓƨÀHÍnïpÏÓÊ4g  ¦ ´ ÂÓÇà Here we have a single large Boolean expression composed by ing together three simpler expressions. (Remember. This ensures that only active buttons will report ܣƐÀH͟ïðÂÑxÄ3" Ò W¨Æ Ñ1ÀҐ Ñ ÎˆÆHà that they have been clicked. Recall that the backslash at the end of a line is used to extend a statement over multiple lines. Here is the complete class with a suitable constructor: – – ¡h óUːɨĐĨÁ£Ç„ïbÏ ÍP̨Áxa Ê !Ḧ"  PÅ4ÒPѨÜUÒvÊCˆÁH̐Ä@Y ÑHÀPˆÜPÜ HɨĐÄÁÓDŽ÷ Ú ËÉ¨ÄÄ¨Á£Ç ҐÜUÂWÀÂÓˈƨÀHÆPÃc̨ƈÑÓÄÂÓÇC!ÀPÆWÒ€Ç ÂÈÛÎÒILjÐÁ1Ûhï ¢xÄÿҐÜUÂÑÓĽÒ"WÂ1ÄÆHÃWÁHÌÝÐƨ¨ÑÓÄ3ÒWˆÂ£ÄÆPÃYÛÎÒxÄHÅÐÄ1ŽÆÝÂÑxÄ3ÒWˆÂ1ĨÆæñ‡ú ÂÓÇÃWèƨ¨ÑÓĽ" Ò WˆÂ£ÄƬñIú ÊÎÆHÄ1ŽÁHÃ3Üæï HŽÆàÑ1ÀÒP Ñ ÎˆÆHÉf ñ “úÊ3ÆHÄ1ŽÁPà ÌÆ1ÄHÉÌ1Ç@Ü ÄPÌHɈÆÐÒ£ÍWÄHÅˆÆ ËÉ¨ÄÄ¨Á£Ç Ò¨ÜU¨ÑÓĽ" Ò WƀÂÓLj£ à  Ґ܀ҀÇ4ÜPңÐÆÐÒÓğïq)© ©)  èÆHÍSÌ©ÌÒIÇ4Òxħ̩̭ñ‡ÜÓƨÀḦ́õ Û3ҀǟõÑ1ÆÓÇÄÆ1Ìnõ Û3Ò£ÃHÄHřõ ŽƈÒ"!1ŨÄnõ ÀPÂÓ˽ƐÀ½ú­÷ ©©ª×1ÌƐÂ1ÄƈÜÈÂUÌÆÑÓÄÂÓǧ!£É3ÀPÂ1ÌÈËPÉÄPÄÁ£ÇŸõ˜Æ)!n÷ í1Ëàß HɨĐĨÁ£Çnñ–ʽg Ï 4ÎҀǟõ ѣƣÇĨÆHÌPØÁˆÒIÇÄoõ Û3Ò£ÃPÄ1řõîňƈÒ"!1ÅÄoõ xÉ4ÒxÄ vúS©© # #Q  ۟õpÅàßcÛ3Ò£ÃHÄHÅ%ŸPÔoïùՄõ ňƈÒ"!1ÅÄCŸÔ„ïðÕ ¦oõðÏÝߡѣƣǨÄÆH̟f ï !ÆHÄ æñIú“õ ѣƣÇĨÆH̟ïf!¨Æ1Ä ‰ñIú ܣƨÀ1͟p ï ¦ÓÊ4  ¦oõ ܣƨÀ1͟ïp¦ÓʓÒIÇÝß ¦á1۟õç¦c¨£Û ܣƨÀ1͟ï–Ï£Ê4  ¦oõ ܣƨÀ1͟ï–ϣʓÒIÇÝßWϨá£Å™õlC Ï ¨ÓÅ †Ö ߀ØÁҀǨĄñ‡ÜÓƨÀ1͟f ï ¦xʓÒIǙõ ܣƨÀ1͟ï–ϣʓÒIǓú 3Ôc߀ØÁҀǨĄñ‡ÜÓƨÀ1͟f ï ¦xÊ4  ¦oõ ܣƨÀ1͟ï–Ï£Ê4  ¦Îú %Ð g“ .

~87P ¹P¯ 6 ‹€I{ôy|ˆ ܣƨÀ1͟ï–ÌƈÑxĀßT ˆÆÑÓÄÂÓǧ!¨ÀPƬñH†Ö@õp½Ô½ú ܣƨÀ1͟ï–ÌƈÑxęïôÜ£ÆH) Ä D3Ò1ÀÀ¬ñ ôÀ¨Ò !1Ũ© Ä !ḦÂÓÏ Œú ܣƨÀ1͟ï–ÌƈÑxęïpÃP̈ÂÓÛoñðÛÎҀÇ@ú ܣƨÀ1͟ïðÀÂÓˈƨÀ T ß ) Æ ¦HĄñŒÑ1ƣǨÄÆ1Ìnõ˜ÀPÂÓˈƨÀ½ú ܣƨÀ1͟ïðÀÂÓˈƨÀ„ïùÃPÌ£ۄñèÛÎÒIǓú ܣƨÀ1͟ïpèƨ¨ÑÓĽ" Ò WˆÂ£ÄƬñIú èÆHÍ¡ÑHÀÒPÑÎÆPÉñvܣƐÀHÍoõ “ú­÷ 3 ˆÆ1ÄHɨÌHÇ@ܪĐÌ1ɽÆàÒ£ÍUËPÉÄPÄÁ£ÇàÂÑÓĽÒ"W¨ÆWÂÓÇã Ґ܀ҀÇ4ÜPңÐÆ' ÌÆHÄ1ÉÌ1Ç Ü£ÆÀH͟ïðÂÑxÄ3" Ò W¨Æ€ÂxLjà ܣƐÀH͟p ï ¦ÓÊ@Ò€Ç ß „p £ ï !¨ÆHÄ ‰ñ‡ú ßÿÜÓƨÀHÍnïf¦xÊ4Âg¦€ÂÓÇà F F ܣƐÀH͟ï–Ï£Ê@Ò€Ç ß „p £ ï !¨ÆHÄ „ñ‡ú ßÿÜÓƨÀHÍnïpÏÓÊ4g  ¦ F ”Ir€” %  ´ gÐ €“ ´ F èÆHÍ¥!¨ÆHÄ)¤ˆÂx˽ƨÀ­ñ‡ÜÓƨÀHÍ3ú¬÷ 3 ˆÆ1ÄHɨÌHÇ@ܪÄHňÆÝÀÂÓˈƨÀà܀ĐÌ3ÒIǧ!WÁH̀ÄHÅÎÒ¨Ü ËÉ¨ÄÄ¨Á£Ç„ïu ÌÆHÄ1ÉÌ1Ç Ü£ÆÀH͟ïðÀÂx˽ƨÀ„f ï !ÆH© Ä ¨) Æ ¦HĄñIú èÆHÍÐÂÑÓĽÒ"WÂ1ÄƬñ‡ÜÓƨÀHÍ3ú¬÷ qÅPÆ1ÄÎÜ Ä1Å4ÒÜ ËÉÄPÄÁÓÇÝÄÁ –ÂÑÓĽÒ"W¨Æ ïu ܣƨÀ1͟ïðÀÂÓˈƨÀ„ïzÜ£Æ1© Ä D½ÒHÀÀ­ñ –Ë3ÀÂ¨ÑÎ vú ܣƨÀ1͟ï–ÌƈÑxęïôÜ£ÆHg Ä 4ÎÒÓÃPÄHÅoñ†Ôˆú ܣƨÀ1͟ïðÂÑÓĽ" Ò W¨ÆUT ß Ì1É½Æ Ã¨ÆHÍWèƨ¨ÑÓĽÒ"WˆÂ£ÄƬñ‡Ü£ÆÀHÍ3ú¬÷ qÅPÆ1ÄÎÜ Ä1Å4ÒÜ ËÉÄPÄÁÓÇÝÄÁ zҀÇ3¨ÑÓĽÒ"WÆ ïu ܣƨÀ1͟ïðÀÂÓˈƨÀ„ïzÜ£Æ1© Ä D½ÒHÀÀ­ñ ðÃÂ1ÌgÎc!HÌÆ£Ï Œú ܣƨÀ1͟ï–ÌƈÑxęïôÜ£ÆHg Ä 4ÎÒÓÃPÄHÅoñ€ÖHú ܣƨÀ1͟ïðÂÑÓĽ" Ò W¨ÆUT ß DˆÂPÀˆÜÓÆ —    } —   f   You should study the constructor in this class to make sure you understand all of the instance variables and how they are initialized. Ê£}È È‘É Sµ ² › œ rQl‘Ù 'l™wm• ¦l‡œ©i ÎÒ£g Æ Û½Ò1Æ1Û Now we’ll turn our attention to the class.  . The face of the die will be a  ˆÆˆÑxĈÂx§ Ç !ÀHÆ square (via ) and the pips will be circles. The purpose of this class is to display the value of a die in a graphical fashion. width. Other instance variables are calculated from these parameters. and height. A button is positioned by providing a center point.

Using the standard position of pips on a die. setValue Change the view to show a given value. The value to display will be passed as a parameter. three down the right edge. The comments Without further ado. the heart of indicate the current value of the die. we will need seven circles: three down the left edge. and the size of the die as parameters. ÎÒ£g Æ Û3Ò£Æ1Û class. and one in the center. the center point of the die. One simple approach is to pre-place circles in all the possible locations where a pip might be and then turn them on or off by changing their colors. We will have to specify the window. 3Ò1ÆgÛ½Ò1Æ£Û is turning various pips “on” and “off” to Obviously. The Ü£Æ1© Ä ÛÀÓÉˆÆ method will set the colors of the circles based on the value of the die. The constructor will create the background square and the seven circles.”Ir ¯ s4tvuxwzy|{I}†~87Püé4{ÒêŠ 6 ŠŒ«sB± uŒˆ–ˆp{ôˆ Our  ÎÒ1ÆÛ3Ò£Æ1Û will have the following interface: constructor Create a die in a window. here is the code for our will help you to follow how it works: óWýңg Æ W½Ò1Æ1ۙU ï ¨Ï ÍP̨Áxa Ê !Ḧ"  PÅ4ÒPѨÜUÒvC Ê ˆÁH̐@ Ä Y ÑHÀPˆÜPÜ ÎÒ£g Æ Û3Ò£Æ1ۙ÷ ©) ÎÒ1 Æ Û3Ò£Æ1ÛÿҐÜUÂÈÛÎÒ£) à !¨Æ1ĀÄHŽÂ1ÄÝýҐq Ü ½ÀÂ1Ï3ÜÈE  !PÌ"  PÅ4ҐÑ1ÀYÌÆ ¨ÌƈܣƣǨĈ£Ä3Ò1ÁÓÇ ÁPÍСÜxÄÂÓÇÃÂ1̐ÃàÜHÒ ¦C¨ÜPÒÓèÆPÃUýңÆnq ï )©   »  èÆHÍSÌ©ÌÒIÇ4Òxħ̩̭ñ‡ÜÓƨÀḦ́õ Û3ҀǟõÑ1ÆÓÇÄÆ1Ìnõ ÜHÒ Æ3ú¬÷ ©©v×H̨ƨÂ1ĨƀE  W3Ò£Æ1ÛÐÁHÍЀýÒ1Ɖõ˜Ænïp!ŸïP÷ Ã4Ö ß 3Ò1g Æ Û½Ò1Æ£Ûoñpʈ) Ï 43ҀǙõ ØÁҀǨĄë ñ dÕ„õÒ9PÕ3ú“õ¢ÔHÕ3ú ÑÓÌƐÂ1ĨƽÜÈÂcÈÒ1ÆàÑ1ÆÓÇĨÆHÌÆHÃÝÂ1Ä©Ò ñ d¨Õ‰ë õ 9PÕ½úfÅ3 W3ÒI§ Ç !¡ÜHÒ£Ã¨ÆˆÜ ÁPÍÐÀPÆÓ§ Ç !HÄHÅ¡ÔHÕnq ï )© # !h óWͽÒÓÌ3ÜxÄÝÐÆPͽÒIǽÆàÜÓÁxÊ3ÆàÜxÄÂÓLjèÂ1̐ÃEWˆÂPÀÓÉ½ÆˆÜ Ü£Æ¨À1͟ï|ÛÎҀÇW߀ÛÎÒ€Ç óÿÜ£  W¨ÆcÄHÅ4ҐÜYͨÁ1ÌÝÃPÌ£ÛÎÒIǧ!`ÎÒ4ÜUÀÂ1ĨÆHÌ Ü£Æ¨À1͟ï Ë3Â Ñ ÎC!HÌÁ£ÉPLjà & ß †ÛHÅ4ÒÓĨ' Æ ó¡Ñ£Á¨ÀHÁHÌÐÁPÍWÈÒ1ƀͨÂÑ1Æ Ü£Æ¨À1͟ïpͨÁH̨) Æ !HÌÁ£ÉPLjà & ß z˽ÀÂ Ñ Îxó¡Ñ£Á¨ÀHÁHÌÐÁP̀Ä1Ž` Æ Î Ò @Ü Ü£Æ¨À1͟b ï @ÜPÒ ¨ÆÈßÝÕn Ö YÐÜHÒ ¨Æ ó€ÌÂHÈҀÉ@ÜYÁPÍÝƨ¨р¥ Å Î Ò  Å@ÜPÒ ¨Æcß ÜHÒ ¨T Æ ŸÐԄïðÕ óUŽÀ1̀ÄHŽơÜHÒ Æ€ÁPÍWÄHňÆcÃ½Ò£Æ ÁP͐ͽܣÆ1ÄWßÝÕnïù@ ø Y Å4ÜPÒ ¨Æ óWÈҨ܀ĈÂÓÇÎÑ1ÆcÍHÌÁ€Ê»Ñ1ÆÓÇÄÆ1̀ÄÁÝÁÓÉÄÆ1£ Ì 4Òq@Ü ) h )h !h )h !h !h ó¡ÑÓÌƐÂ1ĨÆW¡Ü"í1ɽÂ1̨ÆcͨÁ1ÌWÄHŽƀͨÂÑ£Æ .

~87P ¹P¯ 6 ‹€I{ôy|ˆ Ñ o ¦ õ x Ñ ÏÝß¡Ñ1ÆÓÇÄÆ1̙ïp!¨ÆHÄ ‰ñ‡ú†õ˜Ñ1ƣǨÄÆ1̙ïf!ÆHÄ „ñIú ߀ØÁҀǨĄñvÑ"¦C¨xÅ@ÜPÒ ¨Æ‰õ Ñxϧ¨ÓÅ4ÜPÒ ¨Æ3ú 3Ôc߀ØÁҀǨĄñv" Ñ ¦á£Å@ÜPÒ ¨Æ‰õ ÑxϨá1Å4ÜPÒ ¨Æ3ú ÌƈÑxÄWT ß  ˆÆÑÓĈÂx§ Ç !¨ÀPÆæf ñ †Ö@p õ 3Ԉú ÌƈÑxęïpÃP̈ÂÓÛoñðÛÎҀÇ@ú ÌƈÑxęïôÜ£ÆH) Ä D3Ò1ÀÀ¬ñvܣƐÀH͟ï Ë3¨ Ñ ÎC!H̨ÁÓɐǨÃÎú †Ö ”Ir€´ ))hh gÐ ))hh €“ óÝ×HÌƐÂ1Ĩƀþ¡ÑÒÓ̽ÑHÀHƽÜY͐ÁHÌ ÜxÄÂÓÇÃÂ1̐ÃVÎÒÿÀPÁÑH£Ä3Ò1ÁÓÇ@Ü Ü£Æ¨À1͟b ï 4 Ò “Öªß ܣƐÀHÍn¡ ï Ì©ÌIÊ4"  ΈÆHؽÒoñvÑ ¦c¨PÁH͐Í3ÜÓÆ1Äoõ ÑÓÏC¨PÁH͐Í3ÜÓÆHÄÎú ܣƨÀ1͟b ï 4 Ò ½ÔÈß Ü£ÆÀHÍn¡ ï Ì©ÌIÊ4"  ΈÆHؽ Ò oñvÑ ¦c¨PÁH͐Í3ÜÓÆ1Äoõ ÑÓÏÎú ܣƨÀ1͟b ï 4 Ò ˆÞUß Ü£ÆÀHÍn¡ ï Ì©ÌIÊ4"  ΈÆHؽ Ò oñvÑ ¦c¨PÁH͐Í3ÜÓÆ1Äoõ ÑÓϐá¨ÁH͐Í3ÜÓÆHÄÎú ܣƨÀ1͟b ï 4 Ò Cdcß Ü£ÆÀHÍn¡ ï Ì©ÌIÊ4"  ΈÆHؽ Ò oñvÑ ¦„õlÑÓÏÎú ܣƨÀ1͟b ï 4 Ò m9Èß Ü£ÆÀHÍn¡ ï Ì©ÌIÊ4"  ΈÆHؽ Ò oñvÑ ¦Pá¨ÁH͐Í3ÜÓÆ1Äoõ ÑÓC Ï ¨PÁH͐Í3ÜÓÆHÄÎú ܣƨÀ1͟b ï 4 Ò ˆøUß Ü£ÆÀHÍn¡ ï Ì©ÌIÊ4"  ΈÆHؽ Ò oñvÑ ¦Pá¨ÁH͐Í3ÜÓÆ1Äoõ ÑÓÏÎú ܣƨÀ1͟b ï 4 Ò ˆþUß Ü£ÆÀHÍn¡ ï Ì©ÌIÊ4"  ΈÆHؽ Ò oñvÑ ¦Pá¨ÁH͐Í3ÜÓÆ1Äoõ ÑÓϐá¨ÁH͐Í3ÜÓÆHÄÎú ž ó ¨ÌˆÂÓÛ¡ÂÓÇ ÒIÇ4ÒÓĽÒHÂPÀ`WˆÂPÀÓÉ½Æ Ü£Æ¨À1͟ïôÜ£ÆHÄ)ۈÂPÀÓɽƬñ€ÖHú èÆHÍS̩̀ÊΠÎÆHØ3ÒqnñvܣƨÀ1Íoõ ¦oõ˜ÏÎú¬÷ "¢IǨÄÆ1ÌHÇ3ÂPÀ ňƨÀ"ˆÆHÌ Ê3ÆHÄ1ŽÁPÃUÄÁ€ÃPÌ£ۡÂ`4Òq¡Â1Ä 4 Ò àßÝ×ÒÓ̽ÑHÀPƬñ–بÁˆÒ€Ç¨Ä„ñÒ¦oõðÏÎú†õ˜Ü£ÆÀHÍnïU@ÜHÒ Æ3ú 4 Ò hïzÜÓÆH© Ä D½ÒHÀPÀ¬ñ‡ÜÓƨÀ1͟ï|˽Â Ñ ÎC!P̨ÁÓÉPLjýú 4 Ò hïzÜÓÆHÄ Ä ÉÄÀҀLjÆæñvܣƨÀ1͟ï Ë3Â Ñ Îc!HÌÁxɐÇÃÎú 4 Ò hïùÃḦ£ۄñ‡ÜÓƨÀHÍnï–Û3ҀǓú ÌÆHÄ1ÉÌ1T Ç 4q Ò  !h ñÒ¦oõðÏÎúm èÆHÍÿÜ£ÆHÄ)ۈÂPÀÓɽƬñ‡ÜÓƨÀḦ́õIWÀxɽÆ3ú­÷ qÅPÆ1ĀÄHÅÎÒ¨Ü ÃˆÒ1ÆcÄÁ€ÃˆÒ¨u Ü 3ÀÂ£ÏTWˆÂPÀÓɈÆnïq ó€ÄHÉÌ1ÇÿÀPV À 4 Ò 4Ü ÁPÍPÍ Ü£Æ¨À1͟b ï 4 Ò “Ö­ïôÜ£ÆH) Ä D3Ò1ÀÀ¬ñvܣƐÀH͟ï ˽¨ Ñ Î©!P̨Á£ÉHLjÃÎú ܣƨÀ1͟b ï 4 Ò ½ÔoïôÜ£ÆH) Ä D3Ò1ÀÀ¬ñvܣƐÀH͟ï ˽¨ Ñ Î©!P̨Á£ÉHLjÃÎú ܣƨÀ1͟b ï 4 Ò ˆÞnïôÜ£ÆH) Ä D3Ò1ÀÀ¬ñvܣƐÀH͟ï ˽¨ Ñ Î©!P̨Á£ÉHLjÃÎú ܣƨÀ1͟b ï 4 Ò CdŸïôÜ£ÆH) Ä D3Ò1ÀÀ¬ñvܣƐÀH͟ï ˽¨ Ñ Î©!P̨Á£ÉHLjÃÎú ܣƨÀ1͟b ï 4 Ò m9oïôÜ£ÆH) Ä D3Ò1ÀÀ¬ñvܣƐÀH͟ï ˽¨ Ñ Î©!P̨Á£ÉHLjÃÎú ܣƨÀ1͟b ï 4 Ò ˆønïôÜ£ÆH) Ä D3Ò1ÀÀ¬ñvܣƐÀH͟ï ˽¨ Ñ Î©!P̨Á£ÉHLjÃÎú ܣƨÀ1͟b ï 4 Ò ˆþnïôÜ£ÆH) Ä D3Ò1ÀÀ¬ñvܣƐÀH͟ï ˽¨ Ñ Î©!P̨Á£ÉHLjÃÎú .

I have defined a set of values that determine various aspects of the die such as its color and the size of the pips. in the constructor. Calculating these values in the constructor and then using them in other places allows us to easily tweak the appearance of the die without having to search through the code to find all the places where those values are used. I actually figured out the specific calculations (such as the pip size being one-tenth of the die size) through a process of trial and error. This method is just a .”Ir€¹ s4tvuxwzy|{I}†~87Püé4{ÒêŠ 6 ŠŒ«sB± uŒˆ–ˆp{ôˆ ó€ÄHÉÌ1Ç Ñ1Á1̐ÌÆÑÓÄ£ÎÒ4Ü Á£Ç Ò£T Í WˆÂPÀÓɈÆcߐ߻֭÷ ÜÓƨÀ1͟U ï Î Ò CdŸïzÜÓÆHÄ)D3ÒHÀPÀ¬ñvܣƨÀ1͟ï–ͨÁ1ÌÆ!PÌÁÓÉPÇÃÎú ƨÀÒÓE Í WˆÂPÀÓɈƀߐßÐÔo÷ ÜÓƨÀ1͟U ï Î Ò “Ö­ïzÜÓÆH) Ä D3ÒHÀPÀ¬ñvܣƨÀ1͟ï–ͨÁ1Ì Æ !PÌÁÓÉPÇÃÎú ÜÓƨÀ1͟U ï Î Ò ˆþnïzÜÓÆH) Ä D3ÒHÀPÀ¬ñvܣƨÀ1͟ï–ͨÁ1Ì Æ !PÌÁÓÉPÇÃÎú ƨÀÒÓE Í WˆÂPÀÓɈƀߐßÝÞn÷ ÜÓƨÀ1͟U ï Î Ò “Ö­ïzÜÓÆH) Ä D3ÒHÀPÀ¬ñvܣƨÀ1͟ï–ͨÁ1Ì Æ !PÌÁÓÉPÇÃÎú ÜÓƨÀ1͟U ï Î Ò ˆþnïzÜÓÆH) Ä D3ÒHÀPÀ¬ñvܣƨÀ1͟ï–ͨÁ1Ì Æ !PÌÁÓÉPÇÃÎú ÜÓƨÀ1͟U ï Î Ò CdŸïzÜÓÆH) Ä D3ÒHÀPÀ¬ñvܣƨÀ1͟ï–ͨÁ1Ì Æ !PÌÁÓÉPÇÃÎú ƨÀÒÓE Í WˆÂPÀÓɈƀߐ¥ ß dŸ÷ ÜÓƨÀ1͟U ï Î Ò “Ö­ïzÜÓÆH) Ä D3ÒHÀPÀ¬ñvܣƨÀ1͟ï–ͨÁ1Ì Æ !PÌÁÓÉPÇÃÎú ÜÓƨÀ1͟U ï Î Ò ˆÞnïzÜÓÆH) Ä D3ÒHÀPÀ¬ñvܣƨÀ1͟ï–ͨÁ1Ì Æ !PÌÁÓÉPÇÃÎú ÜÓƨÀ1͟U ï Î Ò m9oïzÜÓÆH) Ä D3ÒHÀPÀ¬ñvܣƨÀ1͟ï–ͨÁ1Ì Æ !PÌÁÓÉPÇÃÎú ÜÓƨÀ1͟U ï Î Ò ˆþnïzÜÓÆH) Ä D3ÒHÀPÀ¬ñvܣƨÀ1͟ï–ͨÁ1Ì Æ !PÌÁÓÉPÇÃÎú ƨÀÒÓE Í WˆÂPÀÓɈƀߐS ß 9o÷ ÜÓƨÀ1͟U ï Î Ò “Ö­ïzÜÓÆH) Ä D3ÒHÀPÀ¬ñvܣƨÀ1͟ï–ͨÁ1Ì Æ !PÌÁÓÉPÇÃÎú ÜÓƨÀ1͟U ï Î Ò ˆÞnïzÜÓÆH) Ä D3ÒHÀPÀ¬ñvܣƨÀ1͟ï–ͨÁ1Ì Æ !PÌÁÓÉPÇÃÎú ÜÓƨÀ1͟U ï Î Ò CdŸïzÜÓÆH) Ä D3ÒHÀPÀ¬ñvܣƨÀ1͟ï–ͨÁ1Ì Æ !PÌÁÓÉPÇÃÎú ÜÓƨÀ1͟U ï Î Ò m9oïzÜÓÆH) Ä D3ÒHÀPÀ¬ñvܣƨÀ1͟ï–ͨÁ1Ì Æ !PÌÁÓÉPÇÃÎú ÜÓƨÀ1͟U ï Î Ò ˆþnïzÜÓÆH) Ä D3ÒHÀPÀ¬ñvܣƨÀ1͟ï–ͨÁ1Ì Æ !PÌÁÓÉPÇÃÎú ƨÀˆÜÓÆn÷ ÜÓƨÀ1͟U ï Î Ò “Ö­ïzÜÓÆH) Ä D3ÒHÀPÀ¬ñvܣƨÀ1͟ï–ͨÁ1Ì Æ !PÌÁÓÉPÇÃÎú ÜÓƨÀ1͟U ï Î Ò ½ÔoïzÜÓÆH) Ä D3ÒHÀPÀ¬ñvܣƨÀ1͟ï–ͨÁ1Ì Æ !PÌÁÓÉPÇÃÎú ÜÓƨÀ1͟U ï Î Ò ˆÞnïzÜÓÆH) Ä D3ÒHÀPÀ¬ñvܣƨÀ1͟ï–ͨÁ1Ì Æ !PÌÁÓÉPÇÃÎú ÜÓƨÀ1͟U ï Î Ò m9oïzÜÓÆH) Ä D3ÒHÀPÀ¬ñvܣƨÀ1͟ï–ͨÁ1Ì Æ !PÌÁÓÉPÇÃÎú ÜÓƨÀ1͟U ï Î Ò ˆønïzÜÓÆH) Ä D3ÒHÀPÀ¬ñvܣƨÀ1͟ï–ͨÁ1Ì Æ !PÌÁÓÉPÇÃÎú ÜÓƨÀ1͟U ï Î Ò ˆþnïzÜÓÆH) Ä D3ÒHÀPÀ¬ñvܣƨÀ1͟ï–ͨÁ1Ì Æ !PÌÁÓÉPÇÃÎú There are a couple of things worth noticing in this code. Another important thing to notice is that I have added an extra method ÊΠÎÆHØ3q Ò  that was not part of the original specification. First.

it is ܣƐÀH͟ï ÊΠΈÆ1Ø3ÒqnñvÑ"¦oõ˜ÑÓÏÎú invoked by lines such as . it is appropriate to make it a class method.~87P ¹P¯ 6 ‹€I{ôy|ˆ ”Ir€¿ helper function that executes the four lines of code necessary to draw each of 3Ò1ÆgÛ½Ò1Æ£Û the seven pips. The and classes are imported from their respective modules. Method names beginning with a single or double underscore are used in Python to indicate that a method is “private” to the class and not intended for use by outside programs. Ê£}È È  Sµ ™ ÿ   ¶ %i –%l™w ’”“fv••“H–B— 1ÉÄPÄÁ£Ç 3Ò1ÆW3Ò1Æ£Û Now we are ready to write our main program. Here is the program that uses our new widgets: ó€ÌÁÀÀHÆH̙b ï Ï ó ü Ì"  PÅ4Ґѐ$ Ü ̨) Á !Ḧ€ÊÐÄÁcÌÁÀÀWV  ½ÂÒÓÌÐÁHÍWýÒPÑ1Ænï Ù@ܣƈ܀рÉ4ÜxÄÁ€ÊÐÛÎÒÓ© à !ÆHÄÎÜ ó HɨĐĨÁ£ÇÿÂÓÇà ÎÒ£g Æ Û½Ò1Æ1Û™ï   # Ž ÍP̨ÁxÊ¡ÌÂÓLjÐÁxÊ»ÒvÊCˆÁH̐Äc̈ÂÓÇÃPÌÂÓǧ!Æ ÍP̨Áxa Ê !Ḧ"  PÅ4ÒPѨÜUÒvC Ê ˆÁHÌÄ ü ̈  © Å 4ÎҀǟõlØÁÒ€Ç¨Ä ÍP̨ÁxÊÐËPÉĐĨÁ£Ç ÒvÊCˆÁHÌÄ HÉÄPÄÁÓÇ ÍP̨ÁxÊÿÈÒ1g Æ W½Ò1ƣۡ҇Êc½Á1ÌÄ ÎÒ£ÆgÛ½Ò1Æ1Û Ã¨ÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ó¡ÑǪ́ƨÂ1ĨÆUÄHňÆÝÂ")3ÀÒPÑH£Ä3Ò1ÁÓǀÛ3ҀLjÐÁ1Û ÛÎÒIÇàß ü ̈ũ4ÎҀÇoñ  ÎҐѣÆè Á¨ÀPÀPÆHÌ6£ú ÛÎÒIDŽïzÜÓÆHĨאÁÁ1̨ýܓñzՉõîՄõªÖxՉõªÖxÕ½ú ÛÎÒIDŽïzÜÓÆHÄ ˆÂ Ñ ÎC!HÌÁ£ÉPLjÃæñ ž!HÌÆPƣLjB Ô £ú ¨Ì£ÛÝÄHňÆàҀǨÄÆH̐ͨÑ1Æ Û3Ò£Ã)!¨ÆHÄ3Ü Ã½Ò£ÆÎÖ ß ÎÒ£ÆgÛ½Ò1Æ1ۄñèÛ3ҀǙõ ØÁҀǨĄñzމõ–þ½ú†õ˜Ôˆú ýңƨÔcß ÎÒ£ÆgÛ½Ò1Æ1ۄñèÛ3ҀǙõ ØÁҀǨĄñzþ‰õ–þ½ú†õ˜Ôˆú ÌÁÀÀ 1ÉÄPÄÁ£ÇWß HɨĐÄÁÓÇnñðÛÎҀǟõ بÁˆÒ€Ç¨Ä„ñ89‰õ¡dnï¡9ˆú†õ ø„õªÖ“õV8 ˆÁ¨ÀPÀ ÎÒPÑ1ÆB£ú ÌÁÀÀ 1ÉÄPÄÁ£Çhïè¨ÑÓÄ3 Ò WˆÂ£ÄÆæñ‡ú í1ÉÎÒÓÄ 1ÉÄPÄÁ£ÇWß HɨĐÄÁÓÇnñðÛÎҀǟõ بÁˆÒ€Ç¨Ä„8 ñ 9‰õ‡ÖHú†õ¢Ô‰õªÖ“õè ÓÉÎÒÓÄ#Óú ž#  € ž ž ž  33 # g # ó r  ® ó W¨Æ£ÇÄàÀHÁÁ" G  ÄÝ߀ÛÎÒIDŽïp!¨ÆHÄHöˆÁÓÉ@ܣƬñIú  . Inside the constructor. Since this is a function that is only useful within the class.

The heart of the program is the event loop. but the quit button is left deactivated. The quit button is activated inside the event loop below when the roll button is clicked. The inside the loop ensures that the rolling of the dice only happens when the roll button is clicked. Clicking a point that is not inside either button causes the loop to iterate.”Ir€â s4tvuxwzy|{I}†~87Püé4{ÒêŠ 6 ŠŒ«sB± uŒˆ–ˆp{ôˆ ÛPÅÎÒHÀPÆYǽÁHÄ í£É4ÒxÄ HɨĐĨÁ£Ç„ï–ÑHÀ¨ÒÑÎÆPÃæñHÄÎú¬÷ ң̀ÌÁÀÀ HÉÄPÄÁÓDŽïôÑ1ÀÒPÑΈÆHÉñfÄ4ú­÷ WÀxɽÆÎ֪߀̈ÂÓÇÃPÌÂÓ§ Ç !ÆæñI֓õ–þ½ú ÈÒ1Æ3Ö­ïzÜÓÆH) Ä ÛˆÂÀxÉ½Æ¬Ò ñ WˆÂPÀÓɈÆÎÖPú WÀxɽƨÔÈ߀̈ÂÓÇÃPÌÂÓ§ Ç !ÆæñI֓õ–þ½ú ÈÒ1ƐÔoïzÜÓÆH) Ä ÛˆÂÀxÉ½Æ¬Ò ñ WˆÂPÀÓɈƨԽú í£É4ÒxÄ HɨĐĨÁ£Ç„ïðÂÑxÄ3" Ò WÂ1ĨÆæñIú ÄÝßcÛÎÒIDŽp ï !¨ÆHÄHöˆÁÓÉ@ܣƬñIú ! g g ó ÑHÀHÁ½Ü£ÆÈÉ)»ÜIňÁ ¡ ÛÎÒIDŽïôÑ1ÀPÁˆÜ£Ææñ‡ú  Ê4¨ҀÇoñIú Notice that near the top of the program I have built the visual interface by ÎÒ1ÆÛ3Ò£Æ1Û HÉÄPÄÁÓÇ s and two s. Data is stored in instance variables and manipulated via methods. To demonstrate the activation creating the two feature of buttons. It is the class definition that determines what the attributes of the object will be. ’ Every object is an instance of some class. . but nothing is actually done. This approach forces the user to roll the dice at least once before quitting. Programmers can create new kinds of objects by writing suitable class definitions. the roll button is initially active. Here is a summary of some key points: ’ An object comprises a collection of related data and a set of operations to manipulate that data. It is just a sentinel loop that gets mouse clicks and processes them until the user successfully clicks the quit Ò£Í button. “d™«”sr  ˜Ÿi„¤n…‚™g © ¦§› › ingIí   This chapter has shown you how to work with class definitions.

3. “d™«”s‘ egf„‚hgIƒ¬‡‘‚„‘ ”Ir€é hjiCkmlniCoqpIrQi§sutqlnvxw%s y{zH|c})~Q©€cˆ‚3} 1. New objects are created by invoking a constructor. We can build novel GUI widgets by defining suitable classes. ’ Correctly designed classes provide encapsulation. This separation of concerns is a programming convention in Python. 2.. ’ Defining new objects (via Ñ1ÀÂÜÜ ) can simplify the structure of a program by allowing a single variable to store a constellation of related data. In data processing. These entities may have complex behavior that is captured in method algorithms (e. The internal details of an object are hidden inside the class definition so that other portions of the program do not need to know how an object is implemented. a projectile) or they may be little more than a collection of relevant information about some individual (e. Objects are useful for modeling real world entities. These functions implement the methods of the class.g. Ä1Å4ÒÜ . ’ The special method ÒIÇ4ÒÓÄ is the constructor for a class. Every method definition has a ܣƐÀHÍ ÜÓƨÀHÍ . Its job is to initialize the instance variables of an object. a student record).. The first parameter of a Python method definition is called 4. ’ Most GUI systems are built using an object-oriented approach. An object may have only one instance variable.~37H âHcŽŒ{I} ³Œ6 ˆ–{zˆ ’ A Python class definition is a collection of function definitions. The parameter is used to access the attributes of the object via dot notation. 5. Functions that live in objects are called instance variables. a collection of information about a person or thing is called a file. . the instance variables of an object should only be accessed or modified through the interface methods of the class. The actual parameter of is the special first parameter called ܣƐÀHÍ object to which the method is being applied.g.

The term applied to hiding details inside class definitions is a) obscuring b) subclassing c) documentation d) encapsualtion 7. A Python string literal can span multiple lines if enclosed with  ©) a) b) c) d) ÎÒ£ÆgÛ3Ò£Æ1Û ÂÑÓĽÒ"W¨Æ 8. 10. the instance variable could be accessed via which expression? ¦ ܣƐÀHÍnf ï¦ Ü£ÆÀHÍ û ¦© ÜÓÆPÍnïf!¨Æ1Ä æñIú a) b) c) d) %Ð 5. A Python convention for defining methods that are “private” to a class is to begin the method name with a) “private” b) a pound sign (#) c) an underscore ( ) d) a hyphen (-) 6. A method definition with four formal parameters is generally called with how many actual parameters? a) three b) four c) five d) it depends 3. Within a method definition. Instance variables go away once a method terminates. What Python reserved word starts a class definition? èÆHÍ ÑHÀPˆÜPÜ Á£Ë ƈÑxÄ Ò€Ç4ÒxÄ a) b) c) ï d) 2. the constructor is called 7. It is considered bad style to directly access an instance variable outside of a class definition. 9. A method definition is similar to a(n) a) loop b) module c) import statement ¦ d) function definition 4. 8. what is the data type of the instance variable ? ömÅ 3Ò1Æ a) bool b) int c) float d)   ¹ ! . In a widget. . In a Python class.”I”7 s4tvuxwzy|{I}†~87Püé4{ÒêŠ 6 ŠŒ«sB± uŒˆ–ˆp{ôˆ ÒIÇ4ÒÓÄ 6. Method names should always begin with one or two underscores. “Docstring” is another word for comment. ƒ |§„3…‡†§ˆ}Iˆj‰cŠ§…Œ‹"} 1.

~37H âHcŽŒ{I} ³Œ6 ˆ–{zˆ 1ÉÄPÄÁ£Ç 9. Explain the following in terms of actual code that might be found in a class definition: (a) method (b) instance variable (c) constructor (d) accessor (e) mutator 3. Which of the following methods is part of the class in this chapter? ÂÑxÄ3" Ò WÂ1Ä¨Æ ÜÓÆHÄ×PÁ¨ÀHÁHÌ ÜÓÆH© Ä ÛÀxÉ½Æ ÑHÀ¨Ò Ñ ÎˆÆPà a) b) c) d) ”I”H~    …Œ‚3‹|c‚8‚X…ŒŠm 1. Show the output that would result from the following nonsense program: ÑHÀÂÜÜ Å €h ¨Á ¨Áo÷ ÐÆPÍSÌ)ÌҀÇÎÒÓÄC̩̬ñvܣƐÀHÍoõ WˆÂPÀÓɈÆ3ú¬÷ ¨Ì3ҀǨA Ä ‡×1ÌƐÂ1Ä3ÒI§ Ç !Ý ¨Á Á€ÍPÌÁ€Ê§÷uÎõ°WÀÓÉˆÆ ÜÓƨÀHÍnp ï WÀÓɈÆUßàS Ô YVWˆÂPÀÓÉˆÆ ÃÆPÍ¡Ñ1ÀPÁ1ÛHÇnñvܣƨÀ1Íoõ5¦Îú¬÷ ¨Ì3ҀǨA Ä ‡×ÀPÁ£ÛPÇ4ÒI§ Ç !n÷qÎõ5¦ ¨Ì3ҀǨ¥ Ä ¦aYÝܣƐÀH͟s ï WˆÂPÀÓÉ½Æ Ì¨ÆHÄHɨÌHS Ç ¦ÝáÿÜÓƨÀHÍnp ï WÀÓÉˆÆ Ã¨ÆPÍ ÊÎÂÒIÇnñIú­÷ ¨Ì3ÒIÇ& Ä ‡×ÀPÁ£ÛPÇ4ÒIǧ!€Â1ÌÁÓɐÇÃÈǽÁ£Ûhïq ÑÖ ß Á ÁæñôÞ3ú Ñ1Ôcß Á ÁæÒ ñ dÎú Ž €h   € h  €h . Explain the similarities and differences between instance variables and “regular” function variables. Which of the following methods is not part of the class in this chapter? ÂÑxÄ3" Ò WÂ1Ä¨Æ ÃÆ¨Âx Ñ Ä3ÒWˆÂ1Ä¨Æ Ü£Æ1Ä©¤ÂÓ˽ƐÀ ÑHÀ¨ÒÑÎÆPà b) c) d) a) 3Ò1ÆÛ3Ò1Æ£Û 10. 2.

all prompts and messages should be displayed in the graphics window. “Door 2.” and “Door 3” in a window and randomly select one of the buttons (without telling the user which one is selected). Extend the program from the previous problem by allowing the player to play multiple rounds and displaying the number of wins and losses.3. Here is the specification of the new method: ÂHÐà ü ÌÂHèƬñ‡ÜÓƨÀḦ́5 õ !ḦÂ1èÆHبÁˆÒIÇÄnõ ÑǪ́ÆPýÒxÄÎܐæ ú !ḦÂ1èÆHبÁˆÒIÇÄ is a float that repÑǪ́ÆPÈÒÓÄÎÜ resents a grade (e. The program then prompts the user to click on one of the buttons. and a click on one of the other two is a loss.Your program should be entirely graphical.7 B+ = 3. 1ÉĐĨÁ£Ç 2. etc.0. A = 4. A click on the special button is a win. and is a float indicating the number of credit hours for the class.. Å1Ä1ɈÐƣÇÄ class from the chapter by adding a mutator method 5. Your program should then prompt the user to enter course information (gradepoint and credits) and then print out the final GPA achieved. Use the class discussed in this chapter to build a GUI for one (or more) of your projects from previous chapters. and in the case of a loss. A– = 3. that is. Modifies the student object by adding this grade information. 4. Your program should create a new student object that has 0 credits and 0 quality points (the name is irrelevant). Use the updated class to implement a simple program for calculating GPA. Modify the that records a grade for the student.”I”€r s4tvuxwzy|{I}†~87Püé4{ÒêŠ 6 ŠŒ«sB± uŒˆ–ˆp{ôˆ ¨Ì3ÒIÇÄÿшֆïôÑ1ÀPÁ1ÛHÇnñôÞ3ú ¨Ì3ÒIÇÄÿÑHԄïôÑ1ÀPÁ1ÛHÇnñŒÑˆÖ­ï–ÑHÀHÁ1ÛPÇoñ†Ôˆúú Ê4ÂÒIÇnñ‡ú ’”“fv••“H–B—$—˜l™wm•Sš#›§i•“¡œ©lnsi§s 1.” Your program should draw three buttons labeled “Door 1”.  3. which was the correct button. .). You should tell the user whether they won or lost.g. Add a “Quit” button for ending the game. Write a program to play “Three Button Monte. Modify the cannonball simulation from the chapter so that it also calculates the maximum height achieved by the cannonball.

Ü£ÆHĨאÁÀPÁH̉ñ‡ÜÓƨÀḦ́õ Ñ£Á¨ÀHÁHÌ4ú ”I”€” u    Changes the color of the pips to Ñ£Á¨ÀPÁ1Ì . Your constructor should take the center of the button and its radius as normal parameters. but for a cube. 3Ò1g Æ Û½Ò1Æ£Û class from the chapter by adding a method that allows 8. Write a class to represent the geometric solid sphere. Write a modified class that creates circular buttons. WÁ¨ÀxÉHÊ3Ææñ‡ÜÓƨÀ1ÍÎú Returns the volume of the sphere. Use your new class to solve Programming Exercise 1 from Chapter 3. Use the updated class to improve the GPA calculator by allowing the entry of letter grades. You can test your new class with the program. variable Ü£Æ1© Ä ÛÀÓÉˆÆ Modify so that it remembers the value of the die in an instance ÜÓÆHĨאÁ¨ÀHÁHÌ ÜÓÆH© Ä ÛÀxÉ½Æ variable. a random color with the 9. 11. Test your class by modifying to use your buttons. The constructor should accept the length of a side as a parameter.~37H âHcŽŒ{I} ³Œ6 ˆ–{zˆ ÂHÐg à ¤Æ1ĐÄÆ1Ì ü ̈ÂHÃÆ 6. Implement a class to represent a playing card. HɨĐĨÁ£Ç 7. Â1Ðà ü ̈Â1Ã¨Æ This is similar to except that it accepts a letter grade as a string (instead of a gradepoint). Extend the previous exercise by implementing an method. Same as the previous problem. Call your class × HɨĐĨÁ£Ç and implement the exact same methods that are in the exist1ÉĐĨÁ£Ç ing class. but you also need to redraw the die after doing this. Then can call and pass the stored value to ̨Á¨ÀPÀPÆH̟U ï ¨Ï redraw the die. Have the dice change to a random color after each roll (you can generate Ñ1Á¨ÀHÁHÌ c Ì !£Ë function). Your class should have the following methods: . Your class should implement the following methods: ҀÇÎÒÓÄ ñ‡ÜÓƨÀḦ́õl̈Â1ýÒIÉ@ܨú !¨ÆHÄg ½Â1ýҀÉ4ܓñvܣƨÀ1ÍÎú Creates a sphere having the given ̈Â1ýÒIÉ@Ü . Place your class in a module called рːɨĐĨÁ£Ç„b ï Ï ÌÁÀÀHÆH̙b ï Ï . ÜIÉ̐ͨÑ1Æ Ú ÌƐ¬ñ‡ÜÓƨÀ1ÍÎú Returns the surface area of the sphere. 10. Modify the the color of the pips to be specified. Hints: You can change the color by changing the value of the instance ͐ÁHÌÆg!P̨Á£ÉÇà . Returns the radius of this sphere.

Extend your card class from the previous problem with a ÛÎҀǟõ Ñ1ÆÓÇÄÆ1Ì4ú method that displays the card in a graphics window. “h”. !¨ÆHÄCÅÓÉÎÒÓĄñvܣƐÀHÍÎú Returns the suit of the card. ÃPÌ£ÛoñvܣƐÀHÍoõ 12. %R"ېÀxɽÆæñvܣƐÀHÍÎú Returns the Blackjack value of a card. “c”. Ace counts as 1. or “s” indicating the suit (diamonds. Use your extended class to create and display a hand of five random cards. ÁPS Í Å"½ÂHÐƽ% Ü  . For example. !¨ÆHÄg ½Âxc Ç ÎoñvܣƐÀHÍÎú Returns the rank of the card. Create the corresponding card.  Ü€ÄÌ Note: A method named is special in Python. 13.” Test your card class with a program that prints out ø randomly generated cards and the associated Blackjack value where ø is a number supplied by the user. Ì3ÒIÇÄÿÑ ÑcßÝאÂ1̐Éñ€Ö@õxÜ%£ú will print “Ace of Spades. Hint: the easiest way to do this is to search the Internet for a free set of ¢vÊÎg  !Æ card images and use the object in the graphics library to display them.”I” ¯ ҀÇÎÒÓÄ s4tvuxwzy|{I}†~87Püé4{ÒêŠ 6 ŠŒ«sB± uŒˆ–ˆp{ôˆ ñ‡ÜÓƨÀḦ́õl̈ÂxÇcÎnõ ÜIÉÎÒÓÄ4ú̈ÂxÇcÎ is an int in the range 1–13 indicating ÜIÉÎÒÓÄ the ranks Ace–King. face cards count as 10. If asked to convert an object into a string. clubs. if it’s present. For example. and is a single character “d”. Python uses this method. Here is a simple class that draws a (grim) face in a graphics window: óÐͨÂÑ£ÆnïU¨Ï ÍPÌÁ€a Ê !PÌ"  ÅÎҐѐÜU҇Êc½Á1̐ÄaY ÑHÀÂܐÜèDÂÑ1Æo÷ ÐÆPÍSÌ)ÌҀÇÎÒÓÄC̩̬ñvܣƐÀHÍoõ ÛÎÒILjÐÁ1۟õ Ñ1ƣǨÄÆ1Ìnõ ÜHÒ ¨Æ½ú¬÷ Æ1Ïc Æ Å¨Ò ÆcßÝÕnï†" Ö 9SYÝÜPÒ ¨Æ !h )h !h . hearts. or spades). ÜxÄPÌ ñvܣƐÀHÍÎú  Ú Ñ1Æ Returns a string that names the card.

Ê3g Á WÆ method 14. . Using the move method. Bonus: have the face change expression each time it “hits” the edge of the window. example you might add methods such as Your class should implement at least three such methods. etc. Use your class to write a program that draws a face and provides the user with buttons to change the facial expression. For ÜvÊ@ÒHÀHÆ Û3ҀǩΠÍPÌÁ£ÛPÇ Í¨ÀҀÇÎрŠ. create a program that makes a face bounce around in a window (see Programming Exercise 17 from Chapter 7). P̈Â Ñ ÎˆÆ1Ì 15. Create a class that displays a circle in a graphics window to show the current location of an object. . Here is a quick specification of the class: ÑHÀÂܐÜèP̈ÂÑΈÆ1̙÷ ÐÆPÍSÌ)ÌҀÇÎÒÓÄC̩̬ñvܣƐÀHÍoõ ÛÎÒILjÐÁ1۟õ¢Á£Ë ï ÁÌˆÂ¨ÑÎ4ú¬÷ ó€ÛÎÒILjÐÁ1ÛÿҐÜUÂE!P̈ũ4ÎҀÇàÂÓLjÃÝÁÓË ÁgP̈¨ÑΡҐÜUÂÓÇ¡ÁÓË ï ó ˆÁ½ÜHÒÓÄ3Ò£Á£Ç¡Ò¨ÜYÄÁUˈơÜIŽÁ£ÛPÇ I Ò ÇÐÄHňÆUÛÎҀÇèÁ£ÛhïlÁÓË ï ï Æ ÑÓÄcÛHŽÁˆÜ£Æ  ¨ÁgP̈ÂÑÎ¡ÒÜ . Modify the face class from the previous problem to include a similar to other graphics objects.~37H âHcŽŒ{I} ³Œ6 ˆ–{zˆ Æ1ÏÆ Ä ÍÍ€ß ÜHÒ ¨ÆTŸÝÞoïðÕ Ê3Á£ÉÄ1Å%Å¨Ò ¨ÆÈßÐÕnïHe@YÝÜHÒ Æ Ê3Á£ÉÄ1Å Ä ÍÍ€ßÿÜHÒ ¨Æ ŸWԄïðÕ ÜÓƨÀHÍnï|ňƨÂHÃUßÐ׈ÒÓ̽ÑHÀHÆæñvѣƣǨÄÆHÌoõ ÜHÒ Æ3ú ÜÓƨÀHÍnï|ňƨÂHÃnïùÃḦ£ۄñèÛ3ҀLjÐÁ1Û4ú ÜÓƨÀHÍnïèÀHÆPÍPÄ Ï¨ÆUßÝ׈ÒxÌ3Ñ1ÀPÆæñŒÑ1ÆÓÇÄÆ1Ìnõ ÆHϨÆcÅÒ ¨Æ½ú G ÜÓƨÀHÍnïèÀHÆPÍPÄ Ï¨ÆnïÊ3g Á W¨Ææ3 ñ ¨HÆHÏ¨Æ Ä ÍP̈́I õ ¨HÆHÏ¨Æ Ä ÍPÍÎú G ÜÓƨÀHÍnïpÌ½Ò !1Å¨Ä ÏÆ ßà×ÒÓ̽ÑHÀPƬñvѣƣÇĨÆHÌoõlÆ1Ïc Æ Å¨Ò Æ3ú G ÜÓƨÀHÍnïpÌ½Ò !1Å¨Ä ÏÆnïÊÎ Á WÆæñôÆHÏ¨Æ Ä ÍP̈́I õ ¨HÆHÏ¨Æ Ä ÍPÍÎú G ÜÓƨÀHÍnïèÀHÆPÍPÄ Ï¨ÆnïùÃḦÂÓÛoñèÛ3ҀÇèÁ1Û4ú G ÜÓƨÀHÍnïpÌ½Ò !1Å¨Ä ÏÆnïpÃPÌ£ÛoñðÛÎÒILjèÁ£Û4ú G “Ö ß Ñ£Æ£Ç¨ÄÆH̟ïôÑ1ÀPÁ£ÇˆÆæñ‡ú “Ö­ïÊ3g Á W¨Ææ3 ñ ¨IÊÎÁÓÉÄHm Å ÅÒ ¨c Æ ŸPԉõ Ê3Á£ÉÄ1Å Ä ÍÍÎú ½Ôcß Ñ£Æ£Ç¨ÄÆH̟ïôÑ1ÀPÁ£ÇˆÆæñ‡ú ½ÔoïÊ3g Á W¨ÆæñpÊ3Á£É¨ÄH% Å Å¨Ò c Æ ŸÔæõ ÊÎÁÓÉÄHÅ Ä ÍPÍÎú ÜÓƨÀHÍnïÊ3Á£ÉÄ1ÅÝ¥ ß ¤3ÒIǽƬH ñ †Ö@p õ ½Ô½ú ÜÓƨÀHÍnïÊ3Á£ÉÄ1ńïpÃP̈ÂÓÛoñðÛÎҀÇèÁ£Û@ú ”I”€´ !h !h !h !h !h )h !h !h )h Add methods to this class that cause the face to change expression. .

ˆÂ£c Ì !ÆHÄ 16.”I”€¹ ó ó s4tvuxwzy|{I}†~87Püé4{ÒêŠ 6 ŠŒ«sB± uŒˆ–ˆp{ôˆ ÂxÇ¡Á£Ë ƈÑxĀÄHŽÂ1ÄcŽˆÜV!¨Æ1Ä æñIú ÂxLjå!¨Æ1Ä ‰ñIú Ê3ÆHÄHňÁPÃ½Ü ÄHŽÂ1Ä ï Ì¨Æ ˆÁH̐ÄàÒÓÄÎ܀ÑIÉÌPÌƣǨģ½ÁˆÜPÒxÄ3Ò1ÁÓDŽï óÐ×H̨ƨ£ÄƽÜYÂEÌˆÂ¨ÑÎÆHÌÝÁÓË ÆÑÓÄÐÂxLjÃWÃḦ£ÛÎÜÈÂÐѐÒxÌ3Ñ1ÀPÆàҀÇÝÛ3ҀÇèÁ1Û ï ó £ÄWÄHňÆàрÉÌPÌÆÓÇ£ Ä ˆÁ½ÜPÒxÄ3Ò£Á£ÇÐÁHÍÝÁ£Ë ÁÌÂÑΙï ï %Ð g“ ÐÆPÍUÉ)ˆÃ£ÄƬñIú¬÷ ó€öˆ Á WÆˆÜ ÄHňÆàѐÒÓ̽ÑHÀHÆÐҀÇÐÄ1ŽÆUÛÎÒILjÐÁ1ÛWĨÁcÄHŽÆàÑIÉÌPÌƣǨģ½ÁˆÜPÒxÄ3Ò1ÁÓÇ ó ÁH̀ÄHňÆWÁ£Ë ƈÑxÄU˽ÆҀ§ Ç !UĐ̈¨ Ñ ÎÆPßï ï ÌˆÂ¨ Ñ ÎÆHÌ ØÌ¨Á ƈÑÓĽÒHÀHÆ Use your new class in conjunction with the class to ï write a program that graphically depicts the flight of a cannonball. Your new class will keep track of the various using a quantities that are needed to compute a line of regression (the running sums of “ . predict Accepts a value of “ as a parameter. The regression class should have the following methods: – – init Creates a new regression object to which points can be added. and returns the value of the corresponding on the line of best fit. Note: Your class might also use some internal helper methods to do such things as compute the slope of the regression line. 17. and “ ). – . Redo the regression problem from Chapter 8 (Programming Exercise 13)  ˆÆg!P̨ƽܐÜHÒ1ÁÓÇ class. . Advanced: Add a class to the cannonball program from the previ¦ ous problem. A target should be a rectangle placed at a random position at the bottom of the window. addPoint Adds a point to the regression object. “ µ . Allow users to keep firing until they hit the target.

’ To be familiar with the functions and methods available for manipulating Python lists. É!É { . If you think about the kinds of data that most real-world programs manipulate. ’ To be able to write programs that use lists and classes to structure complex data. classes are one mechanism for structuring the data in our programs. ’ To understand the use of Python dictionaries for storing nonsequential collections. A few examples of the collections that you might find in a modern program include: ’ Words in a document. ’ To be able to write programs that use lists to manage a collection of information. are not enough to satisfy all of our data-handling needs. Classes alone. however.QSRUTWVYXa`cb dWd 1 rò¨ r ¤ ¥ ©m©H —Æ Ш§¥¥§¦m x€y31‚„ƒ†…ˆ‡‰„‚„‘ ’ To understand the use of lists (arrays) to represent a collection of related data. “„“•”–“ egf„i•›¥¤•j ‚m—˜gI™²y•j ‚h›³²È©a‡p›¥¤•j ‚ ©£…i„…ˆ‡‘…‡ƒ¬‘ As you saw in the last chapter. you will quickly realize that many programs deal with large collections of similar information.

but the program itself does not keep track of what numbers were entered. Back in Chapter 8. That’s all that’s needed to compute the mean. but two other standard statistical measures—median and standard deviation —of the data. 9. ’ Customers of a business. Let’s start with a simple example: a collection of numbers. ’ Graphics objects drawn on the screen. This is the value that splits the data set into equal-sized parts. You are probably familiar with the concept of a median. we wrote a simple but useful program to compute the mean (average) of a set of numbers entered by the user. it just keeps a summary of the numbers in the form of a running sum. 4. the median value is 6. Instead.”I”€â s4tvuxwzy|{I}†~I~xüé@u†y–uqs‚g± ± { ³ y 6 ‚HŠ†ˆ ’ Students in a course. 6. Just to refresh your memory (as if you could forget it). 13. ’ Data from an experiment. here is the program again: óÐÂW¨ÆHÌÂg!¨ÆgdŸïbÏ Ã¨ÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ÜIÉ1ÊÿßÝÕnïðÕ Ñ1ÁÓɐÇĀßàÕ ¦CţĐÌÝ߀̈ÂÓÛm̨ҀǩPÉĉñ  ÇĨÆHÌcÂÈǐÉHʨ˽Æ1Ì ñ ÇĨÆHÌ ( ÄÁ¥í£É4ÒÓÄÎú (©( Ó  ú G F G ÛPÅÎÒHÀP£ Æ ¦CÅ1ÄPÌ pA ß )@÷ ¦Wßà Æ WˆÂPÀ¬ë ñ ¦cÅ1ÄPÌ4ú ÜIÉHÊÿßÿ܇ÉHÊÿá ¦ Ñ1Á£ÉPÇÄWßÿÑ£Á£ÉÇ¨ÄWá Ö ¦CÅ1ÄPÌWßẄÂÓm Û ÌÒI© Ç PÉĄñ" ÇÄÆ1ÌcÂUÇPÉHʨ˽ÆHÌòñ ÇĨÆHÌ ( ÄÁ¥í1ÉÎÒÓÄÎú (©( G FG ̽ҀÇ Ä  Óc Ç HňÆW  W¨ÆḦ  !¨Æ€ÁH̀ÄHňÆÈǐÉHʨ˽Æ1ÌÎÜcҐ% Ü Îõ܇ÉHÊϟÐÑ£Á£ÉÇ¨Ä í´ Óú Ê4¨ҀÇoñIú This program allows the user to enter a sequence of numbers. ’ Cards in a deck. you will learn techniques for writing programs that manipulate collections like these. since there are two values greater than 6 and two . For the data 2. In this chapter. Suppose we want to extend this program so that it computes not only the mean.

the standard deviation is larger. The numerator of the fraction is the sum of the deviations (squared) across all the data values. we need a way to store and manipulate an entire collection of numbers. For example.~€~€ rHÕæw€w± ç 6 Š† ¾ 6 ˆ–y|ˆ ”I”€é that are smaller. some teachers define an “A” as any score that is at least two standard deviations above the mean. . “'r represents the ith data value and ø is the numn ber of data values. the mean of this data (“ ) is 6. 4. but it is not hard to compute. then the standard deviation is small. When the data is more spread out. is defined as “ “ ‚ “I†‰“§rb„ µ º¿¾ p øç†V… n In this formula “ is the mean. You can see how the first step of this calculation uses both the mean (which can’t be computed until all of the numbers have been entered) and each individual value as well. and 13. because we don’t know how many numbers there will be. The standard deviation is a measure of how spread out the data is relative to the mean. . If we again use the values 2.8. Computing the standard deviation this way requires some method to remember all of the individual values that were entered. “„“•”–• ÖY¤•¤•j 턇peŸš ¼™‡‘…¨‘ In order to complete our enhanced statistics program.1. The expression ‚ “Ɔ§“ r „ µ is the square of the “deviation” of an individual item n from the mean. If the data is tightly clustered around the mean. 9. So the numerator of the fraction is computed as ‚bi©h –†f¡„ µ  '& n ‚bi©h –†‰)„ µ  '& ‚bi©h 1†æi„ µ  '& ‚bi©h –†$€„ µ  '& ‚bi©h –†V…uy„ µ º '& …Xg€©hi Finishing out the calculation gives us “ …Xg€©hi º ¾ x †`… º 7 y‡)h  º i©h‘… … The standard deviation is about 6. Let’s take a simple example. The standard deviation. One way to calculate the median is to store all the numbers and put them in order so that we can identify the middle value. 6. The formula looks complicated. The standard deviation provides a yardstick for determining how exceptional a value is. We can’t just use a bunch of independent variables.

and the individual items in the sequence can be accessed through subscripting. almost. For instance. Take a look at these interactive examples: Ç !¨Æ¬ñ€Ö€Õ3ú (©()( ̈Âx§ û ՉõªÖ“õ Ôæõ Þ„Æ õ do˜ õ 9æõ ø„õ þ„Ô õ e‰õ ) ý  Ç !Ÿïôq Ü 3À¨ÒÓĉñ X1Å4ÒÜ ÒÜUÂÓÇ¡g Æ ¦C¨"½Â1ÌPÌÁHj Ä uÓú (©()( ÜxÄPÌ3ҀC û fHÅÎÒ¨Ü Põ †ÒÜ Põ ôÂxÇ õ –) Æ ¦c¨"½Â1̨̐ÁHj Ä  ¡  © # © # ‘ ž ¸ Qlnsutus5–Bw £Ú 3 Both of these familiar functions return a collection of values denoted by the enclosing square brackets. but we haven’t discussed the details. Mathematicians sometimes give an entire sequence of items a single name.” ¯ 7 s4tvuxwzy|{I}†~I~xüé@u†y–uqs‚g± ± { ³ y 6 ‚HŠ†ˆ What we need is some way of combining an entire collection of values into one object. We don’t have a way of typing subscripts. we’ve already done something like this. Actually. Ü Suppose that our sequence is stored in a variable called . For example. With a list. In fact. a sequence of ø numbers might just be called À : À º When they want to refer to specific values in the sequence. the ideas and notations that we use for manipulating lists are borrowed from the mathematical notion of sequence. We could write a loop to calculate the sum of the items in the sequence like this: ÜIÉ1ÊÿßÝÕ Í¨Á1ÌÿÒWҀÇà̈Âx§ Ç !ÆæñðÇ@ú¬÷ ÜIÉ1ÊÿßÿÜIÉHÊÿá Ü û Ò  . ÊBÊ'ȑÇÈƒÊ j› g¤ “ë“H– Cs As you know. the first item in the sequence is denoted with the subscript w . Well. These are lists. . we can use a single variable to represent an entire sequence. In this example. but we use indexing instead. Python lists are ordered sequences of items. these values are denoted by subscripts. ¹ By using numbers as subscripts. mathematicians are able to succinctly summarize computations over items in the sequence using subscript variables. of course. the sum of the sequence is written using standard summation notation as “ q “ q “ q “ q Uq “ t ¹ ¶ µ ¸ žh‡h‡h ·B¶ “ t “ Á ·B¶ ¹ r r¡Â A similar idea can be applied to computer programs.

You can mix arbitrary data types in a single list.~€~€ rHÕæw€w± ç 6 Š† ¾ 6 ˆ–y|ˆ ” ¯ ~ Virtually all computer languages provide some sort of sequence structure similar to Python’s list. in other languages. To summarize. ÊBÊ'ȑÇÈ‘Ç ¸ °Ÿ Qlnsut IÍ'i•“H–§tqlnvxw%s Because lists are sequences. To jog your memory. Python lists are dynamic. If you don’t know how many items you will have. You can have an array of ints or an array of strings but cannot mix strings and ints in a single array. Arrays in other programming languages are generally fixed size. Python lists are mutable sequences of arbitrary objects.. it is called an array. In a nutshell. They are also heterogeneous. you have to specify how many items it will hold. û Ü Ò  ). and keep track of how many “slots” you actually fill. here’s a summary of those operations: Operator Ó seq 0 + Ó seq 0 Ó seq 0 * Ó int-expr 0 Ó seq 0 [ ] len( Ó seq 0 ) Ó seq 0 [ : ] for Ó var 0 in Ó seq 0 : Ó expr 0 in Ó seq 0 Meaning Concatenation Repetition Indexing Length Slicing Iteration Membership check (Returns a Boolean) Except for the last (membership check). these are the same operations that we used before on strings. They can grow and shrink on demand. a list or array is a sequence of items where the entire sequence is referred to by a single Ü name (in this case. then you have to allocate a large array. Here are a couple of quick examples checking for membership in lists and string: û ֓õ–Ô‰õèބõ¡d) (©()( ÀˆÜ€ÄÝß à Þ € Ò Ç ˆ À € Ü Ä (©()( Ì1É½Æ . ) and individual items can be selected by indexing (e. When you create an array. just in case. you know that all of the Python built-in sequence operations also apply to lists. In contrast.g. Arrays are also usually homogeneous. That means they are restricted to holding objects of a single data type. The membership operation can be used to see if a certain value appears anywhere in a sequence.

” ¯ r (©()( (©()( Ì1É½Æ (©()( 9ÐÒ€Ç s4tvuxwzy|{I}†~I~xüé@u†y–uqs‚g± ± { ³ y 6 ‚HŠ†ˆ ÀˆÜ€Ä DˆÂPÀˆÜÓÆ ÂÓÇ4Ü ß ÂÓÇ4Ü€Ò€Ç | l“l“   PÏ By the way. Don’t attempt this in other languages! As you know. Python lists are very flexible. You can use assignment to change the value of items in a list. the summing example from above can be written more simply and clearly this way: ÜIÉ1ÊÿßÝÕ Í¨Á1  Ì ¦¡Ò€Ç Üæ÷ ÜIÉ1ÊÿßÿÜIÉHÊÿá ¦ Recall that one important difference between lists and strings is that lists are mutable. is a list containing no items at all—an empty list. lists can be created by listing items inside square brackets. This example creates a list containing 50 zeroes: . since we can iterate through lists. ÁPÃPÃ3Ü ß û ֓õ ބî õ 9æõ þ„õ ) ý  ͨÁPÁPÃWß û Óq Ü ½Â€{ Ê Χ õ v) Æ !©!½% Ü 3 õ z˽Â Ñ Î€Ë3ÂÑ£Á£x Ç ž ÜPÒ1ÀÀ£ÏWß û ֓è õ xq Ü ½Â€Ê 3ç õ doè õ ô Ù X Æxc Ê ÄPÏWß û  ÆxÊC¨ÄÏ In the last example. A list of identical items can be created using the repetition operator. it’s even possible to change an entire subsequence in a list by assigning a list into a slice. û ֓õ Ôæõ ބõÔd© (©()( ÀˆÜ€ÄÝß Þ  (©()( ÀˆÜ€Ä û g d ÀˆÜ€Ä û Þg€ßA3¢ƨÀPÀPÁ' (©()( ÀˆÜ€Ä û Ö@õ ԉõ މõ f¢ˆÆÀÀHÁ ¡ (©()( ÀˆÜ€Ä û Ô€ßÝþ (©()( ÀˆÜ€Ä û Ö@õ ԉõ þ‰õ f¢ˆÆÀÀHÁ ¡ û uŐÀÒPÑ1ÆBÎõ Ú P Ü ÜPÒ !£ÇHÊ3Æ£ÇÄ6ž (©()( ÀˆÜ€Ä û ֆ÷ðÞgcß (©()( ÀˆÜ€Ä û Ö@õ ëÅPÀÒÑ£Æ Põ Ú ÜÜHÒ !1Ç1ÊÎÆÓÇÄ Põ p¢ˆÆ¨ÀPÀPÁ ¡ (©()(  }  }  } ž  ž f As the last example shows.

Deletes the first occurrence of x in list.index(x) list 0 . is being used as an accumulator. Insert x into list at index i. Reverse the list. Returns index of first occurrence of x.sort() Ó Ó Ó list 0 . Deletes the ith element of the list and returns its value. The following table briefly summarizes some things you can do to a list: Ó Method list 0 . and each time through the loop a new value is tacked on. Here is a fragment of code that fills a list with positive numbers typed by the user: ǐÉ1Ê†Ü ß û  ¦WßÿҀ) Ç Éĉñ ÇĨÆH̀ÂÈǐÉHʨ˽Æ1̙÷ Œú G ÛPÅÎÒHÀHE Æ ¦ ( ßÝÕn÷ ǐÉ1ʆÜæïð"  )½Æ£ÇÃ‰Ò ñ ¦Îú ¦WßÿҀ© Ç PÉĉñ  ÇĨÆH̀ÂUÇPÉHʨ˽ÆH̟$ ÷ £ú  Ž G ǐÉHÊ“Ü In essence.~€~€ rHÕæw€w± ç 6 Š† ¾ 6 ˆ–y|ˆ ” ¯ ” h ¨Æ1ÌÁPƽÜYß û Õg@YT9PÕ Â )½Æ£Çà " Often lists are built up one piece at a time using the method. û ބõv֓õHdoõ‡Ö@õë9æõ–ý) (©()( ÀˆÜ€ÄÝß ˆ À € Ü ™ Ä è ï   ©  ˆ  ƣLjÃæñ†Ôˆú (©()( (©()( ÀˆÜ€Ä û މõªÖ“Æ õ d„õªÖ“î õ 9‰õ ý‰õ g Ô  (©()( ÀˆÜ€Ä™ïzÜÓÁHÌPĄñIú (©()( ÀˆÜ€Ä û Ö@õªÖ“õ Ôæõ Þ„Æ õ do˜ õ 9æõ ) ý  Æ W¨ÆHÌÎÜÓÆæñ‡ú (©()( ÀˆÜ€Ä™ïp̨g . Returns the number of occurrences of x in list.reverse() list 0 . Sort (order) the list. The accumulator starts out empty.pop(i) Ó Meaning Add element x to end of list.count(x) list 0 .  ©ˆÆ£ÇˆÃ  method is just one example of a number of useful list-specific The methods. The best way to become comfortable with these methods is simply to try them out in an interactive session.append(x) Ó list 0 .insert(i.remove(x) Ó list 0 .x) Ó list 0 . A comparison function may be passed as parameter.

. from a list using the Ï ¤3Ò¨Ü€Ä (©()( ʽ) ûg Þ doõ ÔHø„õ ՄõªÖ€) Õ  Ï ¤½Ò¨Ü€Ä û q Ö  (©()( èƐÀ ʽ© Ï ¤3Ò¨Ü€Ä (©()( ʽ) ûg Þ doõ ՉõªÖx) Õ  Ï ¤½Ò¨Ü€Ä û ֆ÷ðg Þ  (©()( èƐÀ ʽ© Ï ¤3Ò¨Ü€Ä (©()( ʽ) û Þgd© èƐÀ Notice that is not a list method. which contents of the list in some way. Python lists provide a very flexible mechanism for handling arbitrarily large sequences of data. Lists can also shrink when items are deleted. instead they change the Ñ1ÁÓɐÇÄ ÒILjÐÆ)¦ and .” ¯€¯ ÀˆÜ€Ä û ý‰õî9‰õÆd„õ ބõ ԉõ Ö@õªÖ (©()( ÀˆÜ€Ä™ïôÒILjÐÆ)¦‰ñÒdÎú (©()( s4tvuxwzy|{I}†~I~xüé@u†y–uqs‚g± ± { ³ y 6 ‚HŠ†ˆ Ô ÀˆÜ€Ä™ïôÒIÇ@ÜÓÆH̐ĉñëd„õ3¢ƨÀPÀPÁ'Óú ÀˆÜ€Ä û ý‰õî9‰Æ õ d„õ ބõ f¢ƨÀPÀPÁ Põ ԉõªÖ@õªÖ (©()( ÀˆÜ€Ä™ïôÑ£Á£ÉPÇĄñIÖPú (©()( (©()(  }  } Ô Þ ÀˆÜ€Ä™ïp̨ÆxÊ3ÁgWƬñ€ÖHú (©()( ÀˆÜ€Ä û ý‰õî9‰Æ õ d„õ ބõ f¢ƨÀPÀPÁ Põ ԉõªÖq ï ˆÁ oñzÞ3ú (©()( ÀˆÜ€Ä™U (©()( (©()( À Ü€Ä ˆ û ý‰õî9‰õÆd„õ  } f¢ˆÆÀÀHÁ õ˜Ô‰õªÖ Note that most of these methods do not return a value. The exceptions are ˆÁ  return a value but do not change the list. and . As you can see. Using lists is easy if you keep these basic principles in mind: ’ A list is a sequence of items stored as a single object. but a built-in operation that can be used on list items. Individual items or entire slices can be removed èƐÀ operator. which both returns a value and changes the list. We have seen how lists can grow by appending new items.

we can get a list of numbers from the user with a single line of code.~€~€ rHÕæw€w± ç 6 Š† ¾ 6 ˆ–y|ˆ ’ Items in a list can be accessed by indexing. ÊBÊ'ȑÇÈ‘É Ø tu–mtqlnsutql‡œ©s5o lŒt ” ¯ ´ )  ¸ %lnsqtus Now that you know more about lists. The list will then be returned from the function. ’ Lists are mutable. median. Let’s start by using lists to rewrite our original program that only computes the mean. This function will implement the basic sentinel loop from our original program to input a sequence of numbers. ÊÎƐÂÓÇ ÜxĐà g Æ W ÊÎÆHýÒ1ÂÓÇ . we are ready to solve our little statistics problem. ãĈÂc¥ ß !ÆH© Ä Ð1ÉHʨ˽ÆHÌ3ܓñ‡ú . First. . we need a function that gets the numbers from the user. and sublists can be accessed by slicing. individual items or entire slices can be replaced through assignment statements. ’ Lists will grow and shrink as needed. Recall that we are trying to develop a program that can compute the mean. and standard deviation of a sequence of numbers entered by the user. We will use an initially empty list as an accumulator to collect the numbers. One obvious way to approach this problem is to store the numbers in a list. !ÆH© Ä Ð1ÉHʨ˽ÆHÌ3Ü : Here’s the code for èÆH¥ Í !¨Æ1© Ä ÐHÉ1ÊˈÆHÌÎÜ@ñIú­÷ ǐÉ1Ê†Ü ß û  ó ÜxÄÂ1ÌPÄcÛÎÒxÄHÅÿÂÓǡƀC Ê ¨ÄÏÐÀ¨Ò¨ÜxÄ u óÿÜ£ÆÓÇÄ3ÒIǽƐÀ€ÀPÁPÁ ÐÄÁT!ÆHÄcÇPÉHÊˈÆHÌ3Ü ¦CţĐÌÝ߀̈ÂÓm Û Ì¨Ò€© Ç PÉĉñ  ÇĨÆHÌcÂÈǐÉHʨ˽Æ1Ì ñ ÇĨÆHÌ ( ÄÁ¥í£É4ÒÓÄÎú (©( Ó  ú G F G ÛPÅÎÒHÀP£ Æ ¦CÅ1ÄPÌ pA ß )@÷ ¦Wßà Æ WˆÂPÀ¬ë ñ ¦cÅ1ÄPÌ4ú ǐÉHʓÜæïð"  ©ˆÆ£ÇÉë ñ ¦3ú óàÂ1ÐÀÄHÅÎÒ¨§ Ü WÀxɽÆcÄÁcÄ1ŽÆÝÀ¨Ò¨ÜxÄ ¦CÅ1ÄPÌWßẄÂÓm Û ÌÒI© Ç PÉĄ" ñ  ÇÄÆ1ÌcÂUÇPÉHʨ˽ÆHÌòñ ÇĨÆHÌ ( Ä¥ Á í1ÉÎÒÓÄÎú (©( G FG ÌÆ1ÄHÉÌ1ǀǐÉ1栆 Óú Using this function. ’ Lists support a number of convenient and frequently used methods. Let’s !¨Æ1© Ä ÐHÉ1ÊˈÆHÌÎÜ call it . and —that take a list We can write a series of functions— of numbers and calculate the corresponding statistics.

With these two functions. our original program to average a series of numbers can now be done in two simple lines: èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ãĈÂcߥ!¨Æ1Ä©Ð1ÉHÊˈÆHÌ3ܓñIú ̽ҀÇÄ HHňÆYÊÎƐÂÓÇ Ò¨Ü õ Ê3ƨÂxÇnñôèÂ1Ľú — ’ ÜxĐà g Æ W Next. In order use the standard deviation formula discussed above. let’s tackle the standard deviation function. we first need to compute the mean. We have a design choice here. let’s implement a function that computes the mean of the numbers in a list. Which way should we do it? ܀Ĩà g Æ W On the one hand. . èÆHÍ ÊÎƐÂÓÇnñùǐÉ1ʆܨú­÷ ÜIÉ1ÊÿßÝÕnïðÕ Í¨Á1ÌcǐÉHÊ ÒIÇWǐÉ1ʆÜæ÷ ÜIÉHÊÿßÿ܇ÉHÊÿácǐÉ1Ê ÌÆ1ÄHÉÌ1Ç ÜIÉ1Ï Ê ŸWÀPÆÓÇnñðÇPÉHʓܨú Notice how the average is computed and returned in the last line of this function. Since our program is going to output both the mean and the standard deviation. If our data set is large. The value of the mean can either be calculated ܀Ĩà ˆg Æ W inside of or passed to the function as a parameter. calculating the mean inside of seems cleaner. Computing it again inside of results in the calculations being done twice. we just call and pass it the list of numbers. ÀPÆ£Ç The operation returns the length of a list. we don’t need a separate loop accumulator to determine how many numbers there are. Other options are explored in the exercises at the end of the chapter. We will use a loop to go through the list and compute the sum. This function takes a list of numbers as a parameter and returns the mean. as it makes the interface to the function simpler. To get the standard deviation of a set ܀Ĩà ˆg Æ W of numbers.” ¯ ¹ s4tvuxwzy|{I}†~I~xüé@u†y–uqs‚g± ± { ³ y 6 ‚HŠ†ˆ Next. this seems inefficient. proanalogous to how grams that need to compute the standard deviation will almost certainly need ÜxĐà g Æ W to compute the mean as well. let’s have the main program compute the mean and pass it as a parameter ÜxĨà ˆ Æ W . to ¦1˽Â1Ì Here is the code to compute the standard deviation using the mean ( ) as a parameter: u 3 3 u u 3 èÆHÍÿÜxĐà ˆÆW„ñùǐÉHʓܭõI¦1˽Â1Ì4ú­÷ ÜIÉ1Ê ˆ Æ W§ÅícßÐÕnïùÕ u  é . On the other hand. This is exactly ÊÎƐÂÓÇ ÊÎÆPÈÒHÂxÇ (and below) works.

as we do not have a formula to calculate the median. To test whether the size is tage of the even. the median is determined by averaging the two middle values. We can take advanÜÓÁHÌÄ method to put the list in order. Once this sum has been computed. we need to see if it is divisible by two. èÆHÍ ÊÎÆHýÒHÂxÇnñùǐÉHʓܨú­÷ ǐÉ1ʆÜæïôÜ£Á1̐Ąñ‡ú ÜPÒ ¨Æ€ßÐÀPÆÓÇnñùǐÉHʓܨú ʓÒÓÃPØÁˆÜYßÿÜPÒ ¨  Æ ŸÝÔ Ò£ÍÿÜHÒ ¨Æ ÐԀßPßÝÕn÷ ÊÎÆPÈÒHÂxÇÐß ñðÇPÉH栆 û Ê@Ò£ÃPبÁ½ Ü cáUǐÉ1栆 û ʓÒÓÃPبÁ½ Ü ¨½ Ö 3§ ú ŸWԄïðÕ Æ¨ÀÜ£Æn÷ ÊÎÆPÈÒHÂxÇÐßUǐÉ1栆 û ʓÒÓÃPØÁˆÜ" ÌÆ1ÄHÉÌ1ÇUÊÎÆHýÒ1ÂÓÇ !h ž" )h !h #" )h . There is just one small complication. the last line of the function calculates the rest of the formula. 6. So the median of 3. º  In pseudocode our median algorithm looks like this: Ü£Á1̐ÄWÄ1ŽÆÈǐÉ1ÊˈÆHÌÎÜÈҀǨÄÁ݈ÜHÑ1ÆÓLjýÒI§ Ç !cÁH̨ÐÆHÌ Ò£Í€Ä1ŽơÜHÒ ¨ÆWÁHÍ Ã¨Â1ĈÂWÒ¨ÜÈÁPÃPß÷ ÊÎÆHýÒHÂxÇÐ߀ÄHňÆYʓÒÓÐÃÀH£ Æ WˆÂPÀÓÉˆÆ Æ¨ÀÜ£Æo÷ ÊÎÆHýÒHÂxÇÐ߀ÄHňÆÝ  W¨ÆḦ  !¨Æ€ÁH̀ÄHňÆcÄPۈÁYÊ@Ò£ÃPÃÀP` Æ WˆÂÀxÉ½ÆˆÜ ÌÆ1ÄHɨÌHÇUÊ3ÆPýÒ1ÂÓÇ é !h This algorithm translates almost directly into Python code. we come to the function. there is no exact middle number. The size is even if . The variable stores the running sum of the squares of the deviations. and 9 is ‚bx i„¡ýÓ¡ x©hx . This one is a little bit trickier. This is a perfect application of the ÜPÒ Æ àÔcߐßÝÕ remainder operation. that is. by definition. With these insights. dividing by 2 leaves a remainder of 0. We need an algorithm that picks out the middle value. Whatever value ends up in the middle of the pack is. we are ready to write the code. The first step is to arrange the numbers in increasing order. In that case. If we have an even number of values. 5. the median.~€~€ rHÕæw€w± ç 6 Š† ¾ 6 ˆ–y|ˆ ͨÁ1ÌcǐÉHÊ ÒIÇWǐÉ1ʆÜæ÷ èÆgWÝߥ¦£Ë3£Ì@¨ ǐÉHÊ ÜIÉHÊ ˆ Æ W§ÅgíUß ÜIÉHÊ ˆÆW§ÅgíUáÝèÆgWaYÈÐÆgW ÌÆ1ÄHÉÌ1Ç " Ü íH̐ĉñ‡ÜIÉ1Ê g Æ W§ÅíCŸ­ñ†ÀPÆÓÇnñùǐÉHʓܨú¨3ÖHúú ” ¯ ¿  é  Notice how the summation from the standard deviation formula is computed ܇ÉHÊ ÆgWCÅgí using a loop with an accumulator. Ê3ÆPýÒ1ÂÓÇ Finally.

” ¯ â s4tvuxwzy|{I}†~I~xüé@u†y–uqs‚g± ± { ³ y 6 ‚HŠ†ˆ You should study this code carefully to be sure you understand how it selects the correct median from the sorted list. Now that we have all the basic functions. 2. 1. then is 1 (2 goes into 3 just one time). 3. This is the correct middle position. 2. Here’s the complete program: óÿÜxÄÂ1Ä3ÜæU ï ¨Ï ÍP̨ÁxÊWÊÎÂ1ÄHÅÿ҇C Ê ˆÁHÌPÄÿ" Ü íHÌÄ |  èÆHÍ¥!¨Æ1Ä©ÐHÉ1ÊˈÆHÌÎÜ@ñIú­÷ ǐÉ1Ê†Ü ß û  ó ÜxÄÂ1ÌPÄcÛÎÒxÄHÅÿÂÓǡƀÊC¨ÄÏÐÀ¨Ò¨ÜxÄ Óú óÿÜ£ÆÓÇÄ3ÒIǽƐÀ€ÀPÁPÁ ÐÄÁT!ÆHÄcÇPÉHÊˈÆHÌ3Ü ¦CţĐÌÝ߀̈ÂÓm Û Ì¨Ò€© Ç PÉĉñ  ÇĨÆHÌcÂÈǐÉHʨ˽Æ1Ì ñ ÇĨÆHÌ ( ÄÁ¥í£É4ÒÓÄÎú G F G ÛPÅÎÒHÀP£ Æ ¦CÅ1ÄPÌ pA ß )@÷ ¦Wßà Æ WˆÂPÀ¬ë ñ ¦cÅ1ÄPÌ4ú ǐÉHʓÜæïð"  ©ˆÆ£ÇÉë ñ ¦3ú óàÂ1ÐÀÄHÅÎÒ¨§ Ü WÀxɽÆcÄÁcÄ1ŽÆÝÀ¨Ò¨ÜxÄ (©( . since the three values in the list will have the indexes 0. In this case. èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇÄ HHÅÎÒ¨ Ü ¨Ì) Á !ḦÂIÊ Ñ1Á€C Ê PÉÄƈÜÊÎƐÂÓǟõ ÊÎÆHýÒHÂxÇ¡ÂÓÇÃÿÜxÄÂÓLjèÂ1̐Àè Æ W3ÒH£Ä3Ò£Á£Ç„ï !h !h !h — 3 ãĈÂcߥ!¨Æ1Ä©Ð1ÉHÊˈÆHÌ3ܓñIú ¦1˽Â1ÌÝß ÊÎƐÂÓÇoñôãĈˆú ÜxĐÃWßÿÜxĨà ˆ Æ W„ñôèÂ1ĉ° õ ¦£Ë3£Ì4ú ÊÎÆHÃWß ÊÎÆPÈÒHÂxÇnñôèÂ1Ľú 3 ̽ҀÇÄ ̽ҀÇÄ ̽ҀÇÄ — Q ´ — — HHňơÜxÄÂÓLjèÂ1̐ÃcèÆW3Ò1Â1Ä3Ò£Á£Ç HHňÆYÊÎÆHýÒHÂxÇ ÓÇcHÅˆÆ ÊÎƐÂÓÇ Ò¨Ü õƦ£Ë3Â1Ì Ò¨Ü õ Ê3ÆPà ’ ’ ÒÜ Põ ÜxĐà © Many computational tasks from assigning grades to monitoring flight systems on the space shuttle require some sort of statistical analysis. The correct median is found by averaging the values ʓÒÓÃPØÁˆÜ ʓÒÓÃPبÁ½ Ü ¨½Ö at (2) and (1). The middle position of the list is calculated using integer division as ÜHÒ Æ ʓÒÓÃPØÁˆÜ If is 3. 1. will be 2. we can make our code useful as a standalone program and as a general statistical library module. ÜHÒ Æ ʓңÃHØÁˆÜ Now suppose is 4. ÜHÒ Æ¥ŸÝÔ . and the four values will be in locations 0. By using the Ò£Í Ç3€Ê3Æ ßPß ÊÎÂÒ€Ç technique. finishing out the program is a cinch.

~€~€ rHÕæw€w± ç 6 Š† ¾ 6 ˆ–y|ˆ ¦CÅ1ÄPÌWßẄÂÓÛmÌÒIÇ©PÉĄñ" ÇÄÆ1ÌcÂUÇPÉHʨ˽ÆHÌòñ G ÌÆ1ÄHÉÌ1ǀǐÉ1栆 ” ¯ é ÇĨÆHÌ ( FG ÄÁ¥í1ÉÎÒÓÄÎú (©( Óú èÆHÍ ÊÎƐÂÓÇnñùǐÉ1ʆܨú­÷ ÜIÉ1ÊÿßÝÕnïðÕ Í¨Á1ÌcǐÉHÊ ÒIÇWǐÉ1ʆÜæ÷ ÜIÉHÊÿßÿ܇ÉHÊÿácǐÉ1Ê ÌÆ1ÄHÉÌ1Ç ÜIÉ1Ï Ê ŸWÀPÆÓÇnñðÇPÉHʓܨú èÆHÍÿÜxĐà ˆÆW„ñùǐÉHʓܭõI¦1˽Â1Ì4ú­÷ ÜIÉ1Ê ˆÆW§ÅícßÐÕnïùÕ Í¨Á1ÌcǐÉHÊ ÒIÇWǐÉ1ʆÜæ÷ èg Æ WÝßUÇPÉHÏ Ê ¨T¦1˽Â1Ì ÜIÉHÊ ˆ Æ W§ÅgíUß ÜIÉHÊ ˆÆW§ÅgíUáÝèÆgWaYÈÐÆgW ÌÆ1ÄHÉÌ1Ç " Ü íH̐ĉñ‡ÜIÉ1Ê g Æ W§ÅíCŸ­ñ†ÀPÆÓÇnñùǐÉHʓܨ ú ¨3ÖHúú u  é  é  èÆHÍ ÊÎÆHýÒHÂxÇnñùǐÉHʓܨú­÷ ǐÉ1ʆÜæïôÜ£Á1̐Ąñ‡ú ÜPÒ ¨Æ€ßÐÀPÆÓÇnñùǐÉHʓܨú ʓÒÓÃPØÁˆÜYßÿÜPÒ ¨  Æ ŸÝÔ Ò£ÍÿÜHÒ ¨Æ ÐԀßPßÝÕn÷ ÊÎÆPÈÒHÂxÇÐß ñðÇPÉH栆 û Ê@Ò£ÃPبÁ½ÜcáUǐÉ1栆 û ʓÒÓÃPبÁ½Ü¨½Ö3ú§ŸWԄïðÕ Æ¨ÀÜ£Æn÷ ÊÎÆPÈÒHÂxÇÐßUǐÉ1栆 û Ê“Ó Ò ÃPØÁˆÜ" ÌÆ1ÄHÉÌ1ÇUÊÎÆHýÒ1ÂÓÇ )h ) h !h #" èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇÄ HHÅÎҨܨÌÁ)!ḦÂIÊ — Ñ1Á€ÊCPÉÄƈÜÊÎƐÂÓǟõ ÊÎÆHýÒHÂxÇ¡ÂÓÇÃÿÜxÄÂÓLjèÂ1̐ÀèÆW3ÒH£Ä3Ò£Á£Ç„ï 3 ãĈÂcߥ!¨Æ1Ä©Ð1ÉHÊˈÆHÌ3ܓñIú ¦1˽Â1ÌÝß ÊÎƐÂÓÇoñôãĈˆú ÜxĐÃWßÿÜxĨà ˆ Æ W„ñôèÂ1ĉ° õ ¦£Ë3£Ì4ú ÊÎÆHÃWß ÊÎÆPÈÒHÂxÇnñôèÂ1Ľú 3 ̽ҀÇÄ ̽ҀÇÄ ̽ҀÇÄ — Q  ´ — — ÓÇcHÅˆÆ ÊÎƐÂÓÇ Ò¨Ü õƦ£Ë3Â1Ì HHňơÜxÄÂÓLjèÂ1̐ÃcèÆW3Ò1Â1Ä3Ò£Á£Ç HHňÆYÊÎÆHýÒHÂxÇ Ò¨Ü õ Ê3ÆPà ’ ’ ÒÜ Põ ÜxĐà © .

Let’s write a program that sorts a file of students according to their GPA. ü Æ1ÄWÄHňÆÈÇ3€Ê3ƀÁPÍWÄ1ŽÆàҀ) Ç É¨ÄWͽÒ1ÀPƀÍP̨ÁxÊàÄ1ŽÆÈÉ4Ü£ÆHÌ  ˆÆÂHÃÿ܀ÄHɈÐƣǨÄàҀÇͨÁ1Ì£Ê4£Ä3Ò£Á£ÇÿÒIÇĨÁÝÂWÀÒ¨Ü€Ä ÅPÁ1̐ÄWÄ1ŽÆÝÀҐÜxÄUË¨Ï ü Ø Ú ü Æ1ÄWÄHňÆÈÇ3€Ê3ƀÁPÍWÄ1ŽÆWÁ£É¨g Ä PÉÄW͈ÒHÀPÆUÍPÌÁ€Ê¡ÄHňÆÈÉ@Ü£Æ1Ì 4¨Ì½ÒÓĨÆUÄHňơÜxÄHÉèÆÓÇÄ¡ÒILjͨÁ1Ì£ÊÎÂ1Ä3Ò£Á£ÇWÍPÌÁ€ÊàÄHňÆÝÀҐÜxÄÿҀǨÄÁÝÂc͈ÒHÀPÆ Let’s begin with the file processing. One particularly useful application is storing a collection of records. And a GPA sort would be useful for deciding which students are in the top 10% of the class. it would be useful to have the file in order according to credit-hours. We might want the list in different orders for different purposes. An academic advisor might like to have a file with grade information sorted alphabetically by the name of the student. We want to read through the data file and create a list of students. Here’s a function that takes a filename as a parameter Å£ÄHÉÃ¨Æ£Ç¨Ä and returns a list of objects from the file: èÆH̀ÌƐÂHC à ţÄHÉèƣǨÄÎÜ@ñôͽÒ1ÀPÆÓÇ3€Ê3Æ3ú­÷ ҀÇͽÒHÀHÆcßÝÁ ˆÆ£ÇoñôͽÒ1ÀPÆÓÇ3€Ê3Ƅõ ðÌ vú ÜxÄ1ɈèÆÓÇÄ3Ü ß û  ͨÁ1ÌàÀҀLjÆÐҀǻÒILjͽÒ1ÀPÆo÷ ÜxÄHÉèÆÓÇÄÎܬïè  ©½ÆÓLjÃæñpÊ4"  Έ© Æ Å1ÄHÉÐÆÓÇÄæñ†À¨Ò€ÇÆ3úú ҀÇͽÒHÀHÆnï–ÑHÀPÁˆÜ£Æ¬ñIú ÌÆ1ÄHÉÌ1Ç ÜxÄ1ɈÐƣÇÄ3Ü ¤ … . We just need to borrow the program will make use of a list of Å1Ä1ɈÐƣÇÄ class from our previous program and add a bit of list processing. However. a list can be used to store collections of any type. We can illustrate this idea by building on the student GPA data processing program from last chapter. The basic algorithm for our program is very simple. To determine which students have enough credit hours for graduation. Recall that our previous grade processing program read through a file of student grade information to find and print information about the student with the highest GPA. The Å£ÄHÉˆÃÆ£Ç¨Ä objects. One of the most common operations performed on this kind of data is sorting.”I´7 Ò£ÍSÌ)ÌÓǽ€ÊÎÆ©Ì©ÌUßPß “„“•”– s4tvuxwzy|{I}†~I~xüé@u†y–uqs‚g± ± { ³ y 6 ‚HŠ†ˆ | ëÌ)̀Ê4¨ҀÇmÌ©Ì f ¨÷ŽÊÎÂҀÇoñIú ¼™‡‘…¨‘Йhì x€y31‚„ƒ†…¨‘ All of the list examples we’ve looked at so far have involved lists of simple types like numbers and strings.

We will have to be sure to import this Å1Ä1ɈèÆÓÇÄ function (along with the class) at the top of our program. чc Ê  Here are some examples showing how operates: Ê nñ€Ö@õôԈú (©()( чc ¨3Ö Ê nñ†Ôæõ‡ÖHú (©()( чc Ö Ê nñ ‡B  3 õ zx Ë £ú (©()( чc ¨3Ö ¹ ¹ . 0. credit hours. èÆHÍcۨ̽ÒÓÄ© Æ Å1Ä1ɈèÆÓÇÄ3ܓñ‡Ü€ÄHÉèƣǨÄÎ܆õ ͽÒ1ÀPƣǽ€Ê3Æ3ú¬÷ óÿÜxÄ1ɈèÆÓÇÄ3ÜcÒ¨ÜUÂÝÀҐÜxÄÝÁHS Í Å1Ä1ɈèÆÓÇÄÝÁÓË ÆˆÑÓÄ3Ü ï Á£É¨Ä¨Í½Ò1ÀPÆcßÝ" Á ½ÆÓÇnñô͈ÒHÀHÆ£Ç3ÂIÊÎƉõ pÛ vú ͨÁ1Ì Ü€Ò€Ç»ÜxÄ1ɈÐƣÇÄ3Üæ÷ Á£ÉĐͽÒ1ÀPÆnï|ۨ̽ÒÓÄƬñ  3Ü £Ä PÍ 1Ä PÍ Ó# Ç  ñ‡Ü¬f ï !ÆH© Ä Ð€Ê3ÆæñIú“õ ܬf ï !ÆH) Ä ¢Á£É¨ÌÎܓñ‡ú†õ Üæp ï !¨ÆHÄ 1بÁˆÒ€Ç¨ÄÎÜ@ñIúúPú Á£É¨Ä¨Í½Ò1ÀPÆoïôÑHÀHÁ½ÜÓÆæñIú Ž  G" 3´ %" ´ g" %´ °"  Notice that I used the string formatting operator to generate the appropriate line €Ä ‡Ç of output. The represents a tab character.~I~x ”P¾ 6 ˆ|y|ˆæ‚‡å6Ñ ‰Ê { ³ y|ˆ ”I´H~ This function first opens the file for reading and then reads line by line. and is the newline so that each student’s information occupies one line of the file. A 0 means that the two parameters are equal. What happens if we try to sort a list that contains something other than numbers? How does Python know what order to put things in? If we don’t tell Python any differently. it compares the items in the list using a special built-in чc Ê  чc Ê  function called . each line of the file should contain three pieces of information (name. The code to do this is straightforward. or 1 according to Python’s default ordering. ÜÓÁHÌÄ In the statistics program. it creates a ÜxÄ1ɈÐƣÇÄ object from a line of the file. Notice that ÊΠΈƩÅ1Ä1ɈèÆÓÇÄ ! 3 I am borrowing the function from the program. While we’re thinking about files. let’s also write a function that can write the list of students back out to a file. A result of -1 indicates that the first parameter comes before the second. All we have to do now is figure how to sort the records by GPA. and a 1 indicates that the first comes after the second. we used the method to sort a list of numbers. Remember. and quality points) separated by tabs. appendÜxÄHÉèÆÓÇÄÎÜ ing a student object to the list for each line of the file. The function takes two parameters and returns -1. we can easily conUsing the functions vert our data file into a list of students and then write it back out to a file. ÌƐÂHC à ţÄHÉèƣǨÄÎÜ Û¨Ì3ÒxÄ© Æ Å1ÄHÉèÆÓÇÄÎÜ and .

” In order to make the sorting work with our own objects. We do this by creating our own Ü£Á1ÌÄ custom compare function for student objects and then telling to use it when sorting the list. Here’s the completed code: ó !½ÂˆÜÓÁH̐ğU ¥ ï ¨Ï Ú ¨Ì) ó Á !ḦÂIÊàÄÁ¡ÜÓÁHÌÄ Ü€ÄHÉèƣǨġҀÇͨÁ1Ì£Ê4£Ä3Ò£Á£ÇàҀÇĨÁ ü Ø Ú ÁH̨ÐÆH̟ï ÍP̨ÁxÊa! 3  ÂÐ҇Êc½Á1̐ÄSÅ£ÄHɈÐƣǨÄnõ ÊΠ Î ÆcÅ1Ä1ɈÐƣÇÄ Ã¨ÆH̀ÌƐÂHÃCÅ£ÄHÉèƣǨÄÎÜ@ñôͽÒ1ÀPÆÓÇ3€Ê3Æ3ú­÷ ҀÇͽÒHÀHÆcßÝÁ ˆÆ£ÇoñôͽÒ1ÀPÆÓÇ3€Ê3Ƅõ ðÌ vú ¤ … . 0. or 1 depending on their relative чc Ê  function GPA ordering. Rather. the standard ordering uses general rules like “numbers always come before strings. I do not want to call the function. The easiest way to do this is just to use the built-in on the two student GPAs like this: èÆH͡чc Ê  ü Ø Ú ñvÜ֓õ Ü1Ԉú¬÷ ÌÆ1ÄHÉÌ1Ç Ñ‡c Ê nñvÜÖ­p ï !½Â¬ñIú“õ Ü£Ôop ï !3­ñIúPú Ü£Á1ÌÄ Now sorting our list of students is as easy as calling its method and чÊc ü Ø Ú ) as a parampassing the name of the appropriate comparison function ( èÂ1Ĉ eter. and it will call this function anytime it needs to compare two items to see what their relative ordering should be in the sorted list. I am sending чc Ê  ü Ø Ú ÜÓÁHÌÄ to the method. we need a function that takes two students as parameters and then returns -1. To order by GPA. we can sort it in GPA order with this line of code: ãĈ„ïzÜ£Á1̐ĉñvчc Ê  ü Ø Ú ú An important point to notice here is that I did not put parentheses on the funcчÊC ü Ø Ú ñIú tion name ( ). If is the list of students.”I´€r (©()( s4tvuxwzy|{I}†~I~xüé@u†y–uqs‚g± ± { ³ y 6 ‚HŠ†ˆ чÊcnñ€Ö@õfÖ­ïùÕ3ú чÊcnñ ‡  ÂB3õë9½ú Õ (©()( Ö The comparison function works pretty much as you would expect on all the compatible built-in types. we need to tell Ü£Á1ÌÄ how our objects should be compared. I think we now have all the components in place for our program. For types that aren’t directly comparable.

3Ò1 Æ Û3Ò1Æ£Û Remember the class from last chapter? In order to display the six ÎÒ£ÆgÛ½Ò1Æ1Û possible values of a die. . Let’s put these tools to work in some more sophisticated examples. etc. In the previous version. . each object keeps track of seven circles representing the position of pips on the face of a die. we 4q Ò †Ö 4 Ò ½Ô ÎÒˆÞ saved these circles using instance variables. .   .~I~€ ¯ cé4{zˆ 6 1Š 6 ŠŒ•’ 6 yèt«¾ 6 ˆ|y|ˆ‰uxŠŒ‹asB± uŒˆ–ˆp{ôˆ ÜxÄ1ɈèÆÓÇÄ3Ü ß û  ͨÁ1ÌàÀҀLjÆÐҀǻÒILjͽÒ1ÀPÆo÷ ÜxÄHÉèÆÓÇÄÎܬïè  ©½ÆÓLjÃæñpÊ4Â"ΈƩÅ1ÄHÉÐÆÓÇÄæñ†À¨Ò€ÇÆ3úú ҀÇͽÒHÀHÆnï–ÑHÀPÁˆÜ£Æ¬ñIú ÌÆ1ÄHÉÌ1Ç ÜxÄ1ɈÐƣÇÄ3Ü Ã¨ÆHÍcۨ̽ÒÓÄÆ©Å1Ä1ɈèÆÓÇÄ3ܓñ‡Ü€ÄHÉèƣǨÄÎ܆õ ͽÒ1ÀPƣǽ€Ê3Æ3ú¬÷ Á£É¨Ä¨Í½Ò1ÀPÆcßÝ" Á ½ÆÓÇnñô͈ÒHÀHÆ£Ç3ÂIÊÎƉõ pÛ vú ͨÁ1Ì Ü€Ò€Ç»ÜxÄ1ɈÐƣÇÄ3Üæ÷ Á£ÉĐͽÒ1ÀPÆnï|ۨ̽ÒÓÄƬñ  3Ü £Ä PÍ 1Ä PÍ ÓÇ# ñ‡Ü¬f ï !ÆH© Ä Ð€Ê3ÆæñIú“õ ܬf ï !ÆHÄ)¢Á£É¨ÌÎܓñ‡ú†õ Üæïp!¨ÆHÄ 1بÁˆÒ€Ç¨ÄÎÜ@ñIúúPú Á£É¨Ä¨Í½Ò1ÀPÆoïôÑHÀHÁ½ÜÓÆæñIú ”I´€” Ž  G" 3´ %" ´ g" %´ °"  èÆH͡чÊc ü Ø Ú ñvÜ֓õ Ü1Ԉú¬÷ óWÍ1ÉPÇ4ÑÓĽÒ1ÁÓÇÝÄHŽÂ1ÄÿÑ1Á€ÊC½Â1ÌÆˆÜ ÄHۈÁ¡ÜxÄ1ɈÐƣÇÄ3ܪË3ÂÜ£ÆHÃWÁ£Ç ÌÆ1ÄHÉÌ1Ç Ñ‡c Ê nñvÜÖ­p ï !½Â¬ñIú“õ Ü£Ôoïp!3­ñIúPú èÆHÍ ü Ø Ú ï Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ Ä XHÅÎҨܨÌÁ)!ḦÂIʻܣÁ1̐Ä3ÜWÜxÄHÉèÆÓÇÄ¥!ḦÂHÐÆÐҀÇͨÁ1Ì£Ê4£Ä3Ò£Á£ÇcË¨Ï ü Ø Ú Í½Ò1ÀPƣǽ€Ê3ÆUßẄÂÓm Û ÌÒI© Ç PÉĄ" ñ  ÇÄÆ1Ì ÄHŽÆÈǽ€Ê3ÆWÁP̀ÄHňƀãĈÂcͽÒ1ÀPÆo÷$£ú G ãĈÂc߀ÌƐÂHc à Å1ÄHÉèÆÓÇÄÎÜ@ñô͈ÒHÀPÆÓÇ3ÂIÊÎÆ3ú ãĈÂoïôÜ£Á1̐ĄñŒÑ‡c Ê  ü Ø Ú ú ͽÒ1ÀPƣǽ€Ê3ÆUßẄÂÓm Û ÌÒI© Ç PÉĄ" ñ  ÇÄÆ1ÌcÂUǽ€Ê3ÆcͨÁ1ÌWÄHŽÆWÁÓÉ Ä ÉĀͽÒHÀHÆn ÷ Óú G ۨ̽ÒÓÄ© Æ Å1Ä1ɈèÆÓÇÄ3ܓñôèÂ1ĉõ ͽÒ1ÀPÆÓÇ3€Ê3Æ3ú ̽ҀÇ Ä XHňƀãĈ Å3Âܪ˽ÆPÆ£ÇÝېÌ3ÒÓÄPÄÆÓÇÝÄB Á Îõ˜Í½Ò1ÀPÆÓÇ3€Ê3Æ  Ò£ÍSÌ)ÌÓǽ€ÊÎÆ©Ì©ÌUßPß Ê4¨ҀÇnñ‡ú “„“•”|µ | ëÌ)̀Ê4¨ҀÇmÌ©Ì f ¨÷ «ª‚„‘ˆ‡šqeh‡penš œ ‡ …Θs¼™‡‘…‘Ýi„e™·   j in‘‘‚„‘ Lists and classes taken together give us powerful tools for structuring the data in our programs.

We want to replace these lines with code to create a list of pips. enclosing ÊΠΈÆ1Ø3Òq the calls to inside list construction brackets. the pips were created with this sequence of stateҀÇÎÒÓÄ ments inside of :  ܣƐÀHÍnïU4Òq†Öfß Ü£ÆÀHÍnU ï 4q Ò 3Ô ß Ü£ÆÀHÍnU ï 4q Ò ½ÞÈß Ü£ÆÀHÍnU ï 4q Ò §dUß Ü£ÆÀHÍnU ï 4q Ò %9 ß Ü£ÆÀHÍnU ï 4q Ò ½øÈß Ü£ÆÀHÍnU ï 4q Ò ½þÈß ÜÓƨÀ1͟ï¡Ì)̀ÊΠÜÓƨÀ1͟¡ ï Ì)̀ÊΠÜÓƨÀ1͟¡ ï Ì)̀ÊΠÜÓƨÀ1͟¡ ï Ì)̀ÊΠÜÓƨÀ1͟¡ ï Ì)̀ÊΠÜÓƨÀ1͟¡ ï Ì)̀ÊΠÜÓƨÀ1͟¡ ï Ì)̀ÊΠΈÆ1Ø3ÒqnñvÑ"¦C¨HÁP͐ͽܣƣÄnõlÑxϧ¨PÁH͐ͽܣÆHÄÎú ΈÆ1Ø3ÒqnñvÑ"¦C¨HÁP͐ͽܣƣÄnõlÑxÏ4ú ΈÆ1Ø3ÒqnñvÑ"¦oõ¢ÑÓÏÎú ΈÆ1Ø3ÒqnñvÑ"¦C¨HÁP͐ͽܣƣÄnõlÑxϨá¨ÁH͐ͽܣÆHÄÎú ΈÆ1Ø3ÒqnñvÑ"¦áÁP͐ͽܣƣÄnõlÑxϧ¨PÁH͐ͽܣÆHÄÎú ΈÆ1Ø3ÒqnñvÑ"¦áÁP͐ͽܣƣÄnõlÑxÏ4ú ΈÆ1Ø3ÒqnñvÑ"¦áÁP͐ͽܣƣÄnõlÑxϨá¨ÁH͐ͽܣÆHÄÎú ÊΠÎÆHØ3q Ò  ÎÒ1ÆÛ3Ò£Æ1Û Recall that is a local method of the class that creates a circle centered at the position given by its parameters. û 4Òq@Ü ß 4q Ò @ܬïè"  )½ÆÓLjÉñvܣƐÀH͟H ï Ì©ÌIÊ4 ÎÆH؈ Ò oñv Ñ ¦C¨PÁHÍPͽܣƣÄnõlÑx§ Ï ¨PÁH͐ͽܣÆHÄÎúú 4q Ò @ܬïè"  )½ÆÓLjÉñvܣƐÀH͟H ï Ì©ÌIÊ4 ÎÆH؈ Ò oñv Ñ ¦C¨PÁHÍPͽܣƣÄnõlÑxÏ4úú 4q Ò @ܬïè"  )½ÆÓLjÉñvܣƐÀH͟H ï Ì©ÌIÊ4 ÎÆH؈ Ò oñv Ñ ¦C¨PÁHÍPͽܣƣÄnõlÑxϨá¨ÁH͐ͽܣÆHÄÎúú 4q Ò @ܬïè"  )½ÆÓLjÉñvܣƐÀH͟H ï Ì©ÌIÊ4 ÎÆH؈ Ò oñv Ñ ¦oõlÑÓÏÎúú 4q Ò @ܬïè"  )½ÆÓLjÉñvܣƐÀH͟H ï Ì©ÌIÊ4 ÎÆH؈ Ò oñv Ñ ¦á¨ÁHÍPͽܣƣÄnõlÑx§ Ï ¨PÁH͐ͽܣÆHÄÎúú 4q Ò @ܬïè"  )½ÆÓLjÉñvܣƐÀH͟H ï Ì©ÌIÊ4 ÎÆH؈ Ò oñv Ñ ¦á¨ÁHÍPͽܣƣÄnõlÑxÏ4úú 4q Ò @ܬïè"  )½ÆÓLjÉñvܣƐÀH͟H ï Ì©ÌIÊ4 ÎÆH؈ Ò oñv Ñ ¦á¨ÁHÍPͽܣƣÄnõlÑxϨá¨ÁH͐ͽܣÆHÄÎúú ܣƐÀHÍnU ï 4q Ò @Ü T ß Î Ò 4Ü  An even more straightforward approach is to create the list directly.”I´ ¯ s4tvuxwzy|{I}†~I~xüé@u†y–uqs‚g± ± { ³ y 6 ‚HŠ†ˆ Let’s consider how the code looks using a collection of circle objects stored as a list. Our first problem is to create a suitable list. One approach would be to start with an empty list of pips and build up the final list one pip at a time. This will be done list called ÎÒ£ÆgÛ3Ò£Æ1Û in the constructor for the class. like this: ܣƐÀHÍnïU4Òq@Ü ß û ÜÓƨÀ1͟ï¡Ì)̀ÊΠΈÆ1Ø3ÒqnñvÑ"¦C¨HÁP͐ͽܣÆ1Änõ Ñxϧ¨PÁH͐ͽܣÆHÄÎúú“õ ÜÓƨÀ1͟¡ ï Ì)̀ÊΠΈÆ1Ø3q Ò nñv" Ñ ¦C¨HÁP͐ͽܣÆ1Änõ ÑxÏ4úú“õ ÜÓƨÀ1͟¡ ï Ì)̀ÊΠΈÆ1Ø3q Ò nñv" Ñ ¦C¨HÁP͐ͽܣÆ1Änõ ÑxϨá¨ÁH͐ͽܣÆHÄÎúú“õ ÜÓƨÀ1͟¡ ï Ì)̀ÊΠΈÆ1Ø3q Ò nñv" Ñ ¦oõ¢ÑÓÏÎúú“õ ÜÓƨÀ1͟¡ ï Ì)̀ÊΠΈÆ1Ø3q Ò nñv" Ñ ¦áÁP͐ͽܣÆ1Änõ Ñx§ Ï ¨PÁH͐ͽܣÆHÄÎúú“õ ÜÓƨÀ1͟¡ ï Ì)̀ÊΠΈÆ1Ø3q Ò nñv" Ñ ¦áÁP͐ͽܣÆ1Änõ ÑxÏ4úú“õ . The basic idea is to replace our seven instance variables with a single 4Òq@Ü . In our previous version.

Here is an easier way to turn on the same three pips: . Listing complex objects one per line like this makes it much easier to see what is happening. For example.~I~€ ¯ cé4{zˆ 6 1Š 6 ŠŒ•’ 6 yèt«¾ 6 ˆ|y|ˆ‰uxŠŒ‹asB± uŒˆ–ˆp{ôˆ ÜÓƨÀ1͟ï¡Ì)̀ÊЈ Î Æ1Ø3ÒqnñvÑ"¦áÁP͐ͽܣÆ1Änõ ÑxϨá¨ÁH͐ͽܣÆHÄÎúú  ”I´€´ Notice how I have formatted this statement. we can get at the individual pip objects. However. 3. Similarly. ܣƐÀHÍnU ï 4q Ò †Ö†ïzÜ£Æ1© Ä D½ÒHÀÀ­ñ‡ÜÓƨÀHÍnïùÍPÁH̨) Æ !1ÌÁ£ÉPÇÃ3ú ܣƐÀHÍnU ï 4q Ò §dnïzÜ£Æ1© Ä D½ÒHÀÀ­ñ‡ÜÓƨÀHÍnïùÍPÁH̨) Æ !1ÌÁ£ÉPÇÃ3ú ܣƐÀHÍnU ï 4q Ò ½þoïzÜ£Æ1© Ä D½ÒHÀÀ­ñ‡ÜÓƨÀHÍnïùÍPÁH̨) Æ !1ÌÁ£ÉPÇÃ3ú In the new version. In the original program. this code does not really take advantage of the new representation. just as if they were separate variables. By subscripting the list. Rather than making one giant line. and 6. pips 1. 4. I put one list element on each line. A parallel approach could accomplish this task with these three lines of code: ܣƐÀHÍnU ï 4q Ò @Ü û ) Õ nïzÜÓÆH© Ä D½ÒHÀPÀ¬ñ‡ÜÓƨÀ£ÍŸïpͨÁ£ÌÆ)!H̨ÁÓɐǨÃÎú ܣƐÀHÍnU ï 4q Ò @Ü û ) Þ nïzÜÓÆH© Ä D½ÒHÀPÀ¬ñ‡ÜÓƨÀ£ÍŸïpͨÁ£Ì) Æ !H̨ÁÓɐǨÃÎú ܣƐÀHÍnU ï 4q Ò @Ü û ) ø nïzÜÓÆH© Ä D½ÒHÀPÀ¬ñ‡ÜÓƨÀ£ÍŸïpͨÁ£Ì) Æ !H̨ÁÓɐǨÃÎú Doing it this way makes explicit the correspondence between the individual instance variables used in the first version and the list elements used in the second version. The advantage of a pip list is that it is much easier to perform actions on the entire set. and 7 were turned on for the value 3. Python is smart enough to know that the end of the statement has not been reached until it finds the matching square bracket. this corresponds to pips in positions 0. Just make sure to include the commas at the end of intermediate lines to separate the items of the list. since the pips list is indexed starting at 0. ͨÁ1E Ì 4q Ò  ҀǻܣƐÀHÍnU ï 4q Ò @ܬ÷ 4q Ò „ïzÜÓÆH) Ä D3ÒHÀPÀ¬ñvܣƨÀ1͟ï Ë3Â Ñ ÎC!HÌÁxɐLjÃ3ú See how these two lines of code loop through the entire collection of pips to change their color? This required seven lines of code in the previous version using separate instance variables. we can turn a set of pips back on by indexing the appropriate spot in the pips list. we can blank out the die by setting all of the pips to have the same color as the background.

”I´€¹ s4tvuxwzy|{I}†~I~xüé@u†y–uqs‚g± ± { ³ y 6 ‚HŠ†ˆ ͨÁ1ÌÿÒWÒ€Ç û Չõ–Þ‰õ–ø)n÷ ܣƐÀH͟ïb4Òq@Ü û Ò nïzÜ£Æ1Ä©D½ÒHÀÀ­ñ‡ÜÓƨÀ£ÍŸïù͐Á1̨Æ)!1ÌÁÓɐǨÃÎú Using an index variable in a loop. The idea is to use a list where each item in the list is itself a list of pip indexes. ͨÁ1E Ì 4q Ò  ҀǻܣƐÀHÍnïU4Òq@ܬ÷ ܣƐÀH͟b ï 4q Ò „ïzÜÓÆH) Ä D3ÒHÀPÀ¬ñvܣƨÀ1͟ï Ë3ÑÎC!H̨ÁÓɐǨÃÎú Ò£T Í WÀxÉ½Æ€ßß Ö†÷ Á£Çàß û Þg ƨÀ¨Ò£T Í WÀÓɈÆcߐßÐԄ÷ Á£Çàß û Չõ–øg ƨÀ¨Ò£T Í WÀÓɈÆcߐßÝÞo÷ Á£Çàß û Չõ–Þ‰õ–ø) ƨÀ¨Ò£T Í WÀÓɈÆcߐ¥ ß dn÷ Á£Çàß û ՉõôÔæ¡ õ doõè) ø  ƨÀ¨Ò£T Í WÀÓɈÆcߐS ß 9„÷ Á£Çàß û ՉõôÔæõ–Þ„H õ doõè) ø  ƨÀÜ£Æo÷ Á£Çàß û Չõ‡Ö@õôԉH õ doÒ õ 9‰õ–g ø  ͨÁ1ÌÿÒWҀÇÿÁ£Çh÷ ܣƐÀH͟b ï 4q Ò @Ü û Ò nïzÜ£Æ1© Ä D½ÒHÀÀ­ñ‡ÜÓƨÀ£ÍŸïù͐Á1̨) Æ !1ÌÁÓɐǨÃÎú The version without lists required 36 lines of code to accomplish the same task. Here is the updated algorithm: ¤ÁPÁ ÐÄ1ÅÌÁÓ§ É !£E Å 4q Ò @ÜUÂxLjÀÄHɨÌHÇÿÂPÀÀ€ÁPÍPÍ ˆÆ1ÄÆ1̣ʓÒIÇ½Æ ÄHŽÆÝÀ¨Ò¨Ü€ÄÐÁP£ Í 4q Ò  ҀÇè) Æ ¦Æ½Ü ĨÁcÄHɨÌHÇ¡Á£Ç ¤ÁPÁ ÐÄ1ÅÌÁÓ§ É !£ÅWÄHňÆÝÀҐÜxÄÐÁPÍ¡ÒILjÐ) Æ ¦¨ÆˆÜÈÂÓÇÀÄHɨÌHÇ¡Á£ÇÐÄ1ŽÁˆÜ£V Æ Î Ò @ܬï   We could implement this algorithm using a multi-way selection followed by a loop. For example. ÜÓÆHÄ)ۈÀxÉ½Æ The second approach considerably shortens the code needed in the 3Ò1 Æ Û3Ò1Æ£Û method of the class. The correct list of indexes is determined by . ÒÓC Í ¨PƐÀÒÓÍ Notice that this code still uses the structure to determine which pips WˆÂPÀÓÉ½Æ should be turned on. Here is how a table-driven approach can be coded: . we can make this decision table-driven instead. since these are the pips that must be turned on to show a be the list value of 3. the item in position 3 should û Մõ–Þ‰õ–g ø  . But we can do even better than this. we can turn all three pips on using the same line of code.

it would be better to create the table in the constructor and save it in an instance variable. Putting the definition of Á£c Ç ˆÂxË3ÀPÆ ÒIÇ4ÒxÄ into yields this nicely completed class:   óWýңÆgW½Ò1Æ1ۈÔoïbÏ ÍP̨Áxa Ê !Ḧ"  PÅ4ÒPѨÜUÒvÊCˆÁH̐Ä@Y ÑHÀPˆÜPÜ ÎÒ£g Æ Û3Ò£Æ1ۙ÷ ©) ÎÒ1 Æ Û3Ò£Æ1ÛÿҐÜUÂÈÛÎÒ£Ã)!¨Æ1ĀÄHŽÂ1ÄÝýҐÜq½ÀÂ1Ï3ÜÈÂE!PÌÂ"PÅ4ҐÑ1À Ì" Æ ÌƈܣÆÓÇĈ£Ä3Ò£Á£ÇWÁPÍÐÂàÜxÄÂÓÇÃÂ1̐áÜP" Ò ¦C¨ÜPңÐÆPÃUýÒ1Æoq ï )© »  èÆHÍSÌ©ÌÒIÇ4Òxħ̩̭ñ‡ÜÓƨÀḦ́õ Û3ҀǟõÑ1ÆÓÇÄÆ1Ìnõ ÜHÒ Æ3ú¬÷ ©©v×H̨ƨÂ1ĨƀE  W3Ò£Æ1ÛÐÁHÍЀýÒ1Ɖõ˜Ænïp!ŸïP÷ Ã4Ö ß ü ÎÒ1Ƭñpʈ) Ï 4ÎÒIǙõ ØÁҀÇĉë ñ dÕ„ë õ 9HÕ3ú“õ˜ÔPÕ½ú ÑÓÌƐÂ1ĨƽÜÈÂcÈÒ1ÆàÑ1ÆÓÇĨÆHÌÆHÃÝÂ1Ä©Ò ñ d¨Õ‰ë õ 9PÕ½úfÅ3 W3ÒIǧ!¡ÜHÒ£Ã¨ÆˆÜ ÁPÍÐÀPÆÓ§ Ç !HÄHÅ¡ÔHÕnq ï )©  !h óWͽÒÓÌ3ÜxÄÝÐÆPͽÒIǽÆàÜÓÁxÊ3ÆàÜxÄÂÓLjèÂ1̐ÃEWˆÂPÀÓÉ½ÆˆÜ Ü£Æ¨À1͟ï|ÛÎҀÇW߀ÛÎÒ€Ç Ü£Æ¨À1͟ï Ë3Â Ñ ÎC!HÌÁ£ÉPLjà & ß †ÛHÅ4ÒÓĨ' Æ ó¡Ñ£Á¨ÀHÁHÌÐÁPÍWÈÒ1ƀͨÂÑ1Æ Ü£Æ¨À1͟ïpͨÁH̨) Æ !HÌÁ£ÉPLjà & ß z˽ÀÂ Ñ Îxó¡Ñ£Á¨ÀHÁHÌÐÁP̀Ä1Ž` Æ Î Ò @Ü Ü£Æ¨À1͟b ï @ÜPÒ ¨ÆÈßÝÕn Ö YÐÜHÒ ¨Æ ó€ÌÂHÈҀÉ@ÜYÁPÍÝƨ¨р¥ Å Î Ò  Å@ÜPÒ ¨Æcß ÜHÒ ¨T Æ ŸÐԄïðÕ óUŽÀ1ÍÝÁPÍÿÜPÒ ¨Æ ÁP͐ͽܣÆ1ÄWßÝÕnïù@ ø Y Å4ÜPÒ ¨Æ óWÈҨ܀ĈÂÓÇÎÑ1ÆcÍHÌÁ€Ê»Ñ1ÆÓÇÄÆ1Ì )h )h !h )h !h )h . this version is much easier to modify. Notice that I padded the table WÀxÉ½Æ ÎÒ1ÆÛ3Ò£Æ1Û by placing an empty list in the first position. The will remain unchanged ÎÒ£g Æ Û½Ò1Æ1Û throughout the life of any particular . the will be blank. for various values.~I~€ ¯ cé4{zˆ 6 1Š 6 ŠŒ•’ 6 yèt«¾ 6 ˆ|y|ˆ‰uxŠŒ‹asB± uŒˆ–ˆp{ôˆ Á£ÇcˆÂxË3ÀPÆUß ûÐû oõ û Þ)oõ û ‰ Ô õHd©„õ û Ôæõ–Þ„õHd©„õ û Մ– õ ԉõ¡d„õ–øgoõ û Մõ–Ô‰õ–Þ‰õ¡d„õ–ø)„õ û Մõv֓õôÔæõ¡d„õë9‰õèø)` ”I´€¿ ͨÁ1ÌE4Òq ҀǻܣƐÀHÍnïU4Òq@ܬ÷ ܣƐÀH͟ïb4Òq„ïzÜÓÆHÄ)D3ÒHÀPÀ¬ñvܣƨÀ1͟ï Ë3ÑÎC!H̨ÁÓɐǨÃÎú Á£ÇàßÐÁÓC Ç ˆÂxË3ÀHÆ û WÀxɽ) Æ  ͨÁ1ÌÿÒWҀÇÿÁ£Çh÷ ܣƐÀH͟b ï 4q Ò @Ü û Ò nïzÜ£Æ1© Ä D½ÒHÀÀ­ñ‡ÜÓƨÀ£ÍŸïù͐Á1̨Æ)!1ÌÁÓɐǨÃÎú ÁÓC Ç ˆÂxË3ÀHÆ I have called the table of pip indexes . Now we have reduced our 36 lines of code to seven. if you want to change which pips are displayed Á£C Ç ÂÓ˽ÀPÆ . Rather than (re)creating this table each time a new value is displayed. If is 0. you simply modify the entries in ÁÓC Ç ˆÂxË3ÀHÆ There is one last issue to address. In addition.

”I´€â s4tvuxwzy|{I}†~I~xüé@u†y–uqs‚g± ± { ³ y 6 ‚HŠ†ˆ ĨÁWÁ£É¨ÄÆHÌEÎÒ4Ü ó¡ÑÓÌƐÂ1ĨÆW¡Ü"í1ɽÂ1̨ÆcͨÁ1ÌWÄHŽƀͨÂÑ£Æ Ñ ¦oõ ÑxÏÝß¡Ñ1ÆÓÇÄÆ1̙p ï !¨ÆHÄ ‰ñ‡ú†õ˜Ñ1ƣǨÄÆ1̙ïf!ÆHÄ „ñIú †Ö ߀ØÁҀǨĄñv" Ñ ¦C¨xÅ@ÜPÒ ¨Æ‰õ Ñx§ Ï ¨ÓÅ4ÜPÒ ¨Æ3ú 3Ôc߀ØÁҀǨĄñv" Ñ ¦á£Å@ÜPÒ ¨Æ‰õ ÑxϨá1Å4ÜPÒ ¨Æ3ú ÌƈÑxÄWT ß  ˆÆÑÓĈÂx§ Ç !¨ÀPÆæf ñ †Ö@p õ 3Ԉú ÌƈÑxęïpÃP̈ÂÓÛoñðÛÎҀÇ@ú ÌƈÑxęïôÜ£ÆH) Ä D3Ò1ÀÀ¬ñvܣƐÀH͟ï Ë3¨ Ñ ÎC!H̨ÁÓɐǨÃÎú g Ð ))hh ))hh €“ óÝ×HÌƐÂ1Ĩƀþ¡ÑÒÓ̽ÑHÀHƽÜY͐ÁHÌ ÜxÄÂÓÇÃÂ1̐ÃVÎÒÿÀPÁÑH£Ä3Ò1ÁÓÇ@Ü Ü£Æ¨À1͟b ï 4 Ò 4Ü ß û ܣƐÀHÍn¡ ï Ì©ÌIÊ4Â"ΈÆHؽÒoñvÑ ¦c¨PÁH͐Í3ÜÓÆHĄõlÑÓÏC¨PÁPÍPÍ3ÜÓÆHÄ4ú“õ ܣƐÀHÍn¡ ï Ì©ÌIÊ4"  ΈÆHؽ Ò oñvÑ ¦c¨PÁH͐Í3ÜÓÆHĄõlÑÓÏÎú†õ ܣƐÀHÍn¡ ï Ì©ÌIÊ4"  ΈÆHؽ Ò oñvÑ ¦c¨PÁH͐Í3ÜÓÆHĄõlÑÓϐá¨ÁPÍPÍ3ÜÓÆHÄ4ú“õ ܣƐÀHÍn¡ ï Ì©ÌIÊ4"  ΈÆHؽ Ò oñvÑ ¦„õ¢ÑÓÏ4ú“õ ܣƐÀHÍn¡ ï Ì©ÌIÊ4"  ΈÆHؽ Ò oñvÑ ¦Pá¨ÁH͐Í3ÜÓÆHĄõlÑÓC Ï ¨PÁPÍPÍ3ÜÓÆHÄ4ú“õ ܣƐÀHÍn¡ ï Ì©ÌIÊ4"  ΈÆHؽ Ò oñvÑ ¦Pá¨ÁH͐Í3ÜÓÆHĄõlÑÓÏÎú†õ ܣƐÀHÍn¡ ï Ì©ÌIÊ4"  ΈÆHؽ Ò oñvÑ ¦Pá¨ÁH͐Í3ÜÓÆHĄõlÑÓϐá¨ÁPÍPÍ3ÜÓÆHÄ4$ ú  óÝ×HÌƐÂ1ĨÆWÂcĈÂÓ˽ÀPÆc͐ÁH̀ÛHÅ4ҐÑIÅT4Òq@ÜU£ÌÆWÁ£Çà͐ÁHÌÐƐÂрÅSWÀxÉ½Æ Ü£Æ¨À1͟ïùÁ£C Ç ÂÓ˽ÀPÆ ß ûWû oõ û ) Þ oõ û ԉH õ d©oõ û ԉõèބH õ d©oõ û Մõ–Ô‰¡ õ d„õ–g ø oõ û Մõ–Ô‰õ–Þ‰¡ õ d„õ–) ø „õ û Մõv֓õôÔæ¡ õ d„ë õ 9‰õè) ø ` ܣƨÀ1͟ïôÜ£ÆHÄ)ۈÂPÀÓɽƬñ€ÖHú èÆHÍS̩̀ÊΠÎÆHØ3ÒqnñvܣƨÀ1Íoõ ¦oõ˜ÏÎú¬÷ ©©¢IǨÄÆHÌ1Ç3ÂPÀ ŽƐÀ"ˆÆHÌ Ê3ÆHÄHňÁPÃcĨÁ€ÃPÌ£ۡÂV4ÒqÿÂ1Ä©ñÒ¦oõðÏÎúm)© 4 Ò àßÝ×ÒÓ̽ÑHÀPƬñ–بÁˆÒ€Ç¨Ä„ñÒ¦oõðÏÎú†õ˜Ü£ÆÀHÍnïU@ÜHÒ Æ3ú 4 Ò hïzÜÓÆH© Ä D½ÒHÀPÀ¬ñ‡ÜÓƨÀ1͟ï|˽Â Ñ ÎC!P̨ÁÓÉPLjýú 4 Ò hïzÜÓÆHÄ Ä ÉÄÀҀLjÆæñvܣƨÀ1͟ï Ë3Â Ñ Îc!HÌÁxɐÇÃÎú 4 Ò hïùÃḦ£ۄñ‡ÜÓƨÀHÍnï–Û3ҀǓú ÌÆHÄ1ÉÌ1T Ç 4q Ò  !h èÆHÍÿÜ£ÆHÄ)ۈÂPÀÓɽƬñ‡ÜÓƨÀḦ́õIWÀxɽÆ3ú­÷ ©©ÅHÆHÄWÄ1Å4Ò¨Ü Ã½Ò1ÆcĨÁ€Ã½ÒÜq3ÀPÂ1ÏTWÀxɽÆnïu©) ó HÉÌ1ÇÿÀPÀUÄHŽ` T Æ Î Ò 4Ü ÁPÍPÍ Í¨ÁHE Ì Î Ò  ÒIǻܣƨÀ1͟b ï 4 Ò 4Üæ÷ Î Ò hïzÜ£Æ1© Ä D½ÒHÀÀ­ñ‡ÜÓƨÀHÍnï|˽Â Ñ Îc!P̐Á£ÉPLjýú .

We can even go one step further and view a program itself as a collection of data structures (collections and objects) and a set of algorithms that operate on those data structures. shows a snapshot of the calculator in action. and “=” to do the calculation. The user interface in this . By nesting and combining collections and objects we can devise elegant ways of storing data in or programs.). Our calculator will have buttons for the ten digits (0–9). ÊBÊ'ȑ×ÈƒÊ Ú  ª –•Ùnœ§rBٌ–§tuvB“2–%s –'w ŽŸƒ¾s¿ 3imœ)t As an example. the formula will be   evaluated and the resulting value shown in the display. We’ll take a very simple approach to performing calculations. allowing the user to create a formula. *. We have significantly improved the implementation of the ÎÒ£g Æ Û½Ò1Æ1Û class. we’ll develop a program that implements a simple Python calculator. The encapsulation of objects allows us to build complex software systems as a set of “pluggable modules. -. /). but we have not changed the set of methods that it supports. if a program contains data and operations. and a few special keys: “C” to clear the display.”   “„“•”|º  ¢in‘‚©©£…ΦŸ·•í W ² —îí¬…Î˜Ÿ™£e li„j ƒo¦„j io…¨™„g ÎÒ1 Æ Û3Ò£Æ1Û The reworked class shows how lists can be used effectively as instance ÁÓÇCˆÂxË3ÀHÆ variables of objects. a decimal point (. When the “=” key is pressed. Figure . ÎÒ£g Æ Û½Ò1Æ1Û We can substitute this improved version into any program that uses a without having to modify any of the other code. one natural way to organize the program is to treat the entire application itself as an object. Basically. we can divide the functioning of the calculator into two parts: creating the interface and interacting with the user.~I~€ ´H1s½uŒˆ–{ x ˜ yè…v‹Iç"´æPçzyètŒ‚1Š²s½u± ³ …± u†y|‚Ó} ”I´€é óTHÉÌ1ÇÐÄHňÆÝÂ"©¨ÌÁ"Ì3Ò1Â1ĨÆè4Òq@ܪ˽ÂÑÎàÁ£Ç ͨÁHÌÿÒWÒIǻܣƐÀH͟ïùÁ£c Ç ˆÂÓ˽ÀPÆ û WˆÂPÀÓɈ) Æ Ÿ÷ ÜÓƨÀ1͟U ï Î Ò 4Ü û " Ò ŸïôÜ£ÆH) Ä D3Ò1ÀÀ¬ñvÜ£ÆPÀHÍnïùÍPÁHÌg Æ !H̨Á£ÉHLjÃ3ú This example also showcases the advantages of encapsulation that I talked about in Chapter 10. our pips list and list contain circles and lists. respectively. As buttons are clicked. the corresponding characters will show up in the display. Interestingly. which are themselves objects. four operations (+. “ Ó -” to backspace over characters in the display. Now.

we will create a represents the calculator in our program. èÆHS Í Ì©ÌÒIÇ4Òx§ Ä Ì©Ì­ñ‡ÜÓƨÀHÍ3ú¬÷ ó¡ÑÓÌƐÂ1ĨÆUÄHňÆUÛÎҀÇèÁ£ÛÝͨÁ1ÌWÄHŽÆàÑ1À¨Ñ€É3ÀPÂ1ĨÁHÌ ÛÎҀÇàß ü ̈  c Å 43ҀÇoñ ‡×ÂÀ¨Ñ€É3ÀPÂ1ĨÁH# Ì Óú ÛÎҀÇhïzÜÓÆHÄ×PÁÁ1̨Ã3Ü@ñzՉõ–Õ„õèø„õèþ3ú ÛÎҀÇhïzÜÓÆHÄ Â Ñ ÎC!P̨Á£ÉPLjÉ" ñ ÓÜ£ÀÂ1Ĩg Æ !ḦÂÓ# Ï Óú ܣƨÀ1͟ï|ÛÎҀÇW߀ÛÎÒ€Ç g The coordinates for the window were chosen to simplify the layout of the buttons. .”I¹7 s4tvuxwzy|{I}†~I~xüé@u†y–uqs‚g± ± { ³ y 6 ‚HŠ†ˆ Figure   . We will make the calculator respond to user interaction Ì1ÉÇ by invoking a special method. In the last line. The user interaction can be managed by a set of methods that manipulate the widgets. We can keep track of these GUI widgets with instance variables. ÊBÊ'ȑ×È‘Ç ª vxw%sqt"“ërQœ)tql™wm•£t %i£äUwmtui•“Ã9f–Qœ©i )  רÀ¨Ñ€É½ÀÂ1ĨÁHÌ Let’s take a detailed look at the constructor for the class. case consists of a display widget and a bunch of buttons. אÀÑIÉ3ÀPÂ1ÄÁ1Ì class that To implement this division of labor. : Python calculator in action. The constructor for the class will create the initial interface. the window object is tucked into an instance variable so that other methods can refer to it. we’ll need to create a graphics window to draw the interface. First.

A tuple is just another kind of sequence in Python. This list of specifications is then used to create the buttons. Each specification is a tuple consisting of the “ and coordinates of the center of the button and its label. Since there are a lot of similar buttons. width.~I~€ ´H1s½uŒˆ–{ x ˜ yè…v‹Iç"´æPçzyètŒ‚1Š²s½u± ³ …± u†y|‚Ó} ”I¹H~ The next step is to create the buttons. this code first creates a list of button specifications. height. If the contents of a sequence won’t be changed after it is created. Typing out calls to the constructor with all this information for each button would be tedious. buttons directly. A button is normally specified by providing a center 1ÉÄPÄÁ£Ç point. Here is the code that creates the button list: óÿÑǪ́ƨÂ1ĨÆWÀҐÜxÄÐÁHÍUːÉÄPÄÁÓÇ@Ü ó ÜxÄÂ1̐ÄUÛÎÒÓÄ1ÅÿÀPÀUÄHŽơ܀ĈÂxLją̃ÃÐÜPÒ ÆPÃUËPÉĐĨÁ£Ç4Ü óc% Ë Å½ÆˆÑè Ü !½ Ò WƈÜcÑ1ÆÓÇÄÆ1Ì¡Ñ1ÁPÁH̐Ã3ÜUÂÓÇÃÝÀÂx˽ƐÀ€ÁPÍUːɨĐĨÁ£Ç@Ü û Ë Å½ÆÑ¨Ü ß % ñzԉõv֓õ èÕ Œú†õÈñôބõv֓õ ¨ï Œú†õ ñI֓õ–Ô‰õ vÖ Œú†õÈñzԉõ–Ô‰õ –Ô Œú†õÈñôބõ–Ô‰õ èÞ Œú†õÈÒ ñ doõ–Ô‰õ ðá Œú†õÈ8 ñ 9‰õ–Ô‰õ Ò¨ Œú†õ ñI֓õèބõ Hd Œú†õÈñzԉõèބõ Ò9 Œú†õÈñôބõèބõ èø Œú†õÈÒ ñ doõèބõ 8Y Œú†õÈ8 ñ 9‰õèބõ ҟ Œú†õ ñI֓H õ doõ èþ Œú†õÈñzԉH õ doõ ¡e Œú†õÈñôބH õ doõ èý Œú†õÈÒ ñ doH õ doõ ¨ vú†õ13 ñ 9æ¡ õ doõ –× v ú  F ܣƐÀHÍnï|ːɨĐĨÁ£Ç@Ü ß û  ͨÁ1Ì©ñv" Ñ ¦oõ†ÑxÏnõ–ÀÂÓˈƨÀˆúÈҀÇWm Ë Å"ˆÆˆÑ¨Ü¬÷ ܣƐÀH͟ï ːɨĐÄÁÓÇ@ܬïè"  )½ÆÓLjÉñ HɨĐÄÁÓÇoñvÜ£ÆPÀHÍnï–۽ҀǙõùبÁҀǐĄñŒÑ ¦‰õ†ÑÓÏÎú“õ ïð© þ 9‰õ¨ïðc þ 9æõôÀPÂÓ˽ƐÀ½úPú óÿÑǪ́ƨÂ1ĨÆUÄHňÆÝÀÂ£c Ì !¨Æ1Ì èß ËÉ¨ÄÄÁÓÇ Ü£ÆÀHÍnï|ːɨĐĨÁ£Ç@ܬïè  ©½ÆÓLjÃæñ HɨĐĨÁ£Ç„ñ‡Ü£ÆÀ1Ínï–۽Ҁǟõ ØÁҀÇĉë ñ dn¡ ï 9‰õvÖPú“õ ֆïðc þ 9æõÝïð© þ 9‰è õ Œ6 ß £úPú óàÂÑxÄ3" Ò WÂ1ĨƀÀPÀ ːɨĐÄÁÓÇ@Ü Í¨Á1Ìc˻ҀǻܣƐÀHÍnï|ːɨĐĨÁ£Ç@ܬ÷ ˄ïðÂÑÓĽ" Ò WÂ1ÄƬñIú gg } gg …  } u ggg f f  g } !h gg }  } g } gg …  £ g 6 gg f  f € f |B  } w Study this code carefully. we will use a list to store them. We will reuse the button class from last chapter. the tuple will be asËmÅ"ˆÆˆÑ¨Ü signed each successive item in the list . Rather than creating the ËmÅ"½ÆÑ¨Ü . using a tuple is more efficient than using a list. and label. Tuples are like lists except that tuples are immutable—the items can’t be changed. . The next step is to iterate through the specification list and create a corresponding button for each entry. A tuple looks like a list except that it is û ñIú enclosed in round parentheses instead of square brackets . Take a look at the loop heading: ͨÁHÌ©ñŒÑ ¦„õ†ÑÓÏoõôÀPÂÓ˽ƐÀ½úYҀÇWm Ë Å"½ÆѨܬ÷  – ͐ÁHÌ ñvÑ"¦oõ†ÑxÏnõ–ÀÂÓˈƨÀˆú According to the definition of a loop.

this is how Python actually implements all simultaneous assignments. the larger button is created and tacked onto the list. the corresponding components of the tuple on the right side are unpacked into the variables on the left side. but I think you can see the appeal of the specification-list/loop approach for creating the 17 similar buttons. The display will just be a rectangle with some text centered on it. ܣƐÀHÍnï|ːɨĐĨÁ£Ç@ܬï詽ÆÓLjÃæñ HɨĐĐÁ£Çoñ‡ÜxƨÀHÍnï|Û3ҀÇnõ ØÁҀÇĉñëdnï¡9‰õvÖPú“õ ֆïðþc9æõÝïðþ©9‰õèŒß6£úPú  B I could have written a line like this for each of the previous buttons. When a tuple of variables is used on the left side of an assignment. creating the calculator display is quite simple. We need to save the text object as an instance variable so that its contents can be accessed and changed during processing of button clicks. The values are then used to create a that is appended to the list of buttons. conceptually. each iteration of the loop starts with an assignment. Here is the code that creates the display: ˧!WßE ˆÆÑÓÄÂÓǧ!¨ÀPƬñ–ØÁҀǨĄñ½ïH9‰õÒ9oï¡9ˆú†õ بÁˆÒ€Ç¨Ä„ñ89oï¡9æõ–øoï¡9½úPú ˧!ŸïôÜ£Æ1© Ä D3Ò1ÀÀ­ñ ùÛHÅ4ÒxÄÆ Œú ˧!ŸïpÃPÌ£ÛoñvܣƐÀH͟ï|ÛÎÒIǓú Ä) Æ ¦HÄW¥ ß g Æ ¦PĄñèØÁҀÇĉñzމõ–ø3ú“ü õ ©£ú Ä) Æ ¦HęïpÃP̈ÂÓÛoñvܣƨÀ1͟ï|ÛÎҀÇ@ú Ä) Æ ¦HęïôÜ£ÆH) Ä DˆÂ¨Ñ1Ææ" ñ xÑ£Á£É̽Ò1Æ1# Ì £ú Ä) Æ ¦HęïôÜ£ÆHC Ä Å1ÄPψÀPƬñ ô˽Á¨À16 à Óú Ä) Æ ¦HęïôÜ£ÆHC Ä ÅÒ ¨ÆæñIÖxø½ú ܣƨÀ1͟ïpýҨu Ü 3ÀPÂ1ÏUßÝĨ) Æ ¦HÄ  } )h . another tuple from is unpacked into the 1ÉĐĨÁ£Ç variables in the loop heading. In fact. ß After all of the standard-sized buttons have been created. each item in is also a tuple. In contrast to the buttons. ñvÑ"¦oõzÑÓÏnõ–ÀÂx˽ƨÀˆúªß F ǽÆ)¦HÄ¡ÒÓĨÆxÊÿÍHÌÁxÊWË%Å"ˆÆˆÑÜ ( Ë Å"ˆÆˆÑÜ % Of course. The first time through the loop.”I¹€r s4tvuxwzy|{I}†~I~xüé@u†y–uqs‚g± ± { ³ y 6 ‚HŠ†ˆ Put another way. it is as if we had done this simultaneous assignment: Ñ „ ¦ õ ÑÓÏoõ ÀÂÓˈƨÀUßàÔæõªÖ“õè‡ÕB Ë Å"ˆÆˆÑ¨Ü m Each time through the loop.

we need a method that actually gets the calculator running. Our calculator will use a classic event loop that waits for a button to be clicked and then processes that button.ÊBÊ'ȑ×È‘É ’”“Hvxœ©i§ssl™wm• ² ~I~€ ´H1s½uŒˆ–{ x ˜ yè…v‹Iç"´æPçzyètŒ‚1Š²s½u± ³ …± u†y|‚Ó} rmtžtuvxw%s ”I¹€” Now that we have an interface drawn. To quit the program. and contains the current contents of the display. Getting key presses is easy. èÆH¥ Í !¨ÆHÄ ˆÆ1ϐ̨ؐƽÜPܓñ‡ÜÓƨÀ1ÍÎú¬÷ ó 4½ÂÒxÄÎÜ ÍÁHÌà ːɨĐĨÁ£ÇÝĨÁÈ˽ÆàÑHÀ¨Ò E Ñ ÎˆÆPÃ ó  ˆÆHÄ1ÉÌ1Ç@Ü Ä1ŽÆÝÀÂx˽ƐÀcÁPÍWÄHÅˆÆ ËÉ¨ÄÄ¨Á£ÇÐÄHŽÂ1Äcۈˆ܀Ñ1ÀҐ E Ñ ÎˆÆHßï ÛPÅ4Ò1ÀP£ Æ PÌHɈÆn÷ óÐÀHÁ" Á àͨÁHÌÐƐÂÑIÅUÊÎÁÓÉ@Ü£ÆàÑ1ÀÒP Ñ Î àß ÜÓƨÀHÍnï–Û3ҀDŽp ï !¨Æ1ÄPöˆÁÓÉ@ÜÓÆæñIú ͐ÁHÌcË ÒIǻܣƨÀ1͟ï ːÉÄPÄÁÓÇ@Üæ÷ óÐÀHÁÁ à͐ÁHÌÐƐÂрÅcːÉÄPÄÁÓÇ ÒÓÍU˄ïôÑ1ÀÒP Ñ ÎˆÆHÉf ñ “ú¬÷ ÌÆ1ÄHɨÌHǀËhf ï !¨Æ1© Ä ¤ÂÓ˽ƐÀ¬ñ‡úªóÈÊÎÆ1ÄHňÁPÃWg Æ ¦½ÒÓÄ íÀ uÀ uÀ ͨÁ1Ì You can see how having the buttons in a list is a big win here. If contains the Ĩ) Æ ¦PÄ label of the button. All that’s left is to implement the and ̨ÁˆÑ£Æ½ÜÜ ˆÆ1Ï methods. this is a multi-way decision that checks the key label and takes the appropriate action. We can use a  loop to look at each button in turn. Basically. This is accomplished in . we loop through the list of buttons and check each one. the user will have to !ÆHÄ ˆÆHÏPØÌ¨Æ½ÜÜ “kill” the calculator window. the appropriate line of code looks like this: mÀ . If the clicked point turns out to be in one of the buttons. Let’s encapsulate this in a ÌHÉPÇ method called . ÎÆHÏ A digit or operator is simply appended to the display. èÆH̀ÌHɐÇoñ‡ÜÓƨÀHÍ3ú¬÷ ÛPÅ4Ò1ÀP£ Æ PÌHɈÆn÷ ÎÆHÏÝßÿÜÓƨÀHÍnf ï !ÆHÄ ÆHÏPؐÌƈܐÜ@ñIú ÜÓƨÀ1͟U ï ¨ÌÁÑ1ƽÜPÜ ÆHτH ñ ΈÆ1Ï4ú mÀ €À Notice that this is an infinite loop. providing an exit from the ÛHÅ4ÒHÀHÆ otherwise infinite loop. The result is a nested loop. The last step is to update the display of the calculator according to which ¨ÌÁÑ1ƽÜPÜ ÆHÏ button was clicked. we continue getting mouse clicks until one of those mouse clicks is on a button. To determine whether a button has been clicked. the label of that button is returned.

”I¹ ¯ s4tvuxwzy|{I}†~I~xüé@u†y–uqs‚g± ± { ³ y 6 ‚HŠ†ˆ ÜÓƨÀ1͟ïùÈҨÜu3ÀÂ£Ï™ïôÜ£ÆHÄ)Æg¦PĄñèÄƦPĐágΨÆHÏ4ú The clear key blanks the display. the equal key causes the expression in the display to be evaluated and the result displayed. ÜÓƨÀ1͟ïùÈҨÜu3ÀÂ£Ï™ïôÜ£ÆHÄ)Æg¦PĄñèÄƦPÄ û ÷f¨3Ö3ú Finally. If an error occurs. ÜÓƨÀ1͟ïùÈҨÜu3ÀÂ£Ï™ïôÜ£ÆHÄ)Æg¦PĄñ"©xú The backspace strips off one character. the calculator will display  )  Ä   rather than causing the program to crash. ÄP̐ϟ÷ ̨ƽÜIɽÀ1ÄWßÝÆWˆÂPÀ¬ñ–ĨÆ)¦HÄ4ú Æg¦½Ñ£Æ ğ÷ ̨ƽÜIɽÀ1ÄWß  )  Ä   G ÜÓƨÀ1͟ïùÈҨu Ü 3ÀÂ£Ï™ïôÜ£ÆH) Ä g Æ ¦PĄñvÜxÄH̄ñèÌÆÜIÉ3À£ÄÎúPú |  ÄP̐§ Ï ¨HÆ)¦ˆÑ1Æ ¨Ä The here is necessary to catch run-time errors caused by entries that are not legal Python expressions. G Here is the complete program: ó¡ÑHÂPÀÑæïUÏHÛ@¨©¨ Ú ÍÁ£É̀Í1ɐÇÎÑÓĽÒ1Á£ÇÿÑHÀ¨Ñ€É½ÀÂ1ĨÁHÌ É@ÜPÒIǧ!cØPϐÄ1ŽÁ£ÇàÂ1Ì3ÒxÄHÅ1ÊÎÆHĽҐÑæï ó ¢1ÀPÀÓÉ@܀ĐÌÂ1ÄƈÜfÉ4Ü£ÆWÁPÍÝÁÓË ÆˆÑÓÄ3ÜÈÂÓÇÃÐÀҐÜxÄÎÜ ÄÁÈːÉÎÒHÀ1ÃÐÂàÜP҇c Ê 3ÀHÆ ü • Ù ¢æï ï ÍP̨ÁxÊa!ḦÂ"PÅ4ÒPѨÜUÒvÊCˆÁH̐Ä@Y ÍP̨ÁxÊÐËPÉĐĨÁ£Ç ÒvC Ê ˆÁHÌÄ HÉÄPÄÁÓÇ ÑHÀPˆÜPÜ ×¨ÂPÀрɽÀÂ£ÄÁH̟÷ óTHÅÎҨ܀ÑHÀPˆÜPÜc҇Êc3ÀPƀÊÎÆÓÇÄÎÜY¡ÜP҇Êc3ÀHÆÐÑHÂPÀрɽÀÂ£ÄÁHÌ Ã¨ÆHÍSÌ©ÌÒIÇ4Òxħ̩̭ñ‡ÜÓƨÀHÍ3ú¬÷ ó¡ÑÓÌƐÂ1ĨÆUÄHňÆUÛÎҀÇèÁ£ÛÝͨÁ1ÌWÄHŽÆàÑ1À¨Ñ€É3ÀPÂ1ĨÁHÌ ÛÎҀÇàß ü ̈  c Å 43ҀÇoñ xÑ1À¨Ñ€É3ÀPÂ1ĨÁH# Ì Óú ÛÎҀÇhïzÜÓÆHÄ×PÁÁ1̨Ã3Ü@ñzՉõ–Õ„õèø„õèþ3ú ÛÎҀÇhïzÜÓÆHÄ Â Ñ ÎC!P̨Á£ÉPLjÉ" ñ ÓÜ£ÀÂ1Ĩg Æ !ḦÂÓ# Ï Óú ܣƨÀ1͟ï|ÛÎҀÇW߀ÛÎÒ€Ç ó ÐÁ1Û ÑxÌƐÂ1ÄÆÈÄHŽÆUÛ3Ò£) T à !¨ÆHÄ3Ü Ü£Æ¨À1͟H ï Ì©ÌÑxÌƐÂ1ÄÆ HɨĐÄÁÓÇ@Ü@ñIú ü ٕ¢ ž g 3 .

~I~€ ´H1s½uŒˆ–{ x ˜ yè…v‹Iç"´æPçzyètŒ‚1Š²s½u± ³ …± u†y|‚Ó} ܣƨÀ1͟ïHÌ©ÌÑxÌƐÂ1ÄÆ ÎҐÜq3ÀPÂ1ωñIú ”I¹€´ èÆHÍSÌ©ÌÑxÌƐÂ1ÄÆ HɨĐÄÁÓÇ@Ü@ñ‡Ü£ÆÀHÍ3ú¬÷ ó¡ÑÓÌƐÂ1ĨÆWÀҐÜxÄÐÁPÍUËPÉÄPÄÁ£Ç4Ü óÿÜxĈ£̐ĀÛ3ÒÓÄHÅàÀÀUÄ1Žơ܀ĈÂÓÇą̃áÜHÒ ¨ÆHÃÈːɨĐĨÁ£Ç@Ü óU% Ë Å"ˆÆˆÑè Ü !½ Ò Wƽ܀ѣƣǨÄÆHÌàÑ1ÁÁ1̨ýÜÈÂÓÇÃÐÀÂÓˈƨÀcÁHÍUːɨĐÄÁÓÇ@Ü Ë Å"ˆÆˆÑÜYß û ñzԉõ‡Ö@õ èÕ vú“õÈñôބõ‡Ö@õ ¨ï vú“õ % ñI֓õôÔæõ vÖ vú“õÈñzԉõôÔæõ –Ô vú“õÈñôބõôÔæõ èÞ vú“õÈÒ ñ doõôÔæõ ðá vú“õÈñ89‰õôÔæõ Ò¨ vú“õ ñI֓õ–Þ‰õ Hd vú“õÈñzԉõ–Þ‰õ Ò9 vú“õÈñôބõ–Þ‰õ èø vú“õÈÒ ñ doõ–Þ‰õ 8Y vú“õÈñ89‰õ–Þ‰õ ҟ vú“õ ñI֓¡ õ d„õ èþ vú“õÈñzԉ¡ õ d„õ ¡e vú“õÈñôބ¡ õ d„õ èý vú“õÈÒ ñ do¡ õ d„õ ¨ Œú†õ1ñ39‰õHdoõ –× Œú F ܣƨÀ1͟ï ːÉÄPÄÁÓÇ@Üªß û  ͨÁHÌ©ñŒÑ ¦„õ†ÑÓÏoõôÀPÂÓ˽ƐÀ½úYҀÇWm Ë Å"½ÆѨܬ÷ ÜÓƨÀ1͟ï|ËPÉÄPÄÁ£Ç4Üæïð"  ©ˆÆ£ÇÉñ 1ÉÄHÄÁÓÇnñŒÜ£Æ¨À1Ínï|ÛÎ҇ǙõùØÁ¨Ò€ÇĉñŒ" Ñ ¦oõôÑÓÏÎú†õïðþc9æõ¨ïùþc9¬õôÀPÂÓËƨÀ½úPú ó¡ÑÓÌƐÂ1ĨÆUÄHňÆÝÀÂ1© Ì !¨Æ1ÌWßcːÉÄPÄÁÓÇ Ü£Æ¨À1͟ï ːÉÄPÄÁÓÇ@Üæïð"  )½Æ£ÇÉñ HÉÄPĨÁÓÇnñŒÜ£ÆÀHÍoï–ÛÎÒIǟõ بÁˆÒIÇÄ„Ò ñ dŸH ï 9‰õ‡ÖHú†õÖ­ïùc þ 9‰õWïðc þ 9æè õ v' ß £úú óÐÂÑÓĽ" Ò WÂ1ÄƀÀÀ ËPÉÄPÄÁ£Ç4Ü Í¨ÁHÌcË ÒIǻܣƐÀH͟ï ːɨĐÄÁÓÇ@ܬ÷ Ëhïè¨ÑÓÄ3 Ò WˆÂ£ÄÆæñ‡ú 3 ! gg } gg … } gg fu gg } f !h gg }  } g } gg …  £ g f gg f  f € } w B èÆHÍSÌ©ÌÑxÌƐÂ1ÄÆ ÎҐÜq3ÀPÂ1ωñ‡Ü£ÆÀHÍ3ú¬÷ Ë !WE § ß  ˆÆÑÓÄÂÓǧ!¨ÀPƬñ–ØÁҀǨĄñ½ïH9‰õÒ9oï¡9ˆú†õ بÁˆÒ€Ç¨Ä„ñ89oï¡9æõ–øoï¡9½úPú Ë !ŸïôÜ£Æ1© § Ä D3Ò1ÀÀ­ñ ùÛHÅ4ÒxÄÆ Œú Ë !ŸïpÃPÌ£ÛoñvܣƐÀH͟ï|ÛÎÒIǓú § Ä) Æ ¦HÄW¥ ß g Æ ¦PĄñèØÁҀÇĉñzމõ–ø3ú“ü õ ©£ú Ä) Æ ¦HęïpÃP̈ÂÓÛoñvܣƨÀ1͟ï|ÛÎҀÇ@ú Ä) Æ ¦HęïôÜ£ÆH) Ä DˆÂ¨Ñ1Ææ" ñ xÑ£Á£É̽Ò1Æ1# Ì £ú Ä) Æ ¦HęïôÜ£ÆHC Ä Å1ÄPψÀPƬñ ô˽Á¨À16 à Óú Ä) Æ ¦HęïôÜ£ÆHC Ä ÅÒ ¨ÆæñIÖxø½ú ܣƨÀ1͟ïpýҨu Ü 3ÀPÂ1ÏUßÝĨ) Æ ¦HÄ !  } )h èÆHÍ¥!¨ÆHÄ HɨĐÄÁÓÇnñvܣƨÀ1ÍÎú­÷ ó 4½ÂÒxÄÎÜ ÍÁHÌà ːɨĐĨÁ£ÇÝĨÁÈ˽ÆàÑHÀ¨ÒÑΈÆPÃWÂÓLjĄ̀ÆHÄ1ÉÌHÇ4Ü ÄHňÆÝÀÂx˽ƨÀUÁPÍ E ó ÄHňÆÈːɨĐÄÁÓÇÝÄHŽÂ1Āۈˆ܀ÑHÀ¨Ò Ñ ÎˆÆPÃnï ÛPÅ4Ò1ÀP£ Æ PÌHɈÆn÷ àß ÜÓƨÀHÍnï–Û3ҀDŽp ï !¨Æ1ÄPöˆÁÓÉ@ÜÓÆæñIú ͐ÁHÌcË ÒIǻܣƨÀ1͟ï ːÉÄPÄÁÓÇ@Üæ÷ ÒÓÍU˄ïôÑ1ÀÒP Ñ ÎˆÆHÉf ñ “ú¬÷ ÌÆ1ÄHɨÌHǀËhf ï !¨Æ1© Ä ¤ÂÓ˽ƐÀ¬ñ‡úªóÈÊÎÆ1ÄHňÁPÃWg Æ ¦½ÒÓÄ € .

To run the application. . we רÂPÀÑIÉ3ÀÂ£ÄÁ1Ì ÌHÉPÇ create an instance of the class and then call its method.”I¹€¹ s4tvuxwzy|{I}†~I~xüé@u†y–uqs‚g± ± { ³ y 6 ‚HŠ†ˆ èÆHÍ£ÌÁÑ1ÆˆÜÜ 1ÉÄPÄÁ£Çoñ‡ÜÓƨÀḦ́õ ΈÆ1Ï4ú¬÷ óU© Ù ˆÃ¨Â1Ä¨Æ½Ü Ä1ŽƀýҐÜq½ÀÂ1ÏWÁP̀ÄHňÆàÑHÂPÀрɽÀÂ£ÄÁHÌcͨÁ1ÌEÌÆˆÜÜ ÁH̀ÄHÅÎҨܧΈÆ1Ï Ä) Æ ¦HÄWß Ü£ÆÀH͟ïpýҐq Ü 3ÀPÂ1ϟf ï !¨Æ1© Ä ¨) Æ ¦PĉñIú Ò£E Í ÎˆÆ1ÏÝßß è× ÷ ÜÓƨÀ1͟ïùÈҨu Ü 3ÀÂ£Ï™ïôÜ£ÆH) Ä g Æ ¦PĄ" ñ ©xú ƨÀÒÓ£ Í ÎˆÆ1ÏÝßß ¨ ¨÷ F ó Â Ñ Î4q Ü ½ÂѣƄõÜ£ÀÒPÑ1ÆWÁPÍPÍcÄHňÆÝÀÂÜxÄÿрŽÂ1ÌÂÑÓĨÆH̟ï ÜÓƨÀ1͟ïùÈҨu Ü 3ÀÂ£Ï™ïôÜ£ÆH) Ä g Æ ¦PĄñèÄ Æ ¦PÄ û f ÷ ¨3 Ö 3ú ƨÀÒÓ£ Í ÎˆÆ1ÏÝßß èß ÷ ó WˆÂPÀÓÉ3£ÄÆUÄ1ŽÆWg Æ ¦̨ƽÜPܐÜPÒ£Á£ÇÝÂÓÇÃWýҨu Ü 3ÀPÂ1πÄ1ŽÆcÌƈÜIɽÀ1ęï G ó€Ä1ŽÆcÄP̐ϙïPïïù) Æ ¦½Ñ£Æ ¨ÄYÊÎÆрŽÂÓÇ4ҐÜvò Ê xÑH£Ä3ÑIŽƽm Ü Æ1̐ÌÁ1ÌÎÜcÒIÇÐÄHÅˆÆ óW͐ÁHÌÓÊÉ3ÀPÂY˽ÆҀC Ç !Wg Æ WÀÓɽÂ1ĨÆPßï ÄP̐ϟ÷ ̨ƽÜIɽÀ1ÄWßÝ Æ WˆÂPÀ¬ñ–Ĩ) Æ ¦HÄ4ú Æ ¦½Ñ£Æ ğ÷ g ̨ƽÜIɽÀ1ÄWß  )  Ä   G ÜÓƨÀ1͟ïùÈҨu Ü 3ÀÂ£Ï™ïôÜ£ÆH) Ä g Æ ¦PĄñvÜxÄH̄ñèÌÆÜIÉ3À£ÄÎúPú ƨÀˆÜÓÆn÷ ó ШÁHÌÓÊ4è T À ΈÆHE Ï ¨Ìƈܐܭõ˜"  ©ˆÆ£ÇÃàÒÓÄÝÄÁcÄ1ŽÆWÆÓLjÃÝÁP̀Ä1ŽƀÈҨq Ü ½ÀÂ£Ï ÜÓƨÀ1͟ïùÈҨu Ü 3ÀÂ£Ï™ïôÜ£ÆH) Ä g Æ ¦PĄñèÄ Æ ¦PĐg á ΨÆHÏ4ú s | } Ï  f  # Ï } |  ‘ èÆH̀ÌHɐÇoñ‡ÜÓƨÀHÍ3ú¬÷ ó ¢ILj͈ҀÇÎÒÓÄÆ –ÆgW¨Æ£Ç¨ÄÐÀPÁPÁ  a ÄÁ`̨ÁˆÑ£Æ½ÜÜfːÉÄPÄÁÓÇ ÛPÅ4Ò1ÀP£ Æ PÌHɈÆn÷ ÎÆHÏÝßÿÜÓƨÀHÍnïf!ÆHÄ 1ÉÄPÄÁ£ÇoñIú ÜÓƨÀ1͟U ï ¨ÌÁÑ1ƽÜPÜ 1ÉĐĨÁ£Ço¡ ñ ΈÆ1Ï4ú óTHÅÎÒ¨ÜYÌ1ɐÇ@ÜYÄ1ŽÆ`¨ÌÁ)!ḦÂIʧï Ò£S Í Ì)ÌÓǽ€ÊΩ Æ Ì©ÌUßPß ëÌ)̀Ê4¨Ҁm Ç Ì©Ì ¨÷ ó D3ÒxÌÎÜxÄÿÑxÌƐÂ1ÄƀÂÐÑHÀ¨Ñ€É½ÀÂ1ĨÁH̀Á£Ë ƈÑxÄ T ï ÄHňƐרÂPÀÑ ßÝאÀ¨Ñ€É3ÀPÂ1ĨÁH̄ñ‡ú ó ÐÁ£Û ÑHÀPÀUÄHňÆàÑHÀ¨Ñ€É½ÀÂ1ĨÁHÌ ŒÜfÌHɐÇcÊ3ÆHÄ1ŽÁPÃnï T ÄHňƐרÂPÀÑæïpÌHÉPÇnñ‡ú  | s g f ÑHÀ¨ÒÑÎÎÜæï … Notice especially the very end of the program.

Here is a simple dictionary that stores some fictional usernames and passwords: (©()( 3Âܐ܀ۨÀߖÄBX!1ÉÎңèÁB@÷uÓÜIÉ)½Æ1Ìg̨Á)!Ḧ€ÊPÊÎÆ1Ì#½õ‰ŒÄHɨÌ3ÒIǧ!64÷qX!¨Æ£ÇÎҀÉ4Ü%Îõ ôË4Ò1ÀÀB4÷qèÊÎÁ£ÇˆÁ ˆÁ¨À1Ï6²Å Notice that keys and values are joined with a “:”. The main use for a dictionary is to look up the value associated with a particular key. you can come up with lots of other examples of useful key-value pairs: names and phone numbers. When we want to access an item in the collection. In programming terminology. and commas are used to separate the pairs. For example. If you think a bit. usernames and passwords. they are not as common in other languages as lists (arrays). This is done through indexing notation. While dictionaries are incredibly useful. so you can skip the rest of this section if you’ve learned all you want to about collections for the moment. zip codes and shipping costs. Some other programming languages provide similar structures called hashes or associative arrays. A dictionary can be created in Python by listing key-value pairs inside of curly braces. this is a key-value pair. state names and capitals. etc. we look it up by index—its position in the collection. sales items and quantity in stock. ÊBÊ'È ÈƒÊ Sµ œ ¦l‡œ)tqlnvxw%–%“ q¤ ² –%sl‡œ©s Lists allow us to store and retrieve items from sequential collections. Many applications require a more flexible way to look up information. Python dictionaries are mappings. A collection that allows us to look up information associated with arbitrary keys is called a mapping. called a dictionary. û ž!1ÉÎңÐÁ'ž ŒÜ‡É©ˆÆHÌg¨ÌÁg!P̈ÂIʐÊ3ÆHÌ À ž (©()( 3Âܐ܀ۨà û zË4Ò1À• |Ê3Á£ÇˆÁ ½ÁÀ1Ï (©()( 3Âܐ܀ۨà   …  . We access the value (student information) associated with a particular key (social security number). we might want to retrieve information about students or employees based on their social security numbers. The example programs in the rest of the book will not use dictionaries.“„“•”–ê § ª™£e|g©«‚ «¦Ÿ‚™en…‡i„j  ¢™²j j ‚„ƒ†…‡™£e™‘ }˜ ~I~x ¹P ΂1Škib˜Ó{ 1…Œ{‡Š†y 6 u±xsˆ‚± ± { ³ y 6 ‚1ŠŒˆ ¨ • ”I¹€¿ Python provides another built-in data type for collections.

This is not a mistake. Our password example showed a dictionary having strings as both keys and values. not a mapping. Suppose a new user is added to our password system. you can see that the value associated with has changed –Ë3ÀÓɈƽÜHÑÓÌÆPÆ£Ç to . F ÈҐÑxÄ3Ò1ÁÓÇ3Â£ÌÏ ( û ˆ Î ÆHÏ F (  ÎÆHÏ returns the object associated with the given . the order of keys will look essentially random. When a dictionary is printed out. including programmer-defined classes. you need a sequence. If you want to keep a collection of items in a certain order.”I¹€â s4tvuxwzy|{I}†~I~xüé@u†y–uqs‚g± ± { ³ y 6 ‚HŠ†ˆ In general. We can expand the dictionary by assigning a password for the new username. Internally. To summarize. You have already seen how dictionaries can be defined by explicitly listing the key-value pairs in curly braces. (©()( 3Âܐ܀ۨà û zË4Ò1ÀÀ•žÈßAzË3ÀxɽƈÜPÑǪ́ƐÆÓÇ (©()( 3ÂÜÜ€Û¨Ã Ä ùÄHɨÌ3ҀC Ç ! ¨÷ ¡!Æ£ÇÎҀÉ@Ü õ pË4Ò1ÀÀ ÷ –Ë3ÀÓɈƽÜHÑÓÌÆPÆ£Ç õ H!1ÉÎңèÁ ÷ ŒÜI) É ½Æ1g Ì ̨) Á !Ḧ€ÊPÊÎÆ1Ì „Å pËÎÒHÀPÀ In this example. You can also extend a dictionary by adding new entries. Dictionaries are mutable. Python dictionaries are very efficient and can routinely store even hundreds of thousands of items. X¢ŒÊ Ú ÐÆ1ÛHË4Ò£Æ (©()( 3Âܐ܀ۨà û pǽƣÛPÉ4Ü£ÆHÌ ¡ ß (©()( 3ÂÜÜ€Û¨Ã Ä ùÄHɨÌ3ҀC Ç ! ¨÷ ¡!Æ£ÇÎҀÉ@Ü õ pË4Ò1ÀÀ ÷ –Ë3ÀÓɈƽÜHÑÓÌÆPÆ£Ç õ –ǽƣÛPÉ@ÜÓÆHÌ ÷ 3¢vÊ Ú ÐÆ£ÛPËÎÒ1Æ Põ H!1ÉÎңèÁ ÷ †ÜI) É ½ÆH Ì ̨) Á !PÌ€ÊPÊÎÆHÌ „Å f  … | } …… ¤¤  ’ Ž}   Ž6  Ž f Ž  ´ … . the value associated with a key can be changed through assignment. ÊBÊ'È È‘Ç f f… ®¤  ’ Ž  6 Ž    ´  f Sµ œ ¦l‡œ)tqlnvxw%–%“ q¤¤Ÿ 5ÍBiB“f–§tqlnvxwQs Like lists. Also notice that the dictionary prints out in a different order from how it was originally created. Mappings are inherently unordered. dictionaries are mutable collections that implement a mapping from keys to values. Python stores dictionaries in a way that makes key lookup very efficient. keys can be any immutable type. In general. Python dictionaries support a number of handy built-in operations. and values can be any type at all.

These methods are mostly self-explanatory. Returns a list of the values. èÆHÍÂÓɽÀ1Ä otherwise returns . 3ÂܐÜIÛÀ ß ÄŠͨÁ1ÌàÀÒIǽÆàҀǡ" Á ½ÆÓÇnñ s3Âܐ܀ÛÁH̐Ã3Ü Põ ùÌ vú­÷ É@ÜÓÆHÌnõ 3ˆÜPÜ ßÿÜxÄPÌ3ҀC Ç !Ÿïôq Ü 3À¨ÒÓĉñ†ÀÒIǽƽú 3Âܐ܀ۨà û É@Ü£Æ1c Ì ÈE ß 3ˆÜPÜ  © g  To manipulate the contents of a dictionary. Å3ÂˆÜ ÎÆHÏ Same as Returns a list of the keys. Deletes all entries. where each line of the and passwords were stored in a file called file contains a username and password with a space between. We could easily ½ÂˆÜP܀Ûà create the dictionary from the file.~I~x ¹P ΂1Škib˜Ó{ 1…Œ{‡Š†y 6 u±xsˆ‚± ± { ³ y 6 ‚1ŠŒˆ ¨ • ”I¹€é In fact. Suppose that usernames ½ÂˆÜP܀ۈÁ1Ì¨Ã½Ü . false if it doesn’t. ñ ÎÆHÏoH ¡ õ WˆÂPÀÓɈÆ3ú Returns a list of tuples representing the key-value pairs. For illustration. ÎÆHÏ If dictionary has returns its value. Python provides the following methods: Method ÎÆHÏ ú Ó 0 Ó ÃˆÒÑÓÄ 0 ï|Å3ÂÜ ˆ Î Æ1τñ Ó Ó Ó ÎˆÆHÏ ÒIÇ ÃˆÒÑxÄ 0 Ó 0 à ҐÑÓÄ ïsΈÆ1ÏÎÜ@ñIú ˆ Ó 0 ÈҐÑxÄ ïpWÀÓɈƽÜ@ñIú 0 ýÒPÑÓÄ ï–ÒÓÄƀʆÜ@ñIú 0 0 Ó Ã½ÒPÑÓÄ 0 ïp!¨ÆHĉñ Ó ÎˆÆ1Ï õ Ó Ã¨ÆPͨÂÓɽÀ1Ä 0 0 0 ú èƐÀ Ó Ó ÃˆÒÑxÄ Ã½ÒPÑÓÄ û ΈÆ1Ï  Ó 0 ï–ÑHÀPƐÂ1̉ñIú Meaning Returns true if dictionary contains the specified key. Deletes the specified entry. a common method for building dictionaries is to start with an empty collection and add the key-value pairs one at a time. here is an interactive session using our password dictionary: (©()( 3Âܐ܀ۨßïUΈÆHÏ3ܓñ‡ú û ùÄHɨÌ3ҀC Ç ! Põ pËÎÒHÀPÀ õ pǽƣÛPÉ4Ü£ÆHÌ õ ¡!1ÉÎңÐÁ ¡ 3    ܐ܀ۨßs ï WˆÂÀxɽƈܓñIú (©()( û H!¨ÆÓÇ4ҀÉ4Ü Põ p˽ÀÓɈƽÜPÑxÌÆPÆ£Ç Põ 3¢vÊ Ú ÐÆ£ÛPËÎÒ1Æ Põ †ÜIÉ©ˆÆHÌÌÁg!PÌ€ʐÊ3ÆHÌ ¡ (©()( 3Âܐ܀ۨßï–ÒÓÄƀʆÜ@ñIú û ñ ðÄ1ÉÌ3ÒI§ Ç ! õ H!¨ÆÓÇ4ҀÉ4Ü Œú†õÈñ pËÎÒHÀÀ õ pË3ÀxɽƈÜPÑǪ́ƐÆÓÇ vú“õ ñ pLjÆ1ÛPÉ4Ü£Æ1Ì õ X¢ŒÊ Ú ÐÆ1ÛHË4Ò£Æ vú“õHñ ¡!1ÉÎңÐÁ õ †ÜI) É ½ÆH Ì ̨) Á !PÌ€ÊPÊÎÆHÌ v ú  3     Ü € Ü ¨ Û Ÿ à ï 3 Å ˆ Â Ü Ì  Î H Æ „ Ï ñ p Î Ë H Ò  À À v ú (©()( Ì1É½Æ … ž f ž … Ž }  © ž ‘ Ž } ž … %% } ž %  % 6 Ž}   Å ‘ Q´ …  ¤  ©% }6   .

To update the count for a particular word. We can use a loop that iterates through each word in the document and adds one to the appropriate count. At the highest level. this is just a multi-accumulator problem. Ñ1Á£ÉPÇÄ3Ü Û . The only catch is that we will need hundreds or thousands of accumulators. We will use a dictionary where the keys are strings representing words in the document and the values are ints that count how many times the word appears.”I¿7 (©()( (©()( s4tvuxwzy|{I}†~I~xüé@u†y–uqs‚g± ± { ³ y 6 ‚HŠ†ˆ DˆÂPÀˆÜÓÆ  } èÍHÌÆPà Ò€Ç¥½ÂˆÜP܀Ûà 3Âܐ܀ۨßïp!¨ÆHĉñ –Ë4ÒHÀPÀ Põ pÉPÇcÎHǽÁÓÛPÇ Œú p˽ÀÓɈƽÜPÑxÌÆPÆ£Ç ½ÂˆÜÜIÛÃnïf!¨Æ1Ąñ ÁÓÅÇ õ –ɐǩÎPÇÁ1ÛPÇ Œú (©()( ï pÉPc Ç ÎHǽÁ1ÛHÇ (©()( 3Âܐ܀ۨßï–ÑHÀPƐÂ1̉ñIú (©()( 3Âܐ܀ۨà   ‘ %  f g g ‘ ‘  ÄÅ ÊBÊ'È È‘É Sµ š#›§–B—$ٌ͕i£’”“Hv••“f–'— »¨ w› ¢ Æ¢âvB“ “fi£tr%i•wQœ g¤ Let’s write a program that analyzes text documents and counts how many times each word appears in the document. There is one small complication with using a dictionary here. We need a count for each word that appears in the document. The first time Ñ1ÁÓɐǨÄÎÜ we encounter a word. it will not yet be in . To guard against this. Attempting to access a nonÆHÏ ÌÌ¨ÁHÌ G existent key produces a run-time . This kind of analysis is sometimes used as a crude measure of the style similarity between two documents and is also used by automatic indexing and archiving programs (such as Internet search engines). Let’s call our dictionary we just need a line of code something like this: Ñ1ÁÓɐǨÄÎÜ û C Û Uß Ñ£Á£ÉPÇÄÎÜ û c Û cá Ö Û This says to set the count associated with word to be one more than the current Û count for . one for each unique word in the document. . This is where a (Python) dictionary comes in handy. we need a decision in our algorithm. Ò£ÍcÛ ÒÜUÀ1̨ƨÂ1ÃPÏ¡ÒIÇ Ñ1Á£ÉPÇÄ3Üæ÷ ÂHÃPÃÝÁ£Ç½ÆcĨÁcÄHňÆàÑ1Á£ÉPÇÄW͐ÁHÌ€Û Æ¨ÀÜ£Æo÷ À .

~I~x ¹P ΂1Škib˜Ó{ 1…Œ{‡Š†y 6 u±xsˆ‚± ± { ³ y 6 ‚1ŠŒˆ Ü£Æ1ÄÿÑ1Á£ÉPÇÄW͐ÁH̀ÛÐÄÁ Ö ¨ • ”I¿H~ This decision ensures that the first time a word is encountered. we will also convert all the text to lowercase (so occurrences of “Foo” match “foo”) and eliminate punctuation (so “foo. The dictionary updating code will form the heart of our program.” matches “foo”). . Here’s the code to do that: Í1ǽ€ÊÎÆUßÝÌ£ۧÌҀÇ)É¨Ä„ñ 3D3Ò1ÀPÆ ÄÁÐÂÓǽÀ£Ï ¨Æo÷æÓú ó ÌƐÂHÃWͽÒ1ÀPÆÝÂÜÈÁ£Ç½ÆÝÀHÁ£ÇC!¡ÜxÄPÌ3ҀÇC! € ÄÆg¦PÄÝßÝÁ ˆÆ£ÇoñôÍ1ǽ€Ê3Ƅõ ùÌ Œú¬ïp̨ƨÂ1ÉñIú ó¡Ñ1ÁÓC Ç WÆ1̐ÄÐÂPÀÀWÀHÆHĐĨÆHÌ3Ü ÄÁÝÀHÁ1ۈÆ1Ì¡ÑHÂÜ£Æ ÄÆg¦PÄÝßÿÜxÄPÌ3ÒIǧ!ŸïðÀPÁ£ÛˆÆH̉ñ–ĨÆ)¦PÄÎú ó€ÌÆ"3ÀÂ¨Ñ1ƀƐÂÑIÅ¥ÉÇÎÑÓÄ1É3Â1ĽÒ1ÁÓÇÿрŽÂ1ÌÂÑÓĨÆHÌÈÛÎÒÓÄ1š¡Üq½ÂÑ1Æ Í¨Á1ÌÿÑ€Å Ò€Ç CuŒó ¤Ç‰ñ‡g ú Y£á„ë õ ¨„¡ ï ŸoQ ÷ È ß ( P É û  "Ì ¶Ä˜ÊÃÅVË ¨÷ F Ä) Æ ¦HÄWß ÜxÄPÌ3ҀC Ç !Ÿï–ÌÆ ½ÀÂ¨Ñ1ÆæñèÄg Æ ¦PÄnõlÑIřõ vú ó Üq½ÀÒÓÄ ÿ ۈÁ1̨Ã3Ü ß Ü€ÄÌ½Ò€Ç§!WÂ1ĀÛPÅÎÒÓĨƽÜq½ÂÑ£ÆÈÄÁ€ÍÁHÌÓÊ Ü€ÄÌ½Ò€§ Ç !nïzu Ü 3ÀÒxĄñèÄ) Æ ¦HÄ4ú ÂWÀҨ܀ÄÐÁPÍcÛÁHÌ¨Ã½Ü Ñ1Á£ÉPÇÄ3Ü %h g   ¬ " ´g´ j«¡ 6ú ’ Now we can easily loop through the words to build the dictionary. Û !¨Æ1Ä If is not already in the dictionary. Å3ÂÜ ÎÆHÏ One way to implement this decision is to use the method for dictionaries. The first task is to split our text document into a sequence of words. and the result is that Û the entry for is set to 1. this will return 0. We just need to fill in the parts around it. In the process. it will be entered into the dictionary with a count of 1. ң͡ѣÁ£ÉPÇÄÎܬï|ŽˆÜÌ"ΈÆ1τñèÛ4ú¬÷ Ñ1ÁÓɐÇÄ3Ü û C Û cßÿÑ£Á£ÉÇ¨ÄÎÜ û ÛCUá ƨÀÜ£Æo÷ Ñ1ÁÓɐÇÄ3Ü û C Û cß»Ö Ö A more elegant approach is to use the Ñ1ÁÓɐǨÄÎÜ û ÛCUß Ñ£Á£ÉPÇÄÎܬïf!ÆHĄñð۟õèÕ3úá»Ö !ÆHÄ method.

In order to do that.g. If we simply sort this list ( ) Python will put them in a standard order. which is not what we want. when Python compares tuples. however.. ÒxÄÆ€Ê†Ü method for We can start by getting a list of key-value pairs using the dictionaries. A more interesting analysis is to print out the counts for the ø most frequent words in the document. left to right.e. 0.. word-count pairs) and returns either -1.”I¿€r s4tvuxwzy|{I}†~I~xüé@u†y–uqs‚g± ± { ³ y 6 ‚HŠ†ˆ Ñ1ÁÓɐÇÄ3ÜYߖÄŠͨÁ1Ì€Û Ò€ÇÝۈÁ1̨ýÜæ÷ Ñ1Á£ÉPÇÄ3Ü û c Û cßÿÑ1ÁÓɐǨÄÎÜæïp!¨Æ1ĄñèÛnõ–Õ½úfá»Ö Ñ£Á£ÉÇ¨ÄÎÜ Our last step is to print a report that summarizes the contents of . There will be far too many words.  ÒÓĨÆxʓÜæïzÜÓÁHÌPĄñIú hžhžh ). One approach might be to print out the list of words and their associated counts in alphabetical order. To sort our list of items. most of which only appear a few times. we will need to create a list that is sorted by counts (most to fewest) and then select the first ø items in the list. Unfortunately. it orders them by components. giving the relative order in which we want those two items to appear in the sorted list. Here is the code for a suitable comparison function: èÆHÍ¡Ñ1Á€C Ê 3£Ì§ Æ ¢xÄƀʆÜ@ññèÛ@֓õzшÖPú“õ ñèۈԉõ†Ñ1Ô½úPú¬÷ ң͡ÑÖ ( Ñ1Ôo÷ ÌÆHÄ1ÉÌ1¡ Ç ¨ÿÖ % } %  %  . Since the first component of each pair is the word. ÒÓĨÆxʓÜæïzÜÓÁHÌPĄñIú will put this list in alphabetical order. this is unlikely to be useful. Here’s how that could be done: ó !¨Æ1ÄàÀҐÜxÄÐÁPÍcÛÁH̐Ã3ÜYÄHŽÂ1ÄÐ ¥  ©ˆÆ¨Â1ÌàҀÇàèÁрÉ1ÊÎÆ£Ç¨Ä ÉÇÎÒ í£É½ Æ 4ÁH̐Ã3Ü ß¡Ñ£Á£ÉPÇÄÎܬs ï ÎÆHÏÎÜ@ñIú ó É¨ÄàÀҐÜxÄÐÁPÍcÛÁH̐Ã3܀ҀÇÿÂPÀ"PÅ3ÂÓˈÆHĽҐÑHÂPÀÈÁ1̨ÐÆHÌ £ ɐÇÎÒ í£É½Æ4ÁH̐Ã3ÜæïôÜ£Á1̐Ąñ‡ú ó£̽ҀǨĀۈÁH̐Ã3ÜÈÂxLjÃÐÂܐܣÁѐÒ1Â1ÄÆHÃÐÑ£Á£ÉÇ¨ÄÎÜ Í¨Á1Ì€Û Ò€ÇÝɐÇÎÒ í£É½ Æ 4ÁH̐Ã3Üæ÷ ̽ҀÇÄU۟õ Ñ1ÁÓɐǨÄÎÜ û C Û  For a large document. ÒÓĨÆxʓÜYßÿÑ1Á£ÉPÇÄ3ÜæïôÒxÄƀʆܓñ‡ú û ñ èͨÁPÁ Pë õ 9½ú“õ ñ p˽Â1Ì Põ–þ½ú†õÈñ ŒÜu3Â€Ê õèސþø½ú†õ ÒxÄÆ€Ê†Ü Here will be a list of tuples (e. we need a custom comparison function that takes two items (i. or 1.

however. Finally. Take a look at the decision structure. Notice I have taken advantage of Python’s automatic tuple unpacking and written each parameter as a pair of variables.~I~x ¹P ΂1Škib˜Ó{ 1…Œ{‡Š†y 6 u±xsˆ‚± ± { ³ y 6 ‚1ŠŒˆ ƨÀ¨Ò£Í¡ÑˆÖ ßPß¡ÑHԄ÷ ÌÆHÄ1ÉÌ1Ç Ñ‡ÊcnñèÛ@֓õ ۈԽú ƨÀÜ£Æn÷ ÌÆHÄ1ÉÌ1Ç Ö ¨ • ”I¿€” This function accepts two parameters. ÒÓĨÆxʓÜæïzÜÓÁHÌPĄñvÑ£Áxc Ê 3Â1̨m Æ ¢€ÄÆxʓܨú Now that our items are sorted in order from most to least frequent. each of which is a tuple of two values. we would ̽ҀǨA Ä  c¨3ÖxÕˆÜ c9HÃ6 ©ñèۈÁ1̨Äõ supply a pair of values to fill in the slots (e. the when the second count is larger. In this case. û Ñ1ÁÓɐǨÄ4ú ÒÓÄÆ€Ê†Ü Ò  ). Normally. it is now a simple matter to sort our items into the correct order. then the first item should precede the second in the sorted list (since we want the most frequent words at the front of the list) and the function returns -1.. If the count in the first item is greater than the count in the second item. then we let Python compare the two word strings with чc Ê  . With this comparison function. is a pair. Here’s a loop that does the trick: ͨÁ1ÌÿÒWҀÇÐ̈Âx§ Ç !ÆæñðÇ@ú¬÷ Ì3ÒIÇA Ä  C¨½ÖxÕ½Ü C916 à  ÿÒxÄÆxÊ“Ü û Ò  G" s" " Notice especially the formatted print statement. the function returns a 1 to indicate that the first parameter should follow the second. we are ready to print a report of the ø most frequent words. left-justified in ten spaces. It prints a string. If the counts are equal.g. This ensures that groups of words with the same frequency will appear ƨÀˆÜÓÆ handles the case in alphabetical order relative to each other. Here is the complete program: ócۈÁ1̨ÃPÍPÌg Æ íŸb ï Ï Ò‡c Ê ½Á1̐Äÿ܀ĐÌ3ÒI§ Ç ! R" )" ±" èÆHÍ¡Ñ1Á€ÊC3£ÌƧ¢xÄƀʆÜ@ññèÛ@֓õzшÖPú“õ ñèۈԉõ†Ñ1Ô½úPú¬÷ ң͡ÑÖ ( Ñ1Ôo÷ ÌÆHÄ1ÉÌ1¡ Ç ¨ÿÖ . so Python can extract the two values that it needs. That about does it. followed by an int right-justified in five spaces.

here’s the result of running this program to find the twenty most frequent words in the book you’re reading right now: HÅÎҨܨÌÁ)!ḦÂIÊÿÂÓǽÀ£Ï ¨ÆˆÜ ۈÁ1̨ÃWÍHÌÆ)í£É½ÆÓÇ4ÑÓÏÐҀÇÿ€ͽÒ1ÀPÆ ÂÓÇã̽ҀÇÄ3ÜÈÂUÌÆ"½Á1̐ÄÐÁ£ÇÐÄ1ŽÆÈÇcÊ3Á½ÜxÄÝÍHÌÆgí1ɽÆÓÇÄÈۈÁH̐Ã3Ü¬ï ¨Æn÷ ½ Ë ÁPÁÎhï–Äc¦HÄ É¨ÄgPÉÄÐÂxÇ3À£ÏÎÜHÒ¨Ü ÁHU Í Å½Á1ÛUÊÎÂÓǨÏcۈÁ1̨Ã3ÜgPUÔPÕ %h D3Ò1ÀPÆcĨÁÝÂÓÇ3ÂPÀ1Ï Ä gh .”I¿ ¯ s4tvuxwzy|{I}†~I~xüé@u†y–uqs‚g± ± { ³ y 6 ‚HŠ†ˆ ƨÀ¨Ò£Í¡ÑˆÖ ßPß¡ÑHԄ÷ ÌÆHÄ1ÉÌ1Ç Ñ‡ÊcnñèÛ@֓õ ۈԽú ƨÀÜ£Æn÷ ÌÆHÄ1ÉÌ1Ç Ö Ã¨ÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ Ä XHÅÎҨܨÌÁ)!ḦÂIÊÿÂÓǽÀ£Ï ¨ÆˆÜ ۈÁ1̨ÃWÍHÌÆ)í£É½ÆÓÇ4ÑÓÏÐҀÇÿ€ͽÒ1ÀPÆB ̽ҀÇ Ä IÂÓÇ£ à ̽ҀÇÄ3ÜÈÂUÌ" Æ ½Á1̐ÄÐÁ£ÇÐÄ1ŽÆÈÇcÊ3Á½ÜxÄÝÍHÌÆgí1ɽÆÓÇÄÈۈÁH̐Ã3ܬï ÓÇx %h w´ ó¥!¨Æ1ÄWÄHŽơÜÓÆ)í£É½Æ£ÇÎÑ1ƀÁHÍcۈÁ1̨Ã3Ü ÍPÌÁ€Ê¡ÄHňƀͽÒHÀHÆ Í1ǽ€ÊÎÆUßÝÌ£§ Û ÌҀ) Ç É¨Ä„ñ 3D3Ò1ÀPÆ ÄÁÐÂÓǽÀ£Ï ¨Æo÷æÓú Äg Æ ¦PÄÝßÝÁ ˆÆ£ÇoñôÍ1ǽ€Ê3Ƅõ ùÌ Œú¬ïp̨ƨÂ1ÉñIú Äg Æ ¦PÄÝßÿÜxÄPÌ3ÒI§ Ç !ŸïðÀPÁ£ÛˆÆH̉ñ–Ĩ) Æ ¦PÄÎú ͨÁ1ÌÿÑ€Å Ò€Ç CuŒó ¤Ç‰ñ‡g ú Y£á„ë õ ¨„¡ ï ŸoQ ÷ È ß ( P É û  "Ì ¶Ä˜ÊÃÅVË ¨÷ F Ä) Æ ¦HÄWß ÜxÄPÌ3ҀC Ç !Ÿï–ÌÆ ½ÀÂ¨Ñ1ÆæñèÄg Æ ¦PÄnõlÑIřõ vú ۈÁ1̨Ã3Ü ß Ü€ÄÌ½Ò€§ Ç !nïzu Ü 3ÀÒxĄñèÄ) Æ ¦HÄ4ú  ¬ " g  %h ´g´ j«¡ 6ú ’ ó¡Ñ1ÁÓÇ@ÜxÄPÌHÉÎÑÓÄÐÂcÈҐÑÓĽÒ1ÁÓÇ3Â1ÌPÏWÁHÍcۈÁH̐áÑ1ÁÓɐÇÄ3Ü Ñ1ÁÓɐÇÄ3ÜYߖÄŠͨÁ1Ì€Û Ò€ÇÝۈÁ1̨ýÜæ÷ Ñ1Á£ÉPÇÄ3Ü û c Û cßÿÑ1ÁÓɐǨÄÎÜæp ï !¨Æ1ĄñèÛnõ–Õ½úfá»Ö óÝÁ£É¨g Ä É¨ÄÐÂÓǽÀ£ÏÎÜPÒÜ ÁPÍUǀÊ3Á½ÜxĀÍPÌÆgí1ɈƣÇÄUۈÁH̐Ã3ܬï ÇàßÿҀǩPÉĉñ  Ä ÉĐÉĀÂÓǽÀ£ÏÎÜPÒÜ ÁPÍUňÁ1ÛUÊÎÂÓÇÏUۈÁH̐Ã3ÜgPa£ú ÒÓĨÆxÊ†Ü ß Ñ£Á£ÉPÇÄÎܬïôÒxÄÆxʓܓñ‡ú ÒÓĨÆxʆܬïzÜÓÁH̐ĉñvÑ£ÁxC Ê ½Â1̨m Æ ¢xĨÆxʓܨú ͨÁ1ÌÿÒWҀÇÐ̈Âx§ Ç !ÆæñðÇ@ú¬÷ Ì3ÒIÇA Ä  C¨½ÖxÕ½Ü C916 à  ÿÒxÄÆxÊ“Ü û Ò  Ò£ÍSÌ)ÌÓǽ€ÊÎÆ©Ì©ÌUßPß G" s" " | f ëÌ)̀Ê4¨ҀÇmÌ©Ì ¨÷ŽÊÎÂҀÇoñIú Just for fun.

~€~€ ¿HHs@tŒuxw†y|{‡}%˜¨…€ƒ„ƒŸu‡}‘ç ”I¿€´ ÄHÅˆÆ Â ÁPÍ ÄÁ Ò¨Ü ÄHŽÂ1Ä ÂÓÇÃ Ò€Ç ÛˆÆ ÄHÅÎÒ¨Ü Í¨Á1Ì ÏÁÓÉ ̨) Á !HÌˆÂ€Ê Ë½Æ ÒÓÄ Â1Ì¨Æ ÂˆÜ ÑHÂxÇ ÛÎÒ1ÀÀ ÂÓÇ “„“•”sr ø)d¨Ô)e Ô)egdC9 ÔPøÔÔ Ô d© g ø e ÖxýPސø ÖxÞPÞ¨Ô ÖÓ) Ô 9Pý ÖÓ Ô d¨Õ ÖxÕPÞÕ ý)ec9 þ3Öxý þPÕ¨Ô ø)e)d øPþÕ ø3Öe ø3ÖÓÔ øPՐþ 9geÞ d©eÕ dþÕ  ˜Ÿi„¤n…‚™g © ¦§› › ingIí This chapter has discussed techniques for handling collections of related information. ’ Python lists are similar to arrays in other programming languages. Items can be accessed by indexing and slicing. ’ One particularly important data processing operation is sorting. Python Ü£ÁHÌPÄ lists have a method that can be customized by supplying a suitable comparison function. Here is a summary of some key ideas: ’ A list object is a mutable sequence of arbitrary objects. This allows programs to sort lists of arbitrary objects. The items of a list can be changed by assignment. Python lists also support a number of useful methods. . Python lists are more flexible because their size can vary and they are heterogeneous.

Standard deviation measures how spread out a data set is. 5. “„“•”s‘ egf„‚hgIƒ¬‡‘‚„‘ hjiCkmlniCoqpIrQi§sutqlnvxw%s y{zH|c})~Q©€cˆ‚3} 1.”I¿€¹ s4tvuxwzy|{I}†~I~xüé@u†y–uqs‚g± ± { ³ y 6 ‚HŠ†ˆ ’ Classes can use lists to maintain collections stored as instance variables. ’ An entire program can be viewed as a collection of data and a set of operations—an object. . Python lists are not mutable. ÌHÉˆÆ ÃÆ¨À operator. A comparison function returns either 9. For example. DˆÂPÀˆÜ£Æ or . Items can be removed from a list with the 8. ’ A Python dictionary implements an arbitrary mapping from keys into values. but lists are homogeneous. Arrays are usually heterogeneous. A list must contain at least one item. 3. a GUI application might use a list of buttons instead of an instance variable for each button. It is very useful for representing nonsequential collections. 4. A tuple is similar to a immutable list. 7. Unlike strings. The median is the average of a set of data. A Python list cannot grow and shrink in size. A Python dictionary is a kind of sequence. 6. Oftentimes using a list is more flexible than using separate instance variables. 10. This is a common approach to structuring GUI applications. 2.

Which of the following is not a built-in sequence operation in Python? a) sorting b) concatenation c) slicing d) repetition 3. Where mathematicians use subscripting. Which of the following is not a Python list method? ҀÇèÆ)¦ ҀÇ4Ü£ÆHÌPÄ !¨Æ1Ä ˆÁ  a) b) c) d) 5. Which of the following is not a characteristic of a Python list? a) it is an object b) it is a sequence c) it can hold objects d) it is immutable 6. Given the initial statements ҇ÊCˆÁHÌPÄÿÜxÄPÌ3ҀÇC! ÜÖ ß û Ôæõ‡Ö“H õ doõèÞ) Ü1Ôcß û zÑ õ ô õ –Ë  £ € 6 g ‘ H . Which of the following is not a dictionary method? Å3ÂÜ ÎÆHÏ ÎÆHÏ3Ü Ü£ÁHÌPÄ ÑHÀPƐÂ1Ì b) c) d) a) ÒÓĨÆxÊ“Ü 10. computer programmers use a) slicing b) indexing c) Python d) caffeine 2. The parameter in is what? a) median b) mode c) spread d) mean чc Ê n" ñ IB  3§ õ  '£ú 8. Which of the following expressions correctly tests if ¦ ÐԀߐßÝÕ ÆgW¨Æ£Çoñë¦Îú ǽÁHÄÐÁHÐÃæñë¦Îú b) c) a) ¦£Ë3Â£Ì ÜxĐà ˆ Æ W 7. The method that adds a single item to the end of a list is Æ ¦HÄÆ£Çà ) Â1Ðà 3ÀxÉ@Ü Â")½ÆÓLjà a) b) c) d) 4. The dictionary method returns a(n) a) int b) list of tuples c) bool d) dictionary  …Œ‚3‹|c‚8‚X…ŒŠm 1.~€~€ âHcŽŒ{I} ³Œ6 ˆ–{zˆ ƒ |§„3…‡†§ˆ}Iˆj‰cŠ§…Œ‹"} ”I¿€¿ 1. What is the result of ? a) -1 b) 1 c) True d) Error " ¦ u is even? ¦ àÔcßPßS¦ d) " Rh 9.

and the output file. ÊÎƨÂx% Ç Å£Ä¨Ã g Æ W‰ñðǐÉ1ʆܐú ǐÉHÊ“Ü Returns both the mean and standard deviation of . Extend the program so that it allows the user to sort a file of students based on gpa. Üֆïp̨ÆxÊÎ Á WƬñ†Ô½ú (a) ÜֆïzÜÓÁH̐ĉñIú (b) Üֆïè  ©½ÆÓLjÃæñ û Ü£Ôoï–ҀLjÐ) Æ ¦æñ pË v ú 3ú (c) Ü1ԄU ï ˆÁ nñvÜֆU ï ½" Á nñzÔ½úú (d) Ü1ԄïôÒIÇ@Ü£Æ1̐ĉñ‡ÜÖ û g Õ oõ èà Œú (e) ¤ …   ’”“fv••“H–B—$—˜l™wm•Sš#›§i•“¡œ©lnsi§s 1. Your program should prompt for the input file..e. redesign the library to have the following functions: ÊÎƨÂxÇnñùǐÉHʓܨú ÇPÉHÊ“Ü Returns the mean of numbers in . show the valÜÖ Ü1Ô ues of and after executing each of the following statements.”I¿€â s4tvuxwzy|{I}†~I~xüé@u†y–uqs‚g± ± { ³ y 6 ‚HŠ†ˆ show the result of evaluating each of the following sequence expressions: ÜÖ á Ü£Ô (a) Þ YÝÜÖ áàS ¡ Ô YÐÜ1Ô (b) ÜÖ û Öq (c) ÜÖ û ֆ÷ðÞ) (d) ÜÖ á Ü£Ô û ¨½ Ö  (e) 2. assume that and start with their original values each time). name. Bonus: Allow the user to do multiple sorts and add a button for quitting. ! 3ˆÜÓÁHÌPÄ 2. . Specifically. the field to sort on. Treat Ü¨Ö Ü1Ô each part independently (i. Modify the statistics package from the chapter so that client programs have more flexibility in computing the mean and/or standard deviation. Given the same initial statements as in the previous problem. Give the program from the previous exercise(s) a graphical interface. or credits. 4. 3 u 3. ÜxĨà ˆ Æ W„ñðÇPÉHʓܨú ǐÉHÊ“Ü Returns the standard deviation of . You ÇĐÌPÏ s for the input and output file names and a button for should have G each sorting order. Extend your solution to the previous problem by adding an option to sort the list in either ascending or descending order.

These tuples will get sorted into GPA order. like shuffling a deck of cards.~€~€ âHcŽŒ{I} ³Œ6 ˆ–{zˆ ”I¿€é 5. An alternative to creating a special comparison function is to create a “decorated” list that will sort in the desired order using the standard Python Å1Ä1ɈÐƣÇÄ ordering. The resulting list can then be traversed to ! 3ÂÜ£ÁHÌPÄ rebuild a list of student objects in GPA order. since this function is called repeatedly as Python чC Ê  is needs to compare various items. ÒIǐLjÆH̐ØPÌÁHÉñ름õðÏÎú 7. Most languages do not have the flexible built-in list (array) operations that Python has. Write and test a function random order. Redo the program using this approach. . as a function. sorting with the default much faster. For example. Obviously. Write and test a function plicate values from a list. Write an algorithm for each of the following Python operations and test your algorithm by writing it up in a suitable funcÌÆgW¨ÆHÌ3Ü£Ææñ–ʽÏ)¤3Ҩ܀Ä4ú tion. to sort objects by GPA. you are not allowed to use the corresponding Python method to implement your function. For example. Usually. should do the same as ʽ© Ï ¤½Ò¨Ü€Ä™ïp̨g Æ W¨ÆHÌÎÜÓÆæñ‡ú . Write and test a function that computes the inner product of two (same length) lists. we could first û Ò ñ !3ÂHÕ„Ô õ Å£ÄHÉèƣǨÄÕ½ú†õÈÒ ñ !½Â3Ö“Ò õ Å1Ä1ɈèÆÓÇÄ4ÖPú†õUïPf ï create a list of tuples and then sort this list without passing a comparison function. ̨ÆxÊ3ÁgWÆ PÉ)3ÀÒPÑH£ÄƽÜ@ñ‡ÜÓÁxÊÎƐÀҐ܀ÄÎú ! – – r that removes du- ÜÓÁHÌÄ 9. The inner product of “ and is computed as: t Á rÌ ·B¶ ¹ “§r 8. One disadvantage of passing a function to the list method is that it makes the sorting slower. (a) (b) (c) (d) (e) ʈ© Ï ¤½Ò¨ÜxğïôÑ£Á£ÉÇ¨Ä„ñÒ¦Îú (like ) Ò¨ÜHҀÇoñpʽÏ)¤3ҐÜxÄnõ5¦Îú ¦ ҀÇcʈϩ¤3ҐÜxÄ ÿ (like )) ҀÇèÆg¦‰ñpʈϩ¤½Ò¨ÜxÄoõ5¦3ú ʈ© Ï ¤½Ò¨ÜxğïôÒILjèg Æ ¦‰Ò ñ ¦Îú (like ) ÌÆWÆ1ÌÎܣƬñpʈϩ¤3ҐÜxÄÎú ʽ) Ï ¤3ҐÜxęï–Ì Æ WÆHÌ3ܣƬñIú (like ) Ü£Á1̐ĉñpʽÏ)¤3ҐÜxÄ4ú ʽ© Ï ¤½Ò¨Ü€Ä™ïzÜÓÁHÌPĄñIú (like ) Ñ1ÁÓɐǨĄñpʈϩ¤½Ò¨ÜxÄoõ5¦3ú ܇ŐÉ͐ÍÀHÆæñ–ʽ© Ï ¤½Ò¨Ü€Ä4ú that scrambles a list into a 6.

and you may assume that no words in the file are split across multiple lines. For example. 13. if we wished to find all the primes up to 10. You can ignore punctuation. Extend the program from the previous exercise to accept a file of censored words as another input. This process continues until the list is empty. all of the same suit Four of a Kind Four of the same rank Full House Three of one rank and two of another Flush Five cards of the same suit . Write a program that prompts a user for ø and then uses the sieve algorithm to find all the primes less than or equal to ø . That leaves 3. all of the same suit Straight Flush Five ranks in a row. where each line in the file represents a single card with the rank and suit separated by a space. since they are multiples of 2. That leaves 5 and 7. 9. Extend the previous program to analyze a list of five cards as a poker hand. 10. 7 is announced and removed. 8. Write a program that creates a list of card objects (see Programming Exercise 11 from Chapter 10) and prints out the cards grouped by suit and in rank order within suit. Finally. The first number is removed from the list. Then 4. 6. Royal Flush 10. 8.”Iâ7 s4tvuxwzy|{I}†~I~xüé@u†y–uqs‚g± ± { ³ y 6 ‚HŠ†ˆ 10. 5. The algorithm continues by announcing that 5 is prime and removing it from the list. The basic idea is to first create a list of numbers from 2 to ø . 11. 3. 4. 6. and announced as a prime number. and 10 are removed. and we’re done. Queen. the list would originally contain 2. 12. Your program should read the list of cards from a file. King. 7. 5. 3 is announced as prime and removed. Jack. Repeating the process. and all multiples of this number up to ø are removed from the list. The words in the original file that appear in the censored words file are replaced by an appropriate number of ”*”s. The 2 is removed and announced to be prime. 9. Ace. The Sieve of Eratosthenes is an elegant algorithm for finding all of the prime numbers up to some limit ø . Write an automated censor program that reads in the text from a file and creates a new file where all of the four-letter words have been replaced by ”****”. and 9 is removed because it is a multiple of 3. Hint: first sort by rank and then by suit. 14. the program categorizes accordingly. After printing the cards. 7.

~€~€ âHcŽŒ{I} ³Œ6 ˆ–{zˆ ”IâH~ Straight Five ranks in a row Three of a kind Three of one rank (but not a full house or four of a kind) Two pair Two each of two different ranks Pair Two of the same rank (but not two pair. . ÊÎÆPÈÒHÂxÇnñ‡ÜÓƨÀ1ÍÎú ÜxÄÂ1ÄCÅPÆHÄ Returns the median of the numbers in this . Create a class called that can be used to do simple statistical calculations. For example. the hand is “Jack high. dealCard Returns a single card from the top of the deck and removes the card from the deck. shuffle Randomizes the order of the cards. See Programming Exercises 8 and 9 in Chapter 9. ҀÇÎÒÓÄ ñ‡ÜÓƨÀHÍ3ú 3 Test your class with a program similar to the simple statistics program from this chapter. Create a class that represents a deck of cards (see previous exercise). You could also use your deck object to implement a Blackjack simulation where the pool of cards is finite. three or four of a kind) X High If none of the previous categories fit. Your class should have the following methods:  constructor Creates a new deck of 52 cards in a standard order. The methods for the class are: Creates a statSet with no data in it. if the largest rank is 11. ÊÎƨÂxÇnñvܣƨÀ1ÍÎú ÜxÄÂ1ÄCÅPÆHÄ Returns the mean of the numbers in this . ÂHÐÃgÐHÉ1Ê˽Æ1̄ñvܣƨÀ1ÍoõH¦Îú˜¦ ¦ ÜxĈ£ħÅHÆHÄ is a number. Adds the value to the . Ñ1Á£ÉPÇĉñ‡Ü£ÆÀHÍ3ú ÜxÄÂ1§ Ä ÅHÆHÄ Returns the count of numbers in this . ʓҀÇoñ‡ÜÓƨÀHÍ3ú ܀ĈÂ1C Ä ÅPÆ1Ä Returns the smallest value in this . ţĈÂ1C Ä ÅPÆ1Ä 16. X is the value of the highest rank.” ƈÑÎ 15. Test your program by having it deal out a sequence of ø cards from a shuffled deck where ø is a user input. cardsLeft Returns the number of cards remaining in the deck. ÜxĨà ˆ Æ W„ñ‡ÜÓƨÀ1ÍÎú Üxˆ Ä Â£Ä§ÅHÆHÄ Returns the standard deviation of the numbers in this . Ê4g  ¦æñ‡ÜÓƨÀHÍ3ú ܀ĈÂ1C Ä ÅPÆ1Ä Returns the largest value in this .

a face might be drawn from individual shapes. Start your walker in the middle of a sidewalk of length ø where ø is a user input. the set is left unchanged. Your sets should support the following methods: ÅPÆHĉñzƐÀPÆxÊ3ƣǨÄÎܨú ƨÀPƀÊÎÆÓÇÄÎÜ Create a set ( is the initial list of items in the set). and continue the simulation until it drops off one of the ends. èƨÀHÆHÄ¨Æ ÀHÆxÊ3Æ£Çĉë ñ ¦3ú ¦ ¦ G Removes from the set. if present. Extend the random walk program from Chapter 9 (Programming Exercise 12) to keep track of how many times each square of the sidewalk is crossed. 18. In graphics applications. ÊÎÆxʨ˽Æ1̄ë ñ ¦3ú ¦ Returns true if is in the set and false otherwise. For example. A will manage a list of graphics objects and have the following methods: ҀÇÎÒÓÄ ñ‡ÜÓƨÀḦ́õ ÂÓÇÎрňÁHÌ4úªÂxÇ4рňÁHÌ Ø¨ÁˆÒIÇÄ is a .”Iâ€r s4tvuxwzy|{I}†~I~xüé@u†y–uqs‚g± ± { ³ y 6 ‚HŠ†ˆ 17. . ҀÇĨÆHÌ3ܣƈÑxÄ3Ò£Á£ÇnñvÜ£Æ1ĈԽú Returns a new set containing just those elements Ü£Æ1ÄˆÔ that are common to this set and . it often useful to group separate pieces of a drawing together into a single object. ɐLjÃḦÂÓÛoñ‡ÜÓƨÀ1ÍÎú Undraws all the objects in the group. Create a new ü Ì" ü Ì"  PÅ4ÒÑÜ ü ÌÁ£) É   ÅÎÒÑÜ ü ̨Á£) É  class that can be used for this purpose. The anchor point is not drawn. but then positioned as a whole group. ÃP̈ÂÓÛoñvܣƨÀ1Íoõ ÛÎҀÇ@ú Û3Ò€Ç Draws all the objects in the group into . Adds ï ï ï ï to the group. Use your new class to write a program that draws some simple picture with multiple components and move it to wherever the user clicks. !¨ÆHÄ Ú ÇÎрŽÁ1̄ñvܣƨÀ1ÍÎú Returns a clone of the anchor point. If is not in the set. Creates an empty group with the given anchor point. ÂHÐà ÀHÆxÊÎÆÓÇĉë ñ ¦Îú ¦ G Adds to the set. ÅPÆ1Ä 19. Then print out the counts of how many times each square was landed on. ÂHÃÃ Ä Ë ÆˆÑxĄñvܣƨÀ1ÍoI õ ! Ä Ë ÆÑÓÄÎæ ú ! Ä Ë ÆˆÑxÄ ! Ä Ë ÆˆÑxÄ is a graphics object. Create and test a class to represent a classical set. ÊÎg Á W¨ÆæñvܣƨÀ1Íoõ © à ¦oõðÃPÏÎú Move all of the objects in the group (including the anchor point).

~€~€ âHcŽŒ{I} ³Œ6 ˆ–{zˆ ɐÇ4Ò£Á£Çoñ‡Ü£Æ1ĈԈú Returns a new set containing all of elements that are in this Ü£ÆHÄÔ set. ”I— . or both. ÜIɐ˨ĐÌÂÑÓĉñ‡ÜÓÆHĈԈú Returns a new set containing all the elements of this set ÜÓÆHÄÔ that are not in . .


it’s time to stretch your wings and really put those tools to work. In this chapter. This so-called objectoriented design (OOD) process is a powerful complement to top-down design for the development of reliable. Other components are users or clients of the services. ’ To be able to read and understand object-oriented programs. Î ® É . cost-effective software systems. we will look at the basic principles of OOD and apply them in a couple of case studies. Most modern computer applications are designed using a data-centered view of computing.QSRUTWVYXa`cb dè£ Ã ¦ Ä —Æ  ШxÍ Ã i ¨ ¥ ¦©¨©t 1 òV¥Hv ¦ x€y31‚„ƒ†…ˆ‡‰„‚„‘ ’ To understand the process of object-oriented design. “o•«”–“ — ˜Ÿ‚m—˜gI™qƒ­‚„‘‘W™„ìfxWxa« Now that you know some data structuring techniques. ’ To be able to design moderately complex software using object-oriented design. Each component provides a set of services through its interface. polymorphism and inheritance as they pertain to object-oriented design and programming. ’ To understand the concepts of encapsulation. The essence of design is describing a system in terms of magical black boxes and their interfaces.

Object-oriented design is the process of finding and defining a useful set of classes for a given problem. The magic behind objects lies in class definitions. This separation of concerns is what makes the design of complex systems possible. A client program can use a function as long as it understands what the function does. functions serve the role of our magical black boxes. I’m not convinced that reading many thick volumes will help much either. Like all design. If we can break a large problem into a set of cooperating classes. I can’t pretend to teach you all about OOD in one short chapter. The black box just has to make sure that the service is faithfully delivered. the component providing the service does not have to consider how the service might be used. we drastically reduce the complexity that must be considered to understand any given part of the program. the internal details may change radically and not affect the client at all. Look for object candidates. The details of how the task is accomplished are encapsulated in the function definition. here are some intuitive guidelines for object-oriented design: 1. All ü ̈"  Pc Å 43Ò€Ç and the nitty-gritty details are encapsulated in the class definitions for ׈ÒxÌ3Ñ1ÀPÆ . Start with a careful consideration of the problem statement. There are many different approaches to OOD. notations. The more you design. Objects are usually described by nouns.”I‹ s@tŒuxw†y|{‡}†~†rH˜Ñ  Ê { ³ y•iUÑn} 6 {‡Š†y|{z‹ 4 é {zˆ 6 HŠ A client only needs to understand the interface of a service. gurus. each with its own special techniques. Just to get you started.. On the other hand. Each class stands on its own. the details of how that service is implemented are not important. The best way to learn about design is to do it. Things that seem to involve a grouping of related data items (e. Which of them will actually be represented in the program? Which of them have “interesting” behavior? Things that can be represented as primitive data types (numbers or strings) are probably not important candidates for objects. the black boxes are objects. In top-down design.g. In object-oriented design. You might underline all of the nouns in the problem statement and consider them one by one. coordinates of a point or personal data about an . Similarly. Once a suitable class definition has been written. In fact. This is what allows you to draw circles in graphics !P̈  ÅÎÒÑ¨Ü windows without so much as a glance at the code in the module. Your goal is to define a set of objects that will be helpful in solving the problem. the better you will get. it is part art and part science. and textbooks. we can completely ignore how the class works and just rely on the external interface—the methods.

others might themselves be complex types that suggest other useful objects/classes. Use top-down design and stepwise refinement to flesh out the details of the more difficult methods. When you have identified a potential object/class and some associated data. coined the maxim: “Plan to throw one away. As you work through the design. List the methods that the class will require. Design iteratively. you may very well discover that some new interactions with other classes are needed. Some methods will look like they can be accomplished with a couple of lines of code. Remember that all manipulation of the object’s data should be done through the methods you provide. 2. Think about interfaces. Once you have uncovered some possible objects. What kinds of values will the instance variables have? Some object attributes will have primitive values. As you go along. a legendary software engineer. think about the information that each object will need to do its job. Strive to find good “home” classes for all the data in your program. systematic fashion. Don’t be afraid to scrap an approach that doesn’t seem to be working or to follow an idea and see where it leads. Identify instance variables. Work on whatever seems to be demanding your attention. Try out alternatives. you will bounce back and forth between designing new classes and adding methods to existing classes. think about what operations would be required for objects of that class to be useful. 5. it probably is not the result of a first try.~zrP ~x£ã‰tŒ{£½}$‚ ³ {ôˆpˆæ‚‡å6Ñ Ñjé ”I‿ employee) probably are. you are seeing finished work. 6. 4. . No one designs a program top to bottom in a linear. Verbs are used to describe actions—what must be done. When you look at the programs of others. Refine the nontrivial methods. Make progress wherever it seems progress needs to be made. not the process they went through to get there.” Often you won’t really know how a system should be built until you’ve already built it the wrong way. Other methods will require considerable work to develop an algorithm. Good design involves a lot of trial and error. If a program is well designed. Fred Brooks. You might start by considering the verbs in the problem statement. Sometimes you may discover a need for a brand-new kind of object that calls for the definition of another class. and this might force you to add new methods to other classes. 3.

try to find the simplest approach that will solve the problem at hand. A game will have to keep track of information about two players. The next sections will walk you through a couple case studies that illustrate aspects of OOD. “o•«”–•  ¢in‘‚©©£…ΦŸ·•í ² c ©˜ îiŸƒ «¦Ÿ‚æ…3y™i„j j ©a‡p› ¦„j io…‡™£e For our first case study. Let’s tackle simulation of the game first. This short description already suggests one way of dividing up the work in the program. you will be ready to tackle your own programs and refine your design skills. Our simulation should keep track of both the number of wins for each player and the number of wins that are shutouts. Keep it simple. We could create and play a racquetball game with two lines of code: % . When we create a new game. We can use an object to represent a single game of racquetball. The output is a nicely formatted summary of the results. we ended a game when one of the players reached a total of 15 points. In the original version of the program. we will specify the skill levels of the   ÀÀ ü ÂIÊÎÆ players. What does our program need to do with a game? Obviously. let’s also consider shutouts. and the number of games to simulate. Let’s give our class a method that simulates the game until it is over. the game ends. This suggests a class. the probability for player B. At each step in the design. If one player gets to 7 before the other player has scored a point.”Iâ€â s@tŒuxw†y|{‡}†~†rH˜Ñ  Ê { ³ y•iUÑn} 6 {‡Š†y|{z‹ 4 é {zˆ 6 HŠ 7. Don’t design in extra complexity until it is clear that a more complex approach is needed. We need to do two basic things: simulate a game and keep track of some statistics. The inputs to the simulation are the probability for player A. let’s call it . We need to simulate a series of racquetball games between two players and record some statistics about the series of games. ÊmÇȑÇÈƒÊ ª §› U› ¤Ÿƒ¾s¿ –'w 'l B–mtui 3imœ)tusI–Bw §› ¶ )  £› iCt Qv Bs Our first task is to find a set of objects that could be useful in solving this problem. Once you thoroughly understand these examples. it needs to play 3ÀÂ£Ï it. You might want to go back and review the program that we developed the first time around using top-down design. This time around. with a constructor that requires parameters for the probabilities of the two players. The crux of the problem is to simulate multiple games of racquetball where the ability of the two opponents is represented by the probability that they win a point when they are serving. let’s return to the racquetball simulation from Chapter 9.

This object will be an instance of a class called Ũ҇Q Ê Å1Ĉ£ÄÎÜ A object will keep track of all the information about a series of games. Here we have four related pieces of information. This suggests a report of the accumulated statistics. wins for B.~zrP rP1sˆuŒˆp{ x ˜ y腌‹Iç ´ ÄHÅˆÆ ü €  ÊÎÆUßE  ˆÂPÀÀ ü €Ê3ÆæñfÌÁÓË Ú õ ¨  ÌÁ£Ë 4ú ÄHÅˆÆ ü €  ÊÎÆoïU½ÀÂ1ωñIú % % fi • w u ³ 1…Œ{–y vu± ±˜ 6 ƒ•…± u†y 6 ‚HŠ ”Iâ€é To play lots of games. we need a constructor that initializes all of the counts to 0. Most of the details have been pushed off into the definition of our two classes. when all of the games have been simulated. single object. We will also print out the number of games simulated. We have already analyzed the four crucial pieces of information. and shutouts for B. An easy apÉ ˆÃ¨Â1ÄÆ ) extract whatever proach would be to just send the entire game and let information it needs. For starters. shutouts for A. we will have to keep track of at least four counts in order to print a summary of our simulations: wins for A. We also need a way of updating the counts as each new game is simulated. The update of the statistics will be Let’s give our object an based on the outcome of a game. We have now done enough design that we can actually write the main function for our program. Finally. Let’s turn our attention to collecting statistics about the games. we need to print out a ̽ҀǨ) Ä  ˆ" Æ ½Á1ÌÄ method that prints out a nice report of the results. É ˆÃ¨Â1Ä¨Æ © method. We will have to send some information to the statistics object so that the update can be done appropriately. That’s all we   ÀPÀ ü ÂIÊÎÆ really need in to write the main program. Now we have to decide what operations will be useful. Rather than treating them independently. let’s group them into a Ũ҇Q Ê Å1Ĉ£ÄÎÜ . but this can be calculated by adding the wins for A and B. Obviously. we just need to put a loop around this code. èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ% Ä ¢IǨĐÌÁ¬ñIú ̨Á£Ë Ú I õ ̨Á£Ë nõîÇ¡¥ ß !¨Æ1Q Ä ¢‡© Ç É¨ÄÎÜ@ñIú ó€ØˆÀPÂ1ÏWÄHňT Æ !ÂIÊÎÆ½Ü ÜxÄÂ1ÄÎÜ ¡ ß Å¨Ò‡Q Ê Å1Ĉ£ÄÎÜ@ñIú ͨÁ1ÌÿÒWҀÇÐ̈Âx§ Ç !ÆæñðÇ@ú¬÷ ÄHÅ½Æ ü ÂIÊÎÆcE ß   ˆÂÀPÀ ü €ÊÎƬH ñ ¨ÌÁ£Ë Ú õ ̨Á£Ë 4úYó¡ÑǪ́ƨ£ÄÆWÂÈǽƣ  Û !ÂIÊÎÆ ü ÄHÅ½Æ ÂIÊÎÆnb ï 3ÀPÂ1τñ‡ú ó 3ÀPÂ1ÏÿÒxÄ £ ÜxĈ£ÄÎܬï|© É Ã£ÄÆæñèÄHÅˆÆ ü ÂIÊÎƽú ó !¨Æ1ÄÿҀÇͨÁÝÂÓˈÁ£É¨Ä¡Ñ1Á€C ¥ Ê 3ÀHÆHĨÆPÃE!¨Â€Ê3Æ ó€ØÌ½Ò€ÇÄWÄ1ŽÆc̨ƽÜIɽÀ1Ä3Ü ÜxÄÂ1ÄÎܬU ï ¨Ì3ҀǨ) Ä  Æ ½Á1̐ĉñIú % % g % .

It takes a game as a normal parameter and must update the four counts accordingly.   ˆÂPÀÀ ü €Ê3Æ class. We Our analysis suggests the need for a new method in the  ü ÂIÊÎÆ need to extend the interface so that has a way of reporting the final score. we are not the game. ÅÒvʕÅ1ÄÂ1Ä3Ü Now we have to flesh out the details of our two classes.”Ié7 s@tŒuxw†y|{‡}†~†rH˜Ñ  Ê { ³ y•iUÑn} 6 {‡Š†y|{z‹ 4 é {zˆ 6 HŠ I have also used a couple of helper functions to print an introduction and get the inputs. !¨Æ1§ Ä Å¨Ñ1ÁHÌ¨Æ½Ü Let’s call the new method and have it return the score for player A and the score for player B. Here is an obvious approach: ÑHÀPˆÜPÜ`ÅÒvʕÅ1ÄÂ1Ä3Üæ÷ èÆHS Í Ì©ÌÒIÇ4Òx§ Ä Ì©Ì­ñ‡ÜÓƨÀHÍ3ú¬÷ ܣƨÀ1͟ï|ÛÎҀÇ4Ü Ú ßÝÕ Ü£Æ¨À1͟ï|ÛÎҀÇ4Ü cßÝÕ Ü£Æ¨À1͟ïôÜIŐɨÄÎÜ Ú ßÝÕ Ü£Æ¨À1͟ïôÜIŐɨÄÎÜ €ßÝÕ s m É©ˆÃ¨Â1Ä¨Æ Now let’s take a look at the method. Remember. É ˆÃ¨Â1Ä¨Æ © Now the algorithm for is straightforward. You should have no trouble writing these functions. ÊmÇȑÇÈ‘Ç äU—æٌ͕iB—îi•wmtql™w%• Ø l™— Ø tu–§tus ÅÒv• Ê Å£ÄˆÂ1Ä3Ü The constructor for just needs to initialize the four counts to 0. The class looks pretty easy—let’s tackle that one first. but this information resides inside of  ü €Ê3Æ allowed to directly access the instance variables of . We don’t even know yet what those instance variables will be. The heading of the method will look like this: èÆHÍUÉ©ˆÃ¨Â1ĨÆæñ‡ÜÓƨÀ1Íoõl ü ÂIÊÎƽú¬÷ But how exactly do we know what to do? We need to know the final score of  ü €Ê3Æ . èÆHÍUÉ©ˆÃ¨Â1ĨÆæñ‡ÜÓƨÀ1Íoõl ü ÂIÊÎƽú¬÷ ‰õ Ëàßà ü €ÊÎÆof ï !ÆH§ Ä Å¨Ñ1Á1ÌƽÜ@ñIú Ò£ÍР( ˄÷ ó Ú ÛˆÁÓÇÐÄHŽT Æ !¨Â€Ê3Æ ÜÓƨÀ1͟ï–Û3ҀÇ4Ü Ú ßÿÜÓƨÀ1͟ï–Û3ҀÇ4Ü Ú á»Ö ÒÓÍUËàߐßÐÕn÷ ÜÓƨÀHÍnïz܇ŐÉÄ3Ü Ú ß Ü£Æ¨À1͟ïôÜIŐɨÄÎÜ Ú á Ö Æ¨ÀˆÜÓÆn÷ ó €ÛˆÁÓÇÐÄHŽT Æ !¨Â€Ê3Æ %  .

Let’s write the basic method. and we must avoid division by zero in calculating the shutout percentage for a player who didn’t get any wins. We want to get the columns lined up nicely. shutouts. win percentage. but procrastinate a bit ¨Ì3ҀǨ© Ä ¤½Ò€Ç½Æ . Here is a sample output: ÅÓÉ1ʐÊÎÂ1̐ÏWÁPS Í 9PÕPT Õ !ÂIÊÎƽܬ÷ ÛÎҀÇ4Ü ØˆÀPÂ1ϨÆHÌ ØˆÀPÂ1ϨÆHÌ ¨©¨)¨©¨)¨©¨©¨)¨©¨)¨©¨©¨)¨©¨)¨©¨©¨)¨©¨)¨©¨©¨)¨©¨g¨©¨)¨©¨g¨©¨©¨)¨)¨)¨©¨g¨©¨)¨©¨g¨©¨©¨)¨)¨ Q" ñ €Ä¨ÁHĈÂPÀ½ú e¨Ô„ïèÔ # Ú ÷ Ÿ÷ dÎÖÖ eý ÖxþoïHe u€"" ܇ŐÉĨÁ£É¨ÄÎÜ øÕ þ B" ñ cÛÎÒIÇ@ܨú ÖqdŸïùø þnïùý €€"" It is easy to print out the headings for this table. ¨Ì3ÒIÇ© Ä ¤½Ò€ÇˆÆ The method will need the player label (A or B). we implement the method.~zrP rP1sˆuŒˆp{ x ˜ y腌‹Iç ´ ÜÓƨÀ1͟ï–Û3ҀÇ4Ü €ßÿÜÓƨÀ1͟ï–Û3ҀÇ4Ü €á»Ö ÒÓÍÐÂcߐßÐÕn÷ ÜÓƨÀHÍnïz܇ŐÉÄ3Ü Uß Ü£Æ¨À1͟ïôÜIŐɨÄÎÜ €á s s fi • w s u ³ 1…Œ{–y vu± ±˜ 6 ƒ•…± u†y 6 ‚HŠ ”IéH~ m Ö Å¨Ò‡Ê•Å£ÄˆÂ£ÄÎÜ We can complete the class by writing a method to print out the ¨Ì3ҀǨÄ) Æ ½Á1ÌÄ results. and shutout percentage for each player. and the total number of games (for calculation of percentages). This method will make heavy use of string formatting. èÆH£ Í Ì3ÒIÇg Ä  ˆÆ ˆÁHÌPĄñ‡ÜÓƨÀ1ÍÎú¬÷ ó€ØÌ3ÒIÇÄà ÇÎҐÑ1ƐÀ1ÏW͐ÁHÌÓÊ4Â1ÄPÄÆHÃUÌ" Æ ½Á1ÌÄ Çàß ÜÓƨÀ1͟ï–Û3ҀÇ4Ü Ú áÿÜÓƨÀ1͟ï–Û3ҀÇ4Ü Ì3ÒIÇA Ä uÅÓÉ1ʐÊ4£̐ÏÝÁH6 Í 3õîÇè õ ž!ÂIÊÎƈÜæq ÷  Ì3ÒIÇÄ Ì3ÒIÇA Ä  Û3ҀÇ4Ü ñ €ÄÁ1ĈÂPÀ½ú ÜIÅPÉĨÁ£ÉÄ3Ü ñ cÛÎҀÇ4ܨú  Ì3ÒIÇA Ä u¨©¨)¨©¨©¨)¨©¨)¨©¨©¨)¨©¨)¨©¨©¨)¨©¨)¨©¨©¨)¨©¨)¨©¨g¨©¨©¨)¨)¨)¨©¨g¨©¨)¨©¨g¨©¨©¨)¨)¨)¨©¨g¨©¨• ܣƨÀ1͟b ï Ì3ÒIÇ) Ä ¤3ҀLjÆæ" ñ  Ú 3õ¢Ü£ÆÀH͟ï|ÛÎÒIÇ@Ü Ú õÜÓƨÀHÍnïz܇ŐÉÄ3Ü Ú õ Ǔú ܣƨÀ1͟b ï Ì3ÒIÇ) Ä ¤3ҀLjÆæ" ñ  #3õ¢Ü£ÆÀH͟ï|ÛÎÒIÇ@Ü oõÜÓƨÀHÍnïz܇ŐÉÄ3Ü oõ Ǔú s Q" B" G s s Ì3ÒIÇÄ)¤3Ò€ÇˆÆ To finish out the class. èÆH£ Í Ì3ÒIÇ) Ä ¤3ҀLjÆæñvܣƨÀ1Íoõ ÀÂx˽ƐÀ‰õlÛÎÒIÇ@܆õ ÜIÅPÉÄÎ܆õîǓú­÷ ÄÆxc Ê 3ÀPÂ1ÄÆÈ& ß ŒØˆÀPÂ1ϨÆHÌ ½Üæ÷ ©dÃ c9oï†Ö€Í 4ÖPրà 3Üm Ò£ÍcÛÎÒIÇ@Ü ßPßÝÕn÷ ó Ú W¨ÁˆÒÓÀý Ò W3Ò¨ÜHÒ1ÁÓÇcËÏ ÆHÌÁ  " " " g"€"#" h " . Our method will generate a table that shows the wins. A good start is to define a template for the information that will appear in each line. number of wins and shutouts. but the formatting of the lines takes a little more care. and push off the details of formatting the line into another method.

we need to turn our attention ü   ÀPÀ ÂIÊÎÆ . The main template includes it ÒÓÍ as a string. but the score will just start out at 0. Let’s name that class ؈ÀPÂ1ÏÆ1Ì probability and current score. ÊmÇȑÇÈ‘É äU—æٌ͕iB—îi•wmtql™w%•@h –'—îi Ũ҇ʕţĈ£ÄÎÜ Now that we have wrapped up the class. A object will keep track of its behavior. the score for each player. and a method that reports the scores. We’ll flesh out ؈ÀPÂ1ÏÆ1Ì   ÀÀ ü ÂIÊÎÆ the design of class methods as we work on . we have to remember the probability for each player. while the server is a property of the game between the two players. you will see that probability and score are properties related to particular players. If you think about this carefully.   ˆÂPÀÀ ü €Ê3Æ We are now in a position to define the constructor for . Thinking about the objects. ÑHÀPˆÜPÜ  ÀÀ ü ÂIÊÎÆn÷ èÆHS Í Ì©ÌÒIÇ4Òx§ Ä Ì©Ì­ñ‡ÜÓƨÀḦ́õ ¨ÌÁÓË Ú õ ÌÁÓË Îú¬÷ ܣƨÀ1͟b ï 3ÀÂ£ÏÆ1Ì Ú ßÝØÀÂ£ÏÆH̉H ñ ¨ÌÁ£Ë Ú ú ܣƨÀ1͟b ï 3ÀÂ£ÏÆ1Ì UßÝØÀÂ£ÏÆH̉H ñ ¨ÌÁ£Ë 4ú ܣƨÀ1͟ïôÜ£ÆH) Ì WÆ1̀ßÿܣƐÀHÍnïp؈ÀPÂ1ϨÆHÌ Ú óWØÀÂ1ϨÆHÌ Ú ÂPÀ£ÛˆÂ1ÏÎÜcÜ£ÆH) Ì WƈÜYͽÒxÌÎÜxÄ % % % % % g  % . When a is first created the probability will be supplied as a parameter. and which player is serving. If the players are objects. then we will need another class to define their ØÀÂ1ϨÆHÌ ØˆÀPÂ1ÏÆ1Ì . and the statement takes care of formatting this piece to prevent division by zero.”Ié€r s@tŒuxw†y|{‡}†~†rH˜Ñ  Ê { ³ y•iUÑn} 6 {‡Š†y|{z‹ 4 é {zˆ 6 HŠ ܇ŐɨħÅ1ÄPÌWßAq¨)¨©¨)¨©¨B ƨÀˆÜÓÆn÷ ܇ŐɨħÅ1ÄPÌWßA )dŸï†Ö€Í 6 ñ–ÍÀHÁ¨Â1ĉñ‡Ü‡ÅÉÄ3ܨú"Ÿ£ÛÎÒIÇ@ÜgYˆÖxÕPÕ3ú Ì3ÒIÇĀĨÆxc Ê 3ÀÂ£ÄÆ ñzÀÂx˽ƨÀæõ Î Û ÒIÇ@܆õ¢ÍÀHÁ¨Â1ĉñèÛ3ҀÇ@ܐú ŸxǕYˆÖ€ÕÕ‰õ ÜIÅPÉÄÎ܆õ I Ü ÅPÉÄCÅ1ĐÌÎú žR"" g"€" ±" ² ü –•Ù‡Ù Notice how the shutout percentage is handled. this class needs a to ½ÀÂ£Ï constructor that accepts two probabilities as parameters. a method that !¨ÆHC Ä ÅÑ£ÁHÌÆˆÜ plays the game. What will a racquetball game need to know? To actually play the game. Summarizing what we have decided so far. The game will need instance variables for the two players and another variable to keep track of which player is serving. The players themselves can be objects that know their probability and   ÀÀ ü ÂIÊÎÆ class this way leads us to design some new score. That suggests that we might simply consider that a game needs to know who the players are and which is serving.

We can translate this loose algorithm almost directly into our object-based code. we need to have the serving player serve and. we need to figure out how to play it. Player RBallGame playerA: playerB: server: Player prob: score: 0.6 0 % % Figure …¤† . the decision of whether the game has ended or not can only be made by ” looking at the game object itself.~zrP rP1sˆuŒˆp{ x ˜ y腌‹Iç ´ fi • w u ³ 1…Œ{–y vu± ±˜ 6 ƒ•…± u†y 6 ‚HŠ ”I途 Sometimes it helps to draw a picture to see the relationships among the   ÀPÀ ü ÂIÊÎÆ objects that we are creating. we need an algorithm that continues to serve rallies and either award points or change the server as appropriate until the game is over. based on the result. Going back to the discussion of racquetball from Chapter 9. IÑ i‡ OK. Suppose we create an instance of like this: ÄHÅˆÆ ü €ÊÎÆUE ß   ˆÂPÀÀ ü €Ê3Ææñˆïðø„õ¨ï¡9ˆú P  Figure . The beginning of our method can make use of this ” (yet-to-be-written) method. we need a loop that continues as long as the game is not over.5 0 prob: score: 0. decide what to do. This suggests that objects should have a ëéӀâ3ØÔ3Ù . shows an abstract picture of the objects created by this statement and their inter-relationships. now that we can create an ÏÐ . éâgÓ€Ó %â §Ô àÓuÕ§ò ÷%ÔuÕ á€Ü§€Ó â3uÚ Ø} R ê ! å g Ô Ó€ÔÅì Ö å)Ô%Ó3ՏæQÚgå3õ ÔuÙfêíò  — ’ Ӏâ3Ø Ú%å!õ Ô3Ù  — Inside of the loop. Let’s just assume that an appropriate Q’ method can be written. Obviously. First. … : Abstract view of ÏÐ éâgÓ€Ó %â §Ô IÑ i‡ object.

on the other hand. ÒÓÍÿܣƐÀH͟ïôÜ£Æ1© Ì WÆ1̙ï|ÛÎҀÇ4ÜÅHÆHÌ©W¨Ææñ‡ú¬÷ Based on this result. namely increment the score. here is our method: èÆH£ Í 3ÀÂ£Ï„ñvܣƨÀ1ÍÎú­÷ ÛPÅ4Ò1ÀPÆ ÇˆÁHÄ ÜÓƨÀHÍnïôÒÜ Ä W¨ÆH̉ñIú¬÷ ÒÓÍÿܣƐÀH͟ïôÜ£Æ1© Ì WÆ1̙ï|ÛÎҀÇ4 Ü ÅHÆH© Ì W¨Ææñ‡ú¬÷ ÜÓƨÀHÍnïzÜÓÆH© Ì W¨ÆH̟ïôҀÇÎg Ñ Å¨Ñ1ÁH̨Ææñ‡ú ƐÀˆÜÓÆn÷ ÜÓƨÀHÍnïôÑIÅ3ÂÓC Ç !¨© Æ ÅPÆH) Ì WÆ1̄ñIú % ÜÓƨÀHÍ   ÀÀ ü ÂIÊÎÆ As long as you remember that is an . these methods are straightforward. While the game is not over. namely . Of course. Ü£Æ1© Ì W¨ÆHÌ is done at the game level. we run into the same problem again. èÆH¥ Í !¨ÆHC Ä ÅÑ£ÁHÌƈܓñvܣƨÀ1ÍÎú­÷ ÌÆHÄ1ÉÌ1Ç Ü£ÆÀH͟b ï 3ÀPÂ1ÏÆ1Ì Ú f ï !¨Æ1§ Ä Å¨Ñ1ÁH̨Ææñ‡ú†õlÜÓƨÀHÍnU ï ½ÀÂ1ϨÆHÌ ™f ï !ÆHC Ä ÅÑ1Á1ÌƬñIú % % % € ؈ÀPÂ1ϨÆHÌ This adds one more method to be implemented in the class. since this information is kept in the instance   ÀPÀ ü ÂIÊÎÆ variable of . if the server wins a serve. Make sure you put that on our list to complete later. we either award a point or change the server.   ÀPÀ ü ÂIÊÎÆ Ò¨Ü Ä WÆ1Ì ÑIÅ3ÂÓÇC!¨Æ©ÅPÆHÌ)WÆ1Ì To finish out the class. Changing servers. the price we pay for this simple algorithm is that we now have ÒÜ Ä W¨ÆHÌ Ñ€Å½ÂÓ§ Ç !c Æ ÅHÆH© Ì W¨ÆHÌ and ) that need to be implemented in two new methods ( ü   ÀÀ ÂIÊÎÆ ÛÎÒIÇ@Ü ÅPÆH) Ì WÆ ÒIÇ4g Ñ Å¨Ñ1Á1ÌÆ ØÀÂ£ÏÆHÌ the class and two more ( and ) for the class. Of course. Given what we have developed already and our previous version of this program. After all. This one just returns the scores of the two players. I’ll leave those as an exercise % . This again requires the player to do something. It is the player objects that actually know the scores. otherwise change the server. we need to write the and methods. We’ll just ask the server if the serve is won or lost. award a point to the server. whether the serve is won or not depends on the probability that is stored inside of each player object. Before attacking these new methods. we need to change a player’s score.”Ié ¯ s@tŒuxw†y|{‡}†~†rH˜Ñ  Ê { ³ y•iUÑn} 6 {‡Š†y|{z‹ 4 é {zˆ 6 HŠ method that performs a serve. this code should be clear. let’s go back and finish up the other   ˆÂPÀÀ ü €Ê3Æ !¨ÆHC Ä ÅÑ£ÁHÌÆˆÜ top-level method of the class. To award a point. so we will need a method that asks a player to return its score. ½ÀÂ£Ï Putting it all together.

g %¤ èÆHÍSÌ©ÌÒIÇ4Òxħ̩̭ñ‡ÜÓƨÀḦ́õ ¨ÌÁÓ˓ú¬÷ óÝ×HÌƐÂ1ĨÆW`  3ÀÂ£ÏÆ1ÌcÛÎÒxÄHÅÐÄHÅÎÒ¨Ü$¨ÌÁÓË3ÂÓËÎÒHÀ¨ÒÓÄÏ Ü£Æ¨À1͟b ï ÌÁÓËÝE ß ̨Á£Ë ܣƨÀ1͟ïôÜPÑ1Á1ÌÆÈßÝÕ ØÀÂ£ÏÆHÌ The other methods for our class are even simpler. !¨ÆHC Ä ÅÑ£ÁHÌÆ and . that gives us confidence that we must have gotten it right.or two-line methods. we simply add one to the score. To see if a player wins a serve. you should have no trouble coming up with a constructor. and the score starts at 0. èÆH͡ҀÇ4ÑÅÑ£ÁHÌƬñ‡ÜÓƨÀHÍ3ú¬÷ ܣƨÀ1͟ïôÜPÑ1Á1ÌÆÈßÿܣƨÀ1͟ïôÜPÑ1Á1ÌÆÈá Ö The final method just returns the value of the score. èÆHÍ¥!¨ÆHÄCÅÑ£ÁHÌƬñ‡ÜÓƨÀHÍ3ú¬÷ ÌÆHÄ1ÉÌ1Ç Ü£ÆÀH͟ïôÜPÑ£ÁHÌÆ Initially. The player’s probability will be passed as a parameter. èÆHÍcÛÎҀÇ4ÜÅHÆHÌ©W¨ÆæñvܣƨÀ1ÍÎú­÷ ÌÆHÄ1ÉÌ1ÇÝ̈ÂxLjèÁ€Ê™ñ‡ú ß F ÜÓƨÀHÍnïU¨ÌÁ£Ë To give a player a point. If you are getting the hang of this object-oriented approach. ÊmÇȑÇÈ ™ äU—æٌ͕iB—îi•wmtql™w%•@’ ٌ– gi•“   ˆÂÀPÀ ü €ÊÎÆ ØÀÂ£ÏÆHÌ In developing the class.~zrP rP1sˆuŒˆp{ x ˜ y腌‹Iç ´ fi • w u ³ 1…Œ{–y vu± ±˜ 6 ƒ•…± u†y 6 ‚HŠ ”I逴 for you at the moment. The ؈ÀPÂ1ϨÆHÌ ÛÎÒIÇ@ÜÅHÆHÌ)WÆ Ò€ÇÎÑgÅÑ£ÁHÌ¨Æ class needs a suitable constructor and methods for . We just need to initialize the instance variables. If those pieces are so simple that their implementations are obvious. it’s quite common for a well-modularized. you may think that it’s silly to create a class with a bunch of one. we discovered the need for a class that encapsulates the service probability and current score for a player. skip to the complete code at the end of this section. we compare the probability to a random number between 0 and 1. If you’re looking for my solutions. . objectedoriented program to have lots of trivial methods. . The point of design is to break a problem down into simpler pieces. Actually.

”I逹 ÊmÇȑÇÈ‘× ÿ   ¤ª %i s@tŒuxw†y|{‡}†~†rH˜Ñ  Ê { ³ y•iUÑn} 6 {‡Š†y|{z‹ 4 é {zˆ 6 HŠ vx—æٌ͕iCtuiE’”“fv••“H–B— That pretty much wraps up our object-oriented version of the racquetball simulation. go back to the discussion above to figure it out. óÝÁ£Ë ó ï Ì1Ë3ÀPÀoïbÏ ¨)¨¥ÅÒvÊÉ3ÀPÂ1ĽÒ1Á£ÇÝÁPÍàÂUÌˆÂ¨Ñ í£É½ÆHÄT!€Ê3Ænï ¢£ÀÀxÉ@ÜxÄP̈£ÄÆ½Ü Ã¨ÆˆÜPÒ !£ÇWÛÎÒxÄHÅ¡ÁÓË ÆÑÓÄ3Üæï ï ÍP̨ÁxÊ¡ÌÂÓLjÐÁxÊ»ÒvÊCˆÁH̐Äc̈ÂÓÇèÁ€Ê ÑHÀPˆÜPÜ ˆ Ø ÀPÂ1ÏÆ1̙÷ ó Ú ØˆÀÂ£ÏÆ1ÌEΈÆPÆ @  Ü ÄÌˆÂ¨ÑÎàÁHÍÿÜ£ÆHÌ)W3ÒPÑ1ÆV¨ÌÁ£Ë½ÂÓËÎÒHÀÒxĐπÂÓÇÃÿÜPÑ1Á1ÌÆ Ã¨ÆHÍSÌ©ÌÒIÇ4Òxħ̩̭ñ‡ÜÓƨÀḦ́õ ¨ÌÁÓ˓ú¬÷ óÝ×HÌƐÂ1ĨÆW`  3ÀÂ£ÏÆ1ÌcÛÎÒxÄHÅÐÄHÅÎÒ¨Ü$¨ÌÁÓË3ÂÓËÎÒHÀ¨ÒÓÄÏ Ü£Æ¨À1͟b ï ÌÁÓËÝE ß ̨Á£Ë ܣƨÀ1͟ïôÜPÑ1Á1ÌÆÈßÝÕ Ã¨ÆHÍcÛÎҀÇ4ÜÅHÆHÌ©W¨ÆæñvܣƨÀ1ÍÎú­÷ ó  ˆÆHÄ1ÉÌ1Ç@ÜÈ ÁPÁ¨ÀHƨÂÓǀÄHŽÂ1ÄÿÒ¨ÜYÄPÌHɈÆUÛÎÒÓÄ1ÅT̨Á£Ë½ÂÓË4Ò1ÀÒxĐϡÜÓƨÀ1͟ïU¨ÌÁÓË E ÌÆHÄ1ÉÌ1ÇÝ̈ÂxLjèÁ€Ê™ñ‡ú ß ÜÓƨÀHÍnU ï ¨ÌÁ£Ë F ž èÆH͡ҀÇ4ÑÅÑ£ÁHÌƬñ‡ÜÓƨÀHÍ3ú¬÷ ó Ú ÃÃÐ`  ˆÁˆÒ€Ç¨Ä€ÄÁcÄ1Å4ҐÜ3ÀÂ£ÏÆ1Ì ŒÜUÜPÑ£ÁHÌÆ Ü£Æ¨À1͟ïôÜPÑ1Á1ÌÆÈßÿܣƨÀ1͟ïôÜPÑ1Á1ÌÆÈá Ö Ã¨ÆHÍ¥!¨ÆHÄCÅÑ£ÁHÌƬñ‡ÜÓƨÀHÍ3ú¬÷ ó  ˆÆHÄ1ÉÌ1Ç@Ü Ä1Å4Ò¨ E Ü ½ÀÂ£ÏÆHÌ ŒÜÈрÉÌPÌÆÓÇÄÿÜHÑ1ÁHÌ¨Æ ÌÆHÄ1ÉÌ1Ç Ü£ÆÀH͟ïôÜPÑ£ÁHÌÆ ÑHÀPˆÜPÜ  ÀÀ ü ÂIÊÎÆn÷ ó Ú   ˆÂPÀÀ ü €Ê3ÆÈÌ¨Æ ̨ƽÜÓÆ£ÇÄ3Ü ÂT!ÂIÊÎÆÐÒIÇ¥̨Á)!P̨ƽÜPÜæï Ú !¨Â€ÊÎÆÈŽˆÜYÄHۈÁ`3ÀPÂ1ϨÆHÌÎÜ óÐÂÓÇÃEΈƐÆ"@ÜYÄP̈ÂÑÎÐÁPÍcÛHÅ4ÒPрšÁ£ÇˆÆÐÒ¨ÜWÑIĘ́̐ƣǨĈÀ1ÏàÜ£Æ1Ì©W3ÒIǧ!nï èÆHÍSÌ©ÌÒIÇ4Òxħ̩̭ñ‡ÜÓƨÀḦ́õ ¨ÌÁÓË Ú õ ÌÁÓË Îú¬÷ óÝ×HÌƐÂ1ĨÆWÂÈǽÆ1ÛS!¨Â€Ê3Æ Å3 W3ҀÇC!`3ÀPÂ1ϨÆHÌÎܪÛÎÒÓÄ1ÅÐÄHňÆT!½Ò"W¨Æ£ÇT¨ÌÁÓË@Üæï ܣƨÀ1͟b ï 3ÀÂ£ÏÆ1Ì Ú ßÝØÀÂ£ÏÆH̉ñH¨ÌÁ£Ë Ú ú  … % %  . The complete program follows. You should read through it and make sure you understand exactly what each class does and how it does it. If you have questions about any parts.

~zrP rP1sˆuŒˆp{ x ˜ y腌‹Iç ´ ܣƨÀ1͟ïb3ÀÂ£ÏÆ1Ì UßÝØÀÂ£ÏÆH̉ñH¨ÌÁ£Ë 4ú ܣƨÀ1͟ïôÜ£ÆH) Ì WÆ1̀ßÿܣƐÀHÍnïU3ÀPÂ1ϨÆHÌ Ú ó ØÀÂ1ϨÆHÌ W Ú Ã¨ÆHÍ£3ÀÂ£Ï„ñvܣƨÀ1ÍÎú­÷ ó€ØˆÀÂ£ÏWÄHňÆT!€Ê3ÆUÄÁ¡Ñ£ÁxÊC½ÀPÆ1Ä3Ò1ÁÓÇ ÛPÅ4Ò1ÀPÆ ÇˆÁHÄ ÜÓƨÀHÍnïôÒÜ Ä W¨ÆH̉ñIú¬÷ ÒÓÍÿܣƐÀH͟ïôÜ£Æ1© Ì WÆ1̙ï|ÛÎҀÇ4 Ü ÅHÆH© Ì W¨Ææñ‡ú¬÷ ÜÓƨÀHÍnïzÜÓÆH© Ì W¨ÆH̟ïôҀÇÎg Ñ Å¨Ñ1ÁH̨Ææñ‡ú ƐÀˆÜÓÆn÷ ÜÓƨÀHÍnïôÑIÅ3ÂÓC Ç !¨© Æ ÅPÆH) Ì WÆ1̄ñIú g fi • w % u ³ 1…Œ{–y vu± ±˜ 6 ƒ•…± u†y 6 ‚HŠ ”I逿 ÂPÀ£ÛˆÂ1ÏÎÜcÜ£ÆHÌ)WƈÜYͽÒxÌÎÜxÄ Ã¨ÆHÍ¡Ò¨Ü Ä WÆ1̄ñ‡ÜÓƨÀ1ÍÎú¬÷ óE ˆÆHÄ1ÉÌ1Ç@Üè!¨Â€ÊÎÆàÒÜ Í½ÒIÇ4Ҩ܇ŽÆHà ñvÒæïðÆoï¢Á£Ç½ÆWÁH̀ÄHňÆ`3ÀÂ£ÏÆ1ÌÎÜªÅ½ÂˆÜ ÛˆÁÓǓú­ï ‰õpËàßÿÜÓƨÀ1͟f ï !ÆHC Ä ÅÑ1Á1ÌƈܓñIú ÌÆHÄ1ÉÌ1Ç¡Âcߐ߻" Ö 9€Á1ÌcËàߐ߻Ö"9€Á1Ì ñ†ÂcßPßÝþàÂxLjÃUËàßPßÝÕ3ú ÁHÌ ñùˈߐߐþWÂÓÇÃÐÂcߐßÐÕ3ú ä´ Ã¨ÆH͡рÅ3Âxǧ!ÆcÅPÆ1Ì©W¨ÆH̄ñvܣƐÀHÍÎú­÷ ó Å£ÛÎÒxÄ3ÑIÅWÛPÅÎҐр¥ S Å ½ÀÂ£ÏÆHÌàÒ¨ÜWÜ£Æ1Ì©W½Ò€Ç§! Ò£ÍÿܣƐÀHÍnïzÜ£Æ1© Ì W¨ÆH̀ßPßÿܣƐÀH͟b ï 3ÀPÂ1ÏÆ1Ì Ú ÷ ÜÓƨÀ1͟ïzÜÓÆH) Ì WÆHÌUß Ü£ÆÀH͟b ï 3ÀPÂ1ÏÆ1Ì Æ¨ÀˆÜÓÆn÷ ÜÓƨÀ1͟ïzÜÓÆH) Ì WÆHÌUß Ü£ÆÀH͟b ï 3ÀPÂ1ÏÆ1Ì Ú g èÆHÍ¥!¨ÆHÄCÅÑ£ÁHÌƈܓñvܣƨÀ1ÍÎú­÷ ó  ˆÆHÄ1ÉÌ1Ç@Ü Ä1ŽÆàрɨ̨̐ƣÇÄ¡ÜPÑ1Á1ÌÆˆÜ ÁPÍ£½ÀÂ1ϨÆHÌ Ú ÂxLjã3ÀPÂ1ϨÆHÌ E ÌÆHÄ1ÉÌ1Ç Ü£ÆÀH͟b ï 3ÀPÂ1ÏÆ1Ì Ú f ï !¨Æ1§ Ä Å¨Ñ1ÁH̨Ææñ‡ú†õlÜÓƨÀHÍnïU½ÀÂ1ϨÆHÌ ™ïf!ÆHÄCÅÑ1Á1ÌƬñIú € # ÑHÀPˆÜPÜ`ÅÒvʕÅ1ÄÂ1Ä3Üæ÷ ó ÅÒv• S Ê Å1ÄÂ1Ä3ܪÅ3ÂxLjÃÀHƽÜȨѐÑIÉHÊɽÀÂ£Ä3Ò1ÁÓÇÝÁHÍÿÜxÄÂ1Ä3ҐÜxĽҐѨÜYÂÑxÌÁ½ÜPÜÊɽÀ1ĽÒ3ÀHÆ ó ñvÑ1Á€C Ê ½ÀPÆHĨÆPÃ3 ú !ÂIÊÎƈÜæI ï 1Å4Ò¨ Ü WÆHÌ3ÜPÒ£Á£ÇÝÄP̈Â Ñ Î4Ü Ä1ŽÆUÛ3ҀÇ@ÜUÂxLjÃÿ܇ŐÉĨÁ£É¨ÄÎÜ ÍÁHÌ ó ƨÂÑIT Å 3ÀPÂ1ϨÆH̙ï èÆHÍSÌ©ÌÒIÇ4Òxħ̩̭ñ‡ÜÓƨÀHÍ3ú¬÷ óÝ×HÌƐÂ1ĨÆWÂÈǽÆ1ۡ¨ѐÑIÉHÊɽÀÂ£ÄÁHÌUͨÁ1Ìà¡ܣÆH̽Ò1ÆˆÜ Ü£Æ¨À1͟ï|ÛÎҀÇ4Ü Ú ßÝÕ Ü£Æ¨À1͟ï|ÛÎҀÇ4Ü cßÝÕ Ü£Æ¨À1͟ïôÜIŐɨÄÎÜ Ú ßÝÕ ÁPÍ¥!¨Â€ÊÎÆˆÜ s .

”Ié€â s@tŒuxw†y|{‡}†~†rH˜Ñ ܣƨÀ1͟ïôÜIŐɨÄÎÜ €ßÝÕ m  Ê { ³ y•iUÑn} 6 {‡Š†y|{z‹ 4 é {zˆ 6 HŠ èÆHÍUÉ©ˆÃ¨Â1ĨÆæñ‡ÜÓƨÀ1Íoõl ü ÂIÊÎƽú¬÷ ó ˆÆHĨÆHÌÓʓҀLjÆUÄHňƀÁ£É¨Ä3Ñ£ÁxÊÎÆcÁPÍРü €Ê3ÆÝÂÓLjÃUÉ)ˆÃ¨Â1ÄÆÐÜxĈ£Ä3ҐÜxÄ3ÒPÑ¨Ü Â‰õ Ëàßà ü €ÊÎÆof ï !ÆH§ Ä Å¨Ñ1Á1ÌƽÜ@ñIú Ò£ÍР( ˄÷ ó Ú ÛˆÁÓÇÐÄHŽÆT!¨Â€Ê3Æ ÜÓƨÀ1͟ï–Û3ҀÇ4Ü Ú ßÿÜÓƨÀ1͟ï–Û3ҀÇ4Ü Ú á»Ö ÒÓÍUËàߐßÐÕn÷ ÜÓƨÀHÍnïz܇ŐÉÄ3Ü Ú ß Ü£Æ¨À1͟ïôÜIŐɨÄÎÜ Ú á Ö Æ¨ÀˆÜÓÆn÷ ó €ÛˆÁÓÇÐÄHŽÆT!¨Â€Ê3Æ ÜÓƨÀ1͟ï–Û3ҀÇ4Ü €ßÿÜÓƨÀ1͟ï–Û3ҀÇ4Ü €á»Ö ÒÓÍÐÂcߐßÐÕn÷ ÜÓƨÀHÍnïz܇ŐÉÄ3Ü Uß Ü£Æ¨À1͟ïôÜIŐɨÄÎÜ €á Ö ž s s s s  m èÆHÍ£Ì3ÒIÇÄg ˆÆ ˆÁHÌPĄñ‡ÜÓƨÀ1ÍÎú¬÷ ó€ØÌ3ÒIÇÄà ÇÎҐÑ1ƐÀ1ÏW͐ÁHÌÓÊ4Â1ÄPÄÆHÃUÌÆ"½Á1ÌÄ Çàß ÜÓƨÀ1͟ï–Û3ҀÇ4Ü Ú áÿÜÓƨÀ1͟ï–Û3ҀÇ4Ü Ì3ÒIÇA Ä uÅÓÉ1ʐÊ4£̐ÏÝÁH6 Í 3õîÇè õ ž!ÂIÊÎƈÜæq ÷  Ì3ÒIÇÄ Ì3ÒIÇA Ä  Û3ҀÇ4Ü ñ €ÄÁ1ĈÂPÀ½ú ÜIÅPÉĨÁ£ÉÄ3Ü ñ cÛÎҀÇ4ܨú Ì3ÒIÇA Ä u¨©¨)¨©¨©¨)¨©¨)¨©¨©¨)¨©¨)¨©¨©¨)¨©¨)¨©¨©¨)¨©¨)¨©¨g¨©¨©¨)¨)¨)¨©¨g¨©¨)¨©¨g¨©¨©¨)¨)¨)¨©¨g¨©¨• ܣƨÀ1͟b ï Ì3ÒIÇ) Ä ¤3ҀLjÆæ" ñ  Ú 3õ¢Ü£ÆÀH͟ï|ÛÎÒIÇ@Ü Ú õÜÓƨÀHÍnïz܇ŐÉÄ3Ü Ú õ Ǔú ܣƨÀ1͟b ï Ì3ÒIÇ) Ä ¤3ҀLjÆæ" ñ  #3õ¢Ü£ÆÀH͟ï|ÛÎÒIÇ@Ü oõÜÓƨÀHÍnïz܇ŐÉÄ3Ü oõ Ǔú Q" B"  G èÆHÍ£Ì3ÒIÇÄ)¤3ҀLjÆæñvܣƨÀ1Íoõ ÀÂx˽ƐÀ‰õlÛÎÒIÇ@܆õ ÜIÅPÉÄÎ܆õîǓú­÷ ÄÆxc Ê 3ÀPÂ1ÄÆÈ& ß ŒØˆÀPÂ1ϨÆHÌ ½Üæ÷ ©dÃ c9oï†Ö€Í 4ÖPրà 3Üm Ò£ÍcÛÎÒIÇ@Ü ßPßÝÕn÷ ó Ú W¨ÁˆÒÓÀýÒW3Ò¨ÜHÒ1ÁÓÇcËÏ ÆHÌÁ  ܇Őɨ§ Ä Å1ÄPÌWA ß q¨)¨©¨)¨©¨B ƨÀˆÜÓÆn÷ ܇Őɨ§ Ä Å1ÄPÌWA ß  )dŸï†Ö€Í 6 ñ–ÍÀHÁ¨Â1ĉñ‡Ü‡ÅÉÄ3ܨ" ú Ÿ£ÛÎÒIÇ@ÜgYˆÖxÕPÕ3ú Ì3ÒIÇĀĨÆxc Ê 3ÀÂ£ÄÆ ñzÀÂx˽ƨÀæõ ÛÎÒIÇ@܆õ¢ÍÀHÁ¨Â1ĉñèÛ3ҀÇ@ܐú Ÿx• Ç YˆÖ€ÕÕ‰õ ÜIÅPÉÄÎ܆õ ÜIÅPÉC Ä Å1ĐÌÎú s " " " g"€"#" h " s R " g € " " ± " ž" èÆHÍ£̽ҀÇÄ%¢IǨĐÌÁ¬ñIú­÷ ̽ҀÇ Ä XHÅÎÒ¨ Ü ¨ÌÁ)!ḦÂIÊ»ÜPÒvÊɽÀÂ1ĨƽÜè!¨Â€Ê3Æ½Ü ÁH̀̈ÂÑ"í1ɈÆHÄH˽ÀPÀ ˽Æ1ÄPÛƐƣÇWÄPۈÁB ̽ҀÇÄ p3ÀPÂ1ϨÆHÌÎÜUÑHÀPÀPÆH à  Ú  ÂÓLjA à  #4ï 1ŽÆÝÂÓËÎÒHÀ¨ÒÓĐÏWÁPÍÝƨ¨рť½ÀÂ1ϨÆHÌ¡ÒÜ ̽ҀÇ Ä xҀÇýÒPÑHÂ1ĨÆPÃYËÏà`  ̨Á£Ë3ÂxË4Ò1ÀÒÓÄPÏòñz ǐÉHʨ˽Æ1ÌU˽Æ1ÄPۈÆPÆ£ÇàÕÝÂxLjà ÖHú ÄHÅ3£Ä# ̽ҀÇ Ä ŒÄHň` Æ 3ÀPÂ1ÏÆ1ÌcÛÎÒIÇ@ÜYÄ1Ž` Æ ½ÁҀǨÄcÛPňƣǻܣÆ1Ì©W½Ò€Ç§!nï ØÀÂ1ϨÆHÌ Ú ÂPÀ£Û½Â£ÏÎÜm —  © .

I suggested that objects are particularly useful for the design of graphical user interfaces. I want to finish up this chapter by looking at a graphical application using some of the widgets that we developed in previous chapters. ÊmÇȑÉÈƒÊ ’”“Hv••“f–B— Ø Í'imœcl@u{œ)–mtqlnvxw Our goal is to write a game program that allows a user to play video poker using dice.~zrH ”H1s½uŒˆ–{ x ˜ yè…v‹‡ç ̽ҀÇÄzÅ3ÂÜYÄHňƀͽÒÓÌ3ÜxÄÿÜÓÆHÌ)WÆnï ´{é 6 ³ {qH‚QÒè{‡} ”Ié€é l´ ÓÇx èÆHÍ¥!¨Æ1ÄQ¢IÇ)É¨ÄÎܓñ‡ú¬÷ ó  ˆÆ1ÄHÉÌ1Ç@Ü Ä1ŽÆcÄ1ÅÌÆPÆàÜPÒvÊɽÀÂ1ĽÒ1ÁÓÇE3£̈ÂIÊÎÆHĨÆHÌ3Ü E ÂcßÿҀ© Ç PÉĉñ 34HÅ3£ÄàÒ¨ÜYÄ1Ž` Æ ¨ÌÁ£Ëhï 3ÀPÂ1ϨÆHÌ Ú ÛÎÒIÇ@ÜÈ¡ÜÓÆHÌ©W¨Æ§PaÓú ËàßÿҀ© Ç PÉĉñ 34HÅ3£ÄàÒ¨ÜYÄ1Ž` Æ ¨ÌÁ£Ëhï 3ÀPÂ1ϨÆHÌ WÛÎÒIÇ@ÜÈ¡ÜÓÆH© Ì W¨§ Æ PaÓú ÇàßÿҀ© Ç PÉĉñ 3¢Á1ÛYÊ4ÂÓǨ¥ Ï !ÂIÊÎƈÜYÄÁ¡ÜPÒvÊɽÀÂ1Ĩ§ Æ P@£ú ÌÆ1ÄHÉÌ1ǡ‰õ ˟õ Ç # èÆHÍ Ê4¨ҀÇnñ‡ú¬÷ ̽ҀÇ% Ä ¢IǨĐÌÁ¬ñIú ̨Á£Ë Ú õĮÁ£Ë nõîǡߥ!¨Æ1ÄQ¢‡Ç©É¨ÄÎÜ@ñIú % ó€ØˆÀPÂ1ÏWÄHňÆT!ÂIÊÎÆ½Ü ÜxÄÂ1ÄÎÜ ¡ ß Å¨Ò‡Q Ê Å1Ĉ£ÄÎÜ@ñIú ͨÁ1ÌÿÒWҀÇÐ̈Âx§ Ç !ÆæñðÇ@ú¬÷ ü ÄHÅ½Æ ÂIÊÎÆcE ß   ˆÂÀPÀ ü €  ÊÎƬñH¨ÌÁ£Ë Ú õ   ̨Á£Ë 4úYó¡ÑǪ́ƨ£ÄÆWÂÈǽƣ۠!ÂIÊÎÆ ÄHÅ½Æ ü ÂIÊÎÆnb ï 3ÀPÂ1τñ‡ú ó£3ÀPÂ1ÏÿÒxÄ ÜxĈ£ÄÎܬï|© É Ã£ÄÆæñèÄHÅˆÆ ü ÂIÊÎƽú óÝÆ)¦HĐÌÂÑÓÄàҀLj͐Á g % ó€ØÌ½Ò€ÇÄWÄ1ŽÆc̨ƽÜIɽÀ1Ä3Ü ÜxÄÂ1ÄÎܬU ï ¨Ì3ҀǨ) Ä  Æ ½Á1̐ĉñIú Ê4¨ҀÇoñIú ̈ÂÓm Û Ì¨Ò€© Ç PÉĉñ  xÇØPÌƽÜPÜ “o•«”– í´ FG ǨÄÆ1Ì ( ²S« ĨÁTí1É4ÒxÄ#Óú ‡ƒ¬‚—Ž™“‚™g  ¢in‘‚©©£…ΦŸ·•í Back in Chapter 10. The program will display a hand consisting of five dice. The basic set of .

’ The player initially rolls a completely random hand (i.. By themselves. The interface should have the following characteristics: ’ The current score (amount of money) is constantly displayed. they do . Our interaction will be through mouse clicks. ÊmÇȑÉÈ‘Ç ä Bi•wmtql@9 §l™wm• › l¤ äª §› U› ¤Ÿƒ¾s¿ –Bw 6l B–§tui 3imœ)tus Our first step is to analyze the program description and identify some objects that will be useful in attacking this problem. ’ The player gets two chances to enhance the hand by rerolling some or all of the dice. ’ The interface will present visual cues to indicate what is going on at any given moment and what the valid user responses are. ’ The player may choose to quit at appropriate points during play. the player’s money is updated according to the following payout schedule: Hand Two Pairs Three of a Kind Full House (A Pair and a Three of a Kind) Four of a Kind Straight (1–5 or 2–6) Five of a Kind Pay 5 8 12 15 20 30 Ultimately. Are either of these good candidates for objects? Both the money and an individual die can be simply represented as numbers. ’ The program automatically terminates if the player goes broke. ’ Each round costs $10 to play. all five dice are rolled). This is a game involving dice and money. This amount is subtracted from the user’s money at the start of the round. we want this program to present a nice graphical interface. ’ At the end of the hand.¯ 77 s@tŒuxw†y|{‡}†~†rH˜Ñ  Ê { ³ y•iUÑn} 6 {‡Š†y|{z‹ 4 é {zˆ 6 HŠ rules is as follows: ’ The player starts with $100.e.

roll Assign a random value to some subset of the dice. score Return the score for the dice. However. It’s not clear yet exactly what behaviors we will need from this Ø Á ÎÆHÌ Ú © class. It will implement a method that we use to get things started and also some helper methods that are used to implement ÌHÉPÇ . and the interface is a view of the current state of the model. Another component to this program will be the user interface. We can also think of the entire program as an object. it models a poker game). Here are a few obvious operations that this class will have to implement:  constructor Create the initial collection. Let’s assume that our program will make use of an interface object. We won’t know exactly what methods are needed until we design the main algorithm. These will correspond to ØÁ ΈÆ1Q Ì ¢IǨÄÆ1̨ͨÑ1Æ methods implemented by the class. we might have a text-based version of a progam and a graphical version. values Return the current values of the five dice. A object will keep track of the current amount of money. Our program implements some model (in this case. we will need to get information from the user and also display information about the game. and this sounds like a collection. For example. rollAll Assign random values to each of the five dice. We will need to be able to roll all the dice or a selection of dice as well as analyze the collection to see what it scores. I have concentrated on the actual game that we are implementing. One way of separating out the interface is to encapsulate the decisions about the interface in a separate interface object. .~zrH ”H1s½uŒˆ–{ x ˜ yè…v‹‡ç ´{é 6 ³ {qH‚QÒè{‡} 7 ~ ¯ H not seem to be good object candidates. call it a ØÁ ΈÆ1Q Ì ¢IǨÄÆ1̨ͨÑ1Æ . ÌHÉPÇ the dice. the number of rolls. Up to this point. Let’s call the class ØÁ ΈÆ1Ì Ú ) ØÁ ΈÆ1Ì Ú ) . while maintaining the current value of others. An advantage of this approach is that we can change the look and feel of the program simply by substituting a different interface object. but as we refine the class. the game uses five dice. One good way to break down the complexity of a more sophisticated program is to separate the user interface from the main guts of the program. etc. ÎÒPÑ1Æ We can encapsulate the information about the dice in a class. This is often called the model-view approach.

We can specify which dice to roll by passing a list ̨Á¨ÀÀ­ñ û Մõ–Þ‰¡ õ d)Îú of indexes. WÀÓÉˆÆ½Ü The function is used to return the values of the dice so that they can be displayed. calling it here saves duplicating that code. let’s turn our attention to the function. We need methods to roll selected dice and also to roll all of the dice. . we have a pretty good picture of what the class will do and a starting ØÁ ΈÆHÌ Ú ) point for implementing the class.   ÓpÔ †§ˆ} ÎÒPÑ1Æ The class implements a collection of dice. Since we are going to implement a function anyway. we can use ÌÁ¨ÀPÀ to implement ̨Á¨ÀPÀ Ú ÀPÀ as follows: èÆH̀ÌÁ¨ÀPÀ Ú ÀÀ¬ñvܣƐÀHÍÎú­÷ ܣƨÀ1͟ï–ÌÁ¨ÀPÀ¬ñè̈ÂÓÇC!¨Æ¬ñ39½úPú ̈Âx§ Ç !¨Æ¬3 ñ 9ˆú I used to generate a list of all the indexes. so let’s start with the lower-level class. which rolls a subset.7 r ¯ € ÊmÇȑÉÈ‘É s@tŒuxw†y|{‡}†~†rH˜Ñ äU—æٌ͕iB—îi•wmtql™w%•Vt %i  Ê )  ¶ £› { ³ y•iUÑn} 6 {‡Š†y|{z‹ 4 é {zˆ 6 HŠ v 'i%Ù ÎÒÑ£Æ So far. We just need a loop that goes through the parameter and generates a new random value for each listed position. We could proceed by working on ØÁ ΈÆHÌ Ú ) either of these classes. We won’t really be able to try out the class ÎÒÑ£Æ until we have dice. For example. ÑHÀPˆÜPÜ ÎÒPÑ1Æn÷ èÆHÍSÌ©ÌÒIÇ4Òxħ̩̭ñ‡ÜÓƨÀHÍ3ú¬÷ ܣƨÀ1͟ïpýҐѣÆUß û g Õ mY9 ܣƨÀ1͟ï–ÌÁ¨ÀPÀ Ú ÀÀ¬ñ‡ú  Ô })c„3…‡  …Œ‹"} » This code first creates a list of five zeroes. èÆH̀ÌÁ¨ÀPÀ¬ñvܣƨÀ1Íoõ ÛPÅ4ÒPрÅ@ú¬÷ ͨÁHE Ì ˆÁ½Ü€ÒIÇÝÛPÅ4ÒPрÅh÷ ÜÓƨÀ1͟ïùÃˆÒÑ£Æ û ˆÁ½ Ü U߀ÌÂÓLjÃḦÂxǧ!¨Æ¬ñ€Ö@õ–þ3ú Next. The obvious representation is to use a list of five ints. Another one-liner suffices. Our constructor needs to create a list and assign some initial values. These need to be set to some random ̨Á¨ÀPÀ Ú ÀPÀ values. 3 and 4 of the dice list. Since ÌÁÀÀ the latter is a special case of the former. would roll the dice in positions 0. which are just changing numbers.

Here’s the code:   èÆHÍÿÜPÑ1Á1ÌƬñ‡Ü£ÆÀHÍ3ú¬÷ óÝ×HÌƐÂ1ĨÆUÄHňÆàÑ1Á£ÉPÇÄ3ÜÈÀҐÜxÄ Ñ1Á£ÉPÇÄ3ÜYß û g Õ ¡Y€þ ͨÁH¥ Ì WÀxɽÆÐÒIǻܣƨÀ1͟ïpýҐѣÆn÷ Ñ£Á£ÉPÇÄÎÜ û WÀÓɈ) Æ Èß¡Ñ1ÁÓɐÇÄ3Ü û ˆ W ÀxɽÆgcá Ö óÿÜPÑ1Á1ÌÆcÄ1ŽÆÈÅ3ÂxLjà ңS Í 9ÐҀǻѣÁ£ÉÇ¨ÄÎܬ÷ ̨ÆHÄ1ÉÌH& Ç XD3 Ò WƀÁHÍРÎҀÇÃ63õ˜ÞÕ ƨÀÒÓT Í dÿÒ€Ç Ñ£Á£ÉÇ¨ÄÎܬ÷ ̨ÆHÄ1ÉÌH& Ç XDÁÓÉÌÝÁHÍР΀ Ò ÇÃ63õfÖ"9 ƨÀÒÓÍòñzÞ¡ÒIÇ Ñ1Á£ÉPÇÄ3ܨú ÂxLjà † ñ ÔÐÒIÇ Ñ1ÁÓɐÇÄ3ܨú­÷ ŽÀ ŽÀ . Five of a Kind. That is. Our function will need some way to indicate what the payoff is. Three of a Kind. since dice values are in the range 1–6. This defensive programming prevents other parts of the code from accidentally messing with our object. since the full house is more valuable. For example. ÜHÑ1ÁHÌ¨Æ Finally. if a client WˆÂPÀÓÉ½ÆˆÜ modifies the list that it gets back from .~zrH ”H1s½uŒˆ–{ x ˜ yè…v‹‡ç èÆHÍTWˆÂÀxɽƈܓñ‡ÜÓƨÀ1ÍÎú¬÷ ÌÆHÄ1ÉÌ1Ç Ü£ÆÀH͟ïpýÒPÑ1Æ û ÷f ´{é 6 ³ {qH‚QÒè{‡} 7 ” ¯ € ÎÒÑ£Æ Notice that I created a copy of the dice list by slicing it. We need to examine the values and determine whether we have any of the patterns that lead to a payoff. For example. That way. it will not affect the original copy 3ÒÑ£Æ stored in the object. û މõôÔæë õ 9‰õ–Ô‰õè) Þ  Ò occurs in dice. a full house also contains a three of a kind. We need to check for the full house before checking for three of a kind. If we do so in a sensible order. namely. Four of a Kind. One simple way of checking the hand is to generate a list of the counts Ñ£Á£ÉPÇÄÎÜ û " Ò  will be the number of times that the value of each value. or Straight. we come to the method. This is the function that will determine the worth of the current dice. the for various values in hand contains a triple and a pair. If the dice are: then the count list would be û Չõ–Õ‰õôԉõ–Ô‰õèՄõ‡Ö@õ–g û Õ  Ñ£Á£ÉPÇÄÎÜ g Õ  . Checking for various hands can then be done by looking Ñ1Á£ÉPÇÄ3Ü Ñ1Á£ÉPÇÄ3Ü Þ Ô . it is a full house. We can think of this function as a multi-way decision. if contains a and a . Two Pairs. We simply need to check for each possible hand. Let’s return a string labeling what the hand is and an int that gives the payoff amount. Notice that will always be zero. we can guarantee giving the correct payout. Full House. hence.

ÓpÔ †§ˆ} Ô })c„3…‡ ¥ Š©Õq})zÃÖg†§† Now we are ready to turn our attention to the task of actually implementing the poker game. 4. If there is no 6. likewise. We can use top-down design to flesh out the details and also sugب Á ÎÆHQ Ì ¢‡ÇĨÆH̨ͨÂÑ£Æ gest what methods will have to be implemented in the class. we could try out the correctly. .¯ 7 ¯ s@tŒuxw†y|{‡}†~†rH˜Ñ  Ê { ³ y•iUÑn} 6 {‡Š†y|{z‹ 4 é {zˆ 6 HŠ ̨ÆHÄ1ÉÌHÇ&XDHɽÀÀV¢Á£É4Ü£Æ'3õfÖÓÔ Æ¨ÀÒÓÍWÞ¡Ò€Ç Ñ£Á£ÉÇ¨ÄÎܬ÷ ̨ÆHÄ1ÉÌHÇ&XHŨÌÆPƀÁPÍРÎÒILjÃ'ÎõÆe ƨÀÒÓÍÈǽÁ1Ä©ñ†ÔàÒ€Ç Ñ£Á£ÉPÇÄÎܐú ÂÓÇÃòñvÑ£Á£ÉPÇÄÎÜ û ÖqßßÕcÁ1ÌÿÑ1Á£ÉPÇÄ3Ü û øgcßPßÝÕ3ú¬÷ ̨ÆHÄ1ÉÌH& Ç qÅ1ÄPÌˆÂ¨Ò !1Ũ# Ä 3õ˜ÔPÕ Æ¨ÀÒÓÍàÑ1ÁÓɐǨÄÎÜæï–Ñ1ÁÓɐÇĉñ†ÔˆúªßPßÐÔo÷ ̨ÆHÄ1ÉÌH& Ç XPÛÁU؈¨ÒÓÌ3% Ü ÎÆ õ 9 ƨÀˆÜÓÆn÷ ̨ÆHÄ1ÉÌH& Ç  ü £ÌH˽g  !¨B Æ ÎõlÕ ŽÀ The only tricky part is the testing for straights. Here is a short interaction showing some of what the class can do:  ÍP̨ÁxÊÿýÒPÑ1ÆÐÒvÊCˆÁHÌÄ ÃWß ÎҐѣÆæñ‡ú ï WˆÂÀxɽƈܓñIú (©()( ßs û ø‰õ ބõ މõ ø„õî9g (©()( ßïôÜPÑ1Á1ÌƬñIú ñ fPÛÁU؈¨ÒÓÌÎÜ Ô õ 9ˆú (©()( ßï–ÌÁ¨ÀPÀ¬ñ û d©3ú ï WˆÂÀxɽƈܓñIú (©()( ßs û ø‰õ ބõ މõ ø„õÆd© (©()( ßï–ÌÁ¨ÀPÀ¬ñ û d©3ú ï WˆÂÀxɽƈܓñIú (©()( ßs û ø‰õ ބõ މõ ø„õ Þ) (©()( ßïôÜPÑ1Á1ÌƬñIú ñ fDHɽÀV À ¢Á£É@ÜÓÆ PõfÖÓԈú (©()( (©()( # Ž ÎÒÑ£Æ   ’ } We would want to be sure that each kind of hand scores properly. checking that there are no pairs— — guarantees that the dice show five distinct values. Since we have already checked ǽÁHÄàÔàÒIÇ Ñ1Á£ÉPÇÄ3Ü for 5. and 3 of a kind. 3ÒÑ£Æ class to make sure that it is working At this point. then the values must be 1–5. no 1 means the values must be 2–6.

This will allow us to do any necessary cleaning up such as printing a final message for the user or closing a graphics window. . Since it costs ܣƐÀH͟ïÊÎÁÓǽÆHÏ ( ß Ö€Õ $10 to play a hand. Each round will consist of a series of rolls. we know that the will need to keep track of the dice. allowing the user to continue playing hands until he or she is either out of money or chooses to quit. Determining whether the user actually wants to play another hand must come from the user Ì1ÉÇ method: interface. we will create an instance of this class and call its method. Let’s initialize these values in the constructor. the program will have to adjust the player’s score. ½ÀÂ1Ïg ˆÁÓɐLjà Most of the work of the program has now been pushed into the method. a suitable method from is invoked.~zrH ”H1s½uŒˆ–{ x ˜ yè…v‹‡ç ´{é 6 ³ {qH‚QÒè{‡} 7 ´ ¯ € ØÁ ΈÆ1Ì Ú ) Initially. Based on these rolls. Here is one way we might code the èÆH̀ÌHɐÇoñ‡ÜÓƨÀHÍ3ú¬÷ ÛPÅ4Ò1ÀPÆàÜÓƨÀ1͟ïÊ3Á£ÇˆÆHÏ ( ß ÖxÕÐÂÓÇáܣƐÀHÍnïôҀǨÄÆ1̨ͨÑ1Æoï–Û½ÂxÇ) Ä ÁHØÀÂ£Ï„ñvú¬÷ ÜÓƨÀ1͟U ï ½ÀÂ£) Ï  ˆÁÓɐÇÉñIú ܣƨÀ1͟ï–Ò€ÇĨÆH̐ÍÂÑ£Ænï–ÑHÀPÁˆÜ£Æ¬ñIú ҀÇĨÆH̐ÍÂÑ£Ænï–ÑHÀPÁˆÜ£Æ Notice the call to at the bottom. ÑHÀPˆÜPÜ ØÁ ΈÆHÌ Ú )„÷ èÆHS Í Ì©ÌÒIÇ4Òx§ Ä Ì©Ì­ñ‡ÜÓƨÀHÍ3ú¬÷ ܣƨÀ1͟ïpýҐѣÆUß ÎÒPÑ1ƬñIú ܣƨÀ1͟ïÊÎÁ£ÇˆÆHÏcß ÖxÕÕ Ü£Æ¨À1͟ï–Ò€ÇĨÆH̐ÍÂÑ£ÆÈ߀ب Á ÎÆHQ Ì ¢‡ÇĨÆH̨ͨÂÑ£ÆæñIú # ÌHÉPÇ To run the program. Basically. the amount of money. èÆH£ Í 3ÀÂ£) Ï  Á£ÉÇÉñvܣƨÀ1ÍÎú­÷ ܣƨÀ1͟ïÊÎÁ£ÇˆÆHÏcßÿܣƨÀ1͟ïÊÎÁ£ÇˆÆH¥ Ï ¨ Ö€Õ Ü£Æ¨À1͟ï–Ò€ÇĨÆH̐ÍÂÑ£ÆnïôÜ£ÆHÄHöˆÁÓǽÆHωñvÜÓƨÀ£ÍŸïÊÎÁxǽÆHÏÎú ܣƨÀ1͟ïpè Á  Á¨ÀPÀˆÜ“ñ‡ú Ìƽ܇É3À£Änõ ÜHÑ1ÁH̨ÆcßÿܣƐÀHÍnïùýÒPÑ1ÆoïzÜPÑ£ÁH̨ÆæñIú ܣƨÀ1͟ï–Ò€ÇĨÆH̐ÍÂÑ£ÆnïôÜIŽÁ£© Û  ƽÜIɽÀ£Ä‰ñ–̐ƽ܇É3ÀÓÄnõ¢ÜPÑ£ÁH̨Æ3ú ܣƨÀ1͟ïÊÎÁ£ÇˆÆHÏcßÿܣƨÀ1͟ïÊÎÁ£ÇˆÆHÏcá ÜHÑ1Á1ÌÆ Ü£Æ¨À1͟ï–Ò€ÇĨÆH̐ÍÂÑ£ÆnïôÜ£ÆHÄHöˆÁÓǽÆHωñvÜÓƨÀ£ÍŸïÊÎÁxǽÆHÏÎú This code only really handles the scoring aspect of a round. Anytime new inforҀǨÄÆ1̨ͨÑ1Æ mation must be shown to the user. we can continue as long as . and some user interface. the program will loop. Let’s continue the top-down process by focusing our attention here.

These methods can be implemented in many different ways. we might first try building a simple text-based interface. because we don’t have a user interface. The program then processes a series of ÐÁ ˆÁÀÀÜ ). We can’t really test out this program yet. we are down to the nitty-gritty details of implementing the dice rolling process. If we are in a hurry to get our application running. .7 ¹ ¯ € s@tŒuxw†y|{‡}†~†rH˜Ñ  Ê { ³ y•iUÑn} 6 {‡Š†y|{z‹ 4 é {zˆ 6 HŠ The $10 fee to play a round is first deducted and the interface is updated with the new amount of money remaining. Let’s use a local variable to keep track of how many times the dice have been rolled. producing programs that look ب Á ÎÆHÌ Ú © quite different even though the underlying model. graphical interfaces are much more complicated to design and build than text-based ones. èÆHÍWèÁ Á¨ÀPÀˆÜ“ñvܣƐÀHÍÎú­÷ ܣƨÀ1͟ïpýҐѣÆnï–ÌÁ¨ÀPÀ Ú ÀÀ¬ñ‡ú ÌÁ¨ÀPÀUß»Ö Ü£Æ¨À1͟ï–Ò€ÇĨÆH̐ÍÂÑ£ÆnïôÜ£ÆHÄ ÎÒPÑ1ÆæñvÜÓƐÀHÍoïùÈҐÑÓÆnïpWÂPÀxɽÆܓñ‡úú Ä Á  Á¨ÀPÀUßÿܣƐÀH͟ï–ҀǨÄÆH̐ͨÑ1Ænï–рňÁÁ½ÜÓÆ 3ҐÑ1Ƭñ‡ú ÛPÅ4Ò1ÀPÆŲÁ¨ÀPÀ ÞàÂxLjÀĨ Á  ˆÁÀÃ À –ß û n÷ F ÜÓƨÀ1͟ïùÈҐѣÆnïp̨Á¨ÀPÀ¬ñ–Ĩ Á  Á¨ÀÀˆú ̨Á¨ÀPÀUßWÌÁ¨ÀPÀUá»Ö ÜÓƨÀ1͟ïôÒIÇĨÆH̨ͨÂÑ£ÆnïzÜÓÆHÄ ÎҐѣÆæñŒÜ£ÆÀHÍoïùýÒPÑ£Æop ï W¨ÂÀxɽÆܓñIúPú ÒÓ̀ÌÁÀÀ Þn÷ F Ĩ Á  ˆÁÀÀUßÿÜÓƨÀ1͟ïôÒIÇĨÆH̨ͨÂÑ£ÆnïôÑIŽÁPÁ½Ü£Æ ÎÒPÑ1Æ­ñIú u 3 u ! At this point. Our interface must support the methods for displaying Ü£Æ1ÄPöˆÁÓǽÆ1Ï ÜÓÆHÄ 3ÒÑ£Æ ÜIňÁ1Û© ƽ܇É3À1Ä information: . Obviously. Finally. and updates the amount of money rolls ( accordingly. That is. and . we have a model of the process for playing poker. we have completed the basic functions of our interactive poker program. and . . ÊmÇȑÉÈ ™ Ú ÿ G· ² º›ä¼ iC›Ct –%sqi ä ب Á ΈÆ1Ì Ú © In designing we have also developed a specification for a generic ØÁ ΈÆ1ÌQ¢IǨÄÆ1̨ͨÑ1Æ class. Initially. It must also have methods Û½ÂxÇÄ)ÁHØÀÂ£Ï рňÁÁˆÜ£Æ 3ÒÑ£Æ that allow for input from the user: . shows the user the result. however. remains the same. We can use this for testing € 3 . Then we need a loop that continues rolling user-selected dice until either the user chooses to quit ̨Á¨ÀÀÜ rolling or the limit of three rolls is reached. displaying the dice and getting the list of dice to roll must come from interaction with the ÒIÇĨÆH̨ͨÂÑ£Æ user through . Usually. all of the dice will be rolled.

g Æ ¦P% Ä ¢IÇĨÆH̐ÍÂÑ£Æ class using this approach: Here is a complete óWͽÒ1ÀPÆo÷ Ä) Æ ¦Hg Ä ˆ Á ΈÆ1̙b ï Ï ÑHÀPˆÜP§ Ü g Æ ¦PQ Ä ¢‡ÇĨÆH̨ͨÂÑ£Æn÷ èÆHÍSÌ©ÌÒIÇ4Òxħ̩̭ñ‡ÜÓƨÀHÍ3ú¬÷ Ì3ÒIÇA Ä 84ˆÆÀÑ1Á€ÊÎÆUĨÁEW3ÒÓèƐÁè½ÁÎÆH̟ïq èÆHÍÿÜ£ÆHÄHöˆÁÓǽÆHωñ‡ÜÓƨÀḦ́õ¢ÂIʽÄÎú¬÷ Ì3ÒIÇA Ä  ÁÓÉ Ñ€ÉÌPÌÆÓÇĈÀ£ÏÈŽÂWÆ Ã¨ÆHÍÿÜ£ÆHÄ ÎÒPÑ1ÆæñvܣƐÀHÍoõ WˆÂPÀÓɈƽܨú­÷ Ì3ÒIÇÄA ÎÒPÑ1Æn÷uÎõ°WÀxÉ½Æ½Ü “ u r ¬ " ­" Ãnïq ©ñ†ÂIʽÄÎú èÆHÍcÛ½ÂÓǨĩ¨ÁH؈ÀPÂ1ωñ‡Ü£ÆÀHÍ3ú¬÷ ÂÓÇ@Ü ß€Ì£§ Û ÌҀ) Ç É¨Ä„ñ  ˆÁYÏÁÓÉÝÛÎҨ܇ÅÐÄÁcÄP̐ÏWÏÁÓÉÌàÀxÉ4ÑÎ%Pa£ú ÌÆHÄ1ÉÌ1Ç¡ÂÓÇ4Ü û g Õ àҀ³ Ç †Ï 6 èÆHÍ¡ÑHÀPÁˆÜ£Æ¬ñ‡Ü£ÆÀHÍ3ú¬÷ Ì3ÒIÇA Ä  Óc Ç HÅ3ÂxÇcÎÎÜ Í¨Á1ÌE3ÀPÂ1Ï3ÒIǧ! r g“ èÆHÍÿÜIŽÁ£Û© ƽÜIɽÀ1ĉñ‡Ü£ÆÀḦ́õŽÊ“Ü"!„õÜPÑ1Á1Ìƽú¬÷ Ì3ÒIÇA Ä  3ܬï Á£ÉÝÛ3Ò€Ç ÃŸu ï  ñpʓÜ"!„õÜPÑ1Á1Ìƽú ´ G" ƒ“ u ¬ " ­" . but rather. let’s tweak our as a parameter to the constructor. Each of the necessary methods can be given a trivial implementation. Now let’s consider a bare-bones interface to test out the poker program.~zrH ”H1s½uŒˆ–{ x ˜ yè…v‹‡ç ´{é 6 ³ {qH‚QÒè{‡} 7 ¿ ¯ € and debugging of the model without all the extra complication of a full-blown GUI. ØÁÎÆHÌ Ú © class a bit so that the user interface is supplied First. ÑHÀPˆÜPÜ ØÁ ΈÆHÌ Ú )„÷ èÆHS Í Ì©ÌÒIÇ4Òx§ Ä Ì©Ì­ñ‡ÜÓƨÀḦ́õ ÒIÇĨÆH̨ͨÂÑ£Æ3ú¬÷ ܣƨÀ1͟ïpýҐѣÆUß ÎÒPÑ1ƬñIú ܣƨÀ1͟ïÊÎÁ£ÇˆÆHÏcß ÖxÕÕ Ü£Æ¨À1͟ï–Ò€ÇĨÆH̐ÍÂÑ£ÆÈß¡ÒIÇĨÆH̨ͨÂÑ£Æ # Then we can easily create versions of the poker program using different interfaces. Our text-based version will not present a finished application. it provides a minimalist interface solely to get the program running.

we get a rough but useable interaction. When running this program. 4ˆÆÀÑ£ÁxÊÎÆÈÄE Á W3ÒÓèÆPV Á ½Á ΈÆHÌŸï ˆÁcϨÁ£ÉÝÛ3Ò¨ÜIÅÐĨÁcĐÌPÏWÏÁ£É¨ÌÐÀÓÉÎ Ñ Î%P Ï ÁÓÉ Ñ€É¨ÌÌÆÓÇÄÀ1ÏÈŽ  W¨Æ ýÕoï ÎÒPÑ1Æo÷ û ø‰Æ õ doÆ õ doõÔæÆ õ d© ǨÄÆ1ÌÐÀҐÜxÄÐÁPÍcÛHÅ4ÒPрÅÐÄÁàÑIÅ3Âx§ Ç !¨Æ ñ û €Ä¨Á¡ÜxĨÁ “ú û ՄH õ d© G ÎÒPÑ1Æo÷ û Ö@Æ õ doÆ õ doõÔæõ g Ô  ǨÄÆ1ÌÐÀҐÜxÄÐÁPÍcÛHÅ4ÒPрÅÐÄÁàÑIÅ3Âx§ Ç !¨Æ ñ û €Ä¨Á¡ÜxĨÁ “ú û ) Õ  G û ÎÒPÑ1Æo÷ ÔæÆ õ doÆ õ doõÔæõ g Ô  DHɽÀ` À ¢Á£É@ÜÓÆnï ¨Á£ÉÝÛ3Ò€Ç ÖxÔoï ÁÓÉ Ñ€É¨ÌÌÆÓÇÄÀ1ÏÈŽ  W¨Æ ÖxՐÔoï ˆÁcϨÁ£ÉÝÛ3Ò¨ÜIÅÐĨÁcĐÌPÏWÏÁ£É¨ÌÐÀÓÉÎ Ñ Î%P Ï ÁÓÉ Ñ€É¨ÌÌÆÓÇÄÀ1ÏÈŽ  W¨Æ ý¨Ô„ï ÎÒPÑ1Æo÷ û 9æõ ø„Æ õ doÔ õ d„î õ 9g ǨÄÆ1ÌÐÀҐÜxÄÐÁPÍcÛHÅ4ÒPрÅÐÄÁàÑIÅ3Âx§ Ç !¨Æ ñ û €Ä¨Á¡ÜxĨÁ “ú û  Ö  G ÎÒPÑ1Æo÷ û 9æî õ 9‰Æ õ doÔ õ d„î õ 9g ǨÄÆ1ÌÐÀҐÜxÄÐÁPÍcÛHÅ4ÒPрÅÐÄÁàÑIÅ3Âx§ Ç !¨Æ ñ û €Ä¨Á¡ÜxĨÁ “ú û  G DHɽÀ` À ¢Á£É@ÜÓÆnï ¨Á£ÉÝÛ3Ò€Ç ÖxÔoï ÁÓÉ Ñ€É¨ÌÌÆÓÇÄÀ1ÏÈŽ  W¨Æ Öxg Õ dŸï ˆÁcϨÁ£ÉÝÛ3Ò¨ÜIÅÐĨÁcĐÌPÏWÏÁ£É¨ÌÐÀÓÉÎ Ñ Î%P Ï “     “ “ “ ¬ ½“ ½“ ¬¬ ¬ ¬¬ . Here is a complete program making use of the modules that we have developed: ó€Äg Æ ¦P Ä ½ Á ÎÆH̟U ï ¥ Ï ¨©¨£W½Ò£Ã¨ÆPÁcýÒPÑ1` Æ ˆ Á ΈÆ1ÌUÉ@ÜHҀC Ç !ÐÂUÄ) Æ ¦H§ Ä ¨xË3ˆÜÓÆPÃÝҀÇĨÆH̐ÍÂÑ£Ænï ÍP̨ÁxÊSˆÁΈÆ1̈©ÿÒvÊCˆÁH̐ÄcØÁÎÆHÌ Ú © ÍP̨ÁxʡĨ) Æ ¦PĽҀǨÄÆHÌÐ҇c Ê ½ÁHÌPT Ä g Æ ¦P% Ä ¢IÇĨÆH̐ÍÂÑ£Æ Ò€Ç¨ÄÆ1ÌW¥ ß Æ)¦HÄQ¢‡ÇÄÆ1̨ͨÂÑ1ƬñIú Â")à߀ØÁ ΈÆHÌ Ú )nñvÒIÇĨÆHÌ4ú Â")„ï–ÌHɐÇoñIú Basically. we can test out our program to see if we have implemented a correct model. all this program does is create a text-based interface and then build a ØÁ ΈÆ1Ì Ú ) using this interface and start it running.7 â ¯ € s@tŒuxw†y|{‡}†~†rH˜Ñ  Ê { ³ y•iUÑn} 6 {‡Š†y|{z‹ 4 é {zˆ 6 HŠ èÆH͡рŽÁPÁ½ÜÓÆ ÎÒPÑ1Ƭñ‡Ü£ÆÀHÍ3ú¬÷ ÌÆHÄ1ÉÌ1Ç Ò€) Ç Éĉñ  ÇĨÆH̀ÀҐÜxÄÐÁPÍcÛHÅ4ÒPрÅÐÄÁàÑIÅ3Âxǧ!¨Æ G 3 ñ û€  ĨÁ¡ÜxĨÁ “  úS£ú ØÁ ΈÆ1Ì Ú ) Using this interface.

we’ve got a game that’s already quite a bit of fun to play! ÊmÇȑÉÈ‘× œ iCk§i%ٌvx͕l™wm•£– ä Now that we have a working program. Clearly. we could provide a button for each die and have the user click the buttons for the dice they want to roll. the user will have to decide between either rolling the dice or quitting.  }g‚3…%C…‡î„X‰c} Ó ©„3})zp€)‹„X…ˆŠm Let’s start with the basic methods that must be supported and decide exactly how interaction with the user will occur. Û½ÂxÇ) Ä ÁHØÀÂ£Ï To get information from the user. In . The Ü£Æ1Ä 3ҐÑ1Æ ÜÓÆHÄHöˆÁ£ÇˆÆHÏ and methods will be used to change those displays. ÑIŽÁÁˆÜ£Æ ÎÒÑ£Æ To implement . One leaves one output method. When the user is done € ! . we will make use of buttons. We could include “Roll Dice” and “Quit” buttons for this choice. In fact. in a graphical interface. let’s turn our attention to a graphical interface. This is sometimes called a status bar. That ÜIňÁ1© Û  ƽ܇É3À1Ä .~zrH ”H1s½uŒˆ–{ x ˜ yè…v‹‡ç ´{é 6 ³ {qH‚QÒè{‡} 7 é ¯ € “   “ ÁÓÉ Ñ€É¨ÌÌÆÓÇÄÀ1ÏÈŽÂW¨Æ ý)dnï ÎÒPÑ1Æo÷ û މõ ԉõªÖ“õ Ö@õªÖ ǨÄÆ1ÌÐÀҐÜxÄÐÁPÍcÛHÅ4ÒPрÅÐÄÁàÑIÅ3Âxǧ!¨Æ ñ û €Ä¨Á¡ÜxĨÁ “ú G ÎÒPÑ1Æo÷ û 9æõ ø„õªÖ“õ Ö@õª Ö  ǨÄÆ1ÌÐÀҐÜxÄÐÁPÍcÛHÅ4ÒPрÅÐÄÁàÑIÅ3Âx§ Ç !¨Æ ñ û €Ä¨Á¡ÜxĨÁ “ú G ÎÒPÑ1Æo÷ û Ö@î õ 9‰õªÖ“õ Ö@õª Ö  DÁÓÉÌÐÁHÍРÎҀÇÃŸï ¨Á£ÉÝÛÎÒIÇ Ö 9oï  ÁÓÉ Ñ€É¨ÌÌÆÓÇÄÀ1ÏÈŽ  W¨Æ ÖxÕPýnï ˆÁcϨÁ£ÉÝÛ3Ò¨ÜIÅÐĨÁcĐÌPÏWÏÁ£É¨ÌÐÀÓÉÎÑÎ%P Ç ¬ û ՄõvÖ û ՄõvÖ ¤À ƒ“ ¬ ¬ ü¼ HŽÂÓÇ©Î4ÜY͐ÁHÌE3ÀPÂ1ϽҀǧ!  You can see how this interface provides just enough so that we can test out the model. the faces of the dice and the current score should be continuously displayed. common way to handle this sort of transient information is with a message at the bottom of the window. That leaves us with figuring out how the user should choose dice. that we need to accommodate. The interface will have to support the various methods found in the text-based version and will also probably have some additional helper methods. Our first step must be to decide exactly how we want our interface to look and function.

hence asking the program to roll no dice. One simple approach would be to change the color of the die. Now we have a basic idea of how the interface will function. they could click the “Roll Dice” button again to roll the selected dice.” рňÁÁˆÜ£Æ 3ÒÑ£Æ Our vision for suggests a couple of tweaks for the interface. Unlike the buttons in the calculator program. Perhaps clicking the button of a currently selected die would cause it to become unselected. The latter approach seems a bit more intuitive/informative. We could handle this by having them click the “Roll Dice” button when no dice are selected. we should have some way of showing the user which dice are currently selected. Elaborating on this idea. it would be nice if we allowed the user to change his or her mind while selecting the dice. they would like the dice scored just as they stand. When user input is required. To implement this behavior. I’m sure those of you with a more artistic eye can come up with a more pleasing interface.¯ ~37 s@tŒuxw†y|{‡}†~†rH˜Ñ  Ê { ³ y•iUÑn} 6 {‡Š†y|{z‹ 4 é {zˆ 6 HŠ choosing the dice. First. The user commits to a certain selection by clicking on “Roll Dice. but we’ll use this one as our working design. For example. Another approach would be to provide a separate button to click that causes the dice to be scored. The return value of     . We still need to P  figure out how it will look. Second. is a sample of how the interface might look. and HɨĐÄÁÓÇ since we have quite a number of buttons to manage. the buttons of our poker interface will not be active all of the time. we need a good way for the user to indicate that they wish to stop rolling. That is. The clicking of the button will serve as a sort of toggle that selects/unselects a particular die. There are lots of ways we could do this. we can use a list of s. Let’s add a “Score” button to the interface. and then waits for the user to click one of them. What is the exact layout of the widgets? Figure . HɨĐĨÁ£Ç 3Ò1ÆgÛ½Ò1Æ£Û Our intent is to reuse the and classes for these widgets that HÉÄPÄÁÓÇ were developed in previous chapters. similar to the approach we used in the calculator program from Chapter 11. рňÁÁˆÜ£Æ The method takes a list of button labels as a parameter. activates them. the valid buttons for that interaction will be set active and the others will be inactive. The class can be used as is. we can add a helper method рňÁÁ½ÜÓÆ ØÁ ΈÆH% Ì ¢IǨÄÆH̐ͨÑ1Æ called to the class. 3 ƒ €cC€Im…‡ԄX‰c}Ø× …@¦V§} „8‚ The graphical interface that we are developing makes use of buttons and dice. Let’s “gray out” the pips on the dice selected for rolling. the dice buttons will only be active when the user is actually in the process of choosing dice.

Ü : GUI interface for video dice poker. if we are waiting for the user to choose either the “Roll Dice” or “Quit” button. We can call the ÙiÚ method whenever we need input from the user. here W H ¦S¢¢VW à H ¥ S ¢ Ù Ú i ž Ù  ä ±B¡  Ù «SW ¦S¢¢VW ã R³ä瞲±èä ±B¡ « HI¢¤ê£¥ HVU §6ª W H 㠞 ä韭¼ ä ži±ëÙiÚ ž Ù ¤ ¡ Ù ž¬ ¥ ¢ ž¬ R©¡ .~zrH ”H1s½uŒˆ–{ x ˜ yè…v‹‡ç ´{é 6 ³ {qH‚QÒè{‡} ¯ ~€~ Figure Ý)Ü . we would use a sequence of code like this: ÙiÚ ž « W ž¤Ù Ù²Ú W H W¤W H ßÛ¡ žÙ H HSUQ« ß©ß WW H §XÜ6ݸÞXWVU¤U ´ Ÿ„ÙiÚ ¡ ÝkÞVWVU¤U HßÝ'ã °©žÙ °©ž¤Ù Hßݧà8Ýiái¦ ž ¢ Ý™â§ª ŸŸ¤Ÿ Assuming the buttons are stored in an instance variable called ä WW H is one possible implementation of ÙiÚ : ¡  HI« ä æ ÙiÚ W¤W ¦V¢¤¢VW ¡ H´§ ¡ HVU «|à HVUQ« ÙiÚ ±B¡èß¿¡ ¥ ¢VH H ª ã   žÙ ¡ ¦V¢¢SW Ÿ ä å ±'¡ ¥ ¢SH³WI¢ Ú H W ¦V¢¢SW ±'¡ . ¡ the function is the label of the button that was clicked. For example.

here is Ü£Æ1© Ä ÛÀÓÉˆÆ the method as we left it: èÆHÍÿÜ£ÆH) Ä ÛˆÂPÀÓɽƬñ‡ÜÓƨÀḦ́I õ WÀxɽÆ3ú­÷ ó HÉÌ1ÇÿÀPÀUÄHŽ` T Æ Î Ò 4Ü ÁPÍPÍ Í¨ÁHE Ì Î Ò  ÒIǻܣƨÀ1͟b ï 4 Ò 4Üæ÷ Î Ò hïzÜ£Æ1© Ä D½ÒHÀÀ­ñ‡ÜÓƨÀHÍnï|˽Â Ñ Îc!P̐Á£ÉPLjýú   óTHÉÌ1ÇÐÄHňÆÝÂ"©¨ÌÁ"Ì3Ò1Â1ĨÆè4Òq@ܪ˽ÂÑÎàÁ£Ç ͨÁHÌÿÒWÒIǻܣƐÀH͟ïùÁ£c Ç ˆÂÓ˽ÀPÆ û WˆÂPÀÓɈ) Æ Ÿ÷ û ÜÓƨÀ1͟U ï Î Ò 4Ü " Ò ŸïôÜ£ÆH) Ä D3Ò1ÀÀ¬ñvÜ£ÆPÀHÍnïùÍPÁHÌg Æ !H̨Á£ÉHLjÃ3ú 3Ò1 Æ Û3Ò1Æ£Û Ü£ÆHĨאÁÀPÁHÌ We need to modify the class by adding a method. ÎÒ1 Æ Û3Ò£Æ1Û You might want to go back and review the class. but we need to add just a bit of new functionality. changing the value of ͨÁ1Ìg Æ !PÌÁÓɐÇà will not actually change the appearance of the die until it is redrawn using the new color. we want to change the color of a die to indicate whether it is selected for rerolling. Of course. As Ü£Æ1ĩۈÂPÀÓÉˆÆ you can see in the code for . To refresh your memory a bit. ÜÓÆHÄ×PÁ¨ÀHÁHÌ seems straightforward. we will use the same class as before. We need two steps: The algorithm for рŽÂÓC Ç !¨Æc͐ÁHÌg Æ !P̨Á£ÉÇÃUĨÁcÄHŽÆÈLjÆ1Û Ñ£Á¨ÀPÁ1Ì ÌÆHÃPÌ£ÛWÄ1ŽÆàрɨ̨̐ƣÇE Ä WˆÂÀxɽƀÁH̀ÄHňƀýÒ1Æ  . the class constructor draws a square and seven circles to represent the positions Ü£Æ1© Ä ÛˆÂPÀÓÉˆÆ where the pips of various values will appear. This method will be used to change the color that is used for drawing the pips. Basically. the color of the pips is determined by ͐ÁHÌÆg!P̨Á£ÉÇà the value of the instance variable . The method turns on the appropriate pips to display a given value. Remember. As discussed above.¯ ~†r s@tŒuxw†y|{‡}†~†rH˜Ñ  Ê { ³ y•iUÑn}pì {‡Š†y|{z‹ 4 é {zˆíì HŠ ËhïèÂÑxÄ3ÒWˆÂ1ĨÆæñ‡ú ƐÀˆÜÓÆn÷ ËhïùèƐÂÑxÄ3Ò"WÂ1ĨÆæñIú ó !¨ÆHÄÈÊ3Á£É4Ü£ÆàÑHÀ¨ÒÑÎ4ܪÉPÇÄ3Ò1À€ÂÓÇÿ¨ÑÓĽÒ"WÆYːÉÄPÄÁÓÇ Ò¨ÜWÑHÀ¨ÒÑΈÆPà ¥ ÛPÅ4Ò1ÀPÆ£PÌHɈÆn÷ àß ÜÓƨÀHÍnï–Û3ҀDŽïp!¨Æ1ÄPöˆÁÓÉ@ÜÓÆæñIú ͐ÁHÌcË ÒIÇWːÉÄPÄÁÓÇ@Üæ÷ ÒÓÍU˄ïôÑ1ÀÒP Ñ ÎˆÆHÉf ñ “ú¬÷ ÌÆ1ÄHɨÌHǀËhf ï !¨Æ1© Ä ¤ÂÓ˽ƐÀ¬ñ‡ú óWÍ1ɐÇÎÑÓĽÒ1Á£ÇÐÆ)¦½ÒxÄUŽÆ1ÌÆoï ÎÒ1 Æ Û3Ò£Æ1Û The other widgets in our interface will be our that we developed in the last two chapters.

namely . The constructor will create all of our widgets. But requires us to send the 3Ò1ÆgÛ½Ò1Æ£Û value as a parameter. implementing is a breeze. the second step presents a slight snag. Once the proper pips have been turned on. ܣƐÀHÍnp ï WˆÂPÀÓɈÆUT ß WˆÂPÀÓÉˆÆ  WˆÂÀxÉ½Æ This line stores the value parameter in an instance variable called . Ü£Æ1ÄאÁÀPÁ1Ì Ü£Æ1© Ä ÛÀÓÉˆÆ In order to implement . the actual value is discarded. We already have code ÜÓÆHĩېÀxÉ½Æ ÜÓÆHÄ)ۈÀxÉ½Æ that draws a value. setting up the interface for later interactions. the value that was saved from the last time ˆjzp}€g„X…‡Ƅž‰c} Ó ©„8}©zåîp€)‹"} Now that we have our widgets under control. passing along ÜÓÆHÄ)ۈÀxÉ½Æ was called.~zrH ”H1s½uŒˆ–{ x ˜ yè…v‹‡ç ´{é·ì ³ {qH‚QÒè{‡} ¯ ~†” Unfortunately. Then can redraw the die using its current ÜÓÆH) Ä ÛˆÂÀxÉ½Æ value. we are ready to actually implement our GUI poker interface. The change to is easy. Ü£ÆHÄ)ۈÂPÀÓÉ½Æ Ü£Æ1ÄאÁÀPÁ1Ì . we just need to add a single line. and the current version of does not store this value anywhere. we need to tweak so that it reÜ£ÆHĨאÁÀPÁHÌ members the current value. ÑHÀPˆÜPÜ ü Ì"  ÅÎҐѐ© Ü ¢IǨÄÆ1̨ͨÑ1Æo÷ èÆHS Í Ì©ÌÒIÇ4Òx§ Ä Ì©Ì­ñ‡ÜÓƨÀHÍ3ú¬÷ ܣƨÀ1͟ï|ÛÎҀÇWß ü ̈  © Å 4ÎҀÇoñ  ÎÒÑ£Æ Ø¨ Á ÎÆH# Ì 3õ˜øÕPՄõçdÕÕ½ú ܣƨÀ1͟ï|ÛÎҀÇhïzÜÓÆHÄ Â Ñ ÎC!P̨Á£ÉPLjÉ" ñ X!HÌÆHƣLj' Þ xú Ë3ÂÓÇPǽÆ1ÌWT ß g Æ ¦PĄñèØÁҀÇĉñzÞPՐՄõèސսú†ü õ ŒØPϐÄHňÁ£Ç ØÁ ΈÆ1Ì ØˆÂ£ÌˆÀHÁHÌ#Óú Ë3ÂÓÇPǽÆ1̙ïzÜÓÆHC Ä ÅÒ Ææñzg Ô dÎú Ë3ÂÓÇPǽÆ1̙ïzÜÓÆH) Ä D3ÒHÀPÀ¬" ñ ŒÏƐÀÀHÁ1Û½• Ô Óú Ë3ÂÓÇPǽÆ1̙ïzÜÓÆHC Ä Å1ĐÏÀPƬñ zˈÁ¨À16 à £ú Ë3ÂÓÇPǽÆ1̙ïùÃḦÂÓÛoñ‡ÜÓƨÀ1͟ï–Û3ҀÇ@ú ܣƨÀ1͟ïÊ†" Ü !U¥ ß ) Æ ¦HĄñèØÁˆÒIÇĉñzސÕPՄõè© Þ eÕ½ú†‰ õ 84ˆÆ¨À¨Ñ1Á€ÊÎÆUĨÁcÄHÅ½Æ 3Ґѣ£ Æ ˆÂxË3ÀPB Æ £ú ܣƨÀ1͟ïÊ†" Ü !nïzÜÓÆH§ Ä Å¨Ò Ææñ€ Ö e3ú ܣƨÀ1͟ïÊ†" Ü !nïùÃḦ£ۄñ‡ÜÓƨÀHÍnï–Û3ҀǓú ܣƨÀ1͟ï–ÑÓÌƐÂ1Ä¨Æ ÎÒPÑ1Ƭñ–ØÁҀǨĄñzÞPÕPՉõ‡ÖIՐսú†õ © þ 9½ú ܣƨÀ1͟ï ːÉÄPÄÁÓÇ@Üªß û  g !h r 3 !h Ž . With the modified version of èÆHÍÿÜ£ÆHĨאÁÀPÁH̉ñ‡ÜÓƨÀḦ́õ Ñ£Á¨ÀHÁHÌ4ú­÷ ܣƨÀ1͟ïpͨÁH̨) Æ !HÌÁ£ÉPLjà ßÿÑ1ÁÀPÁHÌ Ü£Æ¨À1͟ïôÜ£ÆH) Ä ÛˆÂPÀÓɽƬñ‡ÜÓƨÀHÍnp ï WÀÓɈƽú Ü£Æ1© Ä ÛˆÂPÀÓÉˆÆ Notice how the last line simply calls to (re)draw the die.

Even simple graphical interfaces involve many independent components. Here are the necessary definitions: èÆHÍ¡ÑÓÌƐÂ1Ä¨Æ ÎÒPÑ1Ƭñ‡Ü£ÆÀḦ́õ˜Ñ£Æ£Ç¨ÄÆHÌoõ ÜPÒ ¨Æ½ú¬÷ Ñ1ƣǨÄÆ1̙ïÊ3g Á W¨Ææ3 ñ ¨H§ Þ YÜPÒ Æ„õèÕ3ú ܣƨÀ1͟ïpýҐѣÆUß û  ͨÁHÌÿÒWÒIÇÐ̈Âx§ Ç !¨Æ¬3 ñ 9ˆú¬÷ W½Ò1Æ£ÛÝß ÎÒ1 Æ Û3Ò£Æ1ÛoñvܣƐÀH͟ï|ÛÎÒIǙõ¢Ñ1ÆÓÇÄÆ1Ìnõ ÜHÒ Æ3ú ÜÓƨÀ1͟ïùÈҐѣÆnïè  ©ˆÆ£ÇˆÃæÒ ñ W½Ò1Æ1Û4ú ѣƣǨÄÆH̟ïÊ3g Á WƬñ€Ö†¡ ï 9CYÜPÒ ¨Æ„õèÕ3ú 3 !h )h # èÆHÍÐÂHÐà ÎÒPÑ1Æ 1ÉÄPÄÁ£Ç4ܓñvܣƨÀ1ÍoõlѣƣÇĨÆHÌoõ ÛÎÒÓÃPÄHşõîŽÆÒ !£ÅÄ4ú­÷ Ñ1ƣǨÄÆ1̙ïÊ3ÁgW¨Ææñ3¨HÞ§Y€ÛÎÒ£ÃHÄHşõ Õ3ú ͨÁHÌÿÒWÒIÇÐ̈Âx§ Ç !¨Æ¬ñ€Ö@õ–ø3ú­÷ ÀPÂÓˈƨÀU& ß  3Ò1Æ P6 à  ©ñvÒ¨ú Ëàß 1ÉĐĨÁ£Çoñ‡Ü£ÆÀHÍnï–ÛÎÒIǙõ¢Ñ1ÆÓÇĨÆHÌnõîÛÎÒ£ÃHÄHşõîŽÆÒ !1ŨÄnõ ÀPÂÓˈƨÀ½ú ÜÓƨÀ1͟ï|ËPÉÄPÄÁ£Ç4Üæïð"  ©ˆÆ£ÇÉñðË@ú ѣƣǨÄÆH̟ïÊ3g Á WƬñ€Ö†¡ ï 9CY€ÛÎÒÓÃPÄHşõ Õ3ú 3 u )h !h   ž" ¯" These two methods are similar in that they employ a loop to draw five similar ØÁҀÇÄ Ñ£Æ£ÇĨÆHÌ widgets.¯ ~ ¯ s@tŒuxw†y|{‡}†~†rH˜Ñ ܣƨÀ1͟ïðÂHÐà ÎÒPÑ1Æ 1ÉÄPÄÁ£Ç4ܓñèØÁˆÒIǨĉñzÞHՐՉõ‡ÖIþÕ3ú“õ þc9æõ ސսú Ëàß 1ÉÄPÄÁ£Çoñ‡ÜÓƨÀHÍnï–Û3ҀǙõ بÁˆÒ€Ç¨Ä„ñôސՐՉõ˜ÔHސÕ3ú“õçd¨ÕPՄõÆdÕ„õè3 Á¨ÀPÀ ÎÒPÑ1Æ'Óú ܣƨÀ1͟ï ːÉÄPÄÁÓÇ@ÜæïðÂ")½Æ£ÇÉñù˓ú Ëàß 1ÉÄPÄÁ£Çoñ‡ÜÓƨÀHÍnï–Û3ҀǙõ بÁˆÒ€Ç¨Ä„ñôސՐՉõ˜ÔgeÕ3ú“õfÖ"9HՄõÆdÕ„õèqŨÑ1Á1ÌÆ'Óú ܣƨÀ1͟ï ːÉÄPÄÁÓÇ@Üæïð"  )½Æ£ÇÉñù˓ú Ëàß 1ÉÄPÄÁ£Çoñ‡ÜÓƨÀHÍnï–Û3ҀǙõ بÁˆÒ€Ç¨Ä„8 ñ 9PþÕ‰õ–ÞPc þ 9½ú“5 õ dÕ„õ ÞPՄè õ  xÉ4Òx# Ä £ú ܣƨÀ1͟ï ːÉÄPÄÁÓÇ@Üæïð"  )½Æ£ÇÉñù˓ú ܣƨÀ1͟ïÊÎÁ£ÇˆÆHÏcT ß ) Æ ¦HĄñèØÁˆÒIÇĉñzސÕPՄõèÞ¨© Ô 9ˆú†ü õ  ÖxÕP' Õ £ú ܣƨÀ1͟ïÊÎÁ£ÇˆÆHϟïzÜ£Æ1§ Ä Å¨Ò ¨Æ¬ñ€ Ö e3ú ܣƨÀ1͟ïÊÎÁ£ÇˆÆHϟïùÃPÌ£ۄñ‡Ü£ÆÀHÍnï–ÛÎÒIÇ@ú ¡ 3 u ¡ ¡  Ê { ³ y•iUÑn}pì {‡Š†y|{z‹ 4 é {zˆíì HŠ ® !h ¬ í You should compare this code to Figure ï¤ð . . a variable. Getting them all set up and initialized is often the most . I hope you noticed that I pushed the creation of the dice and their associated buttons into a couple of helper methods. ð to make sure you understand how the elements of the interface are created and positioned. ÓpÔ †§ˆ} Ô })c„3…‡°„X‰C} Ó ©„8})zp€©‹„3…ŒŠm You might be a little scared at this point that the constructor for our GUI interface was so complex. is used to calculate the correct position of the next widget. In both cases.

provided we attack it one piece at a time. making it functional is not overly difficult. These two methods display some text in our interface window. Since our constructor ) Æ ¦HÄ took care of creating and positioning the relevant objects. ۈÂÓǨ© Ä Á1؈ÀPÂ1Ï The method will wait for the user to click either “Roll Dice” or ÑIŽÁPÁ½Ü£Æ “Quit. It sets the ith die to show the ith value. As you can see.~zrH ”H1s½uŒˆ–{ x ˜ yè…v‹‡ç ´{é·ì ³ {qH‚QÒè{‡} ¯ ~†´ tedious part of coding the interface. actually writing the code that handles the interaction will not be too hard. Now that we have that part out of the way. once the interface has been constructed. this method then clears ʆÜ! out any message—such as the previous results—by setting the text to the . all our methods Ü£Æ1© Ä ¨) Æ ¦PÄ have to do is call the methods for the appropriate objects. èÆHÍcÛ½ÂÓǨ© Ä ¨ÁH؈ÀPÂ1ωñ‡Ü£ÆÀHÍ3ú¬÷ ÂÓÇ@Ü ßÿÜÓƨÀ1͟ïôÑIŽÁPÁ½Ü£Æ¬ñ û 3 ˆÁÀÀ ÎÒPÑ1B Æ Χ õ  ÓÉ4Òx# Ä XÎú ܣƨÀ1͟ïÊ†" Ü !nïzÜÓÆH© Ä ¨) Æ ¦HĄñ )£ú ÌÆHÄ1ÉÌ1Ç¡ÂÓÇ4Ü ßA ß 3 Á¨ÀPÀ ÎÒPÑ1' Æ  ® h  After waiting for the user to click an appropriate button. We can do this ͨÁ1Ì with a loop. èÆHÍÿÜ£ÆHÄ ÎÒPÑ1ÆæñvܣƐÀHÍoõ WˆÂPÀÓɈƽܨú­÷ ͨÁHÌÿÒWÒIÇÐ̈Âx§ Ç !¨Æ¬3 ñ 9ˆú¬÷ ÜÓƨÀ1͟ïùÃˆÒÑ£Æ û " Ò ŸïôÜ£ÆH) Ä ÛˆÂPÀÓÉ½Æ¬Ò ñ W¨ÂÀxɽÆÜ û Ò"3ú € u Take a good look at the line in the loop body. Our output methods are completed with just a few lines of code. èÆHÍÿÜ£ÆHÄHöˆÁÓǽÆHωñ‡ÜÓƨÀḦ́õ¢ÂIʽÄÎú¬÷ ܣƨÀ1͟ïÊÎÁ£ÇˆÆHϟïzÜ£Æ1© Ä ¨) Æ ¦Pĉñ  ' à  ñ†ÂIʽÄÎúú èÆHÍÿÜIŽÁ£Û© ƽÜIɽÀ1ĉñ‡Ü£ÆÀḦ́õŽÊ“Ü"!„õÜPÑ1Á1Ìƽú¬÷ Ò£ÍÿÜPÑ£ÁHÌ¨Æ ( Õn÷ Ĩ) Æ ¦HÄW& ß  3 Ü  ÁÓÉÝÛÎÒIÇ ' à  ñpʓÜ"!oõÜHÑ1Á1ÌÆ3ú ƨÀˆÜÓÆn÷ Ĩ) Æ ¦HÄW& ß  ÁÓÉÝÌÁÀÀHÆPà 3m Ü  ©ñpʓÜ"!Îú ܣƨÀ1͟ïÊ†" Ü !nïzÜÓÆH© Ä ¨) Æ ¦HĄñ–Ĩ) Æ ¦HÄ4ú ¬ " " R" “ ¬ " ¯" G“ " ­"  ÜÓÆHÄ 3ÒÑ£Æ In a similar spirit. Ü£ÆHÄHöˆÁÓǽÆHÏ ÜIňÁ1Û) ˆÆ½Ü‡É3À£Ä Let’s start with the simple output methods and .” We can use our helper method to do this. the output method must make a call to the Ü£Æ1ĩېÀÓÉˆÆ 3Ò1ÆgÛ½Ò1Æ£Û ÃˆÒÑ1Æ method of the approriate objects in . The input methods are only slightly more complicated.

the function returns an empty list to signal that the player is done rolling. The comments in this code explain the algorithm: 3 3  ÐÆPÍ¡ÑIŽÁÁˆÜ£Æ ÎҐѣÆæñvܣƨÀ1ÍÎú­÷ ó¡ÑIŽÁˆÒPÑ1ƈÜcÒ¨ÜUÂÝÀҐÜxÄÝÁH̀ÄHňÆàҀLjÐÆ)¦Æ½Ü ÁH̀ÄHŽơÜÓƨÀHƈÑÓĨÆPÃ€ÃˆÒÑ£Æ ÑIŽÁˆÒPÑ1ÆˆÜ ß û  ó ШÁ€Ã½ÒÑ£ÆÐрňÁ½ÜÓÆ£ÇÐÏÆ1Ä ¥ ÛHÅ4ÒHÀH£ Æ Ì1ɽÆo÷ óc۽¨ÒÓÄÝ͐ÁHÌcÉ@ÜÓÆH̀ĨÁàÑHÀ¨Ò Ñ Î¡£  WÀ¨Ò£ÃUːɨĐĨÁ£Ç û ËàßÿܣƐÀHÍnïôрňÁÁˆÜ£Ææñ  ÎÒ1ÆЧ Ö 3§ õ  3Ò1Æݕ Ô Îè õ  3Ò1ÆWB Þ Îè õ  3Ò1E Æ d'Îõè ÎÒ1Æ 9•Îõ 3 Á¨ÀÀ ÎҐѣ' Æ 3§ õ qŨÑ1ÁH̨' Æ XÎú Ò£ÍUË û Õg€ßß& #@÷ ócÙ4Ü£ÆHÌàÑHÀÒPÑÎÆPÃÝÂ€Ã½Ò£Æ ËÉ¨ÄÄ¨Á£Ç ÒUßÝÆgWÀ¬ñùË û d©Îú§¨ Ö ó¥P̈ÂÓÇ4Ü1ÀPÂ1ÄÆcÀÂx˽ƨÀ ÄÁ€Ã½Ò£ÆàҀÇèÆ)¦ Ò£ÍÿÒWÒIÇ Ñ€Å½ÁҐѣƽÜæ÷ óÐ×ÓĘ́̐ƣǨĈÀ1ÏàܣƐÀPƈÑxÄÆHÃoõ ÉPÇ@ÜÓƨÀPÆÑÓÄ¡ÒxÄ Ñ€ÅˆÁˆÒÑ£Æ½Ü¬ïpÌƀÊÎ Á WÆæñŒÒú ܣƐÀH͟ïpýÒPÑ1Æ û Ò nïzÜ£Æ1Ä×PÁ¨ÀPÁ1̄ñ"zË3ÀP¨ÑÎxxú ƨÀÜ£Æo÷ óÐ×ÓĘ́̐ƣǨĈÀ1Ï ÉÇ4ܣƨÀHƈÑxÄÆPÄõÜÓƨÀPÆÑÓÄ¡ÒxÄ Ñ€ÅˆÁˆÒÑ£Æ½Ü¬ïè"  )½ÆÓLjÉñŒÒú ܣƐÀH͟ïpýÒPÑ1Æ û Ò nïzÜ£Æ1Ä×PÁ¨ÀPÁ1̄" ñ ž!PÌ£6 Ï £ú ƨÀÜ£Æo÷ ócÙ4Ü£ÆHÌàÑHÀÒP Ñ ÎÆP£ à  Á¨ÀÀ€Á1@ Ì ÅÑ£ÁHÌÆ Í¨Á1ÌÝÃÿҀǻܣƐÀHÍnïùýÒPÑ1Æo÷ ó  g T Æ WÆ1̐ÄÐ  ©ˆÆ¨Â1ÌÂÓÇÎÑ1ÆcÁHÍАÀPÀcÃ½ÒÑ£Æ ÃŸïôÜ£ÆHĨאÁÀPÁH̉ñ ôË3ÀÂ¨ Ñ Î#£ú Ò£ÍcËàßPA ß qÅÑ£ÁH̨' Æ @÷ ó ŨÑ1ÁH̨ÆÐÑHÀ¨Ò @ Ñ ÎˆÆPÄõÒ !£Ç½Á1ÌÆÐÑIŽÁˆÒPÑ1ÆˆÜ ÌÆ1ÄHÉÌ1Ç û  ƨÀ¨Ò£Í¡ÑIŽÁˆÒPÑ1ƈ³ Ü pß û Ÿ÷ ó Á£Ç ùÄÐÂÑPÑ1" Æ E Ä  Á¨ÀÀ ÉPÇ3ÀHƽܐÜcÜ£ÁxÊ3Æ !  r Å    r # ‘ . The method then returns a Boolean value by examining the label ÑIŽÁPÁ½Ü£Æ returned by . The interaction ends when the user clicks either the roll button or the score button. the user will choose dice by clicking on corresponding buttons. the color of the 3Ò1g Æ Û½Ò1Æ£Û corresponding reflects the status of the die. that die is either chosen (its index is appended to the list) or unchosen (its index is removed from the list).¯ ~†¹ s@tŒuxw†y|{‡}†~†rH˜Ñ  Ê { ³ y•iUÑn}pì {‡Š†y|{z‹ 4 é {zˆíì HŠ empty string. Each time a die button is clicked. We need to maintain a list of which dice have been chosen. Here we must implement a more рňÁÁ½ÜÓÆ 3ҐÑ1Æ extensive user interaction. In our GUI. In addition. рŽÁPÁ½ÜÓÆ ÎÒPÑ1Æ That brings us to the method. If the roll button is clicked. Here is one way to implement the choosing of dice. the method returns the list of currently chosen indexes. If the score button is clicked. The method returns a list of the indexes of the dice that the user wishes to roll.

not by reading about mine. ҀǨÄÆ1ÌWß ü ̈  ÅÎҐѨ) Ü ¢IǨÄÆH̐ͨÑ1Ææñ‡ú  )à߀ØÁ ΈÆHÌ Ú )nñvÒIÇĨÆHÌ4ú "  )„ï–ÌHɐÇoñIú " We now have a complete. and detour along the way. and keeping track of high scores. Basically. I have tried to keep this example relatively simple. Have fun with them! “o•«”|µ xWx  ¢™£eŸƒ¬‚Ÿ¤n…‘ My goal for the racquetball and video poker case studies was to give you a taste for what OOD is all about. false start. these smallish examples illustrate much of the power and allure of the object-oriented approach. while still illustrating important issues in the design of GUIs using objects. Still.~zrH ¯ Ñ Ñ sˆ‚1Š ³ {Iwzy|ˆ ó ÈҐÑ1ÆÝ£ÌÆݨÑÓÄHɽÀPÀ1Ï¡ÜÓƨÀHƈÑÓĨÆPà ¯ ~†¿ ÌÆ1ÄHÉÌ1Ç Ñ€ÅˆÁˆÒPÑ1Æ½Ü That about wraps up our program. Doing so would have at least tripled the size of this (already long) chapter. To close up the graphical version. The bottom line is that the OO approach helps us to produce complex software that is more reliable and cost-effective. we need a few lines to actually get our graphical poker playing program started. you can see why OO techniques are becoming standard practice in software development. Improvements are left as exercises for you. what you’ve seen is only a distillation of the design process for these two programs. we just need to close the graphics window. You will learn best by making your own decisions and discovering your own mistakes. I have walked you through the algorithms and rationale for two completed designs. ü Ì"  PÅ4Ґѐ© Ü ¢‡ÇÄÆ1̨ͨÂÑ1Æ g Æ ¦P% Ä ¢IÇĨÆH̐ÍÂÑ£Æ except that we use a in place of the . our game is lacking a lot of bells and whistles such as printing a nice introduction. èÆHÍ¡ÑHÀPÁˆÜ£Æ¬ñ‡Ü£ÆÀHÍ3ú¬÷ ܣƨÀ1͟ï|ÛÎҀÇhïôÑ1ÀPÁ½ÜÓÆæñ‡ú Finally. I still have not defined exactly what counts as objectedoriented development. Of course. useable video dice poker game. I did not document every single decision. . providing help with the rules. Actually. This code is exactly like the start code for the textual version. However. The only missing piece of our interface ÑHÀPÁˆÜ£Æ class is the method. Hopefully.

cars. . especially ones that are subject to change. but as long as the interface is preserved. and inheritance. It provides a convenient way to compose complex problems that corresponds to our intuitive view of how the world works. the word polymorphism means “many forms. It allows us to package up general components that can be used from one program to ÎÒ£g Æ Û½Ò1Æ1Û 1ÉĐĨÁ£Ç class and classes are good examples of reusable the next. Each object has its own identity. not a swarming mass of countless molecules or atoms.¯ ~†â s@tŒuxw†y|{‡}†~†rH˜Ñ  Ê { ³ y•iUÑn}pì {‡Š†y|{z‹ 4 é {zˆíì HŠ Most OO gurus talk about three features that together make development truly object-oriented: encapsulation. From a design standpoint. “how. and trees. encapsulation also provides a critical service of separating the concerns of “what” vs. ÊmÇÈ ™ ÈƒÊ šdwQœ©–BÍQs r•ÙŒ–mtqlnvxw I have already mentioned the term encapsulation in previous discussion of objects.” When used in objectoriented literature. I look out my window and I see houses. the approach must also have the characteristics of polymorphism and inheritance.   ÊmÇÈ ™ È‘Ç ’dv6Ù Q—îvB“8Í Qlns— ¤   Literally. and knowing what kind of object it is allows us to understand its nature and capabilities. This process of packaging some data along with the set of operations that can be performed on the data is called encapsulation. The implementation can change. but your introduction to object-oriented design and programming would not be complete without at least some understanding of what is meant by these terms. They combine data and operations. Encapsulation allows us to isolate major design decisions.” The actual implementation of an object is independent of its use. We naturally think of the world around us as consisting of interacting objects. The components. this refers to the fact that what an object does in response to a message (a method call) depends on the type or class of the object. objects know stuff and do stuff. polymorphism. I don’t want to belabor these concepts too much. but alone it only makes a system object-based. Another advantage of encapsulation is that it supports code reuse. As you know. other components that rely on the object will not break. Encapsulation is probably the chief benefit of using objects. Encapsulation is one of the major attractions of using objects. To be truly objected-oriented.

and the existing class (the one being borrowed from) is its superclass. is one that we have not yet used. When ï is a ÃP̈ÂÓÛ rectangle. each subclass would have its own function. what operation does this loop actually execute? When ï ÃPÌÂ£Û ÁÓË is a circle. The new class (the one doing the borrowing) is called a subclass. Inheritance provides two benefits. the showed the dice one way and the did it another way.~zrH ¯ Ñ Ñ sˆ‚1Š ³ {Iwzy|ˆ ¯ ~†é ب Á ΈÆ1Ì Ú © Our poker program illustrated one aspect of polymorphism. ÊmÇÈ ï ™ È‘É äUw %i•“¡lŒtu–BwQœ©i   The third important property for object-oriented approaches. . etc. it executes the method from the circle class. it is the method from the rectangle class. if we are building a system to keep track of employees. and the class could function ØÁ ΈÆ1Ì Ú ) ÜIňÁ1Û ÎÒÑ£Æ quite well with either. since pay is computed differently for these different classes of employees. G G Ê ½ÀPÁHÏ¨ÆÆ C We could make these subclasses of G . When the called the method. however. In our poker example. this kind of flexibility was much harder to achieve. etc. You could draw all the items in a list with this simple code: ͨÁ1ÌÐÁ£Ë ҀǡÁ£Ë ÆÑÓÄÎܬ÷ ï ï Á£Ë ïùÃḦÂÓÛoñèÛ3ҀÇ@ú € ÁÓË Now ask yourself. The ü ̈ÅÎҐѨÜ)¢IǨÄÆH̐ͨÑ1Æ ¨Æ)¦HÄQ¢IǨÄÆ1̨ͨÑ1Æ class was used both with a and a . Polymorphism gives object-oriented systems the flexibility for each object to perform an action just the way that it should be performed for that object. . One example attribute would be a method that returns the home address of an employee. However. we used either the text interface or the graphics interface. suppose you had a list of graphics objects to draw ×ÒÓÌ3Ñ1ÀPÆ  ƈÑÓÄÂÓC Ç !ÀPÆ Ø¨Á¨À£c Ï !¨ÁÓÇ on the screen. inheritance. There ØÁ ΈÆHÌ Ú ) were two different forms of interface. we might distinguish between and . The remarkable thing about polymorphism. The idea behind inheritance is that a new class can be defined to borrow behavior from another class. The list might contain a mixture of . As a simple example. so they would share methods like ŽÁ€ÊÎÆ Ú ÃÃHÌÆˆÜÜ ÊÎÁ£Ç¨ÄHŽÀ1ϐØÂ1Ï . is that a given line in a program may invoke a completely different method from one moment to the next. We don’t have to write a separate . Before object orientation. Within the class of all employÅPÀÂ£Ì3Ò£ÆPà C Ê ½ÀPÁHÏ¨ÆÆ ¢ˆÁÓÉÌÀ1Ï C Ê ½ÀPÁHÏ¨ÆÆ ees. we Ê 3ÀHÁHÏ¨ÆÆ C might have a class G that contains the general information that is comŽÁ€ÊÎÆ Ú ÃÃHÌÆˆÜÜ mon to all employees. For example. One is that we can structure the classes of a system to avoid duplication of operations. for exü ̈Å4ÒPѨÜ)¢IÇĨÆH̐ÍÂÑ£Æ ¨) Æ ¦P% Ä ¢IǨÄÆH̐ͨÑ1Æ ample.

we also need to modify the operation slightly. Here is how it would look in Python: ÑHÀPˆÜPÜ ×ÁÀPÁHÌ ÎÒ£g Æ Û3Ò£Æ1ۄñ ÎÒ£g Æ Û½Ò1Æ1Û4ú¬÷  € €  u w èÆHÍÿÜ£ÆHÄ)ۈÂPÀÓɽƬñ‡ÜÓƨÀḦ́õIWÀxɽÆ3ú­÷ ܣƨÀ1͟s ï WˆÂÀxɽÆÈT ß WˆÂÀxÉ½Æ ÎÒ1 Æ Û3Ò£Æ1ÛhïôÜ£Æ1© Ä ÛˆÂPÀÓɈÆæñ‡ÜÓƨÀ1Íoõ ˆ W ÂPÀÓɈÆ3ú  èÆHÍÿÜ£ÆHĨאÁÀPÁH̉ñ‡ÜÓƨÀḦ́õ Ñ£Á¨ÀHÁHÌ4ú­÷ ܣƨÀ1͟ïpͨÁH̨) Æ !HÌÁ£ÉPLjà ßÿÑ1ÁÀPÁHÌ Ü£Æ¨À1͟ïôÜ£ÆH) Ä ÛˆÂPÀÓɽƬñ‡ÜÓƨÀHÍnïpWÀÓɈƽú ×PÁ¨ÀPÁ1Ì 3Ò1g Æ Û½Ò1Æ£Û The first line of this definition says that we are defining a new class ÎÒ1ÆÛ3Ò£Æ1Û that is based on (i. a subclass of) . Notice especially how the call to the method from the superclass is made. promoting code reuse. we define two Ü£Æ1Ä×PÁ¨ÀPÁ1Ì methods. it did not provide a way of changing the appearance of the die. in ÜÓÆHĨאÁ¨ÀHÁHÌ Ü£Æ1© Ä ÛÀÓÉˆÆ order to make work. adds the new operation. The method in Ü£Æ1© Ä ÛˆÂPÀÓÉˆÆ the new class first stores the value and then relies on the method 3Ò1 Æ Û3Ò1Æ£Û of the superclass to actually draw the pips. We solved this problem by modifying the original class definition.e. ÎÒ£g Æ Û½Ò1Æ1ۙïzÜÓÆH© Ä ÛÀxɽÆæñvܣƐÀHÍof õ WˆÂHÀÓɈÆ3ú  €  €  € €  The actual object to which the method is applied is then sent as the first parameter. When we first 3Ò1g Æ Û½Ò1Æ£Û wrote the class.A is just like a except that it contains an additional method that allows us to change its color. Inside the new class. Of course. A closely related benefit is that new classes can often be based on existing classes. . An alternative would have been to leave the original class unchanged and create a ×PÁ¨ÀPÁ1Ì 3Ò1g Æ Û½Ò1Æ£Û ×PÁ¨ÀHÁHÌ 3Ò1 Æ Û3Ò1Æ£Û ÎÒ1 Æ Û3Ò£Æ1Û new subclass .¯ r7 ŽÁ€ÊÎÆ Ú ÃÃHÌÆˆÜÜ s@tŒuxw†y|{‡}†~†rH˜Ñ  Ê { ³ y•iUÑn}pì {‡Š†y|{z‹ 4 é {zˆíì HŠ ¢ˆÁÓÉ̈À£Ï ÊC3ÀHÁHÏ¨ÆÆ ÅÂÀPÂ1̽Ò1ÆPà Êc3ÀPÁ1ÏÆPÆ method for the G and G classes. We could have used inheritance to build our poker program. The second method. Ü£Æ1© Ä ÛÀÓÉˆÆ ×PÁ¨ÀPÁ1Ì 3Ò1g Æ Û½Ò1Æ£Û The method in redefines or overrides the definition Ü£ÆH) Ä ÛˆÂPÀÓÉ½Æ ÎÒ£g Æ Û½Ò1Æ1Û Ü£ÆH) Ä ÛˆÂPÀÓÉ½Æ of that was provided in the class. In order to call the original Ü£Æ1© Ä ÛÀÓÉˆÆ method from the superclass. since is an instance of . it is necessary to put the class name where the object would normally go.. The normal approach ܣƐÀHÍnïzÜ£Æ1© Ä ÛÀÓɈÆæ¡ ñ WˆÂÀxɽƽú ÜÓÆH© Ä ÛÀxÉ½Æ ×ÁÀPÁ1Ì ÎÒ£g Æ Û½Ò1Æ1Û would refer to the method of the ÜÓƨÀHÍ ×PÁ¨ÀPÁ1Ì 3Ò1g Æ Û½Ò1Æ£Û class. .

Design iteratively. It is similar to top-down design in that the goal is to develop a set of black boxes and associated interfaces. Identify instance variables. 4. OOD looks for objects.~†rH ´HHs@tŒuxw†y|{‡}%˜¨…€ƒ„ƒŸu‡}‘ç “o•«”|º  ˜Ÿi„¤n…‚™g © ¦§› › ingIí ¯ rH~ This chapter has not introduced very much in the way of new technical content. ’ In developing programs with sophisticated user interfaces. This supports sharing of methods among classes and code reuse. 2. This allows for modular design of complex programs. 6. Keep it simple. ’ There are many different ways to do OOD. 3. 7. ’ There are three fundamental principles that make software object oriented: Encapsulation Separating the implementation details of an object from how the object is used. Refine nontrivial methods. Try out alternatives. Some intuitive guidelines can help: 1. Think about interfaces. Rather it has illustrated the process of object-oriented design through the racquetball simulation and dice poker case studies. it’s useful to separate the program into model and view components. Inheritance A new class can be derived from an existing class. 5.g. This makes programs more flexible. The key ideas of OOD are summarized here: ’ Object-oriented design (OOD) is the process of developing a set of classes to solve a problem. allowing a single line of code to call different methods in different situations. Where top-down design looks for functions. . The best way to learn is by doing it. text and GUI interfaces). One advantage of this approach is that it allows the program to sport multiple looks (e. Polymorphism Different classes may implement methods with the same signature.. Look for object candidates.

Candidate objects can be found by looking at the verbs in a problem description. The method is defined in which class? ÅÒv• Ê Å1ÄÂ1Ä3Ü   ˆÂÀPÀ ü €ÊÎÆ ØˆÀÂ£ÏÆ1Ì Ø Á ÎÆHÌ Ú © a) b) c) d) g g g 4. 8. 5. Which of the following is not one of the fundamental characteristics of object-oriented design/programming? a) inheritance b) polymorphism c) generality d) encapsulation 5. Typically. Hiding the details of an object in a class definition is called instantiation. a) abstract b) object-oriented c) model-theoretic d) model-view . 3.” 7. A superclass inherits behaviors from its subclasses. GUIs are generally easier to write than text-based interfaces. GUIs are often built with a model-view architecture. Polymorphism literally means “many changes. Object-oriented design is the process of finding and defining a useful set of functions for solving a problem. ƒ |§„3…‡†§ˆ}Iˆj‰cŠ§…Œ‹"} 1. What is the data type of in an ? ØÀÂ£ÏÆHÌ Å҇Q Ê Å1ÄÂ1ÄÎÜ a) int b) c) bool d) Ò¨Ü Ä W¨ÆHÌ 3. 6. 4.¯ r€r “o•«”–ê egf„‚hgIƒ¬‡‘‚„‘ s@tŒuxw†y|{‡}†~†rH˜Ñ  Ê { ³ y•iUÑn}pì {‡Š†y|{z‹ 4 é {zˆíì HŠ hjiCkmlniCoqpIrQi§sutqlnvxw%s y{zH|c})~Q©€cˆ‚3} 1. 2. Separating the user interface from the “guts” of an application is called a(n) approach. Which of the following was not a class in the racquetball simulation? ؈ÀPÂ1ÏÆ1Ì Å¨Ò‡Ê•Å£ÄˆÂ£ÄÎÜ   ˆÂÀPÀ ü €ÊÎÆ ÅÑ1Á1ÌÆ a) b) c) d) Ü£Æ1© Ì W¨ÆHÌ   ˆÂÀPÀ ü €ÊÎÆ 2. the design process involves considerable trial-and-error.

he/she is invited to type in a name for the list. (c) Add a high score feature. When the program first fires up. company. For each attendee. The high-scores list will have to be stored in a file so that it persists between program invocations. Each user will have access to a checking account and a savings . Using the ideas from this chapter. In your own words. describe the process of OOD. Your program should allow users to do things such as add a new attendee. list the name and email addresses of all attendees. 4.” The main interface shouldn’t appear unless the user selects “Let’s Play. polymorphism. 2. In your own words. The user id will be used to look up the info for the user’s accounts (including the PIN to see if it matches what the user types). and email address. See the programming exercises from Chapter 9 for some ideas. Write a program that simulates an Automatic Teller Machine (ATM). ’”“fv••“H–B—$—˜l™wm•Sš#›§i•“¡œ©lnsi§s 1. have it print a short introductory message about the program and buttons for “Let’s Play” and “Exit. 2. Write a program to keep track of conference attendees. implement a simulation of another racquet game. When a user quits with a good enough score. The attendee list should be stored in a file and loaded when the program starts. Since you probably don’t have access to a card reader. Modify the Dice Poker program from this chapter to include any or all of the following features: (a) Splash Screen. delete an attendee. your program should keep track of name. and list the name and email address of all attendees from a given state. and inheritance.~†rH ¹HcŽŒ{I} ³ ì – ˆ {zˆ  …Œ‚3‹|c‚8‚X…ŒŠm ¯ r€” 1. The program should keep track of the 10 best scores. have the initial screen ask for user id and a PIN.” (b) Add a help button that pops up another window displaying the rules of the game (the payoffs table is the most important part). 3. display info on an attendee. The list should be printed in the splash screen when the program first runs. define encapsulation. state.

withdraw cash. and gives opening bids. and Crazy Eights. Greed. Write a program that deals four bridge hands. Find the rules to an interesting dice game and write an interactive program to play it. and transfer money between accounts. The user account information should be stored in a file when the program terminates. Battleship. 5. Sorry!. and Parcheesi. Some examples are Othello(Reversi). counts how many points they have. and Skunk. The user should able to check balances. Some possibilities are War. Design your interface to be similar to what you see on your local ATM. Connect Four. This file is read in again when the program restarts. 7. Some examples are Craps.¯ r ¯ s@tŒuxw†y|{‡}†~†rH˜Ñ  Ê { ³ y•iUÑn}pì {‡Š†y|{z‹ 4 é {zˆíì HŠ account. Blackjack. Find a simple card game that you like and implement an interactive program to play that game. You will probably need to consult a beginner’s guide to bridge to help you out. Write an interactive program for a board game. Yacht. 8. various solitaire games. . 6.

you are ready to start considering some broader issues in the field. To understand sorting in depth and know the algorithms for selection sort and merge sort. Way back in Chapter 1.ñóò¹ôèõ»öb÷³ø ù»ú û üýÿþ ¡ £¢¥¤§¦©¨  ¢    "!#$ %¢ & Iý þ ')(10¥2436587@9424A B B B B B To understand basic techniques for analyzing the efficiency of algorithms. If you have worked your way through to this point in the book. To appreciate how the analysis of algorithms can demonstrate that some problems are intractable and others are unsolvable. you’ll get a glimpse of recursion. Along the way. Now that you have some programming skills. you are well on the way to becoming a programmer. a particularly powerful way of thinking about algorithms. To know what searching is and understand the algorithms for linear and binary search. namely the design and analysis of algorithms. I discussed the relationship between programming and the study of computer science. Here we will take up one of the central issues. CEDGF . To understand the basic principles of recursive definitions and functions and be able to write simple recursive functions.

a program that maintains the membership list for a club might need to look up the information about a particular member.HPIPQ R SVUXW`Ybadc6e`fEgihqp rPstcvu YwSXx€yTa‚ƒu rE„…UX„‡†‰ˆa‚‘d’Pc“ƒu sE„ T ”–•˜—™” d˜24egfh34ij7lkgm Let’s begin by considering a very common and well-studied programming problem: searching. we can test to see if a value appears in a sequence using . let’s boil the problem down to its essence. You may recall from our discussion of list operations that Python actually provides a number of built-in search-related methods. In the second example. the function returns the index where appears in the list. ‘E’‰“G›”¥¥•1Ÿ6 –h—g ™ ˜ – ™ œ š ž › E  s Ÿ ‘ “ Ž   ¡ “) £‘“¤ ”¦ ¥‘£‘¯8“X¨p §©“ž¨ž£X§1 ’¤£G›¨G¥›° Ÿ«ª8£h›± E•…§E“ ”t¦ ›8© ™‰ £²ž“¤ ”•«›) EŸ‘™¦ ªp¨« ¥•––h«•…“³¨E•µ´1¶€£t’ ¥  E § «  ¥ • ­ › ® “ ¥ § p — §  p — ‘ ¥ ‘ £ P “ € § 8 — E  ¢¢€¬ ™·£‘“€›8¨E§‰£h›±§E—p¦¥‘£‘“P§¹¸ ¢ ”¥•1–h—g˜™»–š¦¼l½4š|¶­š¾»–šÀ¿xšÂÁ¥Ã…  ¿ººžº “G“G ”¥•1–h—g˜ÅÄ4š¦¼l½4š|¶­š¾»–šÀ¿xšÂÁ¥Ã…  ´1 ¶ ººžº ´1¶ Ä» £h› £G’©™‰£h›© ›E“GŸs ‘¨‰ ¨PŸ…“q¥¡ §E—T£h›8Æ ¢ ™ £h›8ž™ › ¥ Ÿ6 “ Çv ¼Œ½x šd¶­ šw»– š™¿xš™ÁEà  › ¥  6 Ÿ q “ ™ ¸ P £ « › ‘  ž  q ™ Å ˜ 1 »   º º ¿ººž ºžº in a list. Here is the specification of a simple searching function: Here are a couple interactive examples that illustrate its behavior: In the first example. If we want to know the position of nicely. the return value indicates that is not in the list. npoqqrnsqrn tvuxwzy|{T}~€ux~81‚ƒƒp„…wz†p‡‰ˆŠ‚Œ‹ŽT}~Ty To make the discussion of searching algorithms as simple as possible. For example. the method fills the bill . This involves some form of search process. For example. Searching is the process of looking for a particular value in a collection.

This strategy is called a linear search. you would simply scan down the list comparing each value to 13. As soon as we encounter a value that is greater than ‘E’‰’‘“G ¥ ” 1 • h – g — ™ ˜ – ™ œ š ž › E  s Ÿ ‘ “ Ž   ¡ ¨¥•‰£G£© •8”X“q›8¼™Æ£Gq ˜`ǐ¥EÇ© G›–™Ó ˜ƒ›¡ ¥Ÿ6“  Ž£X¡ §«XŸ‰’¨Gž›8–šÔ•«E§¥«•¥›¦§E—8µ£P›8ž™€Õ«”¥Xp ’¤£P›± ›¥•‘Ÿ6 € à E  ¥ § «  E • ‰ › £ ¢ ¥E¨¨G¯µ’8£P›…£‘“h—8ž4šÀ£t§‘XŸµ²8”8“€›p¨¥§·£P›°¥‘£‘“X§ •«¥§E«•¥›·´1¶ ¢ £P› £h›8ž™ . using by simply catching the exception and We could implement returning -1 for that case. however. Suppose that I gave you a page full of numbers in no particular order and asked whether the number 13 is in the list. you quit and tell me that you found it. How would you solve this problem? If you are like most people. the only difference between our function and is that the latter raises an exception if the target value does not appear in the list. then you tell me it’s not there. This algorithm was not hard to develop. we might want to organize it in some way so that we don’t have to look at every single item to determine where. a particular value appears in the list. When you see 13 in the list. You are searching through the list of items one by one until the target value is found. This algorithm translates directly into simple code. The real issue is how does Python actually search the list? What is the algorithm? npoqqrnsqvÌ uŽÍt‚ƒ8Íd~«‡sΧnsÏÑÐ1wz†1~pp‚Òuq~pp‚wƒp„ Let’s try our hand at developing a search algorithm using a simple “be the computer” strategy. this algorithm is as good as any. Suppose that the list is stored in sorted order (lowest to highest). For an unordered list. The Python and operations both implement linear searching algorithms. or if.In fact. If we have a very large collection of da