Python Programming Problems

python programming problems

 

ONLINE ACCESS

Thank you for purchasing a new copy of Introduction to Programming Using Python. Your textbook includes six months of prepaid access to the book’s Companion Website. This prepaid subscription provides you with full access to the following student support areas:

ming concepts presented in this textbook.

Use a coin to scratch off the coating and reveal your student access code. Do not use a knife or other sharp object as it may damage the code.

To access the Introduction to Programming Using Python Companion Website for the

a web browser. The process takes just a couple of minutes and only needs to be completed once.

1. Go to http://www.pearsonhighered.com/liang

2. Click on Companion Website.

3. Click on the Register button.

4. *

5. Need Help? icon.

6. Introduction to Programming Using Python Companion Website!

To log in after you have registered:

time at http://www.pearsonhighered.com/liang

*

http:// www.pearsonhighered.com/liang

ALWAYS LEARNING PEARSON

Learn more at www.myprogramminglab.com

MyProgrammingLab™

Through the power of practice and immediate personalized

feedback, MyProgrammingLab improves your performance.

get with the programming

This page intentionally left blank

Boston Columbus Indianapolis New York San Francisco Upper Saddle River Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto

Delhi Mexico City Sao Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo

INTRODUCTION TO PROGRAMMING USING

PYTHON

Y. Daniel Liang Armstrong Atlantic State University

Editorial Director, ECS: Marcia Horton Editor-in-Chief: Michael Hirsch Executive Editor: Tracy Dunkelberger Associate Editor: Carole Snyder Director of Marketing: Patrice Jones Marketing Manager: Yezan Alayan Marketing Coordinator: Kathryn Ferranti Director of Production: Vince O’Brien Managing Editor: Jeff Holcomb Production Project Manager: Heather McNally Manufacturing Buyer: Lisa McDowell Art Director and Cover Designer: Anthony Gemmellaro Text Designer: Gillian Hall Cover Art: “Life Aquatic” © Arthur Xanthopoulos from Damaged Photography Media Editor: Daniel Sandin Full-Service Project Management: Gillian Hall Composition: Laserwords Printer/Binder: Edwards Brothers Cover Printer: Lehigh-Phoenix Color/Hagerstown

Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook appear on Credits page located in the end matter.

Microsoft® and Windows® are registered trademarks of the Microsoft Corporation in the U.S.A. and other coun- tries. Screen shots and icons reprinted with permission from the Microsoft Corporation. This book is not sponsored or endorsed by or affiliated with the Microsoft Corporation.

Copyright © 2013 Pearson Education, Inc., publishing as Prentice Hall. All rights reserved. Manufactured in the United States of America. This publication is protected by Copyright, and permission should be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. To obtain permission(s) to use material from this work, please submit a written request to Pearson Education, Inc., Permissions Department, One Lake Street, Upper Saddle River, New Jersey 07458, or you may fax your request to 201-236-3290.

Many of the designations by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed in initial caps or all caps.

Library of Congress Cataloging-in-Publication Data��������

10 9 8 7 6 5 4 3 2 1

ISBN 13: 978-0-13-274718-9 ISBN 10: 0-13-274718-9

This book is dedicated to my former colleagues at the National Severe Storms Laboratory,

in Norman, Oklahoma.

To Samantha, Michael, and Michelle

vi

PREFACE Dear Reader,

This book assumes that you are a new programmer with no prior knowledge of programming. So, what is programming? Programming solves problems by creating solutions—writing programs—in a programming language. The fundamentals of problem solving and programming are the same regardless of which programming language you use. You can learn programming using any high-level programming language such as Python, Java, C++, or C#. Once you know how to program in one language, it is easy to pick up other languages, because the basic tech- niques for writing programs are the same.

So what are the benefits of learning programming using Python? Python is easy to learn and fun to program. Python code is simple, short, readable, intuitive, and powerful, and thus it is effective for introducing computing and problem solving to beginners.

Beginners are motivated to learn programming so they can create graphics. A big reason for learning programming using Python is that you can start programming using graphics on day one. We use Python’s built-in Turtle graphics module in Chapters 1–6 because it is a good pedagogical tool for introducing fundamental concepts and techniques of programming. We introduce Python’s built-in Tkinter in Chapter 9, because it is a great tool for developing comprehensive graphical user interfaces and for learning object-oriented programming. Both Turtle and Tkinter are remarkably simple and easy to use. More importantly, they are valuable pedagogical tools for teaching the fundamentals of programming and object-oriented programming.

To give instructors flexibility to use this book, we cover Turtle at the end of Chapters 1–6 so they can be skipped as optional material.

The book teaches problem solving in a problem-driven way that focuses on problem solv- ing rather than syntax. We stimulate student interests in programming by using interesting examples in a broad context. While the central thread of the book is on problem solving, appropriate Python syntax and library are introduced in order to solve the problems. To sup- port the teaching of programming in a problem-driven way, the book provides a wide variety of problems at various levels of difficulty to motivate students. In order to appeal to students in all majors, the problems cover many application areas in math, science, business, financial management, gaming, animation, and multimedia.

All data in Python are objects. We introduce and use objects from Chapter 3, but defining custom classes are covered in the middle of the book starting from Chapter 7. The book focuses on fundamentals first: it introduces basic programming concepts and techniques on selections, loops, and functions before writing custom classes.

The best way to teach programming is by example, and the only way to learn programming is by doing. Basic concepts are explained by example and a large number of exercises with various levels of difficulty are provided for students to practice. Our goal is to produce a text that teaches problem solving and programming in a broad context using a wide variety of interesting examples and exercises.

Sincerely,

Y. Daniel Liang y.daniel.liang@gmail.com www.cs.armstrong.edu/liang www.pearsonhighered.com/liang

what is programming?

why Python?

graphics

optional Turtle

problem-driven

fundamentals first

examples and exercises

Preface vii

Pedagogical Features The book uses the following elements to get the most from the material:

■ Objectives list what students should learn in each chapter. This will help them determine whether they have met the objectives after completing the chapter.

■ The Introduction opens the discussion with representative problems to give the reader an overview of what to expect from the chapter.

■ Key Points highlight the important concepts covered in each section.

■ Check Points provide review questions to help students track their progress and evaluate their learning.

■ Problems, carefully chosen and presented in an easy-to-follow style, teach problem solving and programming concepts. The book uses many small, simple, and stimulating examples to demonstrate important ideas.

■ Key Terms are listed with a page number to give students a quick reference to the impor- tant terms introducd in the chapter.

■ The Chapter Summary reviews the important subjects that students should understand and remember. It helps them reinforce the key concepts they have learned in the chapter.

■ Test Questions are available online, grouped by sections for students to do self-test on programming concepts and techniques.

■ Programming Exercises are grouped by sections to provide students with opportunities to apply on their own the new skills they have learned. The level of difficulty is rated as easy (no asterisk), moderate (*), hard (**), or challenging (***). The trick of learning programming is practice, practice, and practice. To that end, the book provides a great many exercises.

■ Notes, Tips, and Cautions are inserted throughout the text to offer valuable advice and insight on important aspects of program development.

Note Provides additional information on the subject and reinforces important concepts.

Tip Teaches good programming style and practice.

Caution Helps students steer away from the pitfalls of programming errors.

Flexible Chapter Orderings Graphics is a valuable pedagogical tool for learning programming. The book uses Turtle graphics in Chapters 1–6 and Tkinter in the rest of the book. However, the book is designed to give the instructors the flexibility to skip the sections on graphics or to cover them later. The following diagram shows the chapter dependencies.

Chapter 10, Lists can be covered right after Chapter 6, Functions. Chapter 14, Tuples, Sets, and Dictionaries can be covered after Chapter 10.

viii Preface

Organization of the Book The chapters can be grouped into three parts that, taken together, form a comprehensive intro- duction to Python programming. Because knowledge is cumulative, the early chapters pro- vide the conceptual basis for understanding programming and guide students through simple examples and exercises; subsequent chapters progressively present Python programming in detail, culminating with the development of comprehensive applications.

Part I: Fundamentals of Programming (Chapters 1–6)

The first part of the book is a stepping stone, preparing you to embark on the journey of learn- ing programming. You will begin to know Python (Chapter 1) and will learn fundamental pro- gramming techniques with data types, variables, constants, assignments, expressions, operators, objects, and simple functions and string operations (Chapters 2–3), selection state- ments (Chapter 4), loops (Chapter 5), and functions (Chapter 6).

Part II: Object-Oriented Programming (Chapters 7–13)

This part introduces object-oriented programming. Python is an object-oriented programming language that uses abstraction, encapsulation, inheritance, and polymorphism to provide great flexibility, modularity, and reusability in developing software. You will learn object-oriented programming (Chapters 7–8), GUI programming using Tkinter (Chapter 9), lists (Chapter 10), multidimensional lists (Chapter 11), inheritance, polymorphism, and class design (Chapter 12), and files and exception handling (Chapter 13).

Part III: Data Structures and Algorithms (Chapters 14–15 and Bonus Chapters 16–23)

This part introduces the main subjects in a typical data structures course. Chapter 14 intro- duces Python built-in data structures: tuples, sets, and dictionaries. Chapter 15 introduces

Chapter 10 Lists

Chapter 4 Selections

Chapter 5 Loops

Chapter 1 Introduction to Computers, Programs, and Python

Chapter 2 Elementary Programming

Chapter 7 Objects and Classes

Chapter 13 Files and Exception Handling

Note: Chapters 16–23 are bonus chapters available from the Companion Website

Chapter 8 More on Strings and Special Methods

Chapter 9 GUI Programming Using Tkinter

Chapter 11 Multidimensional Lists

Chapter 12 Inheritance and Polymorphism

Chapter 14 Tuples, Sets, and Dictionaries

Chapter 15 Recursion

Chapter 16 Developing Efficient Algorithms

Chapter 17 Sorting

Chapter 18 Linked Lists, Stacks, Queues, and Priority Queues

Chapter 19 Binary Search Trees

Chapter 20 AVL Trees

Chapter 21 Hashing: Implementing Dictionaries and Sets

Chapter 22 Graphs and Applications

Chapter 23 Weighted Graphs and Applications

Part I: Fundamentals of Programming

Part II: Object-Oriented Programming

Part III: Data Structures and Algorithms

Chapter 3 Mathematical Functions, Strings, and Objects

Chapter 6 Functions

Preface ix

recursion to write functions for solving inherently recursive problems. Chapters 16–23 are bonus chapters on the Companion Website. Chapter 16 introduces measurement of algorithm efficiency and common techniques for developing efficient algorithms. Chapter 17 discusses classic sorting algorithms. You will learn how to implement linked lists, queues, and priority queues in Chapter 18. Chapter 19 presents binary search trees, and you will learn about AVL trees in Chapter 20. Chapter 21 introduces hashing, and Chapters 22 and 23 cover graph algo- rithms and applications.

Student Resource Website The Student Resource Website (www.cs.armstrong.edu/liang/py) contains the following resources:

■ Answers to review questions

■ Solutions to even-numbered programming exercises

■ Source code for the examples in the book

■ Interactive self-test questions (organized by sections for each chapter)

■ Supplements on using Python IDEs, advanced topics, etc.

■ Resource links

■ Errata

Additional Supplements The text covers the essential subjects. The supplements extend the text to introduce additional topics that might be of interest to readers. The supplements listed in this table are available from the Companion Website.

Part I. General Supplements A. Glossary B. Installing and Using Python C. Python IDLE D. Python on Eclipse E. Python on Eclipse Debugging F. Python Coding Style Guidelines

Part II. Advanced Python Topics A. Regular Expressions B. Obtaining Date and Time C. The str Class’s format Method D. Pass Arguments from Command Line E. Database Programming

Instructor Resource Website The Instructor Resource Website, accessible from www.cs.armstrong.edu/liang/py, contains the following resources:

■ Microsoft PowerPoint slides with interactive buttons to view full-color, syntax-highlighted source code and to run programs without leaving the slides.

■ Solutions to all the review questions and exercises. Students will have access to the solu- tions of even-numbered programming exercises.

■ Web-based quiz generator. (Instructors can choose chapters to generate quizzes from a large database of more than 800 questions.)

x Preface

■ Sample exams. In general, each exam has four parts:

■ Multiple-choice questions or short-answer questions

■ Correct programming errors

■ Trace programs

■ Write programs

■ Projects. In general, each project gives a description and asks students to analyze, design, and implement the project.

Some readers have requested the materials from the Instructor Resource Website. Please understand that these are for instructors only. Such requests will not be answered.

Online Practice and Assessment with MyProgrammingLab MyProgrammingLab helps students fully grasp the logic, semantics, and syntax of program- ming. Through practice exercises and immediate, personalized feedback, MyProgrammingLab improves the programming competence of beginning students who often struggle with the basic concepts and paradigms of popular high-level programming languages.

A self-study and homework tool, a MyProgrammingLab course consists of hundreds of small practice problems organized around the structure of this textbook. For students, the system automatically detects errors in the logic and syntax of their code submissions and offers targeted hints that enable students to figure out what went wrong—and why. For instructors, a comprehensive gradebook tracks correct and incorrect answers and stores the code inputted by students for review.

MyProgrammingLab is offered to users of this book in partnership with Turing’s Craft, the makers of the CodeLab interactive programming exercise system. For a full demonstration, to see feedback from instructors and students, or to get started using MyProgrammingLab in your course, visit www.myprogramminglab.com.

VideoNotes VideoNotes are Pearson’s new visual tool designed for teaching students key programming con- cepts and techniques. These short step-by-step videos demonstrate how to solve problems from design through coding. VideoNotes allow for self-placed instruction with easy navigation includ- ing the ability to select, play, rewind, fast-forward, and stop within each VideoNote exercise.

Margin icons in your textbook let you know when a VideoNote video is available for a par- ticular concept or homework problem.

LiveLab This book is accompanied by a complementary Web-based course assessment and manage- ment system for instructors. The system has four main components:

■ The Automatic Grading System can automatically grade programs.

■ The Quiz Creation/Submission/Grading System enables instructors to create and mod- ify quizzes that students can take and be graded upon automatically.

■ The Peer Evaluation System enables peer evaluations.

■ Checking plagiarisms, tracking grades, attendance, etc., lets students track their grades, and enables instructors to view the grades of all students, to check plagiarisms, and to track students’ attendance.

VideoNote

Preface xi

The main features of the Automatic Grading System include:

■ Students can run and submit exercises. (The system checks whether their program runs correctly—students can continue to run and resubmit the program before the due date.)

■ Instructors can review submissions, run programs with instructor test cases, correct them, and provide feedback to students.

■ Instructors can create/modify their own exercises, create public and secret test cases, as- sign exercises, and set due dates for the whole class or for individuals.

■ All the exercises in the text can be assigned to students. Additionally, LiveLab provides extra exercises that are not printed in the text.

■ Instructors can sort and filter all exercises and check grades (by time frame, student, and/or exercise).

■ Instructors can check plagiarisms for a programming exercise.

■ Instructors can delete students from the system.

■ Students and instructors can track grades on exercises.

The main features of the Quiz System are:

■ Instructors can create/modify quizzes from the test bank or a text file or create completely new tests online.

■ Instructors can assign the quizzes to students and set a due date and test time limit for the whole class or for individuals.

■ Students and instructors can review submitted quizzes.

■ Instructors can analyze quizzes and identify students’ weaknesses.

■ Students and instructors can track grades on quizzes.

The main features of the Peer Evaluation System include:

■ Instructors can assign/unassign exercises for peer evaluation.

■ Instructors can view peer evaluation reports.

Acknowledgments I would like to thank Armstrong Atlantic State University for enabling me to teach what I write and for supporting me in writing what I teach. Teaching is the source of inspiration for the book. I am grateful to the instructors and students who have offered comments, sugges- tions, bug reports, and praise.

This book has been greatly enhanced thanks to the outstanding reviewers. They are:

Claude Anderson – Rose-Hulman Institute of Technology Lee Cornell – Minnesota State University – Mankato John Magee – Boston University Shyamal Mitra – University of Texas – Austin Yenumula Reddy – Grambling State University David Sullivan – Boston University Hong Wang – University of Toledo

It is a great pleasure, honor, and privilege to work with Pearson. I would like to thank Tracy Dunkelberger, Marcia Horton, Michael Hirsch, Matt Goldstein, Carole Snyder, Tim Huddleston, Yez Alayan, Jeff Holcomb, Gillian Hall, Rebecca Greenberg, and their colleagues for organizing, producing, and promoting this project.

As always, I am indebted to my wife, Samantha, for her love, support, and encouragement.

BRIEF CONTENTS 1 Introduction to Computers, Programs,

and Python 1

2 Elementary Programming 31

3 Mathematical Functions, Strings, and Objects 63

4 Selections 91

5 Loops 133

6 Functions 171

7 Objects and Classes 215

8 More on Strings and Special Methods 241

9 GUI Programming Using Tkinter 271

10 Lists 313

11 Multidimensional Lists 361

12 Inheritance and Polymorphism 399

13 Files and Exception Handling 439

14 Tuples, Sets, and Dictionaries 475

15 Recursion 499

xii

Chapters 16–23 are bonus Web chapters

16 Developing Efficient Algorithms 16-1 17 Sorting 17-1 18 Linked Lists, Stacks, Queues,

and Priority Queues 18-1

19 Binary Search Trees 19-1 20 AVL Trees 20-1 21 Hashing: Implementing Dictionaries

and Sets 21-1

22 Graphs and Applications 22-1 23 Weighted Graphs and Applications 23-1

APPENDIXES A Python Keywords 533 B The ASCII Character Set 534 C Number Systems 536

INDEX 541

CREDITS 557

CONTENTS Chapter 1 Introduction to Computers, Programs,

and Python 1 1.1 Introduction 2 1.2 What Is a Computer? 2 1.3 Programming Languages 9 1.4 Operating Systems 12 1.5 The History of Python 13 1.6 Getting Started with Python 14 1.7 Programming Style and Documentation 18 1.8 Programming Errors 19 1.9 Getting Started with Graphics Programming 21

Chapter 2 Elementary Programming 31 2.1 Introduction 32 2.2 Writing a Simple Program 32 2.3 Reading Input from the Console 34 2.4 Identifiers 36 2.5 Variables, Assignment Statements, and Expressions 36 2.6 Simultaneous Assignments 38 2.7 Named Constants 39 2.8 Numeric Data Types and Operators 40 2.9 Evaluating Expressions and Operator Precedence 43

2.10 Augmented Assignment Operators 44 2.11 Type Conversions and Rounding 45 2.12 Case Study: Displaying the Current Time 46 2.13 Software Development Process 48 2.14 Case Study: Computing Distances 52

Chapter 3 Mathematical Functions, Strings, and Objects 63

3.1 Introduction 64 3.2 Common Python Functions 64 3.3 Strings and Characters 67 3.4 Case Study: Minimum Number of Coins 72 3.5 Introduction to Objects and Methods 74 3.6 Formatting Numbers and Strings 76 3.7 Drawing Various Shapes 81 3.8 Drawing with Colors and Fonts 83

xiii

Chapter 4 Selections 91 4.1 Introduction 92 4.2 Boolean Types, Values, and Expressions 92 4.3 Generating Random Numbers 93 4.4 if Statements 95 4.5 Case Study: Guessing Birthdays 96 4.6 Two-Way if-else Statements 100 4.7 Nested if and Multi-Way if-elif-else Statements 102 4.8 Common Errors in Selection Statements 105 4.9 Case Study: Computing Body Mass Index 107

4.10 Case Study: Computing Taxes 108 4.11 Logical Operators 110 4.12 Case Study: Determining Leap Years 113 4.13 Case Study: Lottery 114 4.14 Conditional Expressions 116 4.15 Operator Precedence and Associativity 117 4.16 Detecting the Location of an Object 118

Chapter 5 Loops 133 5.1 Introduction 134 5.2 The while Loop 134 5.3 The for Loop 143 5.4 Nested Loops 145 5.5 Minimizing Numerical Errors 147 5.6 Case Studies 148 5.7 Keywords break and continue 151 5.8 Case Study: Displaying Prime Numbers 154 5.9 Case Study: Random Walk 156

Chapter 6 Functions 171 6.1 Introduction 172 6.2 Defining a Function 172 6.3 Calling a Function 173 6.4 Functions with/without Return Values 176 6.5 Positional and Keyword Arguments 179 6.6 Passing Arguments by Reference Values 180 6.7 Modularizing Code 183 6.8 Case Study: Converting Decimals to Hexadecimals 185 6.9 The Scope of Variables 187

6.10 Default Arguments 189 6.11 Returning Multiple Values 190 6.12 Case Study: Generating Random ASCII Characters 191 6.13 Function Abstraction and Stepwise Refinement 192 6.14 Case Study: Reusable Graphics Functions 199

xiv Contents

Chapter 7 Objects and Classes 215 7.1 Introduction 216 7.2 Defining Classes for Objects 216 7.3 UML Class Diagrams 222 7.4 Immutable Objects vs. Mutable Objects 225 7.5 Hiding Data Fields 227 7.6 Class Abstraction and Encapsulation 229 7.7 Object-Oriented Thinking 233

Chapter 8 More on Strings and Special Methods 241 8.1 Introduction 242 8.2 The str Class 242 8.3 Case Study: Checking Palindromes 253 8.4 Case Study: Converting Hexadecimals to Decimals 254 8.5 Operator Overloading and Special Methods 257 8.6 Case Study: The Rational Class 258

Chapter 9 GUI Programming Using Tkinter 271 9.1 Introduction 272 9.2 Getting Started with Tkinter 272 9.3 Processing Events 273 9.4 The Widget Classes 275 9.5 Canvas 280 9.6 The Geometry Managers 283 9.7 Case Study: Loan Calculator 287 9.8 Displaying Images 288 9.9 Menus 290

9.10 Popup Menus 292 9.11 Mouse, Key Events, and Bindings 294 9.12 Animations 297 9.13 Scrollbars 300 9.14 Standard Dialog Boxes 301

Chapter 10 Lists 313 10.1 Introduction 314 10.2 List Basics 315 10.3 Case Study: Lotto Numbers 325 10.4 Case Study: Deck of Cards 327 10.5 Deck of Cards GUI 329 10.6 Copying Lists 330 10.7 Passing Lists to Functions 332 10.8 Returning a List from a Function 334 10.9 Case Study: Counting the Occurrences of Each Letter 335

10.10 Searching Lists 338

Contents xv

10.11 Sorting Lists 341 10.12 Case Study: Bouncing Balls 345

Chapter 11 Multidimensional Lists 361 11.1 Introduction 362 11.2 Processing Two-Dimensional Lists 362 11.3 Passing Two-Dimensional Lists to Functions 365 11.4 Problem: Grading a Multiple-Choice Test 367 11.5 Problem: Finding the Closest Pair 368 11.6 GUI: Finding the Closest Pair 370 11.7 Problem: Sudoku 372 11.8 Case Study: Sudoku GUI 375 11.9 Multidimensional Lists 377

Chapter 12 Inheritance and Polymorphism 399 12.1 Introduction 400 12.2 Superclasses and Subclasses 400 12.3 Overriding Methods 405 12.4 The object Class 406 12.5 Polymorphism and Dynamic Binding 409 12.6 The isinstance Function 411 12.7 Case Study: A Reusable Clock 414 12.8 Class Relationships 418 12.9 Case Study: Designing the Course Class 421

12.10 Designing a Class for Stacks 423 12.11 Case Study: The FigureCanvas Class 425

Chapter 13 Files and Exception Handling 439 13.1 Introduction 440 13.2 Text Input and Output 440 13.3 File Dialogs 448 13.4 Case Study: Counting Each Letter in a File 451 13.5 Retrieving Data from the Web 452 13.6 Exception Handling 454 13.7 Raising Exceptions 457 13.8 Processing Exceptions Using Exception Objects 460 13.9 Defining Custom Exception Classes 460

13.10 Binary IO Using Pickling 465 13.11 Case Study: Address Book 467

Chapter 14 Tuples, Sets, and Dictionaries 475 14.1 Introduction 476 14.2 Tuples 476 14.3 Sets 479 14.4 Comparing the Performance of Sets and Lists 485

xvi Contents

14.5 Case Study: Counting Keywords 486 14.6 Dictionaries 487 14.7 Case Study: Occurrences of Words 492

Chapter 15 Recursion 499 15.1 Introduction 500 15.2 Case Study: Computing Factorials 500 15.3 Case Study: Computing Fibonacci Numbers 503 15.4 Problem Solving Using Recursion 505 15.5 Recursive Helper Functions 507 15.6 Case Study: Finding the Directory Size 510 15.7 Case Study: Towers of Hanoi 512 15.8 Case Study: Fractals 515 15.9 Case Study: Eight Queens 518

15.10 Recursion vs. Iteration 520 15.11 Tail Recursion 521

A detailed table of contents for the Web chapters is available on the companion Website:

Chapter 16 Developing Efficient Algorithms 16–1

Chapter 17 Sorting 17–1

Chapter 18 Linked Lists, Stacks, Queues, and Priority Queues 18–1

Chapter 19 Binary Search Trees 19–1

Chapter 20 AVL Trees 20–1

Chapter 21 Hashing: Implementing Dictionaries and Sets 21–1

Chapter 22 Graphs and Applications 22-1

Chapter 23 Weighted Graphs and Applications 23-1

APPENDIXES

Appendix A Python Keywords 533 Appendix B The ASCII Character Set 534 Appendix C Number Systems 536

INDEX 541

CREDITS 557

Contents xvii

LOCATION OF VIDEONOTES IN THE TEXT

Chapter 1 Start with Python, p. 14 Start with Turtle graphics, p. 21

Chapter 2 Assignment statement, p. 37 Perform computation, p. 40

Chapter 3 String operations, p. 75 Draw shapes, p. 81

Chapter 4 Boolean expressions, p. 92 Coffee price, p. 123

Chapter 5 while loop, p. 134 for loop, p. 143

Chapter 6 Use functions, p. 172 Divide and conquer, p. 192

Chapter 7 Define and use classes, p. 217 Private data fields, p. 227

Chapter 8 String methods, p. 242 Define classes, p. 258

Chapter 9 Simple GUI, p. 273 Create GUI application, p. 287

Chapter 10 Use lists, p. 315 Search a list, p. 338

Chapter 11 Process a matrix, p. 362 Chessboard, p. 394

Chapter 12 Inheritance and polymorphism, p. 400 Dynamic binding, p. 409

Chapter 13 Process text file, p. 443 Handle exceptions, p. 454

Chapter 14 Use sets, p. 479 Use dictionaries, p. 488

Chapter 15 Function sum, p. 500 Function print numbers, p. 506

xviii Location of VideoNotes in the Text

INTRODUCTION TO COMPUTERS, PROGRAMS, AND PYTHON

Objectives ■ To demonstrate a basic understanding of computer hardware,

programs, and operating systems (§§1.2–1.4).

■ To describe the history of Python (§1.5).

■ To explain the basic syntax of a Python program (§1.6).

■ To write and run a simple Python program (§1.6).

■ To explain the importance of, and provide examples of, proper programming style and documentation (§1.7).

■ To explain the differences between syntax errors, runtime errors, and logic errors (§1.8).

■ To create a basic graphics program using Turtle (§1.9).

CHAPTER

1

2 Chapter 1 Introduction to Computers, Programs, and Python

1.1 Introduction The central theme of this book is to learn how to solve problems by writing a program.

This book is about programming. So, what is programming? The term programming means to create (or develop) software, which is also called a program. In basic terms, software contains the instructions that tell a computer—or a computerized device—what to do.

