100% found this document useful (1 vote)
95 views

Python Programming An Introduction to Computer Science John M. Zelle - The latest ebook edition with all chapters is now available

The document provides links to download various ebooks and textbooks, including 'Python Programming: An Introduction to Computer Science' by John M. Zelle. It lists additional recommended titles related to computer science and programming. The document also includes details about the content and structure of the Python programming book.

Uploaded by

patikyaari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
95 views

Python Programming An Introduction to Computer Science John M. Zelle - The latest ebook edition with all chapters is now available

The document provides links to download various ebooks and textbooks, including 'Python Programming: An Introduction to Computer Science' by John M. Zelle. It lists additional recommended titles related to computer science and programming. The document also includes details about the content and structure of the Python programming book.

Uploaded by

patikyaari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Visit https://ebookultra.

com to download the full version and


explore more ebooks or textbooks

Python Programming An Introduction to Computer


Science John M. Zelle

_____ Click the link below to download _____


https://ebookultra.com/download/python-programming-an-
introduction-to-computer-science-john-m-zelle/

Explore and download more ebooks or textbooks at ebookultra.com


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

The Art Science of Java an introduction to computer


science 1st Edition Eric Roberts

https://ebookultra.com/download/the-art-science-of-java-an-
introduction-to-computer-science-1st-edition-eric-roberts/

Quantum Computer Science An Introduction 1st Edition N.


David Mermin

https://ebookultra.com/download/quantum-computer-science-an-
introduction-1st-edition-n-david-mermin/

Hack Audio An Introduction to Computer Programming and


Digital Signal Processing in MATLAB 2019th Edition Eric
Tarr
https://ebookultra.com/download/hack-audio-an-introduction-to-
computer-programming-and-digital-signal-processing-in-matlab-2019th-
edition-eric-tarr/

Basic Computation and Principles of Computer Programming


An Introduction to Computing WBUT 2015 4th Edition E.
Balagurusamy
https://ebookultra.com/download/basic-computation-and-principles-of-
computer-programming-an-introduction-to-computing-wbut-2015-4th-
edition-e-balagurusamy/
Introduction to Computing and Programming in Python a
Multimedia Approach Mark J. Guzdial

https://ebookultra.com/download/introduction-to-computing-and-
programming-in-python-a-multimedia-approach-mark-j-guzdial/

Systematic Theology An Introduction to Christian Belief


1st Edition John M. Frame

https://ebookultra.com/download/systematic-theology-an-introduction-
to-christian-belief-1st-edition-john-m-frame/

Introduction to Programming with Java 3rd Edition John


Dean

https://ebookultra.com/download/introduction-to-programming-with-
java-3rd-edition-john-dean/

Introduction to Python for Science and Engineering Second


Edition David J. Pine

https://ebookultra.com/download/introduction-to-python-for-science-
and-engineering-second-edition-david-j-pine/

A Computer Science Tapestry Exploring Programming and


Computer Science with C 2nd edition Owen L. Astrachan

https://ebookultra.com/download/a-computer-science-tapestry-exploring-
programming-and-computer-science-with-c-2nd-edition-owen-l-astrachan/
Python Programming An Introduction to Computer
Science John M. Zelle Digital Instant Download
Author(s): John M. Zelle
ISBN(s): 9781887902991, 1887902996
Edition: Pap/Cdr
File Details: PDF, 1.20 MB
Year: 2003
Language: english
Python Programming:
An Introduction to Computer Science

John M. Zelle, Ph.D.

Version 1.0rc2
Fall 2002
Copyright c 2002 by John M. Zelle

All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior
written permission of the author.

This document was prepared with LATEX 2ε and reproduced by Wartburg College Printing Services.
Contents

1 Computers and Programs 1


1.1 The Universal Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Program Power . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 What is Computer Science? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.4 Hardware Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.5 Programming Languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.6 The Magic of Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.7 Inside a Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.8 Chaos and Computers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

2 Writing Simple Programs 13


2.1 The Software Development Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.2 Example Program: Temperature Converter . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.3 Elements of Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.3.1 Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.3.2 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.4 Output Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.5 Assignment Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.5.1 Simple Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.5.2 Assigning Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.5.3 Simultaneous Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.6 Definite Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.7 Example Program: Future Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

3 Computing with Numbers 25


3.1 Numeric Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.2 Using the Math Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.3 Accumulating Results: Factorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
3.4 The Limits of Int . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.5 Handling Large Numbers: Long Ints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.6 Type Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

4 Computing with Strings 39


4.1 The String Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
4.2 Simple String Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.3 Strings and Secret Codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.3.1 String Representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.3.2 Programming an Encoder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.3.3 Programming a Decoder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.3.4 Other String Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

i
ii CONTENTS

4.3.5 From Encoding to Encryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48


4.4 Output as String Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.4.1 Converting Numbers to Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.4.2 String Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
4.4.3 Better Change Counter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
4.5 File Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
4.5.1 Multi-Line Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
4.5.2 File Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
4.5.3 Example Program: Batch Usernames . . . . . . . . . . . . . . . . . . . . . . . . . 55
4.5.4 Coming Attraction: Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
4.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

5 Objects and Graphics 61


5.1 The Object of Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
5.2 Graphics Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
5.3 Using Graphical Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
5.4 Graphing Future Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
5.5 Choosing Coordinates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
5.6 Interactive Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
5.6.1 Getting Mouse Clicks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
5.6.2 Handling Textual Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
5.7 Graphics Module Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
5.7.1 GraphWin Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
5.7.2 Graphics Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
5.7.3 Entry Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
5.7.4 Displaying Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
5.7.5 Generating Colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
5.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82

6 Defining Functions 85
6.1 The Function of Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
6.2 Functions, Informally . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
6.3 Future Value with a Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
6.4 Functions and Parameters: The Gory Details . . . . . . . . . . . . . . . . . . . . . . . . . . 90
6.5 Functions that Return Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
6.6 Functions and Program Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
6.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97

7 Control Structures, Part 1 101


7.1 Simple Decisions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
7.1.1 Example: Temperature Warnings . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
7.1.2 Forming Simple Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
7.1.3 Example: Conditional Program Execution . . . . . . . . . . . . . . . . . . . . . . . 104
7.2 Two-Way Decisions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
7.3 Multi-Way Decisions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
7.4 Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
7.5 Study in Design: Max of Three . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
7.5.1 Strategy 1: Compare Each to All . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
7.5.2 Strategy 2: Decision Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
7.5.3 Strategy 3: Sequential Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
7.5.4 Strategy 4: Use Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
7.5.5 Some Lessons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
7.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
CONTENTS iii

8 Control Structures, Part 2 119


8.1 For Loops: A Quick Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
8.2 Indefinite Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
8.3 Common Loop Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
8.3.1 Interactive Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
8.3.2 Sentinel Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
8.3.3 File Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
8.3.4 Nested Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
8.4 Computing with Booleans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
8.4.1 Boolean Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
8.4.2 Boolean Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
8.5 Other Common Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
8.5.1 Post-Test Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
8.5.2 Loop and a Half . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
8.5.3 Boolean Expressions as Decisions . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
8.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134

9 Simulation and Design 137


9.1 Simulating Racquetball . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
9.1.1 A Simulation Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
9.1.2 Program Specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
9.2 Random Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
9.3 Top-Down Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
9.3.1 Top-Level Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
9.3.2 Separation of Concerns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
9.3.3 Second-Level Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
9.3.4 Designing simNGames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
9.3.5 Third-Level Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
9.3.6 Finishing Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
9.3.7 Summary of the Design Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
9.4 Bottom-Up Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
9.4.1 Unit Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
9.4.2 Simulation Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
9.5 Other Design Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
9.5.1 Prototyping and Spiral Development . . . . . . . . . . . . . . . . . . . . . . . . . . 150
9.5.2 The Art of Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
9.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152

10 Defining Classes 155


10.1 Quick Review of Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
10.2 Example Program: Cannonball . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
10.2.1 Program Specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
10.2.2 Designing the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
10.2.3 Modularizing the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
10.3 Defining New Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
10.3.1 Example: Multi-Sided Dice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
10.3.2 Example: The Projectile Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
10.4 Objects and Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
10.4.1 Encapsulating Useful Abstractions . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
10.4.2 Putting Classes in Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
10.5 Widget Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
10.5.1 Example Program: Dice Roller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
10.5.2 Building Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
10.5.3 Building Dice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
iv CONTENTS

10.5.4 The Main Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172


10.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173

11 Data Collections 177


11.1 Example Problem: Simple Statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
11.2 Applying Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
11.2.1 Lists are Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
11.2.2 Lists vs. Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
11.2.3 List Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
11.3 Statistics with Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
11.4 Combining Lists and Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
11.5 Case Study: Python Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
11.5.1 A Calculator as an Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
11.5.2 Constructing the Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
11.5.3 Processing Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
11.6 Non-Sequential Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
11.6.1 Dictionary Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
11.6.2 Dictionary Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
11.6.3 Example Program: Word Frequency . . . . . . . . . . . . . . . . . . . . . . . . . . 194
11.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198

12 Object-Oriented Design 201


12.1 The Process of OOD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
12.2 Case Study: Racquetball Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
12.2.1 Candidate Objects and Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
12.2.2 Implementing SimStats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
12.2.3 Implementing RBallGame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
12.2.4 Implementing Player . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
12.2.5 The Complete Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
12.3 Case Study: Dice Poker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
12.3.1 Program Specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
12.3.2 Identifying Candidate Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
12.3.3 Implementing the Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
12.3.4 A Text-Based UI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
12.3.5 Developing a GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
12.4 OO Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
12.4.1 Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
12.4.2 Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
12.4.3 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
12.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223

13 Algorithm Analysis and Design 225


