0% found this document useful (0 votes)
6 views

Fundamentals Of Python Programming Richard L Halterman download

Ebook download

Uploaded by

raxannbaessa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Fundamentals Of Python Programming Richard L Halterman download

Ebook download

Uploaded by

raxannbaessa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

Fundamentals Of Python Programming Richard L

Halterman download

https://ebookbell.com/product/fundamentals-of-python-programming-
richard-l-halterman-43157664

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Learn Python Programming A Beginners Guide To Learning The


Fundamentals Of Python Language To Write Efficient Highquality Code
2nd Edition Fabrizio Romano Romano

https://ebookbell.com/product/learn-python-programming-a-beginners-
guide-to-learning-the-fundamentals-of-python-language-to-write-
efficient-highquality-code-2nd-edition-fabrizio-romano-romano-33296430

Learn Python Programming An Indepth Introduction To The Fundamentals


Of Python 3rd Edition 3rd Edition Romano

https://ebookbell.com/product/learn-python-programming-an-indepth-
introduction-to-the-fundamentals-of-python-3rd-edition-3rd-edition-
romano-36149126

How To Use Python Understand The Fundamentals Of Python Programming


Python Programming For Kids Rutha Mitton Mitton

https://ebookbell.com/product/how-to-use-python-understand-the-
fundamentals-of-python-programming-python-programming-for-kids-rutha-
mitton-mitton-27845882

Head First Python A Learners Guide To The Fundamentals Of Python


Programming 3rd Edition Paul Barry

https://ebookbell.com/product/head-first-python-a-learners-guide-to-
the-fundamentals-of-python-programming-3rd-edition-paul-barry-52480386
Python 3 A Stepbystep Guide To Learn In An Easy Way The Fundamentals
Of Python Programming Language John Bach

https://ebookbell.com/product/python-3-a-stepbystep-guide-to-learn-in-
an-easy-way-the-fundamentals-of-python-programming-language-john-
bach-43213818

Python Ai Programming Navigating Fundamentals Of Ml Deep Learning Nlp


And Reinforcement Learning In Practice Patrick J

https://ebookbell.com/product/python-ai-programming-navigating-
fundamentals-of-ml-deep-learning-nlp-and-reinforcement-learning-in-
practice-patrick-j-54845542

Methods In Medical Informatics Fundamentals Of Healthcare Programming


In Perl Python And Ruby Chapman Hall Crc Mathematical Computational
Biology First Edition Jules J Berman

https://ebookbell.com/product/methods-in-medical-informatics-
fundamentals-of-healthcare-programming-in-perl-python-and-ruby-
chapman-hall-crc-mathematical-computational-biology-first-edition-
jules-j-berman-2540850

Fundamentals Of Python From First Programs Through Data Structures


Kenneth A Lambert

https://ebookbell.com/product/fundamentals-of-python-from-first-
programs-through-data-structures-kenneth-a-lambert-46116586

Fundamentals Of Python First Programs Mindtap Course List 3rd Edition


3rd Kenneth A Lambert

https://ebookbell.com/product/fundamentals-of-python-first-programs-
mindtap-course-list-3rd-edition-3rd-kenneth-a-lambert-57564638
Fundamentals of

Python
Programming

Richard L. Halterman
Southern Adventist University

February 24, 2015


Fundamentals of Python Programming
Copyright © 2014 Richard L. Halterman. All rights reserved.

Formerly Learning to Program with Python


Copyright © 2011–2014 Richard L. Halterman. All rights reserved.
i

Contents

1 The Context of Software Development 1


1.1 Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 Development Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Learning Programming with Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 Writing a Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.5 The Python Interactive Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.6 A Longer Python program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

2 Values and Variables 13


2.1 Integer and String Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.2 Variables and Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.3 Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.4 Floating-point Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.5 Control Codes within Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.6 User Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
2.7 The eval Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
2.8 Controlling the print Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.9 String Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
2.10 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
2.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

3 Expressions and Arithmetic 41


3.1 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.2 Mixed Type Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
CONTENTS ii

3.3 Operator Precedence and Associativity . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47


3.4 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
3.5 Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
3.5.1 Syntax Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
3.5.2 Run-time Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
3.5.3 Logic Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
3.6 Arithmetic Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.7 More Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
3.8 Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
3.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
3.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

4 Conditional Execution 65
4.1 Boolean Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
4.2 Boolean Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
4.3 The Simple if Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
4.4 The if/else Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
4.5 Compound Boolean Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
4.6 The pass Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
4.7 Floating-point Equality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
4.8 Nested Conditionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
4.9 Multi-way Decision Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
4.10 Conditional Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
4.11 Errors in Conditional Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
4.12 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
4.13 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98

5 Iteration 103
5.1 The while Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
5.2 Definite Loops vs. Indefinite Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
5.3 The for Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
5.4 Nested Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
5.5 Abnormal Loop Termination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
5.5.1 The break statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
5.5.2 The continue Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124

©2014 Richard L. Halterman Draft date: February 24, 2015


CONTENTS iii

5.6 while/else and for/else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126


5.7 Infinite Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
5.8 Iteration Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
5.8.1 Computing Square Root . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
5.8.2 Drawing a Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
5.8.3 Printing Prime Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
5.8.4 Insisting on the Proper Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
5.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
5.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139

6 Using Functions 147


6.1 Introduction to Using Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
6.2 Standard Mathematical Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
6.3 time Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
6.4 Random Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
6.5 Importing Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
6.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
6.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164

7 Writing Functions 167


7.1 Function Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
7.2 Main Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
7.3 Parameter Passing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
7.4 Function Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
7.4.1 Better Organized Prime Generator . . . . . . . . . . . . . . . . . . . . . . . . . . 181
7.4.2 Command Interpreter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
7.4.3 Restricted Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
7.4.4 Better Die Rolling Simulator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
7.4.5 Tree Drawing Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
7.4.6 Floating-point Equality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
7.5 Custom Functions vs. Standard Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 190
7.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
7.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193

8 More on Functions 199

©2014 Richard L. Halterman Draft date: February 24, 2015


CONTENTS iv

8.1 Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199


8.2 Default Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
8.3 Introduction to Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
8.4 Making Functions Reusable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
8.5 Documenting Functions and Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
8.6 Functions as Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
8.7 Lambda Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
8.8 Generators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
8.9 Local Function Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
8.10 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
8.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231

9 Objects 235
9.1 Using Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
9.2 String Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
9.3 File Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
9.4 Fraction Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
9.5 Turtle Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
9.6 Graphics with tkinter Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
9.7 Other Standard Python Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
9.8 Object Mutability and Aliasing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
9.9 Garbage Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
9.10 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
9.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259

10 Lists 261
10.1 Using Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
10.2 List Traversal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
10.3 Building Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
10.4 List Membership . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
10.5 List Assignment and Equivalence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
10.6 List Bounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
10.7 Slicing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
10.8 List Element Removal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
10.9 Lists and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283

©2014 Richard L. Halterman Draft date: February 24, 2015


CONTENTS v

10.10List Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285


10.11Prime Generation with a List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
10.12Command-line Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
10.13List Comprehensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
10.14Summary of List Creation Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
10.15Lists vs. Generators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
10.16Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
10.17Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296

11 Sorting and Searching 301


11.1 Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
11.2 Flexible Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
11.3 Faster Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
11.4 Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
11.4.1 Linear Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
11.4.2 Binary Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
11.5 Recursion Revisited . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
11.6 List Permutations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
11.7 Randomly Permuting a List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
11.8 Reversing a List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
11.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
11.10Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339

12 Tuples, Dictionaries, and Sets 343


12.1 Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
12.2 Arbitrary Argument Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
12.3 Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
12.4 Using Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
12.5 Counting with Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
12.6 Grouping with Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
12.7 Implementing Mathematical Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
12.8 Keyword Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
12.9 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
12.10Set Quantification with all and any . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
12.11Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367

©2014 Richard L. Halterman Draft date: February 24, 2015


CONTENTS vi

12.12Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367

13 Handling Exceptions 369


13.1 Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
13.2 Common Standard Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
13.3 Handling Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
13.4 Handling Multiple Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
13.5 The Catch-all Handler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
13.6 Catching Exception Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
13.7 The try Statement’s Optional else Block . . . . . . . . . . . . . . . . . . . . . . . . . . 381
13.8 finally block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
13.9 Exception Handling Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
13.10Raising Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
13.11Using Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
13.12Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
13.13Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397

14 Custom Types 399


14.1 Circle Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
14.2 Restricting Access to Members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
14.3 Bank Account Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
14.4 Stopwatch Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
14.5 Automated Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
14.6 Class Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
14.7 Custom Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
14.8 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
14.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418

Index 420

©2014 Richard L. Halterman Draft date: February 24, 2015


1

Chapter 1

The Context of Software Development

A computer program, from one perspective, is a sequence of instructions that dictate the flow of electri-
cal impulses within a computer system. These impulses affect the computer’s memory and interact with
the display screen, keyboard, mouse, and perhaps even other computers across a network in such a way
as to produce the “magic” that permits humans to perform useful tasks, solve high-level problems, and
play games. One program allows a computer to assume the role of a financial calculator, while another
transforms the machine into a worthy chess opponent. Note the two extremes here:

• at the lower, more concrete level electrical impulses alter the internal state of the computer, while

• at the higher, more abstract level computer users accomplish real-world work or derive actual plea-
sure.

So well is the higher-level illusion achieved that most computer users are oblivious to the lower-level
activity (the machinery under the hood, so to speak). Surprisingly, perhaps, most programmers today write
software at this higher, more abstract level also. An accomplished computer programmer can develop
sophisticated software with little or no interest or knowledge of the actual computer system upon which it
runs. Powerful software construction tools hide the lower-level details from programmers, allowing them
to solve problems in higher-level terms.
The concepts of computer programming are logical and mathematical in nature. In theory, computer
programs can be developed without the use of a computer. Programmers can discuss the viability of a
program and reason about its correctness and efficiency by examining abstract symbols that correspond
to the features of real-world programming languages but appear in no real-world programming language.
While such exercises can be very valuable, in practice computer programmers are not isolated from their
machines. Software is written to be used on real computer systems. Computing professionals known
as software engineers develop software to drive particular systems. These systems are defined by their
underlying hardware and operating system. Developers use concrete tools like compilers, debuggers, and
profilers. This chapter examines the context of software development, including computer systems and
tools.

©2014 Richard L. Halterman Draft date: February 24, 2015


1.1. SOFTWARE 2

1.1 Software

A computer program is an example of computer software. One can refer to a program as a piece of software
as if it were a tangible object, but software is actually quite intangible. It is stored on a medium. A hard
drive, a CD, a DVD, and a USB pen drive are all examples of media upon which software can reside. The
CD is not the software; the software is a pattern on the CD. In order to be used, software must be stored
in the computer’s memory. Typically computer programs are loaded into memory from a medium like the
computer’s hard disk. An electromagnetic pattern representing the program is stored on the computer’s hard
drive. This pattern of electronic symbols must be transferred to the computer’s memory before the program
can be executed. The program may have been installed on the hard disk from a CD or from the Internet. In
any case, the essence that was transferred from medium to medium was a pattern of electronic symbols that
direct the work of the computer system.
These patterns of electronic symbols are best represented as a sequence of zeroes and ones, digits from
the binary (base 2) number system. An example of a binary program sequence is

10001011011000010001000001001110

To the underlying computer hardware, specifically the processor, a zero here and three ones there might
mean that certain electrical signals should be sent to the graphics device so that it makes a certain part of
the display screen red. Unfortunately, only a minuscule number of people in the world would be able to
produce, by hand, the complete sequence of zeroes and ones that represent the program Microsoft Word
for an Intel-based computer running the Windows 8.1 operating system. Further, almost none of those who
could produce the binary sequence would claim to enjoy the task.
The Word program for older Mac OS X computers using a PowerPC processor works similarly to
the Windows version and indeed is produced by the same company, but the program is expressed in a
completely different sequence of zeroes and ones! The Intel Core i7 in the Windows machine accepts a
completely different binary language than the PowerPC processor in the older Mac. We say the processors
have their own machine language.

1.2 Development Tools

If very few humans can (or want) to speak the machine language of the computers’ processors and software
is expressed in this language, how has so much software been developed over the years?
Software can be represented by printed words and symbols that are easier for humans to manage than
binary sequences. Tools exist that automatically convert a higher-level description of what is to be done
into the required lower-level code. Higher-level programming languages like Python allow programmers to
express solutions to programming problems in terms that are much closer to a natural language like English.
Some examples of the more popular of the hundreds of higher-level programming languages that have been
devised over the past 60 years include FORTRAN, COBOL, Lisp, Haskell, C, Perl, C++, Java, and C#. Most
programmers today, especially those concerned with high-level applications, usually do not worry about the
details of underlying hardware platform and its machine language.
One might think that ideally such a conversion tool would accept a description in a natural language,
such as English, and produce the desired executable code. This is not possible today because natural
languages are quite complex compared to computer programming languages. Programs called compilers
that translate one computer language into another have been around for over 60 years, but natural language
processing is still an active area of artificial intelligence research. Natural languages, as they are used

©2014 Richard L. Halterman Draft date: February 24, 2015


1.2. DEVELOPMENT TOOLS 3