Software is all around you, even in devices that you might not think would need it. Of course, you expect to find and use software on a personal computer, but software also plays a role in running airplanes, cars, cell phones, and even toasters. On a personal computer, you use word processors to write documents, Web browsers to explore the Internet, and e-mail programs to send messages. These programs are all examples of software. Software develop- ers create software with the help of powerful tools called programming languages.

This book teaches you how to create programs by using the Python programming language. There are many programming languages, some of which are decades old. Each language was invented for a specific purpose—to build on the strengths of a previous lan- guage, for example, or to give the programmer a new and unique set of tools. Knowing that there are so many programming languages available, it would be natural for you to wonder which one is best. But, in truth, there is no “best” language. Each one has its own strengths and weaknesses. Experienced programmers know that one language might work well in some situations, whereas a different language may be more appropriate in other situations. For this reason, seasoned programmers try to master as many different programming languages as they can, giving them access to a vast arsenal of software-development tools.

If you learn to program using one language, you should find it easy to pick up other languages. The key is to learn how to solve problems using a programming approach. That is the main theme of this book.

You are about to begin an exciting journey: learning how to program. At the outset, it is helpful to review computer basics, programs, and operating systems. If you are already familiar with such terms as CPU, memory, disks, operating systems, and programming languages, you may skip the review in Sections 1.2–1.4.

1.2 What Is a Computer? A computer is an electronic device that stores and processes data.

A computer includes both hardware and software. In general, hardware comprises the visible, physical elements of the computer, and software provides the invisible instructions that control the hardware and make it perform specific tasks. Knowing computer hardware isn’t essential to learning a programming language, but it can help you better understand the effects that a program’s instructions have on the computer and its components. This section introduces com- puter hardware components and their functions.

A computer consists of the following major hardware components (Figure 1.1):

■ A central processing unit (CPU)

■ Memory (main memory)

■ Storage devices (such as disks and CDs)

■ Input devices (such as the mouse and keyboard)

■ Output devices (such as monitors and printers)

■ Communication devices (such as modems and network interface cards)

A computer’s components are interconnected by a subsystem called a bus. You can think of a bus as a sort of system of roads running among the computer’s components; data and

what is programming?

program

programming languages

hardware

software

bus

Key Point

Key Point

1.2 What Is a Computer? 3

power travel along the bus from one part of the computer to another. In personal computers, the bus is built into the computer’s motherboard, which is a circuit case that connects all of the parts of a computer together, as shown in Figure 1.2.

1.2.1 Central Processing Unit The central processing unit (CPU) is the computer’s brain. It retrieves instructions from memory and executes them. The CPU usually has two components: a control unit and an arithmetic/logic unit. The control unit controls and coordinates the actions of the other components. The arithmetic/logic unit performs numeric operations (addition, subtraction, multiplication, division) and logical operations (comparisons).

Today’s CPUs are built on small silicon semiconductor chips that contain millions of tiny electric switches, called transistors, for processing information.

Every computer has an internal clock, which emits electronic pulses at a constant rate. These pulses are used to control and synchronize the pace of operations. A higher clock speed enables more instructions to be executed in a given period of time. The unit of measurement of clock speed is the hertz (Hz), with 1 hertz equaling 1 pulse per second. In the 1990s computers measured clocked speed in megahertz, but CPU speed has been improving continuously, and

motherboard

CPU

Bus

Memory

Storage Devices

Input Devices

Output Devices

Communication Devices

FIGURE 1.1 A computer consists of a CPU, memory, storage devices, input devices, output devices, and communication devices.

CPU

speed

hertz

megahertz

4 Chapter 1 Introduction to Computers, Programs, and Python

the clock speed of a computer is now usually stated in gigahertz (GHz). Intel’s newest proces- sors run at about 3 GHz.

CPUs were originally developed with only one core. The core is the part of the processor that performs the reading and executing of instructions. In order to increase CPU processing power, chip manufacturers are now producing CPUs that contain multiple cores. A multicore CPU is a single component with two or more independent processors. Today’s consumer computers typically have two, three, and even four separate cores. Soon, CPUs with tens or even hundreds of cores will be affordable.

1.2.2 Bits and Bytes Before we discuss memory, let’s look at how information (data and programs) are stored in a computer.

A computer is really nothing more than a series of switches. Each switch exists in two states: on or off. Storing information in a computer is simply a matter of setting a sequence of switches on or off. If the switch is on, its value is 1. If the switch is off, its value is 0. These 0s and 1s are interpreted as digits in the binary number system and called bits (binary digits).

The minimum storage unit in a computer is a byte. A byte is composed of eight bits. A small number such as 3 can be stored as a single byte. To store a number that cannot fit into a single byte, the computer uses several bytes.

Data of various kinds, such as numbers and characters, are encoded as a series of bytes. As a programmer, you don’t need to worry about the encoding and decoding of data, which the computer system performs automatically, based on the encoding scheme. An encoding scheme is a set of rules that govern how a computer translates characters, numbers, and sym- bols into data the computer can actually work with. Most schemes translate each character into a predetermined string of numbers. In the popular ASCII encoding scheme, for example, the character C is represented as 01000011 in one byte.

gigahertz

core

bits

CPU is placed under the fan

Memory

Motherboard

FIGURE 1.2 The motherboard connects all parts of computer together.

byte

encoding scheme

1.2 What Is a Computer? 5

A computer’s storage capacity is measured in bytes and multiples of the byte, as follows:

■ A kilobyte (KB) is about 1,000 bytes.

■ A megabyte (MB) is about 1 million bytes.

■ A gigabyte (GB) is about 1 billion bytes.

■ A terabyte (TB) is about 1 trillion bytes.

A typical one-page word document might take 20 KB. So 1 MB can store 50 pages of doc- uments and 1 GB can store 50000 pages of documents. A typical two-hour high-resolution movie might take 8 GB. So it would require 160 GB to store 20 movies.

1.2.3 Memory A computer’s memory consists of an ordered sequence of bytes for storing programs as well as data that the program is working with. You can think of memory as the computer’s work area for executing a program. A program and its data must be moved into the computer’s memory before they can be executed by the CPU.

Every byte in the memory has a unique address, as shown in Figure 1.3. The address is used to locate the byte for storing and retrieving the data. Since the bytes in the memory can be accessed in any order, the memory is also referred to as random-access memory (RAM).

kilobyte (KB)

megabyte (MB)

gigabyte (GB)

terabyte (TB)

memory

unique address

RAM

01000011 01110010 01100101 01110111 00000011

Encoding for character ‘C’ Encoding for character ‘r’ Encoding for character ‘e’ Encoding for character ‘w’ Encoding for number 3

2000 2001 2002 2003 2004

Memory address Memory content

FIGURE 1.3 Memory stores data and program instructions in uniquely addressed memory locations. Each memory location can store one byte of data.

Today’s personal computers usually have at least 1 gigabyte of RAM, but they more com- monly have 2 to 4 GB installed. Generally speaking, the more RAM a computer has, the faster it can operate, but there are limits to this simple rule of thumb.

A memory byte is never empty, but its initial content may be meaningless to your program. The current content of a memory byte is lost whenever new information is placed in it.

Like the CPU, memory is built on silicon semiconductor chips that have millions of transistors embedded on their surface. Compared to CPU chips, memory chips are less com- plicated, slower, and less expensive.

1.2.4 Storage Devices A computer’s memory is a volatile form of data storage: any information that hasn’t been stored in memory (that is, saved) is lost when the system’s power is turned off. Programs and data are permanently stored on storage devices and are moved, when the computer actually uses them, to memory, which operates at much faster speeds than permanent storage devices can.

storage device

6 Chapter 1 Introduction to Computers, Programs, and Python

There are three main types of storage devices:

■ Magnetic disk drives

■ Optical disc drives (CD and DVD)

■ USB flash drives

Drives are devices for operating a medium, such as disks and CDs. A storage medium physi- cally stores data or program instructions. The drive reads data from the medium and/or writes data onto the medium.

Disks A computer usually has at least one hard disk drive (Figure 1.4). Hard disks are used for per- manently storing data and programs. Newer computers have hard disks that can store from 200 to 800 gigabytes of data. Hard disk drives are usually encased inside the computer, but remov- able hard disks are also available.

drive

hard disk

CD-R

CD-RW

DVD

FIGURE 1.4 A hard disk is a device for permanently storing programs and data.

CDs and DVDs CD stands for compact disc. There are two types of CD drives: CD-R and CD-RW. A CD-R is for read-only permanent storage; the user cannot modify its contents once they are recorded. A CD-RW can be used like a hard disk; that is, you can write data onto the disc, and then overwrite that data with new data. A single CD can hold up to 700 MB. Most new PCs are equipped with a CD-RW drive that can work with both CD-R and CD-RW discs.

DVD stands for digital versatile disc or digital video disc. DVDs and CDs look alike, and you can use either to store data. A DVD can hold more information than a CD; a standard DVD’s storage capacity is 4.7 GB. Like CDs, there are two types of DVDs: DVD-R (read-only) and DVD-RW (rewritable).

1.2 What Is a Computer? 7

USB Flash Drives Universal serial bus (USB) connectors allow the user to attach many kinds of peripheral devices to the computer. You can use a USB to connect a printer, digital camera, mouse, external hard disk drive, and other devices to the computer.

A USB flash drive is a device for storing and transporting data. A flash drive is small— about the size of a pack of gum, as shown in Figure 1.5. It acts like a portable hard drive that can be plugged into your computer’s USB port. USB flash drives are currently available with up to 256 GB storage capacity.

FIGURE 1.5 USB flash drives are popular portable devices for storing data.

Function

Modifier

Numeric Keypad

Page Up

Insert

Delete

Page Down

Arrows

FIGURE 1.6 A computer keyboard consists of the keys for sending input to a computer.

1.2.5 Input and Output Devices Input and output devices let the user communicate with the computer. The most common input devices are keyboards and mice. The most common output devices are monitors and printers.

The Keyboard A keyboard is a device for entering input. A typical keyboard is shown in Figure 1.6. Compact keyboards are available without a numeric keypad.

Function keys are located across the top of the keyboard and are prefaced with the letter F. Their functions depend on the software currently being used.

function key

8 Chapter 1 Introduction to Computers, Programs, and Python

A modifier key is a special key (such as the Shift, Alt, and Ctrl keys) that modifies the normal action of another key when the two are pressed simultaneously.

The numeric keypad, located on the right side of most keyboards, is a separate set of keys styled like a calculator to use for entering numbers quickly.

Arrow keys, located between the main keypad and the numeric keypad, are used to move the mouse pointer up, down, left, and right on the screen in many kinds of programs.

The Insert, Delete, Page Up, and Page Down keys are used in word processing and other programs for inserting text and objects, deleting text and objects, and moving up or down through a document one screen at a time.

The Mouse A mouse is a pointing device. It is used to move a graphical pointer (usually in the shape of an arrow) called a cursor around the screen or to click on-screen objects (such as a button) to trigger them to perform an action.

The Monitor The monitor displays information (text and graphics). The screen resolution and dot pitch determine the quality of the display.

The screen resolution specifies the number of pixels in horizontal and vertical dimensions of the display device. Pixels (short for “picture elements”) are tiny dots that form an image on the screen. A common resolution for a 17-inch screen, for example, is 1024 pixels wide and 768 pixels high. The resolution can be set manually. The higher the resolution, the sharper and clearer the image is.

The dot pitch is the amount of space between pixels, measured in millimeters. The smaller the dot pitch, the sharper the display.

1.2.6 Communication Devices Computers can be networked through communication devices, such as a dial-up modem (modulator/demodulator), a DSL or cable modem, a wired network interface card, or a wire- less adapter.

■ A dial-up modem uses a phone line and can transfer data at a speed up to 56,000 bps (bits per second).

■ A digital subscriber line (DSL) connection also uses a standard phone line, but it can transfer data 20 times faster than a standard dial-up modem.

■ A cable modem uses the cable TV line maintained by the cable company and is generally faster than DSL.

■ A network interface card (NIC) is a device that connects a computer to a local area network (LAN), as shown in Figure 1.7. LANs are commonly used in universities, businesses, and government agencies. A high-speed NIC called 1000BaseT can transfer data at 1,000 million bits per second (mbps).

■ Wireless networking is now extremely popular in homes, businesses, and schools. Every laptop computer sold today is equipped with a wireless adapter that enables the computer to connect to a local area network and the Internet.

Note Answers to checkpoint questions are on the Companion Website.

1.1 What are hardware and software? 1.2 List five major hardware components of a computer. 1.3 What does the acronym “CPU” stand for?

modifier key

numeric keypad

arrow keys

Insert key

Delete key

Page Up key Page Down key

screen resolution

pixels

dot pitch

modem

digital subscriber line (DSL)

cable modem

network interface card (NIC) local area network (LAN)

million bits per second (mbps)

✓Point✓Check

1.3 Programming Languages 9

1.4 What unit is used to measure CPU speed? 1.5 What is a bit? What is a byte? 1.6 What is memory for? What does RAM stand for? Why is memory called RAM? 1.7 What unit is used to measure memory size? 1.8 What unit is used to measure disk size? 1.9 What is the primary difference between memory and a storage device?

1.3 Programming Languages Computer programs, known as software, are instructions that tell a computer what to do.

Computers do not understand human languages, so programs must be written in a language a computer can use. There are hundreds of programming languages, and they were developed to make the programming process easier for people. However, all programs must be converted into a language the computer can understand.

1.3.1 Machine Language A computer’s native language, which differs among different types of computers, is its machine language—a set of built-in primitive instructions. These instructions are in the form of binary code, so if you want to give a computer an instruction in its native language, you have to enter

Network Interface Card

LAN

FIGURE 1.7 A local area network connects computers in close proximity to each other.

machine language

Key Point

10 Chapter 1 Introduction to Computers, Programs, and Python

the instruction as binary code. For example, to add two numbers, you might have to write an instruction in binary code, like this:

1101101010011010

1.3.2 Assembly Language Programming in machine language is a tedious process. Moreover, programs written in machine language are very difficult to read and modify. For this reason, assembly language was created in the early days of computing as an alternative to machine languages. Assembly language uses a short descriptive word, known as mnemonic, to represent each of the machine- language instructions. For example, the mnemonic add typically means to add numbers and sub means to subtract numbers. To add the numbers 2 and 3 and get the result, you might write an instruction in assembly code like this:

add 2, 3, result

Assembly languages were developed to make programming easier. However, because the computer cannot understand assembly language, another program—called an assembler—is used to translate assembly-language programs into machine code, as shown in Figure 1.8.

assembly language

assembler

Assembly Source File

… add 2, 3, result

Machine-Code File

… 1101101010011010

Assembler

FIGURE 1.8 An assembler translates assembly-language instructions into machine code.

Writing code in assembly language is easier than in machine language. However, it is still tedious to write code in assembly language. An instruction in assembly language essentially corresponds to an instruction in machine code. Writing in assembly requires that you know how the CPU works. Assembly language is referred to as a low-level language, because assembly language is close in nature to machine language and is machine dependent.

1.3.3 High-Level Language In the 1950s, a new generation of programming languages known as high-level languages emerged. They are platform-independent, which means that you can write a program in a high- level language and run it in different types of machines. High-level languages are English-like and easy to learn and use. The instructions in a high-level programming language are called statements. Here, for example, is a high-level language statement that computes the area of a circle with a radius of 5:

area = 5 * 5 * 3.1415

There are many high-level programming languages, and each was designed for a specific purpose. Table 1.1 lists some popular ones.

A program written in a high-level language is called a source program or source code. Because a computer cannot understand a source program, a source program must be translated into machine code for execution. The translation can be done using another programming tool called an interpreter or a compiler.

■ An interpreter reads one statement from the source code, translates it to the machine code or virtual machine code, and then executes it right away, as shown in Figure 1.9a.

low-level language

high-level language

source program

source code

interpreter

compiler

statement

1.3 Programming Languages 11

TABLE 1.1 Popular High-Level Programming Languages

Language Description

Ada Named for Ada Lovelace, who worked on mechanical general-purpose computers. The Ada language was developed for the Department of Defense and is used mainly in defense projects.

BASIC Beginner’s All-purpose Symbolic Instruction Code. It was designed to be learned and used easily by beginners.

C Developed at Bell Laboratories. C combines the power of an assembly language with the ease of use and portability of a high-level language.

C++ C++ is an object-oriented language, based on C.

C# Pronounced “C Sharp.” It is a hybrid of Java and C++ and was developed by Microsoft.

COBOL COmmon Business Oriented Language. Used for business applications.

FORTRAN FORmula TRANslation. Popular for scientific and mathematical applications.

Java Developed by Sun Microsystems, now part of Oracle. It is widely used for developing platform-independent Internet applications.

Pascal Named for Blaise Pascal, who pioneered calculating machines in the seventeenth century. It is a simple, structured, general-purpose language primarily for teaching programming.

Python A simple general-purpose scripting language good for writing short programs.

Visual Basic Visual Basic was developed by Microsoft and it enables the programmers to rapidly develop Windows-based applications.

Machine-Code File

… 0101100011011100 1111100011000100

High-Level Source File

… area = 5 * 5 * 3.1415;

(b)

Compiler Executor

High-Level Source File

… area = 5 * 5 * 3.1415;

(a)

Interpreter Output

Output

FIGURE 1.9 (a) An interpreter translates and executes a program one statement at a time. (b) A compiler translates the entire source program into a machine-language file for execution.

Note that a statement from the source code may be translated into several machine instructions.

■ A compiler translates the entire source code into a machine-code file, and the machine code file is then executed, as shown in Figure 1.9b.

Python code is executed using an interpreter. Most other programming languages are processed using a compiler.

1.10 What language does the CPU understand? 1.11 What is an assembly language? ✓Point✓Check

12 Chapter 1 Introduction to Computers, Programs, and Python

operating system (OS)

User

Application Programs

Operating System

Hardware

FIGURE 1.10 Users and applications access the computer’s hardware via the operating system.

1.12 What is an assembler? 1.13 What is a high-level programming language? 1.14 What is a source program? 1.15 What is an interpreter? 1.16 What is a compiler? 1.17 What is the difference between an interpreted language and a compiled language?

1.4 Operating Systems The operating system (OS) is the most important program that runs on a computer. The OS manages and controls a computer’s activities.

The popular operating systems for general-purpose computers are Microsoft Windows, Mac OS, and Linux. Application programs, such as a Web browser or a word processor, cannot run unless an operating system is installed and running on the computer. Figure 1.10 shows the interrelationship of hardware, operating system, application software, and the user.

The major tasks of an operating system are:

■ Controlling and monitoring system activities

■ Allocating and assigning system resources

■ Scheduling operations

1.4.1 Controlling and Monitoring System Activities Operating systems perform basic tasks, such as recognizing input from the keyboard, sending output to the monitor, keeping track of files and folders on storage devices, and controlling peripheral devices, such as disk drives and printers. An operating system must also ensure that different programs and users working at the same time do not interfere with each other. In addition, the OS is responsible for security, ensuring that unauthorized users and programs do not access the system.

1.4.2 Allocating and Assigning System Resources The operating system is responsible for determining what computer resources a program needs (such as CPU time, memory space, disks, input and output devices) and for allocating and assigning them to run the program.

Key Point

1.5 The History of Python 13

1.4.3 Scheduling Operations The OS is responsible for scheduling programs’ activities to make efficient use of system resources. Many of today’s operating systems support such techniques as multiprogramming, multithreading, and multiprocessing to increase system performance.

Multiprogramming allows multiple programs to run simultaneously by sharing the same CPU. The CPU is much faster than the computer’s other components. As a result, it is idle most of the time—for example, while waiting for data to be transferred from a disk or waiting for other system resources to respond. A multiprogramming OS takes advantage of this situa- tion by allowing multiple programs to use the CPU when it would otherwise be idle. For example, multiprogramming enables you to use a word processor to edit a file at the same time as your Web browser is downloading a file.

Multithreading allows a single program to execute multiple tasks at the same time. For instance, a word-processing program allows users to simultaneously edit text and save it to a disk. In this example, editing and saving are two tasks within the same application. These two tasks may run concurrently.

Multiprocessing, or parallel processing, uses two or more processors together to per- form subtasks concurrently and then combine solutions of the subtasks to obtain a solution for the entire task. It is like a surgical operation where several doctors work together on one patient.

1.18 What is an operating system? List some popular operating systems. 1.19 What are the major responsibilities of an operating system? 1.20 What are multiprogramming, multithreading, and multiprocessing?

1.5 The History of Python Python is a general-purpose, interpreted, object-oriented programming language.

Python was created by Guido van Rossum in the Netherlands in 1990 and was named after the popular British comedy troupe Monty Python’s Flying Circus. Van Rossum developed Python as a hobby, and Python has become a popular programming language widely used in industry and academia due to its simple, concise, and intuitive syntax and extensive library.

Python is a general-purpose programming language. That means you can use Python to write code for any programming task. Python is now used in the Google search engine, in mission-critical projects at NASA, and in transaction processing at the New York Stock Exchange.

Python is interpreted, which means that Python code is translated and executed by an inter- preter, one statement at a time, as described earlier in the chapter.

Python is an object-oriented programming (OOP) language. Data in Python are objects created from classes. A class is essentially a type or category that defines objects of the same kind with properties and methods for manipulating objects. Object-oriented programming is a powerful tool for developing reusable software. Object-oriented programming in Python will be covered in detail starting in Chapter 7.

Python is now being developed and maintained by a large team of volunteers and is avail- able for free from the Python Software Foundation. Two versions of Python are currently coexistent: Python 2 and Python 3. The programs written in Python 3 will not run in Python 2. Python 3 is a newer version, but it is not backward-compatible with Python 2. This means that if you write a program using the Python 2 syntax, it may not work with a Python 3 inter- preter. Python provides a tool that automatically converts code written in Python 2 into syntax Python 3 can use. Python 2 will eventually be replaced by Python 3. This book teaches pro- gramming using Python 3.

multiprogramming

multithreading

multiprocessing

general-purpose programming language

interpreted

object-oriented programming (OOP)

Python 2 vs. Python 3

✓Point✓Check

Key Point

14 Chapter 1 Introduction to Computers, Programs, and Python

1.21 Python is interpreted. What does that mean? 1.22 Can a program written in Python 2 run in Python 3? 1.23 Can a program written using Python 3 run in Python 2?

1.6 Getting Started with Python A Python program is executed from the Python interpreter.

Let’s get started by writing a simple Python program that displays the messages Welcome to Python and Python is fun on the console. The word console is an old computer term that refers to the text entry and display device of a computer. Console input means to receive input from the keyboard and console output means to display output to the monitor.

Note You can run Python on the Windows, UNIX, and Mac operating systems. For informa- tion on installing Python, see Supplement I.B, Installing and Using Python, on the Companion Website.

1.6.1 Launching Python Assume you have Python installed on the Windows OS. You can start Python in a com- mand window by typing python at the command prompt, as shown in Figure 1.11, or by using IDLE, as shown in Figure 1.12. IDLE (Interactive DeveLopment Environment) is an integrated development environment (IDE) for Python. You can create, open, save, edit, and run Python programs in IDLE. Both the command-line Python interpreter and IDLE are available after Python is installed on your machine. Note that Python (command line)

console

install Python

IDLE

FIGURE 1.11 You can launch Python from the command window.

FIGURE 1.12 You can use Python from IDLE.

Key Point

console input

console output

✓Point✓Check

VideoNote Start with Python

1.6 Getting Started with Python 15

and IDLE can also be accessed directly from the Windows Start button by searching for Python (command line) or IDLE (Python GUI) on Windows 7 or Vista, as shown in Figure 1.13.

After Python starts, you will see the symbol >>>. This is the Python statement prompt, and it is where you can enter a Python statement.

Note Type the commands exactly as they are written in this text. Formatting and other rules will be discussed later in this chapter.

Now, type print(“Welcome to Python”) and press the Enter key. The string Welcome to Python appears on the console, as shown in Figure 1.11. String is a programming term meaning a sequence of characters.

Note Note that Python requires double or single quotation marks around strings to delineate them from other code. As you can see in the output, Python doesn’t display those quotation marks.

The print statement is one of Python’s built-in functions that can be used to display a string on the console. A function performs actions. In the case of the print function, it dis- plays a message to the console.

Note In programming terminology, when you use a function, you are said to be “invoking a function” or “calling a function.”

Next, type print(“Python is fun”) and press the Enter key. The string Python is fun appears on the console, as shown in Figure 1.11. You can enter additional statements at the statement prompt >>>.

Note To exit Python, press CTRL+Z and then the Enter key.

Python IDLE Python command line

Enter Python here

FIGURE 1.13 You can launch the Python IDLE and command line from the Start button.

Python statement prompt >>>

string

function

invoking a function

calling a function

16 Chapter 1 Introduction to Computers, Programs, and Python

1.6.2 Creating Python Source Code Files Entering Python statements at the statement prompt >>> is convenient, but the statements are not saved. To save statements for later use, you can create a text file to store the statements and use the following command to execute the statements in the file:

python filename.py

The text file can be created using a text editor such as Notepad. The text file, filename, is called a Python source file or script file, or module. By convention, Python files are named with the extension .py.

Running a Python program from a script file is known as running Python in script mode. Typing a statement at the statement prompt >>> and executing it is called running Python in interactive mode.

Note Besides developing and running Python programs from the command window, you can create, save, modify, and run a Python script from IDLE. For information on using IDLE, see Supplement I.C on the Companion Website. Your instructor may also ask you to use Eclipse. Eclipse is a popular interactive development environment (IDE) used to develop programs quickly. Editing, running, debugging, and online help are integrated in one graphical user interface. If you want to develop Python programs using Eclipse, see Supplement I.D, on the Companion Website.

Listing 1.1 shows you a Python program that displays the messages Welcome to Python and Python is fun.

LISTING 1.1 Welcome.py 1 # Display two messages 2 print(“Welcome to Python”) 3 print(“Python is fun”)

In this text, line numbers are displayed for reference purposes; they are not part of the pro- gram. So, don’t type line numbers in your program.

Suppose the statements are saved in a file named Welcome.py. To run the program, enter python Welcome.py at the command prompt, as shown in Figure 1.14.

source file script file module .py file script mode interactive mode

Python on Eclipse

comment print a message

FIGURE 1.14 You can run a Python script file from a command window.