13.1 Searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
13.1.1 A Simple Searching Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
13.1.2 Strategy 1: Linear Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
13.1.3 Strategy 2: Binary Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
13.1.4 Comparing Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
13.2 Recursive Problem-Solving . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
13.2.1 Recursive Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
13.2.2 Recursive Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
13.2.3 Recursive Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
13.3 Sorting Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
13.3.1 Naive Sorting: Selection Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
13.3.2 Divide and Conquer: Merge Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
CONTENTS v

13.3.3 Comparing Sorts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234


13.4 Hard Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
13.4.1 Towers of Hanoi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
13.4.2 The Halting Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
13.4.3 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
vi CONTENTS
Chapter 1

Computers and Programs

Almost everyone has used a computer at one time or another. Perhaps you have played computer games or
used a computer to write a paper or balance your checkbook. Computers are used to predict the weather,
design airplanes, make movies, run businesses, perform financial transactions, and control factories.
Have you ever stopped to wonder what exactly a computer is? How can one device perform so many
different tasks? These basic questions are the starting point for learning about computers and computer
programming.

1.1 The Universal Machine


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

1
2 CHAPTER 1. COMPUTERS AND PROGRAMS

1.2 Program Power


You have already learned an important lesson of computing: Software (programs) rules the hardware (the
physical machine). It is the software that determines what any computer can do. Without programs, comput-
ers would just be expensive paperweights. The process of creating software is called programming, and that
is the main focus of this book.
Computer programming is a challenging activity. Good programming requires an ability to see the big
picture while paying attention to minute detail. Not everyone has the talent to become a first-class program-
mer, just as not everyone has the skills to be a professional athlete. However, virtually anyone can learn how
to program computers. With some patience and effort on your part, this book will help you to become a
programmer.
There are lots of good reasons to learn programming. Programming is a fundamental part of computer
science and is, therefore, important to anyone interested in becoming a computer professional. But others can
also benefit from the experience. Computers have become a commonplace tool in our society. Understanding
the strengths and limitations of this tool requires an understanding of programming. Non-programmers often
feel they are slaves of their computers. Programmers, however, are truly the masters. If you want to become
a more intelligent user of computers, then this book is for you.
Programming can also be loads of fun. It is an intellectually engaging activity that allows people to
express themselves through useful and sometimes remarkably beautiful creations. Believe it or not, many
people actually write computer programs as a hobby. Programming also develops valuable problem-solving
skills, especially the ability to analyze complex systems by reducing them to interactions of understandable
subsystems.
As you probably know, programmers are in great demand. More than a few liberal arts majors have turned
a couple computer programming classes into a lucrative career option. Computers are so commonplace in the
business world today that the ability to understand and program computers might just give you the edge over
your competition, regardless of your occupation.

1.3 What is Computer Science?


You might be surprised to learn that computer science is not the study of computers. A famous computer
scientist named Edsgar Dijkstra once quipped that computers are to computer science what telescopes are to
astronomy. The computer is an important tool in computer science, but it is not itself the object of study.
Since a computer can carry out any process that we can describe, the real question is What processes can we
describe? Put another way, the fundamental question of computer science is simply What can be computed?
Computer scientists use numerous techniques of investigation to answer this question. The three main ones
are design, analysis, and experimentation.
One way to demonstrate that a particular problem can be solved is to actually design a solution. That is,
we develop a step-by-step process for achieving the desired result. Computer scientists call this an algorithm.
That’s a fancy word that basically means “recipe.” The design of algorithms is one of the most important
facets of computer science. In this book you will find techniques for designing and implementing algorithms.
One weakness of design is that it can only answer the question What is computable? in the positive. If I
can devise an algorithm, then the problem is solvable. However, failing to find an algorithm does not mean
that a problem is unsolvable. It may mean that I’m just not smart enough, or I haven’t hit upon the right idea
yet. This is where analysis comes in.
Analysis is the process of examining algorithms and problems mathematically. Computer scientists have
shown that some seemingly simple problems are not solvable by any algorithm. Other problems are in-
tractable. The algorithms that solve these problems take too long or require too much memory to be of
practical value. Analysis of algorithms is an important part of computer science; throughout this book we
will touch on some of the fundamental principles. Chapter 13 has examples of unsolvable and intractable
problems.
Some problems are too complex or ill-defined to lend themselves to analysis. In such cases, computer
scientists rely on experimentation; they actually implement systems and then study the resulting behavior.
Even when theoretical analysis is done, experimentation is often needed in order to verify and refine the
1.4. HARDWARE BASICS 3

Output Devices
CPU

Input Devices

Secondary
Main Memory
Memory

Figure 1.1: Functional View of a Computer.

analysis. For most problems, the bottom-line is whether a working, reliable system can be built. Often we
require empirical testing of the system to determine that this bottom-line has been met. As you begin writing
your own programs, you will get plenty of opportunities to observe your solutions in action.

1.4 Hardware Basics

You don’t have to know all the details of how a computer works to be a successful programmer, but under-
standing the underlying principles will help you master the steps we go through to put our programs into
action. It’s a bit like driving a car. Knowing a little about internal combustion engines helps to explain why
you have to do things like fill the gas tank, start the engine, step on the accelerator, etc. You could learn
to drive by just memorizing what to do, but a little more knowledge makes the whole process much more
understandable. Let’s take a moment to “look under the hood” of your computer.
Although different computers can vary significantly in specific details, at a higher level all modern digital
computers are remarkably similar. Figure 1.1 shows a functional view of a computer. The central processing
unit (CPU) is the “brain” of the machine. This is where all the basic operations of the computer are carried
out. The CPU can perform simple arithmetic operations like adding two numbers and can also do logical
operations like testing to see if two numbers are equal.
The memory stores programs and data. The CPU can only directly access information that is stored in
main memory (called RAM for Random Access Memory). Main memory is fast, but it is also volatile. That is,
when the power is turned off, the information in the memory is lost. Thus, there must also be some secondary
memory that provides more permanent storage. In a modern personal computer, this is usually some sort of
magnetic medium such as a hard disk (also called a hard drive) or floppy.
Humans interact with the computer through input and output devices. You are probably familiar with
common devices such as a keyboard, mouse, and monitor (video screen). Information from input devices is
processed by the CPU and may be shuffled off to the main or secondary memory. Similarly, when information
needs to be displayed, the CPU sends it to one or more output devices.
So what happens when you fire up your favorite game or word processing program? First, the instructions
that comprise the program are copied from the (more) permanent secondary memory into the main memory
of the computer. Once the instructions are loaded, the CPU starts executing the program.
Technically the CPU follows a process called the fetch execute cycle. The first instruction is retrieved
from memory, decoded to figure out what it represents, and the appropriate action carried out. Then the next
instruction is fetched, decoded and executed. The cycle continues, instruction after instruction. This is really
all the computer does from the time that you turn it on until you turn it off again: fetch, decode, execute. It
doesn’t seem very exciting, does it? But the computer can execute this stream of simple instructions with
blazing speed, zipping through millions of instructions each second. Put enough simple instructions together
in just the right way, and the computer does amazing things.
4 CHAPTER 1. COMPUTERS AND PROGRAMS

1.5 Programming Languages


Remember that a program is just a sequence of instructions telling a computer what to do. Obviously, we
need to provide those instructions in a language that a computer can understand. It would be nice if we could
just tell a computer what to do using our native language, like they do in science fiction movies. (“Computer,
how long will it take to reach planet Alphalpha at maximum warp?”) Unfortunately, despite the continuing
efforts of many top-flight computer scientists (including your author), designing a computer to understand
human language is still an unsolved problem.
Even if computers could understand us, human languages are not very well suited for describing complex
algorithms. Natural language is fraught with ambiguity and imprecision. For example, if I say: “I saw the
man in the park with the telescope,” did I have the telescope, or did the man? And who was in the park? We
understand each other most of the time only because all humans share a vast store of common knowledge and
experience. Even then, miscommunication is commonplace.
Computer scientists have gotten around this problem by designing notations for expressing computa-
tions in an exact, and unambiguous way. These special notations are called programming languages. Every
structure in a programming language has a precise form (its syntax) and a precise meaning (its semantics). A
programming language is something like a code for writing down the instructions that a computer will follow.
In fact, programmers often refer to their programs as computer code, and the process of writing an algorithm
in a programming language is called coding.
Python is one example of a programming language. It is the language that we will use throughout this
book. You may have heard of some other languages, such as C++, Java, Perl, Scheme, or BASIC. Although
these languages differ in many details, they all share the property of having well-defined, unambiguous syntax
and semantics.
All of the languages mentioned above are examples of high-level computer languages. Although they are
precise, they are designed to be used and understood by humans. Strictly speaking, computer hardware can
only understand very low-level language known as machine language.
Suppose we want the computer to add two numbers. The instructions that the CPU actually carries out
might be something like this.

load the number from memory location 2001 into the CPU
load the number from memory location 2002 into the CPU
Add the two numbers in the CPU
store the result into location 2003