by most humans, are inherently ambiguous. To understand properly all but a very limited subset of a
natural language, a human (or artificially intelligent computer system) requires a vast amount of background
knowledge that is beyond the capabilities of today’s software. Fortunately, programming languages provide
a relatively simple structure with very strict rules for forming statements that can express a solution to any
problem that can be solved by a computer.
Consider the following program fragment written in the Python programming language:
subtotal = 25
tax = 3
total = subtotal + tax

While these three lines do constitute a proper Python program, they must likely are merely a small piece
of a larger program. The lines of text in this program fragment look similar to expressions in algebra.
We see no sequence of binary digits. Three words, subtotal, tax, and total, called variables, represent
information. Mathematicians have used variables for hundreds of years before the first digital computer was
built. In programming, a variable represents a value stored in the computer’s memory. Familiar operators
(= and +) are used instead of some cryptic binary digit sequence that instructs the processor to perform the
operation. Since this program is expressed in the Python language, not machine language, no computer
processor can execute the program directly. A program called an interpreter translates the Python code into
machine code when a user runs the program. The higher-level language code is called source code. The
corresponding machine language code is called the target code. The interpreter translates the source code
into the target machine language.
The beauty of higher-level languages is this: the same Python source code can execute on different target
platforms. The target platform must have a Python interpreter available, but multiple Python interpreters
are available for all the major computing platforms. The human programmer therefore is free to think about
writing the solution to the problem in Python, not in a specific machine language.
Programmers have a variety of tools available to enhance the software development process. Some
common tools include:

• Editors. An editor allows the programmer to enter the program source code and save it to files.
Most programming editors increase programmer productivity by using colors to highlight language
features. The syntax of a language refers to the way pieces of the language are arranged to make
well-formed sentences. To illustrate, the sentence

The tall boy runs quickly to the door.

uses proper English syntax. By comparison, the sentence

Boy the tall runs door to quickly the.

is not correct syntactically. It uses the same words as the original sentence, but their arrangement
does not follow the rules of English.
Similarly, programming languages have strict syntax rules that programmers must follow to create
well-formed programs. Only well-formed programs are acceptable for translation into executable
machine code. Some syntax-aware editors can use colors or other special annotations to alert pro-
grammers of syntax errors during the editing process.

• Compilers. A compiler translates the source code to target code. The target code may be the machine
language for a particular platform or embedded device. The target code could be another source
language; for example, the earliest C++ compiler translated C++ into C, another higher-level language.
The resulting C code was then processed by a C compiler to produce an executable program. (C++

©2014 Richard L. Halterman Draft date: February 24, 2015


1.3. LEARNING PROGRAMMING WITH PYTHON 4

compilers today translate C++ directly into machine language.) Compilers translate the contents of a
source file and produce a file containing all the target code. Popular compiled languages include C,
C++, Java, C#.

• Interpreters. An interpreter is like a compiler, in that it translates higher-level source code into
target code (usually machine language). It works differently, however. While a compiler produces
an executable program that may run many times with no additional translation needed, an inter-
preter translates source code statements into machine language each time a user runs the program. A
compiled program does not need to be recompiled to run, but an interpreted program must be rein-
terpreted each time it executes. For this reason interpreted languages are often refered to as scripting
languages. The interpreter in essence reads the script, where the script is the source code of the
program. In general, compiled programs execute more quickly than interpreted programs because
the translation activity occurs only once. Interpreted programs, on the other hand, can run as is on
any platform with an appropriate interpreter; they do not need to be recompiled to run on a different
platform. Python, for example, is used mainly as an interpreted language, but compilers for it are
available. Interpreted languages are better suited for dynamic, explorative development which many
people feel is ideal for beginning programmers. Popular scripting languages include Python, Ruby,
Perl, and, for web browsers, Javascript.

• Debuggers. A debugger allows a programmer to more easily trace a program’s execution in order
to locate and correct errors in the program’s implementation. With a debugger, a developer can
simultaneously run a program and see which line in the source code is responsible for the program’s
current actions. The programmer can watch the values of variables and other program elements to see
if their values change as expected. Debuggers are valuable for locating errors (also called bugs) and
repairing programs that contain errors. (See Section 3.5 for more information about programming
errors.)

• Profilers. A profiler collects statistics about a program’s execution allowing developers to tune ap-
propriate parts of the program to improve its overall performance. A profiler indicates how many
times a portion of a program is executed during a particular run, and how long that portion takes to
execute. Developers also can use profilers for testing purposes to ensure all the code in a program is
actually being used somewhere during testing. This is known as coverage. It is common for software
to fail after its release because users exercise some part of the program that was not executed anytime
during testing. The main purpose of profiling is to find the parts of a program that can be improved
to make the program run faster.

Many developers use integrated development environments (IDEs). An IDE includes editors, debug-
gers, and other programming aids in one comprehensive program. Python IDEs include Wingware, En-
thought, and IDLE.
Despite the wide variety of tools (and tool vendors’ claims), the programming process for all but trivial
programs is not automatic. Good tools are valuable and certainly increase the productivity of developers,
but they cannot write software. There are no substitutes for sound logical thinking, creativity, common
sense, and, of course, programming experience.

1.3 Learning Programming with Python

Guido van Rossum created the Python programming language in the late 1980s. In contrast to other popular
languages such as C, C++, Java, and C#, Python strives to provide a simple but powerful syntax.

©2014 Richard L. Halterman Draft date: February 24, 2015


1.4. WRITING A PYTHON PROGRAM 5

Python is used for software development at companies and organizations such as Google, Yahoo, Face-
book, CERN, Industrial Light and Magic, and NASA. Experienced programmers can accomplish great
things with Python, but Python’s beauty is that it is accessible to beginning programmers and allows them
to tackle interesting problems more quickly than many other, more complex languages that have a steeper
learning curve.
More information about Python, including links to download the latest version for Microsoft Windows,
Mac OS X, and Linux, can be found at http://www.python.org.
In late 2008, Python 3.0 was released. Commonly called Python 3, the current version of Python is
incompatible with earlier versions of the language. Currently the Python world still is in transition between
Python 2 and Python 3. Many existing published books cover Python 2, but more Python 3 resources now
are becoming widely available. The code in this book is based on Python 3.
This book does not attempt to cover all the facets of the Python programming language. Experienced
programmers should look elsewhere for books that cover Python in much more detail. The focus here is on
introducing programming techniques and developing good habits. To that end, our approach avoids some
of the more esoteric features of Python and concentrates on the programming basics that transfer directly to
other imperative programming languages such as Java, C#, and C++. We stick with the basics and explore
more advanced features of Python only when necessary to handle the problem at hand.

1.4 Writing a Python Program

The text that makes up a Python program has a particular structure. The syntax must be correct, or the
interpreter will generate error messages and not execute the program. This section introduces Python by
providing a simple example program.
A program consists of one or more statements. A statement is an instruction that the interpreter executes.
The following statement invokes the print function to display a message:
print("This is a simple Python program")

We can use the statement in a program. Listing 1.1 (simple.py) is one of the simplest Python programs that
does something:

Listing 1.1: simple.py


print("This is a simple Python program")

We will use Wingware’s WingIDE 101 to develop our Python programs. This integrated development
environment is freely available from http://http://wingware.com/downloads/wingide-101, and its
target audience is beginning Python programmers. Its feature set and ease of use make WingIDE 101 an
ideal platform for exploring programming in Python.
The way you launch WingIDE 101 depends on your operating system and how it was installed. Fig-
ure 1.1 shows a screenshot of WingIDE 101 running on a Windows 8.1 computer. The IDE consists of a
menu bar at the top, along with a tool bar directly underneath it, and several sub-panes within the window.
The large, unlabeled pane in the upper left portion of the window is the editor pane in which we type in
our program’s source code. The versions of WingIDE 101 for Apple Mac OS X and Linux are similar in
appearance.
To begin entering our program, we will choose the New item from the File menu (File→New menu
sequence), as shown in Figure 1.2. This action produces a new editor pane for a file named Unititled-1.py.

©2014 Richard L. Halterman Draft date: February 24, 2015


1.4. WRITING A PYTHON PROGRAM 6

Figure 1.1: WingIDE 101 running under Microsoft Windows

Figure 1.2: The menu selection to create a new Python program.

As Figure 1.3 shows, the file’s name appears in the editor’s tab at the top. (We will save the file with a

Figure 1.3: The new, untitled editor pane ready for code.

different name later.)


We now are ready to type in the code that constitutes the program. Figure 1.4 shows the text to type.
Next we will save the file. The menu sequence File→Save, also shown in Figure 1.5, produces the
dialog box shown in Figure 1.6 that allows us to select a folder and filename for our program. You should

©2014 Richard L. Halterman Draft date: February 24, 2015


1.4. WRITING A PYTHON PROGRAM 7

Figure 1.4: The code for the simple program after typed into the editor pane.

Figure 1.5: Save the Python program

name all Python programs with a .py extension.

Figure 1.6: The file save dialog allows the user to name the Python file and locate the file in a particular
folder.

To execute the program, select the little green triangle under the menu bar, shown in Figure 1.7.

Figure 1.7: Running the program

In the pane labeled Python Shell we will the program’s output. Figure 1.8 shows the results of running
the program.

©2014 Richard L. Halterman Draft date: February 24, 2015


1.4. WRITING A PYTHON PROGRAM 8

Figure 1.8: WingIDE 101 running under Microsoft Windows

When you are finished programming and wish to quit the IDE, follow the menu sequence File→Quit as
shown in Figure 1.9.

Figure 1.9: WingIDE 101 running under Microsoft Windows

Listing 1.1 (simple.py) contains only one line of code:


print("This is a simple Python program")

This is a Python statement. A statement is a command that the interpreter executes. This statement
prints the message This is a simple Python program on the screen. A statement is the fundamental unit of
execution in a Python program. Statements may be grouped into larger chunks called blocks, and blocks can
make up more complex statements. Higher-order constructs such as functions and methods are composed
of blocks. The statement
print("This is a simple Python program")

makes use of a built in function named print. Python has a variety of different kinds of statements that we
can use to build programs, and the chapters that follow explore these various kinds of statements.
While integrated development environments like Wingware’s WingIDE-101 are useful for developing
Python programs, we can execute Python programs directly from a command line. In Microsoft Windows,
the command console (cmd.exe) and PowerShell offer command lines. In Apple Mac OS X, Linux, and
Unix, a terminal provides a command line. Figure 1.10 shows the Windows command shell running a
Python program. In all cases the user’s PATH environment variable must be set properly in order for the
operating system to find the Python interpreter to run the program.
Figure 1.8 shows that WingIDE 101 displays a program’s output as black text on a white background. In
order to better distinguish visually in this text program source code from program output, we will render the
program’s output with white text on a black background, as it would appear in the command line interpreter
under Windows as shown in Figure 1.10. This means we would show the output of Listing 1.1 (simple.py)
as

©2014 Richard L. Halterman Draft date: February 24, 2015


1.5. THE PYTHON INTERACTIVE SHELL 9

Figure 1.10: Running a Python program from the command line

This is a simple Python program

1.5 The Python Interactive Shell

We created the program in Listing 1.1 (simple.py) and submitted it to the Python interpreter for execution.
We can interact with the interpreter directly, typing in Python statements and expressions for its immediate
execution. As we saw in Figure 1.8, the WingIDE 101 pane labeled Python Shell is where the executing
program directs its output. We also can type commands into the Python Shell pane, and the interpreter
will attempt to execute them. Figure 1.11 shows how the interpreter responds when we enter the program
statement directly into the shell. The interpreter prompts the user for input with three greater-than symbols

Figure 1.11: The interactive shell allows us to submit Python statements and expressions directly to the
interpreter

(>>>). This means the user typed in the text on the line prefixed with >>>. Any lines without the >>> prefix
represent the interpreter’s output, or feedback, to the user.
We will find Python’s interactive interpreter invaluable for experimenting with various language con-
structs. We can discover many things about Python without ever writing a complete program.

©2014 Richard L. Halterman Draft date: February 24, 2015


1.6. A LONGER PYTHON PROGRAM 10

We can execute the interactive Python interpreter directly from the command line, as Figure 1.12
demonstrates. This means not only can we execute Python programs apart from the WingIDE 101 de-

Figure 1.12: Running the Python interpreter from the command line

veloper environment, we also we can access Python’s interactive interpreter separately from WingIDE 101
if we so choose.
Figure 1.11 shows that the WingIDE 101 interpreter pane displays black text on a white background. In
order for readers of this text to better distinguish visually program source code from program output, we
will render the user’s direct interaction with the Python interpreter as black text on a light-gray background.
As an example, the following shows a possible interactive session with a user:
>>> print("Hello!")
Hello!

The interpreter prompt (>>>) prefixes all user input in the interactive shell. Lines that do not begin with the
>>> prompt represent the interpreter’s response.

1.6 A Longer Python program

More interesting programs contain multiple statements. In Listing 1.2 (arrow.py), six print statements draw
an arrow on the screen:

Listing 1.2: arrow.py


print(" * ")
print(" *** ")
print(" ***** ")
print(" * ")
print(" * ")
print(" * ")

We wish the output of Listing 1.2 (arrow.py) to be

©2014 Richard L. Halterman Draft date: February 24, 2015


1.7. SUMMARY 11

*
***
*****
*
*
*