In Listing 1.1, line 1 is a comment that documents what the program is and how it is con- structed. Comments help programmers communicate and understand a program. They are not programming statements and thus are ignored by the interpreter. In Python, comments are preceded by a pound sign (#) on a line, called a line comment, or enclosed between three con- secutive single quotation marks (”’) on one or several lines, called a paragraph comment.

line numbers

execute the program

comment

line comment

paragraph comment

1.6 Getting Started with Python 17

When the Python interpreter sees #, it ignores all text after # on the same line. When it sees ”’, it scans for the next ”’ and ignores any text between the triple quotation marks. Here are examples of comments:

# This program displays Welcome to Python

”’ This program displays Welcome to Python and Python is fun

”’

Indentation matters in Python. Note that the statements are entered from the first column in the new line. The Python interpreter will report an error if the program is typed as follows:

# Display two messages print(“Welcome to Python”)

print(“Python is fun”)

Don’t put any punctuation at the end of a statement. For example, the Python interpreter will report errors for the following code:

# Display two messages print(“Welcome to Python”). print(“Python is fun”),

Python programs are case sensitive. It would be wrong, for example, to replace print in the program with Print.

You have seen several special characters (#, “, ()) in the program. They are used in almost every program. Table 1.2 summarizes their uses.

TABLE 1.2 Special Characters

Character Name Description

() Opening and closing parentheses Used with functions.

# Pound sign Precedes a comment line.

” ” Opening and closing quotation marks Encloses a string (i.e., sequence of characters).

”’ ”’ Paragraph comments Encloses a paragraph comment.

The program in Listing 1.1 displays two messages. Once you understand the program, it is easy to extend it to display more messages. For example, you can rewrite the program to dis- play three messages, as shown in Listing 1.2.

LISTING 1.2 WelcomeWithThreeMessages.py 1 # Display three messages 2 print(“Welcome to Python”) 3 print(“Python is fun”) 4 print(“Problem Driven”)

Welcome to Python Python is fun Problem Driven

indentation

case sensitive

special characters

comment print statement

BAD CO

DE

BAD CO

DE

18 Chapter 1 Introduction to Computers, Programs, and Python

1.6.3 Using Python to Perform Mathematical Computations Python programs can perform all sorts of mathematical computations and display the result. To display the addition, subtraction, multiplication, and division of two numbers, x and y, use the following code:

print(x + y) print(x – y) print(x * y) print(x / y)

Listing 1.3 shows an example of a program that evaluates and prints its result.

LISTING 1.3 ComputeExpression.py 1 # Compute expression 2 print((10.5 + 2 * 3) / (45 – 3.5))

10.5 + 2 * 3 45 – 3.5

comment compute expression

0.397590361446

As you can see, it is a straightforward process to translate an arithmetic expression to a Python expression. We will discuss Python expressions further in Chapter 2.

1.24 You can run Python in two modes. Explain these two modes. 1.25 Is Python case sensitive? 1.26 What is the Python source filename extension by convention? 1.27 What is the command to run a Python source file? 1.28 What is a comment? How do you denote a comment line and a comment paragraph? 1.29 What is the statement to display the message Hello world on the console? 1.30 Identify and fix the errors in the following code:

1 # Display two messages 2 print(“Welcome to Python”) 3 print(“Python is fun”).

1.31 Show the output of the following code: print(“3.5 * 4 / 2 – 2.5 is”) print(3.5 * 4 / 2 – 2.5)

1.7 Programming Style and Documentation Good programming style and proper documentation make a program easy to read and prevents errors.

Programming style deals with what programs look like. When you create programs with a professional programming style, they not only execute properly but are easy for people to read and understand. This is very important if other programmers will access or modify your programs.

Documentation is the body of explanatory remarks and comments pertaining to a program. These remarks and comments explain various parts of the program and help others understand its structure and function. As you saw earlier in the chapter, remarks and comments are

programming style

documentation

✓Point✓Check

Key Point

1.8 Programming Errors 19

embedded within the program itself; Python’s interpreter simply ignores them when the pro- gram is executed.

Programming style and documentation are as important as coding. Here are a few guidelines.

1.7.1 Appropriate Comments and Comment Styles Include a summary comment at the beginning of the program to explain what the program does, its key features, and any unique techniques it uses. In a long program, you should also include comments that introduce each major step and explain anything that is difficult to read. It is important to make comments concise so that they do not crowd the program or make it difficult to read.

1.7.2 Proper Spacing A consistent spacing style makes programs clear and easy to read, debug (find and fix errors), and maintain.

A single space should be added on both sides of an operator, as shown in the following statement:

More detailed guidelines can be found in Supplement I.F, Python Coding Style Guidelines, on the Companion Website.

1.8 Programming Errors Programming errors can be categorized into three types: syntax errors, runtime errors, and logic errors.

1.8.1 Syntax Errors The most common error you will encounter are syntax errors. Like any programming lan- guage, Python has its own syntax, and you need to write code that obeys the syntax rules. If your program violates the rules—for example, if a quotation mark is missing or a word is misspelled—Python will report syntax errors.

Syntax errors result from errors in code construction, such as mistyping a statement, incor- rect indentation, omitting some necessary punctuation, or using an opening parenthesis with- out a corresponding closing parenthesis. These errors are usually easy to detect, because Python tells you where they are and what caused them. For example, the following print statement has a syntax error:

common errors

syntax rules

syntax errors

print(3+4*4) Bad style

print(3 + 4 * 4) Good style

Key Point

20 Chapter 1 Introduction to Computers, Programs, and Python

The string Programming is fun should be closed with a closing quotation mark.

Tip If you don’t know how to correct a syntax error, compare your program closely, charac- ter by character, with similar examples in the text. In the first few weeks of this course, you will probably spend a lot of time fixing syntax errors. Soon, you will be familiar with Python syntax and will be able to fix syntax errors quickly.

1.8.2 Runtime Errors Runtime errors are errors that cause a program to terminate abnormally. They occur while a program is running if the Python interpreter detects an operation that is impossible to carry out. Input mistakes typically cause runtime errors. An input error occurs when the user enters a value that the program cannot handle. For instance, if the program expects to read in a number, but instead the user enters a string of text, this causes data-type errors to occur in the program.

Another common source of runtime errors is division by zero. This happens when the divi- sor is zero for integer divisions. For example, the expression 1 / 0 in the following statement would cause a runtime error.

logic errors

Fahrenheit 35 is Celsius degree -12.555555555555554

You will get Celsius –12.55 degrees, which is wrong. It should be 1.66. To get the correct result, you need to use 5 / 9 * (35 – 32) rather than 5 / 9 * 35 – 32 in the expression. That is, you need to add parentheses around (35 – 32) so Python will calculate that expression first before doing the division.

In Python, syntax errors are actually treated like runtime errors because they are detected by the interpreter when the program is executed. In general, syntax and runtime errors are easy to find and easy to correct, because Python gives indications as to where the errors came from and why they are wrong. Finding logic errors, on the other hand, can be very challenging.

fix syntax errors

runtime errors

input errors

1.8.3 Logic Errors Logic errors occur when a program does not perform the way it was intended to. Errors of this kind occur for many different reasons. For example, suppose you wrote the program in Listing 1.4 to convert a temperature (35 degrees) from Fahrenheit to Celsius.

LISTING 1.4 ShowLogicErrors.py 1 # Convert Fahrenheit to Celsius 2 print(“Fahrenheit 35 is Celsius degree “) 3 print(5 / 9 * 35 – 32)

1.9 Getting Started with Graphics Programming 21

turtle

Tkinter

1.32 What are three kinds of program errors? 1.33 If you forget to put a closing quotation mark on a string, what kind of error will be

raised?

1.34 If your program needs to read data from a file, but the file does not exist, an error would occur when running this program. What kind of error is this?

1.35 Suppose you write a program for computing the perimeter of a rectangle and you mistakenly write your program so that it computes the area of a rectangle. What kind of error is this?

1.9 Getting Started with Graphics Programming Turtle is Python’s built-in graphics module for drawing lines, circles, and other shapes, including text. It is easy to learn and simple to use.

Beginners often enjoy learning programming by using graphics. For this reason, we provide a section on graphics programming at the end of most of the chapters in the first part of the book. However, these materials are not mandatory. They can be skipped or covered later.

There are many ways to write graphics programs in Python. A simple way to start graphics programming is to use Python’s built-in turtle module. Later in the book, we will introduce Tkinter for developing comprehensive graphical user interface applications.

1.9.1 Drawing and Adding Color to a Figure The following procedure will give you a basic introduction to using the turtle module. Sub- sequent chapters introduce more features.

1. Launch Python by choosing Python (command line) from the Windows Start button or by typing python at the command prompt.

2. At the Python statement prompt >>>, type the following command to import the turtle module. This command imports all functions defined in the turtle module and makes them available for you to use.

>>> import turtle # Import turtle module

3. Type the following command to show the current location and direction of the turtle, as shown in Figure 1.15a.

>>> turtle.showturtle()

Graphics programming using the Python Turtle module is like drawing with a pen. The arrowhead indicates the current position and direction of the pen. turtle is initially positioned at the center of the window. Here, turtle refers to the object for drawing graphics (objects will be introduced in Chapter 3).

4. Type the following command to draw a text string:

>>> turtle.write(“Welcome to Python”)

Your window should look like the one shown in Figure 1.15b.

5. Type the following command to move the arrowhead 100 pixels forward to draw a line in the direction the arrow is pointing:

>>> turtle.forward(100)

Your window should now look like the one shown in Figure 1.15c.

To draw the rest of Figure 1.15, continue with these steps.

VideoNote

Start with Turtle graphics

Key Point

✓Point✓Check

22 Chapter 1 Introduction to Computers, Programs, and Python

6. Type the following commands to turn the arrowhead right 90 degrees, change the turtle’s color to red, and move the arrowhead 50 pixels forward to draw a line, as shown in Figure 1.15d:

>>> turtle.right(90) >>> turtle.color(“red”) >>> turtle.forward(50)

7. Now, type the following commands to turn the arrowhead right 90 degrees, set the color to green, and move the arrowhead 100 pixels forward to draw a line, as shown in Figure 1.15e:

>>> turtle.right(90) >>> turtle.color(“green”) >>> turtle.forward(100)

8. Finally, type the following commands to turn the arrowhead right 45 degrees and move it 80 pixels forward to draw a line, as shown in Figure 1.15f:

>>> turtle.right(45) >>> turtle.forward(80)

9. You can now close the Turtle Graphics window and exit Python.

1.9.2 Moving the Pen to Any Location When the Turtle program starts, the arrowhead is at the center of the Python Turtle Graphics window at the coordinates (0, 0), as shown in Figure 1.16a. You can also use the goto(x, y) command to move the turtle to any specified point (x, y).

Restart Python and type the following command to move the pen to (0, 50) from (0, 0), as shown in Figure 1.16b.

>>> import turtle >>> turtle.goto(0, 50)

(a) (b)

(d) (e) (f)

(c)

FIGURE 1.15 Graphics are dynamically displayed with each statement.

1.9 Getting Started with Graphics Programming 23

(a) (b)

(d) (e)

(c) (0, 0)

(0, 50)

(50, –50)

Y-axis

X-axis(0, 0)

FIGURE 1.16 (a) The center of the Turtle Graphics window is at the coordinates (0, 0). (b) Move to (0, 50). (c) Move the pen to (50, –50). (d) Set color to red. (e) Draw a circle using the circle command.

You can also lift the pen up or put it down to control whether to draw a line when the pen is moved by using the penup() and pendown() commands. For example, the following commands move the pen to (50, -50), as shown in Figure 1.16c.

>>> turtle.penup() >>> turtle.goto(50, -50) >>> turtle.pendown()

You can draw a circle using the circle command. For example, the following commands set color red (Figure 1.16d) and draw a circle with radius 50 (Figure 1.16e).

>>> turtle.color(“red”) >>> turtle.circle(50) # Draw a circle with radius 50

1.9.3 Drawing the Olympic Rings Logo Listing 1.5 shows a program for drawing the Olympics rings logo, as shown in Figure 1.17.

LISTING 1.5 OlympicSymbol.py 1 import turtle 2 3 turtle.color(“blue”) 4 turtle.penup() 5 turtle.goto(-110, -25) 6 turtle.pendown() 7 turtle.circle(45) 8 9 turtle.color(“black”)

draw blue circle

draw black circle

24 Chapter 1 Introduction to Computers, Programs, and Python

10 turtle.penup() 11 turtle.goto(0, -25) 12 turtle.pendown() 13 turtle.circle(45) 14 15 turtle.color(“red”) 16 turtle.penup() 17 turtle.goto(110, -25) 18 turtle.pendown() 19 turtle.circle(45) 20 21 turtle.color(“yellow”) 22 turtle.penup() 23 turtle.goto(-55, -75) 24 turtle.pendown() 25 turtle.circle(45) 26 27 turtle.color(“green”) 28 turtle.penup() 29 turtle.goto(55, -75) 30 turtle.pendown() 31 turtle.circle(45) 32 33 turtle.done()

The program imports the turtle module to use the Turtle Graphics window (line 1). It moves the pen to (line 5) and draws a blue circle with radius 45 (line 7). Similarly, it draws a black circle (lines 9–13), a red circle (lines 15–19), a yellow circle (lines 21–25), and a green circle (lines 27–31).

Line 33 invokes turtle’s done() command, which causes the program to pause until the user closes the Python Turtle Graphics window. The purpose of this is to give the user time to view the graphics. Without this line, the graphics window would be closed right after the pro- gram is finished.

1.36 How do you import the turtle module? 1.37 How do you display text in Turtle? 1.38 How do you move the pen forward? 1.39 How do you set a new color? 1.40 How do you move the pen without drawing anything? 1.41 How do you draw a circle? 1.42 What is the purpose of turtle.done() in line 33 in Listing 1.5?

(-110, -25)

FIGURE 1.17 The program draws the Olympics rings logo.

draw yellow circle

draw green circle

pause

✓Point✓Check

draw red circle

Chapter Summary 25

KEY TERMS

.py file 16 assembler 10 assembly language 10 bit 4 bus 2 byte 4 cable modem 8 calling a function 15 central processing unit (CPU) 3 comment 16 compiler 10 console 14 dot pitch 8 DSL (digital subscriber line) 8 encoding scheme 4 function 15 hardware 2 high-level language 10 IDLE (Interactive DeveLopment

Environment) 14 indentation 17 interactive mode 16 interpreter 10 invoking a function 15

line comment 16 logic error 20 low-level language 10 machine language 9 memory 5 modem 8 module 16 motherboard 3 network interface card (NIC) 8 operating system (OS) 12 pixel 8 program 2 runtime errors 20 screen resolution 8 script file 16 script mode 16 software 2 source code 10 source file 16 source program 10 statement 10 storage device 5 syntax errors 19 syntax rules 19

Note The above terms are defined in the present chapter. Supplement I.A, Glossary, lists all the key terms and descriptions in the book, organized by chapters.

CHAPTER SUMMARY 1. A computer is an electronic device that stores and processes data.

2. A computer includes both hardware and software.

3. Hardware is the physical aspect of the computer that can be touched.

4. Computer programs, known as software, are the invisible instructions that control the hardware and make it perform tasks.

5. Computer programming is the writing of instructions (i.e., code) for computers to perform.

6. The central processing unit (CPU) is a computer’s brain. It retrieves instructions from memory and executes them.

7. Computers use zeros and ones because digital devices have two stable electrical states, off and on, referred to by convention as zero and one.

8. A bit is a binary digit 0 or 1.

Supplement I.A

26 Chapter 1 Introduction to Computers, Programs, and Python

9. A byte is a sequence of 8 bits.

10. A kilobyte is about 1,000 bytes, a megabyte about 1 million bytes, a gigabyte about 1 billion bytes, and a terabyte about 1,000 gigabytes.

11. Memory stores data and program instructions for the CPU to execute.

12. A memory unit is an ordered sequence of bytes.

13. Memory is volatile, because information that hasn’t been saved is lost when the power is turned off.

14. Programs and data are permanently stored on storage devices and are moved to memory when the computer actually uses them.

15. The machine language is a set of primitive instructions built into every computer.

16. Assembly language is a low-level programming language in which a mnemonic is used to represent each machine-language instruction.

17. High-level languages are English-like and easy to learn and program.

18. A program written in a high-level language is called source code.

19. A compiler is a software program that translates the source program into a machine- language program.

20. The operating system (OS) is a program that manages and controls a computer’s activities.

21. You can run Python on Windows, UNIX, and Mac.

22. Python is interpreted, meaning that Python translates each statement and processes it one at a time.

23. You can enter Python statements interactively from the Python statement prompt >>> or store all your code in one file and execute it using one command.

24. To run a Python source file from the command line, use the python filename.py command.

25. In Python, comments are preceded by a pound sign (#) on a line, called a line comment, or enclosed between triple quotation marks (”’ and ”’) on one or several lines, called a paragraph comment.

26. Python source programs are case sensitive.

27. Programming errors can be categorized into three types: syntax errors, runtime errors, and logic errors. Syntax and runtime errors cause a program to terminate abnormally. Logic errors occur when a program does not perform the way it was intended to.

TEST QUESTIONS Do test questions for this chapter online at www.cs.armstrong.edu/liang/py/test.html.

Programming Exercises 27

PROGRAMMING EXERCISES

Note Solutions to even-numbered exercises in this book are on the Companion Website. Solutions to all exercises are on the Instructor Resource Website. The level of difficulty is rated easy (no star), moderate (*), hard (**), or challenging (***).

Section 1.6 1.1 (Display three different messages) Write a program that displays Welcome to

Python, Welcome to Computer Science, and Programming is fun.

1.2 (Display the same message five times) Write a program that displays Welcome to Python five times.

*1.3 (Display a pattern) Write a program that displays the following pattern:

FFFFFFF U U NN NN FF U U NNN NN FFFFFFF U U NN N NN FF U U NN N NN FF UUU NN NNN

1.4 (Print a table) Write a program that displays the following table:

a a^2 a^3 1 1 1 2 4 8 3 9 27 4 16 64

1.5 (Compute expressions) Write a program that displays the result of

1.6 (Summation of a series) Write a program that displays the result of

1.7 (Approximate ) can be computed using the following formula:

Write a program that displays the result of

and

1.8 (Area and perimeter of a circle) Write a program that displays the area and perimeter of a circle that has a radius of 5.5 using the following formulas:

perimeter = 2 * radius * p area = radius * radius * p

4 * ¢1 – 1 3

+ 1

5 –

1

7 +

1

9 –

1

11 +

1

13 –

1

15 ≤ .

4 * ¢1 – 1 3

+ 1

5 –

1

7 +

1

9 –

1

11 ≤ .

p = 4 * ¢1 – 1 3

+ 1

5 –

1

7 +

1

9 –

1

11 + c ≤

pp

3 + 4 + 5 + 6 + 7 + 8 + 9. 1 + 2 +

9.5 * 4.5 – 2.5 * 3 45.5 – 3.5

level of difficulty

28 Chapter 1 Introduction to Computers, Programs, and Python

1.9 (Area and perimeter of a rectangle) Write a program that displays the area and perimeter of a rectangle with the width of 4.5 and height of 7.9 using the follow- ing formula:

1.10 (Average speed) Assume a runner runs 14 kilometers in 45 minutes and 30 sec- onds. Write a program that displays the average speed in miles per hour. (Note that 1 mile is 1.6 kilometers.)

*1.11 (Population projection) The US Census Bureau projects population based on the following assumptions:

One birth every 7 seconds One death every 13 seconds One new immigrant every 45 seconds

Write a program to display the population for each of the next five years. Assume the current population is 312032486 and one year has 365 days. Hint: in Python, you can use integer division operator // to perform division. The result is an integer. For example, 5 // 4 is 1 (not 1.25) and 10 // 4 is 2 (not 2.5).

Section 1.9 1.12 (Turtle: draw four squares) Write a program that draws four squares in the center

of the screen, as shown in Figure 1.18a.

area = width * height

(a) (b) (c) (d)

FIGURE 1.18 Four squares are drawn in (a), a cross is drawn in (b), a triangle is drawn in (c), and two triangles are drawn in (d).

1.13 (Turtle: draw a cross) Write a program that draws a cross as shown in Figure 1.18b. 1.14 (Turtle: draw a triangle) Write a program that draws a triangle as shown in

Figure 1.18c.

1.15 (Turtle: draw two triangles) Write a program that draws two triangles as shown in Figure 1.18d.

1.16 (Turtle: draw four circles) Write a program that draws four circles in the center of the screen, as shown in Figure 1.19a.

1.17 (Turtle: draw a line) Write a program that draws a red line connecting two points (-39, 48) and (50, -50) and displays the coordinates of the two points, as shown in Figure 1.19b.

**1.18 (Turtle: draw a star) Write a program that draws a star, as shown in Figure 1.19c. (Hint: The inner angle of each point in the star is 36 degrees.)

Programming Exercises 29

1.20 (Turtle: display a rectanguloid) Write a program that displays a rectanguloid, as shown in Figure 1.20b.

*1.21 (Turtle: display a clock) Write a program that displays a clock to show the time 9:15:00, as shown in Figure 1.20c.

(a) (b) (c)

FIGURE 1.20 (a) The program displays a polygon. (b) The program displays a rectanguloid. (c) The program displays a clock for the time.

(a) (c)(b)

FIGURE 1.19 Four circles are drawn in (a), a line is drawn in (b), and a star is drawn in (c).

1.19 (Turtle: draw a polygon) Write a program that draws a polygon that connects the points (40, -69.28), (-40, -69.28), (-80, -9.8), (-40, 69), (40, 69), and (80, 0) in this order, as shown in Figure 1.20a.

This page intentionally left blank

ELEMENTARY PROGRAMMING

Objectives ■ To write programs that perform simple computations (§2.2).

■ To obtain input from a program’s user by using the input function (§2.3).

■ To use identifiers to name elements such as variables and functions (§2.4).

■ To assign data to variables (§2.5).

■ To perform simultaneous assignment (§2.6).

■ To define named constants (§2.7).

■ To use the operators +, -, *, /, //, %, and ** (§2.8).

■ To write and evaluate numeric expressions (§2.9).

■ To use augmented assignment operators to simplify coding (§2.10).

■ To perform numeric type conversion and rounding with the int and round functions (§2.11).

■ To obtain the current system time by using time.time() (§2.12).

■ To describe the software development process and apply it to develop a loan payment program (§2.13).

■ To compute and display the distance between two points in graphics (§2.14).

CHAPTER

2

32 Chapter 2 Elementary Programming

2.1 Introduction The focus of this chapter is on learning elementary programming techniques to solve problems.

In Chapter 1 you learned how to create and run very basic Python programs. Now you will learn how to solve problems by writing programs. Through these problems, you will learn fundamental programming techniques, such as the use of variables, operators, expressions, and input and output.

Suppose, for example, that you need to take out a student loan. Given the loan amount, loan term, and annual interest rate, can you write a program to compute the monthly payment and total payment? This chapter shows you how to write programs like this. Along the way, you learn the basic steps that go into analyzing a problem, designing a solution, and imple- menting the solution by creating a program.

2.2 Writing a Simple Program Writing a program involves designing a strategy for solving the problem and then using a programming language to implement that strategy.

Let’s first consider the simple problem of computing the area of a circle. How do we write a program for solving this problem?

Writing a program involves designing algorithms and then translating them into program- ming instructions, or code. When you code—that is, when you write a program—you translate an algorithm into a program. An algorithm describes how a problem is solved by listing the actions that need to be taken and the order of their execution. Algorithms can help the programmer plan a program before writing it in a programming language. Algorithms can be described in natural languages or in pseudocode (natural language mixed with some program- ming code). The algorithm for calculating the area of a circle can be described as follows:

1. Get the circle’s radius from the user.

2. Compute the area by applying the following formula:

3. Display the result.

Tip It’s always good practice to outline your program (or its underlying problem) in the form of an algorithm before you begin coding.

In this problem, the program needs to read the radius, which the program’s user enters from the keyboard. This raises two important issues:

■ Reading the radius.

■ Storing the radius in the program.

Let’s address the second issue first. The value for the radius is stored in the computer’s memory. In order to access it, the program needs to use a variable. A variable is a name that references a value stored in the computer’s memory. Rather than using x and y as variable names, choose descriptive names: in this case, for example, you can use the name radius for the variable that references a value for radius and area for the variable that references a value for area.

The first step is to prompt the user to designate the circle’s radius. You will learn how to prompt the user for information shortly. For now, to learn how variables work, you can assign a fixed value to radius in the program as you write the code.

area = radius * radius * p

problem

algorithm

pseudocode

variable

descriptive names

Key Point

Key Point

line# radius area

2 20

5 1256.636

2.2 Writing a Simple Program 33

The second step is to compute area by assigning the result of the expression radius * radius * 3.14159 to area.

In the final step, the program will display the value of area on the console by using Python’s print function.

The complete program is shown in Listing 2.1.

LISTING 2.1 ComputeArea.py 1 # Assign a value to radius 2 radius = 20 # radius is now 20 radius 20 3 4 # Compute area 5 area = radius * radius * 3.14159 area 1256.636 6 7 # Display results 8 print(“The area for the circle of radius”, radius, “is”, area) display result

The area for the circle of radius 20 is 1256.636

Variables such as radius and area reference values stored in memory. Every variable has a name that refers to a value. You can assign a value to a variable using the syntax as shown in line 2.

radius = 20

This statement assigns 20 to the variable radius. So now radius references the value 20. The statement in line 5

area = radius * radius * 3.14159

uses the value in radius to compute the expression and assigns the result into the variable area. The following table shows the value for radius and area as the program is executed. Each row in the table shows the values of variables after the statement in the corresponding line in the program is executed. This method of reviewing how a program works is called tracing a program. Tracing programs are helpful for understanding how programs work, and they are useful tools for finding errors in programs.

If you have programmed in other languages, such as Java, you know you have to declare a variable with a data type to specify what type of values are being used, such as integers or text characters. You don’t do this in Python, however, because Python automatically figures out the data type according to the value assigned to the variable.

The statement in line 8 displays four items on the console. You can display any number of items in a print statement using the following syntax:

print(item1, item2, …, itemk)

assign value

trace a program

data type

print(item1, …)

34 Chapter 2 Elementary Programming

If an item is a number, the number is automatically converted to a string for displaying.

2.1 Show the printout of the following code: width = 5.5

height = 2

print(“area is”, width * height)

2.2 Translate the following algorithm into Python code: ■ Step 1: Use a variable named miles with initial value 100.

■ Step 2: Multiply miles by 1.609 and assign it to a variable named kilometers.

■ Step 3: Display the value of kilometers.

What is kilometers after Step 3?

2.3 Reading Input from the Console Reading input from the console enables the program to accept input from the user.

In Listing 2.1, a radius is set in the source code. To use a different radius, you have to modify the source code. You can use the input function to ask the user to input a value for the radius. The following statement prompts the user to enter a value, and then it assigns the value to the variable:

variable = input(“Enter a value: “)

The value entered is a string. You can use the function eval to evaluate and convert it to a numeric value. For example, eval(“34.5”) returns 34.5, eval(“345”) returns 345, eval(“3 + 4”) returns 7, and eval(“51 + (54 * (3 + 2))”) returns 321.

Listing 2.2 rewrites Listing 2.1 to prompt the user to enter a radius.

LISTING 2.2 ComputeAreaWithConsoleInput.py 1 # Prompt the user to enter a radius 2 radius = 3 4 # Compute area 5 area = radius * radius * 3.14159 6 7 # Display results 8 print(“The area for the circle of radius”, radius, “is”, area)

eval(input(“Enter a value for radius: “))

eval function

input radius

compute area

display result

Enter a value for radius: The area for the circle of radius 2.5 is 19.6349375

2.5

Enter a value for radius: The area for the circle of radius 23 is 1661.90111

23

Line 2 prompts the user to enter a value (in the form of a string) and converts it to a num- ber, which is equivalent to

s = input(“Enter a value for radius: “) # Read input as a string radius = eval(s) # Convert the string to a number

After the user enters a number and presses the Enter key, the number is read and assigned to radius.

Key Point

✓Point✓Check

2.3 Reading Input from the Console 35

Listing 2.2 shows how to prompt the user for a single input. However, you can prompt for multiple inputs as well. Listing 2.3 gives an example of reading multiple inputs from the key- board. This program reads three integers and displays their average.

LISTING 2.3 ComputeAverage.py 1 # Prompt the user to enter three numbers 2 number1 = eval(input(“Enter the first number: “)) 3 number2 = eval(input(“Enter the second number: “)) 4 number3 = eval(input(“Enter the third number: “)) 5 6 # Compute average 7 average = (number1 + number2 + number3) / 3 8 9 # Display result 10 print(“The average of”, number1, number2, number3, 11 “is”, average)

input number1 input number2 input number3

Enter the first number:

Enter the second number:

Enter the third number:

The average of 1 2 3 is 2.0

3

2

1

The program prompts the user to enter three integers (lines 2–4), computes their average (line 7), and displays the result (lines 10–11).

If the user enters something other than a number, the program will terminate with a runtime error. In Chapter 13, you will learn how to handle the error so that the program can continue to run.

Normally a statement ends at the end of the line. In the preceding listing, the print state- ment is split into two lines (lines 10–11). This is okay, because Python scans the print state- ment in line 10 and knows it is not finished until it finds the closing parenthesis in line 11. We say that these two lines are joined implicitly.

Note In some cases, the Python interpreter cannot determine the end of the statement written in multiple lines. You can place the line continuation symbol (\) at the end of a line to tell the interpreter that the statement is continued on the next line. For example, the following statement

sum = 1 + 2 + 3 + 4 + 5 + 6

is equivalent to

sum = 1 + 2 + 3 + 4 + 5 + 6

Note Most of the programs in early chapters of this book perform three steps: Input, Process, and Output, called IPO. Input is to receive input from the user. Process is to produce results using the input. Output is to display the results.

2.3 How do you write a statement to prompt the user to enter a numeric value? 2.4 What happens if the user enters 5a when executing the following code?

radius = eval(input(“Enter a radius: “))

2.5 How do you break a long statement into multiple lines?

\

runtime error

split a long statement

joining lines explicitly

line continuation symbol

IPO

✓Point✓Check

36 Chapter 2 Elementary Programming

identifiers

identifier naming rules

case sensitive

descriptive names

variable naming convention

camelCase

why called variables?

2.4 Identifiers Identifiers are the names that identify the elements such as variables and functions in a program.

As you can see in Listing 2.3, number1, number2, number3, average, input, eval, and print are the names of things that appear in the program. In programming terminology, such names are called identifiers. All identifiers must obey the following rules:

■ An identifier is a sequence of characters that consists of letters, digits, and underscores (_).

■ An identifier must start with a letter or an underscore. It cannot start with a digit.

■ An identifier cannot be a keyword. (See Appendix A, Python Keywords, for a list of keywords.) Keywords, also called reserved words, have special meanings in Python. For example, import is a keyword, which tells the Python interpreter to import a module to the program.

■ An identifier can be of any length.

For example, area, radius, and number1 are legal identifiers, whereas 2A and d+4 are not because they do not follow the rules. When Python detects an illegal identifier, it reports a syntax error and terminates the program.

Note Because Python is case sensitive, area, Area, and AREA are all different identifiers.

Tip Descriptive identifiers make programs easy to read. Avoid using abbreviations for identi- fiers. Using complete words is more descriptive. For example, numberOfStudents is better than numStuds, numOfStuds, or numOfStudents. We use descriptive names for complete programs in the text. However, we will occasionally use variables names such as i, j, k, x, and y in the code snippets for brevity. These names also provide a generic tone to the code snippets.

Tip Use lowercase letters for variable names, as in radius and area. If a name consists of several words, concatenate them into one, making the first word lowercase and capital- izing the first letter of each subsequent word—for example, numberOfStudents. This naming style is known as the camelCase because the uppercase characters in the name resemble a camel’s humps.

2.6 Which of the following identifiers are valid? Which are Python keywords (see Appendix A)? miles, Test, a+b, b–a, 4#R, $4, #44, apps if, elif, x, y, radius

2.5 Variables, Assignment Statements, and Expressions Variables are used to reference values that may be changed in the program.

As you can see from the programs in the preceding sections, variables are the names that refer- ence values stored in memory. They are called “variables” because they may reference different values. For example, in the following code, radius is initially 1.0 (line 2) and then changed to 2.0 (line 7), and area is set to 3.14159 (line 3) and then reset to 12.56636 (line 8).

Key Point

keyword

reserved word

✓Point✓Check

Key Point

2.5 Variables, Assignment Statements, and Expressions 37

1 # Compute the first area 2 radius = 1.0 radius 1.0 3 area = radius * radius * 3.14159 area 3.14159 4 print(“The area is”, area, “for radius”, radius) 5 6 # Compute the second area 7 radius = 2.0 radius 2.0 8 area = radius * radius * 3.14159 area 12.56636 9 print(“The area is”, area, “for radius”, radius)

The statement for assigning a value to a variable is called an assignment statement. In Python, the equal sign (=) is used as the assignment operator. The syntax for assignment state- ments is as follows:

variable = expression

An expression represents a computation involving values, variables, and operators that, taken together, evaluate to a value. For example, consider the following code:

y = 1 # Assign 1 to variable y radius = 1.0 # Assign 1.0 to variable radius x = 5 * (3 / 2) + 3 * 2 # Assign the value of the expression to x x = y + 1 # Assign the addition of y and 1 to x area = radius * radius * 3.14159 # Compute area

You can use a variable in an expression. A variable can also be used in both sides of the = operator. For example,

x = x + 1

In this assignment statement, the result of x + 1 is assigned to x. If x is 1 before the state- ment is executed, then it becomes 2 after the statement is executed.

To assign a value to a variable, you must place the variable name to the left of the assign- ment operator. Thus, the following statement is wrong:

1 = x # Wrong

Note In mathematics, x = 2 * x + 1 denotes an equation. However, in Python, x = 2 * x + 1 is an assignment statement that evaluates the expression 2 * x + 1 and assigns the result to x.

If a value is assigned to multiple variables, you can use a syntax like this:

i = j = k = 1

which is equivalent to

k = 1 j = k i = j

Every variable has a scope. The scope of a variable is the part of the program where the variable can be referenced. The rules that define the scope of a variable will be introduced gradually later in the book. For now, all you need to know is that a variable must be created before it can be used. For example, the following code is wrong:

assignment statement

assignment operator

expression

Assignment statement VideoNote

scope of a variable

38 Chapter 2 Elementary Programming

But you can simplify the task using the following statement to swap the values of x and y.

>>> x, y = y, x # Swap x with y

Simultaneous assignment can also be used to obtain multiple input in one statement. Listing 2.3 gives an example that prompts the user to enter three numbers and obtains their average. This program can be simplified using a simultaneous assignment statement, as shown in Listing 2.4.

count is not defined yet.

>>> count = count + 1 NameError: count is not defined >>>

To fix it, you may write the code like this:

>>> count = 1 # count is not created >>> count = count + 1 # Now increment count >>>

Caution A variable must be assigned a value before it can be used in an expression. For example,

interestRate = 0.05 interest = interestrate * 45

This code is wrong, because interestRate is assigned a value 0.05, but interestrate is not defined. Python is case-sensitive. interestRate and interestrate are two different variables.

2.6 Simultaneous Assignments Python also supports simultaneous assignment in syntax like this:

var1, var2, …, varn = exp1, exp2, …, expn

It tells Python to evaluate all the expressions on the right and assign them to the corre- sponding variable on the left simultaneously. Swapping variable values is a common opera- tion in programming and simultaneous assignment is very useful to perform this operation. Consider two variables: x and y. How do you write the code to swap their values? A common approach is to introduce a temporary variable as follows:

>>> x = 1 >>> y = 2 >>> temp = x # Save x in a temp variable >>> x = y # Assign the value in y to x >>> y = temp # Assign the value in temp to y

simultaneous assignment

2.7 Named Constants 39

input numbers

Enter three numbers separated by commas: The average of 1 2 3 is 2.0

1, 2, 3 enter input in one line

2.7 What is the naming convention for variables? 2.8 What is wrong in the following statement?

2 = a

2.9 What is x, y, and z after the following statement? x = y = z = 0

2.10 Assume that a = 1 and b = 2. What is a and b after the following statement? a, b = b, a

2.7 Named Constants A named constant is an identifier that represents a permanent value.

The value of a variable may change during the execution of a program, but a named constant (or simply constant) represents permanent data that never changes. In our ComputeArea program, p is a constant. If you use it frequently, you don’t want to keep typing 3.14159; instead, you can use a descriptive name PI for the value. Python does not have a special syntax for naming constants. You can simply create a variable to denote a constant. However, to distinguish a constant from a variable, use all uppercase letters to name a constant. For example, you can rewrite Listing 2.1 to use a named constant for p, as follows:

# Assign a radius radius = 20 # radius is now 20

# Compute area PI = 3.14159 area = radius * radius * PI

# Display results print(“The area for the circle of radius”, radius, “is”, area)

There are three benefits of using constants:

1. You don’t have to repeatedly type the same value if it is used multiple times.

2. If you have to change the constant’s value (e.g., from 3.14 to 3.14159 for PI), you need to change it only in a single location in the source code.

3. Descriptive names make the program easy to read.

constant naming convention

Key Point

✓Point✓Check

LISTING 2.4 ComputeAverageWithSimultaneousAssignment.py 1 # Prompt the user to enter three numbers 2 number1, number2, number3 = eval(input( 3 “Enter three numbers separated by commas: “)) 4 5 # Compute average 6 average = (number1 + number2 + number3) / 3 7 8 # Display result 9 print(“The average of”, number1, number2, number3 10 “is”, average)

benefits of constants

40 Chapter 2 Elementary Programming

2.8 Numeric Data Types and Operators Python has two numeric types—integers and floating-point numbers—for working with the operators +, -, *, /, //, **, and %.

The information stored in a computer is generally referred to as data. There are two types of numeric data: integers and real numbers. Integer types (int for short) are for represent- ing whole numbers. Real types are for representing numbers with a fractional part. Inside the computer, these two types of data are stored differently. Real numbers are represented as floating-point (or float) values. How do we tell Python whether a number is an integer or a float? A number that has a decimal point is a float even if its fractional part is 0. For example, 1.0 is a float, but 1 is an integer. These two numbers are stored differently in the computer. In the programming terminology, numbers such as 1.0 and 1 are called literals. A literal is a constant value that appears directly in a program.

The operators for numeric data types include the standard arithmetic operators, as shown in Table 2.1. The operands are the values operated by an operator.

floating-point numbers

integer

int

float

operands

operators +, -, *, /, //, **, %

unary operator

binary operator

/ operator

TABLE 2.1 Numeric Operators

Name Meaning Example Result

+ Addition 34 + 1 35

– Subtraction 34.0 – 0.1 33.9

* Multiplication 300 * 30 9000

/ Float Division 1 / 2 0.5

// Integer Division 1 // 2 0

** Exponentiation 4 ** 0.5 2.0

% Remainder 20 % 3 2

The +, -, and * operators are straightforward, but note that the + and – operators can be both unary and binary. A unary operator has only one operand; a binary operator has two. For example, the – operator in -5 is a unary operator to negate the number 5, whereas the – oper- ator in 4 – 5 is a binary operator for subtracting 5 from 4.

2.8.1 The /, //, and ** Operators The / operator performs a float division that results in a floating number. For example,

>>> 4 / 2 2.0 >>> 2 / 4 0.5 >>>

Key Point

VideoNote Perform computation

literal

>>> 5 // 2 2 >>> 2 // 4 0 >>>

The // operator performs an integer division; the result is an integer, and any fractional part is truncated. For example,

// operator

2.8 Numeric Data Types and Operators 41

To compute (a with an exponent of b) for any numbers a and b, you can write a ** b in Python. For example,

ab ** exponent operator

>>> 2.3 ** 3.5 18.45216910555504 >>> (-2.5) ** 2 6.25 >>>

2.8.2 The % Operator The % operator, known as remainder or modulo operator, yields the remainder after division. The left-side operand is the dividend and the right-side operand is the divisor. Therefore, 7 % 3 yields 1, 3 % 7 yields 3,12 % 4 yields 0, 26 % 8 yields 2, and 20 % 13 yields 7.

% operator

4 12

12 0

3

8 26

24 2

3

Remainder

Quotient

Divisor Dividend13 20

13 7

1

7 3

0 3

0

3 7

6 1

2

The remainder operator is very useful in programming. For example, an even number % 2 is always 0 and an odd number % 2 is always 1. Thus, you can use this property to determine whether a number is even or odd. If today is Saturday, it will be Saturday again in 7 days. Sup- pose you and your friends are going to meet in 10 days. What day is in 10 days? You can find that the day is Tuesday using the following expression:

Listing 2.5 shows a program that obtains minutes and remaining seconds from an amount of time in seconds. For example, 500 seconds contains 8 minutes and 20 seconds.

input seconds

get minutes

LISTING 2.5 DisplayTime.py 1 # Prompt the user for input 2 seconds = eval(input(“Enter an integer for seconds: “)) 3 4 # Get minutes and remaining seconds 5 minutes = seconds // 60 # Find minutes in seconds 6 remainingSeconds = seconds % 60 # Seconds remaining 7 print(seconds, “seconds is”, minutes, 8 “minutes and”, remainingSeconds, “seconds”)

get remainingSeconds

Enter an integer for seconds: 500 seconds is 8 minutes and 20 seconds

500

(6 + 10) % 7 is 2

After 10 days

Day 2 in a week is Tuesday Note: Day 0 in a week is Sunday

A week has 7 days Day 6 in a week is Saturday

42 Chapter 2 Elementary Programming

Line 2 reads an integer for seconds. Line 5 obtains the minutes using seconds // 60. Line 6 (seconds % 60) obtains the remaining seconds after taking away the minutes.

2.8.3 Scientific Notation Floating-point values can be written in scientific notation in the form of For example, the scientific notation for 123.456 is and for 0.0123456 is Python uses a special syntax to write scientific notation numbers. For example, is written as 1.23456E2 or 1.23456E+2, and as 1.23456E-2. The letter E (or e) represents an exponent and can be in either lowercase or uppercase.

Note The float type is used to represent numbers with a decimal point. Why are they called floating-point numbers? These numbers are stored in scientific notation in memory. When a number such as 50.534 is converted into scientific notation, such as 5.0534E+1, its decimal point is moved (floated) to a new position.

Caution When a variable is assigned a value that is too large (in size) to be stored in memory, it causes overflow. For example, executing the following statement causes overflow.

1.23456 * 10-2 1.23456 * 102

1.23456 * 10-2.1.23456 * 102 a * 10b.scientific notation

why called floating point?

what is overflow?

line# seconds minutes remainingSeconds

2 500

5 8

6 20

>>> 245.0 ** 1000 OverflowError: ‘Result too large’ >>>

When a floating-point number is too small (that is, too close to zero), it causes underflow and Python approximates it to zero. Therefore, usually you don’t need to be concerned with underflow.

2.11 What are the results of the following expressions?

Expression Result

42 / 5 _____

42 // 5 _____

42 % 5 _____

40 % 5 _____

1 % 2 _____

2 % 1 _____

45 + 4 * 4 – 2 _____

45 + 43 % 5 * (23 * 3 % 2) _____

5 ** 2 _____

5.1 ** 2 _____

what is underflow?

✓Point✓Check

2.9 Evaluating Expressions and Operator Precedence 43

evaluate an expression

2.12 If today is Tuesday, what day of the week will it be in 100 days? 2.13 What is the result of 25 / 4? How would you rewrite the expression if you wished

the result to be an integer number?

2.9 Evaluating Expressions and Operator Precedence Python expressions are evaluated in the same way as arithmetic expressions.

Writing a numeric expression in Python involves a straightforward translation of an arith- metic expression using operators. For example, the arithmetic expression

can be translated into a Python expression as:

(3 + 4 * x) / 5 – 10 * (y – 5) * (a + b + c) / x + 9 * (4 / x + (9 + x) / y)

Though Python has its own way to evaluate an expression behind the scene, the results of a Python expression and its corresponding arithmetic expression are the same. Therefore, you can safely apply the arithmetic rules for evaluating a Python expression. Operators con- tained within pairs of parentheses are evaluated first. Parentheses can be nested, in which case the expression in the inner parentheses is evaluated first. When more than one operator is used in an expression, the following operator precedence rule is used to determine the order of evaluation.

■ Exponentiation (**) is applied first.

■ Multiplication (*), float division (/), integer division (//) , and remainder operators (%) are applied next. If an expression contains several multiplication, division, and remainder operators, they are applied from left to right.

■ Addition (+) and subtraction (-) operators are applied last. If an expression contains several addition and subtraction operators, they are applied from left to right.

Here is an example of how an expression is evaluated:

3 + 4x 5

– 10(y – 5)(a + b + c)

x + 9¢4

x +

9 + x y ≤

Key Point

operator precedence rule

3 + 4 * 4 + 5 * (4 + 3) – 1

3 + 4 * 4 + 5 * 7 – 1

3 + 16 + 5 * 7 – 1

3 + 16 + 35 – 1

19 + 35 – 1

54 – 1

53

(1) inside parentheses first

(2) multiplication

(3) multiplication

(4) addition

(5) addition

(6) subtraction

44 Chapter 2 Elementary Programming

addition assignment operator

TABLE 2.2 Augmented Assignment Operators

Operator Name Example Equivalent

+= Addition assignment i += 8 i = i + 8

-= Subtraction assignment i -= 8 i = i – 8

*= Multiplication assignment i *= 8 i = i * 8

/= Float division assignment i /= 8 i = i / 8

//= Integer division assignment i //= 8 i = i // 8

%= Remainder assignment i %= 8 i = i % 8

**= Exponent assignment i **= 8 i = i ** 8

✓Point✓Check

Key Point

augmented assignment

compound assignment

2.14 How would you write the following arithmetic expression in Python?

2.15 Suppose m and r are integers. Write a Python expression for mr2.

2.10 Augmented Assignment Operators The operators +, -, *, /, //, %, and ** can be combined with the assignment operator (=) to form augmented assignment operators.

Very often the current value of a variable is used, modified, and then reassigned back to the same variable. For example, the following statement increases the variable count by 1:

count = count + 1

Python allows you to combine assignment and addition operators using an augmented (or compound) assignment operator. For instance, the preceding statement can be written as:

count += 1

The += operator is called the addition assignment operator. All augmented assignment operators are shown in Table 2.2.

4

3(r + 34) – 9(a + bc) +

3 + d(2 + a) a + bd

Caution There are no spaces in the augmented assignment operators. For example, + = should be +=.

2.16 Assume that a = 1, and that each expression is independent. What are the results of the following expressions? a += 4 a -= 4 a *= 4 a /= 4 a //= 4 a %= 4 a = 56 * a + 6

✓Point✓Check

2.11 Type Conversions and Rounding 45

2.11 Type Conversions and Rounding If one of the operands for the numeric operators is a float value, the result will be a float value.

Can you perform binary operations with two operands of different types? Yes. If an integer and a float are involved in a binary operation, Python automatically converts the integer to a float value. This is called type conversion. So, 3 * 4.5 is the same as 3.0 * 4.5.

Sometimes, it is desirable to obtain the integer part of a fractional number. You can use the int(value) function to return the integer part of a float value. For example,

>>> value = 5.6 >>> int(value) 5 >>>

Note that the fractional part of the number is truncated, not rounded up. You can also use the round function to round a number to the nearest whole value. For

example,

>>> value = 5.6 >>> round(value) 6 >>>

We will discuss the round function more in Chapter 3.

Note The functions int and round do not change the variable being converted. For exam- ple, value is not changed after invoking the function in the following code:

>>> value = 5.6 >>> round(value) 6 >>> value 5.6 >>>

round function

type conversion

int function

Key Point

Note The int function can also be used to convert an integer string into an integer. For example, int(“34”) returns 34. So you can use the eval or int function to convert a string into an integer. Which one is better? The int function performs a sim- ple conversion. It does not work for a non-integer string. For example, int(“3.4”) will cause an error. The eval function does more than a simple conversion. It can be used to evaluate an expression. For example, eval(“3 + 4”) returns 7. However, there is a subtle “gotcha” for using the eval function. The eval function will pro- duce an error for a numeric string that contains leading zeros. In contrast, the int function works fine for this case. For example, eval(“003”) causes an error, but int(“003”) returns 3.

int vs. eval functions

46 Chapter 2 Elementary Programming

format

Enter purchase amount: Sales tax is 11.85

197.55

The value of the variable purchaseAmount is 197.55 (line 2). The sales tax is 6% of the purchase, so the tax is evaluated as 11.853 (line 5). Note that

tax * 100 is 1185.3 int(tax * 100) is 1185 int(tax * 100) / 100.0 is 11.85

So, the statement in line 8 displays the tax 11.85 with two digits after the decimal point.

2.17 What does a conversion from a float to an integer do with the fractional part of the float value? Does the int(value) function change the variable value?

2.18 Are the following statements correct? If so, show their printout. value = 4.6 print(int(value)) print(round(value)) print(eval(“4 * 5 + 2”)) print(int(“04”)) print(int(“4.5”)) print(eval(“04”))

2.12 Case Study: Displaying the Current Time You can use the time() function in the time module to obtain the current system time.

The problem is to develop a program that displays the current time in Greenwich Mean Time (GMT) in the format hour:minute:second, such as 13:19:18.

The time() function in the time module returns the current time in seconds with millisecond precision elapsed since the time 00:00:00 on January 1, 1970 GMT, as shown in Figure 2.1. This time is known as the UNIX epoch. The epoch is the point when time starts. 1970 was the year when the UNIX operating system was formally introduced. For

format numbers

UNIX epoch

line# purchaseAmount tax output

2 197.55

5 11.853

8 11.85

Listing 2.6 shows a program that displays the sales tax with two digits after the decimal point.

LISTING 2.6 SalesTax.py 1 # Prompt the user for input 2 purchaseAmount = eval(input(“Enter purchase amount: “)) 3 4 # Compute sales tax 5 tax = purchaseAmount * 0.06 6 7 # Display tax amount with two digits after decimal point 8 print(“Sales tax is”, int(tax * 100) / 100.0)

input purchaseAmount

compute tax

✓Point✓Check

Key Point

2.12 Case Study: Displaying the Current Time 47

time.time()example, time.time() returns 1285543663.205, which means 1285543663 seconds and 205 milliseconds.

You can use this function to obtain the current time, and then compute the current second, minute, and hour as follows.

1. Obtain the current time (since midnight, January 1, 1970) by invoking time.time() (for example, 1203183068.328).

2. Obtain the total seconds totalSeconds using the int function (int(1203183068.328) 1203183068).

3. Compute the current second from totalSeconds % 60 (1203183068 seconds % 60 8, which is the current second).

4. Obtain the total minutes totalMinutes by dividing totalSeconds by 60 (1203183068 seconds // 60 20053051 minutes).

5. Compute the current minute from totalMinutes % 60 (20053051minutes % 60 31, which is the current minute).

6. Obtain the total hours totalHours by dividing totalMinutes by 60 (20053051 minutes // 60 334217 hours).

7. Compute the current hour from totalHours % 24 (334217 hours % 24 17, which is the current hour).

Listing 2.7 gives the complete program.

LISTING 2.7 ShowCurrentTime.py 1 import time 2 3 currentTime = time.time() # Get current time 4 5 # Obtain the total seconds since midnight, Jan 1, 1970 6 totalSeconds = int(currentTime) 7 8 # Get the current second 9 currentSecond = totalSeconds % 60 10 11 # Obtain the total minutes 12 totalMinutes = totalSeconds // 60 13 14 # Compute the current minute in the hour 15 currentMinute = totalMinutes % 60 16 17 # Obtain the total hours 18 totalHours = totalMinutes // 60 19 20 # Compute the current hour 21 currentHour = totalHours % 24

=

=

=

=

=

=

import time module

currentTime

totalSeconds

currentSecond

UNIX epoch 01-01-1970

00:00:00 GMT

Elapsed time

Current Time time.time ()

Time

FIGURE 2.1 The time.time() function returns the seconds with millisecond precision since the UNIX epoch.

totalMinutes

currentMinute

totalHours

currentHour

48 Chapter 2 Elementary Programming

display output

Current time is 17:31:8 GMT

Line 3 invokes time.time() to return the current time in seconds as a float value with millisecond precision. The seconds, minutes, and hours are extracted from the current time using the // and % operators (lines 6–21).

In the sample run, a single digit 8 is displayed for the second. The desirable output would be 08. This can be fixed by using a function that formats a single digit with a prefix 0 (see Exercise 6.48).

2.19 What is the UNIX epoch? 2.20 What does time.time() return? 2.21 How do you obtain the seconds from the returned value for time.time()?

2.13 Software Development Process The software development life cycle is a multistage process that includes requirements specification, analysis, design, implementation, testing, deployment, and maintenance.

Developing a software product is an engineering process. Software products, no matter how large or how small, have the same life cycle: requirements specification, system analysis, system design, implementation, testing, deployment, and maintenance, as shown in Figure 2.2.

Requirements specification is a formal process that seeks to understand the problem that the software will address and to document in detail what the software system needs to do. This phase involves close interaction between users and developers. Most of the examples in

line#

variables

3 6 9 12 15 18 21

currentTime 1203183068.328

totalSeconds 1203183068

currentSecond 8

totalMinutes 20053051

currentMinute 31

totalHours 334217

currentHour 17

requirements specification

22 23 # Display results 24 print(“Current time is”, currentHour, “:”, 25 currentMinute, “:”, currentSecond, “GMT”)

✓Point✓Check

Key Point

2.13 Software Development Process 49

system analysis

system design

this book are simple, and their requirements are clearly stated. In the real world, however, problems are not always well defined. Developers need to work closely with their customers (the individuals or organizations that will use the software) and study the problem carefully to identify what the software needs to do.

System analysis seeks to analyze the data flow and to identify the system’s input and output. When you do analysis, it helps to identify what the output is first, and then figure out what input data you need in order to produce the output.

System design is to design a process for obtaining the output from the input. This phase involves the use of many levels of abstraction to decompose the problem into manageable components, and design strategies for implementing each component. You can view a compo- nent as a subsystem that performs a specific function of the system. The essence of system analysis and design is input, process, and output (IPO).

Implementation involves translating the system design into programs. Separate programs are written for each component and then integrated to work together. This phase requires the use of a programming language such as Python. The implementation involves coding, self testing, and debugging (that is, finding errors, called bugs, in the code).

Testing ensures that the code meets the requirements specification and weeds out bugs. An independent team of software engineers not involved in the design and implementation of the product usually conducts such testing.

Deployment makes the software available for use. Depending on the type of the soft- ware, it may be installed on each user’s machine or installed on a server accessible on the Internet.

Maintenance is concerned with updating and improving the product. A software product must continue to perform and improve in an ever-evolving environment. This requires periodic upgrades of the product to fix newly discovered bugs and incorporate changes.

To see the software development process in action, we will now create a program that computes loan payments. The loan can be a car loan, a student loan, or a home mortgage loan. For an introductory programming course, we focus on requirements specification, analysis, design, implementation, and testing.

Requirements Specification

System Analysis

System Design

Testing

Input, Process, Output IPO

Implementation

Maintenance

Deployment

FIGURE 2.2 At any stage of the software development life cycle, it may be necessary to go back to a previous stage to correct errors or deal with other issues that might prevent the software from functioning as expected.

IPO

implementation

testing

deployment

maintenance

50 Chapter 2 Elementary Programming

Stage 1: Requirements Specification

The program must satisfy the following requirements:

■ It must let the user enter the interest rate, the loan amount, and the number of years for which payments will be made.

■ It must compute and display the monthly payment and total payment amounts.

Stage 2: System Analysis

The output is the monthly payment and total payment, which can be obtained using the fol- lowing formula:

So, the input needed for the program is the annual interest rate, the length of the loan in years, and the loan amount.

Note The requirements specification says that the user must enter the interest rate, the loan amount, and the number of years for which payments will be made. During analysis, however, it is possible that you may discover that input is not sufficient or that some values are unnecessary for the output. If this happens, you can go back to modify the requirements specification.

Note In the real world, you will work with customers from all walks of life. You may develop software for chemists, physicists, engineers, economists, and psychologists and of course, you will not have (or need) the complete knowledge of all these fields. There- fore, you don’t have to know how the mathematical formulas are derived. Nonetheless, given the annual interest rate, number of years, and loan amount, you can use this for- mula to compute the monthly payment. You will, however, need to communicate with the customers and understand how the mathematic model works for the system.

Stage 3: System Design

During system design, you identify the steps in the program:

Step 1. Prompt the user to enter the annual interest rate, number of years, and loan amount.

Step 2. The input for the annual interest rate is a number in percent format, such as 4.5%. The program needs to convert it into a decimal by dividing it by 100. To obtain the monthly interest rate from the annual interest rate, divide it by 12, since a year has 12 months. So to obtain the monthly interest rate in decimal format, you need to divide the annual interest rate in percentage by 1200. For example, if the annual interest rate is 4.5%, then the monthly interest rate is

Step 3. Compute the monthly payment using the formula given in Stage 2.

Step 4. Compute the total payment, which is the monthly payment multiplied by 12 and multiplied by the number of years.

Step 5. Display the monthly payment and total payment.

4.5/1200 = 0.00375.

totalPayment = monthlyPayment * numberOfYears * 12

monthlyPayment = loanAmount * monthlyInterestRate

1 – 1

(1 + monthlyInterestRate)numberOfYears*12

2.13 Software Development Process 51

Stage 4: Implementation

Implementation is also known as coding (writing the code). In the formula, you have to com- pute You can use the exponentiation operator to write it as

(1 + monthlyInterestRate) ** (numberOfYears * 12)

Listing 2.8 gives the complete program.

LISTING 2.8 ComputeLoan.py 1 # Enter annual interest rate as a percentage, e.g., 7.25 2 annualInterestRate = eval(input( 3 “Enter annual interest rate, e.g., 7.25: “)) 4 monthlyInterestRate = annualInterestRate / 1200 5 6 # Enter number of years 7 numberOfYears = eval(input( 8 “Enter number of years as an integer, e.g., 5: “)) 9 10 # Enter loan amount 11 loanAmount = eval(input(“Enter loan amount, e.g., 120000.95: “)) 12 13 # Calculate payment 14 monthlyPayment = loanAmount * monthlyInterestRate / (1 15 – 1 / (1 + monthlyInterestRate) ** (numberOfYears * 12)) 16 totalPayment = monthlyPayment * numberOfYears * 12 17 18 # Display results 19 print(“The monthly payment is”, int(monthlyPayment * 100) / 100) 20 print(“The total payment is”, int(totalPayment * 100) /100)

(1 + monthlyInterestRate)numberOfYears*12.

enter interest rate

obtain monthly interest rate

enter years

enter loan amount

monthlyPayment

totalPayment

display result

line#

variables

2 4 7 11 14 16

annualInterestRate 5.75

monthlyInterestRate 0.0047916666666

numberOfYears 15

loanAmount 250000

monthlyPayment 2076.0252175

totalPayment 373684.539

Enter annual interest rate, e.g., 7.25:

Enter number of years as an integer, e.g., 5:

Enter loan amount, e.g., 120000.95:

The monthly payment is 2076.02

The total payment is 373684.53

250000

15

5.75

52 Chapter 2 Elementary Programming

incremental development and testing

enter x1, y1

enter x2, y2

compute distance

Enter x1 and y1 for Point 1:

Enter x2 and y2 for Point 2:

The distance between the two points is 8.764131445842194

4, 5

1.5, -3.4

The program prompts the user to enter the coordinates of the first point (line 2) and the second point (line 5). It then computes the distance between them (line 8) and displays it (line 10).

Key Point

Line 2 reads the annual interest rate, which is converted into the monthly interest rate in line 4.

The formula for computing the monthly payment is translated into Python code in lines 14–15.

The variable monthlyPayment is 2076.0252175 (line 14). Note that

int(monthlyPayment * 100) is 207602.52175 int(monthlyPayment * 100) / 100.0 is 2076.02

So, the statement in line 19 displays the tax 2076.02 with two digits after the decimal point.

Stage 5: Testing

After the program is implemented, test it with some sample input data and verify whether the output is correct. Some of the problems may involve many cases as you will see in later chap- ters. For this type of problems, you need to design test data that cover all cases.

Tip The system design phase in this example identified several steps. It is a good approach to develop and test these steps incrementally by adding them one at a time. This process makes it much easier to pinpoint problems and debug the program.

2.14 Case Study: Computing Distances This section presents two programs that compute and display the distance between two points.

Given two points, the formula for computing the distance is You can use a ** 0.5 to compute The program in Listing 2.9 prompts the user to enter two points and computes the distance between them.

LISTING 2.9 ComputeDistance.py 1 # Enter the first point with two float values 2 x1, y1 = eval(input(“Enter x1 and y1 for Point 1: “)) 3 4 # Enter the second point with two float values 5 x2, y2 = eval(input(“Enter x2 and y2 for Point 2: “)) 6 7 # Compute the distance 8 distance = ((x1 – x2) * (x1 – x2) + (y1 – y2) * (y1 – y2)) ** 0.5 9 10 print(“The distance between the two points is”, distance)

2a. 2(x2 – x1 )2 + (y2 – y1)2.

format numbers

2.14 Case Study: Computing Distances 53

Figure 2.3 illustrates the program in Listing 2.10. This program

1. Prompts the user to enter two points.

2. Computes the distance between the points.

3. Uses Turtle graphics to display the line that connects the two points.

4. Displays the length of the line at the center of the line.

Listing 2.10 gives the program.

LISTING 2.10 ComputeDistanceGraphics.py 1 import turtle 2 3 # Prompt the user for inputting two points 4 x1, y1 = eval(input(“Enter x1 and y1 for point 1: “)) 5 x2, y2 = eval(input(“Enter x2 and y2 for point 2: “)) 6 7 # Compute the distance 8 distance = ((x1 – x2) ** 2 + (y1 – y2) ** 2) ** 0.5 9 10 # Display two points and the connecting line 11 turtle.penup() 12 turtle.goto(x1, y1) # Move to (x1, y1) 13 turtle.pendown() 14 turtle.write(“Point 1”) 15 turtle.goto(x2, y2) # Draw a line to (x2, y2) 16 turtle.write(“Point 2”) 17 18 # Move to the center point of the line 19 turtle.penup() 20 turtle.goto((x1 + x2) / 2, (y1 + y2) / 2) 21 turtle.write(distance) 22 23 turtle.done()

FIGURE 2.3 The program displays a line and its length.

Enter x1 and y1 for Point 1:

Enter x2 and y2 for Point 2: 49, -85

-50, 34

The program prompts the user to enter the value for two points (x1, y1) and (x2, y2), and computes their distance (lines 4–8). It then moves to (x1, y1) (line 12), displays the

display distance

pause

import turtle

enter x1, y1 enter x2, y2

compute distance

move to point 1

display point 1 draw a line display point 2

move to center

54 Chapter 2 Elementary Programming

CHAPTER SUMMARY 1. You can get input using the input function and convert a string into a numerical

value using the eval function.

2. Identifiers are the names used for elements in a program.

3. An identifier is a sequence of characters of any length that consists of letters, digits, underscores (_), and asterisk signs (*). An identifier must start with a letter or an underscore; it cannot start with a digit. An identifier cannot be a keyword.

4. Variables are used to store data in a program.

5. The equal sign (=) is used as the assignment operator.

6. A variable must be assigned a value before it can be used.

7. There are two types of numeric data in Python: integers and real numbers. Integer types (int for short) are for whole numbers, and real types (also called float) are for numbers with a decimal point.

8. Python provides assignment operators that perform numeric operations: + (addi- tion), – (subtraction), * (multiplication), / (division), // (integer division), % (remainder), and ** (exponent).

9. The numeric operators in a Python expression are applied the same way as in an arith- metic expression.

10. Python provides augmented assignment operators: += (addition assignment), –= (subtraction assignment), *= (multiplication assignment), /= (float division assign- ment), //= (integer division assignment), and %= (remainder assignment). These operators combine the +, -, *, /, //, and % operators and the assignment operator into one augmented operators.

algorithm 32 assignment operator (=) 37 augmented assignment 44 camelCase 36 compound assignment 44 data type 33 expression 37 floating-point numbers 40 identifiers 36 incremental development and testing 52 input, process, output (IPO) 35 keyword 36

line continuation symbol 35 literal 40 operands 40 operators 40 pseudocode 32 reserved word 36 scope of a variable 37 simultaneous assignment 38 system analysis 49 system design 49 type conversion 45 variable 32

text Point 1 (line 14), draws a line from (x1, y1) to (x2, y2) (line 15), and displays the text Point 2 (line 16). Finally, it moves to the center of the line (line 20) and displays the distance (line 21).

KEY TERMS

Programming Exercises 55

11. When evaluating an expression with values of an int type and a float type, Python automatically converts the int value to a float type value.

12. You can convert a float to an int using the int(value) function.

13. System analysis seeks to analyze the data flow and to identify the system’s input and output.

14. System design is the stage when programmers develop a process for obtaining the output from the input.

15. The essence of system analysis and design is input, process, and output. This is called IPO.

TEST QUESTIONS Do test questions for this chapter online at www.cs.armstrong.edu/liang/py/test.html.

PROGRAMMING EXERCISES

Pedagogical Note Instructors may ask you to document analysis and design for selected exercises. You should use your own words to analyze the problem, including the input, output, and what needs to be computed, and describe how to solve the problem in pseudocode.

Debugging Tip Python usually gives a reason for a syntax error. If you don’t know how to correct it, compare your program closely, character by character, with similar examples in the text.

Sections 2.2–2.10 2.1 (Convert Celsius to Fahrenheit) Write a program that reads a Celsius degree from

the console and converts it to Fahrenheit and displays the result. The formula for the conversion is as follows:

fahrenheit = (9 / 5) * celsius + 32

Here is a sample run of the program:

Enter a degree in Celsius: 43 Celsius is 109.4 Fahrenheit

43

2.2 (Compute the volume of a cylinder) Write a program that reads in the radius and length of a cylinder and computes the area and volume using the following formulas:

area = radius * radius * π volume = area * length

Here is a sample run:

learn from examples

document analysis and design

56 Chapter 2 Elementary Programming

*2.5 (Financial application: calculate tips) Write a program that reads the subtotal and the gratuity rate and computes the gratuity and total. For example, if the user enters 10 for the subtotal and 15% for the gratuity rate, the program displays 1.5 as the gratuity and 11.5 as the total. Here is a sample run:

Enter the subtotal and a gratuity rate: The gratuity is 2.35 and the total is 18.04

15.69, 15

**2.6 (Sum the digits in an integer) Write a program that reads an integer between 0 and 1000 and adds all the digits in the integer. For example, if an integer is 932, the sum of all its digits is 14. (Hint: Use the % operator to extract digits, and use the // operator to remove the extracted digit. For instance, 932 % 10 = 2 and 932 // 10 = 93.) Here is a sample run:

Enter a number between 0 and 1000: The sum of the digits is 27

999

**2.7 (Find the number of years and days) Write a program that prompts the user to enter the minutes (e.g., 1 billion), and displays the number of years and days for the minutes. For simplicity, assume a year has 365 days. Here is a sample run:

Enter the number of minutes: 1000000000 minutes is approximately 1902 years and 214 days

1000000000

2.8 (Science: calculate energy) Write a program that calculates the energy needed to heat water from an initial temperature to a final temperature. Your program should

2.4 (Convert pounds into kilograms) Write a program that converts pounds into kilograms. The program prompts the user to enter a value in pounds, converts it to kilograms, and displays the result. One pound is 0.454 kilograms. Here is a sample run:

Enter a value in pounds: 55.5 pounds is 25.197 kilograms

55.5

Enter the radius and length of a cylinder: The area is 95.0331 The volume is 1140.4

5.5, 12

2.3 (Convert feet into meters) Write a program that reads a number in feet, converts it to meters, and displays the result. One foot is 0.305 meters. Here is a sample run:

Enter a value for feet: 16.5 feet is 5.0325 meters

16.5

Programming Exercises 57

Enter the amount of water in kilograms:

Enter the initial temperature:

Enter the final temperature:

The energy needed is 1625484.0

10.5

3.5

55.5

*2.9 (Science: wind-chill temperature) How cold is it outside? The temperature alone is not enough to provide the answer. Other factors including wind speed, relative humidity, and sunshine play important roles in determining coldness outside. In 2001, the National Weather Service (NWS) implemented the new wind-chill tem- perature to measure the coldness using temperature and wind speed. The formula is given as follows:

where is the outside temperature measured in degrees Fahrenheit and v is the speed measured in miles per hour. is the wind-chill temperature. The formula cannot be used for wind speeds below 2 mph or for temperatures below or above 41°F.

Write a program that prompts the user to enter a temperature between and 41°F and a wind speed greater than or equal to 2 and displays the wind-chill tem- perature. Here is a sample run:

-58 �F

-58 �F twc

ta

twc = 35.74 + 0.6215ta – 35.75v0.16 + 0.4275tav0.16

prompt the user to enter the amount of water in kilograms and the initial and final temperatures of the water. The formula to compute the energy is

Q = M * (finalTemperature – initialTemperature) * 4184

where M is the weight of water in kilograms, temperatures are in degrees Celsius, and energy Q is measured in joules. Here is a sample run:

Enter the temperature in Fahrenheit between -58 and 41:

Enter the wind speed in miles per hour:

The wind chill index is -5.56707

6

5.3

*2.10 (Physics: find runway length) Given an airplane’s acceleration a and take-off speed v, you can compute the minimum runway length needed for an airplane to take off using the following formula:

Write a program that prompts the user to enter v in meters/second (m/s) and the acceleration a in meters/second squared and displays the minimum runway length. Here is a sample run:

(m/s2),

length = v2

2a

Enter speed and acceleration:

The minimum runway length for this airplane is 514.286 meters

60, 3.5

58 Chapter 2 Elementary Programming

Enter final account value:

Enter annual interest rate in percent:

Enter number of years:

Initial deposit value is 808.8639197424636

5

4.25

1000

2.12 (Print a table) Write a program that displays the following table:

a b a ** b 1 2 1 2 3 8 3 4 81 4 5 1024 5 6 15625

*2.13 (Split digits) Write a program that prompts the user to enter a four-digit integer and displays the number in reverse order. Here is a sample run:

Enter an integer: 3 1 2 5

3125

*2.14 (Geometry: area of a triangle) Write a program that prompts the user to enter the three points (x1, y1), (x2, y2), and (x3, y3) of a triangle and displays its area. The formula for computing the area of a triangle is

Here is a sample run:

area = 2s(s – side1)(s – side2)(s – side3) s = (side1 + side2 + side3) / 2

Enter three points for a triangle:

The area of the triangle is 33.6 9.5, -3.4

1.5, -3.4, 4.6, 5,

*2.11 (Financial application: investment amount) Suppose you want to deposit a certain amount of money into a savings account with a fixed annual interest rate. What amount do you need to deposit in order to have $5,000 in the account after three years? The initial deposit amount can be obtained using the following formula:

Write a program that prompts the user to enter final account value, annual interest rate in percent, and the number of years, and displays the initial deposit amount. Here is a sample run:

initialDepositAmount = finalAccountValue

(1 + monthlyInterestRate)numberOfMonths

Programming Exercises 59

2.15 (Geometry: area of a hexagon) Write a program that prompts the user to enter the side of a hexagon and displays its area. The formula for computing the area of a

hexagon is where s is the length of a side. Here is a sample run:Area = 323

2 s2,

Enter the side: The area of the hexagon is 78.5895

5.5

2.16 (Physics: acceleration) Average acceleration is defined as the change of velocity divided by the time taken to make the change, as shown in the following formula:

Write a program that prompts the user to enter the starting velocity in meters/second, the ending velocity in meters/second, and the time span t in seconds, and displays the average acceleration. Here is a sample run:

v1

v0

a = v1 – v0

t

Enter v0, v1, and t: The average acceleration is 10.0889

5.5, 50.9, 4.5

*2.17 (Health application: compute BMI) Body mass index (BMI) is a measure of health based on weight. It can be calculated by taking your weight in kilograms and dividing it by the square of your height in meters. Write a program that prompts the user to enter a weight in pounds and height in inches and displays the BMI. Note that one pound is 0.45359237 kilograms and one inch is 0.0254 meters. Here is a sample run:

Enter weight in pounds:

Enter height in inches:

BMI is 26.8573

50

95.5

Sections 2.11–2.13 *2.18 (Current time) Listing 2.7, ShowCurrentTime.py, gives a program that displays the

current time in GMT. Revise the program so that it prompts the user to enter the time zone in hours away from (offset to) GMT and displays the time in the speci- fied time zone. Here is a sample run:

Enter the time zone offset to GMT: The current time is 4:50:34

-5

60 Chapter 2 Elementary Programming

*2.20 (Financial application: calculate interest) If you know the balance and the annual percentage interest rate, you can compute the interest on the next monthly pay- ment using the following formula:

interest = balance * (annualInterestRate / 1200)

Write a program that reads the balance and the annual percentage interest rate and displays the interest for the next month. Here is a sample run:

Enter balance and interest rate (e.g., 3 for 3%): The interest is 2.91667

1000, 3.5

**2.21 (Financial application: compound value) Suppose you save $100 each month into a savings account with an annual interest rate of 5%. Therefore, the monthly inter- est rate is After the first month, the value in the account becomes

100 * (1 + 0.00417) = 100.417

After the second month, the value in the account becomes

(100 + 100.417) * (1 + 0.00417) = 201.252

After the third month, the value in the account becomes

(100 + 201.252) * (1 + 0.00417) = 302.507

and so on.

Write a program that prompts the user to enter a monthly saving amount and displays the account value after the sixth month. Here is a sample run of the program:

0.05/12 = 0.00417.

*2.19 (Financial application: calculate future investment value) Write a program that reads in an investment amount, the annual interest rate, and the number of years, and displays the future investment value using the following formula:

For example, if you enter the amount 1000, an annual interest rate of 4.25%, and the number of years as 1, the future investment value is 1043.33. Here is a sample run:

futureInvestmentValue = investmentAmount * (1 + monthlyInterestRate)numberOfMonths

Enter investment amount:

Enter annual interest rate:

Enter number of years:

Accumulated value is 1043.33

1

4.25

1000

Programming Exercises 61

Enter the monthly saving amount: After the sixth month, the account value is 608.81

100

2.22 (Population projection) Rewrite Exercise 1.11 to prompt the user to enter the number of years and displays the population after that many years. Here is a sample run of the program:

Enter the number of years: The population in 5 years is 325932970

5

(a) (b) (c)

FIGURE 2.4 Four circles are drawn in (a), four hexagons are drawn in (b), and a rectangle is drawn in (c).

Section 2.14 2.23 (Turtle: draw four circles) Write a program that prompts the user to enter the

radius and draws four circles in the center of the screen, as shown in Figure 2.4a.

2.24 (Turtle: draw four hexagons) Write a program that draws four hexagons in the center of the screen, as shown in Figure 2.4b.

**2.25 (Turtle: draw a rectangle) Write a program that prompts the user to enter the center of a rectangle, width, and height, and displays the rectangle, as shown in Figure 2.4c.

**2.26 (Turtle: draw a circle) Write a program that prompts the user to enter the center and radius of a circle, and then displays the circle and its area, as shown in Figure 2.5.

FIGURE 2.5 A circle and its area are displayed.

This page intentionally left blank

MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS

Objectives ■ To solve mathematics problems by using the functions in the math

module (§3.2).

■ To represent and process strings and characters (§§3.3–3.4).

■ To encode characters using ASCII and Unicode (§§3.3.1–3.3.2).

■ To use the ord function to obtain a numerical code for a character and the chr function to convert a numerical code to a character (§3.3.3).

■ To represent special characters using the escape sequence (§3.3.4).

■ To invoke the print function with the end argument (§3.3.5).

■ To convert numbers to a string using the str function (§3.3.6).

■ To use the + operator to concatenate strings (§3.3.7).

■ To read strings from the keyboard (§3.3.8).

■ To introduce objects and methods (§3.5).

■ To format numbers and strings using the format function (§3.6).

■ To draw various shapes (§3.7).

■ To draw graphics with colors and fonts (§3.8).

CHAPTER

3

64 Chapter 3 Mathematical Functions, Strings, and Objects

3.1 Introduction The focus of this chapter is to introduce functions, strings, and objects, and to use them to develop programs.

The preceding chapter introduced fundamental programming techniques and taught you how to write simple programs to solve basic problems. This chapter introduces Python functions for performing common mathematical operations. You will learn how to create custom func- tions in Chapter 6.

Suppose you need to estimate the area enclosed by four cities, given the GPS locations (lat- itude and longitude) of these cities, as shown in the following diagram. How would you write a program to solve this problem? You will be able to write such a program after completing this chapter.

problem

Orlando (28.5383355, –81.3792365)

Savannah (32.0835407, –81.0998342)

Charlotte (35.2270869, –80.8431267)

Atlanta (33.7489954, –84.3879824)

Because all data in Python are objects, it is beneficial to introduce objects early so that you can begin to use them to develop useful programs. This chapter gives a brief introduction to objects and strings; you will learn more on objects and strings in Chapters 7 and 8.

3.2 Common Python Functions Python provides many useful functions for common programming tasks.

A function is a group of statements that performs a specific task. Python, as well as other programming languages, provides a library of functions. You have already used the func- tions eval, input, print, and int. These are built-in functions and they are always avail- able in the Python interpreter. You don’t have to import any modules to use these functions. Additionally, you can use the built-in functions abs, max, min, pow, and round, as shown in Table 3.1.

Key Point

Key Point

function

TABLE 3.1 Simple Python Built-in Functions

Function Description Example

abs(x) Returns the absolute value for x. abs(-2) is 2

max(x1, x2, …) Returns the largest among x1, x2, … max(1, 5, 2) is 5

min(x1, x2, …) Returns the smallest among x1, x2, … min(1, 5, 2) is 1

pow(a, b) Returns ab. Same as a ** b. pow(2, 3) is 8

round(x) Returns an integer nearest to x. If x is equally close to two integers, the even one is returned.

round(5.4) is 5

round(5.5) is 6

round(4.5) is 4

round(x, n) Returns the float value rounded to n digits after the decimal point.

round(5.466, 2) is 5.47

round(5.463, 2) is 5.46

3.2 Common Python Functions 65

>>> abs(-3) # Returns the absolute value 3 >>> abs(-3.5) # Returns the absolute value 3.5 >>> max(2, 3, 4, 6) # Returns the maximum number 6 >>> min(2, 3, 4) # Returns the minimum number 2 >>> pow(2, 3) # Same as 2 ** 3 8 >>> pow(2.5, 3.5) # Same as 2.5 ** 3.5 24.705294220065465 >>> round(3.51) # Rounds to its nearest integer 4 >>> round(3.4) # Rounds to its nearest integer 3 >>> round(3.1456, 3) # Rounds to 3 digits after the decimal point 3.146 >>>

Many programs are created to solve mathematical problems. The Python math module provides the mathematical functions listed in Table 3.2.

Two mathematical constants, pi and e, are also defined in the math module. They can be accessed using math.pi and math.e. Listing 3.1 is a program that tests some math func- tions. Because the program uses the math functions defined in the math module, the math module is imported in line 1.

For example,

TABLE 3.2 Mathematical Functions

Function Description Example

fabs(x) Returns the absolute value for x as a float. fabs(-2) is 2.0

ceil(x) Rounds x up to its nearest integer and returns that integer. ceil(2.1) is 3 ceil(-2.1) is -2

floor(x) Rounds x down to its nearest integer and returns that integer. floor(2.1) is 2 floor(-2.1) is -3

exp(x) Returns the exponential function of x (ex). exp(1) is 2.71828

log(x) Returns the natural logarithm of x. log(2.71828) is 1.0

log(x, base) Returns the logarithm of x for the specified base. log(100, 10) is 2.0

sqrt(x) Returns the square root of x. sqrt(4.0) is 2

sin(x) Returns the sine of x. x represents an angle in radians. sin(3.14159 / 2) is 1 sin(3.14159) is 0

asin(x) Returns the angle in radians for the inverse of sine. asin(1.0) is 1.57 asin(0.5) is 0.523599

cos(x) Returns the cosine of x. x represents an angle in radians. cos(3.14159 / 2) is 0 cos(3.14159) is -1

acos(x) Returns the angle in radians for the inverse of cosine. acos(1.0) is 0 acos(0.5) is 1.0472

tan(x) Returns the tangent of x. x represents an angle in radians. tan(3.14159 / 4) is 1 tan(0.0) is 0

degrees(x) Converts angle x from radians to degrees. degrees(1.57) is 90

radians(x) Converts angle x from degrees to radians. radians(90) is 1.57

66 Chapter 3 Mathematical Functions, Strings, and Objects

You can use the math functions to solve many computational problems. Given the three vertices of a triangle, for example, you can compute the angles by using the following formula:

import math module

enter three points

compute edges

A = acos((a * a – b * b – c * c) / (-2 * b * c))

B = acos((b * b – a * a – c * c) / (-2 * a * c))

C = acos((c * c – b * b – a * a) / (-2 * a * b))

LISTING 3.1 MathFunctions.py 1 # import math module to use the math functions 2 3 # Test algebraic functions 4 print(“exp(1.0) =”, ) 5 print(“log(2.78) =”, ) 6 print(“log10(10, 10) =”, ) 7 print(“sqrt(4.0) =”, ) 8 9 # Test trigonometric functions 10 print(“sin(PI / 2) =”, ) 11 print(“cos(PI / 2) =”, ) 12 print(“tan(PI / 2) =”, ) 13 print(“degrees(1.57) =”, ) 14 print(“radians(90) =”, )math.radians(90)

math.degrees(1.57) math.tan(math.pi / 2) math.cos(math.pi / 2) math.sin(math.pi / 2)

math.sqrt(4.0) math.log(10, 10)

math.log(math.e) math.exp(1)

import math

exp(1.0) = 2.71828182846 log(2.78) = 1.0 log10(10, 10) = 1.0 sqrt(4.0) = 2.0 sin(PI / 2) = 1.0 cos(PI / 2) = 6.12323399574e-17 tan(PI / 2) = 1.63312393532e+16 degrees(1.57) = 89.9543738355 radians(90) = 1.57079632679

A

B

C

a

b

c

x1, y1

x2, y2

x3, y3

Don’t be intimidated by the mathematic formula. As we discussed early in Listing 2.8, ComuteLoan.py, you don’t have to know how the mathematical formula is derived in order to write a program for computing the loan payments. Here in this example, given the length of three sides, you can use this formula to write a program to compute the angles without having to know how the formula is derived. In order to compute the lengths of the sides, we need to know the coordinates of three corner points and compute the distances between the points.

Listing 3.2 is an example of a program that prompts the user to enter the x- and y-coordinates of the three corner points in a triangle and then displays the figure’s angles.

LISTING 3.2 ComputeAngles.py 1 import math 2 3 x1, y1, x2, y2, x3, y3 = eval(input(“Enter three points: “)) 4 5 a = math.sqrt((x2 – x3) * (x2 – x3) + (y2 – y3) * (y2 – y3)) 6 b = math.sqrt((x1 – x3) * (x1 – x3) + (y1 – y3) * (y1 – y3)) 7 c = math.sqrt((x1 – x2) * (x1 – x2) + (y1 – y2) * (y1 – y2))

import math module

exp log log10 sqrt

sin cos tan degrees radians

3.3 Strings and Characters 67

compute angles

display result

Enter three points: The three angles are 15.26 90.0 74.74

1, 1, 6.5, 1, 6.5, 2.5

The program prompts the user to enter three points (line 3). This prompting message is not clear. You should give the user explicit instructions on how to enter these points as follows:

input(“Enter six coordinates of three points separated by commas\ like x1, y1, x2, y2, x3, y3: “)

The program computes the distances between the points (lines 5–7), and applies the for- mula to compute the angles (lines 9–11). The angles are rounded to display up to two digits after the decimal point (lines 13–14).

3.1 Evaluate the following functions:

3.2 True or false? The argument for trigonometric functions represents an angle in radians. 3.3 Write a statement that converts 47 degrees to radians and assigns the result to a variable. 3.4 Write a statement that converts π / 7 to an angle in degrees and assigns the result to

a variable.

3.3 Strings and Characters A string (described in Chapter 1) is a sequence of characters. Python treats characters and strings the same way.

In addition to processing numeric values, you can process strings in Python. A string is a sequence of characters and can include text and numbers. String values must be enclosed in matching single quotes (‘) or double quotes (“). Python does not have a data type for charac- ters. A single-character string represents a character. For example,

letter = ‘A’ # Same as letter = “A” numChar = ‘4’ # Same as numChar = “4” message = “Good morning” # Same as message = ‘Good morning’

string

single quotes or double quotes

8 9 A = math.degrees(math.acos((a * a – b * b – c * c) / (-2 * b * c))) 10 B = math.degrees(math.acos((b * b – a * a – c * c) / (-2 * a * c))) 11 C = math.degrees(math.acos((c * c – b * b – a * a) / (-2 * a * b))) 12 13 print(“The three angles are “, round(A * 100) / 100.0, 14 round(B * 100) / 100.0, round(C * 100) / 100.0)

(a) math.sqrt(4) (j) math.floor(-2.5)

(b) math.sin(2 * math.pi) (k) round(3.5)

(c) math.cos(2 * math.pi) (l) round(-2.5)

(d) min(2, 2, 1) (m) math.fabs(2.5)

(e) math.log(math.e) (n) math.ceil(2.5)

(f) math.exp(1) (o) math.floor(2.5)

(g) max(2, 3, 4) (p) round(-2.5)

(h) abs(-2.5) (q) round(2.6)

(i) math.ceil(-2.5) (r) round(math.fabs(-2.5))

✓Point✓Check

Key Point

68 Chapter 3 Mathematical Functions, Strings, and Objects

The first statement assigns a string with the character A to the variable letter. The sec- ond statement assigns a string with the digit character 4 to the variable numChar. The third statement assigns the string Good morning to the variable message.

Note For consistency, this book uses double quotes for a string with more than one character and single quotes for a string with a single character or an empty string. This convention is consistent with other programming languages, so it will be easy for you to convert a Python program to a program written in other languages.

3.3.1 ASCII Code Computers use binary numbers internally (see Section 1.2.2). A character is stored in a computer as a sequence of 0s and 1s. Mapping a character to its binary representation is called character encoding. There are different ways to encode a character. The manner in which characters are encoded is defined by an encoding scheme. One popular standard is ASCII (American Standard Code for Information Interchange), a 7-bit encoding scheme for repre- senting all uppercase and lowercase letters, digits, punctuation marks, and control characters. ASCII uses numbers 0 through 127 to represent characters. Appendix B, The ASCII Charac- ter Set, shows the ASCII code for characters.

3.3.2 Unicode Code Python also supports Unicode. Unicode is an encoding scheme for representing interna- tional characters. ASCII is a small subset of Unicode. Unicode was established by the Unicode Consortium to support the interchange, processing, and display of written texts in the world’s diverse languages. A Unicode starts with \u, followed by four hexadecimal digits that run from \u0000 to \uFFFF. (For information on hexadecimal numbers, see Appendix C.) For example, the word “welcome” is translated into Chinese using two characters, and . The Unicode representations of these two characters are \u6B22\u8FCE.

The program in Listing 3.3 displays two Chinese characters and three Greek letters, as shown in Figure 3.1.

LISTING 3.3 DisplayUnicode.py 1 import turtle 2 3 turtle.write(“\u6B22\u8FCE \u03b1 \u03b2 \u03b3”) 4 5 turtle.done()

character encoding

FIGURE 3.1 You can use Unicode to display international characters in a Python GUI program.

If no Chinese font is installed on your system, you will not be able to see the Chinese char- acters. In this case, delete \u6B22\u8FCE from your program to avoid errors. The Unicode codes for the Greek letters and are \u03b1, \u03b2, and \u03b3.ga, b,

3.3 Strings and Characters 69

>>> ch = ‘a’ >>> ord(ch) 97 >>> chr(98) ‘b’ >>> ord(‘A’) 65 >>>

The ASCII code for a is 97, which is greater than the code for A (65). The ASCII code for lowercase letters are consecutive integers starting from the code for a, then for b, c, and so on, up to the letter z. The same is true for the uppercase letters. The difference between the ASCII code of any lowercase letter and its corresponding uppercase letter is the same: 32. This is a useful property for processing characters. For example, you can find the uppercase represen- tation of any lowercase letter, as shown in the following code:

1 >>> ord(‘a’) – ord(‘A’) 2 32 3 >>> ord(‘d’) – ord(‘D’) 4 32 5 >>> offset = ord(‘a’) – ord(‘A’) 6 >>> lowercaseLetter = ‘h’ 7 >>> uppercaseLetter = chr(ord(lowercaseLetter) – offset) 8 >>> uppercaseLetter 9 ‘H’ 10 >>>

Line 6 assigns a lowercase letter to variable lowercaseLetter. Line 7 obtains its corre- sponding uppercase letter.

3.3.4 Escape Sequences for Special Characters Suppose you want to print a message with quotation marks in the output. Can you write a statement like this?

print(“He said, “John’s program is easy to read””)

No, this statement has an error. Python thinks the second quotation mark is the end of the string and does not know what to do with the rest of the characters.

To overcome this problem, Python uses a special notation to represent special characters, as shown in Table 3.3. This special notation, which consists of a backslash (\) followed by a letter or a combination of digits, is called an escape sequence.

The \n character is also known as a newline, line break or end-of-line (EOL) character, which signifies the end of a line. The \f character forces the printer to print from the next page. The \r character is used to move the cursor to the first position on the same line. The \f and \r characters are rarely used in this book.

backslash (\)

escape sequence

newline

line break

end-of-line (EOL) character

3.3.3 The ord and chr Functions Python provides the ord(ch) function for returning the ASCII code for the character ch and the chr(code) function for returning the character represented by the code. For example,

70 Chapter 3 Mathematical Functions, Strings, and Objects

TABLE 3.3 Python Escape Sequences

Character Escape Sequence Name Numeric Value

\b Backspace 8

\t Tab 9

\n Linefeed 10

\f Formfeed 12

\r Carriage Return 13

\\ Backslash 92

\’ Single Quote 39

\” Double Quote 34

Now you can print the quoted message using the following statement:

>>> print(“He said, \”John’s program is easy to read\””) He said, “John’s program is easy to read”

3.3.5 Printing without the Newline When you use the print function, it automatically prints a linefeed (\n) to cause the out- put to advance to the next line. If you don’t want this to happen after the print function is finished, you can invoke the print function by passing a special argument end = “anyendingstring” using the following syntax:

print(item, end = “anyendingstring”)

For example, the following code

1 print(“AAA”, end = ‘ ‘) 2 print(“BBB”, end = ”) 3 print(“CCC”, end = ‘***’) 4 print(“DDD”, end = ‘***’)

displays

AAA BBBCCC***DDD***

Line 1 prints AAA followed by a space character ‘ ‘, line 2 prints BBB, line 3 prints CCC followed by ***, and line 4 prints DDD followed by ***. Note that ” in line 2 means an empty string. So, nothing is printed for ”.

You can also use the end argument for printing multiple items using the following syntax:

print(item1, item2, …, end = “anyendingstring”)

For example,

radius = 3 print(“The area is”, radius * radius * math.pi, end = ‘ ‘) print(“and the perimeter is”, 2 * radius)

displays

The area is 28.26 and the perimeter is 6

Note that the symbols \ and ” together represent one character.

3.3 Strings and Characters 71

3.3.6 The str Function The str function can be used to convert a number into a string. For example,

>>> s = str(3.4) # Convert a float to string >>> s ‘3.4’ >>> s = str(3) # Convert an integer to string >>> s ‘3’ >>>

3.3.7 The String Concatenation Operator You can use the + operator to add two numbers. The + operator can be used to concatenate two strings. Here are some examples:

1 >>> message = “Welcome ” + “to ” + “Python” 2 >>> message 3 ‘Welcome to Python’ 4 >>> chapterNo = 3 5 >>> s = “Chapter ” + str(chapterNo) 6 >>> s 7 ‘Chapter 3’ 8 >>>

Line 1 concatenates three strings into one. In line 5, the str function converts the numeric value in variable chapterNo to a string. This string is concatenated with “Chapter ” to obtain the new string “Chapter 3″.

The augmented assignment += operator can also be used for string concatenation. For example, the following code concatenates the string in message with the string ” and Python is fun”.

>>> message = “Welcome to Python” >>> message ‘Welcome to Python’ >>> message += ” and Python is fun” >>> message ‘Welcome to Python and Python is fun’ >>>

3.3.8 Reading Strings from the Console To read a string from the console, use the input function. For example, the following code reads three strings from the keyboard:

s1 = input(“Enter a string: “) s2 = input(“Enter a string: “) s3 = input(“Enter a string: “) print(“s1 is ” + s1) print(“s2 is ” + s2) print(“s3 is ” + s3)

72 Chapter 3 Mathematical Functions, Strings, and Objects

Enter a string:

Enter a string:

Enter a string: s1 is Welcome s2 is to s3 is Python

Python

to

Welcome

3.5 Use the ord function to find the ASCII code for 1, A, B, a, and b. Use the chr function to find the character for the decimal codes 40, 59, 79, 85, and 90.

3.6 How do you display the characters \ and “? 3.7 How do you write a character in Unicode? 3.8 Suppose you entered A when running the following code. What is the output?

x = input(“Enter a character: “) ch = chr(ord(x) + 3) print(ch)

3.9 Suppose you entered A and Z when running the following code. What is the output? x = input(“Enter a character: “) y = input(“Enter a character: “) print(ord(y) – ord(x))

3.10 What is wrong in the following code? How do you fix it? title = “Chapter ” + 1

3.11 Show the result of the following code: sum = 2 + 3 print(sum) s = ‘2’ + ‘3’ print(s)

3.4 Case Study: Minimum Number of Coins Now let’s look at a sample program that uses the features covered in this section. Suppose you want to develop a program that classifies a given amount of money into smaller monetary units. The program lets the user enter an amount as a floating-point value representing a total in dollars and cents, and then outputs a report listing the monetary equivalent in dollars, quar- ters, dimes, nickels, and pennies, as shown in the sample run.

Your program should report the maximum number of dollars, then the number of quarters, dimes, nickels, and pennies, in this order, to result in the minimum number of coins.

Here are the steps in developing the program:

1. Prompt the user to enter the amount as a decimal number, such as 11.56.

2. Convert the amount (11.56) into cents (1156).

3. Divide the cents by 100 to find the number of dollars. Obtain the remaining cents using the cents remainder % 100.

4. Divide the remaining cents by 25 to find the number of quarters. Obtain the remaining cents using the remaining cents remainder % 25.

minimum number of coins

✓Point✓Check

3.4 Case Study: Minimum Number of Coins 73

enter input

dollars

quarters

dimes

nickels

5. Divide the remaining cents by 10 to find the number of dimes. Obtain the remaining cents using the remaining cents remainder % 10.

6. Divide the remaining cents by 5 to find the number of nickels. Obtain the remaining cents using the remaining cents remainder % 5.

7. The remaining cents are the pennies.

8. Display the result.

The complete program is shown in Listing 3.4.

LISTING 3.4 ComputeChange.py 1 # Receive the amount 2 amount = eval(input(“Enter an amount, for example, 11.56: “)) 3 4 # Convert the amount to cents 5 remainingAmount = int(amount * 100) 6 7 # Find the number of one dollars 8 numberOfOneDollars = remainingAmount // 100 9 remainingAmount = remainingAmount % 100 10 11 # Find the number of quarters in the remaining amount 12 numberOfQuarters = remainingAmount // 25 13 remainingAmount = remainingAmount % 25 14 15 # Find the number of dimes in the remaining amount 16 numberOfDimes = remainingAmount // 10 17 remainingAmount = remainingAmount % 10 18 19 # Find the number of nickels in the remaining amount 20 numberOfNickels = remainingAmount // 5 21 remainingAmount = remainingAmount % 5 22 23 # Find the number of pennies in the remaining amount 24 numberOfPennies = remainingAmount 25 26 # Display the results 27 print(“Your amount”, amount, “consists of\n”, 28 “\t”, numberOfOneDollars, “dollars\n”, 29 “\t”, numberOfQuarters, “quarters\n”, 30 “\t”, numberOfDimes, “dimes\n”, 31 “\t”, numberOfNickels, “nickels\n”, 32 “\t”, numberOfPennies, “pennies”)

Enter an amount, for example, 11.56: Your amount 11.56 consists of

11 dollars 2 quarters 0 dimes 1 nickels 1 pennies

11.56

pennies

output

74 Chapter 3 Mathematical Functions, Strings, and Objects

The variable amount stores the amount entered from the console (line 2). This variable is not changed, because the amount has to be used at the end of the program to display the results. The program introduces the variable remainingAmount (line 5) to store the chang- ing remainingAmount.

The variable amount is a float representing dollars and cents. It is converted to an integer variable remainingAmount, which represents all the cents. For instance, if amount is 11.56, then the initial remainingAmount is 1156. 1156 // 100 is 11 (line 8). The remainder operator obtains the remainder of the division. So, 1156 % 100 is 56 (line 9).

The program extracts the maximum number of quarters from remainingAmount and obtains a new remainingAmount (lines 12–13). Continuing the same process, the program finds the maximum number of dimes, nickels, and pennies in the remaining amount.

As shown in the sample run, 0 dimes, 1 nickels, and 1 pennies are displayed in the result. It would be better not to display 0 dimes, and to display 1 nickel and 1 penny using the sin- gular forms of the words. You will learn how to use selection statements to modify this pro- gram in the next chapter (see Exercise 4.7).

Caution One serious problem with this example is the possible loss of precision when converting a float amount to the integer remainingAmount. This could lead to an inaccurate result. If you try to enter the amount 10.03, 10.03 * 100 might be 1003.9999999999999. You will find that the program displays 10 dollars and 2 pennies. To fix the problem, enter the amount as an integer value representing cents (see Exercise 3.8).

3.5 Introduction to Objects and Methods In Python, all data—including numbers and strings—are actually objects.

In Python, a number is an object, a string is an object, and every datum is an object. Objects of the same kind have the same type. You can use the id function and type function to get these pieces of information about an object. For example,

loss of precision

object

1 >>> n = 3 # n is an integer 2 >>> id(n) 3 505408904 4 >>> type(n) 5 <class ‘int’> 6 >>> f = 3.0 # f is a float

line# variables

2 5 8 9 12 13 16 17 20 21 24

amount 11.56

remainingAmount 1156 56 6 6 1

numberOfOneDollars 11

numberOfQuarters 2

numberOfDimes 0

numberOfNickels 1

numberOfPennies 1

Key Point

3.5 Introduction to Objects and Methods 75

The id for the object is automatically assigned a unique integer by Python when the program is executed. The id for the object will not be changed during the execution of the program. However, Python may assign a different id every time the program is executed. The type for the object is determined by Python according to the value of the object. Line 2 displays the id for a number object n, line 3 shows the id Python has assigned for the object, and its type is dis- played in line 4.

In Python, an object’s type is defined by a class. For example, the class for string is str (line 15), for integer is int (line 5), and for float is float (line 10). The term “class” comes from object-oriented programming, which will be discussed in Chapter 7. In Python, classes and types are synonymous.

Note The id and type functions are rarely used in programming, but they are good tools for learning more about objects.

A variable in Python is actually a reference to an object. Figure 3.2 shows the relationship between the variables and objects for the preceding code.

id function

type function

objects vs. object reference variable

The object for int 3

n

n = 3 f = 3.0 s = “Welcome”

The object for float

3.0

The object for str

“Welcome”

id: 505408904 id: 26647120 id: 36201472 f s

FIGURE 3.2 In Python, each variable is actually a reference to an object.

The statement n = 3 in line 1 assigns value 3 to n, which actually assigns 3 to an int object referenced by variable n.

Note For n = 3, we say n is an integer variable that holds value 3. Strictly speaking, n is a variable that references an int object for value 3. For simplicity, it is fine to say n is an int variable with value 3.

You can perform operations on an object. The operations are defined using functions. The functions for the objects are called methods in Python. Methods can only be invoked from a specific object. For example, the string type has the methods such as lower() and upper(),

methods

7 >>> id(f) 8 26647120 9 >>> type(f) 10 <class ‘float’> 11 >>> s = “Welcome” # s is a string 12 >>> id(s) 13 36201472 14 >>> type(s) 15 <class ‘str’> 16 >>>

VideoNote

String operations

76 Chapter 3 Mathematical Functions, Strings, and Objects

strip()

whitespace characters

>>> s = “\t Welcome \n”

>>> s1 = # Invoke the strip method >>> s1 ‘Welcome’ >>>

s.strip()

Note If you use Python on Eclipse, Eclipse automatically appends \r in the string entered from the input function. Therefore, you should use the strip() method to remove the \r character as follows:

s = input(“Enter a string”).strip()

More details on processing strings and on object-oriented programming will be discussed in Chapter 7.

3.12 What is an object? What is a method? 3.13 How do you find the id for an object? How do you find the type for an object? 3.14 Which of the following statements is the precise meaning for the statement n = 3?

(a) n is a variable that holds int value 3.

(b) n is a variable that references an object that holds int value 3.

3.15 Suppose s is “\tGeorgia\n”. What is s.lower() and s.upper()? 3.16 Suppose s is ” \tGood\tMorning\n”. What is s.strip()?

3.6 Formatting Numbers and Strings You can use the format function to return a formatted string.

Often it is desirable to display numbers in a certain format. For example, the following code computes interest, given the amount and the annual interest rate.

Python on Eclipse

Line 2 invokes s.lower() on object s to return a new string in lowercase and assigns it to s1. Line 5 invokes s.upper() on object s to return a new string in uppercase and assigns it to s2.

As you can see from the preceding example, the syntax to invoke a method for an object is object.method().

Another useful string method is strip(), which can be used to remove (strip) the whitespace characters from both ends of a string. The characters ‘ ‘, \t, \f, \r, and \n are known as the whitespace characters.

For example,

✓Point✓Check

Key Point

which return a new string in lowercase and uppercase. Here are some examples of how to invoke these methods:

1 >>> s = “Welcome” 2 >>> s1 = # Invoke the lower method 3 >>> s1 4 ‘welcome’ 5 >>> s2 = # Invoke the upper method 6 >>> s2 7 ‘WELCOME’ 8 >>>

s.upper()

s.lower()

3.6 Formatting Numbers and Strings 77

>>> amount = 12618.98 >>> interestRate = 0.0013 >>> interest = amount * interestRate >>> print(“Interest is”, interest) Interest is 16.404674 >>>

Because the interest amount is currency, it is desirable to display only two digits after the decimal point. To do this, you can write the code as follows:

>>> amount = 12618.98 >>> interestRate = 0.0013 >>> interest = amount * interestRate >>> print(“Interest is”, round(interest, )) Interest is 16.4 >>>

2

However, the format is still not correct. There should be two digits after the decimal point like 16.40 rather than 16.4. You can fix it by using the format function, like this: format

>>> amount = 12618.98 >>> interestRate = 0.0013 >>> interest = amount * interestRate >>> print(“Interest is”, ) Interest is 16.40 >>>

format(interest, “.2f”)

The syntax to invoke this function is

format(item, format-specifier)

where item is a number or a string and format-specifier is a string that specifies how the item is formatted. The function returns a string.

3.6.1 Formatting Floating-Point Numbers If the item is a float value, you can use the specifier to give the width and precision of the format in the form of width.precisionf. Here, width specifies the width of the resulting string, precision specifies the number of digits after the decimal point, and f is called the conversion code, which sets the formatting for floating point numbers. For example,

print(format(57.467657, “10.2f”)) print(format(12345678.923, “10.2f”)) print(format(57.4, “10.2f”)) print(format(57, “10.2f”))

displays

conversion code

2 f10 .

field width

precision

conversion code

format specifier

10 57.47

123456782.92 57.40 57.00

where a square box ( ) denotes a blank space. Note that the decimal point is counted as one space.

78 Chapter 3 Mathematical Functions, Strings, and Objects

3.6.2 Formatting in Scientific Notation If you change the conversion code from f to e, the number will be formatted in scientific notation. For example,

print(format(57.467657, “10.2e”)) print(format(0.0033923, “10.2e”)) print(format(57.4, “10.2e”)) print(format(57, “10.2e”))

displays

10 5.75e+01 3.39e-03 5.74e+01 5.70e+01

The + and – signs are counted as places in the width limit.

3.6.3 Formatting as a Percentage You can use the conversion code % to format a number as a percentage. For example,

print(format(0.53457, “10.2%”)) print(format(0.0033923, “10.2%”)) print(format(7.4, “10.2%”)) print(format(57, “10.2%”))

displays

10 53.46% 0.34%

740.00% 5700.00%

10 57.47

57.47

The format(“10.2f”) function formats the number into a string whose width is 10, includ- ing a decimal point and two digits after the point. The number is rounded to two decimal places. Thus there are seven digits allocated before the decimal point. If there are fewer than seven digits before the decimal point, spaces are inserted before the number. If there are more than seven digits before the decimal point, the number’s width is automatically increased. For example, format(12345678.923, “10.2f”) returns 12345678.92, which has a width of 11.

You can omit the width specifier. If so, it defaults to 0. In this case, the width is automati- cally set to the size needed for formatting the number. For example,

print(format(57.467657, “10.2f”)) print(format(57.467657, “.2f”))

displays

The format 10.2% causes the number to be multiplied by 100 and displayed with a % sign following it. The total width includes the % sign counted as one space.

3.6 Formatting Numbers and Strings 79

10 59832

59832 e9b8

e9b8

3.6.4 Justifying Format By default, the format of a number is right justified. You can put the symbol < in the format specifier to specify that the item be left-justified in the resulting format within the specified width. For example,

print(format(57.467657, “10.2f”)) print(format(57.467657, “<10.2f”))

displays

10 57.47

57.47

3.6.5 Formatting Integers The conversion codes d, x, o, and b can be used to format an integer in decimal, hexadecimal, octal, or binary. You can specify a width for the conversion. For example,

print(format(59832, “10d”)) print(format(59832, “<10d”)) print(format(59832, “10x”)) print(format(59832, “<10x”))

displays

The format specifier 10d specifies that the integer is formatted into a decimal with a width of ten spaces. The format specifier 10x specifies that the integer is formatted into a hexadeci- mal integer with a width of ten spaces.

3.6.6 Formatting Strings You can use the conversion code s to format a string with a specified width. For example,

print(format(“Welcome to Python”, “20s”)) print(format(“Welcome to Python”, “<20s”)) print(format(“Welcome to Python”, “>20s”)) print(format(“Welcome to Python and Java”, “>20s”))

displays

20 Welcome to Python Welcome to Python

Welcome to Python Welcome to Python and Java

The format specifier 20s specifies that the string is formatted within a width of 20. By default, a string is left justified. To right-justify it, put the symbol > in the format specifier. If the string is longer than the specified width, the width is automatically increased to fit the string.

Table 3.4 summarizes the format specifiers introduced in this section.

80 Chapter 3 Mathematical Functions, Strings, and Objects

3.17 What is the return value from invoking the format function? 3.18 What happens if the size of the actual item is greater than the width in the format

specifier?

3.19 Show the printout of the following statements: print(format(57.467657, “9.3f”)) print(format(12345678.923, “9.1f”)) print(format(57.4, “.2f”)) print(format(57.4, “10.2f”))

3.20 Show the printout of the following statements: print(format(57.467657, “9.3e”)) print(format(12345678.923, “9.1e”)) print(format(57.4, “.2e”)) print(format(57.4, “10.2e”))

3.21 Show the printout of the following statements: print(format(5789.467657, “9.3f”)) print(format(5789.467657, “<9.3f”)) print(format(5789.4, “.2f”)) print(format(5789.4, “<.2f”)) print(format(5789.4, “>9.2f”))

3.22 Show the printout of the following statements: print(format(0.457467657, “9.3%”)) print(format(0.457467657, “<9.3%”))

3.23 Show the printout of the following statements: print(format(45, “5d”)) print(format(45, “<5d”)) print(format(45, “5x”)) print(format(45, “<5x”))

3.24 Show the printout of the following statements: print(format(“Programming is fun”, “25s”)) print(format(“Programming is fun”, “<25s”)) print(format(“Programming is fun”, “>25s”))

TABLE 3.4 Frequently Used Specifiers

Specifier Format

“10.2f” Format the float item with width 10 and precision 2.

“10.2e” Format the float item in scientific notation with width 10 and precision 2.

“5d” Format the integer item in decimal with width 5.

“5x” Format the integer item in hexadecimal with width 5.

“5o” Format the integer item in octal with width 5.

“5b” Format the integer item in binary with width 5.

“10.2%” Format the number in decimal.

“50s” Format the string item with width 50.

“<10.2f” Left-justify the formatted item.

“>10.2f” Right-justify the formatted item.

✓Point✓Check

3.7 Drawing Various Shapes 81

3.7 Drawing Various Shapes The Python turtle module contains methods for moving the pen, setting the pen’s size, lifting, and putting down the pen.

Chapter 1 introduced drawing with the turtle. A turtle is actually an object that is created when you import the turtle module. You then invoke the turtle object’s methods to perform operations. This section introduces more methods for the turtle object.

When a turtle object is created, its position is set at (0, 0)—the center of the window—and its direction is set to go straight to the right. The turtle module uses a pen to draw shapes. By default, the pen is down (like the tip of an actual pen touching a sheet of paper). When you move the turtle, it draws a line from the current position to the new position if the pen is down. Table 3.5 lists the methods for controlling the pen’s drawing state; Table 3.6 lists the methods for moving the turtle.

turtle’s position and direction

turtle’s pen

TABLE 3.5 Turtle Pen Drawing State Methods

Method Description

turtle.pendown() Pulls the pen down—drawing when moving.

turtle.penup() Pulls the pen up—no drawing when moving.

turtle.pensize(width) Sets the line thickness to the specified width.

All these methods are straightforward. The best way to learn them is to write a test code to see how each method works.

The circle method has three arguments: The radius is required, and extent and step are optional. extent is an angle that determines which part of the circle is drawn. step determines the number of steps to use. If step is 3, 4, 5, 6, …, the circle method will draw a maximum regular polygon with three, four, five, six, or more sides enclosed inside the cir- cle (that is, a triangle, square, pentagon, hexagon, etc.). If step is not specified, the circle method will draw a circle.

TABLE 3.6 Turtle Motion Methods

Method Description

turtle.forward(d) Moves the turtle forward by the specified distance in the direction the turtle is headed.

turtle.backward(d) Moves the turtle backward by the specified distance in the opposite direction the turtle is headed. The turtle’s direction is not changed.

turtle.right(angle) Turns the turtle right by the specified angle.

turtle.left(angle) Turns the turtle left by the specified angle.

turtle.goto(x, y) Moves the turtle to an absolute position.

turtle.setx(x) Moves the turtle’s x-coordinate to the specified position.

turtle.sety(y) Moves the turtle’s y-coordinate to the specified position.

turtle.setheading(angle) Sets the orientation of the turtle to a specified angle. 0-East, 90-North, 180-West, 270-South.

turtle.home() Moves the turtle to the origin (0, 0) and east direction.

turtle.circle(r, ext, step) Draws a circle with the specified radius, extent, and step.

turtle.dot(diameter, color) Draws a circle with the specified diameter and color.

turtle.undo() Undo (repeatedly) the last turtle action(s).

turtle.speed(s) Sets the turtle’s speed to an integer between 1 and 10, with 10 being the fastest.

Key Point

VideoNote

Draw shapes

82 Chapter 3 Mathematical Functions, Strings, and Objects

Listing 3.5 shows sample code for drawing a triangle, a square, a pentagon, a hexagon, and a circle, as shown in Figure 3.3.

LISTING 3.5 SimpleShapes.py 1 import turtle 2 3 # Set pen thickness to 3 pixels 4 # Pull the pen up 5 6 # Pull the pen down 7 # Draw a triangle 8 9 turtle.penup() 10 turtle.goto(-100, -50) 11 turtle.pendown() 12 turtle.circle(40, steps = 4) # Draw a square 13 14 turtle.penup() 15 turtle.goto(0, -50) 16 turtle.pendown() 17 turtle.circle(40, steps = 5) # Draw a pentagon 18 19 turtle.penup() 20 turtle.goto(100, -50) 21 turtle.pendown() 22 turtle.circle(40, steps = 6) # Draw a hexagon 23 24 turtle.penup() 25 turtle.goto(200, -50) 26 turtle.pendown() 27 turtle.circle(40) # Draw a circle 28 29 turtle.done()

Line 1 imports the turtle module. Line 3 sets the pen’s thickness to 3 pixels. Line 4 pulls the pen up so that you can reposition it to (-200, -50) in line 5. Line 6 puts the pen down to draw a triangle in line 7. In line 7, the turtle object invokes the circle method with a radius of 40 and 3 steps to draw a triangle. Similarly, the rest of the program draws a square (line 12), a pentagon (line 17), a hexagon (line 22), and a circle (line 27).

3.25 How do you set the turtle to its original position (0, 0)? 3.26 How do you draw a red dot with diameter 3? 3.27 What figure will the following method draw?

turtle.circle(50, step = 4)

turtle.circle(40, steps = 3) turtle.pendown() turtle.goto(-200, -50) turtle.penup() turtle.pensize(3)

import turtle module

set pen size

FIGURE 3.3 The program draws five shapes.

penup move pen pendown draw a triangle

pause

✓Point✓Check

3.8 Drawing with Colors and Fonts 83

3.28 How do you make the turtle move fast? 3.29 How do you undo the turtle’s last action?

3.8 Drawing with Colors and Fonts A turtle object contains the methods for setting colors and fonts.

The preceding section showed you how to draw shapes with the turtle module. You learned how to use the motion methods to move the pen and use the pen methods to raise the pen up, set it down, and control its thickness. This section introduces more pen control methods and shows you how to set colors and fonts and write text.

Table 3.7 lists the pen methods for controlling drawing, color, and filling. Listing 3.6 is a sample program that draws a triangle, a square, a pentagon, a hexagon, and a circle in differ- ent colors, as shown in Figure 3.4. The program also adds text to the drawing.

TABLE 3.7 Turtle Pen Color, Filling, and Drawing Methods

Method Description

turtle.color(c) Sets the pen color.

turtle.fillcolor(c) Sets the pen fill color.

turtle.begin_fill() Calls this method before filling a shape.

turtle.end_fill() Fills the shapes drawn before the last call to begin_fill.

turtle.filling() Returns the fill state: True if filling, False if not filling.

turtle.clear() Clears the window. The state and the position of the turtle are not affected.

turtle.reset() Clears the window and reset the state and position to the original default value.

turtle.screensize(w, h) Sets the width and height of the canvas.

turtle.hideturtle() Makes the turtle invisible.

turtle.showturtle() Makes the turtle visible.

turtle.isvisible() Returns True if the turtle is visible.

turtle.write(s, font=(“Arial”, 8, “normal”))

Writes the string s on the turtle position. Font is a triple consisting of fontname, fontsize, and fonttype.

LISTING 3.6 ColorShapes.py 1 2 3 turtle.pensize(3) # Set pen thickness to 3 pixels 4 turtle.penup() # Pull the pen up 5 turtle.goto(-200, -50) 6 turtle.pendown() # Pull the pen down 7 # Begin to fill color in a shape 8 9 turtle.circle(40, steps = 3) # Draw a triangle 10 # Fill the shape 11 12 turtle.penup() 13 turtle.goto(-100, -50) 14 turtle.pendown() 15 turtle.begin_fill() # Begin to fill color in a shape 16 turtle.color(“blue”) 17 turtle.circle(40, steps = 4) # Draw a square

turtle.end_fill()

turtle.color(“red”) turtle.begin_fill()

import turtle import turtle module

set pen size penup move pen pendown begin_fill set a color draw a triangle end_fill

Key Point

84 Chapter 3 Mathematical Functions, Strings, and Objects

18 turtle.end_fill() # Fill the shape 19 20 turtle.penup() 21 turtle.goto(0, -50) 22 turtle.pendown() 23 turtle.begin_fill() # Begin to fill color in a shape 24 turtle.color(“green”) 25 turtle.circle(40, steps = 5) # Draw a pentagon 26 turtle.end_fill() # Fill the shape 27 28 turtle.penup() 29 turtle.goto(100, -50) 30 turtle.pendown() 31 turtle.begin_fill() # Begin to fill color in a shape 32 turtle.color(“yellow”) 33 turtle.circle(40, steps = 6) # Draw a hexagon 34 turtle.end_fill() # Fill the shape 35 36 turtle.penup() 37 turtle.goto(200, -50) 38 turtle.pendown() 39 turtle.begin_fill() # Begin to fill color in a shape 40 turtle.color(“purple”) 41 turtle.circle(40) # Draw a circle 42 turtle.end_fill() # Fill the shape 43 turtle.color(“green”) 44 turtle.penup() 45 turtle.goto(-100, 50) 46 turtle.pendown() 47 48 49 50 51 turtle.done()

turtle.hideturtle() font = (“Times”, 18, “bold”))

turtle.write(“Cool Colorful Shapes”,write text

pause

FIGURE 3.4 The program draws five shapes in different colors.

The program is similar to Listing 3.5. SimpleShapes.py, except that it fills each shape with a color and writes a string. The turtle object invokes the begin_fill() method in line 7 to tell Python to draw shapes filled with color. A triangle is drawn in line 9. Invoking the end_fill() method (line 10) completes the color filling for the shape.

The write method writes a string with the specified font at the current pen position (lines 47–48). Note that drawing takes place when the pen is moved if the pen is down. To avoid drawing, you need to pull the pen up. Invoking hideturtle() makes the turtle invisible (line 49) so you will not see the turtle in the window.

Programming Exercises 85

backslash (\) 69 character encoding 68 end-of-line 69 escape sequence 69 line break 69

methods 75 newline 69 object 74 string 67 whitespace characters 76

CHAPTER SUMMARY 1. Python provides the mathematical functions abs, max, min, pow, and round in the

interpreter and the functions fabs, ceil, floor, exp, log, sqrt, sin, asin, cos, acos, tan, degrees, and radians in the math module.

2. A string is a sequence of characters. String values can be enclosed in matching single quotes (‘) or double quotes (“). Python does not have a data type for characters; a single-character string represents a character.

3. An escape sequence is a special syntax that begins with the character \ followed by a letter or a combination of digits to represent special characters, such as \’, \”, \t, and \n.

4. The characters ‘ ‘, \t, \f, \r, and \n are known as the whitespace characters.

5. All data including numbers and strings are objects in Python. You can invoke methods to perform operations on the objects.

6. You can use the format function to format a number or a string and return the result as a string.

TEST QUESTIONS Do test questions for this chapter online at www.cs.armstrong.edu/liang/py/test.html.

PROGRAMMING EXERCISES Section 3.2 3.1 (Geometry: area of a pentagon) Write a program that prompts the user to enter the

length from the center of a pentagon to a vertex and computes the area of the pen- tagon, as shown in the following figure.

3.30 How do you set the turtle’s color? 3.31 How do you fill a shape with color? 3.32 How do you make the turtle invisible?

KEY TERMS

r

✓Point✓Check

86 Chapter 3 Mathematical Functions, Strings, and Objects

Enter the length from the center to a vertex: The area of the pentagon is 108.61

5.5

*3.2 (Geometry: great circle distance) The great circle distance is the distance between two points on the surface of a sphere. Let (x1, y1) and (x2, y2) be the geographical latitude and longitude of two points. The great circle distance between the two points can be computed using the following formula:

Write a program that prompts the user to enter the latitude and longitude of two points on the earth in degrees and displays its great circle distance. The average earth radius is 6,371.01 km. Note that you need to convert the degrees into radians using the math.radians function since the Python trigonometric functions use radians. The latitude and longitude degrees in the formula are for north and west. Use negative to indicate south and east degrees. Here is a sample run:

d = radius * arccos(sin(x1) * sin(x2) + cos(x1) * cos(x2) * cos(y1 – y2))

Enter point 1 (latitude and longitude) in degrees:

Enter point 2 (latitude and longitude) in degrees:

The distance between the two points is 10691.79183231593 km

41.5, 87.37

39.55, -116.25

*3.3 (Geography: estimate areas) Find the GPS locations for Atlanta, Georgia; Orlando, Florida; Savannah, Georgia; and Charlotte, North Carolina from www.gps-data-team.com/map/ and compute the estimated area enclosed by these four cities. (Hint: Use the formula in Programming Exercise 3.2 to compute the distance between two cities. Divide the polygon into two triangles and use the for- mula in Programming Exercise 2.14 to compute the area of a triangle.)

3.4 (Geometry: area of a pentagon) The area of a pentagon can be computed using the following formula (s is the length of a side):

Write a program that prompts the user to enter the side of a pentagon and displays the area. Here is a sample run:

Area = 5 * s2

4 * tan¢p 5 ≤

Enter the side: The area of the pentagon is 53.04444136781625

5.5

The formula for computing the area of a pentagon is where s is

the length of a side. The side can be computed using the formula

where r is the length from the center of a pentagon to a vertex. Here is a sample run:

s = 2r sin p

5 ,

Area = 323

2 s2,

Programming Exercises 87

*3.5 (Geometry: area of a regular polygon) A regular polygon is an n-sided polygon in which all sides are of the same length and all angles have the same degree (i.e., the polygon is both equilateral and equiangular). The formula for computing the area of a regular polygon is

Here, s is the length of a side. Write a program that prompts the user to enter the number of sides and their length of a regular polygon and displays its area. Here is a sample run:

Area = n * s2

4 * tan¢p n ≤

Enter the number of sides:

Enter the side: The area of the polygon is 73.69017017488385

6.5

5

Enter an ASCII code: The character is E

69

3.7 (Random character) Write a program that displays a random uppercase letter using the time.time() function.

*3.8 (Financial application: monetary units) Rewrite Listing 3.4, ComputeChange.py, to fix the possible loss of accuracy when converting a float value to an int value. Enter the input as an integer whose last two digits represent the cents. For exam- ple, the input 1156 represents 11 dollars and 56 cents.

*3.9 (Financial application: payroll) Write a program that reads the following infor- mation and prints a payroll statement:

Employee’s name (e.g., Smith) Number of hours worked in a week (e.g., 10) Hourly pay rate (e.g., 9.75) Federal tax withholding rate (e.g., 20%) State tax withholding rate (e.g., 9%)

A sample run is shown below:

Sections 3.3–3.6 *3.6 (Find the character of an ASCII code) Write a program that receives an ASCII

code (an integer between 0 and 127) and displays its character. For example, if the user enters 97, the program displays the character a. Here is a sample run:

Enter employee’s name:

Enter number of hours worked in a week:

Enter hourly pay rate:

Enter federal tax withholding rate:

Enter state tax withholding rate:

Employee Name: Smith

0.09

0.20

9.75

10

Smith

88 Chapter 3 Mathematical Functions, Strings, and Objects

*3.10 (Turtle: display Unicodes) Write a program to display Greek letters The Unicode of these characters are \u03b1 \u03b2 \u03b3 \u03b4 \u03b5 \u03b6 \u03b7 \u03b8.

3.11 (Reverse number) Write a program that prompts the user to enter a four-digit inte- ger and displays the number in reverse order. Here is a sample run:

abgdPzhu.

Enter an integer: The reversed number is 5213

3125

Sections 3.7–3.8 **3.12 (Turtle: draw a star) Write a program that prompts the user to enter the length of

the star and draw a star, as shown in Figure 3.5a. (Hint: The inner angle of each point in the star is 36 degrees.)

*3.13 (Turtle: display a STOP sign) Write a program that displays a STOP sign, as shown in Figure 3.5b. The hexagon is in red and the text is in white.

3.14 (Turtle: draw the Olympic symbol ) Write a program that prompts the user to enter the radius of the rings and draws an Olympic symbol of five rings of the same size with the colors blue, black, red, yellow, and green, as shown in Figure 3.5c.

*3.15 (Turtle: paint a smiley face) Write a program that paints a smiley face, as shown in Figure 3.6a.

(a) (b) (c)

FIGURE 3.5 The program (a) draws a star, (b) displays a STOP sign, and (c) draws an Olympic symbol.

Hours Worked: 10.0 Pay Rate: $9.75 Gross Pay: $97.5 Deductions: Federal Withholding (20.0%): $19.5 State Withholding (9.0%): $8.77 Total Deduction: $28.27

Net Pay: $69.22

Programming Exercises 89

**3.16 (Turtle: draw shapes) Write a program that draws a triangle, square, pentagon, hexagon, and octagon, as shown in Figure 3.6b. Note that the bottom edges of these shapes are parallel to the x-axis. (Hint: For a triangle with a bottom line parallel to the x-axis, set the turtle’s heading to 60 degrees.)

*3.17 (Turtle: triangle area) Write a program that prompts the user to enter the three points p1, p2, and p3 for a triangle and display its area below the triangle, as shown in Figure 3.7a. The formula for computing the area of a triangle is given in Exercise 2.14.

(a) (b)

FIGURE 3.6 The program paints a smiley face in (a) and draws five shapes with bottom edges parallel to the x-axis in (b).

*3.18 (Turtle: triangle angles) Revise Listing 3.2, ComputeAngles.py, to write a pro- gram that prompts the user to enter the three points p1, p2, and p3 for a triangle and display its angles, as shown in Figure 3.7b.

**3.19 (Turtle: draw a line) Write a program that prompts the user to enter two points and draw a line to connect the points and displays the coordinates of the points, as shown in Figure 3.7c.

(a) (b) (c)

FIGURE 3.7 The program displays (a) the area of the triangle and (b) the angles for the triangle. (c) The program draws a line.

This page intentionally left blank

SELECTIONS

CHAPTER

4

Objectives ■ To write Boolean expressions using comparison operators (§4.2).

■ To generate random numbers using the random.randint(a, b) or random.random() functions (§4.3).

■ To program with Boolean expressions (AdditionQuiz) (§4.3).

■ To implement selection control using one-way if statements (§4.4).

■ To program with one-way if statements (GuessBirthday) (§4.5).

■ To implement selection control using two-way if-else statements (§4.6).

■ To implement selection control with nested if and multi-way if-elif-else statements (§4.7).

■ To avoid common errors in if statements (§4.8).

■ To program with selection statements (§§4.9–4.10).

■ To combine conditions using logical operators (and, or, and not) (§4.11).

■ To use selection statements with combined conditions (LeapYear, Lottery) (§§4.12–4.13).

■ To write expressions that use the conditional expressions (§4.14).

■ To understand the rules governing operator precedence and associativity (§4.15).

■ To detect the location of an object (§4.16).

92 Chapter 4 Selections

4.1 Introduction A program can decide which statements to execute based on a condition.

If you enter a negative value for radius in Listing 2.2, ComputeAreaWithConsoleInput.py, the program displays an invalid result. If the radius is negative, the program cannot compute the area. How can you deal with this situation?

Like all high-level programming languages, Python provides selection statements that let you choose actions with two or more alternative courses. You can use the following selection statement to replace line 5 in Listing 2.2:

if radius < 0: print(“Incorrect input”)

else: area = radius * radius * math.pi print(“Area is”, area)

Selection statements use conditions, which are Boolean expressions. This chapter introduces Boolean types, values, comparison operators, and expressions.

4.2 Boolean Types, Values, and Expressions A Boolean expression is an expression that evaluates to a Boolean value True or False.

How do you compare two values, such as whether a radius is greater than 0, equal to 0, or less than 0? Python provides six comparison operators (also known as relational operators), shown in Table 4.1, which an be used to compare two values (the table assumes that a radius of 5 is being used).

problem

selection statements

Boolean expressions

comparison operators

== vs. =

TABLE 4.1 Comparison Operators

Python Operator

Mathematics Symbol Name

Example (radius is 5) Result

< < less than radius < 0 False

<= < less than or equal to radius <= 0 False

> > greater than radius > 0 True

>= > greater than or equal to radius >= 0 True

== = equal to radius == 0 False

!= � not equal to radius != 0 True

Boolean value

Caution The equal to comparison operator is two equal signs (==), not a single equal sign (=). The latter symbol is for assignment.

The result of the comparison is a Boolean value: True or False. For example, the follow- ing statement displays the result True:

radius = 1 print(radius > 0)

Key Point

Key Point

VideoNote Boolean expressions

4.3 Generating Random Numbers 93

A variable that holds a Boolean value is known as a Boolean variable. The Boolean data type is used to represent Boolean values. A Boolean variable can hold one of the two values: True or False. For example, the following statement assigns the value True to the variable lightsOn:

lightsOn = True

True and False are literals, just like a number such as 10. They are reserved words and cannot be used as identifiers in a program.

Internally, Python uses 1 to represent True and 0 for False. You can use the int function to convert a Boolean value to an integer.

For example,

print(int(True))

displays 1 and

print(int(False))

displays 0. You can also use the bool function to convert a numeric value to a Boolean value. The

function returns False if the value is 0; otherwise, it always returns True. For example,

print(bool(0))

displays False and

print(bool(4))

displays True.

4.1 List six comparison operators. 4.2 Can the following conversions be allowed? If so, find the converted result.

i = int(True) j = int(False)

b1 = bool(4) b2 = bool(0)

4.3 Generating Random Numbers The randint(a, b) function can be used to generate a random integer between a and b, inclusively.

Suppose you want to develop a program to help a first grader practice addition. The program randomly generates two single-digit integers, number1 and number2, and dis- plays to the student a question such as What is 1 + 7, as shown in Listing 4.1. After the student types the answer, the program displays a message to indicate whether it is true or false.

To generate a random number, you can use the randint(a, b) function in the random module. This function returns a random integer i between a and b, inclusively. To obtain a random integer between 0 and 9, use randint(0, 9).

Boolean variable

Boolean literals

convert Boolean to int

bool function

Key Point

✓Point✓Check

94 Chapter 4 Selections

The program may be set up to work as follows:

Step 1: Generate two single-digit integers for number1 (e.g., 4) and number2 (e.g., 5)

Step 2: Prompt the student to answer, “What is 4 + 5?”

Step 3: Check whether the student’s answer is correct.

LISTING 4.1 AdditionQuiz.py 1 import random 2 3 # Generate random numbers 4 5 number2 = random.randint(0, 9) 6 7 # Prompt the user to enter an answer 8 answer = eval(input(“What is ” + + ” + ” 9 + str(number2) + “? “)) 10 11 # Display result 12 print(number1, “+”, number2, “=”, answer, 13 “is”, number1 + number2 == answer)

str(number1)

number1 = random.randint(0, 9)

import random module

generate number1 generate number2

show question

display result

What is 1 + 7? 1 + 7 = 8 is True

8

What is 4 + 8? 4 + 8 = 9 is False

9

The program uses the randint function defined in the random module. The import statement imports the module (line 1).

Lines 4–5 generate two numbers, number1 and number2. Line 8 obtains an answer from the user. The answer is graded in line 12 using a Boolean expression number1 + number2 == answer.

Python also provides another function, randrange(a, b), for generating a random inte- ger between a and b – 1, which is equivalent to randint(a, b – 1). For example, randrange(0, 10) and randint(0, 9) are the same. Since randint is more intuitive, the book generally uses randint in the examples.

You can also use the random() function to generate a random float r such that 0 <= r < 1.0. For example

random module

randrange function

random function

line# number1 number2 answer output

4 4

5 8

8 9

12 4 + 8 = 9 is False

1 >>> import random 2 >>> random.random() 3 0.34343 4 >>> random.random() 5 0.20119 6 >>> random.randint(0, 1)

random.random()

random.random()

random.randint(a, b)

4.4 if Statements 95

random.randrange(a, b)

Invoking random.random() (lines 2 and 4) returns a random float number between 0.0 and 1.0 (excluding 1.0). Invoking random.randint(0, 1) (lines 6 and 8) returns 0 or 1. Invoking random.randrange(0, 1) (line 10) always returns 0.

4.3 How do you generate a random integer i such that 4.4 How do you generate a random integer i such that 4.5 How do you generate a random integer i such that 4.6 How do you generate a random integer 0 or 1?

4.4 if Statements A one-way if statement executes the statements if the condition is true.

The preceding program displays a message such as 6 + 2 = 7 is False. If you wish the message to be 6 + 2 = 7 is incorrect, you have to use a selection statement to make this minor change.

Python has several types of selection statements: one-way if statements, two-way if- else statements, nested if statements, multi-way if-elif-else statements and conditional expressions. This section introduces one-way if statements.

A one-way if statement executes an action if and only if the condition is true. The syntax for a one-way if statement is:

if boolean-expression: statement(s) # Note that the statement(s) must be indented

The statement(s) must be indented at least one space to the right of the if keyword and each statement must be indented using the same number of spaces. For consistency, we indent it four spaces in this book.

The flowchart in Figure 4.1a illustrates how Python executes the syntax of an if state- ment. A flowchart is a diagram that describes an algorithm or process, showing the steps as boxes of various kinds, and their order by connecting these with arrows. Process operations are represented in these boxes, and arrows connecting them show flow of control. A diamond box is used to denote a Boolean condition and a rectangle box is for representing statements.

If the boolean-expression evaluates to true, the statements in the if block are exe- cuted. The if block contains the statements indented after the if statement. For example:

if radius >= 0: area = radius * radius * math.pi print(“The area for the circle of radius”, radius, “is”, area)

The flowchart of the preceding statement is shown in Figure 4.1b. If the value of radius is greater than or equal to 0, then the area is computed and the result is displayed; otherwise, these statements in the block are not executed.

The statements in the if block must be indented in the lines after the if line and each statement must be indented using the same number of spaces. For example, the following code is wrong, because the print statement in line 3 is not indented using the same number of spaces as the statement for computing area in line 2.

1 if radius >= 0: 2 area = radius * radius * math.pi # Compute area 3 print(“The area for the circle of radius”, radius, “is”, area)

10 … i … 50? 10 … i 6 20? 0 … i 6 20?

if statements

if statement

7 0 8 >>> random.randint(0, 1) 9 1 10 >>> random.randrange(0, 1) # This will always be 0 11 0 12 >>>

if block

flowchart

✓Point✓Check

Key Point

BAD CO

DE

96 Chapter 4 Selections

Listing 4.2 is an example of a program that prompts the user to enter an integer. If the num- ber is a multiple of 5, the program displays the result HiFive. If the number is divisible by 2, the program displays HiEven.

LISTING 4.2 SimpleIfDemo.py 1 number = eval(input(“Enter an integer: “)) 2 3 if : 4 print(“HiFive”) 5 6 if : 7 print(“HiEven”)

number % 2 == 0

number % 5 == 0

enter input

check 5

check even

Enter an integer: HiEven

4

Enter an integer: HiFive HiEven

30

The program prompts the user to enter an integer (line 1) and displays HiFive if it is divis- ible by 5 (lines 3–4) and HiEven if it is divisible by 2 (lines 6–7).

4.7 Write an if statement that assigns 1 to x if y is greater than 0. 4.8 Write an if statement that increases pay by 3% if score is greater than 90.

4.5 Case Study: Guessing Birthdays Guessing birthdays is an interesting problem with a simple program solution.

You can find out the date of the month when your friend was born by asking five questions. Each question asks whether the day is in one of the five sets of numbers.

Statement(s)

boolean- expression

true

false

(a)

area = radius * radius * math.pi print(“The area for the circle of”, “radius”, radius, “is”, area)

radius >= 0?

true

false

(b)

FIGURE 4.1 An if statement executes statements if the boolean-expression evaluates to True.

✓Point✓Check

Key Point

4.5 Case Study: Guessing Birthdays 97

day to be determined

in question1?

in question2?

The birthday is the sum of the first numbers in the sets where the date appears. For exam- ple, if the birthday is 19, it appears in Set1, Set2, and Set5. The first numbers in these three sets are 1, 2, and 16. Their sum is 19.

Listing 4.3 is a program that prompts the user to answer whether the day is in Set1 (lines 4–13), in Set2 (lines 16–25), in Set3 (lines 28–37), in Set4 (lines 40–49), or in Set5 (lines 52–61). If the number is in the set, the program adds the first number in the set to day (lines 13, 25, 37, 49, and 61).

LISTING 4.3 GuessBirthday.py 1 # birth day to be determined 2 3 # Prompt the user to answer the first question 4 question1 = “Is your birthday in Set1?\n” + 5 ” 1 3 5 7\n” + \ 6 ” 9 11 13 15\n” + \ 7 “17 19 21 23\n” + \ 8 “25 27 29 31” + \ 9 “\nEnter 0 for No and 1 for Yes: ” 10 answer = eval(input(question1)) 11 12 if : 13 day += 1 14 15 # Prompt the user to answer the second question 16 question2 = “Is your birthday in Set2?\n” + 17 ” 2 3 6 7\n” + \ 18 “10 11 14 15\n” + \ 19 “18 19 22 23\n” + \ 20 “26 27 30 31” + \ 21 “\nEnter 0 for No and 1 for Yes: ” 22 answer = eval(input(question2)) 23 24 if : 25 day += 2 26 27 # Prompt the user to answer the third question 28 question3 = “Is your birthday in Set3?\n” + \ 29 ” 4 5 6 7\n” + \ 30 “12 13 14 15\n” + \ 31 “20 21 22 23\n” + \ 32 “28 29 30 31” + \ 33 “\nEnter 0 for No and 1 for Yes: ” 34 answer = eval(input(question3)) 35 36 if : 37 day += 4

answer == 1

answer == 1

\

answer == 1

\

day = 0

16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

9 10 11 12 13 14 15 24 25 26 27 28 29 30 31

5 6 7 12 13 14 15 20 21 22 23 28 29 30 31

2 3 6 7 10 11 14 15 18 22 23 26 27 30 31

3 5 7 9 11 13 15

17 19 1921 23 25 27 29 31

Set1 Set2 Set3 Set4 Set5

= 19

841

+

in question3?

98 Chapter 4 Selections

38 39 # Prompt the user to answer the fourth question 40 question4 = “Is your birthday in Set4?\n” + \ 41 ” 8 9 10 11\n” + \ 42 “12 13 14 15\n” + \ 43 “24 25 26 27\n” + \ 44 “28 29 30 31” + \ 45 “\nEnter 0 for No and 1 for Yes: ” 46 answer = eval(input(question4)) 47 48 if : 49 day += 8 50 51 # Prompt the user to answer the fifth question 52 question5 = “Is your birthday in Set5?\n” + \ 53 “16 17 18 19\n”+ \ 54 “20 21 22 23\n” + \ 55 “24 25 26 27\n” + \ 56 “28 29 30 31” + \ 57 “\nEnter 0 for No and 1 for Yes: ” 58 answer = eval(input(question5)) 59 60 if : 61 day += 16 62 63 print(“\nYour birthday is “+ str(day) + “!”)

answer == 1

answer == 1

in question4?

in question5?

Is your birthday in Set1? 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 Enter 0 for No and 1 for Yes:

Is your birthday in Set2? 2 3 6 7 10 11 14 15 18 19 22 23 26 27 30 31 Enter 0 for No and 1 for Yes:

Is your birthday in Set3? 4 5 6 7 12 13 14 15 20 21 22 23 28 29 30 31 Enter 0 for No and 1 for Yes:

Is your birthday in Set4? 8 9 10 11 12 13 14 15 24 25 26 27 28 29 30 31 Enter 0 for No and 1 for Yes: 0

0

1

1

4.5 Case Study: Guessing Birthdays 99

Is your birthday in Set5? 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Enter 0 for No and 1 for Yes: Your birthday is 19!

1

The last character \ at the end of lines 4–8 is the line continuation symbol, which tells the interpreter that the statement is continued on the next line (see Section 2.3).

This game is easy to program. You may wonder how the game was created. The mathematics behind the game is actually quite simple. The numbers are not grouped together by accident. The way they are placed in the five sets is deliberate. The starting numbers in the five sets are 1, 2, 4, 8, and 16, which correspond to 1, 10, 100, 1000, and 10000 in binary. A binary number for decimal integers between 1 and 31 has at most five digits, as shown in Figure 4.2a. Assume this number is So,

as shown in Figure 4.2b. If a day’s binary number has a digit 1 in the number should appear in Setk. For example, number 19 is binary 10011, so it appears in Set1, Set2, and Set5. It is binary 1 + 10 + 10000 = 10011 or decimal 1 + 2 + 16 = 19. Number 31 is binary 11111, so it appears in Set1, Set2, Set3, Set4, and Set5. It is binary 1 + 10 + 100 + 1000 + 10000 = 11111 or decimal 1 + 2 + 4 + 8 + 16 = 31.

bk, b5b4b3b2b1 = b50000 + b4000 + b300 + b20 + b1,

b5b4b3b2b1.

mathematics behind the game

line# day answer output

1 0

10 1

13 1

22 1

25 2

34 0

46 0

58 1

61 19

63 Your birthday is 19

Decimal Binary

1 00001 2 00010 3 00011 … 19 10011 … 31 11111

b5 0 0 0 0 10000 b4 0 0 0 1000 b3 0 0 10000 100

b2 0 10 10 + b1 + 1 + 1

b5b4b3b2b1 10011 11111

19 31

(a) A number between 1 and 31 can be represented using a 5-digit binary num- ber. (b) A 5-digit binary number can be obtained by adding binary numbers 1, 10, 100, 1000, or 10000.

FIGURE 4.2

(a) (b)

100 Chapter 4 Selections

4.6 Two-Way if-else Statements A two-way if-else statement decides which statements to execute based on whether the condition is true or false.

A one-way if statement takes an action if the specified condition is True. If the condition is False, nothing is done. But what if you want to take one or more alternative actions when the condition is False? You can use a two-way if-else statement. The actions that a two-way if-else statement specifies differ based on whether the condition is True or False.

Here is the syntax for a two-way if-else statement:

if boolean-expression: statement(s)-for-the-true-case

else: statement(s)-for-the-false-case

The flowchart of the statement is shown in Figure 4.3.

If the boolean-expression evaluates to True, the statement(s) for the true case are exe- cuted; otherwise, the statement(s) for the false case are executed. For example, consider the following code:

if radius >= 0: area = radius * radius * math.pi print(“The area for the circle of radius”, radius, “is”, area)

else: print(“Negative input”)

If radius >= 0 is true, area is computed and displayed; if it is false, the message Negative input is displayed.

Here is another example of the if-else statement. This one determines whether a num- ber is even or odd, as follows:

if number % 2 == 0: print(number, “is even.”)

else: print(number, “is odd.”)

Suppose you want to develop a program for a first grader to practice subtraction. The pro- gram randomly generates two single-digit integers, number1 and number2, with number1 >= number2 and asks the student a question such as “What is 9 – 2? ” After the student enters the answer, the program displays a message indicating whether it is correct.

two-way if-else statement

Statement(s) for the true case Statement(s) for the false case

boolean- expression

true false

FIGURE 4.3 An if-else statement executes statements for the true case if the Boolean expression evaluates to True; otherwise, statements for the false case are executed.

Key Point

4.6 Two-Way if-else Statements 101

The program may work as follows:

Step 1: Generate two single-digit integers for number1 and number2.

Step 2: If number1 < number2, swap number1 with number2.

Step 3: Prompt the student to answer, “What is number1 – number2?”

Step 4: Check the student’s answer and display whether the answer is correct.

The complete program is shown in Listing 4.4.

LISTING 4.4 SubtractionQuiz.py 1 import random 2 3 # 1. Generate two random single-digit integers 4 number1 = random.randint(0, 9) 5 number2 = random.randint(0, 9) 6 7 # 2. If number1 < number2, swap number1 with number2 8 if number1 < number2: 9 number1, number2 = number2, number1 # Simultaneous assignment 10 11 # 3. Prompt the student to answer “What is number1 – number2?” 12 answer = eval(input(“What is “+ str(number1) + ” – ” + 13 str(number2) + “? “)) 14 15 # 4. Check the answer and display the result 16 if number1 – number2 == answer: 17 print(“You are correct!”) 18 else: 19 print(“Your answer is wrong.\n”, number1, ‘-‘, 20 number2, “is”, number1 – number2, ‘.’)

import random module

random numbers

swap if necessary

get answer

check the answer

What is 6 – 6? You are correct!

0

What is 9 – 2? Your answer is wrong. 9 – 2 is 7.

5

line# number1 number2 answer output

4 2

5 9

9 9 2

12 5

19 Your answer is wrong. 9 – 2 is 7.

If number1 number2, the program uses simultaneous assignment to swap the two variables (lines 8–9).

4.9 Write an if statement that increases pay by 3% if score is greater than 90, other- wise it increases pay by 1%.

6

✓Point✓Check

102 Chapter 4 Selections

4.10 What is the printout of the code in (a) and (b) if number is 30 and 35, respectively?

nested if statement

FIGURE 4.4 A preferred format for multiple alternatives is shown in (b) using a multi-way if-elif-else statement.

if number % 2 == 0: print(number, “is even.”)

print(number, “is odd.”)

if number % 2 == 0: print(number, “is even.”)

else print(number, “is odd.”)

(a) (b)

4.7 Nested if and Multi-Way if-elif-else Statements One if statement can be placed inside another if statement to form a nested if statement.

The statement in an if or if-else statement can be any legal Python statement, including another if or if-else statement. The inner if statement is said to be nested inside the outer if statement. The inner if statement can contain another if statement; in fact, there is no limit to the depth of the nesting. For example, the following is a nested if statement:

if i > k: if j > k:

print(“i and j are greater than k”) else:

print(“i is less than or equal to k”)

The if j > k statement is nested inside the if i > k statement. The nested if statement can be used to implement multiple alternatives. The statement

given in Figure 4.4a, for instance, assigns a letter value to the variable grade according to the score, with multiple alternatives.

if score >= 90.0: grade = ‘A’

else: if score >= 80.0:

grade = ‘B’ else:

if score >= 70.0: grade = ‘C’

else: if score >= 60.0:

grade = ‘D’ else:

grade = ‘F’

if score >= 90.0: grade = ‘A’

elif score >= 80.0: grade = ‘B’

elif score >= 70.0: grade = ‘C’

elif score >= 60.0: grade = ‘D’

else: grade = ‘F’

Equivalent

This is better

The execution of how this if statement proceeds is shown in Figure 4.5. The first condi- tion (score >= 90) is tested. If it is True, the grade becomes A. If it is False, the second condition (score >= 80) is tested. If the second condition is True, the grade becomes B. If that condition is False, the third condition and the rest of the conditions (if necessary) are tested until a condition is met or all of the conditions prove to be False. If all of the condi- tions are False, the grade becomes F. Note that a condition is tested only when all of the con- ditions that come before it are False.

(a) (b)

Key Point

4.7 Nested if and Multi-Way if-elif-else Statements 103

The if statement in Figure 4.4a is equivalent to the if statement in Figure 4.4b. In fact, Figure 4.4b is the preferred coding style for multiple alternative if statements. This style, called multi- way if statements, avoids deep indentation and makes the program easier to read. The multi-way if statements uses the syntax if-elif-else; elif (short for else if ) is a Python keyword.

Now let’s write a program to find out the Chinese zodiac sign for a given year. The Chinese zodiac sign is based on a 12-year cycle, and each year in this cycle is represented by an animal— monkey, rooster, dog, pig, rat, ox, tiger, rabbit, dragon, snake, horse, and sheep—as shown in Figure 4.6.

grade = ‘A’

true

false

false

false

false

grade = ‘B’

score >= 80

true

grade = ‘C’

score >= 70

true

grade = ‘D’

score >= 60

true

grade = ‘F’

score >= 90

FIGURE 4.5 You can use a multi-way if-elif-else statement to assign a grade.

rat 0: monkey 1: rooster 2: dog 3: pig 4: rat 5: ox 6: tiger 7: rabbit 8: dragon 9: snake 10: horse 11: sheep

ox

tiger

rabbit

dragon

snakehorse

sheep

monkey

rooster

dog

pig

year % 12 =

FIGURE 4.6 The Chinese zodiac is based on a 12-year cycle.

multi-way if statement

104 Chapter 4 Selections

The value of year % 12 determines the zodiac sign. 1900 is the year of the rat since 1900 % 12 is 4. Listing 4.5 shows a program that prompts the user to specify a year, and then it displays the animal for that year.

LISTING 4.5 ChineseZodiac.py 1 year = eval(input(“Enter a year: “)) 2 zodiacYear = year % 12 3 if zodiacYear == 0: 4 print(“monkey”) 5 elif zodiacYear == 1: 6 print(“rooster”) 7 elif zodiacYear == 2: 8 print(“dog”) 9 elif zodiacYear == 3: 10 print(“pig”) 11 elif zodiacYear == 4: 12 print(“rat”) 13 elif zodiacYear == 5: 14 print(“ox”) 15 elif zodiacYear == 6: 16 print(“tiger”) 17 elif zodiacYear == 7: 18 print(“rabbit”) 19 elif zodiacYear == 8: 20 print(“dragon”) 21 elif zodiacYear == 9: 22 print(“snake”) 23 elif zodiacYear == 10: 24 print(“horse”) 25 else: 26 print(“sheep”)

enter year 12-year cycle determine zodiac sign

Enter a year: rabbit

1963

Enter a year: ox

1877

4.11 Suppose x = 3 and y = 2; show the output, if any, of the following code. What is the output if x = 3 and y = 4? What is the output if x = 2 and y = 2? Draw a flow- chart for the code.

if x > 2: if y > 2:

z = x + y print(“z is”, z)

else: print(“x is”, x)

4.12 Suppose x = 2 and y = 4. Show the output, if any, of the following code. What is the output if x = 3 and y = 2? What is the output if x = 3 and y = 3? (Hint: Indent the statement correctly first.)

✓Point✓Check

4.8 Common Errors in Selection Statements 105

if x > 2: if y > 2:

z = x + y print(“z is”, z)

else: print(“x is”, x)

4.13 What is wrong in the following code?

if score >= 60.0: grade = ‘D’

elif score >= 70.0: grade = ‘C’

elif score >= 80.0: grade = ‘B’

elif score >= 90.0: grade = ‘A’

else: grade = ‘F’

4.8 Common Errors in Selection Statements Most common errors in selection statements are caused by incorrect indentation.

Consider the following code in (a) and (b).

radius = -20

if radius >= 0: area = radius * radius * math.pi

print(“The area is”, area)

radius = -20

if radius >= 0: area = radius * radius * math.pi print(“The area is”, area)

(a) Wrong (b) Correct

In (a), the print statement is not in the if block. To place it in the if block, you have to indent it, as shown in (b).

Consider another example in the following code in (a) and (b). The code in (a) below has two if clauses and one else clause. Which if clause is matched by the else clause? The indentation indicates that the else clause matches the first if clause in (a) and the second if clause in (b).

i = 1 j = 2 k = 3

if i > j: i > k: print(‘A’)

: print(‘B’)

else

if

i = 1 j = 2 k = 3

if i > j: i > k: print(‘A’) : print(‘B’)

else

if

(a) (b)

Since (i > j) is false, the code in (a) displays B, but nothing is displayed from the state- ment in (b).

Key Point

106 Chapter 4 Selections

The code can be simplified by assigning the test value directly to the variable, as shown in (b).

4.14 Which of the following statements are equivalent? Which ones are correctly indented?

if number % 2 == 0: even = True

else: even = False

even = number % 2 == 0

(a) (b)

Equivalent

This is shorter

if i > 0: x = 0 y = 1

else: y = 0 z = 0

if i > 0: x = 0

y = 1 else:

y = 0 z = 0

(a) (b)

if i > 0: x = 0 y = 1

else: y = 0 z = 0

if i > 0: x = 0 y = 1

else: y = 0

z = 0

(c) (d)

4.15 Rewrite the following statement using a Boolean expression:

if count % 10 == 0: newLine = True

else: newLine = False

4.16 Are the following statements correct? Which one is better?

if age < 16: print(“Cannot get a driver’s license”)

if age >= 16: print(“Can get a driver’s license”)

if age < 16: print(“Cannot get a driver’s license”)

else: print(“Can get a driver’s license”)

(a) (b)

4.17 What is the output of the following code if number is 14, 15, and 30?

if number % 2 == 0: print(number, “is even”)

if number % 5 == 0: print(number, “is multiple of 5”)

if number % 2 == 0: print(number, “is even”)

elif number % 5 == 0: print(number, “is multiple of 5”)

(a) (b)

Tip Often new programmers write the code that assigns a test condition to a Boolean variable, like the code in (a):

assign Boolean variable

✓Point✓Check

4.9 Case Study: Computing Body Mass Index 107

Write a program that prompts the user to enter a weight in pounds and height in inches and then displays the BMI. Note that one pound is 0.45359237 kilograms and one inch is 0.0254 meters. Listing 4.6 gives the program.

LISTING 4.6 ComputeBMI.py 1 # Prompt the user to enter weight in pounds 2 weight = eval(input(“Enter weight in pounds: “)) 3 4 # Prompt the user to enter height in inches 5 height = eval(input(“Enter height in inches: “)) 6 7 KILOGRAMS_PER_POUND = 0.45359237 # Constant 8 METERS_PER_INCH = 0.0254 # Constant 9 10 # Compute BMI 11 weightInKilograms = weight * KILOGRAMS_PER_POUND 12 heightInMeters = height * METERS_PER_INCH 13 bmi = weightInKilograms / (heightInMeters * heightInMeters) 14 15 # Display result 16 print(“BMI is”, format(bmi, “.2f”)) 17 if bmi < 18.5: 18 print(“Underweight”) 19 elif bmi < 25: 20 print(“Normal”) 21 elif bmi < 30: 22 print(“Overweight”) 23 else: 24 print(“Obese”)

4.9 Case Study: Computing Body Mass Index You can use nested if statements to write a program that interprets body mass index.

Body mass index (BMI) is a measure of health based on weight. It can be calculated by taking your weight in kilograms and dividing it by the square of your height in meters. The interpre- tation of BMI for people 16 years and older is as follows:

BMI Interpretation

Below 18.5 Underweight

18.5–24.9 Normal

25.0–29.9 Overweight

Above 30.0 Obese

input weight

input height

compute bmi

display output

Enter weight in pounds: Enter height in inches: BMI is 20.95 Normal

70 146

Key Point

108 Chapter 4 Selections

The two named constants, KILOGRAMS_PER_POUND and METERS_PER_INCH, are defined in lines 7–8. Named constants were introduced in Section 2.6. Using named constants here makes programs easy to read. Unfortunately, there is no special syntax for defining named constants in Python. Named constants are treated just like variables in Python. This book uses the format of writing constants in all uppercase letters to distinguish them from variables, and separates the words in constants with an underscore (_).

4.10 Case Study: Computing Taxes You can use nested if statements to write a program for computing taxes.

The United States federal personal income tax is calculated based on filing status and taxable income. There are four filing statuses: single filers, married filing jointly, married filing sepa- rately, and head of household. The tax rates vary every year. Table 4.2 shows the rates for 2009. If you are, say, single with a taxable income of $10,000, the first $8,350 is taxed at 10% and the other $1,650 is taxed at 15%. So, your tax is $1,082.50.

You are to write a program to compute personal income tax. Your program should prompt the user to enter the filing status and taxable income and then compute the tax. Enter 0 for single filers, 1 for married filing jointly, 2 for married filing separately, and 3 for head of household.

Your program computes the tax for the taxable income based on the filing status. The filing status can be determined using if statements outlined as follows:

if status == 0: # Compute tax for single filers

elif status == 1: # Compute tax for married filing jointly

Professional Presentation

Assignment : Professional Presentation

The fifth and final phase is to create a professional presentation to serve as an executive overview detailing all the aspects of the plan. Remember that your presentation is the first item the team will look at, so try to capture all the ideas concisely to make the team eager to read your project plan, WBS, and other related items

Create an eight to ten slide PowerPoint presentation that addresses the following questions:

1. Determine why the problem occurred: Identify the root cause of the issue from a technical and process perspective and determine what issues led to the problem occurring.

2. Discuss the gaps in the requirement analysis that led to this issue.

3. Describe the selected development methodology and criteria used for your selection.

4. Elaborate on the approach you took with regard to security for the proposed web portal.

Your assignment must follow these formatting requirements:

Include a title slide containing the title of the assignment, the student’s name, the professor’s name, the course title, and the date.

Include charts or diagrams created in MS-Project.

The specific course learning outcomes associated with this assignment are:

Develop proposed improvements to theory and practice in software management.

Apply project management techniques to manage resources and issues in software engineering.

Write clearly and concisely about software engineering using proper writing mechanics and technical style convention

Linux Implementation Proposal

You’ve won the business! Faster Computing has agreed to the project. As the final stage of preimplementation, you have been asked to produce a training guide that will demonstrate how to install Linux and provide an overview of several common commands, as follows:

  • Use a hypervisor of your choice to install Linux. Many hypervisors are available, such as VirtualBox, which is a free download. In addition, as part of UMGC’s agreement with VMware, you can download VMware Workstation for free. See below for specific screenshot requirements.
  • Demonstrate command-line operations that will provide the following information:
    • A listing of files in a directory and common file attributes
    • The current directory (hint: also known as the present working directory)
    • Create a file, then copy it to a different directory
    • Create a second file and move it to a different directory
    • Remove the first file, as well as the copy you created
    • The manual page for a given command
    • Create a text file, then use an editor to modify the content. Then display the content of the modified file
    • Show running processes on the system. Demonstrate how to search for a specific process
    • Forcibly stop a running process

The deliverable for the final phase of the project is a written paper with screenshots. Use the Training Guide Template to record your work.

There is no minimum or maximum page requirement, but all of the requirements must be met. The installation portion should include at least three screenshots showing the progress of your installation. Each screenshot should be accompanied by a brief explanation of what you did. For each of the command-line operations, include at least one screenshot along with a short explanation of the commands used.

Excel Hm For Introduction Of Computer Information Syste

Excel Hm For Introduction Of Computer Information Syste

Setting Up Damn Vulnerable Web Applications (DVWA) Environment And Preparing PPT With The Screenshots

Setting Up Damn Vulnerable Web Applications (DVWA) Environment at https://www.youtube.com/watch?v=LOTaLgY5i5I. Download the image at https://www.vulnhub.com/entry/damn-vulnerable-web-application-dvwa-107,43/. Complete at least two scenarios and provide PowerPoint presentations with screenshots of what you did

Server Virtualization1

You have read about server virtualization and cloud computing in chapter 6 of your textbook. For your written assignment this week, complete a case study of the organization you work for (use a hypothetical or “other” organization if more applicable) that will address the following prompts:

• Describe the organization’s environment, and evaluate its preparedness for virtualization.

• Explain Microsoft (or another product) licensing for virtualized environments.

• Recommend a configuration for shared storage; make sure to discuss the need for high availability and redundancy for virtualization for the organization.

• Explain Windows Azure capabilities for virtual machines and managing a hybrid cloud, including Windows Azure’s Internet as a Service (IaaS) and storage capabilities

Make a recommendation for cloud computer use in the organization, including a justification for your recommendations.

DBM 380

Normalized Database Design

Instructions:

1. Read the business scenario on page 3. The scenario is communicated in the form of an order form from Brewton Enterprises, Inc.

2. Create an ERD that represents the data and data relationships associated with the business scenario. Strongly consider sketching a first draft of the ERD on paper first; following the instructions that begin with step 3 below to normalize the design; making any necessary changes to your on-paper ERD; and then creating your final ERD in a software application such as Microsoft® Visio®, Lucidchart, Microsoft® PowerPoint®, or another software tool of your choice.

3. Fill out the normalization table on page 4.

a. Begin by defining un-normalized form (UNF).

i. Consider all of the nouns that appear in the business scenario. Decide which of these nouns should be fields in the database you will be designing. What nouns need to be identified, stored, and tracked in this particular business scenario? The nouns you identify are what you will list in the UNF column. The nouns you list in this column are all the potential field names you are considering to include in the yet-to-be-identified entity/entities.

For example, in an educational scenario, some things (nouns) that typically need to be identified/stored/tracked include student name, student ID, student standing, all of the classes a student takes, all of the teachers that teach the classes, and so on.

ii. In the UNF column, designate any field names that seem to uniquely identify a person, place, or thing (noun) by typing an asterisk next to that field name. These are your potential keys. ID numbers (such as student IDs, order IDs, and social security numbers) that are unique to a specific individual, transaction, or other noun make good keys.

· For example, field names that can hold the same value in different situations (such as “John Smith” or “freshman”) are not unique and therefore not suitable for keys.

iii. Also in the UNF column, designate any field names that seem to represent repeating values. Use a closing parenthesis “)” to designate repeating values.

· For example, students typically take many classes, so in an educational scenario where “student ID” is a key, “class name” is an example of a repeating value. Because one customer can place many orders, in a business scenario where “customer ID” is a key, “order” is an example of a repeating value.

iv. Also in the UNF column, for any group of repeating values you have identified (the values you marked with a parenthesis), identify the key, or unique identifier, for that group of repeating values. Type an asterisk next to the key associated with each group of repeating values.

· For example, in an educational setting that has repeating values of “class name,” “class ID,” and “class instructor,” “class ID” would be a suitable unique identifier/key. In a business scenario that has repeating values of “order,” “order ID” would be a suitable unique identifier/key.

b. Apply the first normal form rule. 1NF states that each group of related field names should have a unique identifier (primary key), and each field name should represent one and only one value and contain no repeating groups. The result of applying 1NF to the field names in the UNF column will be a grouping of related fields and a repetition of one or more keys.

§ For example, you may find you will move all of the fields designated with a parenthesis in the UNF column to the 1NF column and then repeat the key in both columns. The key you repeat will be considered the primary key in the UNF column and the foreign key in the 1NF column. In an educational scenario, you might retain the primary key “class ID” in the UNF column; move all of the fields marked with a parenthesis that have to do with classes to the 1NF column; and repeat the “class ID” field in the 1NF column. This repetition allows you to “match” the value of a primary key to the value of a foreign key and relate the eventual data groups/entities/tables.

c. Apply the second normal form rule. 2NF states that any non-key field must be dependent on the entire primary key. Conceptually, this means that any non-key field must be able to be located uniquely, based on concatenated or compound keys if necessary. The result of applying 2NF to the field names in the 1NF column is typically groups split apart into smaller groups with additional (and repeated) keys.

d. Identify sensible entity names for each group of fields. The result of applying this last step to the groups of related field names in the 3NF column is one entity name listed in the Entity Name field for each group.

§ For example, if the 3NF column contains groups of fields related to customers, orders, and sales reps, sensible entity names may be Customer, Order, and Sales Representative, respectively. If the 3NF column contains groups of fields related to students, classes, and teachers, sensible entity names might be Student, Class, and Teacher. Because each entity will eventually be implemented as a relational table, take a moment at this point to double-check that each group in the 3NF form that corresponds to an entity name (that is, each eventual table) contains one primary key. If tables are related, they must have a second foreign key that matches the primary key of the table(s) to which they relate

 

Brewton Enterprises, Inc. Order Form

Order number: 1234

Order Date: 5/12/18

Customer number: 9876

Customer name: John Doe

Customer address: 456 Bishop Street Honolulu, Hawaii 96813

Tel: (808) 8650990

Sales agent: Lloyd Johnson

Sales agent number: S99

 

Product No.

Description

Quantity

Unit Price

Discussion 300 Words With In Text Citations, References

Here is an assessment on Leadership Style. Please take this assessment and provide an analysis of the results. How does this relate to you? How does your style impact the technological tools that you will use as a leader? How would you use your style to lead your organization?

Please see the attachment for questionnaire.

Current Topics In Cloud Security

Keeping the organization’s Cloud solution secure is no easy task. Disasters happen so planning for them before they strike can make the difference between surviving and sinking.

Use the ECPI Online Library to find a current article on cloud computing security. You may also use a search engine to search for an article, but be sure the article is a credible source. Write a 2 page summary of the article and explain how the topic might impact an organization’s cloud solution. What changes to the business continuity plan can be made to avoid similar problems?”

Your paper must use proper APA formatting and must contain citations and references to all materials you access to help you with this paper.

ISOL 531 Access Control

Assignment: Provide a reflection of at least 500 words (or 2 pages double spaced) of how the knowledge, skills, or theories of this course have been applied, or could be applied, in a practical manner to your current work environment. If you are not currently working, share times when you have or could observe these theories and knowledge could be applied to an employment opportunity in your field of study. This should summarize what our discussions for the last 7 weeks.

Requirements:

Provide a 500 word (or 2 pages double spaced) minimum reflection.

Use of proper APA formatting and citations. If supporting evidence from outside resources is used those must be properly cited.

Share a personal connection that identifies specific knowledge and theories from this course.

Demonstrate a connection to your current work environment. If you are not employed, demonstrate a connection to your desired work environment.

You should NOT, provide an overview of the assignments assigned in the course. The assignment asks that you reflect how the knowledge and skills obtained through meeting course objectives were applied or could be applied in the workplace.