This seems like a lot of work to add two numbers, doesn’t it? Actually, it’s even more complicated than this
because the instructions and numbers are represented in binary notation (as sequences of 0s and 1s).
In a high-level language like Python, the addition of two numbers can be expressed more naturally: c =
a + b. That’s a lot easier for us to understand, but we need some way to translate the high-level language
into the machine language that the computer can execute. There are two ways to do this: a high-level language
can either be compiled or interpreted.
A compiler is a complex computer program that takes another program written in a high-level language
and translates it into an equivalent program in the machine language of some computer. Figure 1.2 shows
a block diagram of the compiling process. The high-level program is called source code, and the resulting
machine code is a program that the computer can directly execute. The dashed line in the diagram represents
the execution of the machine code.
An interpreter is a program that simulates a computer that understands a high-level language. Rather than
translating the source program into a machine language equivalent, the interpreter analyzes and executes the
source code instruction by instruction as necessary. Figure 1.3 illustrates the process.
The difference between interpreting and compiling is that compiling is a one-shot translation; once a
program is compiled, it may be run over and over again without further need for the compiler or the source
code. In the interpreted case, the interpreter and the source are needed every time the program runs. Compiled
programs tend to be faster, since the translation is done once and for all, but interpreted languages lend
themselves to a more flexible programming environment as programs can be developed and run interactively.
The translation process highlights another advantage that high-level languages have over machine lan-
guage: portability. The machine language of a computer is created by the designers of the particular CPU.
1.6. THE MAGIC OF PYTHON 5

Source
Code Compiler Machine
(Program) Code

Running
Outputs
Inputs Program

Figure 1.2: Compiling a High-Level Language

Source
Code Computer
(Program)
Running an
Outputs
Interpreter
Inputs

Figure 1.3: Interpreting a High-Level Language.

Each kind of computer has its own machine language. A program for a Pentium CPU won’t run on a Mac-
intosh that sports a PowerPC. On the other hand, a program written in a high-level language can be run on
many different kinds of computers as long as there is a suitable compiler or interpreter (which is just another
program). For example, if I design a new computer, I can also program a Python interpreter for it, and then
any program written in Python can be run on my new computer, as is.

1.6 The Magic of Python


Now that you have all the technical details, it’s time to start having fun with Python. The ultimate goal is
to make the computer do our bidding. To this end, we will write programs that control the computational
processes inside the machine. You have already seen that there is no magic in this process, but in some ways
programming feels like magic.
The computational processes inside the computer are like magical spirits that we can harness for our
work. Unfortunately, those spirits only understand a very arcane language that we do not know. What we
need is a friendly Genie that can direct the spirits to fulfill our wishes. Our Genie is a Python interpreter. We
can give instructions to the Python interpreter, and it directs the underlying spirits to carry out our demands.
We communicate with the Genie through a special language of spells and incantations (i.e., Python). The
best way to start learning about Python is to let our Genie out of the bottle and try some spells.
You can start the Python interpreter in an interactive mode and type in some commands to see what
happens. When you first start the interpreter program, you may see something like the following:

Python 2.1 (#1, Jun 21 2001, 11:39:00)


[GCC pgcc-2.91.66 19990314 (egcs-1.1.2 release)] on linux2
Type "copyright", "credits" or "license" for more information.
>>>

The  is a Python prompt indicating that the Genie is waiting for us to give it a command. In programming
languages, a complete command is called a statement.
Here is a sample interaction with the Python interpreter.
6 CHAPTER 1. COMPUTERS AND PROGRAMS

>>> print "Hello, World"


Hello, World
>>> print 2 + 3
5
>>> print "2 + 3 =", 2 + 3
2 + 3 = 5

Here I have tried out three examples using the Python print statement. The first statement asks Python to
display the literal phrase Hello, World. Python responds on the next line by printing the phrase. The second
print statement asks Python to print the sum of 2 and 3. The third print combines these two ideas.
Python prints the part in quotes “2 + 3 =” followed by the result of adding 2 + 3, which is 5.
This kind of interaction is a great way to try out new things in Python. Snippets of interactive sessions
are sprinkled throughout this book. When you see the Python prompt  in an example, that should tip
you off that an interactive session is being illustrated. It’s a good idea to fire up Python and try the examples
for yourself.
Usually we want to move beyond snippets and execute an entire sequence of statements. Python lets us
put a sequence of statements together to create a brand-new command called a function. Here is an example
of creating a new function called hello.

>>> def hello():


print "Hello"
print "Computers are Fun"

>>>

The first line tells Python that we are defining a new function called hello. The following lines are indented
to show that they are part of the hello function. The blank line (obtained by hitting the <Enter> key
twice) lets Python know that the definition is finished, and the interpreter responds with another prompt.
Notice that the definition did not cause anything to happen. We have told Python what should happen when
the hello function is used as a command; we haven’t actually asked Python to perform it yet.
A function is invoked by typing its name. Here’s what happens when we use our hello command.

>>> hello()
Hello
Computers are Fun
>>>

Do you see what this does? The two print statements from the hello function are executed in sequence.
You may be wondering about the parentheses in the definition and use of hello. Commands can have
changeable parts called parameters that are placed within the parentheses. Let’s look at an example of a
customized greeting using a parameter. First the definition:

>>> def greet(person):


print "Hello", person
print "How are you?"

Now we can use our customized greeting.

>>> greet("John")
Hello John
How are you?
>>> greet("Emily")
Hello Emily
How are you?
>>>
1.6. THE MAGIC OF PYTHON 7

Can you see what is happening here? When we use greet we can send different names to customize the
result. We will discuss parameters in detail later on. For the time being, our functions will not use parameters,
so the parentheses will be empty, but you still need to include them when defining and using functions.
One problem with entering functions interactively at the Python prompt like this is that the definitions go
away when we quit Python. If we want to use them again the next time, we have to type them all over again.
Programs are usually created by typing definitions into a separate file called a module or script. This file is
saved on a disk so that it can be used over and over again.
A module file is just a text file, and you can create one using any program for editing text, like a notepad or
word processor program (provided you save your program as a “plain text” file). A special type of program
known as a programming environment simplifies the process. A programming environment is specifically
designed to help programmers write programs and includes features such as automatic indenting, color high-
lighting, and interactive development. The standard Python distribution includes a programming environment
called Idle that you may use for working on the programs in this book.
Let’s illustrate the use of a module file by writing and running a complete program. Our program will
illustrate a mathematical concept known as chaos. Here is the program as we would type it into Idle or some
other editor and save in a module file:
# File: chaos.py
# A simple program illustrating chaotic behavior.

def main():
print "This program illustrates a chaotic function"
x = input("Enter a number between 0 and 1: ")
for i in range(10):
x = 3.9 * x * (1 - x)
print x

main()
This file should be saved with with the name chaos.py. The .py extension indicates that this is a
Python module. You can see that this particular example contains lines to define a new function called main.
(Programs are often placed in a function called main.) The last line of the file is the command to invoke
this function. Don’t worry if you don’t understand what main actually does; we will discuss it in the next
section. The point here is that once we have a program in a module file, we can run it any time we want.
This program can be run in a number of different ways that depend on the actual operating system and
programming environment that you are using. If you are using a windowing system, you can run a Python
program by (double-)clicking on the module file’s icon. In a command-line situation, you might type a
command like python chaos.py. If you are using Idle (or another programming environment) you can
run a program by opening it in the editor and then selecting a command like import, run, or execute.
One method that should always work is to start the Python interpreter and then import the file. Here is
how that looks.
>>> import chaos
This program illustrates a chaotic function
Enter a number between 0 and 1: .25
0.73125
0.76644140625
0.698135010439
0.82189581879
0.570894019197
0.955398748364
0.166186721954
0.540417912062
0.9686289303
0.118509010176
>>>
8 CHAPTER 1. COMPUTERS AND PROGRAMS

Typing the first line import chaos tells the Python interpreter to load the chaos module from the file
chaos.py into main memory. Notice that I did not include the .py extension on the import line; Python
assumes the module will have a .py extension.
As Python imports the module file, each line executes. It’s just as if we had typed them one-by-one at the
interactive Python prompt. The def in the module causes Python to create the main function. When Python
encounters the last line of the module, the main function is invoked, thus running our program. The running
program asks the user to enter a number between 0 and 1 (in this case, I typed “.25”) and then prints out a
series of 10 numbers.
When you first import a module file in this way, Python creates a companion file with a .pyc extension.
In this example, Python creates another file on the disk called chaos.pyc. This is an intermediate file used
by the Python interpreter. Technically, Python uses a hybrid compiling/interpreting process. The Python
source in the module file is compiled into more primitive instructions called byte code. This byte code (the
.pyc) file is then interpreted. Having a .pyc file available makes importing a module faster the second time
around. However, you may delete the byte code files if you wish to save disk space; Python will automatically
re-create them as needed.
A module only needs to be imported into a session once. After the module has been loaded, we can run the
program again by asking Python to execute the main command. We do this by using a special dot notation.
Typing chaos.main() tells Python to invoke the main function in the chaos module. Continuing with
our example, here is how it looks when we rerun the program with 26 as the input.

>>> chaos.main()
Enter a number between 0 and 1: .26
0.75036
0.73054749456
0.767706625733
0.6954993339
0.825942040734
0.560670965721
0.960644232282
0.147446875935
0.490254549376
0.974629602149
>>>

1.7 Inside a Python Program


The output from the chaos program may not look very exciting, but it illustrates a very interesting phe-
nomenon known to physicists and mathematicians. Let’s take a look at this program line by line and see what
it does. Don’t worry about understanding every detail right away; we will be returning to all of these ideas in
the next chapter.
The first two lines of the program start with the # character:

# File: chaos.py
# A simple program illustrating chaotic behavior.

These lines are called comments. They are intended for human readers of the program and are ignored by
Python. The Python interpreter always skips any text from the pound sign (#) through the end of a line.
The next line of the program begins the definition of a function called main.

def main():

Strictly speaking, it would not be necessary to create a main function. Since the lines of a module are
executed as they are loaded, we could have written our program without this definition. That is, the module
could have looked like this:
1.7. INSIDE A PYTHON PROGRAM 9

# File: chaos.py
# A simple program illustrating chaotic behavior.

print "This program illustrates a chaotic function"


x = input("Enter a number between 0 and 1: ")
for i in range(10):
x = 3.9 * x * (1 - x)
print x
This version is a bit shorter, but it is customary to place the instructions that comprise a program inside of a
function called main. One immediate benefit of this approach was illustrated above; it allows us to (re)run
the program by simply invoking chaos.main(). We don’t have to reload the module from the file in order
to run it again, which would be necessary in the main-less case.
The first line inside of main is really the beginning of our program.
print "This program illustrates a chaotic function"
This line causes Python to print a message introducing the program when it runs.
Take a look at the next line of the program.
x = input("Enter a number between 0 and 1: ")
Here x is an example of a variable. A variable is used to give a name to a value so that we can refer to it at
other points in the program. The entire line is an input statement. When Python gets to this statement, it
displays the quoted message Enter a number between 0 and 1: and then pauses, waiting for the
user to type something on the keyboard and press the <Enter> key. The value that the user types is then
stored as the variable x. In the first example shown above, the user entered .25, which becomes the value of
x.
The next statement is an example of a loop.
for i in range(10):
A loop is a device that tells Python to do the same thing over and over again. This particular loop says to
do something 10 times. The lines indented underneath the loop heading are the statements that are done 10
times. These form the body of the loop.
x = 3.9 * x * (1 - x)
print x
The effect of the loop is exactly the same as if we had written the body of the loop 10 times:
x = 3.9 * x * (1 - x)
print x
x = 3.9 * x * (1 - x)
print x
x = 3.9 * x * (1 - x)
print x
x = 3.9 * x * (1 - x)
print x
x = 3.9 * x * (1 - x)
print x
x = 3.9 * x * (1 - x)
print x
x = 3.9 * x * (1 - x)
print x
x = 3.9 * x * (1 - x)
print x
x = 3.9 * x * (1 - x)
10 CHAPTER 1. COMPUTERS AND PROGRAMS

print x
x = 3.9 * x * (1 - x)
print x

Obviously using the loop instead saves the programmer a lot of trouble.
But what exactly do these statements do? The first one performs a calculation.

x = 3.9 * x * (1 - x)

This is called an assignment statement. The part on the right side of the = is a mathematical expression.
Python uses the * character to indicate multiplication. Recall that the value of x is 0 25 (from the input
statement). The computed value is 3 9 0 25 1 0 25 or 0 73125. Once the value on the righthand side is
  

computed, it is stored back (or assigned) into the variable that appears on the lefthand side of the =, in this
case x. The new value of x (0 73125) replaces the old value (0 25).
The second line in the loop body is a type of statement we have encountered before, a print statement.

print x

When Python executes this statement the current value of x is displayed on the screen. So, the first number
of output is 0.73125.
Remember the loop executes 10 times. After printing the value of x, the two statements of the loop are
executed again.

x = 3.9 * x * (1 - x)
print x

Of course, now x has the value 0 73125, so the formula computes a new value of x as 3 9 0 73125 1  

0 73125 , which is 0 76644140625.




Can you see how the current value of x is used to compute a new value each time around the loop? That’s
where the numbers in the example run came from. You might try working through the steps of the program
yourself for a different input value (say 0 5). Then run the program using Python and see how well you did
impersonating a computer.

1.8 Chaos and Computers


I said above that the chaos program illustrates an interesting phenomenon. What could be interesting about
a screen full of numbers? If you try out the program for yourself, you’ll find that, no matter what number
you start with, the results are always similar: the program spits back 10 seemingly random numbers between
0 and 1. As the program runs, the value of x seems to jump around, well, chaotically.
The function computed by this program has the general form: k x 1 x , where k in this case is 3.9.
  

This is called a logistic function. It models certain kinds of unstable electronic circuits and is also sometimes
used to predict population under limiting conditions. Repeated application of the logistic function can pro-
duce chaos. Although our program has a well defined underlying behavior, the output seems unpredictable.
An interesting property of chaotic functions is that very small differences in the initial value can lead to
large differences in the result as the formula is repeatedly applied. You can see this in the chaos program by
entering numbers that differ by only a small amount. Here is the output from a modified program that shows
the results for initial values of 0 25 and 0 26 side by side.

input 0.25 0.26


---------------------------
0.731250 0.750360
0.766441 0.730547
0.698135 0.767707
0.821896 0.695499
0.570894 0.825942
0.955399 0.560671
1.9. EXERCISES 11

0.166187 0.960644
0.540418 0.147447
0.968629 0.490255
0.118509 0.974630

With very similar starting values, the outputs stay similar for a few iterations, but then differ markedly. By
about the fifth iteration, there no longer seems to be any relationship between the two models.
These two features of our chaos program, apparent unpredictability and extreme sensitivity to initial
values, are the hallmarks of chaotic behavior. Chaos has important implications for computer science. It
turns out that many phenomena in the real world that we might like to model and predict with our computers
exhibit just this kind of chaotic behavior. You may have heard of the so-called butterfly effect. Computer
models that are used to simulate and predict weather patterns are so sensitive that the effect of a single
butterfly flapping its wings in New Jersey might make the difference of whether or not rain is predicted in
Peoria.
It’s very possible that even with perfect computer modeling, we might never be able to measure existing
weather conditions accurately enough to predict weather more than a few days in advance. The measurements
simply can’t be precise enough to make the predictions accurate over a longer time frame.
As you can see, this small program has a valuable lesson to teach users of computers. As amazing as
computers are, the results that they give us are only as useful as the mathematical models on which the
programs are based. Computers can give incorrect results because of errors in programs, but even correct
programs may produce erroneous results if the models are wrong or the initial inputs are not accurate enough.

1.9 Exercises
1. Compare and contrast the following pairs of concepts from the chapter.

(a) Hardware vs. Software


(b) Algorithm vs. Program
(c) Programming Language vs. Natural Language
(d) High-Level Language vs. Machine Language
(e) Interpreter vs. Compiler
(f) Syntax vs. Semantics

2. List and explain in your own words the role of each of the five basic functional units of a computer
depicted in Figure 1.1.

3. Write a detailed algorithm for making a peanut butter and jelly sandwich (or some other simple every-
day activity).

4. As you will learn in a later chapter, many of the numbers stored in a computer are not exact values, but
rather close approximations. For example, the value 0.1, might be stored as 0.10000000000000000555.
Usually, such small differences are not a problem; however, given what you have learned about chaotic
behavior in Chapter 1, you should realize the need for caution in certain situations. Can you think of
examples where this might be a problem? Explain.

5. Trace through the Chaos program from Section 1.6 by hand using 0 15 as the input value. Show the
sequence of output that results.

6. Enter and run the Chaos program from Section 1.6 using whatever Python implementation you have
available. Try it out with various values of input to see that it functions as described in the chapter.

7. Modify the Chaos program from Section 1.6 using 2.0 in place of 3.9 as the multiplier in the logistic
function. Your modified line of code should look like this:
12 CHAPTER 1. COMPUTERS AND PROGRAMS

x = 2.0 * x * (1 - x)
Run the program for various input values and compare the results to those obtained from the original
program. Write a short paragraph describing any differences that you notice in the behavior of the two
versions.
8. Modify the Chaos program from Section 1.6 so that it prints out 20 values instead of 10.
9. (Advanced) Modify the Chaos program so that it accepts two inputs and then prints a table with two
columns similar to the one shown in Section 1.8. (Note: You will probably not be able to get the
columns to line up as nicely as those in the example. Chapter 4 discusses how to print numbers with a
fixed number of decimal places.)
Other documents randomly have
different content
The next advice which, the Ras said, this devil, or angel, gave him,
was, that they should set fire to the town of Gondar, and burn it to
the ground, otherwise his good fortune was to leave him there for
ever; and for this there was a great number of advocates, Michael
seeming to lean that way himself. But, when it was reported to the
king, that young prince put a direct negative upon it, by declaring
that he would rather stay in Gondar, and fall by the hands of his
enemies, than either conquer them, or escape from them, by the
commission of so enormous a crime. When this was publicly known,
it procured the king universal good-will, as was experienced
afterwards, when he and Michael were finally defeated, and taken
prisoners, upon their march in return to Gondar.

The army advanced rapidly towards Walkayt. Being near the


Tacazzé, they turned short upon Mai-Lumi, (the River of Limes) the
governor of which, as I have already said, in our journey from
Masuah, detained us several days at Addergey with a view to rob us,
upon a report prevailing that Ras Michael was defeated at Fagitta.
This thief the king surprised and made prisoner, set fire to his house
after having plundered it, and carried him as hostage to Tigré, for
the payment of a sum which he laid upon every village to save them
from being set on fire.

Being now safely arrived on the banks of the Tacazzè, the first
province beyond which is that of Sirè, Michael sent before him Ayto
Tesfos the governor, a man exceedingly beloved, to assemble all sort
of assistance for passing the river. Every one flocked to the stream
with the utmost alacrity; the water was deep, and the baggage wet
in crossing, but the bottom was good and hard; they passed both
expeditiously and safely, and were received in Siré, and then in
Tigré, with every demonstration of joy.

Michael, now arrived in his government, set himself seriously to


unite every part under his own jurisdiction. It was now the rainy
season; there was no possibility of taking the field, and a rebellion
prevailed in two different districts of his province. The sons of
Kasmati Woldo, whose father Ras Michael put to death, had declared
for themselves, in their paternal government of Enderta, and Netcho
who married Ras Michael’s daughter, had taken possession of the
mountain Aromata, commonly called Haramat, an ancient strong-
hold of his father’s, of which Michael had made himself master, while
yet a young man, after besieging it fifteen years. Netcho had also
united himself with Za Menfus Kedus, a man of great property in
that and the neighbouring country. Enderta is a flat, fertile territory,
in the very south-east of Abyssinia, depending on Tigré, and the
mountain Aromata is situated near the middle of that province;
before taking the field, Michael had directed the two Woldos to be
assassinated during a feast at Enderta, and their party dispersed of
itself without farther effort.

The mountain shewed a better countenance, and seemed to promise


employment for a long time; it was garrisoned by old and veteran
troops who had served under Ras Michael. Netcho was the son of his
hereditary enemy, anciently governor of that mountain, whom he
had reconciled by giving him his daughter in marriage;
notwithstanding which he had now rebelled, just as the Ras marched
to Maitsha against Fasil, by the persuasion of Gusho and Powussen,
purposely that he might form a diversion in Tigré, and for this
reason he had little hopes of mercy, if ever he fell into the hands of
Ras Michael. I had seen him often, and knew him; he was a tall,
thin, dull man, of a soft temper, and easily imposed upon. Za
Menfus, the other chief in the mountain, was a very active, resolute,
enterprising man, of whom Michael was afraid. He had a large
property all around the mountain; had been put in irons by Michael,
and had escaped; besides, on his return to Tigré, he had slain the
father of Guebra Mascal, Michael’s nephew by marriage, who was
commander in chief of all the musquetry Michael had brought from
Tigrè, so that he feared nothing so much as falling into Ras Michael’s
hands.

Ras Michael saw the danger of leaving an enemy so prepared and so


situated behind him; he therefore, before the rainy season was yet
finished, ordered the whole mountain to be surrounded with
barracks, or huts, for his soldiers; he also erected three houses for
himself, the principal officers, and the king. The country people were
called in to plow and sow the ground in the neighbourhood, so that
his intention was plainly never to rise from thence till he had
reduced the mountain of Aromata for the second time, after having
once before succeeded in taking it, after fifteen years siege, from
Netcho’s father. There we shall leave him at this siege, and return to
Gondar.

It was on the 10th of June that Gusho and Powussen entered


Gondar, and next day, the 11th, waited upon the queen; they both
beseeched her to return from Koscam to the capital, and take into
her hands the reins of government for the interim: this she positively
refused, unless peace was first made with Fasil. She said, that Fasil
was the only person who had endeavoured to avenge his master
Joas’s death; that he had continued till that day in arms in that
quarrel; and, notwithstanding all the offers that could be made her,
she never would come to Gondar, nor take any part in public
business, without this condition. Fasil, moreover, informed her by a
messenger, that there was no trust to be put either in Gusho or
Powussen; that they had failed in their engagement of following and
fighting Ras Michael in Maitsha, and had purposely staid at home till
a superior army should fall upon him singly, and ravage his country:
That they had broken their word a second time by entering into
Gondar without him; whereas the agreement was, that they all three
should have done this at once, to settle the form of government by
their joint deliberation. Many days passed in these negociations;
Fasil always promising to come upon some condition or other, but
never keeping his word, or stirring from Buré.

On the 20th, the queen’s servants, who had gone to offer terms of
reconciliation to Fasil on the part of Gusho and Powussen, returned
to their homes. The same day he ordered it to be proclaimed in the
market-place, That Ayto Tesfos should be governor of Samen, and
that whoever should rob on that road, or commit any violence,
should suffer death. This was an act of power, purposely intended to
affront Powussen and Gusho, and seemed to be opening a road for a
correspondence with Ras Michael; but, above all, it shewed
contempt for their party and their cause, and that he considered his
own as very distinct from theirs; for Tesfos had taken arms in the
late king’s lifetime, at the same time, and upon the same principles
and provocation, as Fasil, and had never laid down his arms, or
made peace with Ras Michael, but kept his government in defiance
of him.

On the 24th, for fear of giving umbrage, I waited upon Gusho and
Powussen at Gondar. I saw them in the same room where Ras
Michael used to sit. They were both lying on the floor playing at
draughts, with the figure of a draught-table drawn with chalk upon
the carpet; they offered no other civility or salutation, but, shaking
me each by the hand, they played on, without lifting their heads, or
looking me in the face.

Gusho began by asking me, “Would it not have been better if you
had gone with me to Amhara, as I desired you, when I saw you last
at Gondar? you would have saved yourself a great deal of fatigue
and trouble in that dangerous march through Maitsha.” To this I
answered, “It is hard for me, who am a stranger, to know what is
best to be done in such a country as this. I was, as you may have
heard, the king’s guest, and was favoured by him; it was my duty
therefore to attend him, especially when he desired it; and such I
am informed has always been the custom of the country; besides,
Ras Michael laid his commands upon me.” On this, says Powussen,
shaking his head, “You see he cannot forget Michael and the Tigré
yet.”—“Very naturally, added Gusho, they were good to him; he was
a great man in their time; they gave him considerable sums of
money, and he spent it all among his own soldiers, the king’s guard,
which they had given him to command after the Armenian. Yagoube
taught him and his brother George to ride on horseback like the
Franks, and play tricks with guns and pikes on horseback; folly, all of
it to be sure, but I never heard he meddled in affairs, or that he
spoke ill of any one, much less did any harm, like those rascals the
Greeks when they were in favour in Joas’s time, for it was not their
fault they did not direct every thing.”—“I hope I never did, said I;
sure I am I never so intended, nor had I any provocation. I have
received much good usage from every one; and the honour, if I do
not forget, of a great many professions and assurances of friendship
from you, said I, turning to Gusho. He hesitated a little, and then
added very superciliously, “Aye, aye, we were, as I think, always
friends.”—“You have had, says Powussen, a devilish many hungry
bellies since we left Gondar.”—“You will excuse me, Sir, replied I, as
to that article; I at no time ever found any difference whether you
was in Gondar or not.”—“There, says Gusho, by St Demetrius, there
is a truth for you, and you don’t often hear that in Begemder. May I
suffer death if ever you gave a jar of honey to any white man in
your life.”—“But I, says Powussen, sitting upright on the floor, and
leaving off play, will give you, Yagoube, a present better than
Gusho’s paultry jars of honey. I have brought with me, addressing
himself to me, your double-barrelled gun, and your sword, which I
took from that son of a wh—e Guebra Mehedin: by St Michael,
continued Powussen, if I had got hold of that infidel I would have
hanged him upon the first tree in the way for daring to say that he
was one of my army when he committed that unmanly robbery upon
your people. The Iteghé, your friend, would yesterday have given
me ten loads of wheat for your gun, for she believes I am to carry it
back to Begemder again, and do not mean to give it you, but come
to my tent to-morrow and you shall have it.” I very well understood
his meaning, and that he wanted a present; but was happy to
recover my gun at any rate.

I arose to get away, as what had passed did not please me; for
before the king’s retreat to Tigré, Gusho had sat in my presence
uncovered to the waist, in token of humility, and many a cow, many
a sheep, and jar of honey he had sent me; but my importance was
now gone with the king; I was fallen! and they were resolved, I saw,
to make me sensible of it. I told the queen, on my return, what had
passed. They are both brutes, said she; but Gusho should have
known better.

The next morning, being the 25th, about eight o’clock, I went to
Powussen’s tent. His camp was on the Kahha, near the church of
Ledata, or the Nativity. After waiting near an hour, I was admitted;
two women sat by him, neither handsome nor cleanly dressed; and
he returned me my gun and sword, which was followed by a small
present on my part. This, says he, turning to the women, is a man
who knows every thing that is to come; who is to die, and who is to
live; who is to go to the devil, and who not; who loves her husband,
and who cuckolds him.”—“Tell me then, Yagoube, says one of the
women, will Tecla Haimanout and Michael ever come to Gondar
again?”—“I do not know who you mean, Madam, said I; is it the
king and the Ras you mean?”—“Call him the King, says the other
woman in half a whisper; he loves the king.”—“Well, aye, come, let it
be the king then, says she; will the King and Ras Michael ever come
to Gondar?”—“Surely, said I, the king is king, and will go to any part
of his dominions he pleases, and when he pleases; do you not hear
he is already on his way?”—“Aye, aye, by G—d, says Powussen, no
fear he’ll come with a vengeance, therefore I think it is high time
that I was in Begemder.” He then shrugged up his shoulders, and
rose, upon which I took my leave. He had kept me standing all the
time; and when I came to Koscam I made my report as usual to the
Iteghé, who laughed very heartily, though the king’s arrival, which
was prophecied, was likely to be a very serious affair to her.

That very day, in the evening, came a servant from Ras Michael,
with taunts and severe threats to the queen, to Powussen, and
Gusho; he said he was very quickly bringing the king back to Gondar,
and being now old, intended to pass the rest of his life in Tigré; he,
therefore, hoped they would await the king’s coming to Gondar, and
chuse a Ras for his successor from among themselves, as he
understood they were all friends, and would easily agree, especially
as it was to oblige him.
On the 27th, Gusho and Powussen waited upon the queen to take
their leave. They declared it was not their intention to stay at
Gondar, merely to be alternately the subject of merriment and
scoffing to Michael and to Fasil, and upon this they immediately set
out on their way home, without drum or trumpet, or any parade
whatever.

Immediately after, arrived another servant from Fasil to the queen,


desiring that Powussen and Gusho might halt at Emfras, adding, that
he had just then begun his march from Buré, and would be at
Gondar in a few days. Gusho and Powussen did accordingly halt
there, and were detained for the space of six weeks, amused by
false pretences and messages, in very uncomfortable quarters, till
their armies disbanded, the soldiers, from hunger and constant
rains, deserted their leaders, and went every man to his home.

In the beginning of August the queen came to Gondar, and sat on


the throne all day. She had not been there these three years, and I
sincerely wished she had not gone then. It was in meditation that
day to chuse a new king; she was present at that deliberation, and
her intention was known to place a son of Aylo, Joas’s brother, a
mere infant, upon the throne. All those that were in fear of Michael,
and it was very general at that time, cried out against an infant king
at such a critical period; but, old as that princess was, the desire of
reigning had again returned.

Upon the return of the Iteghé that night to Koscam, Sanuda held a
council of the principal officers that had remained at Gondar, and
fixed upon one Welleta Girgis, a young man of about 24 years of
age, who had, indeed, been reputed Yasous’s son, but his low life
and manners had procured him safety and liberty by the contempt
they had raised in Ras Michael. His mother, indeed, was of a noble
origin, but so reduced in fortune as to have been obliged to gain her
livelihood by carrying jars of water for hire. The mother swore this
son was begot by Yasous, and as that prince was known not to have
been very nice in his choice of mistresses, or limited in their number,
it was, perhaps, as likely to be true as not, that Welleta Girgis was
his son. He took the name of Socinios. On the morning after, the
new king came to Koscam, attended by Sanuda and his party, with
guards, and all the ensigns of royalty. He threw himself at the
Iteghé’s feet, and begged her forgivenness if he had vindicated the
rights of his birth, without her leave or participation; he declared his
resolution to govern entirely by her advice, and begged her to grant
his request and come to Gondar, and again take possession of her
place as Iteghé, or regent of the kingdom.

It was about the 10th of August that an accident happened, which it


was generally thought would have determined Fasil to come to
Gondar. A common woman, wife of a Galla at Tchelga, a town upon
the frontiers of Sennaar, being at variance with her husband,
upbraided him with being the person that, with his own hand, had
assassinated the late king Joas. This Galla was immediately seized
and sent to Gondar, and was examined before the queen, where I
was present. He, with very little hesitation, declared, That, on a
night immediately after the battle of Azazo, he was sent for to Ras
Michael, who gave him some money and large promises, on
condition that he would undertake to murder the king that night.
The persons present were Laeca Netcho, and his two sons, Nebrit
Tecla and his two sons, Shalaka Becro relation to the present king,
and Woldo Hawaryat a monk of Tigré The prisoner said, he was
afraid, if he should refuse, they would murder him for the sake of
secrecy. He further said, that they had given him spirits to drink till
he was intoxicated, and then delivered to him the keys of the
apartments where Joas was confined, and they all went with him to
the palace; they found the unfortunate king alone, walking in his
apartment, very pensive, and, though at the late hour of twelve at
night, dressed in his usual habit. Two of Laeca Netcho’s sons
attempted to put a cord round his neck, but the king, being young
and strong, shewed a disposition to defend himself, and wrested the
cord out of the murderers hands; upon which Zor Woldo (the name
of the Galla) struck him a violent blow with a bludgeon on the head,
which felled him to the ground: The others then, with a short cord,
strangled him, the monk, Woldo Hawaryat, crying, dispatch him
quickly; after this they carried the body to the neighbouring church
of St Raphael, where a grave, or rather hole, was ready, into which
they threw it with the clothes just as he was. The prisoner said,
That, when they were carrying the king’s body out of the palace into
the church-yard, over a breach in the church-yard wall, they were
challenged by a person, who asked them what they were about? to
which they replied, Burying a stranger who died that day of a
pestilential fever.

Immediately upon this confession, the Galla was carried out and
hanged upon the daroo-tree before the king’s gate. Many
condemned this hasty execution, but many likewise thought it
prudent; for he had already named a great part of the people about
the queen as accessary to the death of her son.

I have said his name was Zor Woldo; he was of the race of Galla,
called Toluma, on the borders of Amhara; he had been formerly a
servant to Kasmati Becro; was of small stature, thin and lightly
made; his complexion a yellowish black, and singularly ill-favoured.
When under the tree, he acknowledged the murder of the king with
absolute indifference; nor did he desire any favour, or shew any fear
of death. Zor Woldo’s examination and declaration were sent
immediately to Fasil, who, as usual, promised to come to Gondar
quickly. The body of Joas was raised also, and laid in the church (in
his clothes, just as he was dug up) upon a little straw; his features
were easily distinguishable, but some animal had ate part of his
cheek.

The day after, I went from Koscam to Gondar without acquainting


the Iteghé, and took a Greek called Petros with me; he had been
chamberlain to Joas. We went about eleven o’clock in the forenoon
to the church of St Raphael, expecting to have seen many as curious
as ourselves, but, by reason of the atrociousness of the act, now for
the first time known to be true, and the fear of Ras Michael
threatening Gondar every day, not a living soul was there but a
monk belonging to the church itself, who kept the key. It was
thought criminal to know what it was apparent Michael had wished
to conceal. Petros no sooner saw his master’s face than, saying, It is
he! he ran off with all the speed possible: for my part, I was shocked
at the indecent manner in which the body was exposed; it affected
me more than the murder itself, for it appeared as if it had been
thrown down upon the ground, the head, arms, and legs lying in all
sorts of directions, and great part of his haunch and thigh bare. I
desired the monk to lock the door, and come along with me to
Petros’s house. Petros was a merchant who sold carpets, and such
sort of goods used in the country, which he brought from Cairo. It
was full an hour before we could make him behave sensibly, or
deliver me a small Persian carpet, such as Mahometans use to pray
upon, that is about seven feet long and four feet broad, and a web
of coarse muslin, which I bought of him. I told the priest (for Petros
absolutely refused to return to the church) how to lay the body
decently upon the carpet, and to cover his face and every part with
the muslin cloth, which might be lifted when any body came to see
the corpse.

The priest received the carpet with great marks of satisfaction, and
told me it was he who had challenged the murderers when carrying
the body over the wall; that he knew them well, and suspected they
had been about some mischief; and, upon hearing the king was
missing the next day, he was firmly convinced it was his body that
had been buried. Upon going also to the place early in the morning,
he had found one of the king’s toes, and part of his foot, not quite
covered with earth, from the haste the murderers were in when they
buried him; these he had put properly out of sight, and constantly
ever after, as he said, had watched the place in order to hinder the
grave from being disturbed, or any other person being buried there.

About the beginning of October, Guebra Selassé, a servant of the


king and one of the porters in the palace, came on a message to the
queen. It was a laconic one, but very easily understood.—“Bury your
boy, now you have got him; or, when I come, I will bury him, and
some of his relations with him.” Joas, upon this, was privately
buried. As this Selassé was a favourite of mine, who took care of my
shoes when I pulled them off to go into the audience-room, I waited
impatiently for this messenger’s coming to my apartment, which he
did late in the evening. I was alone, and he advanced so softly that I
did not at first hear or know him; but, when the door was shut, he
began to give two or three capers; and, pulling out a very large
horn, “Drink! drink! G—d d—n! repeating this two or three times,
and brandishing his horn over his head. Selassé, said I, have you
lost your senses, or are you drunk? you used to be a sober
man.”—“And so I am yet, says he, I have not tasted a morsel since
noon; and, being tired of running about on my affairs, I am now
come to you for my supper, as I am sure you’ll not poison me for my
master’s sake, nor for my own either, and I have now enemies
enough in Gondar.”—“I then asked, How is the king?”—“Did not you
hear, said he—Drink!—the king told me to say this to you that you
might know me to be a true messenger.” And an Irish servant of
mine, opening the door in the instant, thinking it was I that called
drink! Selassé adroitly continued, “He knows you are curious in
horns, and sent you this, desiring me first to get it filled at the
Iteghé’s with good red wine, which I have done; and now, Hallo!
Drink! Englishman!” He then added in a whisper, when the servant
had shut the door, “I’ll tell it you all after supper, when the house is
quiet, for I sleep here all night, and go to Tigré to-morrow morning.”

The time being come, he informed me Ras Michael and Fasil had
made peace; Welleta Michael, the Ras’s nephew, taken by Fasil at
the battle of Limjour, had been the mediator; that the king and
Michael, by their wise behaviour, had reconciled Tigré as one man,
and that the Ras had issued a proclamation, remitting to the
province of Tigré their whole taxes from the day they passed the
Tacazzé till that time next year, in consideration of their fidelity and
services; and this had been solemnly proclaimed in several places by
beat of drum. The Ras declared, at the same time, that he would,
out of his own private fortune, without other assistance, bear the
expence of the campaign till he seated the king on his throne in
Gondar. A kind of madness, he said, had seized all ranks of people to
follow their sovereign to the capital; that the mountain Haramat still
held out; but that all the principal friends, both of Za Menfus and
Netcho, had been up with the governors of that fortress offering
terms of peace and forgivenness, and desiring they would not be an
obstacle in the king’s way, and a hinderance to his return, but that
all terms had been as yet refused; however, says he, you know the
Ras as well as I, he will play them a trick some of these days,
winking with his eye, and then crying out, Drink!

I asked him if any notice had been taken of the carpet I had
procured to cover the body of Joas, and hoped it had given no
umbrage. He said, “No; none at all; on the contrary, the king had
said twenty kind things upon it; that he was present also when a
priest told it to Ras Michael, who only observed, Yagoube, who is a
stranger in this country, is shocked to see a man taken out of his
grave, and thrown like a dog upon the bare floor. This was all
Michael said, and he never mentioned a word on the subject
afterwards;” nor did he, or the king, ever speak of it to me upon
their return to Gondar.

The Iteghé, too, had much commended me, so did all the nobility,
more than the thing deserved; for surely common humanity dictated
thus much, and the fear of Michael, which I had not, was the only
cause that so proper an action was left in a stranger’s power. Even
Ozoro Esther, enemy to Joas on account of the death of her husband
Mariam Barea, after I had attended her one Sunday from church to
the house of the Iteghé, and when she was set down at the head of
a circle of all those that were of distinction at the court, called out
aloud to me, as I was passing behind, and pointing to one of the
most honourable seats in the room, said, Sit down there, Yagoube;
God has exalted you above all in this country, when he has put it in
your power, though but a stranger, to confer charity upon the king of
it. All was now acclamation, especially from the ladies; and, I
believe, I may safely say, I had never in my life been a favourite of
so many at one time.
I dispatched Guebra Selassé with a message to the king, that I was
resolved now to try once more a journey to the head of the Nile;
that I thought I should have time to be there, and return to Gondar,
before the Tacazzé was fordable, soon after which I expected he
would cross it, and that nothing but want of health would prevent
me from joining him in Belessen, or sooner, if any opportunity should
offer.

Before I took my last resolutions I waited upon the queen. She was
exceedingly averse to the attempt; she bade me remember what the
last trial had cost me; and begged me to defer any further thoughts
of it till Fasil arrived in Gondar; that she would then deliver me into
his hands, and procure from him sure guides, together with a safe
conduct. She bade me beware also of troops of Pagan Galla which
were passing and repassing to and from his army, who, if they fell in
with me, would murder me without mercy. She added, that the
priests of Gojam and Damot were mortal enemies to all men of my
colour, and, with a word, would raise the peasants against me. This
was all true; but then many reasons, which I had weighed well,
concurred to shew that this opportunity, dangerous as it was, might
be the only time in which my enterprise could be practicable; for I
was confident a speedy rupture between Fasil and Michael would
follow upon the king’s return to Gondar. I determined therefore to
set out immediately without farther loss of time.
CHAP. VIII.
Second Journey to discover the Source of the Nile—Favourable Turn
of the King’s Affairs in Tigré—We fall in with Fasil’s Army at Bamba.

T HOUGH the queen shewed very great dislike to my attempting


this journey at such a time, yet she did not positively command
the contrary; I was prepared, therefore, to leave Gondar the 27th of
October 1770, and thought to get a few miles clear of the town, and
then make a long stretch the next day. I had received my quadrant,
time-keeper, and telescopes from the island of Mitraha, where I had
placed them after the affair of Guebra Mehedin, and had now put
them in the very best order.

But, about twelve o’clock, I was told a message from Ras Michael
had arrived with great news from Tigré. I went immediately to
Koscam as fast as I could gallop, and found there Guebra Christos, a
man used to bring the jars of bouza to Ras Michael at his dinner and
supper: low men are always employed on such errands, that they
may not, from their consequence excite a desire of vengeance. The
message that he brought was to order bread and beer to be ready
for 30,000 men who were coming with the king, as he had just
decamped from before the mountain Haramat, which he had taken,
and put Za Menfus to the sword, with every man that was in it: this
message struck the queen with such a terror that she was not visible
the whole day.

After asking the messenger if he had any word from the king to me,
he said, “Very little;” that the king had called him to tell me he
should soon begin his march by Belessen; and that he would send
for me to meet him when he should arrive at Mariam-Ohha; he told
me besides, that the king had got a stone for me with writing upon
it of old times, which he was bringing to me; that it had been dug up
at Axum, and was standing at the foot of his bed, but that he did not
order him to tell me this, and had only learned it from the servants.
My curiosity was very much raised to know what this stone could be,
but I soon saw it was in vain to endeavour to learn any thing from
Guebra Christos; he answered in the affirmative to every inquiry:
when I asked if it was blue, it was blue; and if black, it was black; it
was round, and square, and oblong, just as I put my question to
him: all he knew about it at last, he said, was, that it cured all sort
of sickness; and, if a man used it properly, it made him invulnerable
and immortal: he did not, however, pretend to warrant this himself,
but swore he had the account from a priest of Axum who knew it. I
was perfectly satisfied all further inquiry was unnecessary; he had
got a very plentiful portion of bouza from his friends, and was, I
saw, fast engaged in the pursuit of more, so I gave him a small
present for his good news, and took my leave, my mind being full of
reflections upon the king’s goodness, who, after such an absence,
and in so critical a situation as he then was, still remembered the
trifling pursuits in which he had seen me often engaged.

In the afternoon I received a message from Ozoro Esther, as brought


to her by a servant of Ras Michael. It seems the giving up the king’s
revenue due from Tigré, and all sort of taxes upon the inhabitants,
had interested the whole province so strongly, that all of them, as
one man, endeavoured to remove the obstacle which stood in the
way of the king’s return: Michael, moreover, offered peace and
pardon to the rebels, certain compensations, and an amnesty of all
that was past. All the friends, both of Netcho and Za Menfus, and
the other leaders upon the mountain, endeavoured to persuade
them to accept the terms offered, whilst all the priests and hermits,
eminent for sanctity, became as mediators between them and Ras
Michael: this intercourse, though it had no effect upon Za Menfus,
had seduced Netcho, and opened a large field for treachery.

In the midst of this treaty, Kefla Yasous, with a detachment of


chosen men, in a very stormy night, was appointed to ascend up a
private path to that part of the mountain where Netcho kept the
principal guard, and being admitted, found the garrison mostly
asleep; he surprised and obliged them to surrender, with very little
bloodshed; Za Menfus was taken prisoner, and, while Kefla Yasous
conducted him to the camp, was met by Guebra Mascal, who thrust
him through with a lance, as a retaliation for his father’s death.
Netcho and the rest of the garrison being pardoned, all joined Ras
Michael’s army. I looked upon these news as a good omen, and
experienced a degree of confidence and composure of mind to which
I for a long time had been a stranger. I slept sound that night, and it
was not till half after nine in the morning that I was ready for my
journey.

In the evening before, I had endeavoured to engage my old


companion Strates to accompany me on this attempt as he had
done, on the former; but the recollection of past dangers and
sufferings was not yet banished from his mind; and upon my asking
him to go and see the head of this famous river, he coarsely,
according to his stile, answered, Might the devil fetch him if ever he
sought either his head or his tail again.

It was on the 28th of October, at half past nine in the morning, that
we left Gondar, and passed the river Kahha at the foot of the town;
our route was W. S. W. the road a little rugged upon the side of a
hill, but the day was fair, with sunshine; and a small breeze from the
north had risen with the sun, and made the temperature of the air
perfectly agreeable. We left the church of Ledeta about a mile on
the right, and passed by several poor villages called Abba Samuel;
thence we came to the small river Shimfa, then to the Dumaza,
something larger. Upon the banks of this river, very pleasantly
situated, is Azazo, a country-house built by the late king Yasous,
who often retired here to relax himself with his friends. It is
surrounded, I may say covered, with orange-trees, so as to be
scarcely seen; the trees are grown very large and high; they are
planted without order, the only benefit expected from them being
the shade. At some small distance is the village Azazo, originally
built for the accommodation of the king’s servants while he resided
there, but now chiefly occupied by monks belonging to the large
church of Tecla Haimanout, which is on a little hill adjoining. Azazo,
though little, is one of the most chearful and pleasant villages in the
neighbourhood of Gondar. The lemon-tree seems to thrive better
and grow higher than the orange; but the house itself is going fast
to ruin, as the kings of this country have a fixed aversion to houses
built by their predecessors.

The Dumaza is a very clear and pleasant stream, running briskly


over a small bed of pebbles: both this river and the Shimfa come
from Woggora on the N. W. they pass the hill of Koscam, called
Debra Tzai, join below Azazo, and, traversing the flat country of
Dembea, they meet the Angrab, which passes by Gondar, and with it
fall into the Tacazzè, or Atbara.

At noon we passed a small rivulet called Azzargiha, and, soon after,


the Chergué, where there began a most violent storm of rain, which
forced us, much against our will, into the village, one of the most
miserable I ever entered; it consisted of small hovels built with
branches of trees, and covered with thatch of straw. These rains that
fall in the latter season are what the natives very much depend
upon, and without which they could not sow the latter crops; for,
though it rains violently every day from May to the beginning of
September, by the end of October the ground is so burnt that the
country would be unfit for culture.
Our quarters here were so bad that we were impatient to depart,
but came to a water just below Chergué, which quickly made us
wish ourselves back in the village; this is a torrent that has no
springs in the hills, but only great basons, or reservoirs, of stone;
and, though it is dry all the year else, yet, upon a sudden, violent
shower, as this was, it swells in an instant, so that it is impassable
for man or horse by any device whatever. This violence is of short
duration; we waited above half an hour, and then the peasants
shewed us a place, some hundred yards above, where it was
shallower; but even here we passed with the utmost difficulty, from
the impetuosity of the stream, after getting all possible assistance
from four people of the village; but we stood very much in need of
some check to our impatience, so eager were we to get forward and
finish our journey before some revolution happened.

We had not many minutes been delivered from this torrent, before
we passed two other rivers, the one larger, the other smaller. All
these rivers come from the north-west, and have their sources in the
mountains a few miles above, towards Woggora, from which, after a
short course on the side of the hills, they enter the low, flat country
of Dembea, and are swallowed up in the Tzana.

We continued along the side of the hill in a country very thinly


inhabited; for, it being directly in the march of the army, the
peasants naturally avoided it, or were driven from it. Our road was
constantly intersected by rivers, which abound, in the same space,
more than in any other country in the world. We then came to the
river Derma, the largest and most rapid we had yet met with, and
soon after a smaller, called Ghelghel Derma. In the afternoon, at a
quarter past three, we passed another river, called Gavi-Corra;
these, like the others, all point as radii to the center of the lake, in
which they empty themselves. A little before four o’clock we
encamped on the side of the river Kemona. Upon the hill, on the
other side of the river, stands the village of that name; it was full of
cattle, very few of which we had seen during the fore-part of the
journey; we had all that day travelled six hours and a quarter, which
we computed not to exceed 14 miles: the reason of this slowness
was the weight of my quadrant, which, though divided into two,
required four men to carry it, tied upon bamboo, as upon two chair-
poles. The time-keeper and two telescopes employed two men
more. We pitched our tent on the side of the river, opposite to the
village, and there passed the night.

On the 29th of October, at seven in the morning, we left our station,


the river Kemona; our direction was W. S. W. after, about an hour,
we came to a church called Abba Abraham, and a village that goes
by the same name; it is immediately upon the road on the left hand.
At the distance of about a mile are ten or twelve villages, all
belonging to the Abuna, and called Ghendi, where many of his
predecessors have been buried. The low, hot, unwholesome, woody
part of the Abyssinian Kolla, and the feverish, barren province of
Walkayt, lay at the distance of about fourteen or sixteen miles on
our right. We had been hitherto ascending a gentle rising-ground in
a very indifferent country, the sides of the hill being skirted with little
rugged wood, and full of springs, which join as they run down to the
low country of Walkayt. We saw before us a small hill called Guarré,
which is to the south-west. At half past ten we rested under the
before-mentioned hill; it stands alone in the plain, in shape like a
sugar-loaf, and seems almost as regular as if it had been a work of
art. At a quarter past eleven we resumed our journey, our course
always nearly west south-west; we passed the small village of
Bowiha, at the distance of about a mile; and, on the left, about six
miles, is Gorgora, a peninsula that runs into the lake Tzana for
several miles.

There was one of the first and most magnificent churches and
monasteries of the Portuguese Jesuits, in the time of their mission to
convert this country: Socinios, then king, gave them the grounds,
with money for the expence; they built it with their own hands, and
lined it elegantly with cedar. The king, who was a zealous Roman
Catholic, chose afterwards a country-house for himself there, and
encouraged them much by his presents and by his charity; it is one
of the pleasantest situations in the world; the vast expanse of the
lake is before you; Dembea, Gojam, and Maitsha, flat and rich
countries all round, are in view; and the tops of the high hills of
Begemder and Woggora close the prospect.

The lake here, I am told, has plenty of fish, which is more than can
be said for many of the other parts of it; the fish are of two kinds,
both of them seemingly a species of what the English call bream. I
never could make them to agree with me, which I attribute to the
drug with which they are taken; it is of the nature of nux vomica,
pounded in a morter, and thrown into streams, where they run into
the lake; the fish, feeding there, are thus intoxicated and taken;
however, it would admit of a doubt of this being the reason, because
the queen and all the great people in Gondar eat them in Lent
without any bad consequences.

The great elevation of the peninsula of Gorgora makes it one of the


healthiest, as well as beautiful parts of the country; for, out of this
neck of land, at several different seasons of the year, the inhabitants
of the flat country suffer from malignant fevers. From Gondar hither
we had always been edging down to the lake.

At a quarter before noon we halted to rest upon the banks of a small


river called Baha; the country was rich, and cultivated; great part of
it, too, was laid out in pasture, and flocked with an immense
quantity of cattle. At one o’clock we resumed our journey, going
west south-west as before; we were apparently turning the north
end of the lake as short as possible, to set our face due south to the
country of the Agows. At a quarter before three we pitched our tents
at Bab Baha, after having travelled five hours and three quarters,
which we computed to be equal to twelve miles. The first part of our
journey this day was not like that of the day before; the road was,
indeed, rough, burled through very agreeable valleys and gentle-
rising hills; it appeared, on the whole, however, that we had
ascended considerably since we left Gondar.
The country about Bab Baha is the richest in Abyssinia; this on the
south, and Woggora on the north, are the two granaries that supply
the rest of the kingdom. Bab Baha is a parcel of small villages, more
considerable in number and strength than those at Kemona, and is
near the lake Tzana. The queen and many of her relations have here
their houses and possessions, and these, therefore, being respected
by Michael, had not been involved in the devastation of the late war.
The villages are all surrounded with Kol-quall trees, as large at the
trunk as those we met on the side of the mountain of Taranta, when
we ascended it on our journey from Masuah to enter into the
province of Tigré; but the tree wants much of the beauty of those of
Tigré; the branches are fewer in number, less thorny, and less
indented, which seems to prove that this is not the climate for them.

The 30th of October, at six in the morning, we continued our journey


from Bab Baha still rounding the lake at W. S. W. and on the very
brink of it: the country here is all laid out in large meadows of a
deep, black, rich soil, bearing very high grass, through the midst of
which runs the river Sar-Ohha, which, in English, is the Grassy River;
it is about forty yards broad and not two feet deep, has a soft clay
bottom, and runs from north to south into the lake Tzana.

We turned out of the road to the left at Bab Baha, and were obliged
to go up the hill; in a quarter of an hour we reached the high road to
Mescala Christos. At seven o’clock we began to turn more to the
southward, our course being S. W.; three miles and a half on our
right remained the village of Tenkel; and four miles and a half that of
Tshemmera to the N. N. W.; we were now close to the border of the
lake, whose bottom here is a fine sand. Neither the fear of
crocodiles, nor other monsters in this large lake, could hinder me
from swimming in it for a few minutes. Though the sun was very
warm, the water was intensely cold, owing to the many fresh
streams that pour themselves continually into the lake Tzana from
the mountains. The country here is sown with dora, which is maize,
or millet; and another plant, not to be distinguished from our
marigold either in size, shape, or foliage; it is called Nook118, and
furnishes all Abyssinia with oil for the kitchen, and other uses.

At a quarter past nine we rested a little at Delghi Mariam; the village


called simply Delghi, adjoining to it, is but small, and on the S. W. is
the hill of Goy Mariam, where the queen-mother has a house. All the
habitations in this country were burnt by Ras Michael in his return to
Gondar after the battle of Fagitta. The mountain Debra Tzai above
Koscam, was seen this day at N. E. and by E. from us.

At a quarter past ten we again set out, our route being S. W. at


eleven we left the small village Arrico, about two miles on our right.
At a quarter past eleven we halted to rest our men; we passed the
church of St Michael on our right, and at a quarter past one we
passed two small islands in the lake, called Kedami Aret; and, half an
hour after, we passed a small river, and came to Mescala Christos, a
large village upon a high mountain, the summit of which it occupies
entirely; it is surrounded on both sides by a river, and the descent is
steep and dangerous. We thought to have staid here all night; but,
after mounting the hill with great fatigue and trouble, we found the
whole village abandoned, on intelligence that Waragna Fasil was on
his march to Gondar, and not far distant.

This intelligence, which came all at once upon us, made us lay aside
the thoughts of sleeping that night; we descended the hill of
Mescala Christos in great haste, and with much difficulty, and came
to the river Kemon below it, clear and limpid, but having little water,
running over a bed of very large stones. This river, too, comes from
the north-west, and falls into the lake a little below; we rested on its
banks half an hour, the weather being very sultry; from this place we
had a distinct view of the Nile, where, after crossing the lake, it
issues out near Dara, the scene of our former misfortunes; we set it
carefully by the compass, and it bore nearly S. W.

We began our journey again at three quarters after two, and at half
after three we passed a river, very clear, with little water, the name
of which I have forgot; by the largeness of its bed it seemed to be a
very considerable stream in winter; at present it had very little water,
but a fine gravelly bottom; here we met multitudes of peasants
flying before the army of Fasil, many of whom, seeing us, turned out
of the way; one of these was a servant of Guebra Ehud, brother to
Ayto Aylo, my most intimate friend: he told us it was very possible
that Fasil would pass us that night, advised us not to linger in the
front of such an army, but fall in as soon as possible with his Fit-
Auraris, rather than any other of his advanced posts; he was
carrying a message to his master’s brother at Gondar. I told him I
had rather linger in the front of such an army than in the rear of it,
and should be very sorry to be detained long, even in the middle of
it; that I only wished to salute Fasil, and procure a pass and
recommendations from him to Agow Midre.

Ayto Aylo’s servant, who was with me, presently made acquaintance
with this man, and I trusted him to learn from him as much as he
knew about Fasil; the result was, that Fasil pretended to be in a
violent hurry, from what motive was not known; but that he, at the
same time, marched very slowly, contrary to his usual custom; that
his speech and behaviour promised peace, and that he had hurt
nobody on the way, but proclaimed constantly, that all people should
keep their houses without fear; that Ayto Woldo of Maitsha, a great
robber, was his Fit-Auraris, and never distant from him more than
three miles; that the troops of Agow, Maitsha, and Damot, were with
him, and with some Galla of Gojam and Metchakel composed the
van and center of his army, whilst his rear consisted of wild lawless
Galla, whom he had brought from the other side of the Nile from
Bizamo, his own country, and were commanded by Ayto Welleta
Yasous, his great confident; that these Galla were half a day
generally behind him, and there was some talk that, the same day,
or the next, he was to send these invaders home; that he marched
as if he was in fear; always took strong posts, but had received
every body that came to him, either from the country or Gondar,
affably and kindly enough, but no one knew any thing of his
intentions.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookultra.com

You might also like