9372
9372
https://ebookgate.com/product/invent-your-own-computer-games-
with-python-3rd-edition-al-sweigart/
https://ebookgate.com/product/invent-your-own-computer-games-
with-python-4th-edition-al-sweigart/
https://ebookgate.com/product/opencv-computer-vision-with-
python-1st-edition-howse/
https://ebookgate.com/product/make-games-with-python-1st-edition-
edition-sean-m-tracey/
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/
https://ebookgate.com/product/learning-opencv-3-computer-vision-
with-python-2nd-edition-joe-minichino/
https://ebookgate.com/product/on-your-own-how-to-start-your-own-
cpa-firm-second-edition-poe/
https://ebookgate.com/product/computational-physics-problem-
solving-with-python-3rd-edition-paez/
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
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.
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
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.
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.
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.
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
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
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
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.
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:
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.
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:
2. Type Python in the search box in the top-right corner of the window.
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
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.
You do not need to type the “9.” on the left side, or the one space immediately following it. Just
type it like this:
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:
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.
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.
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.
When used in this way, +, -, *, and / are called operators. Operators tell Python what to do with
the numbers surrounding them.
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
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
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.
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
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.
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
>>> 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
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:
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':
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:
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:
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.
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.
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.
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.
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.
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.
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
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
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.
2. print('Hello world!')
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.
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.
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
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.
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.
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
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.
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.)
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:
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:
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.
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.
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 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:
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.
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
>>> 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.
>>> 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
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.
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
A while statement always has a : colon after the condition. Statements that end with a colon
expect a new block on the next line.
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.
1. Action of Torrents.
2. Action of Rivers.
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.
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