0% found this document useful (0 votes)
2 views85 pages

9372

Invent Your Own Computer Games with Python (3rd Edition) by Al Sweigart is a programming book aimed at beginners, particularly kids and teenagers, to learn Python through game creation. The book is available under a Creative Commons license, allowing for noncommercial sharing and modification with proper attribution. This edition has been streamlined for clarity and ease of understanding, featuring the same source code as the previous edition but with expanded explanations.

Uploaded by

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

9372

Invent Your Own Computer Games with Python (3rd Edition) by Al Sweigart is a programming book aimed at beginners, particularly kids and teenagers, to learn Python through game creation. The book is available under a Creative Commons license, allowing for noncommercial sharing and modification with proper attribution. This edition has been streamlined for clarity and ease of understanding, featuring the same source code as the previous edition but with expanded explanations.

Uploaded by

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

Invent Your Own Computer Games with Python 3rd

Edition Al Sweigart download

https://ebookgate.com/product/invent-your-own-computer-games-
with-python-3rd-edition-al-sweigart/

Get Instant Ebook Downloads – Browse at https://ebookgate.com


Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats

Invent Your Own Computer Games with Python 4th Edition


Al Sweigart

https://ebookgate.com/product/invent-your-own-computer-games-
with-python-4th-edition-al-sweigart/

OpenCV Computer Vision with Python 1st Edition Howse

https://ebookgate.com/product/opencv-computer-vision-with-
python-1st-edition-howse/

Make Games with Python 1st edition Edition Sean M.


Tracey

https://ebookgate.com/product/make-games-with-python-1st-edition-
edition-sean-m-tracey/

Make Fun Create Your Own Toys Games and Amusements


First Edition Bob Knetzger

https://ebookgate.com/product/make-fun-create-your-own-toys-
games-and-amusements-first-edition-bob-knetzger/
OpenCV with Python blueprints design and develop
advanced computer vision projects using OpenCV with
Python 1st Edition Michael Beyeler

https://ebookgate.com/product/opencv-with-python-blueprints-
design-and-develop-advanced-computer-vision-projects-using-
opencv-with-python-1st-edition-michael-beyeler/

Learning Opencv 3 Computer Vision with Python 2nd


Edition Joe Minichino

https://ebookgate.com/product/learning-opencv-3-computer-vision-
with-python-2nd-edition-joe-minichino/

On your own how to start your own CPA firm Second


Edition Poe

https://ebookgate.com/product/on-your-own-how-to-start-your-own-
cpa-firm-second-edition-poe/

Computational Physics Problem Solving with Python 3rd


Edition Páez

https://ebookgate.com/product/computational-physics-problem-
solving-with-python-3rd-edition-paez/

Tiny Python Projects Learn coding and testing with


puzzles and games 1st Edition Ken Youens-Clark

https://ebookgate.com/product/tiny-python-projects-learn-coding-
and-testing-with-puzzles-and-games-1st-edition-ken-youens-clark/
Invent Your Own
Computer Games
with Python
3rd Edition

By Al Sweigart
ii http://inventwithpython.com

Copyright © 2008-2015 by Albert Sweigart

Some Rights Reserved. "Invent Your Own Computer Games with Python" ("Invent with Python")
is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States
License.

You are free:

To Share — to copy, distribute, display, and perform the work

To Remix — to make derivative works

Under the following conditions:

Attribution — You must attribute the work in the manner specified by the author or
licensor (but not in any way that suggests that they endorse you or your use of the work).
(Visibly include the title and author’s name in any excerpts of this work.)

Noncommercial — You may not use this work for commercial purposes.

Share Alike — If you alter, transform, or build upon this work, you may distribute
the resulting work only under the same or similar license to this one.

Your fair use and other rights are in no way affected by the above. There is a human-readable
summary of the Legal Code (the full license), located here:
http://creativecommons.org/licenses/by-nc-sa/3.0/us/legalcode

The source code in this book is released under a BSD 2-Clause license, located here:
http://opensource.org/licenses/BSD-2-Clause

Book Version 3.0.1, ISBN 978-1503212305

Attribution: Treasure chest icon by Victor Escorsin, Sonar icon by Pantelis Gkavos

If you’ve downloaded this book from a torrent, it’s probably out of date. Go
to http://inventwithpython.com to download the latest version instead.

Post questions to http://invpy.com/forum


For Caro, with more love

than I ever knew I had.


iv http://inventwithpython.com

A Note to Parents and Fellow Programmers


Thank you for reading this book. My motivation for writing it came from a gap I saw in today’s
literature for kids interested in learning to program. I started programming in the BASIC
programming language with a book similar to this one.

During the course of writing this, I've realized how a modern language like Python has made
programming far easier and versatile for a new generation of programmers. Python has a gentle
learning curve while still being a serious language used by programmers professionally.

The current crop of programming books fall into two categories. First, books that didn’t teach
programming so much as “game creation software” or a dumbed-down languages to make
programming “easy” to the point that it is no longer programming. Or second, they taught
programming like a mathematics textbook: all principles and concepts with little application
given to the reader. This book takes a different approach: show the source code for games right
up front and explain programming principles from the examples.

I’ve also made this book available under the Creative Commons license, which allows you to
make copies and distribute this book (or excerpts) with my full permission, as long as attribution
to me is left intact and it is used for noncommercial purposes. (See the copyright page.) I want to
make this book a gift to a world that has given me so much.

What’s New in the 3rd Edition?


The third edition features no new content since the second edition. However, the third edition has
been streamlined to cover the same content with 20% fewer pages. Explanations have been
expanded where needed and ambiguities clarified.

Chapter 9 was split into chapters 9 and 9½ to keep the chapter numbering the same.

The source code has intentionally been kept the same as the second edition to prevent confusion.
If you’ve already read the second edition, there’s no reason to read this book. However, if you are
new to programming, or introducing a friend to programming, this third edition will make the
process easier, smoother, and more fun.

Post questions to http://invpy.com/forum


Who is this book for?
Programming isn’t hard. But it is hard to find learning materials that teach you to do interesting
things with programming. Other computer books go over many topics most newbie coders don’t
need. This book will teach you how to program your own computer games. You’ll learn a useful
skill and have fun games to show for it! This book is for:

 Complete beginners who want to teach themselves computer programming, even if they
have no previous experience programming.
 Kids and teenagers who want to learn programming by creating games.
 Adults and teachers who wish to teach others programming.
 Anyone, young or old, who wants to learn how to program by learning a professional
programming language.
vi http://inventwithpython.com

TABLE OF CONTENTS
Chapter 1 - Installing Python ........................................................................................................... 1
Downloading and Installing Python ............................................................................................. 2
Starting IDLE ............................................................................................................................... 3
How to Use this Book .................................................................................................................. 4
Finding Help Online .................................................................................................................... 5
Chapter 2 - The Interactive Shell ..................................................................................................... 6
Some Simple Math Stuff .............................................................................................................. 6
Evaluating Expressions ................................................................................................................ 8
Storing Values in Variables ......................................................................................................... 9
Chapter 3 - Writing Programs ........................................................................................................ 14
Strings ........................................................................................................................................ 14
String Concatenation.................................................................................................................. 15
Writing Programs in IDLE’s File Editor.................................................................................... 15
Hello World! .............................................................................................................................. 16
Saving Your Program ................................................................................................................ 17
Opening The Programs You’ve Saved....................................................................................... 18
How the “Hello World” Program Works ................................................................................... 20
Variable Names .......................................................................................................................... 22
Chapter 4 - Guess the Number ....................................................................................................... 24
Sample Run of Guess the Number ............................................................................................. 24
Source Code of Guess the Number ............................................................................................ 25
import statements ................................................................................................................... 26
The random.randint() Function....................................................................................... 27
Loops ......................................................................................................................................... 29
Blocks ........................................................................................................................................ 29
The Boolean Data Type ............................................................................................................. 30

Post questions to http://invpy.com/forum


Comparison Operators ............................................................................................................... 30
Conditions .................................................................................................................................. 31
The Difference Between = and == ............................................................................................ 32
Looping with while statements ............................................................................................... 33
Converting Values with the int(), float(), and str() Functions .................................. 34
if statements ............................................................................................................................. 36
Leaving Loops Early with the break statement....................................................................... 37
Flow Control Statements............................................................................................................ 39
Chapter 5 - Jokes............................................................................................................................ 41
Making the Most of print() .................................................................................................. 41
Sample Run of Jokes .................................................................................................................. 41
Source Code of Jokes ................................................................................................................. 41
Escape Characters ...................................................................................................................... 42
Quotes and Double Quotes ........................................................................................................ 43
print()’s end Keyword Argument....................................................................................... 44
Chapter 6 - Dragon Realm ............................................................................................................. 46
Functions .................................................................................................................................... 46
How to Play Dragon Realm ....................................................................................................... 46
Sample Run of Dragon Realm ................................................................................................... 47
Source Code of Dragon Realm .................................................................................................. 47
def Statements .......................................................................................................................... 48
Boolean Operators ..................................................................................................................... 50
Return Values............................................................................................................................. 54
Global Scope and Local Scope .................................................................................................. 55
Parameters .................................................................................................................................. 56
Designing the Program .............................................................................................................. 60
Chapter 7 - Using the Debugger .................................................................................................... 62
Bugs! .......................................................................................................................................... 62
The Debugger............................................................................................................................. 63
viii http://inventwithpython.com

Stepping ..................................................................................................................................... 65
Find the Bug............................................................................................................................... 68
Break Points ............................................................................................................................... 71
Example Using Break Points ..................................................................................................... 72
Chapter 8 - Flow Charts ................................................................................................................. 75
How to Play Hangman ............................................................................................................... 75
Sample Run of Hangman ........................................................................................................... 75
ASCII Art ................................................................................................................................... 77
Designing a Program with a Flowchart...................................................................................... 77
Creating the Flow Chart ............................................................................................................. 79
Chapter 9 - Hangman ..................................................................................................................... 88
Source Code of Hangman .......................................................................................................... 88
Multi-line Strings ....................................................................................................................... 92
Constant Variables ..................................................................................................................... 93
Lists ............................................................................................................................................ 93
Methods ..................................................................................................................................... 97
The lower() and upper() String Methods ......................................................................... 98
The reverse() and append() List Methods.................................................................... 100
The split() List Method ..................................................................................................... 100
The range() and list() Functions................................................................................... 103
for Loops ............................................................................................................................... 104
Slicing ...................................................................................................................................... 106
elif (“Else If”) Statements .................................................................................................... 109
Chapter 9 ½ - Extending Hangman .............................................................................................. 117
Dictionaries .............................................................................................................................. 118
The random.choice() Function ....................................................................................... 121
Multiple Assignment ................................................................................................................ 122
Chapter 10 - Tic Tac Toe ............................................................................................................. 125
Sample Run of Tic Tac Toe ..................................................................................................... 125

Post questions to http://invpy.com/forum


Source Code of Tic Tac Toe .................................................................................................... 127
Designing the Program ............................................................................................................ 131
Game AI ................................................................................................................................... 133
References ................................................................................................................................ 138
Short-Circuit Evaluation .......................................................................................................... 146
The None Value ...................................................................................................................... 149
Chapter 11 - Bagels ...................................................................................................................... 157
Sample Run of Bagels .............................................................................................................. 157
Source Code of Bagels ............................................................................................................. 158
The random.shuffle() Function..................................................................................... 161
Augmented Assignment Operators .......................................................................................... 163
The sort() List Method ....................................................................................................... 164
The join() String Method .................................................................................................... 165
String Interpolation .................................................................................................................. 167
Chapter 12 - Cartesian Coordinates ............................................................................................. 171
Grids and Cartesian Coordinates.............................................................................................. 171
Negative Numbers ................................................................................................................... 173
Math Tricks .............................................................................................................................. 175
Absolute Values and the abs() Function .............................................................................. 177
Coordinate System of a Computer Screen ............................................................................... 178
Chapter 13 - Sonar Treasure Hunt ............................................................................................... 179
Sample Run of Sonar Treasure Hunt ....................................................................................... 180
Source Code of Sonar Treasure Hunt ...................................................................................... 183
Designing the Program ............................................................................................................ 188
An Algorithm for Finding the Closest Treasure Chest ............................................................ 195
The remove() List Method .................................................................................................. 197
Chapter 14 - Caesar Cipher .......................................................................................................... 207
Cryptography ........................................................................................................................... 207
The Caesar Cipher.................................................................................................................... 208
x http://inventwithpython.com

ASCII, and Using Numbers for Letters ................................................................................... 209


The chr() and ord() Functions .......................................................................................... 210
Sample Run of Caesar Cipher .................................................................................................. 211
Source Code of Caesar Cipher ................................................................................................. 212
How the Code Works ............................................................................................................... 213
The isalpha() String Method ............................................................................................ 215
The isupper() and islower() String Methods.............................................................. 216
Brute Force............................................................................................................................... 218
Chapter 15 - Reversi .................................................................................................................... 222
Sample Run of Reversi ............................................................................................................ 224
Source Code of Reversi ........................................................................................................... 227
How the Code Works ............................................................................................................... 235
The bool() Function............................................................................................................. 244
Chapter 16 - Reversi AI Simulation............................................................................................. 258
Making the Computer Play Against Itself................................................................................ 259
Percentages .............................................................................................................................. 263
The round() function ........................................................................................................... 264
Sample Run of AISim2.py ....................................................................................................... 265
Comparing Different AI Algorithms........................................................................................ 266
Chapter 17 - Graphics and Animation ......................................................................................... 274
Installing Pygame..................................................................................................................... 274
Hello World in Pygame ........................................................................................................... 275
Source Code of Hello World.................................................................................................... 275
Running the Hello World Program .......................................................................................... 277
Tuples....................................................................................................................................... 278
RGB Colors.............................................................................................................................. 279
Fonts, and the pygame.font.SysFont() Function ........................................................ 280
Attributes ................................................................................................................................. 282
Constructor Functions .............................................................................................................. 283

Post questions to http://invpy.com/forum