If you try to enter each line one at a time into the IDLE interactive shell, the program’s output will be
intermingled with the statements you type. In this case the best approach is to type the program into an
editor, save the code you type to a file, and then execute the program. Most of the time we use an editor to
enter and run our Python programs. The interactive interpreter is most useful for experimenting with small
snippets of Python code.
In Listing 1.2 (arrow.py) each print statement “draws” a horizontal slice of the arrow. All the horizontal
slices stacked on top of each other results in the picture of the arrow. The statements form a block of Python
code. It is important that no whitespace (spaces or tabs) come before the beginning of each statement. In
Python the indentation of statements is significant and the interpreter generates error messages for improper
indentation. If we try to put a single space before a statement in the interactive shell, we get
>>> print('hi')
File "<stdin>", line 1
print('hi')
ˆ
IndentationError: unexpected indent

The interpreter reports a similar error when we attempt to run a saved Python program if the code contains
such extraneous indentation.

1.7 Summary

• Computers require both hardware and software to operate. Software consists of instructions that
control the hardware.

• At the lowest level, the instructions for a computer program can be represented as a sequence of zeros
and ones. The pattern of zeros and ones determine the instructions performed by the processor.

• Two different kinds of processors can have different machine languages.

• Application software can be written largely without regard to the underlying hardware. Tools au-
tomatically translate the higher-level, abstract language into the machine language required by the
hardware.

• A compiler translates a source file into an executable file. The executable file may be run at any time
with no further translation needed.

• An interpreter translates a source file into machine language each time a user executes the program.

• Compiled programs generally execute more quickly than interpreted programs. Interpreted languages
generally allow for a more interactive development experience.

• Programmers develop software using tools such as editors, compilers, interpreters, debuggers, and
profilers.

©2014 Richard L. Halterman Draft date: February 24, 2015


1.8. EXERCISES 12

• Python is a higher-level programming language. It is considered to be a higher-level language than


C, C++, Java, and C#.
• An IDE is an integrated development environment—one program that provides all the tools that
developers need to write software.

• Messages can be printed in the output window by using Python’s print function.
• A Python program consists of a code block. A block is made up of statements.

1.8 Exercises

1. What is a compiler?
2. What is an interpreter?
3. How is a compiler similar to an interpreter? How are they different?
4. How is compiled or interpreted code different from source code?

5. What tool does a programmer use to produce Python source code?


6. What is necessary to execute a Python program?
7. List several advantages developing software in a higher-level language has over developing software
in machine language.

8. How can an IDE improve a programmer’s productivity?


9. What the “official” Python IDE?
10. What is a statement in a Python program?

©2014 Richard L. Halterman Draft date: February 24, 2015


13

Chapter 2

Values and Variables

In this chapter we explore some building blocks that are used to develop Python programs. We experiment
with the following concepts:

• numeric values
• strings
• variables
• assignment
• identifiers
• reserved words

In the next chapter we will revisit some of these concepts in the context of other data types.

2.1 Integer and String Values

The number four (4) is an example of a numeric value. In mathematics, 4 is an integer value. Integers
are whole numbers, which means they have no fractional parts, and they can be positive, negative, or zero.
Examples of integers include 4, −19, 0, and −1005. In contrast, 4.5 is not an integer, since it is not a whole
number.
Python supports a number of numeric and non-numeric values. In particular, Python programs can use
integer values. The Python statement
print(4)

prints the value 4. Notice that unlike Listing 1.1 (simple.py) and Listing 1.2 (arrow.py) no quotation marks
(") appear in the statement. The value 4 is an example of an integer expression. Python supports other types
of expressions besides integer expressions. An expression is part of a statement.
The number 4 by itself is not a complete Python statement and, therefore, cannot be a program. The
interpreter, however, can evaluate a Python expression. You may type the enter 4 directly into the interactive
interpreter shell:

©2014 Richard L. Halterman Draft date: February 24, 2015


2.1. INTEGER AND STRING VALUES 14

Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:24:06)


[MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 4
4
>>>

The interactive shell attempts to evaluate both expressions and statements. In this case, the expression 4
evaluates to 4. The shell executes what is commonly called the read, eval, print loop. This means the
interactive shell’s sole activity consists of

1. reading the text entered by the user,

2. attempting to evaluate the user’s input in the context of what the user has entered up that point, and

3. printing its evaluation of the user’s input.

If the user enters a 4, the shell interprets it as a 4. If the user enters x = 10, a statement has has no overall
value itself, the shell prints nothing. If the user then enters x, the shell prints the evaluation of x, which is 10.
If the user next enters y, the shell reports a error because y has not been defined in a previous interaction.
Python uses the + symbol with integers to perform normal arithmetic addition, so the interactive shell
can serve as a handy adding machine:
>>> 3 + 4
7
>>> 1 + 2 + 4 + 10 + 3
20
>>> print(1 + 2 + 4 + 10 + 3)
20

The last line evaluated shows how we can use the + symbol to add values within a print statement that
could be part of a Python program.
Consider what happens if we use quote marks around an integer:
>>> 19
19
>>> "19"
'19'
>>> '19'
'19'

Notice how the output of the interpreter is different. The expression "19" is an example of a string value.
A string is a sequence of characters. Strings most often contain non-numeric characters:
>>> "Fred"
'Fred'
>>> 'Fred'
'Fred'

Python recognizes both single quotes (') and double quotes (") as valid ways to delimit a string value. The
word delimit means to determine the boundaries or limits of something. The left ' symbol determines the

©2014 Richard L. Halterman Draft date: February 24, 2015


2.1. INTEGER AND STRING VALUES 15

beginning of a string, and the right ' symbol that follows specifies the end of the string. If a single quote
marks the beginning of a string value, a single quote must delimit the end of the string. Similarly, the double
quotes, if used instead, must appear in pairs. You may not mix the quotes when representing a string:
>>> 'ABC'
'ABC'
>>> "ABC"
'ABC'
>>> 'ABC"
File "<stdin>", line 1
'ABC"
ˆ
SyntaxError: EOL while scanning string literal
>>> "ABC'
File "<stdin>", line 1
"ABC'
ˆ
SyntaxError: EOL while scanning string literal

The interpreter’s output always uses single quotes, but it accepts either single or double quotes as valid
input.
Consider the following interaction sequence:
>>> 19
19
>>> "19"
'19'
>>> '19'
'19'
>>> "Fred"
'Fred'
>>> 'Fred'
'Fred'
>>> Fred
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Fred' is not defined

Notice that with the missing quotation marks the interpreter does not accept the expression Fred.
It is important to note that the expressions 4 and '4' are different. One is an integer expression and
the other is a string expression. All expressions in Python have a type. The type of an expression indicates
the kind of expression it is. An expression’s type is sometimes denoted as its class. At this point we have
considered only integers and strings. The built in type function reveals the type of any Python expression:
>>> type(4)
<class 'int'>
>>> type('4')
<class 'str'>

Python associates the type name int with integer expressions and str with string expressions.
The built in int function converts the string representation of an integer to an actual integer, and the
str function converts an integer expression to a string:

©2014 Richard L. Halterman Draft date: February 24, 2015


2.1. INTEGER AND STRING VALUES 16

>>> 4
4
>>> str(4)
'4'
>>> '5'
'5'
>>> int('5')
5

The expression str(4) evaluates to the string value '4', and int('5') evaluates to the integer value 5.
The int function applied to an integer evaluates simply to the value of the integer itself, and similarly str
applied to a string results in the same value as the original string:
>>> int(4)
4
>>> str('Judy')
'Judy'

As you might guess, there is little reason for a programmer to perform these kinds of transformations—the
expression int(4) is more easily expressed as 4, so the utility of the str and int functions will not become
apparent until we introduce variables in Section 2.2.
Any integer has a string representation, but not all strings have an integer equivalent:
>>> str(1024)
'1024'
>>> int('wow')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'wow'
>>> int('3.4')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '3.4'

In Python, neither wow nor 3.4 represent valid integer expressions. In short, if the contents of the string
(the characters that make it up) look like a valid integer number, you safely can apply the int function to
produce the represented integer.
The plus operator (+) works differently for strings; consider:
>>> 5 + 10
15
>>> '5' + '10'
'510'
>>> 'abc' + 'xyz'
'abcxyz'

As you can see, the result of the expression 5 + 10 is very different from '5' + '10'. The plus operator
splices two strings together in a process known as concatenation. Mixing the two types directly is not
allowed:
>>> '5' + 10
Traceback (most recent call last):

©2014 Richard L. Halterman Draft date: February 24, 2015


2.2. VARIABLES AND ASSIGNMENT 17

File "<stdin>", line 1, in <module>


TypeError: Can't convert 'int' object to str implicitly
>>> 5 + '10'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

but the int and str functions can help:


>>> 5 + int('10')
15
>>> '5' + str(10)
'510'

The type function can determine the type of the most complicated expressions:
>>> type(4)
<class 'int'>
>>> type('4')
<class 'str'>
>>> type(4 + 7)
<class 'int'>
>>> type('4' + '7')
<class 'str'>
>>> type(int('3') + int(4))
<class 'int'>

Commas may not appear in Python integer values. The number two thousand, four hundred sixty-eight
would be written 2468, not 2,468.
In mathematics, integers are unbounded; said another way, the set of mathematical integers is infinite. In
Python, integers may be arbitrarily large, but the larger the integer, the more memory required to represent
it. This means Python integers theoretically can be as large or as small as needed, but, since a computer
has a finite amount of memory (and the operating system may limit the amount of memory allowed for a
running program), in practice Python integers are bounded by available memory.

2.2 Variables and Assignment

In algebra, variables represent numbers. The same is true in Python, except Python variables also can
represent values other than numbers. Listing 2.1 (variable.py) uses a variable to store an integer value and
then prints the value of the variable.

Listing 2.1: variable.py


x = 10
print(x)

Listing 2.1 (variable.py) contains two statements:

• x = 10

©2014 Richard L. Halterman Draft date: February 24, 2015


2.2. VARIABLES AND ASSIGNMENT 18

This is an assignment statement. An assignment statement associates a value with a variable. The
key to an assignment statement is the symbol = which is known as the assignment operator. The
statement assigns the integer value 10 to the variable x. Said another way, this statement binds the
variable named x to the value 10. At this point the type of x is int because it is bound to an integer
value.
We may assign and reassign a variable as often as necessary. The type of a variable will change if it
is reassigned an expression of a different type.
• print(x)
This statement prints the variable x’s current value. Note that the lack of quotation marks here is very
important. If x has the value 10, the statement
print(x)

prints 10, the value of the variable x, but the statement


print('x')

prints x, the message containing the single letter x.

The meaning of the assignment operator (=) is different from equality in mathematics. In mathematics,
= asserts that the expression on its left is equal to the expression on its right. In Python, = makes the variable
on its left take on the value of the expression on its right. It is best to read x = 5 as “x is assigned the value
5,” or “x gets the value 5.” This distinction is important since in mathematics equality is symmetric: if
x = 5, we know 5 = x. In Python this symmetry does not exist; the statement
5 = x

attempts to reassign the value of the literal integer value 5, but this cannot be done because 5 is always 5
and cannot be changed. Such a statement will produce an error.
>>> x = 5
>>> x
5
>>> 5 = x
File "<stdin>", line 1
SyntaxError: can't assign to literal

We can reassign different values to a variable as needed, as Listing 2.2 (multipleassignment.py) shows.

Listing 2.2: multipleassignment.py


x = 10
print('x = ' + str(x))
x = 20
print('x = ' + str(x))
x = 30
print('x = ' + str(x))

Observe that each print statement in Listing 2.2 (multipleassignment.py) is identical, but when the pro-
gram runs (as a program, not in the interactive shell) the print statements produce different results:
x = 10
x = 20
x = 30

©2014 Richard L. Halterman Draft date: February 24, 2015


2.2. VARIABLES AND ASSIGNMENT 19

The variable x has type int, since it is bound to an integer value. Observe how Listing 2.2 (multipleassignment.py)
uses the str function to treat x as a string so the + operator will use string concatenation:
print('x = ' + str(x))

The expression 'x = ' + x would not be legal; as indicated in Section 2.1, the plus (+) operator may not
applied with mixed string and integer operands.
Listing 2.3 (multipleassignment2.py) provides a variation of Listing 2.2 (multipleassignment.py) that
produces the same output.

Listing 2.3: multipleassignment2.py


x = 10
print('x =', x)
x = 20
print('x =', x)
x = 30
print('x =', x)

This version of the print statement:


print('x =', x)

illustrates the print function accepting two parameters. The first parameter is the string 'x =', and the
second parameter is the variable x bound to an integer value. The print function allows programmers to
pass multiple expressions to print, each separated by commas. The elements within the parentheses of the
print function comprise what is known as a comma-separated list. The print function prints each element
in the comma-separated list of parameters. The print function automatically prints a space between each
element in the list so they do not run together.
A programmer may assign multiple variables in one statement using tuple assignment. Listing 2.4
(tupleassign.py) shows how:

Listing 2.4: tupleassign.py


x, y, z = 100, -45, 0
print('x =', x, ' y =', y, ' z =', z)

The Listing 2.4 (tupleassign.py) program produces


x = 100 y = -45 z = 0

A tuple is a comma separated list of expressions. In the assignment statement


x, y, z = 100, -45, 0

x, y, z is one tuple, and 100, -45, 0 is another tuple. Tuple assignment works as follows: The first
variable in the tuple on left side of the assignment operator is assigned the value of the first expression in
the tuple on the left side (effectively x = 100). Similarly, the second variable in the tuple on left side of
the assignment operator is assigned the value of the second expression in the tuple on the left side (in effect
y = -45). z gets the value 0. A tuple is a kind of Python type, like int or float, and we explore tuples in
more detail in Chapter 12.

©2014 Richard L. Halterman Draft date: February 24, 2015


2.2. VARIABLES AND ASSIGNMENT 20

a
2
Figure 2.1: Binding a variable to an object

An assignment statement binds a variable name to an object. We can visualize this process with boxes
and an arrow as shown in Figure 2.1.
One box represents the variable, so we name the box with the variable’s name. The arrow projecting
from the box points to the object to which the variable is bound. In this case the arrow points to another
box that contains the value 2. The second box represents a memory location that holds the internal binary
representation of the value 2.
To see how variable bindings can change as the computer executes a sequence of assignment statements,
consider the following sequence of Python statements:
a = 2
b = 5
a = 3
a = b
b = 7

Figure 2.2 illustrates the variable bindings after the Python interpreter executes the first statement.

a
a = 2 2

Figure 2.2: How variable bindings change as a program runs: step 1

Figure 2.3 shows how the situation changes after the second statement’s execution.
Figure 2.4 shows how the situation changes after the third statement’s execution.
Figure 2.5 illustrates the effects of statement four, and finally Figure 2.6 shows the variable bindings after
all the statements have executed in the order listed.
Importantly, the statement
a = b

means that a and b both are bound to the same numeric object. Note that reassigning b does not affect a’s
value.

©2014 Richard L. Halterman Draft date: February 24, 2015


2.2. VARIABLES AND ASSIGNMENT 21

a
a = 2 2
b = 5 b
5

Figure 2.3: How variable bindings change as a program runs: step 2

a 3
a = 2
b = 5 2
a = 3 b
5

Figure 2.4: How variable bindings change as a program runs: step 3

a = 2 a 3
b = 5 2
a = 3 b
a = b 5

Figure 2.5: How variable bindings change as a program runs: step 4

Not only may a variable’s value change during its use within an executing program; the type of a variable
can change as well. Consider Listing 2.5 (changeabletype.py).

Listing 2.5: changeabletype.py


a = 10
print('First, variable a has value', a, 'and type', type(a))
a = 'ABC'
print('Now, variable a has value', a, 'and type', type(a))

Listing 2.5 (changeabletype.py) produces the following output:


First, variable a has value 10 and type <class 'int'>

©2014 Richard L. Halterman Draft date: February 24, 2015


2.2. VARIABLES AND ASSIGNMENT 22

a = 2 a 3
b = 5 2
a = 3 b
a = b 5
b = 7 7

Figure 2.6: How variable bindings change as a program runs: step 5

Now, variable a has value ABC and type <class 'str'>

Programmers infrequently perform assignments that change a variable’s type. A variable should have
a specific meaning within a program, and its meaning should not change during the program’s execution.
While not always the case, sometimes when a variable’s type changes its meaning changes as well.
A variable that has not been assigned is an undefined variable or unbound variable. Any attempt to use
an undefined variable is an error, as the following sequence from Python’s interactive shell shows:
>>> x = 2
>>> x
2
>>> y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined

The assignment statement binds 2 to the variable x, and after that the interpreter can evaluate x. The
interpreter cannot evaluate the variable y, so it reports an error.
In rare circumstances we may want to undefine a previously defined variable. The del statement does
that, as the following interactive sequence illustrates:
>>> x = 2
>>> x
2
>>> del x
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

The del keyword stands for delete, and so del deletes or removes a variable’s definition from the current
interpreter session or from an executing Python program. Figure 2.7 illustrates the definition and subsequent
deletion of variable x. If variables a, b, and c currently are defined, the statement
del a, b, c

undefines all three variables in one statement.

©2014 Richard L. Halterman Draft date: February 24, 2015


2.3. IDENTIFIERS 23

x
x = 2 2

x
x = 2 2
del x

Figure 2.7: Definition and subsequent deletion of variable x

2.3 Identifiers

While mathematicians are content with giving their variables one-letter names like x, programmers should
use longer, more descriptive variable names. Names such as sum, height, and sub_total are much better
than the equally permissible s, h, and st. A variable’s name should be related to its purpose within the
program. Good variable names make programs more readable by humans. Since programs often contain
many variables, well-chosen variable names can render an otherwise obscure collection of symbols more
understandable.
Python has strict rules for variable names. A variable name is one example of an identifier. An identifier
is a word used to name things. One of the things an identifier can name is a variable. We will see in later
chapters that identifiers name other things such as functions, classes, and methods. Identifiers have the
following form:

• An identifiers must contain at least one character.


• The first character of an identifiers must be an alphabetic letter (upper or lower case) or the underscore
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_
• The remaining characters (if any) may be alphabetic characters (upper or lower case), the underscore,
or a digit
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_0123456789
• No other characters (including spaces) are permitted in identifiers.
• A reserved word cannot be used as an identifier (see Table 2.1).

Examples of valid Python identifiers include

• x
• x2
• total
• port_22

©2014 Richard L. Halterman Draft date: February 24, 2015


2.3. IDENTIFIERS 24

and del from None try


as elif global nonlocal True
assert else if not while
break except import or with
class False in pass yield
continue finally is raise
def for lambda return

Table 2.1: Python keywords

• FLAG.

None of the following words are valid identifiers:

• sub-total (dash is not a legal symbol in an identifier)


• first entry (space is not a legal symbol in an identifier)
• 4all (begins with a digit)
• *2 (the asterisk is not a legal symbol in an identifier)
• class (class is a reserved word)

Python reserves a number of words for special use that could otherwise be used as identifiers. Called
reserved words or keywords, these words are special and are used to define the structure of Python programs
and statements. Table 2.1 lists all the Python reserved words. The purposes of many of these reserved words
are revealed throughout this book.
None of the reserved words in Table 2.1 may be used as identifiers. Fortunately, if you accidentally
attempt to use one of the reserved words as a variable name within a program, the interpreter will issue an
error:
>>> class = 15
File "<stdin>", line 1
class = 15
ˆ
SyntaxError: invalid syntax

(see Section 3.5 for more on interpreter generated errors).


To this point we have avoided keywords completely in our programs. This means there is nothing special
about the names print, int, str, or type, other than they happen to be the names of built-in functions.
We are free to reassign these names and use them as variables. Consider the following interactive sequence
that reassigns the name print to mean something new:
>>> print('Our good friend print')
Our good friend print
>>> print
<built-in function print>
>>> type(print)
<class 'builtin_function_or_method'>
>>> print = 77

©2014 Richard L. Halterman Draft date: February 24, 2015


2.4. FLOATING-POINT NUMBERS 25

>>> print
77
>>> print('Our good friend print')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> type(print)
<class 'int'>

Here we used the name print as a variable. In so doing it lost its original behavior as a function to print
the console. While we can reassign the names print, str, type, etc., it generally is not a good idea to do
so.
Not only can we reassign a function name, but we can assign a variable to a function.
>>> my_print = print
>>> my_print('hello from my_print!')
hello from my_print!

After binding the variable my_print to print we can use my_print in exactly as we would use the built-in
print function.
Python is a case-sensitive language. This means that capitalization matters. if is a reserved word, but
none of If, IF, or iF is a reserved word. Identifiers also are case sensitive; the variable called Name is
different from the variable called name. Note that three of the reserved words (False, None, and True) are
capitalized.
Programmers generally avoid distinguishing between two variables in the same context merely by dif-
ferences in capitalization. Doing so is more likely to confuse human readers. For the same reason, it is
considered poor practice to give a variable the same name as a reserved word with one or more of its letters
capitalized.
The most important thing to remember about variables names is that they should be well chosen. A
variable’s name should reflect the variable’s purpose within the program. For example, consider a program
controlling a point-of-sale terminal (also known as an electronic cash register). The variable keeping track
of the total cost of goods purchased might be named total or total_cost. Variable names such as a67_99
and fred would be poor choices for such an application.

2.4 Floating-point Numbers

Many computational tasks require numbers that have fractional parts. For example, to compute the area of
a circle given the circle’s radius, we use the value π, or approximately 3.14159. Python supports such non-
integer numbers, and they are called floating-point numbers. The name implies that during mathematical
calculations the decimal point can move or “float” to various positions within the number to maintain the
proper number of significant digits. The Python name for the floating-point type is float. Consider the
following interactive session:
>>> x = 5.62
>>> x
5.62
>>> type(x)
<class 'float'>

©2014 Richard L. Halterman Draft date: February 24, 2015


2.4. FLOATING-POINT NUMBERS 26

Title Storage Smallest Magnitude Largest Magnitude Minimum Precision


float 64 bits 2.22507 × 10−308 1.79769 × 10+308 15 digits

Table 2.2: Characteristics of Floating-point Numbers on 32-bit Computer Systems

The range of floating-points values (smallest value to largest value, both positive and negative) and precision
(the number of digits available) depends of the Python implementation for a particular machine. Table 2.2
provides some information about floating point values as commonly implemented on 32-bit computer sys-
tems. Floating point numbers can be both positive and negative.
As you can see from Table 2.2, unlike Python integers which can be arbitrarily large (or, for negatives,
arbitrarily small), floating-point numbers have definite bounds.
Listing 2.6 (pi-print.py) prints an approximation of the mathematical value π.

Listing 2.6: pi-print.py


pi = 3.14159
print("Pi =", pi)
print("or", 3.14, "for short")

The first line in Listing 2.6 (pi-print.py) assigns an approximation of π to the variable named pi, and the
second line prints its value. The last line prints some text along with a literal floating-point value. Any
literal numeric value with a decimal point in a Python program automatically has the type float.
Floating-point numbers are an approximation of mathematical real numbers. The range of floating-point
numbers is limited, since each value requires a fixed amount of memory. Floating-point numbers differ from
integers in another, very important way. An integer has an exact representation. This is not true necessarily
for a floating-point number. Consider the real number π. The mathematical constant π is an irrational
number which means it contains an infinite number of digits with no pattern that repeats. Since π contains
an infinite number of digits, a Python program can only approximate π’s value. Because of the limited
number of digits available to floating-point numbers, Python cannot represent exactly even some numbers
with a finite number of digits; for example, the number 23.3123400654033989 contains too many digits
for the float type. As the following interaction sequence shows, Python stores 23.3123400654033989 as
23.312340065403397:
>>> x = 23.3123400654033989
>>> x
23.312340065403397

An example of the problems that can arise due to the inexact nature of floating-point numbers is demon-
strated later in Listing 3.2 (imprecise.py).
We can express floating-point numbers in scientific notation. Since most programming editors do not
provide superscripting and special symbols like ×, Python slightly alters the normal scientific notation. The
number 6.022 × 1023 is written 6.022e23. The number to the left of the e (we can use capital E as well) is
the mantissa, and the number to the right of the e is the exponent of 10. As another example, −5.1 × 10−4
is expressed in Python as -5.1e-4. Listing 2.7 (scientificnotation.py) prints some scientific constants using
scientific notation.

Listing 2.7: scientificnotation.py

©2014 Richard L. Halterman Draft date: February 24, 2015


2.4. FLOATING-POINT NUMBERS 27

avogadros_number = 6.022e23
c = 2.998e8
print("Avogadro's number =", avogadros_number)
print("Speed of light =", c)

Unlike floating-point numbers, integers are whole numbers and cannot store fractional quantities. We
can convert a floating-point to an integer in two fundamentally different ways:

• Rounding adds or subtracts a fractional amount as necessary to produce the integer closest to the
original floating-point value.
• Truncation simply drops the fractional part of the floating-point number, simply keeping whole num-
ber part that remains.

We can see how rounding and truncation differ in Python’s interactive shell:
>>> 28.71
28.71
>>> int(28.71)
28
>>> round(28.71)
29
>>> round(19.47)
19
>>> int(19.47)
19

As we can see, truncation always “rounds down,” while rounding behaves as we would expect.
We also can use the round function to round a floating-point number to a specified number of decimal
places. The round function accepts an optional argument that produces a floating-point rounded to fewer
decimal places. The additional argument specifies the desired number of decimal places. In the shell we
see
>>> x
93.34836
>>> round(x)
93
>>> round(x, 2)
93.35
>>> round(x, 3)
93.348
>>> round(x, 0)
93.0
>>> round(x, 1)
93.3
>>> type(round(x))
<class 'int'>
>>> type(round(x, 1))
<class 'float'>
>>> type(round(x, 0))
<class 'float'>

As we can see, the single-argument version of round produces an integer result, but the two-argument
version produces a floating-point result.

©2014 Richard L. Halterman Draft date: February 24, 2015


2.5. CONTROL CODES WITHIN STRINGS 28

2.5 Control Codes within Strings

The characters that can appear within strings include letters of the alphabet (A-Z, a-z), digits (0-9), punctu-
ation (., :, ,, etc.), and other printable symbols (#, &, %, etc.). In addition to these “normal” characters, we
may embed special characters known as control codes. Control codes control the way the console window
or a printer renders text. The backslash symbol (\) signifies that the character that follows it is a control
code, not a literal character. The string '\n' thus contains a single control code. The backslash is known
as the escape symbol, and in this case we say the n symbol is escaped. The \n control code represents
the newline control code which moves the text cursor down to the next line in the console window. Other
control codes include \t for tab, \f for a form feed (or page eject) on a printer, \b for backspace, and \a
for alert (or bell). The \b and \a do not produce the desired results in the IDLE interactive shell, but they
work properly in a command shell. Listing 2.8 (specialchars.py) prints some strings containing some of
these control codes.
Listing 2.8: specialchars.py
print('A\nB\nC')
print('D\tE\tF')
print('WX\bYZ')
print('1\a2\a3\a4\a5\a6')

When executed in a command shell, Listing 2.8 (specialchars.py) produces


A
B
C
D E F
WYZ
123456

On most systems, the computer’s speaker beeps five times when printing the last line.
A string with a single quotation mark at the beginning must be terminated with a single quote; sim-
ilarly, A string with a double quotation mark at the beginning must be terminated with a double quote.
A single-quote string may have embedded double quotes, and a double-quote string may have embedded
single quotes. If you wish to embed a single quote mark within a single-quote string, you can use the
backslash to escape the single quote (\'). An unprotected single quote mark would terminate the string.
Similarly, you may protect a double quote mark in a double-quote string with a backslash (\"). Listing 2.9
(escapequotes.py) shows the various ways in which quotation marks may be embedded within string liter-
als.
Listing 2.9: escapequotes.py
print("Did you know that 'word' is a word?")
print('Did you know that "word" is a word?')
print('Did you know that \'word\' is a word?')
print("Did you know that \"word\" is a word?")

The output of Listing 2.9 (escapequotes.py) is


Did you know that 'word' is a word?
Did you know that "word" is a word?
Did you know that 'word' is a word?
Did you know that "word" is a word?

©2014 Richard L. Halterman Draft date: February 24, 2015


2.6. USER INPUT 29

Since the backslash serves as the escape symbol, in order to embed a literal backslash within a string
you must use two backslashes in succession. Listing 2.10 (printpath.py) prints a string with embedded
backslashes.

Listing 2.10: printpath.py


filename = 'C:\\Users\\rick'
print(filename)

Listing 2.10 (printpath.py) displays


C:\Users\rick

2.6 User Input

The print function enables a Python program to display textual information to the user. Programs may use
the input function to obtain information from the user. The simplest use of the input function assigns a
string to a variable:
x = input()

The parentheses are empty because the input function does not require any information to do its job.
Listing 2.11 (usinginput.py) demonstrates that the input function produces a string value.

Listing 2.11: usinginput.py


print('Please enter some text:')
x = input()
print('Text entered:', x)
print('Type:', type(x))

The following shows a sample run of Listing 2.11 (usinginput.py):


Please enter some text:
My name is Rick
Text entered: My name is Rick
Type: <class 'str'>

The second line shown in the output is entered by the user, and the program prints the first, third, and fourth
lines. After the program prints the message Please enter some text:, the program’s execution stops and
waits for the user to type some text using the keyboard. The user can type, backspace to make changes, and
type some more. The text the user types is not committed until the user presses the enter (or return) key.
Quite often we want to perform calculations and need to get numbers from the user. The input function
produces only strings, but we can use the int function to convert a properly formed string of digits into an
integer. Listing 2.12 (addintegers.py) shows how to obtain an integer from the user.

Listing 2.12: addintegers.py


print('Please enter an integer value:')
x = input()
print('Please enter another integer value:')

©2014 Richard L. Halterman Draft date: February 24, 2015


2.6. USER INPUT 30

y = input()
num1 = int(x)
num2 = int(y)
print(num1, '+', num2, '=', num1 + num2)

A sample run of Listing 2.12 (addintegers.py) shows

Please enter an integer value:


2
Please enter another integer value:
17
2 + 17 = 19

Lines two and four represent user input, while the program generates the other lines. The program halts
after printing the first line and does not continue until the user provides the input. After the program prints
the second message it again pauses to accept the user’s second entry.
Since user input almost always requires a message to the user about the expected input, the input
function optionally accepts a string that it prints just before the program stops to wait for the user to respond.
The statement

x = input('Please enter some text: ')

prints the message Please enter some text: and then waits to receive the user’s input to assign to x. We can
express Listing 2.12 (addintegers.py) more compactly using this form of the input function as shown in
Listing 2.13 (addintegers2.py).

Listing 2.13: addintegers2.py


x = input('Please enter an integer value: ')
y = input('Please enter another integer value: ')
num1 = int(x)
num2 = int(y)
print(num1, '+', num2, '=', num1 + num2)

Listing 2.14 (addintegers3.py) is even shorter. It combines the input and int functions into one statement.

Listing 2.14: addintegers3.py


num1 = int(input('Please enter an integer value: '))
num2 = int(input('Please enter another integer value: '))
print(num1, '+', num2, '=', num1 + num2)

In Listing 2.14 (addintegers3.py) the expression

int(input('Please enter an integer value: '))

uses a technique known as functional composition. The result of the input function is passed directly to
the int function instead of using the intermediate variables shown in Listing 2.13 (addintegers2.py). We
frequently will use functional composition to make our program code simpler.

©2014 Richard L. Halterman Draft date: February 24, 2015


2.7. THE EVAL FUNCTION 31

2.7 The eval Function

The input function produces a string from the user’s keyboard input. If we wish to treat that input as a
number, we can use the int or float function to make the necessary conversion:
x = float(input('Please enter a number'))

Here, whether the user enters 2 or 2.0, x will be a variable with type floating point. What if we wish x to
be of type integer if the user enters 2 and x to be floating point if the user enters 2.0? Python provides the
eval function that attempts to evaluate a string in the same way that the interactive shell would evaluate it.
Listing 2.15 (evalfunc.py) illustrates the use of eval.

Listing 2.15: evalfunc.py


x1 = eval(input('Entry x1? '))
print('x1 =', x1, ' type:', type(x1))

x2 = eval(input('Entry x2? '))


print('x2 =', x2, ' type:', type(x2))

x3 = eval(input('Entry x3? '))


print('x3 =', x3, ' type:', type(x3))

x4 = eval(input('Entry x4? '))


print('x4 =', x4, ' type:', type(x4))

x5 = eval(input('Entry x5? '))


print('x5 =', x5, ' type:', type(x5))

A sample run of Listing 2.15 (evalfunc.py) produces


Entry x1? 4
x1 = 4 type: <class 'int'>
Entry x2? 4.0
x2 = 4.0 type: <class 'float'>
Entry x3? 'x1'
x3 = x1 type: <class 'str'>
Entry x4? x1
x4 = 4 type: <class 'int'>
Entry x5? x6
Traceback (most recent call last):
File "C:\Users\rick\Documents\Code\Other\python\changeable.py", line 13, in <module>
x5 = eval(input('Entry x5? '))
File "<string>", line 1, in <module>
NameError: name 'x6' is not defined

Notice that when the user enters 4, the variable’s type is integer. When the user enters 4.0, the variable is a
floating-point variable. For x3, the user supplies the string 'x3' (note the quotes), and the variable’s type
is string. The more interesting situation is x4. The user enters x1 (no quotes). The eval function evaluates
the non-quoted text as a reference to the name x1. The program bound the name x1 to the value 4 when
executing the first line of the program. Finally, the user enters x6 (no quotes). Since the quotes are missing,
the eval function does not interpret x6 as a literal string; instead eval treats x6 as a name an attempts to
evaluate it. Since no variable named x6 exists, the eval function prints an error message.

©2014 Richard L. Halterman Draft date: February 24, 2015


2.8. CONTROLLING THE PRINT FUNCTION 32

The eval function dynamically translates the text provided by the user into an executable form that the
program can process. This allows users to provide input in a variety of flexible ways; for example, users
can enter multiple entries separated by commas, and the eval function evaluates it as a Python tuple. As
Listing 2.16 (addintegers4.py) shows, this makes tuple assignment (see Section 2.2) possible.

Listing 2.16: addintegers4.py


num1, num2 = eval(input('Please enter number 1, number 2: '))
print(num1, '+', num2, '=', num1 + num2)

The following sample run shows how the user now must enter the two numbers at the same time separated
by a comma:
Please enter number 1, number 2: 23, 10
23 + 10 = 33

Listing 2.17 (enterarith.py) is a simple, one line Python program that behaves like the IDLE interactive
shell, except that it accepts only one expression from the user.

Listing 2.17: enterarith.py


print(eval(input()))

A sample run of Listing 2.17 (enterarith.py) shows that the user may enter an arithmetic expression, and
eval handles it properly:
4 + 10
14

The users enters the text 4 + 10, and the program prints 14. Notice that the addition is not programmed
into Listing 2.17 (enterarith.py); as the program runs the eval function compiles the user-supplied text into
executable code and executes it to produce 14.

2.8 Controlling the print Function

In Listing 2.12 (addintegers.py) we would prefer that the cursor remain at the end of the printed line so
when the user types a value it appears on the same line as the message prompting for the values. When the
user presses the enter key to complete the input, the cursor automatically will move down to the next line.
The print function as we have seen so far always prints a line of text, and then the cursor moves down
to the next line so any future printing appears on the next line. The print statement accepts an additional
argument that allows the cursor to remain on the same line as the printed text:
print('Please enter an integer value:', end='')

The expression end='' is known as a keyword argument. The term keyword here means something dif-
ferent from the term keyword used to mean a reserved word. We defer a complete explanation of keyword
arguments until we have explored more of the Python language. For now it is sufficient to know that a print
function call of this form will cause the cursor to remain on the same line as the printed text. Without this
keyword argument, the cursor moves down to the next line after printing the text.
The print statement

©2014 Richard L. Halterman Draft date: February 24, 2015


2.8. CONTROLLING THE PRINT FUNCTION 33

print('Please enter an integer value: ', end='')

means “Print the message Please enter an integer value:, and then terminate the line with nothing rather
than the normal \n newline code.” Another way to achieve the same result is
print(end='Please enter an integer value: ')

This statement means “Print nothing, and then terminate the line with the string 'Please enter an integer value:'
rather than the normal \n newline code. The behavior of the two statements is indistinguishable.
The statement
print('Please enter an integer value:')

is an abbreviated form of the statement


print('Please enter an integer value:', end='\n')

that is, the default ending for a line of printed text is the string '\n', the newline control code. Similarly,
the statement
print()

is a shorter way to express


print(end='\n')

Observe closely the output of Listing 2.18 (printingexample.py).

Listing 2.18: printingexample.py


print('A', end='')
print('B', end='')
print('C', end='')
print()
print('X')
print('Y')
print('Z')

Listing 2.18 (printingexample.py) displays


ABC
X
Y
Z

The statement
print()

essentially moves the cursor down to next line.


Sometimes it is convenient to divide the output of a single line of printed text over several Python
statements. As an example, we may want to compute part of a complicated calculation, print an intermediate
result, finish the calculation, and print the final answer with the output all appearing on one line of text. The
end keyword argument allows us to do so.

©2014 Richard L. Halterman Draft date: February 24, 2015


2.9. STRING FORMATTING 34

Another keyword argument allows us to control how the print function visually separates the argu-
ments it displays. By default, the print function places a single space in between the items it prints. print
uses a keyword argument named sep to specify the string to use insert between items. The name sep stands
for separator. The default value of sep is the string ' ', a string containing a single space. Listing 2.19
(printsep.py) shows the sep keyword customizes print’s behavior.

Listing 2.19: printsep.py


w, x, y, z = 10, 15, 20, 25
print(w, x, y, z)
print(w, x, y, z, sep=',')
print(w, x, y, z, sep='')
print(w, x, y, z, sep=':')
print(w, x, y, z, sep='-----')

The output of Listing 2.19 (printsep.py) is


10 15 20 25
10,15,20,25
10152025
10:15:20:25
10-----15-----20-----25

The first of the output shows print’s default method of using a single space between printed items. The
second output line uses commas as separators. The third line runs the items together with an empty string
separator. The fifth line shows that the separating string may consist of multiple characters.

2.9 String Formatting

Consider Listing 2.20 (powers10left.py) which prints the first few powers of 10.

Listing 2.20: powers10left.py


print(0, 10**0)
print(1, 10**1)
print(2, 10**2)
print(3, 10**3)
print(4, 10**4)
print(5, 10**5)
print(6, 10**6)
print(7, 10**7)
print(8, 10**8)
print(9, 10**9)
print(10, 10**10)
print(11, 10**11)
print(12, 10**12)
print(13, 10**13)
print(14, 10**14)
print(15, 10**15)

Listing 2.20 (powers10left.py) prints

©2014 Richard L. Halterman Draft date: February 24, 2015


2.9. STRING FORMATTING 35

0 1
1 10
2 100
3 1000
4 10000
5 100000
6 1000000
7 10000000
8 100000000
9 1000000000
10 10000000000
11 100000000000
12 1000000000000
13 10000000000000
14 100000000000000
15 1000000000000000

Observe that each number is left justified.


Next, consider Listing 2.21 (powers10left2.py) which again prints the first few powers of 10, albeit in
most complicated way.

Listing 2.21: powers10left2.py


print('{0} {1}'.format(0, 10**0))
print('{0} {1}'.format(1, 10**1))
print('{0} {1}'.format(2, 10**2))
print('{0} {1}'.format(3, 10**3))
print('{0} {1}'.format(4, 10**4))
print('{0} {1}'.format(5, 10**5))
print('{0} {1}'.format(6, 10**6))
print('{0} {1}'.format(7, 10**7))
print('{0} {1}'.format(8, 10**8))
print('{0} {1}'.format(9, 10**9))
print('{0} {1}'.format(10, 10**10))
print('{0} {1}'.format(11, 10**11))
print('{0} {1}'.format(12, 10**12))
print('{0} {1}'.format(13, 10**13))
print('{0} {1}'.format(14, 10**14))
print('{0} {1}'.format(15, 10**15))

Listing 2.21 (powers10left2.py) produces output identical to Listing 2.20 (powers10left.py):


0 1
1 10
2 100
3 1000
4 10000
5 100000
6 1000000
7 10000000
8 100000000
9 1000000000
10 10000000000

©2014 Richard L. Halterman Draft date: February 24, 2015


2.9. STRING FORMATTING 36

11 100000000000
12 1000000000000
13 10000000000000
14 100000000000000
15 1000000000000000

The third print statement in Listing 2.21 (powers10left2.py) prints the expression
'{0} {1}'.format(2, 10**2)

This expression has two main parts:

• '{0} {1}': This is known as the formatting string. It is a Python string because it is a sequence of
characters enclosed with quotes. Notice that the program at no time prints the literal string {0} {1}.
This formatting string serves as a pattern that the second part of the expression will use. {0} and {1}
are placeholders, known as positional parameters, to be replaced by other objects. This formatting
string, therefore, represents two objects separated by a single space.
• format(2, 10**2): This part provides arguments to be substituted into the formatting string. The
first argument, 2, will take the position of the {0} positional parameter in the formatting string. The
value of the second argument, 10**2, which is 100, will replace the {1} positional parameter.

The format operation matches the 2 with the position marked by {0} and the 10**2 with the position
marked by {1}. This somewhat complicated expression evaluates to the simple string '2 100'. The print
function then prints this string as the first line of the program’s output.
In the statement
print('{0} {1}'.format(7, 10**7))

the expression to print, namely


'{0} {1}'.format(7, 10**7)

becomes ’7 10000000’, since 7 replaces {0} and 107 = 10000000 replaces {1}. Figure 2.8 shows how the
arguments of format substitute for the positional parameters in the formatting string.
Listing 2.21 (powers10left2.py) provides no advantage over Listing 2.20 (powers10left.py), and it is
more complicated. Is the extra effort of string formatting ever useful? Observe that in both programs each
number printed is left justified. Ordinarily we want numeric values appearing in a column to be right-
justified so they align on the right instead of the left. A positional parameter in the format string provides
options for right-justifying the object that takes its place. Listing 2.22 (powers10right.py) uses a string
formatter with enhanced positional parameters to right justify the values it prints.

Listing 2.22: powers10right.py


print('{0:3} {1:16}'.format(0, 10**0))
print('{0:3} {1:16}'.format(1, 10**1))
print('{0:3} {1:16}'.format(2, 10**2))
print('{0:3} {1:16}'.format(3, 10**3))
print('{0:3} {1:16}'.format(4, 10**4))
print('{0:3} {1:16}'.format(5, 10**5))
print('{0:3} {1:16}'.format(6, 10**6))
print('{0:3} {1:16}'.format(7, 10**7))
print('{0:3} {1:16}'.format(8, 10**8))

©2014 Richard L. Halterman Draft date: February 24, 2015


2.9. STRING FORMATTING 37

10000000

'{0} {1}'.format(7, 10**7) '7 10000000'


7

'y'

'a{0}b{1}c{0}d'.format('x', 'y') 'axbycxd'

'x'
'x'

Figure 2.8: Placeholder substitution within a formatting string

print('{0:3} {1:16}'.format(9, 10**9))


print('{0:3} {1:16}'.format(10, 10**10))
print('{0:3} {1:16}'.format(11, 10**11))
print('{0:3} {1:16}'.format(12, 10**12))
print('{0:3} {1:16}'.format(13, 10**13))
print('{0:3} {1:16}'.format(14, 10**14))
print('{0:3} {1:16}'.format(15, 10**15))

Listing 2.22 (powers10right.py) prints


0 1
1 10
2 100
3 1000
4 10000
5 100000
6 1000000
7 10000000
8 100000000
9 1000000000
10 10000000000
11 100000000000
12 1000000000000
13 10000000000000
14 100000000000000
15 1000000000000000

©2014 Richard L. Halterman Draft date: February 24, 2015


2.10. SUMMARY 38

The positional parameter {0:3} means “right-justify the first argument to format within a width of
three characters.” Similarly, the {1:16} positional parameter indicates that format’s second argument is
to be right justified within 16 places. This is exactly what we need to properly align the two columns of
numbers.
The format string can contain arbitrary text amongst the positional parameters. Consider the following
interactive sequence:
>>> print('$${0}//{1}&&{0}ˆ ˆ ˆ{2}abc'.format(6, 'Fred', 4.7))
$$6//Fred&&6ˆ ˆ ˆ4.7abc

Note how the resulting string is formatted exactly like the format string, including spaces. The only dif-
ference is the format arguments replace all the positional parameters. Also notice that we may repeat a
positional parameter multiple times within a formatting string.

2.10 Summary

• Python supports both integer and floating-point kinds of numeric values and variables.

• Python does not permit commas to be used when expressing numeric literals.

• Numbers represented on a computer have limitations based on the finite nature of computer systems.

• Variables are used to store values.

• The = operator means assignment, not mathematical equality.

• A variable can be reassigned at any time.

• A variable must be assigned before it can be used within a program.

• Multiple variables can be assigned in one statement.

• A variable represents a location in memory capable of storing a value.

• The statement a = b copies the value stored in variable b into variable a.

• A variable name is an example of an identifier.

• The name of a variable must follow the identifier naming rules.

• All identifiers must consist of at least one character. The first symbol must be an alphabetic letter or
the underscore. Remaining symbols (if any) must be alphabetic letters, the underscore, or digits.

• Reserved words have special meaning within a Python program and cannot be used as identifiers.

• Descriptive variable names are preferred over one-letter names.

• Python is case sensitive; the name X is not the same as the name x.

• Floating-point numbers approximate mathematical real numbers.

• There are many values that floating-point numbers cannot represent exactly.

• In Python we express scientific notation literals of the form 1.0 × 101 as 1.0e1.0.

©2014 Richard L. Halterman Draft date: February 24, 2015


2.11. EXERCISES 39

• Strings are sequences of characters.


• String literals appear within single quote marks (') or double quote marks (").
• Special non-printable control codes like newline and tab are prefixed with the backslash escape char-
acter (\).
• The \n character represents a newline.
• The literal backslash character is a string must appear as two successive backslash symbols.
• The input function reads in a string of text entered by the user from the keyboard during the pro-
gram’s execution.
• The input function accepts an optional prompt string.
• Programmers can use the eval function to convert a string representing a numeric expression into its
evaluated numeric value.

2.11 Exercises

1. Will the following lines of code print the same thing? Explain why or why not.
x = 6
print(6)
print("6")

2. Will the following lines of code print the same thing? Explain why or why not.
x = 7
print(x)
print("x")

3. What is the largest floating-point value available on your system?


4. What is the smallest floating-point value available on your system?
5. What happens if you attempt to use a variable within a program, and that variable has not been
assigned a value?
6. What is wrong with the following statement that attempts to assign the value ten to variable x?
10 = x

7. Once a variable has been properly assigned can its value be changed?
8. In Python can you assign more than one variable in a single statement?
9. Classify each of the following as either a legal or illegal Python identifier:

(a) fred
(b) if
(c) 2x
(d) -4

©2014 Richard L. Halterman Draft date: February 24, 2015


2.11. EXERCISES 40

(e) sum_total
(f) sumTotal
(g) sum-total
(h) sum total
(i) sumtotal
(j) While
(k) x2
(l) Private
(m) public
(n) $16
(o) xTwo
(p) _static
(q) _4
(r) ___
(s) 10%
(t) a27834
(u) wilma's

10. What can you do if a variable name you would like to use is the same as a reserved word?
11. How is the value 2.45 × 10−5 expressed as a Python literal?

12. How can you express the literal value 0.0000000000000000000000000449 as a much more compact
Python literal?
13. How can you express the literal value 56992341200000000000000000000000000000 as a much more
compact Python literal?

14. Can a Python programmer do anything to ensure that a variable’s value can never be changed after
its initial assignment?
15. Is "i" a string literal or variable?
16. What is the difference between the following two strings? 'n' and '\n'?

17. Write a Python program containing exactly one print statement that produces the following output:
A
B
C
D
E
F

18. Write a Python program that simply emits a beep sound when run.

©2014 Richard L. Halterman Draft date: February 24, 2015


41

Chapter 3

Expressions and Arithmetic

This chapter uses the Python numeric types introduced in Chapter 2 to build expressions and perform
arithmetic. Some other important concepts are covered—user input, comments, and dealing with errors.

3.1 Expressions

A literal value like 34 and a variable like x are examples of simple expressions. We can use operators to
combine values and variables and form more complex expressions. In Section 2.1 we saw how we can use
the + operator to add integers and concatenate strings. Listing 3.1 (adder.py) shows we can use the addition
operator (+) to add two integers provided by the user.

Listing 3.1: adder.py


value1 = eval(input('Please enter a number: '))
value2 = eval(input('Please enter another number: '))
sum = value1 + value2
print(value1, '+', value2, '=', sum)

To review, in Listing 3.1 (adder.py):

• value1 = eval(input('Please enter a number: '))


This statement prompts the user to enter some information. After displaying the prompt string Please
enter an integer value:, this statement causes the program’s execution to stop and wait for the user to
type in some text and then press the enter key. The string produced by the input function is passed
off to the eval function which produces a value to assign to the variable value1. If the user types the
sequence 431 and then presses the enter key, value1 is assigned the integer 431. If instead the user
enters 23 + 3, the variable gets the value 26.

• value2 = eval(input('Please enter another number: '))


This statement is similar to the first statement.

• sum = value1 + value2;

©2014 Richard L. Halterman Draft date: February 24, 2015


3.1. EXPRESSIONS 42

Expression Meaning
x+y x added to y, if x and y are numbers
x concatenated to y, if x and y are strings
x-y x take away y, if x and y are numbers
x*y x times y, if x and y are numbers
x concatenated with itself y times, if x is a string and y is an integer
y concatenated with itself x times, if y is a string and x is an integer
x/y x divided by y, if x and y are numbers
x // y Floor of x divided by y, if x and y are numbers
x%y Remainder of x divided by y, if x and y are numbers
x ** y x raised to y power, if x and y are numbers

Table 3.1: Commonly used Python arithmetic binary operators

This is an assignment statement because is contains the assignment operator (=). The variable sum
appears to the left of the assignment operator, so sum will receive a value when this statement exe-
cutes. To the right of the assignment operator is an arithmetic expression involving two variables and
the addition operator. The expression is evaluated by adding together the values bound to the two
variables. Once the addition expression’s value has been determined, that value is assigned to the sum
variable.
• print(value1, '+', value2, '=', sum)
This statement prints the values of the three variables with some additional decoration to make the
output clear about what it is showing.

All expressions have a value. The process of determining the expression’s value is called evaluation.
Evaluating simple expressions is easy. The literal value 54 evaluates to 54. The value of a variable named x
is the value stored in the memory location bound to x. The value of a more complex expression is found by
evaluating the smaller expressions that make it up and combining them with operators to form potentially
new values.
Table 3.1 contains the most commonly used Python arithmetic operators. The common arithmetic
operations, addition, subtraction, multiplication, division, and power behave in the expected way. The
// and % operators are not common arithmetic operators in everyday practice, but they are very useful in
programming. The // operator is called integer division, and the % operator is the modulus or remainder
operator. 25/3 is 8.3333. Three does not divide into 25 evenly. In fact, three goes into 25 eight times with a
remainder of one. Here, eight is the quotient, and one is the remainder. 25//3 is 8 (the quotient), and 25%3
is 1 (the remainder).
All these operators are classified as binary operators because they operate on two operands. In the
statement
x = y + z

on the right side of the assignment operator is an addition expression y + z. The two operands of the +
operator are y and z.
Two operators, + and -, can be used as unary operators. A unary operator has only one operand. The -
unary operator expects a single numeric expression (literal number, variable, or more complicated numeric
expression within parentheses) immediately to its right; it computes the additive inverse of its operand.
If the operand is positive (greater than zero), the result is a negative value of the same magnitude; if the

©2014 Richard L. Halterman Draft date: February 24, 2015


Another Random Document on
Scribd Without Any Related Topics
night on a small creek, tributary to a main fork of Grand River, which
ran through this portion of the valley. The appearance of the country
in the Old Park is interesting, though of a different character from
the New; instead of being a comparative plain, it is more or less
broken into hills, and surrounded by the high mountains, timbered
on the lower parts with quaking asp and pines.
"We entered the Bayou Salade, (South Park,) and immediately
below us was a green valley, through which ran a stream; and a
short distance opposite rose snowy mountains, whose summits were
formed into peaks of naked rock.
"On the following day we descended the stream by an excellent
buffalo trail, along the open grassy bottom of the river. On our right,
the bayou was bordered by a mountainous range, crested with rocky
and naked peaks; and below it had a beautiful park-like character of
pretty level prairies, interspersed among low spurs, wooded openly
with pine and quaking asp, contrasting well with the denser pines
which swept around on the mountain sides.
"During the afternoon, Pike's Peak had been plainly in view
before us.
"The next day we left the river, which continued its course
towards Pike's Peak; and taking a south-easterly direction, in about
ten miles we crossed a gentle ridge, and, issuing from the South
Park, found ourselves involved among the broken spurs of the
mountains which border the great prairie plains. Although broken
and extremely rugged, the country was very interesting, being well
watered by numerous affluents to the Arkansas River, and covered
with grass and a variety of trees."
Carson had disposed of his furs, and was again quietly attending
to his ranche, when he heard of the exorbitant prices for which
sheep were selling in California, and determined to enter upon a
speculation. He had already visited the Navajos Indians, and thither
he went again, and in company with Maxwell and another
mountaineer, purchased several thousand sheep; and with a suitable
company of trusty men as shepherds, took them to Fort Laramie,
and thence by the regular emigrant route, past Salt Lake to
California, and arriving without any disaster, disposed of them in one
of the frontier towns, and then went down to the Sacramento valley,
to witness the change which had come over old familiar places; not
that the mining did not interest him; he had seen that before in
Mexico, but he had not seen the cities which had sprung into
existence at a hundred points, in the foot hills of the Sierras, nor had
he seen San Francisco, that city of wondrous growth, which now
contained thirty-five thousand inhabitants.
But for the remembrance of the hills on which the city rested,
Carson would not have known the metropolis of California, as the
spot where in '48 "the people could be counted in an hour." In San
Francisco he met so many old friends, and so many, who, knowing
him from the history of his deeds, desired to do him honor, that the
attentions he received, while it gratified his ambition, were almost
annoying.
Tired by the anxiety and hard work of bringing his property over
a long and dangerous journey to a good market, he had looked for
rest and retirement; but instead, he was everywhere sought out and
made conspicuous.
He found himself surrounded with the choice spirits of the new
El Dorado; his name a prestige of strength and position, and his
society courted by everybody. The siren voice of pleasure failed not
to speak in his ear her most flattering invitations. Good-fellowship
took him incessantly by the hand, desiring to lead him into the paths
of dissipation. But the gay vortex, with all its brilliancy, had no
attractions for him; the wine cup, with its sparkling arguments, failed
to convince his calm earnestness of character, that his simple habits
of life needed remodeling. To the storm, however, he was exposed;
but, like a good ship during the gale, he weathered the fierce blast,
and finally took his departure from the new city of a day, with his
character untarnished, but nevertheless leaving behind him many
golden opinions.
Some newspaper scribbler, last autumn, announced the death of
Carson, and said, in connection, "His latest and most remarkable
exploit on the plains, was enacted in 1853, when he conducted a
drove of sheep safely to California." Probably the writer was one of
those whose eager curiosity had met a rebuff, in the quiet dignity
with which Carson received the officiousness of the rabble who
thronged around him on that visit. Not that he appreciated honor
less, but that its unnecessary attachments were exceedingly
displeasing to him.
In this terribly fast city, where the monte table, and its kindred
dissipations, advertised themselves without a curtain, and where to
indulge was the rule rather than the exception, Carson was able to
stand fire, for he had been before now tried by much greater
temptations.
In the strange commingling of people from all quarters of the
globe, whom Carson witnessed in San Francisco, he saw but a slight
exaggeration of what he had often witnessed in Santa Fe,—and
indeed, for the element of variety, in many a trapping party, not to
name the summer rendezvous of the trappers, or the exploring
parties of Col. Fremont. To be sure the Chinamen and the Kanackers
were a new feature in society. But whether it be in the many
nationalities represented, or in the pleasures they pursued, except
that in San Francisco there was a lavishness in the expenditure of
wealth commensurate with its speedier accumulation, there was little
new to him, and while he saw its magic growth with glad surprise,
the attractions this city offered could not allure him. Nor could the
vista it opened up of a chance to rise into position in the advancing
struggles for political ascendency, induce one wish to locate his
home in a spot so wanting in the kindly social relationships; for he
had tried the things and found them vanity and vexation of spirit,
and now he yearned for his mountain home, and the sweet pastoral
life which it afforded in his circle of tried friends.
He saved the money he had secured by the sale of his flocks,
and went down overland to Los Angelos to meet Maxwell, who took
the trip by sea, which Carson having tasted once, could not be
persuaded to try again, and there renewing his outfit, and visiting
again some of its honored citizens, they started homeward, and had
a pleasant passage till they reached the Gila River, where grass
became so scarce that they were compelled to take a new course in
order to find food for their horses; but Carson had no difficulty in
pursuing a measurably direct course, and without encountering a
snow storm, often terribly severe in the mountains of this interior
country, he reached Taos on the third of December 1853.
He here received the unexpected information that he had been
appointed Indian agent for New Mexico, and immediately wrote and
sent to Washington the bonds of acceptance of this office. And now
commences Carson's official career, in a capacity for which he was
better fitted than any other person in the Territory.
Long had the Indians in his vicinity called him "father," but now
he had a new claim to this title, for he was to be to them the
almoner of the bounty of the United States Government. There was
immediate call for the exercise of the duties of his office, (for the
Indians of New Mexico had all buried the tomahawk and calumet,) in
visiting and attempting to quiet a band of Apaches, among whom he
went alone, for they all knew him, and secured from them plenty of
promises to do well; but he had scarcely left them, before they were
tired of the self-imposed restraint, and renewedly continued their
depredations, and several serious battles were fought with them by
the United States troops, the first having proved unsuccessful, but
never was success wanting when the commander of United States
dragoons had placed his confidence in the advice, and followed the
suggestions of Kit Carson, who was admitted by them to be the
prince of Indian fighters—though he never tolerated cruelty or the
expenditure of life when there was no imperious necessity, but yet
regarded severe measures better than a dawdling policy.
There had been serious fights in New Mexico in 1846, while
Carson was away with Fremont; and it was better so, as the
Mexicans were his blood and kin; yet, in the change of authority, he
fully sympathized. But now, the enemy was the different tribes of
Indians, and in the capacity of Agent for them, Carson chose to
impress them with the power of the government for which he acted
for their own good, that they might be induced to desist from their
plundering, and be prepared for the influences and practices of
civilization; and all the victories secured over them were due, as
history truly records, "To the aid of Kit Carson," "With the advice of
Kit Carson;" and never once is his name associated with a defeat;
for, if he made a part of an expedition, a condition must be, that
such means should be employed as he knew would accomplish the
end desired; for he did not choose, by one single failure, to give the
Indians a chance to think their lawlessness could escape its merited
retribution.
Nor yet did Carson ever advise that confidence in the promises
of the Indians which was not backed by such exhibition of power as
to command obedience; knowing that with these children of the
forest, schooled in the arts of plunder, and the belief that white men
and white men's property were an intrusion on their hunting
grounds, and therefore lawful prey—this was and is their law—non-
resistance would not answer, and only stern command, backed by
the rifle, ever has secured obedience—though they appreciate the
kindnesses done by those friends who have such reliance. But it was
Carson's opinion that the country cannot be safe while the Indians
roam over it in this wild way, or until they are located on lands
devoted to them and theirs for permanent homes, and are
compelled to settle upon and cultivate the soil, when he thinks they
will come, by careful teaching, to display sentiments of responsibility
for their own acts.
There is little doubt that, had Carson been appointed
Superintendent of Indian Affairs for the department of New Mexico,
the reliance sometimes placed on treaties would have been
discarded, and measures taken at an earlier date, to locate the
Apaches and Camanches and Utahs, which might have been
accomplished with less expenditure of blood and of treasure; but he
quietly pursued his business, relying upon the influence which his
knowledge and skill had given him to induce his superiors in official
authority to undertake such measures as seemed to him the wisest.
The headquarters of his Indian agency were at Taos, and while
he spent as much of his time as possible at Rayedo, the duties of his
office compelled the larger part of it at Taos. The thousand kindly
acts he was able to perform for the Indians, by whom he was
constantly surrounded, had secured such regard for himself that he
needed no protection where he was known—and what Indian of
New Mexico did not know him? He went among them, and
entertained them as the children of his charge, having their
unbounded confidence and love.
Every year, in the hey-day of the season, Carson continued the
custom of a revival of earlier associations, by indulging, for a few
days, or perhaps weeks, in the chase; and was joined in these
excursions by a goodly company of his old compeers, as well as later
acquired friends, and men of reputation and culture, from whatever
quarter of the world, visiting the territory; and especially by a select
few of the braves of the Indian tribes under his charge. These were
seasons of grateful recurrence, and their pleasures were long
anticipated amid the wearisome duties of his office.
The incidents of his every-day life, intervening his appointment
as Indian agent and the rebellion, would furnish an abundance of
material for a romance even stranger than fiction. A life so exciting
as that among the Indians and brave frontiersmen, and a name so
renowned as that of Christopher Carson, could not but attract and
concentre wild and romantic occurrences. His life during these years
is inseparably connected with the history of the Territory of New
Mexico, which, could it be given to the public in all its copious and
interesting details, would unquestionably concede to him all the
noblest characteristics in man.
The treaties between the United States and the Indians, during
the term of his appointment, were mainly the result of his
acquaintance with the Indians, his knowledge of their character, and
his influence over them. Nor did the Government fail to recognize his
valuable services. During the rebellion, and while serving principally
in New Mexico, where he distinguished himself by his untiring
prosecution of hostilities with his savage foes, then at war with the
Government, he was promoted from rank to rank, until he finally
reached that of Brevet Brigadier-General.
In a report to the National headquarters, dated at Camp Florilla,
near Fort Canby, N. M., January 26, 1864, we find the following
detailed account of operations in New Mexico:
"The culminating point in this expedition has been reached at
last by the very successful operations of our troops at Cañon de
Chelly. Col. Kit Carson left Fort Canby on the sixth instant with a
command of four hundred men, twenty of whom were mounted. He
had a section of mountain artillery with him, and taking the road via
Puebla, Colorado, he started for Cañon de Chelly. He gave orders to
Capt. Pheiffer with his command of one hundred men to enter the
cañon at the east opening, while he himself intended to enter it at
the 'mouth,' or west opening, and by this movement he expected
that both columns would meet in the cañon on the second day, as it
was supposed to be forty miles in length.
"Capt. Pheiffer's party proceeded two days through the cañon,
fighting occasionally; but although the Indians frequently fired on
them from the rocky walls above, the balls were spent long before
they reached the bottom of the cañon, which, in many places,
exceeded one thousand five hundred feet in depth. It was a singular
spectacle to behold. A small detachment of troops moving cautiously
along the bottom of one of the greatest cañons on the globe, (the
largest is in Asia, I believe,) and firing volleys upward at hundreds of
Navajoes, who looked, on the dizzy height above them, like so many
pigmies. As they advanced the cañon widened in places, and various
spots of cultivated land were passed, where wheat, maize, beans,
melons, etc., had been planted last year; while more than a
thousand feet above their heads they beheld neat-looking stone
houses built on the receding ledges of rocks, which reminded the
beholder of the swallows' nests in the house eaves, or on the rocky
formation overhanging the 'sea-beat caves.' Further on, an orchard
containing about six hundred peach-trees was passed, and it was
evident that the Indians had paid great attention to their culture.
"On the second day a party from Col. Carson's column met the
Captain in the cañon, and returned with him to Col. Carson's camp.
A party from the Colonel's command had, in the meantime, attacked
a party of Indians, twenty-two of whom were killed. This had a
dispiriting effect on many others, who sent in three of their number
under a white flag. Col. Carson received them, and assured them
that the Government did not desire to exterminate them, but that,
on the contrary, the President wished to save and civilize them; and
to that end Gen. Carlton had given him instructions to send all the
Navajoes who desired peace to the new reservation on the Rio
Pecos, where they would be supplied with food for the present, and
be furnished with implements, seeds, etc., to cultivate the soil. They
departed well-satisfied, and Col. Carson immediately ordered Capt.
A. B. Carey, Thirteenth United States Infantry, with a battalion to
enter the cañon, and make a thorough exploration of its various
branches, and at the same time to be in readiness to chastise any
body of hostile Navajoes he might encounter, and to receive all who
were friendly, and who wished to emigrate to the new reservation.
Capt. Carey, during a passage of twenty-four hours through a branch
of the cañon hitherto unexplored, made an exact geographical map
of this terrible chasm, and discovered many side cañons hitherto
unknown. About one hundred Indians came in to him and declared
that 'the Navajo nation was no more;' that they were tired of fighting
and nearly starved, and that they wished to be permitted to advise
their friends and families in the mountains; many of whom were
willing to leave the land forever, and go to a country where they
would be cared for and protected. They said they understood
agriculture, and were certain they would make comfortable homes
on the Pecos. This was, of course, only the opinion of some; others
would prefer to remain and culture the soil on which they were born,
and live at peace with the territory. However, the latter were
positively informed that unless they were willing to remove they had
better not come in, and, moreover, that the troops would destroy
every blade of corn in the country next summer.
"On the 20th of January Col. Carson came to Fort Canby, and
about six hundred Indians had collected there; but when the wagons
arrived to remove them only one hundred wished to go, and the
remainder desired to return to their villages and caves in the
mountains, on pretence of bringing in some absent member of their
families. Col. Carson very nobly and generously permitted them to
choose for themselves; but told them if ever they came in again they
should be sent to Borgue Redondo, whether willing or not. Col.
Carson himself took the Indians to Santa Fe, and will remain absent
about a month. Since his departure many Indians came in and
agreed to go to the reservation.
"I think the Colonel foresaw this, as no person understands
Indian character better than he does. Capt. A. B. Carey, Thirteenth
Infantry, commanding in his absence, will see that all Indians coming
in will be removed, and, I think, before April next, if the present
good feeling exists, we shall have accomplished the removal of the
entire tribe. Capt. A. B. Carey, after successfully marching through
the cañon and noting its topography, reached Fort Canby on the
eighteenth instant, and relieved Capt. Francis M'Cabe, First New
Mexico Cavalry, who commanded in the absence of Col. Kit Carson.
"As the Navajo expedition is now entirely successful, it is but
justice to the officers and men of the First Cavalry of New Mexico,
and to Col. Christopher Carson and his staff to say that they have all
acted with zeal and devotion for the accomplishment of that great
desideratum—the removal of the Navajoes. Cut off from the
enjoyments of civilized life, deprived of its luxuries, comforts, and
even many of its necessaries, and restricted to the exploration of a
wilderness and the castigation of an army of savages, who defied
them, and endeavored to find a shelter among the cliffs, groves, and
cañons of their country; in pursuing them to their haunts they have
encountered appalling difficulties, namely: want of water, grass, and
fuel; often exposed to the merciless fury of the elements, and to the
bullets and arrows of a hidden foe. In the face of these difficulties
they have discovered new rivers, springs, and mountains in a region
hitherto unexplored, and penetrated by companies into the very
strongholds of the enemy, who fled farther west as our columns
advanced, and on various occasions the dismounted cavalry have, by
rapid and unparalleled night marches, surprised that enemy,
capturing his camp and securing his flocks and herds, at a time
when he imagined himself far beyond our reach, and really when he
occupied a country never before trodden by the foot of a white man.
"Much of the credit is due to the perseverance and courage of
Col. Kit Carson, commanding the expedition, whose example excited
all to great energy, and inspired great resolution; but it may not be
out of place to remark that it is now demonstrated beyond a doubt
that, while the troops of New Mexico have long borne the reputation
of being the best cavalry, they have proved themselves in the
present campaign to be the best infantry in the world.
"Gen. James H. Carlton, who knows, perhaps, and understands
the material for an army as well as any General in our army, has
directed the formation of a New-Mexican Brigade, and when the
savage foe is removed, that Brigade, commanded by Brigadier-Gen.
Kit Carson, would surely reflect credit on the Territory and on the
Department Commander."
After the close of the war Christopher Carson continued in the
employ of the Government, rendering such services as only one
equally skilled and experienced could render, until his death. He died
at Fort Lyon, Colorado, on the 23d of May, 1868, from the effects of
the rupture of an artery, or probably an aneurism of an artery, in the
neck. But a few weeks previous he had visited Washington on a
treaty mission, in company with a deputation of red men, and made
a tour of several of the Northern and Eastern cities.
In his death the country has lost the most noted of that intrepid
race of mountaineers, trappers, and guides that have ever been the
pioneers of civilization in its advancement westward. As an Indian
fighter he was matchless. His rifle, when fired at a redskin, never
failed him, and the number that fell beneath his aim, who can tell!
(The identical rifle which Carson used in all his scouts, during the
last thirty-five years of his life, he bequeathed, just previous to his
death, to Montezuma Lodge, A. F. and A. M., Santa Fe, of which he
was a member.) The country will always regard him as a perfect
representative of the American frontiersman, and accord to him the
most daring valor, consistent kindliness, perseverant energy and
truthfulness which that whole great territory, that we must still
regard as lying between the civilizations, is capable of furnishing.
FOOTNOTES
A Peters.

B Annals of San Francisco. By Frank Soulé, John H


Gihon, and James Nisbet. New York, D. Appleton & Co.,
1855.
C Cutts. Conquest of California and New Mexico.

D Peters.

Transcriber's Notes
Simple typographical errors were corrected.
Punctuation and spelling were made
consistent when a predominant preference was
found in this book; otherwise they were not
changed.
Ambiguous and missing quotation marks
remedied on pages 79, 177-178, and 334.
Page 301: "it is not wonderful" probably
should be "is it not wonderful".
*** END OF THE PROJECT GUTENBERG EBOOK LIFE OF KIT
CARSON, THE GREAT WESTERN HUNTER AND GUIDE ***

Updated editions will replace the previous one—the old editions will
be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States copyright in
these works, so the Foundation (and you!) can copy and distribute it
in the United States without permission and without paying
copyright royalties. Special rules, set forth in the General Terms of
Use part of this license, apply to copying and distributing Project
Gutenberg™ electronic works to protect the PROJECT GUTENBERG™
concept and trademark. Project Gutenberg is a registered trademark,
and may not be used if you charge for an eBook, except by following
the terms of the trademark license, including paying royalties for use
of the Project Gutenberg trademark. If you do not charge anything
for copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such as
creation of derivative works, reports, performances and research.
Project Gutenberg eBooks may be modified and printed and given
away—you may do practically ANYTHING in the United States with
eBooks not protected by U.S. copyright law. Redistribution is subject
to the trademark license, especially commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the free


distribution of electronic works, by using or distributing this work (or
any other work associated in any way with the phrase “Project
Gutenberg”), you agree to comply with all the terms of the Full
Project Gutenberg™ License available with this file or online at
www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand, agree
to and accept all the terms of this license and intellectual property
(trademark/copyright) agreement. If you do not agree to abide by all
the terms of this agreement, you must cease using and return or
destroy all copies of Project Gutenberg™ electronic works in your
possession. If you paid a fee for obtaining a copy of or access to a
Project Gutenberg™ electronic work and you do not agree to be
bound by the terms of this agreement, you may obtain a refund
from the person or entity to whom you paid the fee as set forth in
paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only be


used on or associated in any way with an electronic work by people
who agree to be bound by the terms of this agreement. There are a
few things that you can do with most Project Gutenberg™ electronic
works even without complying with the full terms of this agreement.
See paragraph 1.C below. There are a lot of things you can do with
Project Gutenberg™ electronic works if you follow the terms of this
agreement and help preserve free future access to Project
Gutenberg™ electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright law
in the United States and you are located in the United States, we do
not claim a right to prevent you from copying, distributing,
performing, displaying or creating derivative works based on the
work as long as all references to Project Gutenberg are removed. Of
course, we hope that you will support the Project Gutenberg™
mission of promoting free access to electronic works by freely
sharing Project Gutenberg™ works in compliance with the terms of
this agreement for keeping the Project Gutenberg™ name associated
with the work. You can easily comply with the terms of this
agreement by keeping this work in the same format with its attached
full Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.

1.E. Unless you have removed all references to Project Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project Gutenberg™
work (any work on which the phrase “Project Gutenberg” appears,
or with which the phrase “Project Gutenberg” is associated) is
accessed, displayed, performed, viewed, copied or distributed:
This eBook is for the use of anyone anywhere in the
United States and most other parts of the world at no
cost and with almost no restrictions whatsoever. You
may copy it, give it away or re-use it under the terms
of the Project Gutenberg License included with this
eBook or online at www.gutenberg.org. If you are not
located in the United States, you will have to check the
laws of the country where you are located before using
this eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is derived


from texts not protected by U.S. copyright law (does not contain a
notice indicating that it is posted with permission of the copyright
holder), the work can be copied and distributed to anyone in the
United States without paying any fees or charges. If you are
redistributing or providing access to a work with the phrase “Project
Gutenberg” associated with or appearing on the work, you must
comply either with the requirements of paragraphs 1.E.1 through
1.E.7 or obtain permission for the use of the work and the Project
Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is posted


with the permission of the copyright holder, your use and distribution
must comply with both paragraphs 1.E.1 through 1.E.7 and any
additional terms imposed by the copyright holder. Additional terms
will be linked to the Project Gutenberg™ License for all works posted
with the permission of the copyright holder found at the beginning
of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files containing a
part of this work or any other work associated with Project
Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute this


electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the Project
Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™ works
unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or providing


access to or distributing Project Gutenberg™ electronic works
provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™


electronic work or group of works on different terms than are set
forth in this agreement, you must obtain permission in writing from
the Project Gutenberg Literary Archive Foundation, the manager of
the Project Gutenberg™ trademark. Contact the Foundation as set
forth in Section 3 below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on, transcribe
and proofread works not protected by U.S. copyright law in creating
the Project Gutenberg™ collection. Despite these efforts, Project
Gutenberg™ electronic works, and the medium on which they may
be stored, may contain “Defects,” such as, but not limited to,
incomplete, inaccurate or corrupt data, transcription errors, a
copyright or other intellectual property infringement, a defective or
damaged disk or other medium, a computer virus, or computer
codes that damage or cannot be read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for


the “Right of Replacement or Refund” described in paragraph 1.F.3,
the Project Gutenberg Literary Archive Foundation, the owner of the
Project Gutenberg™ trademark, and any other party distributing a
Project Gutenberg™ electronic work under this agreement, disclaim
all liability to you for damages, costs and expenses, including legal
fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR
NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR
BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH
1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK
OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL
NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF
YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of receiving
it, you can receive a refund of the money (if any) you paid for it by
sending a written explanation to the person you received the work
from. If you received the work on a physical medium, you must
return the medium with your written explanation. The person or
entity that provided you with the defective work may elect to provide
a replacement copy in lieu of a refund. If you received the work
electronically, the person or entity providing it to you may choose to
give you a second opportunity to receive the work electronically in
lieu of a refund. If the second copy is also defective, you may
demand a refund in writing without further opportunities to fix the
problem.

1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of damages.
If any disclaimer or limitation set forth in this agreement violates the
law of the state applicable to this agreement, the agreement shall be
interpreted to make the maximum disclaimer or limitation permitted
by the applicable state law. The invalidity or unenforceability of any
provision of this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation,


the trademark owner, any agent or employee of the Foundation,
anyone providing copies of Project Gutenberg™ electronic works in
accordance with this agreement, and any volunteers associated with
the production, promotion and distribution of Project Gutenberg™
electronic works, harmless from all liability, costs and expenses,
including legal fees, that arise directly or indirectly from any of the
following which you do or cause to occur: (a) distribution of this or
any Project Gutenberg™ work, (b) alteration, modification, or
additions or deletions to any Project Gutenberg™ work, and (c) any
Defect you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new computers.
It exists because of the efforts of hundreds of volunteers and
donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project Gutenberg™’s
goals and ensuring that the Project Gutenberg™ collection will
remain freely available for generations to come. In 2001, the Project
Gutenberg Literary Archive Foundation was created to provide a
secure and permanent future for Project Gutenberg™ and future
generations. To learn more about the Project Gutenberg Literary
Archive Foundation and how your efforts and donations can help,
see Sections 3 and 4 and the Foundation information page at
www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-profit
501(c)(3) educational corporation organized under the laws of the
state of Mississippi and granted tax exempt status by the Internal
Revenue Service. The Foundation’s EIN or federal tax identification
number is 64-6221541. Contributions to the Project Gutenberg
Literary Archive Foundation are tax deductible to the full extent
permitted by U.S. federal laws and your state’s laws.

The Foundation’s business office is located at 809 North 1500 West,


Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up
to date contact information can be found at the Foundation’s website
and official page at www.gutenberg.org/contact

Section 4. Information about Donations to


the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission of
increasing the number of public domain and licensed works that can
be freely distributed in machine-readable form accessible by the
widest array of equipment including outdated equipment. Many
small donations ($1 to $5,000) are particularly important to
maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws regulating


charities and charitable donations in all 50 states of the United
States. Compliance requirements are not uniform and it takes a
considerable effort, much paperwork and many fees to meet and
keep up with these requirements. We do not solicit donations in
locations where we have not received written confirmation of
compliance. To SEND DONATIONS or determine the status of
compliance for any particular state visit www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states where


we have not met the solicitation requirements, we know of no
prohibition against accepting unsolicited donations from donors in
such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot make


any statements concerning tax treatment of donations received from
outside the United States. U.S. laws alone swamp our small staff.

Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could be
freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose network of
volunteer support.
Project Gutenberg™ eBooks are often created from several printed
editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how
to subscribe to our email newsletter to hear about new eBooks.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like