Pygame’s Drawing Functions .................................................................................................. 283
Events and the Game Loop ...................................................................................................... 288
Animation ................................................................................................................................ 289
Source Code of the Animation Program .................................................................................. 289
How the Animation Program Works ....................................................................................... 292
Running the Game Loop .......................................................................................................... 295
Chapter 18 - Collision Detection and Keyboard/Mouse Input ..................................................... 300
Source Code of the Collision Detection Program .................................................................... 300
The Collision Detection Algorithm.......................................................................................... 304
Don’t Add to or Delete from a List while Iterating Over It ..................................................... 309
Source Code of the Keyboard Input Program .......................................................................... 310
The colliderect() Method.............................................................................................. 318
Chapter 19 - Sounds and Images.................................................................................................. 319
Sound and Image Files ............................................................................................................. 320
Sprites and Sounds Program .................................................................................................... 321
Source Code of the Sprites and Sounds Program .................................................................... 321
The pygame.transform.scale() Function ................................................................. 325
Chapter 20 - Dodger..................................................................................................................... 329
Review of the Basic Pygame Data Types ................................................................................ 329
Source Code of Dodger ............................................................................................................ 330
Fullscreen Mode....................................................................................................................... 339
The Game Loop ....................................................................................................................... 343
Event Handling ........................................................................................................................ 343
The move_ip() Method ....................................................................................................... 346
The pygame.mouse.set_pos() Function ...................................................................... 349
Modifying the Dodger Game ................................................................................................... 353
Chapter 1 – Installing Python 1

Chapter 1
INSTALLING PYTHON
Topics Covered In This Chapter:
 Downloading and installing the Python interpreter
 How to use this book
 The book’s website at http://inventwithpython.com

Hello! This book teaches you how to program by making video games. Once you learn how the
games in this book work, you’ll be able to create your own games. All you’ll need is a computer,
some software called the Python interpreter, and this book. The Python interpreter is free to
download from the Internet.

When I was a kid, a book like this one taught me how to write my first programs and games. It
was fun and easy. Now as an adult, I still have fun programming and I get paid for it. But even if
you don’t become a computer programmer when you grow up, programming is a useful and fun
skill to have.

Computers are incredible machines, and learning to program them isn’t as hard as people think. If
you can read this book, you can program a computer. A computer program is a bunch of
instructions that the computer can understand, just like a storybook is a bunch of sentences
understood by the reader. Since video games are nothing but computer programs, they are also
made up of instructions.

To instruct a computer, you write a program in a language the computer understands. This book
teaches a programming language named Python. There are many different programming
languages including BASIC, Java, JavaScript, PHP, and C++.

When I was a kid, BASIC was a common first language to learn. However, new programming
languages such as Python have been invented since then. Python is even easier to learn than
BASIC! But it’s still a serious programming language used by professional programmers. Many
adults use Python in their work and when programming for fun.

The games you’ll create from this book seem simple compared to the games for Xbox,
PlayStation, or Nintendo. These games don’t have fancy graphics because they’re meant to teach
coding basics. They’re purposely simple so you can focus on learning to program. Games don’t
have to be complicated to be fun.
2 http://inventwithpython.com

Downloading and Installing Python


You’ll need to install software called the Python interpreter. The interpreter program
understands the instructions you’ll write in the Python language. I’ll just refer to “the Python
interpreter software” as “Python” from now on.

Important Note! Be sure to install Python 3, and not Python 2. The programs in
this book use Python 3, and you’ll get errors if you try to run them with Python 2.
It is so important I’ve added a cartoon penguin in Figure 1-1 to tell you to install
Python 3 so you do not miss this message.

Figure 1-1: An incongruous penguin tells you to install Python 3.

On Windows, download the Python installer (the filename will end with .msi) and double-click it.
Follow the instructions the installer displays on the screen to install Python, as listed here:

1. Select Install for All Users and then click Next.

2. Install to the C:\Python34 folder by clicking Next.

3. Click Next to skip the Customize Python section.

On Mac OS X, download the .dmg file that’s right for your version of OS X from the website and
double-click it. Follow the instructions the installer displays on the screen to install Python, as
listed here:

1. When the DMG package opens in a new window, double-click the Python.mpkg file. You
may have to enter the administrator password.

2. Click Continue through the Welcome section and click Agree to accept the license.

Post questions to http://invpy.com/forum


Chapter 1 – Installing Python 3

3. Select HD Macintosh (or whatever name your hard drive has) and click Install.

If you’re running Ubuntu, you can install Python from the Ubuntu Software Center by following
these steps:

1. Open the Ubuntu Software Center.

2. Type Python in the search box in the top-right corner of the window.

3. Select IDLE (using Python 3.4), or whatever is the latest version.

4. Click Install. You may have to enter the administrator password to complete the
installation.

Starting IDLE
IDLE stands for Interactive DeveLopment Environment. The development environment is like
word processing software for writing Python programs. Starting IDLE is different on each
operating system.

On Windows, click the Start button in the lower left corner, type “IDLE” and select IDLE
(Python GUI).

On Mac OS X, open the Finder window and click on Applications. Then click Python 3.4. Then
click the IDLE icon.

On Ubuntu or Linux, open a terminal window and then type “idle3”. You may also be able to
click on Applications at the top of the screen. Then click Programming and IDLE 3.

The window that appears when you first run IDLE is the interactive shell, as shown in Figure 1-
2. You can enter Python instructions into the interactive shell at the >>> prompt and Python will
perform them. After displaying instruction results, a new >>> prompt will wait for your next
instruction.

Figure 1-2: The IDLE program’s interactive shell on Windows, OS X, and Ubuntu Linux.
4 http://inventwithpython.com

How to Use this Book


Most chapters in this book will begin with a sample run of the chapter’s featured program. This
sample run shows you what the program looks like when you run it. The parts the user types in
are shown as bold print.

Type the code for the program into IDLE’s file editor yourself, rather than download or
copy/paste it. You’ll remember programming better if you take the time to type in the code.

Line Numbers and Spaces


When typing the source code from this book, do not type the line numbers at the start of each
line. For example, if you see this in the book:

9. number = random.randint(1, 20)

You do not need to type the “9.” on the left side, or the one space immediately following it. Just
type it like this:

number = random.randint(1, 20)

Those numbers are there only so that this book can refer to specific lines in the program. They are
not a part of the actual program’s source code.

Aside from the line numbers, enter the code exactly as it appears. Notice that some of the lines of
code are indented by four or eight spaces. Each character in IDLE is the same width, so you can
count the number of spaces by counting the number of characters on the line above or below.

For example, the indented spaces here are marked with a ▪ black square so you can see them:

while guesses < 10:


▪▪▪▪if number == 42:
▪▪▪▪▪▪▪▪print('Hello')

Text Wrapping in This Book


Some instructions are too long to fit on one line on the page and will wrap around to the next line.
When you type this code, enter it all on one line without pressing ENTER. You can tell when a
new instruction starts by looking at the line numbers on the left. The example below has only two
instructions:

1. print('This is the first instruction! xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


xxxxxxxxxxxx')

Post questions to http://invpy.com/forum


Chapter 1 – Installing Python 5

2. print('This is the second instruction, not the third instruction.')

The first instruction wraps around and makes it look like three instructions in total. That’s only
because this book’s pages aren’t wide enough to fit the first instruction on one line.

Finding Help Online


This book’s website is at http://inventwithpython.com. You can find several resources related to
this book there. Several links in this book use the invpy.com domain name for shortened URLs.

The website at http://reddit.com/r/inventwithpython is a great place to ask programming questions


related to this book. Post general Python questions to the LearnProgramming and LearnPython
websites at http://reddit.com/r/learnprogramming and http://reddit.com/r/learnpython,
respectively.

You can also email me your programming questions at al@inventwithpython.com.

Keep in mind there are smart ways to ask programming questions that help others help you. Be
sure to read the Frequently Asked Questions sections these websites have about the proper way to
post questions. When asking programming questions, do the following:

 If you are typing out the programs in this book but getting an error, first check for typos
with the online diff tool at http://invpy.com/diff. Copy and paste your code into the diff
tool to find any differences from the book’s code in your program.
 Explain what you are trying to do when you explain the error. This will let your helper
know if you are on the wrong path entirely.
 Copy and paste the entire error message and your code.
 Search the Web to see whether someone else has already asked (and answered) your
question.
 Explain what you’ve already tried to do to solve your problem. This tells people you’ve
already put in some work to try to figure things out on your own.
 Be polite. Don’t demand help or pressure your helpers to respond quickly.

Asking someone, “Why isn’t my program working?” doesn’t tell them anything. Tell them what
you are trying to do, the exact error you are getting, and your operating system and version.
6 http://inventwithpython.com

Chapter 2
THE INTERACTIVE SHELL
Topics Covered In This Chapter:
 Integers and Floating Point Numbers
 Expressions
 Values
 Operators
 Evaluating Expressions
 Storing Values in Variables

Before you can make games, you need to learn a few basic programming concepts. You won’t
make games in this chapter, but learning these concepts is the first step to programming video
games. You’ll start by learning how to use Python’s interactive shell.

Some Simple Math Stuff


Open IDLE using the steps in Chapter 1, then get Python to solve some simple math stuff. The
interactive shell can work just like a calculator. Type 2 + 2 into the interactive shell at the >>>
prompt and press the ENTER key on your keyboard. (On some keyboards, this is the RETURN key.)
Figure 2-1 shows how the interactive shell responds with the number 4.

Figure 2-1: Enter 2+2 into the interactive shell.

This math problem is a simple programming instruction. The + sign tells the computer to add the
numbers 2 and 2. Table 2-1 lists the other math symbols available in Python. The - sign will
subtract numbers. The * asterisk will multiply numbers. The / slash will divide numbers.

Post questions to http://invpy.com/forum


Chapter 2 – The Interactive Shell 7

Table 2-1: The various math operators in Python.


Operator Operation
+ addition
- subtraction
* multiplication
/ division

When used in this way, +, -, *, and / are called operators. Operators tell Python what to do with
the numbers surrounding them.

Integers and Floating Point Numbers


Integers (or ints for short) are whole numbers such as 4, 99, and 0. Floating point numbers (or
floats for short) are fractions or numbers with decimal points like 3.5, 42.1 and 5.0. In Python,
the number 5 is an integer, but 5.0 is a float. These numbers are called values.

Expressions
These math problems are examples of expressions. Computers can solve millions of these
problems in seconds. Expressions are made up of values (the numbers) connected by operators
(the math signs). Try entering some of these math problems into the interactive shell, pressing the
ENTER key after each one.

2+2+2+2+2
8*6
10-5+6
2 + 2

After you type in the above instructions, the interactive shell will look like Figure 2-2.

Figure 2-2: What the IDLE window looks like after entering instructions.
8 http://inventwithpython.com

Figure 2-3: An expression is a made up of values and operators.

In the 2 + 2 example, notice that there can be any amount of spaces between the values
and operators. However, always start instructions at the beginning of the line when entering them
into the interactive shell.

Evaluating Expressions
When a computer solves the expression 10 + 5 and gets the value 15, it has evaluated the
expression. Evaluating an expression reduces the it to a single value, just like solving a math
problem reduces the problem to a single number: the answer. The expressions 10 + 5 and 10 + 3
+ 2 both evaluate to 15.

Expressions can be of any size, but they will always evaluate down to a single value. Even single
values are expressions: The expression 15 evaluates to the value 15. For example, the expression
8 * 3 / 2 + 2 + 7 - 9 will evaluate down to the value 12.0 through the following steps:

8 * 3 / 2 + 2 + 7 – 9

24 / 2 + 2 + 7 – 9

12.0 + 2 + 7 – 9

14.0 + 7 – 9

21.0 – 9

12.0

You don’t see all of these steps in the interactive shell. The interactive shell does them and just
shows you the results:

>>> 8 * 3 / 2 + 2 + 7 - 9
12.0

Post questions to http://invpy.com/forum


Chapter 2 – The Interactive Shell 9

Notice that the / division operator evaluates to a float value, as in 24 / 2 evaluating to 12.0.
Math operations with float values also evaluate to float values, as in 12.0 + 2 evaluating to 14.0.

Syntax Errors
If you enter 5 + into the interactive shell, you’ll get an error message.

>>> 5 +
SyntaxError: invalid syntax

This error happened because 5 + isn’t an expression. Expressions have values connected by
operators. But the + operator expects a value after the + sign. An error message appears when this
value is missing.

SyntaxError means Python doesn’t understand the instruction because you typed it incorrectly.
A lot of computer programming isn’t just telling the computer what to do, but also knowing how
to tell it.

Don’t worry about making mistakes though. Errors don’t damage your computer. Just retype the
instruction correctly into the interactive shell at the next >>> prompt.

Storing Values in Variables


You can save the value an expression evaluates to so you can use it later by storing them in
variables. Think of variables like a box that can hold a value.

An assignment statement instruction will store a value inside a variable. Type the name for the
variable, followed by the = sign (called the assignment operator), and then the value to store in
the variable. For example, enter spam = 15 into the interactive shell:

>>> spam = 15
>>>

The spam variable’s box will have the value 15 stored in it, as shown in Figure 2-4. The name
“spam” is the label on the box (so Python can tell variables apart) and the value is written on a
small note inside the box.

When you press ENTER you won’t see anything in response. In Python, the instruction executed
was successful if no error message appears. The >>> prompt will appear so you can type in the
next instruction.
10 http://inventwithpython.com

Figure 2-4: Variables are like boxes that can hold values in them.

Unlike expressions, statements are instructions that do not evaluate to any value. This is why
there’s no value displayed on the next line in the interactive shell after spam = 15. If you are
confused about which instructions are expressions and which are statements, remember that
expressions evaluate to a single value. Any other kind of instruction is a statement.

Variables store values, not expressions. For example, consider the expression in the statements
spam = 10 + 5 and spam = 10 + 7 - 2. They both evaluate to 15. The end result is the same:
Both assignment statements store the value 15 in the variable spam.

The first time a variable is used in an assignment statement, Python will create that variable. To
check what value is in a variable, type the variable name into the interactive shell:

>>> spam = 15
>>> spam
15

The expression spam evaluates to the value inside the spam variable: 15. You can use variables in
expressions. Try entering the following in the interactive shell:

>>> spam = 15
>>> spam + 5
20

You’ve set the value of the variable spam to 15, so writing spam + 5 is like writing the
expression 15 + 5. Here are the steps of spam + 5 being evaluated:

spam + 5

15 + 5

20

Post questions to http://invpy.com/forum


Chapter 2 – The Interactive Shell 11

You cannot use a variable before an assignment statement creates it. Python will give you a
NameError because no such variable by that name exists yet. Mistyping the variable name also
causes this error:

>>> spam = 15
>>> spma
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
spma
NameError: name 'spma' is not defined

The error appeared because there’s spam variable but no variable named spma.

You can change the value stored in a variable by entering another assignment statement. For
example, try entering the following into the interactive shell:

>>> spam = 15
>>> spam + 5
20
>>> spam = 3
>>> spam + 5
8

When you first enter spam + 5, the expression evaluates to 20 because you stored 15 inside spam.
However, when you enter spam = 3, the value 15 is replaced, or overwritten, with the value 3.
Now when you enter spam + 5, the expression evaluates to 8 because the value of spam is now 3.
Overwriting is shown in Figure 2-5.

Figure 2-5: The 15 value in spam being overwritten by the 3 value.

You can even use the value in the spam variable to assign a new value to spam:
12 http://inventwithpython.com

>>> spam = 15
>>> spam = spam + 5
20

The assignment statement spam = spam + 5 is like saying, “the new value of the spam variable
will be the current value of spam plus five.” Keep increasing the value in spam by 5 several times
by entering the following into the interactive shell:

>>> spam = 15
>>> spam = spam + 5
>>> spam = spam + 5
>>> spam = spam + 5
>>> spam
30

Using More Than One Variable


Create as many variables as you need in your programs. For example, let’s assign different values
to two variables named eggs and bacon, like so:

>>> bacon = 10
>>> eggs = 15

Now the bacon variable has 10 inside it, and eggs has 15 inside it. Each variable is its own box
with its own value, like in Figure 2-6.

Figure 2-6: The “bacon” and “eggs” variables have values stored in them.

Try entering spam = bacon + eggs into the interactive shell, then check the new value of spam:

>>> bacon = 10
>>> eggs = 15
>>> spam = bacon + eggs
>>> spam

Post questions to http://invpy.com/forum


Chapter 2 – The Interactive Shell 13

25

The value in spam is now 25. When you added bacon and eggs you are adding their values,
which are 10 and 15, respectively. Variables contain values, not expressions. The spam variable
was assigned value 25, and not the expression bacon + eggs. After the spam = bacon + eggs
assignment statement, changing bacon or eggs does not affect spam.

Summary
In this chapter, you learned the basics about writing Python instructions. Python needs you to tell
it exactly what to do in a strict way. Computers don’t have common sense and only understand
specific instructions.

Expressions are values (such as 2 or 5) combined with operators (such as + or -). Python can
evaluate expressions, that is, reduce the expression to a single value. You can store values inside
of variables so that your program can remember them and use them later.

There are many other types of operators and values in Python. In the next chapter, you’ll go over
some more basic concepts and write your first program. You’ll learn about working with text in
expressions. Python isn’t limited to just numbers; it’s more than a calculator!
14 http://inventwithpython.com

Chapter 3
WRITING PROGRAMS
Topics Covered In This Chapter:
 Flow of execution
 Strings
 String concatenation
 Data types (such as strings or integers)
 Using the file editor to write progams
 Saving and running programs in IDLE
 The print() function
 The input() function
 Comments
 Case-sensitivity

That’s enough math for now. Now let’s see what Python can do with text. In this chapter, you’ll
learn how to store text in variables, combine text, and display text on the screen.

Almost all programs display text to the user, and the user enters text into your programs through
the keyboard. You’ll also make your first program in this chapter. This program displays the
greeting, “Hello World!” and asks for the user’s name.

Strings
In Python, text values are called strings. String values can be used just like integer or float values.
You can store strings in variables. In code, string values start and end with a single quote ('). Try
entering this code into the interactive shell:

>>> spam = 'hello'

The single quotes tell Python where the string begins and ends. They are not part of the string
value’s text. Now if you type spam into the interactive shell, you will see the contents of the spam
variable. Remember, Python evaluates variables to the value stored inside the variable. In this
case, this is the string 'hello':

>>> spam = 'hello'


>>> spam
'hello'

Post questions to http://invpy.com/forum


Chapter 3 – Writing Programs 15

Strings can have any keyboard character in them and can be as long as you want. These are all
examples of strings:

'hello'
'Hi there!'
'KITTENS'
'7 apples, 14 oranges, 3 lemons'
'Anything not pertaining to elephants is irrelephant.'
'A long time ago, in a galaxy far, far away...'
'O*&#wY%*&OCfsdYO*&gfC%YO*&%3yc8r2'

String Concatenation
String values can combine with operators to make expressions, just like integer and float values
do. You can combine two strings with the + operator. This is string concatenation. Try entering
'Hello' + 'World!' into the interactive shell:

>>> 'Hello' + 'World!'


'HelloWorld!'

The expression evaluates to a single string value, 'HelloWorld!'. There is no space between the
words because there was no space in either of the two concatenated strings, unlike this example:

>>> 'Hello ' + 'World!'


'Hello World!'

The + operator works differently on string and integer values because they are different data
types. All values have a data type. The data type of the value 'Hello' is a string. The data type of
the value 5 is an integer. The data type tells Python what operators should do when evaluating
expressions. The + operator will concatenate string values but add integer and float values.

Writing Programs in IDLE’s File Editor


Until now, you’ve been typing instructions into IDLE’s interactive shell one at a time. When you
write programs though, you type in several instructions and have them run all at once. Let’s write
your first program!

IDLE has another part called the file editor. Click on the File menu at the top of the interactive
shell window. Then select New Window. A blank window will appear for you to type your
program’s code into, like in Figure 3-1.
16 http://inventwithpython.com

Figure 3-1: The file editor window (left) and the interactive shell window (right).

The two windows look similar, but just remember this: The interactive shell window will have
the >>> prompt. The file editor window will not.

Hello World!
It’s traditional for programmers to make their first program display “Hello world!” on the screen.
You’ll create your own Hello World program now.

When you enter your program, don’t enter the numbers at the left side of the code. They’re there
so this book can refer to code by line number. The bottom-right corner of the file editor window
will tell you where the blinking cursor is. Figure 3-2 shows that the cursor is on line 1 and column
0.

Figure 3-2: The bottom right of the file editor window tells you what line the cursor is on.

hello.py
Enter the following text into the new file editor window. This is the program’s source code. It
contains the instructions Python will follow when the program is run.

Post questions to http://invpy.com/forum


Chapter 3 – Writing Programs 17

IMPORTANT NOTE! The programs in this book will only run on Python 3, not
Python 2. When the IDLE window starts, it will say something like “Python
3.4.2” at the top. If you have Python 2 installed, you can have Python 3 installed
at the same time. To download Python 3, go to https://python.org/download/.

hello.py
1. # This program says hello and asks for my name.
2. print('Hello world!')
3. print('What is your name?')
4. myName = input()
5. print('It is good to meet you, ' + myName)

The IDLE program will write different types of instructions with different colors. After you’re
done typing the code, the window should look like this:

Figure 3-3: The file editor window will look like this after you type in the code.

Saving Your Program


Once you’ve entered your source code, save it by clicking on File ► Save As. Or press Ctrl-S to
save with a keyboard shortcut. Figure 3-4 shows the Save As window that will open. Enter
hello.py in the File name text field then click Save.
18 http://inventwithpython.com

Figure 3-4: Saving the program.

You should save your programs often while you type them. That way, if the computer crashes or
you accidentally exit from IDLE you won’t lose much work.

Opening The Programs You’ve Saved


To load your previously saved program, click File ► Open. Choose the file in the window that
appears and click the Open button. Your saved hello.py program will open in the File Editor
window.

Now it’s time to run the program. Click File ► Run ► Run Module or just press F5 from the
file editor window. Your program will run in the interactive shell window.

Enter your name when the program asks for it. This will look like Figure 3-5.

Figure 3-5: The interactive shell after running hello.py.

Post questions to http://invpy.com/forum


Chapter 3 – Writing Programs 19

When you type your name and push ENTER, the program will greet you by name.
Congratulations! You’ve written your first program and are now a computer programmer. Press
F5 again to run the program a second time and enter another name.

If you got an error, compare your code to this book’s code with the online diff tool at
http://invpy.com/diff. Copy and paste your code from the file editor into the web page and click
the Compare button. This tool will highlight any differences between your code and the code in
this book, like in Figure 3-6.

Figure 3-6: The diff tool at http://invpy.com/diff

While coding, if you get a NameError that looks like this:

Hello world!
What is your name?
Albert
Traceback (most recent call last):
File "C:/Python26/test1.py", line 4, in <module>
myName = input()
File "<string>", line 1, in <module>
NameError: name 'Albert' is not defined

...that means you are using Python 2, instead of Python 3. Install a version of Python 3 from
https://python.org/download. Re-run the program with Python 3.
20 http://inventwithpython.com

How the “Hello World” Program Works


Each line of code is an instruction interpreted by Python. These instructions make up the
program. A computer program’s instructions are like the steps in a cookbook recipe. Each
instruction executes in order, beginning from the top of the program and going down the list of
instructions.

The step Python is at in the program is called the execution. When the program starts, the
execution is at the first instruction. After executing the instruction, the execution moves down to
the next instruction.

Let’s look at each line of code to see what it’s doing. We’ll begin with line number 1.

Comments

1. # This program says hello and asks for my name.

This instruction is a comment. Any text following a # sign (called the pound sign) is a comment.
Comments are not for Python, but for you, the programmer. Python ignores comments.
Comments are the programmer’s notes about what the code does. You can write anything in a
comment. To make it easier to read the source code, this book prints comments in a light gray-
colored text.

Programmers usually put a comment at the top of their code to give their program a title.

Functions
A function is kind of like a mini-program inside your program. Functions contain several
instructions to execute when the function is called. Python provides some built-in functions
already. Two functions, print() and input(), are described next. The great thing about
functions is that you only need to know what the function does, but not how it does it.

A function call is an instruction that tells Python to run the code inside a function. For example,
your program calls the print() function to display a string on the screen. The print() function
takes the string you type between the parentheses as input and displays the text on the screen.

To display Hello world! on the screen, type the print function name, followed by an opening
parenthesis, followed by the 'Hello world!' string and a closing parenthesis.

The print() function

2. print('Hello world!')

Post questions to http://invpy.com/forum


Chapter 3 – Writing Programs 21

3. print('What is your name?')

Lines 2 and 3 are calls to the print() function. A value between the parentheses in a function
call is an argument. The argument on line 2’s print() function call is 'Hello world!'. The
argument on line 3’s print() function call is 'What is your name?'. This is called passing the
argument to the print() function.

In this book, function names have parentheses at the end. This makes it clear that print() means
this book is talking about a function named print(), and not a variable named print. This is like
the quotes around the number '42' telling Python that you are talking about a string '42' and not
an integer 42.

The input() function

4. myName = input()

Line 4 is an assignment statement with a variable (myName) and a function call (input()). When
input() is called, the program waits for the user to enter text. The text string that the user enters
becomes the value that the function call evaluates to. Function calls can be used in expressions
anywhere a value can be used.

The value that the function call evaluates to is called the return value. (In fact, “the value a
function call returns” means the same thing as “the value a function call evaluates to”.) In this
case, the return value of the input() function is the string that the user typed in-their name. If the
user typed in “Albert”, the input() function call evaluates to the string 'Albert'. The evaluation
looks like this:

myName = input()

myName = 'Albert'

This is how the string value 'Albert' gets stored in the myName variable.

Using Expressions in Function Calls

5. print('It is good to meet you, ' + myName)

The last line is another print() function call. The expression 'It is good to meet you, ' +
myName in between the parentheses of print(). However, arguments are always single values.
Python will first evaluate this expression and then pass that value as the argument. If 'Albert' is
stored in myName, the evaluation looks like this:
22 http://inventwithpython.com

print('It is good to meet you, ' + myName)



print('It is good to meet you, ' + 'Albert')

print('It is good to meet you, Albert')

This is how the program greets the user by name.

Ending the Program


Once the program executes the last line, it terminates or exits. This means the program stops
running. Python forgets all of the values stored in variables, including the string stored in myName.
If you run the program again and enter a different name, the program will think that is your name.

Hello world!
What is your name?
Carolyn
It is good to meet you, Carolyn

Remember, the computer does exactly what you program it to do. Computers are dumb and just
follow the instructions you give it exactly. The computer doesn’t care if you type in your name,
someone else’s name, or just something silly. Type in anything you want. The computer will treat
it the same way:

Hello world!
What is your name?
poop
It is good to meet you, poop

Variable Names
Giving variables descriptive names makes it easier to understand what a program does. Imagine if
you were moving to a new house and you labeled every moving box “Stuff”. That wouldn’t be
helpful at all!

Instead of myName, you could have called this variable abrahamLincoln or nAmE. Python doesn’t
care. It will run the program just the same.

Variable names are case-sensitive. Case-sensitive means the same variable name in a different
case is considered a different variable. So spam, SPAM, Spam, and sPAM are four different variables
in Python. They each contain their own separate values. It’s a bad idea to have differently cased
variables in your program. Use descriptive names for your variables instead.

Post questions to http://invpy.com/forum


Chapter 3 – Writing Programs 23

Variable names are usually lowercase. If there’s more than one word in the variable name,
capitalize each word after the first. This makes your code more readable. For example, the
variable name whatIHadForBreakfastThisMorning is much easier to read than
whatihadforbreakfastthismorning. This is a convention: an optional but standard way of
doing things in Python programming.

Short variable names are better than long names: breakfast or foodThisMorning is more
readable than whatIHadForBreakfastThisMorning.

This book’s interactive shell examples use variable names like spam, eggs, ham, and bacon. This
is because the variable names in these examples don’t matter. However, this book’s programs all
use descriptive names. Your programs should use descriptive variable names too.

Summary
Once you learn about strings and functions, you can start making programs that interact with
users. This is important because text is the main way the user and the computer will communicate
with each other. The user enters text through the keyboard with the input() function. The
computer will display text on the screen with the print() function.

Strings are just values of a new data type. All values have a data type, and there are many data
types in Python. The + operator can concatenate strings.

Functions are used to carry out some complicated instruction as part of your program. Python has
many built-in functions that you’ll learn about in this book. Function calls can be used in
expressions anywhere a value is used.

The instruction in your program that Python is currently at is called the execution. In the next
chapter, you’ll learn more about making the execution move in ways other than just straight down
the program. Once you learn this, you’ll be ready to create games.
24 http://inventwithpython.com

Chapter 4
GUESS THE NUMBER
Topics Covered In This Chapter:
 import statements
 Modules
 while statements
 Conditions
 Blocks
 Booleans
 Comparison operators
 The difference between = and ==
 if statements
 The break keyword
 The str()and int()and float() functions
 The random.randint() function

In this chapter, you’re going to make a “Guess the Number” game. The computer will think of a
random number from 1 to 20, and ask you to guess it. The computer will tell you if each guess is
too high or too low. You win if you can guess the number within six tries.

This is a good game to code because it uses random numbers, loops, and input from the user in a
short program. You’ll learn how to convert values to different data types, and why you would
need to do this. Since this program is a game, we’ll call the user the player. But “user” would be
correct too.

Sample Run of Guess the Number


Here’s what the program looks like to the player when run. The text that the player types in is in
bold.

Hello! What is your name?


Albert
Well, Albert, I am thinking of a number between 1 and 20.
Take a guess.
10
Your guess is too high.
Take a guess.
2

Post questions to http://invpy.com/forum


Chapter 4 – Guess the Number 25

Your guess is too low.


Take a guess.
4
Good job, Albert! You guessed my number in 3 guesses!

Source Code of Guess the Number


Open a new file editor window by clicking on the File ► New Window. In the blank window
that appears, type in the source code and save it as guess.py. Then run the program by pressing
F5. When you enter this code into the file editor, be sure to pay attention to the spacing at the
front of some of the lines. Some lines have four or eight spaces of indentation.

IMPORTANT NOTE! The programs in this book will only run on Python 3, not
Python 2. When the IDLE window starts, it will say something like “Python
3.4.2” at the top. If you have Python 2 installed, you can have Python 3 installed
at the same time. To download Python 3, go to https://python.org/download/.

If you get errors after typing this code in, compare the code you typed to the book’s code with the
online diff tool at http://invpy.com/diff/guess.

guess.py
1. # This is a guess the number game.
2. import random
3.
4. guessesTaken = 0
5.
6. print('Hello! What is your name?')
7. myName = input()
8.
9. number = random.randint(1, 20)
10. print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')
11.
12. while guessesTaken < 6:
13. print('Take a guess.') # There are four spaces in front of print.
14. guess = input()
15. guess = int(guess)
16.
17. guessesTaken = guessesTaken + 1
18.
19. if guess < number:
20. print('Your guess is too low.') # There are eight spaces in front
of print.
21.
22. if guess > number:
26 http://inventwithpython.com

23. print('Your guess is too high.')


24.
25. if guess == number:
26. break
27.
28. if guess == number:
29. guessesTaken = str(guessesTaken)
30. print('Good job, ' + myName + '! You guessed my number in ' +
guessesTaken + ' guesses!')
31.
32. if guess != number:
33. number = str(number)
34. print('Nope. The number I was thinking of was ' + number)

import statements
1. # This is a guess the number game.
2. import random

The first line is a comment. Remember that Python will ignore everything after the # sign. This
just reminds us what this program does.

The second line is an import statement. Remember, statements are instructions that perform
some action but don’t evaluate to a value like expressions do. You’ve already seen statements:
assignment statements store a value in a variable.

While Python includes many built-in functions, some functions exist in separate programs called
modules. You can use these functions by importing their modules into your program with an
import statement.

Line 2 imports the module named random so that the program can call random.randint(). This
function will come up with a random number for the user to guess.

4. guessesTaken = 0

Line 4 creates a new variable named guessesTaken. You’ll store the number of guesses the
player has made in this variable. Since the player hasn’t made any guesses at this point in the
program, store the integer 0 here.

6. print('Hello! What is your name?')


7. myName = input()

Post questions to http://invpy.com/forum


Chapter 4 – Guess the Number 27

Lines 6 and 7 are the same as the lines in the Hello World program that you saw in Chapter 3.
Programmers often reuse code from their other programs to save themselves work.

Line 6 is a function call to the print() function. Remember that a function is like a mini-
program inside your program. When your program calls a function, it runs this mini-program.
The code inside the print() function displays the string argument you passed it on the screen.

Line 7 lets the user type in their name and stores it in the myName variable. (Remember, the string
might not really be the player’s name. It’s just whatever string the player typed. Computers are
dumb and just follow their instructions no matter what.)

The random.randint() Function


9. number = random.randint(1, 20)

Line 9 calls a new function named randint() and stores the return value in number. Remember,
function calls can be part of expressions because they evaluate to a value.

The randint() function is provided by the random module, so you must precede it with random.
(don’t forget the period!) to tell Python that the function randint() is in the random module.

The randint() function will return a random integer between (and including) the two integer
arguments you pass to it. Line 9 passes 1 and 20 between the parentheses separated by commas
that follow the function name. The random integer that randint() returns is stored in a variable
named number; this is the secret number the player is trying to guess.

Just for a moment, go back to the interactive shell and enter import random to import the random
module. Then enter random.randint(1, 20) to see what the function call evaluates to. It will
return an integer between 1 and 20. Repeat the code again and the function call will return a
different integer. The randint() function returns random integer each time, just as rolling dice
you’ll get a random number each time:

>>> import random


>>> random.randint(1, 20)
12
>>> random.randint(1, 20)
18
>>> random.randint(1, 20)
3
>>> random.randint(1, 20)
18
>>> random.randint(1, 20)
7
28 http://inventwithpython.com

Use the randint() function when you want to add randomness to your games. You’ll use
randomness in many games. (Think of how many board games use dice.)

You can also try different ranges of numbers by changing the arguments. For example, enter
random.randint(1, 4) to only get integers between 1 and 4 (including both 1 and 4). Or try
random.randint(1000, 2000) to get integers between 1000 and 2000.

For example, enter the following into the interactive shell. The results you get when you call the
random.randint() function will probably be different (it is random, after all).

>>> random.randint(1, 4)
3
>>> random.randint(1000, 2000)
1294

You can change the game’s code slightly to make the game behave differently. Try changing line
9 and 10 from this:

9. number = random.randint(1, 20)


10. print('Well, ' + name + ', I am thinking of a number between 1 and 20.')

…into these lines:

9. number = random.randint(1, 100)


10. print('Well, ' + name + ', I am thinking of a number between 1 and 100.')

And now the computer will think of an integer between 1 and 100 instead of 1 and 20. Changing
line 9 will change the range of the random number, but remember to change line 10 so that the
game also tells the player the new range instead of the old one.

Welcoming the Player

10. print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')

On line 10 the print() function welcomes the player by name, and tells them that the computer
is thinking of a random number.

It may look like there’s more than one string argument in line 10, but look at the line carefully.
The plus signs concatenate the three strings to evaluate down to one string. And that one string is
the argument passed to the print() function. If you look closely, you’ll see that the commas are
inside the quotes and part of the strings themselves.

Post questions to http://invpy.com/forum


Chapter 4 – Guess the Number 29

Loops
12. while guessesTaken < 6:

Line 12 is a while statement, which indicates the beginning of a while loop. Loops let you
execute code over and over again. However, you need to learn a few other concepts first before
learning about loops. Those concepts are blocks, Booleans, comparison operators, conditions, and
the while statement.

Blocks
Several lines of code can be grouped together in a block. Every line in a block of code has the
same minimum amount of indentation. You can tell where a block begins and ends by looking at
the number of spaces at the front of the lines. This is the line’s indentation.

A block begins when a line’s indentation increases (usually by four spaces). Any following line
also indented by four spaces is part of the block. The block ends when there’s a line of code with
the same indentation before the block started. This means blocks can exist within other blocks.
Figure 4-1 is a diagram of code with the blocks outlined and numbered.

In Figure 4-1, line 12 has no indentation and isn’t inside any block. Line 13 has an indentation of
four spaces. Since this indentation is larger than the previous line’s indentation, a new block has
started. This block is labeled (1) in Figure 4-1. This block will continue until a line with zero
spaces (the original indentation before the block began). Blank lines are ignored.

Line 20 has an indentation of eight spaces. Eight spaces is more than four spaces, which starts a
new block. This block is labeled (2) in Figure 4-1. This block is inside of another block.

Figure 4-1: Blocks and their indentation. The black dots represent spaces.
30 http://inventwithpython.com

Line 22 has only four spaces. Because the indentation has decreased, you know that block has
ended. Line 20 is the only line in that block. Line 22 is in the same block as the other lines with
four spaces.

Line 23 increases the indentation to eight spaces, so again a new block has started. It is labeled
(3) in Figure 4-1.

To recap, line 12 isn’t in any block. Lines 13 to 23 all in one block marked (1). Line 20 is in a
block in a block marked as (2). Line 23 is the only line in another block in a block marked as (3).

The Boolean Data Type


The Boolean data type has only two values: True or False. These values must be typed with a
capital “T” and “F”. The rest of the value’s name must be in lowercase. You will use Boolean
values (called bools for short) with comparison operators to form conditions. (Conditions are
explained later.)

For example, try storing the Boolean values in variables:

>>> spam = True


>>> eggs = False

The data types that have been introduced so far are integers, floats, strings, and now bools. Every
value in Python belongs to one data type.

Comparison Operators
Line 12 has a while statement:

12. while guessesTaken < 6:

The expression that follows the while keyword (the guessesTaken < 6 part) contains two values
(the value in the variable guessesTaken, and the integer value 6) connected by an operator (the <
“less than” sign). The < sign is a comparison operator.

Comparison operators compare two values and evaluate to a True or False Boolean value. A list
of all the comparison operators is in Table 4-1.

Post questions to http://invpy.com/forum


Chapter 4 – Guess the Number 31

Table 4-1: Comparison operators.


Operator Sign Operator Name
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to

You’ve already read about the +, -, *, and / math operators. Like any operator, the comparison
operators combine with values to form expressions such as guessesTaken < 6.

Conditions
A condition is an expression that combines two values with a comparison operator (such as < or
>) and evaluates to a Boolean value. A condition is just another name for an expression that
evaluates to True or False. Conditions are used in while statements (and a few other
instructions, explained later.)

For example, the condition guessesTaken < 6 asks, “is the value stored in guessesTaken less
than the number 6?” If so, then the condition evaluates to True. If not, the condition evaluates to
False.

In the case of the “Guess the Number” program, on line 4 you stored the value 0 in
guessesTaken. Because 0 is less than 6, this condition evaluates to the Boolean value of True.
The evaluation would look like this:

guessesTaken < 6

0 < 6

True

Experiment with Booleans, Comparison Operators, and Conditions


Enter the following expressions in the interactive shell to see their Boolean results:

>>> 0 < 6
True
>>> 6 < 0
False
>>> 50 < 10
32 http://inventwithpython.com

False
>>> 10 < 11
True
>>> 10 < 10
False

The condition 0 < 6 returns the Boolean value True because the number 0 is less than the
number 6. But because 6 isn’t less than 0, the condition 6 < 0 evaluates to False. 50 isn’t less
than 10, so 50 < 10 is False. 10 is less than 11, so 10 < 11 is True.

Notice that 10 < 10 evaluates to False because the number 10 isn’t smaller than the number 10.
They are the same size. If Alice were the same height as Bob, you wouldn't say that Alice is taller
than Bob or that Alice is shorter than Bob. Both of those statements would be false.

Now try entering these expressions into the interactive shell:

>>> 10 == 10
True
>>> 10 == 11
False
>>> 11 == 10
False
>>> 10 != 10
False
>>> 10 != 11
True
>>> 'Hello' == 'Hello'
True
>>> 'Hello' == 'Goodbye'
False
>>> 'Hello' == 'HELLO'
False
>>> 'Goodbye' != 'Hello'
True

The Difference Between = and ==


Try not to confuse the assignment operator (=) and the “equal to” comparison operator (==). The
equal sign (=) is used in assignment statements to store a value to a variable, while the equal-
equal sign (==) is used in expressions to see whether two values are equal. It’s easy to
accidentally use one when you meant to use the other.

Just remember that the “equal to” comparison operator (==) has two characters in it, just as the
“not equal to” comparison operator (!=) has two characters in it.

Post questions to http://invpy.com/forum


Chapter 4 – Guess the Number 33

String and integer values will never be equal to each other. For example, try entering the
following into the interactive shell:

>>> 42 == 'Hello'
False
>>> 42 != '42'
True

Looping with while statements


The while statement marks the beginning of a loop. Loops can execute the same code repeatedly.
When the execution reaches a while statement, it evaluates the condition next to the while
keyword. If the condition evaluates to True, the execution moves inside the following block,
called the while-block. (In the program, the while-block begins on line 13.) If the condition
evaluates to False, the execution moves all the way past the while-block. In Guess the Number,
the first line after the while-block is line 28.

A while statement always has a : colon after the condition. Statements that end with a colon
expect a new block on the next line.

12. while guessesTaken < 6:

Figure 4-2: The while loop’s condition.

Figure 4-2 shows how the execution flows depending on the condition. If the condition evaluates
to True (which it does the first time, because the value of guessesTaken is 0), execution will
Another Random Scribd Document
with Unrelated Content
longer defiles, and opening through the last defile into a wider
valley, or a marsh. The shape of these basins, or cauldrons,
commonly lying above one another like so many stories, and the
level surface of their water, leave no doubt of their being once
enclosed lakes which were formerly blocked up by the barriers of the
defiles, and which flowed towards the level country, as soon as the
defiles were broken down by the waters. If no kind of historical
monuments in the west of Europe bears evidence of those events,
which, at least on a small scale, occur in our own times, this
intimates that it was inhabited, not by an original population, but by
a foreign or modern race of people; whereas those revolutions
extended to remote antiquity. The numerous masses of rock found
on both sides of the Alps to the height of 4000 feet, as well as in the
plains of the north of Europe, at a great distance from their original
position, and concerning whose coming hither so much light has
lately been thrown by Messrs Buch and Escher, are a very probable
proof of these debacles; while every circumstance renders it evident
that these blocks were swept along by the currents thus created, to
the place where they are now found. The Greek writers have also
preserved accounts of such revolutions, which, although not
unquestionably authenticated, are yet stamped with the impress of
historical testimony. Herodotus has the following passages directly
relative to the country where the Greeks place their second or
Deucalionic deluge. “Thessaly must formerly have been an inland
sea, surrounded by high mountains. On the east it was bounded by
Pelios and Ossa, whose bases were united; on the north by
Olympus; on the west by Pindus; and on the south by Othrys.
Thessaly lay in the midst of these mountains in the form of a basin,
into which, in conjunction with other copious streams, the five well-
known rivers, the Peneus, the Apidanus, the Orochomenus, the
Enipeus, and the Pamisos, emptied themselves. These rivers, which
are collected in their basin from the mountains which encompass
Thessaly, after their junction under the name of Peneus, in which
they lose their former appellation, open towards the sea through a
narrow valley. According to tradition, this valley and opening did not
formerly exist; so that the rivers and the Lake Brebeis, which did not
formerly bear these names, having their confluence in this place,
rendered the whole of Thessaly an inland sea. The Thessalians
affirm that Neptune opened the valley for the passage of the river
Peneus, and they may perhaps be right. If we consider Neptune the
author of earthquakes, and consider the violent concussion of the
mountains caused by them as the work of this deity, we must, upon
surveying these regions, confess that they owe their present shape
to him; for the separation of every mountain appears to me to have
been produced by some violent commotion of the earth.” Strabo
makes mention of this tradition, which he thought worthy of belief,
and accounts for the origin of the Vale of Tempe, which is the bed of
the river Peneus, and likewise for the separation of Ossa from
Olympus, by means of an earthquake[405]. In making this remark,
we perceive that our theories which allow that earthquakes are to
operate in forming the surface of the earth, have not even the merit
of novelty. According to the last writer, similar eruptions of water
must have originated in the lake Copais in Bœotia[406], in the lakes
Bistonis and Aphnetis, in Thrace, and have been accompanied with
huge devastation[407]. Diodorus Siculus[408] remembered a
Samothracian tradition, according to which the Euxine Sea was once
shut up on all sides. It afterwards burst through its mighty mound of
kyanischen rocks to the Hellespont, and inundated a great part of
the coast of Asia, as well as Samothracia itself. An objection started
to the possibility of such an event is, that, from the observations of
Olivier and General Andreossy, the shores of the Black Sea are, in
most places, lower than those of the Bosphorus; and that its waters,
therefore, even if they were considerably higher than they are at
present, would more readily overflow the former than the latter. But
since every rock exposed for such a length of time is daily crumbling
down, it is a question, whether the shore of the Black Sea has
undergone any alteration since that period; and we know that the
eruptions took their direction, not so much from the low situation of
the barrier, as from the nature of the rock of which it was
constructed, being influenced by the weather, and from the rock
itself being rent asunder. Be that as it may, the words with which
Diodorus commences his narrative are remarkable, when he says,
the Samothracian deluge happened earlier than those of other
nations. It at least so far preceded others, that, in the estimation of
the Greek historian, independent of the deluges of Ogyges and
Deucalion, similar natural occurrences more or less authenticated
were received as historical facts.
Finally, the effects produced by the bursting of lakes or debacles
do not appear to be out of proportion to the devastation mentioned
by the traditions of nations. To abide by our former example, floods
which could carry along with them masses of rock of 50,000 cubic
feet, were in a situation to bury a whole people; and the few
individuals who might be preserved would undoubtedly have handed
down the memory of such an event to remote posterity. Other
deluges may have arisen from other causes, at a time when, as is
shewn by numerous vestiges, lakes and rivers had a much greater
elevation than at present; and, therefore, every overflowing of them
must have produced greater and more extensive ravages.
From these last local eruptions of water, that is, from single limited
districts, arose the mechanical precipitates known under the
denomination of Alluvial Soil. Their situation, as the uppermost
covering of the earth, as well as their origin, which takes place
beneath our own observation, furnishes evidence of their being the
most recent mineral formations; and it follows from their nature and
connection that they were not produced by chemical means, but
removed by the mechanical force of water. Since they, among other
things, contain prostrate forests, and abundant remains of land
animals, we conclude that they did not originate in the bed of the
sea, but were floated and deposited upon the dry land by an
overflow of land water. How is it conceivable that these precipitates
have been covered by the ocean, since their deposition, and have,
by means of an opposite change, become the dry land they are at
present; and yet it must have been so, if they are to be considered
as intimations of the Mosaic deluge.
The view now given, which is that of Henger in his Beiträge, is
also advocated by other naturalists, and has lately been brought
forward in an interesting manner in the Edinburgh Philosophical
Journal[409]. We have been frequently requested to give the two
views, in regard to the universal deluge, namely, that which
maintains that it is proved by an appeal to the phenomena of the
mineral kingdom; the other, which affirms that that great event has
left no traces of its existence on the surface or in the interior of the
earth. M. Cuvier’s Essay, and Professor Buckland’s Reliquiæ, are the
best authorities for the first opinion; while numerous writers have
advocated the second.
Note, p. 244.
ON THE ACTION OF RUNNING WATERS.

A very great degree of power has been attributed to the waters


which move at the surface of the earth, or in its interior. Many
geologists have advanced the opinion, that they have scooped out
the channels and even the valleys in which they flow, and formed
the cliffs whose feet they wash; and many philosophers, naturalists
and even geologists, still support this opinion, not only in some of its
applications, but even in its whole extent.
In order to appreciate it, it is sufficient to observe with care the
different modes of action of water set in motion by different causes,
and the changes which it has operated upon the rocks and deposits
upon which it has acted, from the most remote times to which
history may reach.
We must, in the first place, successively examine the different
sorts of action of the principal masses of water which are in motion
at the surface of the earth, that is to say, the action of torrents, of
rivers, of currents of the sea, or of great lakes, and that of waves.
We shall afterwards see what consequences are to be deduced
from these observations.

1. Action of Torrents.

Torrents have a true degrading and scooping action upon the


earth’s surface, but, by the necessary consequence of the sense
which we attach to the word, this action cannot be exercised upon
spaces of great extent, for a torrent is a water-course which has a
great declivity. Now, on account of the little height which the most
elevated summits of the globe have in comparison with the extent of
its surface, this action cannot be very extensive; it can only,
therefore, produce short and narrow ravines. This action, as all who
have visited high mountain chains may have seen, is only often local
and instantaneous; it presents no remarkable effect but upon the
heaps of debris which cover the declivities of the mountains, and on
broken rocks, partially disintegrated by other causes, and lastly on
moveable deposits. The results of this action contribute to confine it
within narrower limits still, by heaping up at the mouths of torrents
in the valleys or plains, the debris carried down by these torrents.
The elevation of the soil, which necessarily follows from the
accumulation of these debris, diminishes with the declivity, the
rapidity, and consequently the power of these water-courses.
Great masses of water moving rapidly, have a marked transporting
power. Striking examples of this power have but too often been seen
in Holland, by the breaking down of the dikes, and in Alpine
mountains, in consequence of extraordinary rains during tempests,
or from the rupture of some of the natural barriers of lakes. In these
latter times (in 1818), the Vallée de Bagne experienced the terrible
effects of this devastating power. Masses of ice having fallen towards
the upper part of this valley, and accumulated there, raised a dike
sufficiently compact and strong to block up the course of the Dranse.
The waters of this river, rapid and pent up in certain parts of its
course, as are all those of the high Alps, accumulated above this
barrier of ice, and formed a lake which attained, at its maximum,
130 metres of mean breadth, from 3000 to 4000 metres of length,
and 36 of mean depth, and consequently a volume of water
estimated at about 29,000,000 cubic metres. Although, by means of
operations conducted with equal skill and courage, about the third
part of this volume was let off without danger, the remaining part
having suddenly broken through the barrier of ice, was precipitated
with an almost unexampled impetuosity of 11 metres in the second,
into the Vallée de Bagne. In the first part of its course, and in the
space of half an hour which the mass of water took in traversing a
league, it carried away trees, dwellings, enormous masses of debris,
and rocks already separated from their mass, as M. Escher, expressly
says; it covered all the broad parts of the valley with rubbish,
pebbles and sand, and carried the remainder of the substances
which it had swept away, as well to the extremity of the valley,
towards Martigny, as into the bed of the Rhone. The mass of water
took an hour and a half in rushing from the glacier to Martigny. The
same event took place from the same cause, and with nearly similar
results, in 1595.
Torrents may therefore scoop out ravines in certain formations,
and produce effects which appear considerable, because we judge of
them by comparison with our own feeble means. But how diminutive
and circumscribed are these changes produced in the configuration
of the globe, compared with the long and broad valleys which furrow
in vast numbers the immense surface of the earth, and to the
formation of which neither the torrents nor great rivers which exist
at the present day have in any way contributed, as we shall
presently demonstrate.

2. Action of Rivers.

The action of rivers must be examined under two very different


circumstances, or at two different parts of their course.
First, When they are compressed between mountains, whether at
no great distance from their source, or even at the middle of their
course.
Secondly, When they have reached broad valleys, whose declivity
is slight, or plains which commonly surround their mouth.
In the first case, these rivers partake of the impetuosity and
power of torrents. They often run with rapidity, and in great
quantity, at the bottom of narrow and deep valleys: they are as it
were inclosed in channels, whose vertical walls appear as if cut by
art. The first idea which presents itself to all who have seen these
appearances for the first time, and who are satisfied with first
impressions, is, that these streams, which are pretty powerful and
always very impetuous, have dug these deep grooves; and if
sometimes the hardness of the rocks and the height of the
precipices which form their sides, appear too great for those small
streams that meander at their feet, what cannot be attributed to
their immediate power is attributed to the continued action of time.
Without examining how long a series of ages it would be
necessary to admit, before the rivers which we have mentioned
above, and the water-courses encased in the deep valleys of the
Alps, Pyrenees, Jura, Grampians, &c. could have scooped their
valleys, on which their present action is so slow that no one has yet
been able to estimate it; without examining if this long series of
ages agrees with the phenomena, which preclude our attributing so
remote an antiquity to the actual state of the earth’s surface, a
question of too much importance to be treated indirectly; it will be
sufficient to mention here four sorts of observations, in order to be
persuaded, or at least to suspect, that the present rivers, even
supposing them ten times the size that they are, could not have
scooped out the deep channels at the bottom of which they run.
1. We must recur to the period when the ranges of hills which
border the present valleys were not as yet scooped out, but were
united in such a manner as not to leave any hollow between them,
or merely a slight original depression.
This shallowness of the valley would be accompanied with an
inconsiderable slope of its bottom. If, then, we suppose the same
mass of water, it must run with less quickness, and consequently
with much less power; and yet a very great force must be attributed
to it, before it could have had the power of removing a portion of
rock nearly represented by a recumbent triangular prism, having
often 500 metres of breadth by a sometimes equal and often much
greater vertical thickness. If, in order to get rid of this difficulty, we
admit a volume of water incomparably larger than the present
volume of the rivers to which so great effects are attributed, we
must admit much more elevated and more extended mountains, to
give rise to so great a volume of water.
Were we only detained by this hypothesis, and did not direct
observation oppose itself to the admission of this disaggregating
power and its effect, we might pass it over; but two other
observations render the hypothesis inadmissible.
2. Historical records equally concur to prove that the rivers
possessed of the greatest power which can be attributed to them,
have no appreciable corroding action upon the rocks on which they
move.
No one has maintained that the greater number of the cascades,
cataracts, or rapids, long known and mentioned on account of their
celebrity, have disappeared or have even sensibly diminished, nor
consequently that the natural dike which the water had encountered
in its course, has been worn or even completely disrupted. We do
not find that cascades have changed into cataracts, and these again
into rapids. The cataracts of the Nile have been spoken of from time
immemorial, as always opposing an obstacle to the navigation of
that river; the same is the case with those of the Danube, of the fall
of the Rhine at Schaffhausen, &c. The famous cascades of the Alps
and Pyrenees have been cited ever since writing was in use; and
among all these examples we can scarcely find two or three
cascades that have been lowered, or cataracts reduced in their level.
The only cascade which we can point out as having really
diminished in height, is that of Tungasca in Siberia. We do not,
however, assert but that there may be others. So many causes
different from those of erosion may concur to lower a cascade, or
even make it disappear almost entirely, that we are rather
astonished at the small number of examples mentioned, than
embarrassed by the objections which these examples might present
to the opinion which we are defending: for the fall of a part of the
rock which forms the cliff from which the cascade is precipitated; an
abundant accumulation of debris at the foot of the cliff; a real
destruction of the softer deposits, forming part of the strata of the
mountain from which they fall, are sufficient causes for changing the
height of waterfalls. These causes must present themselves pretty
frequently; but how different is their action from that of erosion?
This, if it existed, would extend from the source of the river to its
mouth, and would have a considerable influence upon the
configuration of the earth’s surface. Those which we have mentioned
have, on the contrary, an action so limited and so local, as to be
scarcely appreciable.
3. Allowing, for the moment, that a river, possessed of a vast
erosive or disaggregating power, may have scooped out the valley in
the bottom of which it at present flows, in a state of feebleness very
different from its original state, we must account for the disposal of
a vast mass of earth and rock, which filled up the valley before the
river had removed it. It is not possible to suppose that it has been
transported into the sea, which is often more than a hundred
leagues from the valley; for we know that when rivers, on reaching
the plains, lose their rapidity, they allow the matters to be
precipitated which they held in suspension. Besides, we have shown
that many rivers, on leaving the mountains, traverse lakes, in which
they deposit all the earthy matters suspended in their waters. This
deposition is particularly striking in all the considerable rivers, which
descend from the ridge of the Alps toward the north-west and south-
east of that chain of mountains. These rivers meet, at the opening of
the valleys they flow through, lakes, which they traverse, and which
seem intended for their purification. Thus, on the northern side, we
see the Rhone traversing the lake of Geneva; the Aar, the Lakes of
Brientz and Thun; the Reuss, the Lake of the Four Cantons; the
Linth, the Lake of Zurich; the Rhine, the Lake of Constance. On the
south side, the Lac Majeur is traversed by the Tessin, the Lake of
Como by the Adda, the Lake Disco by the Oglio; the Lake of Guarda
by the Mincio, &c. Now, these lakes, which are only themselves
deeper parts of the valley, would have been filled up by the debris
conveyed to the valley, if this valley had the origin attributed to it.
Proceeding from one hypothesis to another, it might perhaps be
supposed that these lakes may have been sufficiently deep to
swallow up all the debris of the valley, without being chocked up.
But, rather than admit such suppositions, why not grant that the
same unknown cause which has scooped out the lake, has also
scooped out the valley which is only a continuation of it?
4. But if facts had proved that the waters degrade the rocks,
scoop them out, and perpetually remove their debris, we might
perhaps be induced to admit that unknown causes, of which we are
absolutely ignorant, and of which we can form no idea, have given
to the original rivers the means of surmounting all these obstacles.
Now, observation would seem absolutely to prove the contrary.
We have remarked, that rapid rivers which, in the bottom of
valleys, fall in cascades, from rock to rock, which beat with violence
against the walls which contain them, do not in any degree alter
these rocks, and that, far from corroding their surface, they allow it
to be covered with a rich coating of mosses, confervæ, &c. which
could neither maintain itself, nor be formed at all, were the least
portion of the surface of these rocks continually or even only
frequently removed.
A much more striking fact is that which some of the great rivers
present, such as the Nile, the Orinoco, &c. which flow in the
equatorial regions.
These powerful rivers, when they have arrived at places where
they are contracted, and, as it were, jammed in between two rocky
walls, form impetuous cataracts. Their waters, endowed by the
celerity of this fall with the greatest erosive power that can be
attributed to this fluid, must necessarily have corroded, or at least
worn, the rocks which they have thus beat against since the creation
of our present Continent. Now, so far from removing the surface,
they cover it with a brownish varnish of a peculiar nature.
It appears, therefore, well established, that water alone does not
scoop those rocks, whose aggregation is complete, or which are
solid; and that it does not wear them in any way, whatever be its
quantity of motion.
We say water alone; and we must insist on this distinction, in
order to make the preceding facts agree with other facts, which
might seem contradictory.
We often see furrows scooped out on the walls that bound the
narrows of rivers; we also see rocks rounded, and entirely destitute
of moss. But let the facts be examined with attention, and we shall
find that this erosion always takes place in the parts of their course,
where, on account of the nature of the neighbouring soil, the
torrents carry with them, in their risings (or floods), debris and
detached stones from their banks; and it is by means of these
stones that they wear the rocks which are in their bed.
It is very easy to appreciate these circumstances. It is remarked,
that this erosion has never taken place at the sources of powerful
springs. All the pebbles which had to be carried off have been so
long ago, and the mosses which grow abundantly on the rocks at
the level of the water, and in the bed of these torrents, have nothing
more to fear from the destructive action of these solid bodies. The
case is the same with the parts which immediately succeed a lake,
or a great excavation, capable of arresting all the hard bodies carried
off by the river. There the mosses appear in abundance; because
they are not subjected to the action of any other substance than of
the water alone.
The present rivers do not therefore appear to have any erosive
power upon the rocks which are completely aggregated, when they
act by themselves, and when no other cause, such as frost,
decomposition, &c. has disintegrated the rock. The absence of these
foreign circumstances is proved by the vegetation or the enamel
which then cover the rocks exposed to the action of the water.
These rivers, in proportion as they remove from the rocks in the
neighbourhood of the lofty mountains in which they took their rise,
often gain in volume what they have lost in velocity; but the power
dependent upon size rarely compensates that which they owed to
rapidity; and although these large rivers still retain a transporting
power, sufficient to carry along with them the obstacles which
oppose themselves to their progress, they are far from presenting
results of action so striking as those of torrents. They stir up, when
flooded, or when they change place, the earth and mobile sand
which cover their bottom, especially towards their edges, and
transport them to some distance; but they scarcely move pebbles
larger than an egg, which occur in their bed, and which have been
brought there in other times, and under other circumstances. On
thus transporting the comminuted and mobile mineral matters, they
deposite them again in places where their current is relaxed by some
cause, and thus raise the bottom of their bed in these places; they
seek a new passage in the midst of the barriers which they have
themselves constructed. The principal current is then borne,
sometimes against one bank, and sometimes against the other; and
when it comes to beat upon the foot of a steep part, composed of
moveable soil, as the banks commonly are, in such cases, they really
erode it, and make it fall into the river; and transport to another part
of its course, the earth resulting from the destruction of the bank,
and give rise to new obstacles. Hence the new deposites, which
border rivers in all points where their current is slackened, and
principally toward their mouth. It is sufficient for our present
purpose to have referred to facts remarkable for their number, for
the importance which they have had in regard to the modern
changes of the configuration of the globe; and, lastly, in regard to
agriculture and civilisation;—facts of easy observation, and which
tend to prove, that the action of rivers, whose fall is not sufficiently
rapid to entitle them to be considered as torrents, is not to scoop
out their bed, either in the valleys or in the plains through which
they flow, but rather to raise them, and to tend, consequently, rather
to level and flatten the earth than to furrow it, more than it has been
since the Continents have assumed the configuration which they
now possess.
But if we have not been able to recognise a real corroding power
in the great rivers falling in the form of cascades or cataracts, let us
inquire elsewhere, in circumstances where the water seems
endowed with a still superior power, what are the effects of this
agent?

3. Action of Waves.
It is in the sea, an enormous mass, sometimes acquiring, from the
action of the winds, an incalculable power, that we must find the
maximum of force of the water of the present times. In fact, in this
case, the power of transportation is so prodigious, that the strongest
barriers, both natural and artificial, are overturned, and the largest
stones, together with enormous fragments of rocks torn from their
place, transported, and even projected to a distance. But it is to
these effects that this immeasurable power is limited. The water,
which displaces and transports to a distance these heavy masses,
does not abrade the surface when it acts by itself. We see this
surface, on rocks and the sides of piers and dikes, perpetually
beaten by the waves, covered with fuci, confervæ, byssi, and other
delicate vegetables, without roots, which the waves have not
prevented from contracting a first and feeble adherence, and which
they do not hinder from growing. But, if the waves carry with them
pebbles, or even sand, it is those hard bodies which act; the surface
of the rocks is abraded, and all vegetation ceases.
The same effect takes place, and is even augmented by the real
degradation of the coasts, if the sea acts upon friable rocks, capable
of mixing with water, such as argillaceous or calcareous marl, or
chalk, or upon rocks which are hard, but naturally fissured, or partly
disaggregated, such as certain granites; it then easily removes the
crumbled or previously detached parts, scoops out the foot of the
rock or steep coast, and causes the upper part, which is deprived of
support, to fall. But, in consequence of this fall, it forms a slope,
which, by its inclination, deadens the violence of the shock, and
even protects the foot of the cliff, for some time only, if it be friable,
or capable of disintegration; and for ever, if, being compact, it does
not carry in it the causes of destruction. The action of the waves
ceasing, the slope is covered with vegetation; and if the coast
continues, nevertheless, to be worn, the changes are then owing to
causes unconnected with the action of water.
Such is, in few words, the ordinary action of the water of the sea
upon steep coasts, and even that of great masses of water in a state
of agitation. M. De Luc, in his various works, has estimated this
action with a correctness of observation and of reasoning, which is
remarkable only, because it has not been adopted by all naturalists;
and few have bestowed the unremitting attention upon the subject
which this respectable geologist has done. He has shewn, that the
destructive action of the waters upon steep shores, and other coasts
or abrupt cliffs, was considerably restrained by the very
consequences of this action; that the debris which accumulated
protected the lower parts of these coasts from the action of the
water, or gradually reduced an abrupt coast to a very inclined and
permanent slope.
Next, to torrents, to rapid and large rivers, and to waves, it is to
currents that a great influence on the earth’s surface has been
attributed,—an influence which a highly gifted naturalist, Buffon, has
employed to explain all the inequalities of the earth’s surface.
Our knowledge of the action of currents is less precise than that
which we possess of rivers. But if we cannot so visibly demonstrate
that, in no circumstance similar to those which we have specified, do
they scoop out the bottom of the sea into valleys, nor form any
mountains, we can, at least, conjecture with much probability, and
maintain, that we have no direct and constant proof of that action.

4. Action of Currents.

No one doubts that currents, near coasts, heap up upon the


beach, at the mouth of rivers and harbours, pebbles, sand, gravel,
mud, or other transportable matters, whether these currents
constantly exist, or simply result from the momentary action of a
predominating wind; but this action, although already limited to the
mobile matters which form the bottom of the sea only in some parts,
whether this action, I say, extends to a great depth, that is to
several hundred yards, is a question not yet resolved. In the first
place, the observation made by mariners, that, in the most violent
tempests, the sea is only agitated towards the coasts, or on
shallows, and that bodies, sunk to a great depth, (and still what is
this depth in comparison with that of the sea,) do not feel the
motions of its surface, nor that of currents; and, secondly,
reasoning, and even calculation, according to Messieurs La Place and
Poisson, concur to shew, that the violent motions of the waters of
the sea are not propagated to a great depth. It is therefore
probable, that all the transportable matters, which are at this depth,
must remain nearly in the position in which they are, since our
Continents have assumed their present configuration, unless
phenomena and motions of the sea take place at the bottom, of
which we are ignorant, and which are foreign to the subject which at
present occupies our attention.
But if we have no perfectly certain ideas regarding the
propagation of the motions of the sea in depth, we can assert, that,
whatever that extent and that power may be, the submarine
currents no more abrade the rocks than rivers do the surface of the
land. This proof is always derived from the same kind of fact,
namely, from the vegetable and animal bodies which constantly
cover the rocks, and which are found, at all times, by means of
various sorts of dredge-fishing. In fact, no one has remarked, that
the places in which oysters, mussels, corals and sponges are fished,
are more sheltered from currents than others; nor that these places,
after violent tempests, have been deprived, and consequently, as it
were, despoiled of those productions, which, by covering the rocks,
demonstrate that they preserve the integrity of their surface. Many
of these bodies, however, as sponges, fuci and confervæ, contract
but a feeble adherence to the bodies upon which they are placed.

It therefore appears, if not completely proved, at least extremely


probable, from the facts and reasonings which we have related,
1. That the presently existing waters, that is to say, in the state of
purity in which we are acquainted with them, have no erosive action
upon rocks, whatever be the nature of these rocks, when, 1st, The
rocks are completely solid, and when they are neither friable nor
disintegrated; 2d, When these waters act by themselves, that is to
say, when their action is not complicated with the really erosive
action of solid bodies, such as pebbles, sand, and perhaps even
pieces of ice.
2. That water, sometimes acquiring, on account of its quality and
velocity, a great transporting power, may remove masses, already
detached, and of great size, according to its degree of velocity, and
the bulk of its mass, and so far as it preserves this same power.
3. That the presently existing waters may have attacked,
undermined, and caused to fall down, portions of solid and steep
rocks, by mixing with beds of clay, marl, and sand, interposed
between their solid strata; that they may also, in their rapid falls,
have scooped pretty deep ravines in very inclined deposites,
consisting of disintegrated rocks; but that these waters could not
have scooped out, either by a violent action, or by a slow one,
however long continued, any of those long and broad longitudinal
depressions, which are named valleys, or of those narrow openings,
with almost vertical walls, which are named gorges or ravines.
4. That, even when the deposites, which border these valleys or
these ravines, are composed of transportable matter, the waters
which at present flow in them could not have scooped them out,
even supposing them to have been much larger in some than they
now are; the declivity of the present deposite not being sufficiently
great to give to these masses of water the rapidity necessary for
producing this effect, and a power sufficient for carrying off the
moveable matters which filled the valley or gorge.
5. Lastly, that the present running waters, so far from having
contributed to form the numerous valleys, glens, gorges and ravines,
continually tend to fill them up, and rather to level the surface of the
globe than to furrow it, more deeply than it is.
Vid. Brongniart sur l’Eau.
Note

On the Connection of Geology with Agriculture and Planting [410] .

That all sorts of soils are not equally adapted to all productions, is
a remark of Virgil’s, the truth of which becomes obvious, when we
consider many facts ascertained in Agriculture and Forestry. If,
therefore, as the poet advises, our object be to determine what each
particular region can produce, and what it cannot, our attention
ought in the first place to be directed to the physical circumstances
which exert their influence over vegetation.
All plants that are the subject of cultivation are fixed in the
ground. By one of their parts, through which they derive their
principal nourishment, they penetrate into the soil, which serves
them as a basis, and affords them the means of procuring
subsistence; by the other part they raise themselves into the
atmosphere, which is not only necessary in itself for their existence,
but is also the medium through which they derive the warming and
vivifying influence of the solar rays. Hence we can understand how
much the existence of plants must be influenced by differences in
the condition of the soil and air.
The superficial crust of the globe is formed of soil capable of
producing vegetables. This productive soil, however, is not
everywhere continuous, being interrupted on the one hand by the
watery covering of the earth, and on the other by perennial snow
and bare rock. Where soil does occur, it separates the solid mass of
the earth from the atmosphere, and is the porous medium through
which the gaseous and watery parts of the latter may act in a
greater or less degree upon the former. It is very seldom that strata
of vegetable soil lie beneath strata of other matters; and where they
occur in this position, the overlying strata are either of volcanic or of
alluvial origin. Of the former case, a very remarkable example occurs
in the Isle of Bourbon, in which large tracts covered with vegetables
and even trees, have been laid waste and overwhelmed by streams
of lava; and large rivers in their overflowings occasionally leave
deposits of various characters, over the productive soil containing
remains of formerly existing plants.
Productive soil, as well in regard to its situation as to its
constitution, depends upon the nature and condition of the rocks
which form the solid mass of the earth. It is always of secondary
formation, compared with the rock on which it rests, its principal
parts usually originating from the decomposition of this rock. While
the forms of the surface of the solid mass of the earth, have much
influence upon the action of the atmosphere, they also in some
degree modify that of climate. From these circumstances it would
appear that the solid substrata of productive soil exert an influence
in various ways upon vegetables; whence it follows that, in order to
obtain a more intimate knowledge of the conditions which operate
upon their existence, it is necessary to call in geology to our
assistance.
Although the scientific study of agriculture has made great
progress in our times, the relations which exist between the
constitution of the solid crust of the earth, and the formation and
nature of vegetable soil, present a wide field for investigation.
Geologists have hitherto too much neglected the examination of the
productive covering of the earth, and those who have treated
scientifically of agriculture and forestry have usually looked upon the
vegetable soil in its own simple capacity, without regard to its
foundation and origin. To point out the way by which we are to
proceed in our investigation of the relations which exist between the
solid crust of the earth and the productive soil which covers it, is the
principal object of the following observations.
Bare rocks cannot be made subservient to the purposes of
agriculture. Lichens indeed, cover the surface of rocks, deriving their
chief nutriment from the atmosphere; mosses draw the water
necessary for their subsistence from the fissures of stones; the roots
of grasses seek in the chinks of rocks for particles of earth sufficient
for their sustenance; various shrubs and trees penetrate here and
there into rocky masses by their roots (having the powerful and
continued action of living wedges), where the cohesion of the parts
is smallest, in order to prepare a fixed seat for themselves, and be
secure from the pernicious effects of the atmosphere. The surface of
the earth is always sterile, however, when it shows a continuity of
naked rock, uncovered by vegetable mould. The cultivation of fields
and woods, and even the rearing of cattle, cannot therefore find
scope in regions which are entirely rocky. Abrupt and precipitous
mountains being generally in this condition are usually barren; but in
plains and on declivities, a bare rocky surface is much less frequently
the cause of sterility than an unfavourable proportion of mould.
Some rocky and moderately elevated regions also occur, more or less
destitute of vegetable mould, whose sterility depends upon volcanic
causes. Iceland, for example, affords cases of this description. In
many parts of Sweden, as in Westrogothia, in Scotland, &c., there
occur many elevated regions, in which gneiss and granite
predominating, exclude to a great extent all kinds of vegetation
excepting lichens. In the same districts we sometimes meet with
pastures and corn-fields interrupted here and there by bare rocks
rising but little above the surface, by which the value of the ground
is much diminished, and great impediments opposed to its
cultivation.
As bare rocks are incapable of all cultivation, their distance from
the under surface of vegetable mould must also be of great
importance. In the plains of the north of Germany, for example, this
distance is often so great that a rocky surface is never found, while,
on the contrary, in other countries, especially such as are
mountainous, the roots of plants not unfrequently touch the
subjacent rock; the variation between these extremes being of all
degrees. The effect of the distance of the surface of the solid rock
from the under surface of productive soil may be both direct and
indirect, and may vary much, not only with reference to the species
of rock, but also to the vegetables.
The surface of the solid strata of the earth has a direct influence
upon the cultivation of plants, because it terminates the extension of
their roots, and limits the volume of the soil necessary for their
sustenance. As the length and direction of the roots vary exceedingly
in different species, the difference of effect with regard to their
growth, and the approximation of the rock to the under surface of
the soil, must in general be so much the less prejudicial in
proportion as the roots decline from the perpendicular; whence it
follows, that certain grasses, and some small pasture plants, may
grow in very thin layers of soil, where the larger grasses and pasture
plants with longer roots, could not find subsistence; and that shrubs
and trees, with long perpendicular roots, cannot survive in many
places, where others with more horizontal roots may thrive. These
inferences are proved to be correct by observations in agriculture
and forestry generally known.
Mountainous regions, which are not so elevated but that corn
might grow sufficiently well in them, in so far as depends upon the
conditions of the air or climate, are yet frequently not adapted for its
cultivation, on account of the too near approach of the rock to the
surface, or shallowness of the soil, and produce nothing but grasses,
and some other pasture plants, among which, however, there is the
greatest difference in this respect. Trifolium montanum, for example,
can support itself on rocky mountains, where T. pratense could not
grow. Hedysarum onobrychis grows luxuriantly on the sunny
declivities of calcareous mountains, where Medicago sativa (Lucern)
does not find a suitable station. The cultivation of this excellent
pasture plant in some mountainous regions, especially where the
rocks are calcareous, has not proved so advantageous as might have
been expected, because the plants have died out in the course of a
few years; whereas, in proper places, where its very long roots find
a sufficient depth of soil, they usually last for a great length of time.
The vicinity of the rock to the under surface of the vegetable
mould, or the shallowness of the soil, seems to be the principal
cause why the Beech grows better on many calcareous mountains
than the Oak, which, on the other hand, finds a fitter station on
mountains in which sandstone predominates, where the soil is
usually deeper. It would seem to be for a similar reason that the
Beech grows in many rocky districts, for example, on the Hartz
Mountains, at pretty considerable heights, especially on the sides of
valleys which run to the south, while these places do not admit the
Oak, which is found in the middle provinces of Sweden and Norway;
while the Beech, on the other hand, grows only in the southern
parts. From the deficiency of soil, the Upper Hartz can produce
neither the Pinus pinea, nor P. sylvestris; the horizontal roots,
however, of the Abies, or Norway Spruce, are content with the small
portion of earth which covers the greywacke and slate, although
they cannot find sufficient hold to protect its lofty trunks from being
thrown down by the tempest. In some parts of the Forest of
Thuringia, where the covering of loose earth is deeper than in the
Hartz, the Pinus picea, or pitch pine, grows luxuriantly. The common
fir, Pinus sylvestris, which attains a great height in proper soil, on the
contrary, is stunted and distorted on rocky mountains, where the
roots soon come in contact with the rock. It there loses the
character of a tree, and assumes that of a shrub, as in place of a
single upright stem, several branches shoot out, and these, not
unfrequently, are creeping or bent.
The different conditions of rocks, especially their structure and
their state of cohesion, are of some importance in producing these
effects; for the surface of rocks must be detrimental or impervious to
the roots of plants, in proportion to the compactness of their
structure, and the cohesion of their parts. Schistose rocks, for
example, afford a more easy passage to roots, than granular
crystalline ones; pure quartz resists the roots of plants in the highest
degree; sandstone much less; and pure limestone, on account of its
comparatively small number of fissures, is much less favourable to
vegetation than marl, chalk, or slightly cohering calcareous rocks,
the masses of which are usually split in all directions.
The direction and inclination of the strata have also some
influence in this matter; for, in proportion as the principal fissures of
the strata are, from their direction or inclination, more readily
presented to the roots of vegetables, the less prejudicial will their
surface be to vegetation. Horizontal strata, therefore, are the least
favourable to vegetation, perpendicular ones the most. In the
inclination of strata intermediate in some degree between these
positions, the roots of vegetables will find a greater obstacle on the
side of a hill in which the surface of a stratum is opposed to them,
than on the other, in which the principal fissures of the strata are
open. The effects of this circumstance may frequently be observed
in mountainous tracts having two principal inclinations, the state of
vegetation, and especially the growth of wood, being more
prosperous on the one of these declivities than on the other.
The surface of the solid strata of the earth may also have an
indirect influence upon the cultivation of vegetables. The various
inclinations of this surface deserve first to be considered, being of
the greatest effect with regard to fixing the fertile soil. The
horizontal position of a rocky surface is in the highest degree
favourable to the stability of vegetable earth; and the greater its
angle of inclination, the greater is the danger of its losing the soil
upon it. In a highly inclined plane, the imperfect support of the
centre of gravity is the sole cause of the loss of earth; in a less
inclined plane the diminution of soil is usually caused by water,
which produces this effect in a greater or less degree, according to
the difference of inclination. In both these modes, by which a
removal of soil is produced, the effect may be modified by a
difference in the condition of the loose earth, as not only its stability
as to situation, but also its resistance to the power of water, vary
according to the size, figure, and cohesion of the parts, as well as
their adhesion to the surface of the rock. Sandy loose soils, for
example, are more liable to transposition than marly or loamy ones;
and these, again, are more easily moved than such as are clayey
and adhesive.
Whatever be the nature of the soil, a small degree of inclination in
the solid rock is sufficient to favour its denudation by the removal of
the former; and the inclinations of the surfaces of rocks having a
covering of earth and vegetation, are in reality much less
considerable than we usually suppose them to be, judging merely by
the eye. The celebrated Humboldt has published observations on
this subject. According to his measurements, a slope of even fifteen
degrees appears steep, and a declivity of thirty-seven degrees is so
abrupt, that if it be covered with a dense sward, it can scarcely be
climbed. The inclination of the pastures of the Alps seldom exceeds
an angle of ten or fifteen degrees, and a slope of twenty degrees is
pretty steep. At an inclination of forty degrees, the surface of the
rock is sometimes covered with earth bearing a sward, but at a
greater inclination the rocks are usually destitute of soil and
vegetation. In the Upper Hartz, the most common inclination of the
declivities of the mountains is twenty-five degrees; nor does it
usually exceed thirty-three, at which inclination the beech and
spruce grow. The greatest declivities at which ground can be
advantageously cultivated have an inclination of thirty degrees.
The roots of vegetables, especially of grasses, shrubs, and trees,
are of much importance in supporting the earth upon the declivities
of rocks. Care must therefore be taken that the declivities of
mountains which are covered with turf or wood, be not altogether
deprived of these coverings, as sometimes happens in consequence
of loosening the turf for agricultural purposes, or of incautiously
extirpating the wood. In Norway, near Roraas, there occur
mountains, destitute of all vegetation, that had formerly been
covered with woods, but where now, from the deficiency of soil, no
seeds could take root. The same is the case in many parts of the
Alps, where, from the irregular long-continued removal of the timber,
the sides of mountains which were formerly covered with thick
woods, now show nothing but naked rocks. For this reason, in
mountainous countries with very steep declivities, the breeding of
cattle and planting of woods are often more advantageous than
agriculture. In France the greatest inclination of the public roads is
limited by law to an angle of four degrees and forty-six minutes: a
similar restriction with regard to agriculture might not be without
benefit in certain mountainous countries.
The inclinations of the surface of the solid crust of the earth vary
much, according to the different qualities of the rocks; some having
a tendency to form abrupt precipices, others, again, to produce
gentle declivities. For this reason, mountains consisting of quartz or
porphyry, for example, very frequently present surfaces destitute of
vegetation; while, on the other hand, those of granite, slate or
sandstone, are more frequently adapted for agriculture and planting.
In the northern parts of Scotland, quartz rocks, destitute of all
vegetation, rise in the midst of mountains covered with gramineous
plants, and sometimes wood. In the most fertile part of the south of
Norway porphyritic mountains rise from a calcareous and schistose
base, with lofty, rugged, and bare cliffs. In the southern parts of the
Tyrol the rocky sterility of the abrupt and lofty porphyritic mountains
presents a striking contrast to the fertility of the neighbouring
limestone mountains, which are covered with vines, walnuts and
chesnuts.
The surface of the solid strata of the earth has also an indirect
influence upon the cultivation of plants, in so far as the water which
the vegetable mould acquires from the atmosphere, is retained in
the soil, or is drawn off by the subjacent rock. Different rocks
produce very different effects in this respect, depending as well
upon their constitution as their structure. The component parts of
rocks imbibe water in different modes and degrees; and different
sorts of rocks not only attract water with different celerity, but also
imbibe different quantities of it. The latter difference depends chiefly
upon the various substances of which rocks are composed, partly,
also, upon their porosity. Siliceous rocks attract water in the lowest
degree, argillaceous ones in the highest, and calcareous rocks
appear to have an intermediate action in this respect. Compact and
granular crystalline rocks attract water in a smaller degree, and more
slowly; friable or crumbled rocks imbibe it in greater quantity, and
with more celerity than those which are not disintegrated. The
condition of rocks with regard to the attraction of water, affects, in a
different manner, the humidity of soil; for, by this attraction,
moisture may as well be abstracted from, as imparted to, the loose
earth or soil by which rocks are covered. Part of the moisture which
vegetable earth or soil derives from the atmosphere passes into the
subjacent mass of rock, but this may again be compensated by
evaporation; on which account the soil of such rocks as have but a
small attraction for water usually dries up more readily than soils
whose solid substratum attracts and retains the moisture in a greater
degree.
It is probable that the structure of rocks has also a greater, and
not less, diversified influence upon the humidity of productive soil.
Solid rocks, which are not traversed by numerous perpendicular
fissures penetrating to a considerable depth, allow the water to
remain in the soil; but columnar and schistose rocks, with
perpendicular fissures, and strata declined from the horizontal
position, draw off the water from the soil covering their surface, into
lower places, where it often re-appears under the form of springs. In
these circumstances, we find a partial explanation of the great
difference between the humidity of soil covering a surface of solid
granite, and that lying upon limestone, which is intersected by
numerous fissures. Granitic mountains are often furnished with
marshes, whereas, on the other hand, the dryness of the soil upon
calcareous mountains is generally excessive[411], the cause of which
phenomenon is, in a great measure, to be attributed to the
circumstances above mentioned. Columella observes, that silex
having a moderate covering of earth, preserves to the latter its
humidity; and Palladius repeats the remark. In districts which consist
of quartzose rocks, not less than of granitic ones, the surface is
often covered with marshes. Porphyritic rocks, on the contrary,
which have a remarkable segregation of parts, as well as columnar
basalt, let off the water to lower places. Springs are very frequently
found at the bottom of basaltic mountains; for the atmospheric
waters penetrate by the perpendicular fissures to the strata on which
the basalt rests, and appear at the place where the two rocks meet.
The effect of different rocks upon the preservation and diminution
of the moisture of fertile soil, influences vegetation in various
degrees. The retentive power of the surface of rocks is of the
greatest importance, where the soil consists chiefly of sand, through
which the water percolates, and passes off entirely, unless it meets
with a stratum of such a nature, as to obstruct its passage, or comes
upon a surface of solid rock. The cause of the sterility of sandy
plains is not merely their sandy nature, but also the great depth of
the mass or rock capable of retaining the water. The same sand,
when covering mountains consisting of sandstone, has a much less
degree of sterility than in those plains, because the surface of the
subjacent rock impedes the progress of the water, and consequently
retains it in the soil[412]. It has been sufficiently proved by
experiments, that plants can grow in pure sand, when furnished with
the necessary quantity of water. A subjacent rocky surface has an
entirely different effect upon soil which is very retentive of moisture,
upon a clay soil for example, as, in that case, the humidity is
increased to a prejudicial degree. In land of this nature, a
substratum of rock having the property of drawing off the water
would be useful.
The different conditions of rocks with regard to caloric, may have
some indirect influence upon the vigour of plants. Heat, whether
imparted to the vegetable soil by the sun’s rays, or generated by
various chemical processes in the earth itself, penetrates to the
surface of the subjacent rocks, and is more or less drawn from it in a
longer or shorter time. Columella observes, that rocks in the upper
part of the soil are prejudicial to vines and trees, but in the lower
part cool them. The heat of soil will be more or less drawn from it,
according to the greater or less conducting power of the subjacent
rock. Compact crystalline rocks are probably better conductors of
caloric than those which are of looser texture; siliceous rocks than
argillaceous and calcareous ones. The influence of the subjacent
rock must be greater in this respect, in proportion to the thinness of
the superincumbent soil. The effect of the abduction of caloric is
more particularly sensible, where the roots of cultivated plants touch
the rock, a circumstance which we often see in vineyards. The vine
frequently thrives remarkably on the declivities of mountains, in
which it sends its roots among fragments of stones. Experience
shows, that the quality of wine is influenced by the different
conditions of the stones, among which vines are planted. Albertus
Magnus has observed, that the vine thrives well in earth which is
mixed with fragments of black roofing slate; and Humboldt remarks,
that the vines which grow upon the mountains of the valley of the
Rhine, consisting of black clay-slate, afford an excellent wine. At the
Cape of Good Hope, also, the vine thrives well in a soil produced by
the decomposition of clay-slate, and mixed with fragments of it[413].
It is probable, that the adaptation of this sort of soil to the
cultivation of the vine, depends upon its slow conducting power, and
upon its rapidly imbibing the rays of the sun, on account of its dark
colour, and thus increasing the heat of the ground.
Hitherto we have only spoken of the proximate influence of rocks
upon plants; but it cannot be denied, that the remote effects which
they produce, (inasmuch as vegetable soil is derived from them,
and, therefore, the qualities of this soil depend in a great measure
upon their nature,) are of greater importance.
It is from the rocks which constitute the crust of the earth, that
the principal portion of productive soil is derived. Although other
substances belonging to the animal and vegetable kingdoms, are
necessary for the nourishment of plants, a soil consisting chiefly of
inorganic particles is still more necessary, both for sustaining their
roots, and for receiving, retaining, and partly also preparing nutrition
for them; for, according to accurate observations, some inorganic
substances exert an influence upon the decomposition of animal and
vegetable remains. These effects vary much according to differences
in the aggregation and chemical nature of the inorganic parts; of
which circumstances, however, the different qualities of rocks are the
ultimate cause.
Two kinds of productive soil may be distinguished with regard to
their origin. The soil has either originated in the place in which it
now is from the subjacent rock, or it has been transported to the
places in which it is now found by some power, especially by that of
water. The first kind may be named untransported, the second
transported soil. To the first kind of soil is to be referred a great part
of the soil which covers the summits and declivities of mountains,
and to the other, the soil which fills the bottoms of valleys, as well as
a great part of the loose soil of extensive strata in hilly countries and
plains. Untransported soil is generally thinner than the transported;
and of the two the latter is that which most frequently occurs in low
land. The first kind of soil, the untransported, is found to be more or
less similar, in its principal constituent parts, to the rocks from which
it has originated; in the other kind, the transported soil, on the
contrary, the parts which were originally in connection, have been
variously separated and mixed, by the agency of the powers by
which its transportation was effected.
The quantity and quality of the soil derived from the disintegration
of rocks, must depend upon the nature of these rocks; its quality
being determined by the constituent parts of the rock from which it
originated, and its quantity being proportioned to the greater or less
degree in which the rock may resist decomposition.
The disintegration of rocks, and their conversion into loose earth,
are partly mechanical, and partly chemical. The principal mechanical
powers, by which disintegration is effected, are, 1st, The weight of
the loosened parts; 2d, Water, not merely in its liquid and mobile
state, but also, and that chiefly, in the state of ice; 3d, The roots of
vegetables in general, and especially of trees. These powers usually
act more or less in conjunction, and the effects produced by this
union are in many cases almost incredible.
The disintegration of rocks commences in those parts where the
power of cohesion is least energetic. Rents take place owing to the
unequal attraction of parts, and also in the direction of planes, in
which heterogeneous parts are in contact; and in this manner the
original structure of rocks determines the first steps of their
disintegration. Water, which enters into the minute fissures of rocks,
by the power of capillary attraction, is expanded by congelation, and
thus overcomes the cohesion of parts, and produces rents. The roots
of trees acting as wedges, produce the same effect in a wonderful
degree, a phenomenon which has been so well illustrated by
Annæus Seneca, in his Natural Questions. “Let us consider,” says he,
“how great a power is exerted by the most minute seeds, which,
although at first small as they are, can scarcely find a place in the
crevices of rocks, yet at length grow to such a size as to rend
asunder vast rocks, overturning crags and cliffs, by the power of
their very minute and delicate roots.” The parts of rocks loosened by
these powers, are entirely separated, and are carried to a great or
less distance, by streams of water, and in the higher regions, by the
power of winds. In cliffs and precipices which have been formed by
the splitting of masses of rock, effected in the manner above
described, the loosened parts often lose their stability; and, following
the direction of gravity, fall to the ground, an effect which has also
been described by Seneca in another place. “Nor is it alone
probable,” says he, “that rocks are split asunder by their mere
weight, but also when streams of water are carried over them, the
continual moisture works into the joinings of the rock, and daily
takes away a portion of the connecting matter, and, if I may so
speak, abrades the skin by which it is contained. At length, in the
course of ages, this gradual detrition so much diminishes the
supporting parts, that they can no longer sustain the weight. Then
masses of vast size fall down, and the rock tumbling from its ancient
seat, overwhelms whatever lies below.” The cohesion of some rocks,
especially argillaceous ones, is so slight, and their porosity so great,
that their smallest parts imbibe water, and are sensibly softened by
it, an effect which is much assisted by the freezing of the water. This
mechanical change is experienced by the different varieties of
common clay, slate-clay, and some other rocks.
Chemical powers often act in conjunction with mechanical ones, in
breaking down rocks, the former, the chemical, frequently finishing
what had been begun by the latter. Mechanical powers only
changing the aggregation of rocks, may break down their parts to a
certain size, according to their different nature; chemical powers,
again, which change the nature of substances, destroy the
connection of the minute parts of rocks. When chemical is preceded
by mechanical action, it is much assisted by it. The latter has a much
more general effect, as all rocks are subjected to its influence;
chemical decomposition, on the other hand, acts only upon some
rocks, and in these only upon certain parts. The chemical
decomposition of rocks is chiefly effected by the oxygen of
atmospheric air and of water; but we are also persuaded, that
certain cryptogamic plants, intimately attached to the surface of
stones, Lichens namely, assist in their destruction.
The oxygen of air and water can only affect the constituent parts
of rocks, which have a great affinity to it, such as the iron and
sulphur forming pyrites, oxydulous iron, oxydulous manganese, or
the same substances mixed with earth or carbonic acid, charcoal and
bitumen. Very solid and compact masses of rock, such as
greenstone, which are not easily affected by other means, are
sometimes corroded by the chemical change of the pyrites contained
in them, by which it is converted into a hydrate of iron[414]. In
certain other rocks, which are also readily broken down by
mechanical agents, clay-slate for instance, the disintegration is much
accelerated by the decomposition of the pyrites. The oxydulous iron
of felspar is commonly converted by decomposition into a hydrate or
ochre. The carbonate of iron, as well as of manganese, which
sometimes occur in rocks, in limestone rock for example, are
deprived of carbonic acid by the oxidation of their bases. Charcoal
and bitumen, which are sometimes contained in rocks, limestone
and argillaceous ones for example, are dissipated by the contact of
air, so that rocks which were originally of a dark colour, lose it, and
become whitish. Water, as a chemical agent, contributes so much to
the decomposition of certain rocks, that, either in a pure state, or in
combination with carbonic acid, it dissolves their parts, of which
gypsum and limestone afford examples. In certain other minerals, in
felspar for instance, a separation of the constituent parts, produced
by the contact of air and water, is observed, the proximate cause of
which has not hitherto been discovered. The mass is decomposed,
its lamellar structure is converted into an earthy nature, the alkali
contained in the felspar is extracted by the water, a mineral is
produced, to which the Chinese have given the name of Kaolin, and
which is adapted for the manufacture of porcelain. Granite and
gneiss occur in some districts, the felspar of which is decomposed in
this manner through the whole mass,—a circumstance which must
be of great importance in regard to the formation of productive soil.
Cryptogamic plants covering the surface of rocks, and thriving well
in this situation, where more perfect vegetables could not grow,
seem also destined to promote the chemical decomposition of rocks,
an effect which they produce both directly and indirectly. As they
imbibe the water of the atmosphere, and retain it like a sponge, they
keep up a constant application of this substance to the rock, and in
this manner contribute indirectly to its decomposition. There are
some cryptogamic plants also, which consume certain portions of the
rocks with which they are in contact, corrode their surface, and
destroy the cohesion of its parts, effects which may chiefly be seen
in certain cryptogamic plants attached to calcareous rocks. In this
manner one sort of vegetation prepares a place for another, and the
most imperfect vegetables are subservient to the growth of the more
perfect.
After premising thus much, we shall now proceed to the
examination of the principal rocks, in so far as regards their
connection with the formation of productive soil, beginning with
those which resist decomposition in the highest degree, and ending
with those which are the most conducive to the formation of loose
earth and soil.
In the first class, we place those rocks which experience no
chemical decomposition, in so far as regards their principal mass,
and whose cohesion of parts is so great that mechanical powers can
only open their natural fissures to a greater extent, and thus break
them down into fragments. Of this kind are vitreous lava, pure
quartz, compact quartz, flinty slate, and porphyry with a siliceous
basis. On mountains consisting of these rocks, scarcely any
productive soil is found, and frequently none at all. They are usually
characterized by sterile rocks and cliffs, the bases of which are
covered with innumerable rough fragments of stones, retaining their
sharp edges for a great length of time, the heaps of which seldom
produce any thing else than mosses, which frequently cover the
interstices of fragments, occasionally a few grasses, and sometimes
a solitary shrub or tree. Examples, Bennevis, Paps of Jura, and
Morven Hills. Of all rocks, vitreous volcanic productions are the least
capable of contributing to the formation of productive soil. Their
dark coloured tracts descend from volcanic mountains to the valleys
in frightful sterility, the chinks of their rugged masses scarcely
affording sufficient water for the roots of mosses[415]. To the second
class we refer compact limestone, a rock which contributes
extensively to the formation of the solid crust of the globe. In so far
as regards its principal constituent parts, it is not affected by
atmospheric water or air; but, as its parts have but comparatively
little cohesion, and are usually separated in a considerable degree by
minute fissures, they are more liable to be broken down and
crumbled by mechanical powers, than those of the rocks belonging
to the first class. In districts where the fundamental rock is
limestone, the layers of loose original soil or subsoil are thin, and
filled with numerous fragments. As the soil arising from the
disintegration of limestone contains a great proportion of calcareous
matter, it is neither favourable to the growth of plants in general, nor
to that of the greater number of vegetables which are the object of
cultivation. Soil of this kind is too hot, dry and stony; hence the
reason why districts, in which pure limestone rocks predominate, are
often sterile. The case is different, however, where a portion of clay
enters as an ingredient into the composition of calcareous rocks, for
here the soil is usually very productive; or, where rocks of a different
nature alternate with masses of pure limestone, having a greater
capability than it of contributing to the formation of productive soil.
When water, containing carbonic acid, passes through limestone
rocks, it dissolves portions of it, and deposits them in other places,
by which the decomposition of the limestone and the formation of
loose earth may be in some measure accelerated.
To the third class belong chalk and gypsum; which, in so far as
regards their decomposition by chemical means, are of a similar
nature with compact limestone; but possessing a much slighter
cohesion of parts, are more liable to be broken down by mechanical
means. Water also dissolves gypsum, and thus assists in its
disintegration. The soil arising from these rocks resembles that
produced by compact limestone, which explains the want of fertility,
observable in certain gypseous tracts of the North of Germany, and
in the chalk districts of France. The fertility which we see in certain
places where chalk is the fundamental rock, as in the Isle of Wight,
Island of Rugen, &c. is to be attributed as well to argillaceous and
marly strata alternating with the chalk, as to the greater humidity of
the atmosphere, by which the dryness and heat of the soil are
diminished.
In the fourth class we place certain rocks, composed of different
minerals, but compact in appearance, which, although they resist
mechanical disintegration, are yet subject to chemical action, and
are, by means of it, converted into a loose, compound productive
soil. Of this kind are basalt, and some other rocks very nearly allied
to it.
To the fifth class we refer those rocks which have a crystalline,
granular, or slaty texture. The mutual adhesion of the heterogeneous
parts, of which they consist, being, in general, inconsiderable, they
are easily broken down by mechanical means, and thus contribute in
a high degree to the formation of productive soil. The felspar
contained in these rocks, on account of the chemical decomposition
which it readily undergoes, has a great effect not only upon the
quantity, but also the fertility of the soil produced. The quartz, on
the contrary, as well as the mica and hornblende, long resist
chemical decomposition; they are, however, useful in this respect,
that the argillaceous soil arising from the felspar, has its tenacity
diminished; and is consequently rendered better adapted for
vegetation, by being intermixed with them. Granite and gneiss, of all
truly granular crystalline rocks, afford the deepest and most fertile
soil, aptly compounded of different substances, sufficiently loose in
its aggregation, and capable of retaining the necessary moisture.
Soil arising from the disintegration of granite is unfavourable to
vegetation only, where the rock abounds much in quartz, and where
the superfluous water cannot run off, and so gives rise to marshes,
which produce only vegetables of inferior quality; of which we have
examples in the granite districts of Aberdeen. In such places as
these, peat is easily generated, which, although of great use, is yet
much less advantageous than wood. Syenite, which abounds much
in hornblende, is inferior to granite, with respect to the production of
fertile soil; and primitive greenstone, which resists disintegration and
decomposition in the highest degree, occupies the last place in this
class. In the series of slaty crystalline rocks, mica-slate is next to
gneiss: but on account of the small proportion of felspar which
enters into its composition, it does not afford so productive a soil.
In the sixth class may be placed the slaty rocks, whether simple,
or intimately compounded, which do not readily undergo chemical
decomposition, but which easily separate at their natural fissures,
and are mechanically resolved into an earthy mass, forming a paste
with water, circumstances which are observed chiefly in clay-slate, a
rock of much importance in the formation of productive soil, usually
passing into a clayey sort of earth.
To the seventh class belong the conglomerated rocks, whose parts
indeed undergo very little, if any, chemical change, but are easily
separated by mechanical means, and are thus converted into a
gravelly, sandy, or earthy mass. Of this kind are greywacke, old red
sandstone, and sandstones of various kinds. Much diversity is
exhibited by these rocks, with regard to the facility with which they
undergo disintegration, as well as the nature of the soil arising from
them; circumstances which chiefly depend upon the nature of the
cement, and its relation to the parts cemented. The disintegration of
these rocks is the more easily effected that the cement is abundant,
and less intimately connected with the other parts, that is, the more
they depart from a crystalline nature; on which account greywacke is
less easily converted into soil, than the common varieties of
sandstone. By the decomposition of greywacke, a loose and fertile
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy