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

Mastering Python Network Automation Tim Peters pdf download

The document is a comprehensive guide titled 'Mastering Python Network Automation' by Tim Peters, focusing on using Python for network automation, container orchestration, and configuration management. It covers essential topics such as setting up a network automation lab, utilizing various Python libraries, and implementing service mesh technologies like Calico and Istio. The guide is aimed at network engineers and DevOps professionals, providing practical examples and code usage permissions for readers.

Uploaded by

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

Mastering Python Network Automation Tim Peters pdf download

The document is a comprehensive guide titled 'Mastering Python Network Automation' by Tim Peters, focusing on using Python for network automation, container orchestration, and configuration management. It covers essential topics such as setting up a network automation lab, utilizing various Python libraries, and implementing service mesh technologies like Calico and Istio. The guide is aimed at network engineers and DevOps professionals, providing practical examples and code usage permissions for readers.

Uploaded by

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

Mastering Python Network Automation Tim Peters

install download

https://ebookmeta.com/product/mastering-python-network-
automation-tim-peters/

Download more ebook from https://ebookmeta.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmeta.com
to discover even more!

Mastering Python Networking Your one stop solution to


using Python for network automation programmability and
DevOps 3rd Edition Eric Chou

https://ebookmeta.com/product/mastering-python-networking-your-
one-stop-solution-to-using-python-for-network-automation-
programmability-and-devops-3rd-edition-eric-chou/

Network Automation using Python 3: An Administrator's


Handbook 1st Edition Jithin Aby Alex

https://ebookmeta.com/product/network-automation-using-
python-3-an-administrators-handbook-1st-edition-jithin-aby-alex/

Introduction to Ansible Network Automation: A Practical


Primer Brendan Choi

https://ebookmeta.com/product/introduction-to-ansible-network-
automation-a-practical-primer-brendan-choi/

Studies in Chinese Literary Genres Cyril Birch (Editor)

https://ebookmeta.com/product/studies-in-chinese-literary-genres-
cyril-birch-editor/
3D and Circuit Integration of MEMS 1st Edition
Masayoshi Esashi

https://ebookmeta.com/product/3d-and-circuit-integration-of-
mems-1st-edition-masayoshi-esashi/

Star Wars Myths Fables George Mann

https://ebookmeta.com/product/star-wars-myths-fables-george-mann/

A Course of Modern Analysis 5th Edition E. T. Whittaker

https://ebookmeta.com/product/a-course-of-modern-analysis-5th-
edition-e-t-whittaker/

Hate Crime in Turkey Implications of Collective Action


Media Representation and Policy Making 1st Edition
Deniz Ünan Göktan

https://ebookmeta.com/product/hate-crime-in-turkey-implications-
of-collective-action-media-representation-and-policy-making-1st-
edition-deniz-unan-goktan/

Beastly Bullies Loved By Three 7 1st Edition Evie Rae

https://ebookmeta.com/product/beastly-bullies-loved-by-
three-7-1st-edition-evie-rae/
Export Control Law and Regulations Handbook A Practical
Guide to Military and Dual Use Goods Trade Restrictions
and Compliance 3rd edition Yann Aubin

https://ebookmeta.com/product/export-control-law-and-regulations-
handbook-a-practical-guide-to-military-and-dual-use-goods-trade-
restrictions-and-compliance-3rd-edition-yann-aubin/
MASTERING PYTHON
NETWORK AUTOMATION
Automating Container Orchestration,
Configuration, and Networking with
Terraform, Calico, HAProxy, and Istio

Tim Peters
Content
Preface
Chapter 1: Python Essentials for Networks
Role of Python in Network Programming
Overview
Factors Benefitting Networking
Learn to use Data Types
Numeric Data Types
Boolean Data Type
Sequence Data Types
Mapping Data Types
Set Data Types
Binary Data Types
Exploring Loops
For Loops
While Loops
Working with Functions
Defining Functions
Calling Functions
Default Arguments
Variable-length Arguments
Lambda Functions
Recursion
Global and Local Variables
Function Arguments
Nested Functions
Summary
Chapter 2: File Handling and Modules in Python
File Handling
Opening and Closing Files
Reading from Files
Writing to Files
Appending to Files
With Statement
Exception Handling:
Utilizing Modules
Creating a Module
Importing a Module
Built-In Modules
Creating Packages
Standard Library Modules
My First Python Script
Summary
Chapter 3: Preparing Network Automation Lab
Components of Network Automation Process
Network Devices
Network Emulator
Python Environment
Automation Scripts
Putting It All Together
Benefits of Network Automation Lab
Install NS3 Network Simulator
System Requirements
Install Required Dependencies
Download NS-3
Install Python
Update System
Install Python
Install pip
Install paramiko, Netmiko and Nornir
Install Virtual Environment
Create Virtual Environment
Activate the Virtual Environment
Install Python Libraries in Virtual Environment
Deactivate the Virtual Environment
Install Visual Studio Code
Download and Install VS Code
Install Python Extension
Configure Python Interpreter
Create Python Project
Write Python Code
Run Python Code
Summary
Chapter 4: Configuring Libraries and Lab Components
Nornir
Architecture of Nornir
Significance of Nornir
Paramiko
Architecture of Paramiko
Significance of Paramiko
Netmiko
Architecture of Netmiko
Significance of Netmiko
PyEZ
Architecture of PyEZ
Significance of PyEZ
Configure nornir, paramiko, netmiko and pyEZ
Installing and Configuring Nornir
Installing and Configuring Paramiko
Installing and Configuring Netmiko
Installing and Configuring PyEZ
Configure Ports
Configuring Ports on Switches
Configuring Ports on Routers
Configure Hosts
Configuring Hosts on Windows
Configuring Hosts on Linux
Configure Servers
Installing Server Operating System
Configuring Network Settings
Installing and Configuring Server Software
Configure Network Encryption
SSL/TLS
IPsec
SSH
VPN
Testing the Network Automation Environment
Test Connectivity between Hosts
Test Port Connectivity
Test SSH Connectivity
Test Network Automation Libraries
Test NS3 Emulator
Test Network Encryption
Summary
Chapter 5: Code, Test & Validate Network Automation
Understanding Network Automation Scripts
Procedure of Network Automation Scripts
Define Variables for Automation Scripts
Install Required Libraries
Import Libraries
Define Variables
Connect to Device
Send Configuration Commands
Close Connection
Create Script to Use Variables
Run the Script
Write Codes using Python Tools
Install Required Libraries and Tools
Import Libraries
Define Inventory
Define Tasks
Define Playbook
Execute the Script
Test and Validate the Script
Testing Network Automation Scripts
Set Up a Test Environment
Create Test Cases
Run the Code
Document Test Results
Debug Errors
Identify the Error or Issue
Review the Code
Use Print Statements
Use a Debugger
Fix the Error or Issue
Validate Network Automation Scripts
Prepare the Production Environment
Deploy Code to Production Environment or Devices
Run the Code on Production Environment or Devices
Verify the Output
Summary
Chapter 6: Automation of Configuration Management
Why Configuration Management?
Need of Configuration Management
Role of Python in Configuration Management
Server Provisioning with Terraform
Set up AWS Credentials
Install Terraform
Define Terraform Configuration
Initialize Terraform
Apply Terraform Configuration
Connect to EC2 Instance
Creating Server
Testing Server
Using Python to Automate System Settings
Import Necessary Modules
Define Timezone
Execute Command to Change Timezone
Verify Setting the Timezone
Using Python to Modify Base Configurations
Using Terraform to Modify Base Configurations
Automating System Identification
Install Terraform Module
Python Script to Retrieve System Information
Using Python to Automate Patches and Updates
Install Necessary Libraries
Check for Available Updates
Upgrade the System
Reboot the System
Schedule Regular Updates
Using Terraform to Roll Patches and Updates
Create Configuration File
Applying Configuration File
Identify Unstable and Non-compliant Configurations
Establish Connection with Device
Retrieve Running Configuration
Search Non-compliant Interfaces
Fixing Non-compliant Configurations
Summary
Chapter 7: Managing Docker and Container Networks
Docker and Containers
Docker & Container Fundmentals
Benefits & Applications
Role of Python in Containerization
Install and Configure Docker
Install Docker
Install Docker Python Module
Create Dockerfile
Build Docker Image
Run Docker Container
Test Docker Container
Using Python to Build Docker Images
Create DockerFile
Install Dependencies
Define Command
Build Docker Image
Run Container
Running Containers
Automate Running of Containers
Install Docker SDK for Python
Import Docker SDK
Connect to Docker Daemon
Define Container Configuration
Create Container
Start the Container
Stop and Remove Containers
Container Network Management
Overview
Managing Container Networks with Docker SDK
Summary
Chapter 8: Orchestrating Container & Workloads
Container Scheduling and Workload Automation
Network Service Disocvery
Understanding etcd
Service Discovery using etcd
Install etcd
Start etcd
Register Services
Discover Services
Automate Service Discovery
Sample Program to Automate Service Discovery
Kubernetes Load Balancers
Exploring HAProxy
Manage Load Balancer Servers using HAProxy
Import Required Libraries
Define API Endpoint URLs
Define Function to Add or Remove Servers
Call Function
Sample Program to Manage Load Balancer Servers
Automate Add/Manage SSL Certificate
Using Cryptography Library to Automate SSL
Step-by-step Illustration of Sample Program
Manage Container Storage
Sample Program
Step-by-step Illustration of Sample Program
Necessity of Container Performance
Why Container Performance?
Container Performance KPIs
Setting Up Container Performance Monitoring
Install the Required Libraries
Import Required Libraries
Connect to Docker API
Get Container List
Pull Performance Metrics
Print Container Metrics
Automated Rolling of Updates
Get Current Deployment Object
Update Deployment Object
Check Status of Deployment Rollout
Clean Up Resources
Summary
Chapter 9: Pod Networking
Pods and Pod Networking
What are Pods?
Pods beyond Containers
Networking in Pods
Setting Up Pod Network
Choose a Pod Network Provider
Install Pod Network Provider
Configure Pod Network
Verify the Pod Network
Exploring Calico
Overview
Characteristics of Calico
Getting Started with Calico
Using Calico to Setup Pod Network
Routing Protocols
Border Gateway Protocol (BGP)
Open Shortest Path First (OSPF)
Intermediate System to Intermediate System (IS-IS)
Routing Information Protocol (RIP)
Exploring Cilium
Key Features of Cilium
Cilium Architecture
Install Cilium
Automation of Network Policies
Overview
Steps for Network Policies Automation
Using Calico to Automate Network Policies
Workload Routing
Need of Workload Routing
Istio
Linkerd
Consul
Summary
Chapter 10: Implementing Service Mesh
Service-to-Service Communication
Remote Procedure Calls (RPCs)
Message-based Communication
Need of Service-to-Service
Rise of Service Mesh
Exploring Istio
Overview
Istio’s Capabilities
Installing Istio
Cluster Traffic
NodePort
LoadBalancer
Ingress
Istio Control Plane
Using Istio to Route Traffic
Metrics, Logs and Traces
Metrics
Logs
Traces
Using Grafana to Collect Metrics
Steps to Collect Metrics
Summary
Preface
With "Mastering Python Network Automation," you can streamline
container orchestration, configuration management, and resilient
networking with Python and its libraries, allowing you to emerge as a
skilled network engineer or a strong DevOps professional.
From the ground up, this guide walks readers through setting up a
network automation lab using the NS3 network simulator and Python
programming. This includes the installation of NS3, as well as python
libraries like nornir, paramiko, netmiko, and PyEZ, as well as the
configuration of ports, hosts, and servers. This book will teach you
the skills to become a proficient automation developer who can test
and fix any bugs in automation scripts. This book examines the
emergence of the service mesh as a solution to the problems
associated with service-to-service communication over time.
This book walks you through automating various container-related
tasks in Python and its libraries, including container orchestration,
service discovery, load balancing, container storage management,
container performance monitoring, and rolling updates. Calico and
Istio are two well-known service mesh tools, and you'll find out how
to set them up and configure them to manage traffic routing,
security, and monitoring.
Additional topics covered in this book include the automation of
network policies, the routing of workloads, and the collection and
monitoring of metrics, logs, and traces. You'll also pick up some tips
and tricks for collecting and visualising Istio metrics with the help of
tools like Grafana.
In this book you will learn how to:
Use of Istio for cluster traffic management, traffic routing,
and service mesh implementation.
Utilizing Cilium and Calico to solve pod networking and
automate network policy and workload routing.
Monitoring and managing Kubernetes clusters with etcd
and HAProxy load balancers and container storage.
Establishing network automation lab with tools like NS3
emulator, Python, Virtual Environment, and VS Code.
Establishing connectivity between hosts, port connectivity,
SSH connectivity, python libraries, NS3, and network
encryption.
GitforGits
Prerequisites
"Mastering Python Network Automation" is an essential guide for
network engineers, DevOps professionals, and developers who want
to streamline container orchestration and resilient networking with
the help of Terraform, Calico, and Istio. Knowing Python and basics
of networking is sufficient to pursue this book.

Codes Usage
Are you in need of some helpful code examples to assist you in your
programming and documentation? Look no further! Our book offers
a wealth of supplemental material, including code examples and
exercises.

Not only is this book here to aid you in getting your job done, but
you have our permission to use the example code in your programs
and documentation. However, please note that if you are
reproducing a significant portion of the code, we do require you to
contact us for permission.

But don't worry, using several chunks of code from this book in your
program or answering a question by citing our book and quoting
example code does not require permission. But if you do choose to
give credit, an attribution typically includes the title, author,
publisher, and ISBN. For example, "Mastering Python Network
Automation by Tim Peters".

If you are unsure whether your intended use of the code examples
falls under fair use or the permissions outlined above, please do not
hesitate to reach out to us at [email protected] .

We are happy to assist and clarify any concerns.


Acknowledgement
Tim Peters expresses his gratitude to all of the other contributors to
Rust and work tirelessly to improve the quality of the programming
language. Tim would want to express his gratitude to the entire
team of GitforGits and Kitten Publishing who helped create a
powerful yet simple book that outperforms coding in a relatively
short period of time. And, lastly to his entire family and friends
extending their support to finish the project at the earliest.
CHAPTER 1: PYTHON
ESSENTIALS FOR
NETWORKS
Role of Python in Network
Programming
Overview
Python is a popular programming language that is widely used in the
field of network programming and network automation. Python's
popularity for network programming stems from its simplicity,
flexibility, and extensive collection of libraries and frameworks that
make it easy to work with network devices and protocols. This
chapter explores the concept of Python's ease of use for network
programming and network automation.
Python is an interpreted language that is easy to learn and use,
making it a popular choice for network programmers and network
engineers. Python's syntax is easy to read and understand, and the
language provides a rich set of tools and libraries that simplify
network programming tasks. For instance, Python's standard library
includes modules for handling networking protocols such as TCP/IP,
UDP, and HTTP, making it easier to work with these protocols in
Python code.

Factors Benefitting Networking


One of the most popular libraries for network programming in
Python is the Socket library. The Socket library provides an interface
for creating network sockets, which are endpoints for network
communication. With the Socket library, Python developers can
create client-server applications, send and receive data over network
connections, and handle network errors and exceptions.
Python's ease of use for network programming is also due to the
availability of third-party libraries and frameworks. For instance, the
Paramiko library is a popular Python library for working with Secure
Shell (SSH) protocols. With Paramiko, Python developers can
establish SSH connections with network devices, execute commands
on remote devices, and transfer files over the network. Similarly, the
Netmiko library is a Python library for working with network devices
such as routers and switches. With Netmiko, Python developers can
automate network device configuration, backup and restore network
configurations, and collect device information.
Another reason why Python is popular for network automation is its
integration with other tools and technologies. For example, Python
can be used with Ansible, a popular IT automation tool, to automate
network tasks such as device configuration and monitoring. Python
can also be used with the Simple Network Management Protocol
(SNMP) to monitor network devices, collect network statistics, and
troubleshoot network issues.
To conclude, Python's ease of use for network programming and
network automation stems from its simplicity, flexibility, and
extensive collection of libraries and frameworks. Python provides an
easy-to-learn syntax, a rich set of tools and libraries for network
programming, and seamless integration with other tools and
technologies. Python's popularity in the field of network
programming and network automation is set to grow as more
organizations adopt automation and seek to streamline their network
operations.
Learn to use Data Types
Python is a dynamically typed language that supports several data
types. A data type is a classification of data that determines the type
of operations that can be performed on it. In this chapter, we will
discuss the different data types supported by Python along with
examples and illustrations.

Numeric Data Types


Python supports various numeric data types such as integers,
floating-point numbers, and complex numbers.

Integers
An integer is a whole number, either positive or negative, without a
decimal point. In Python, integers are represented by the int class.
For example, 5, -10, and 0 are all integers.

x=5
y = -10
print(x, y)
Output:
5 -10
Floating-Point Numbers
A floating-point number is a number that has a decimal point. In
Python, floating-point numbers are represented by the float class.
For example, 3.14 and -2.5 are floating-point numbers.

x = 3.14
y = -2.5
print(x, y)
Output:
3.14 -2.5
Complex Numbers
A complex number is a number that has both a real and imaginary
part. In Python, complex numbers are represented by the complex
class. For example, 3 + 4j is a complex number where 3 is the real
part and 4j is the imaginary part.

x = 3 + 4j
y = -2 - 3j
print(x, y)
Output:
(3+4j) (-2-3j)

Boolean Data Type


A boolean data type is a data type that can have one of two possible
values: True or False. In Python, boolean values are represented by
the bool class. Boolean values are used in conditional statements
and loops to control program flow.

x = True
y = False
print(x, y)
Output:
True False

Sequence Data Types


Python supports several sequence data types such as strings, lists,
tuples, and range objects.

Strings
A string is a sequence of characters. In Python, strings are
represented by the str class. Strings can be enclosed in single quotes
('...') or double quotes ("...") or triple quotes ('''...''' or """...""").
x = 'Hello'
y = "World"
print(x, y)
Output:
Hello World
Lists
A list is a collection of items that are ordered and changeable. In
Python, lists are represented by the list class. Lists can contain any
data type, including other lists.

x = [1, 2, 3, 'four', 5.5]


y = ['apple', 'banana', 'cherry']
print(x, y)
Output:
[1, 2, 3, 'four', 5.5] ['apple', 'banana', 'cherry']
Tuples
A tuple is a collection of items that are ordered and immutable. In
Python, tuples are represented by the tuple class. Tuples can contain
any data type, including other tuples.

x = (1, 2, 3, 'four', 5.5)


y = ('apple', 'banana', 'cherry')
print(x, y)
Output:
(1, 2, 3, 'four', 5.5) ('apple', 'banana', 'cherry')
Range Objects
A range object is an immutable sequence of numbers. In Python,
range objects are created using the range() function. Range objects
are commonly used in loops to execute a set of instructions a certain
number of times.

x = range(0, 10)
for i in x:
print(i)
Output:
0
1
2
3
4
5
6
7
8
9

Mapping Data Types


Python supports a mapping data type called a dictionary.

Dictionaries
A dictionary is an unordered collection of key-value pairs. In Python,
dictionaries are represented by the dict class. Dictionaries are used
to store and retrieve data based on a key rather than an index.

x = {'name': 'John', 'age': 25, 'city': 'New York'}


y = {1: 'one', 2: 'two', 3: 'three'}
print(x, y)
Output:
{'name': 'John', 'age': 25, 'city': 'New York'} {1:
'one', 2: 'two', 3: 'three'}

Set Data Types


Python supports a set data type.

Sets
A set is an unordered collection of unique elements. In Python, sets
are represented by the set class. Sets are used to perform
mathematical set operations such as union, intersection, and
difference.

x = {1, 2, 3, 4, 5}
y = {4, 5, 6, 7, 8}
print(x, y)
Output:
{1, 2, 3, 4, 5} {4, 5, 6, 7, 8}

Binary Data Types


Python supports two binary data types, bytes and bytearray.

Bytes
A bytes object is an immutable sequence of bytes. In Python, bytes
objects are represented by the bytes class.

x = b'Hello'
y = b'\x48\x65\x6c\x6c\x6f'
print(x, y)
Output:
b'Hello' b'Hello'
Bytearray
A bytearray object is a mutable sequence of bytes. In Python,
bytearray objects are represented by the bytearray class.

x = bytearray(b'Hello')
x[0] = 72
print(x)
Output:
bytearray(b'Hello')
Overall, Python supports various data types such as numeric,
boolean, sequence, mapping, set, and binary data types.
Understanding these data types and their characteristics is essential
to write efficient and effective Python programs.
Exploring Loops
Loops in Python are used to execute a set of instructions repeatedly.
There are two types of loops in Python: for loops and while loops. In
this tutorial, we will discuss both types of loops with practical
examples.

For Loops
For loops are used to iterate over a sequence (such as a list, tuple,
or string) or other iterable objects (such as a dictionary or a file).
The syntax of the for loop is as follows:

for variable in sequence:


# Code to be executed
The for loop first initializes the variable with the first value in the
sequence. Then, it executes the code block until the last value in the
sequence is reached.

Example#1: Looping through a list


fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Example#2: Looping through a string
name = 'John'
for character in name:
print(character)
Output:
J
o
h
n
Example#3: Looping through a dictionary
person = {'name': 'John', 'age': 25}
for key, value in person.items():
print(key, value)
Output:
name John
age 25

While Loops
While loops are used to execute a set of instructions repeatedly as
long as a certain condition is true. The syntax of the while loop is as
follows:

while condition:
# Code to be executed
The while loop first checks the condition. If the condition is true, it
executes the code block. Then, it checks the condition again and
continues until the condition becomes false.

Example#1: Looping until a condition is met


count = 0
while count < 5:
print(count)
count += 1
Output:
0
1
2
3
4
Example#2: Looping until a user enters a valid input
valid_input = False
while not valid_input:
user_input = input('Enter a number: ')
if user_input.isdigit():
print('You entered:', user_input)
valid_input = True
else:
print('Invalid input, please try again')
Output:
Enter a number: abc
Invalid input, please try again
Enter a number: 123
You entered: 123
Example#3: Looping until a user decides to quit
while True:
user_input = input('Enter a number or type "quit"
to exit: ')
if user_input == 'quit':
break
elif user_input.isdigit():
print('You entered:', user_input)
else:
print('Invalid input, please try again')
Output:
Enter a number or type "quit" to exit: abc
Invalid input, please try again
Enter a number or type "quit" to exit: 123
You entered: 123
Enter a number or type "quit" to exit: quit
Overall, loops in Python are essential for executing a set of
instructions repeatedly. The for loop is used to iterate over a
sequence or iterable object, while the while loop is used to execute a
set of instructions repeatedly as long as a certain condition is true.
Understanding loops and their syntax is essential for writing efficient
and effective Python programs.

Working with Functions


Functions in Python are reusable blocks of code that perform a
specific task. They are used to reduce code duplication and to make
code easier to read and maintain. In this tutorial, we will discuss the
basics of functions in Python with practical examples.

Defining Functions
The syntax for defining a function in Python is as follows:
def function_name(parameters):
# Code to be executed
return return_value
The function definition starts with the def keyword, followed by the
name of the function, and a set of parentheses that may or may not
contain parameters. The code to be executed by the function is
indented and followed by an optional return statement that specifies
the value to be returned by the function.

Example#1: A simple function that adds two


numbers
def add_numbers(a, b):
result = a + b
return result
Example#2: A function that prints a greeting
message
def say_hello(name):
print(f'Hello, {name}!')

Calling Functions
To call a function in Python, you simply write the name of the
function followed by a set of parentheses that may or may not
contain arguments.

Example#1: Calling the add_numbers function


result = add_numbers(2, 3)
print(result)
Output:
5
Example#2: Calling the say_hello function
say_hello('John')
Output:
Hello, John!

Default Arguments
In Python, you can define default values for function parameters. If
a value is not passed for a parameter, the default value is used
instead.

Example#1: A function with default arguments


def say_hello(name='World'):
print(f'Hello, {name}!')
Example#2: Calling the say_hello function with
default arguments
say_hello()
say_hello('John')
Output:
Hello, World!
Hello, John!

Variable-length Arguments
In Python, you can define functions that accept a variable number of
arguments. There are two ways to define variable-length arguments:
using the *args syntax to pass a variable number of positional
arguments, or using the **kwargs syntax to pass a variable number
of keyword arguments.

Example#1: A function with variable-length


positional arguments
def print_args(*args):
for arg in args:
print(arg)
Example#2: Calling the print_args function with
variable-length positional arguments
print_args(1, 2, 3)
Output:
1
2
3
Example#3: A function with variable-length keyword
arguments
def print_kwargs(**kwargs):
for key, value in kwargs.items():
print(key, value)
Example#4: Calling the print_kwargs function with
variable-length keyword arguments
print_kwargs(name='John', age=25)
Output:
name John
age 25

Lambda Functions
Lambda functions, also known as anonymous functions, are small,
one-line functions that can be defined without a name. They are
useful for writing quick and simple functions that are only used once.

Example#1: A lambda function that doubles a


number
double = lambda x: x * 2
result = double(3)
print(result)
Output:
6
Example#2: A lambda function that sorts a list of
tuples by the second element
students = [('John', 25), ('Mary', 23), ('Tom', 27)]
students.sort(key=lambda x: x[1])
print(students)
Output:
[('Mary', 23), ('John', 25), ('Tom', 27)]

Recursion
In Python, you can define functions that call themselves. These
functions are called recursive functions, and they are useful for
solving problems that can be broken down into smaller subproblems.

Example#1: A recursive function that calculates the


factorial of a number
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
Example#2: Calling the factorial function
result = factorial(5)
print(result)
Output:
120

Global and Local Variables


In Python, variables defined inside a function are local to that
function and cannot be accessed outside of it. Variables defined
outside of a function are global and can be accessed anywhere in
the program.
Example#1: A function that modifies a global
variable
count = 0
def increment_count():
global count
count += 1
increment_count()
increment_count()
increment_count()
print(count)
Output:
3
Example#2: A function that uses a local variable
def square(x):
result = x ** 2
return result
print(square(5))
Output:
25

Function Arguments
In Python, function arguments can be passed by reference or by
value. When an argument is passed by reference, any changes made
to the argument inside the function are reflected outside the
function. When an argument is passed by value, any changes made
to the argument inside the function are not reflected outside the
function.

Example#1: A function that modifies a list passed by


reference
def add_to_list(numbers, x):
numbers.append(x)
my_list = [1, 2, 3]
add_to_list(my_list, 4)
print(my_list)
Output:
[1, 2, 3, 4]
Example#2: A function that does not modify an
integer passed by value
def square(x):
x = x ** 2
return x
number = 5
square(number)
print(number)
Output:
5

Nested Functions
In Python, you can define functions inside other functions. These
functions are called nested functions, and they are useful for
organizing code and limiting the scope of variables.

Example#1: A function that defines a nested function


def outer_function():
def inner_function():
print('This is the inner function')
inner_function()
outer_function()
Output:
This is the inner function
Example#2: A function that returns a nested function
def outer_function():
def inner_function():
print('This is the inner function')
return inner_function
function = outer_function()
function()
Output:
This is the inner function
Overall, functions are an essential part of Python programming. They
allow us to write reusable code, organize our programs, and solve
problems more efficiently. Understanding the basics of functions is
crucial for any Python developer, and the examples provided in this
tutorial should help you get started.
Summary
In this chapter, we covered a wide range of topics related to Python
programming. We started by discussing the basics of Python,
including its history, features, and use cases. Python is a popular
high-level programming language that is used for a wide range of
tasks, including web development, data analysis, machine learning,
and more. It is known for its simplicity, readability, and flexibility.
We then covered the fundamental concepts of Python, such as
variables, data types, operators, and control structures. Variables are
used to store data, while data types define the kind of data that can
be stored. Operators are used to perform operations on data, while
control structures, such as if-else statements and loops, are used to
control the flow of a program.
CHAPTER 2: FILE
HANDLING AND MODULES
IN PYTHON
File Handling
File handling is an important aspect of programming, and it refers to
the various operations that can be performed on files such as
reading from, writing to, and modifying files. In Python, you can
perform file handling operations using the built-in file handling
functions.
There are three main file handling modes in Python: read, write, and
append. In the read mode, you can read data from a file. In the
write mode, you can create a new file or overwrite an existing file
with new data. In the append mode, you can add new data to an
existing file.

Opening and Closing Files


To perform file handling operations, you need to open a file first. You
can do this using the open() function, which takes two arguments:
the name of the file and the mode in which you want to open the
file.

Example#1: Opening a file in read mode


file = open('example.txt', 'r')
Example#2: Opening a file in write mode
file = open('example.txt', 'w')
Once you have finished performing operations on the file, you should
close the file using the close() function.

Example#3: Closing a file


file.close()

Reading from Files


In Python, you can read data from files using the read() function.
This function reads the entire file and returns the contents of the file
as a string.

Example#1: Reading from a file


file = open('example.txt', 'r')
contents = file.read()
print(contents)
file.close()
Output:
This is an example file.
It contains some text.
You can also read data from a file line by line using the readline()
function.

Example#2: Reading from a file line by line


file = open('example.txt', 'r')
line = file.readline()
while line != '':
print(line)
line = file.readline()
file.close()
Output:
This is an example file.
It contains some text.

Writing to Files
In Python, you can write data to files using the write() function. This
function writes data to a file and returns the number of characters
written to the file.

Example#1: Writing to a file


file = open('example.txt', 'w')
file.write('This is a new line.\n')
file.write('This is another new line.\n')
file.close()
Example#2: Writing to a file using a list of strings
lines = ['This is a new line.\n', 'This is another new
line.\n']
file = open('example.txt', 'w')
file.writelines(lines)
file.close()
Both examples produce the same output:
This is a new line.
This is another new line.

Appending to Files
In Python, you can append data to a file using the append()
function. This function adds data to the end of a file without
overwriting any existing data.

Example: Appending to a file


file = open('example.txt', 'a')
file.write('This is a third line.\n')
file.close()
Output:
This is a new line.
This is another new line.
This is a third line.

With Statement
In Python, you can use the with statement to open a file and
automatically close it when you are finished performing operations
on the file. This is a safer and more efficient way of working with
files, as it ensures that the file is properly closed even if an error
occurs.

Example#1: Using the with statement to read from a


file
with open('example.txt', 'r') as file:
contents = file.read()
print(contents)
Output:
This is a new line.
This is another new line.
This is a third line.
Example#2: Using the with statement to write to a
file
with open('example.txt', 'w') as file:
file.write('This is a new line.\n')
file.write('This is another new line.\n')
Example#3: Using the with statement to append to a
file
with open('example.txt', 'a') as file:
Another Random Scribd Document
with Unrelated Content
of the skull it is a veritable “missing link” between the batrachia and
reptilia.
The deposit in which I found the Lysorophus was large, containing
thousands of bones and many fine skulls. I am convinced that these
creatures must have hibernated, as many of them were coiled in a
circle in an envelope of hardened mud, and appear to have lain down
never to wake again, each tiny reptile and its nest having been
preserved through all the ages since. The flesh, of course, decayed
soon after death, but by the process of petrification the bones have
been replaced by stone.
Now I have always wanted to explain to a popular audience what this
process of petrification really is. The word petrification should be
dropped from our vocabulary, because it signifies an impossibility. I
remember, as a boy, translating from the Latin a sentence like this
—“His bones became stone,” that is, turned to stone, and one often
hears the expression petrified wood as meaning wood which has
turned to stone; as if there were a process in nature by which one
substance could be turned into another, as the philosopher’s stone
would have changed iron to gold. As a matter of fact, the process
denoted by the word petrification is a process of replacement, not of
transmutation. After the death of these ancient animals and the
decay of their flesh, the water that passed through the bones carried
from the cells of which they were made up the organic contents
which decay, and left in their place deposits of the silica or lime
which it held in solution. The same process continued when the
lagoon bed was elevated above the water as solid rock. The rain-
water, seeping down through rock and fossil alike, left in the bone
cells the mineral matter it was carrying, until they were filled with it.
Then, in process of time, the cell walls are broken down and rebuilt
with silica or lime, and complete fossilization, or petrifaction as it is
called, takes place, as in the case of the fossil bones in the Texas
Permian. I found one specimen of the ladder-spined reptile in which
the bones had been entirely replaced by iron ore, and others made up
of silica.
How long does it take for the mineral matter to replace entirely the
original bones? Ages upon ages. I found on the plains of Kansas a
quarry of elephant bones, from which I took over two hundred teeth
of the Columbian mammoth, some of the larger ones weighing
fourteen pounds each. The broken bones were scattered by the ton
through the matrix. I had them analyzed by Dr. Bailey, the head of
the chemical department of Kansas State University, and he found
only ten per cent. of silicified matter in them; that is, they were only
ten per cent. less rich in phosphate of lime than Armour’s ground
bone meal. This great elephant lived about the time of the Ohio
mastodon, whose bones have been found in such a position as to
indicate that they were buried when Niagara Falls were six miles
below their present site. So if we knew how long it has taken the river
to dig six miles of its big ditch, we could tell how long it has taken to
impregnate the bones of the mammoths in central Kansas with ten
per cent. of silica. How foolish, then, to speak of completely petrified
men, when man had probably not made his appearance in America
at the time of the mammoths.
The rocks of the Texas Permian, as I have already mentioned, are of
red clay filled with concretions of every conceivable form. I
remember once rounding a butte and seeing before me hundreds of
cocoanuts, some whole and others with the brownish shells broken,
showing the white meat within. Absent-mindedly, I sprang from my
horse to feast upon them, to find that they were concretions which
had so closely imitated cocoanuts in shape and color that even I, an
experienced collector, had been momentarily deceived. I knew, too,
of a man who exhibited a collection of large concretions as fossil
Hubbard squashes, and I heard no one doubting that they were all
that their labels claimed.
There are two distinct formations in the Permian of this part of Texas
which give character to the surface of the country. They are as
different as if separated by hundreds of miles. I visited one locality
on Pony Creek, where the red beds lay on top of the gray beds
conformably. Looking to the west, a vast panorama, desolate and
forlorn, of crumbling and denuded bluffs, narrow valleys, and
beetling crags, spread out before me, with the usual red color
dominant everywhere, its monotony relieved only here and there by
the green of some stunted mesquite or patch of grass. To the east
stretched the narrow valley of Pony Creek, whose topography is the
same as that which is so familiar to the residents of eastern Kansas—
a ledge of gray sandstone forming a narrow escarpment on either
side and following the trend of the hills around the ravines, with
grass coming down in gentle swells to meet it or rising to it from the
bottom lands below. The greatest thickness of this sandstone, as I
observed it, was at the head of a narrow gulch near my camp in the
creek bottom, eight miles north of Seymour. I made a section there
and sent samples of the rock to Munich.
I observed this rock under peculiar circumstances, and found that it
solved an interesting problem—that of the water supply of the red
beds. I discovered why the water that falls where these beds only are
exposed runs off soon after a shower, except when caught in natural
or artificial tanks, so that there are no wells or springs in the red
beds, while in the gray beds there are always springs and streams of
running water.
In the September of my 1901 expedition, the heaviest rain since May
fell in torrents for an hour and a half; water lay everywhere on the
surface of the ground. But soon after the rain stopped, it had all
disappeared. My son had discovered across the creek a locality which
was rich in fossil invertebrates, consisting chiefly of straight and
coiled nautilus-like shells; and shortly after the downpour I went
over to set to work collecting them, as Dr. Broili had told me that the
Munich Museum was anxious to secure such a collection. I had not
been long at work before George shouted to me that if I did not want
to swim I would better cross the creek again at once. I followed his
advice so hastily that I left my tools behind. Instantly, a raging,
boiling flood of water covered the rocks in the bed of the creek, over
which I had just crossed dry-shod, and rapidly rose to a height of
eight feet, threatening to submerge my camp.
Looking for a good place to work on my side of the creek, the west, I
found the gulch which I have referred to above. There was a level
floor, formed by the first stratum of the gray beds, extending about
five hundred yards to a ledge of red sandstone, eight feet thick. The
floor was covered with debris washed from the red beds. To my
astonishment, although the surface was dry, a flood of water was
rushing out from under the upper deposits and tumbling in a
miniature waterfall over the gray ledge, which was nearly five feet
thick, into the ravine below.
The rock I found to be composed of four layers of sandstone. The
upper layer, eight inches thick, is composed of fine-grained sand,
which seems to have been ground to an impalpable powder by the
beating of the waves. It is very compact and heavy, and upon
exposure, breaks into rectangular blocks, so perfect in shape that
they can be used for building purposes without being touched by
hammer or chisel. The second layer breaks into large blocks of many
tons’ weight. It is coarser grained than No. 1, and is about twenty
inches thick. It contains a few casts of invertebrate fossils. No. 3 is
twelve inches thick, and is of the same general character as the other
layers. It is literally packed with casts of straight and coiled shells
related to our living nautilus. They are mingled in great confusion. I
believe some of the coiled shells are a foot in diameter. This stratum
is not so compact as the others, and seems to contain more lime. No.
4 is a very solid gray sandstone, eight inches thick, its upper surface
crossed at various angles by elevated ridges of harder material.
From these observations, I am led to the conclusion that the pervious
nature of the red beds, which in the valley of the Wichita are about
three hundred feet thick, allows the water to sink rapidly down
through them until it reaches the impenetrable gray sandstone; from
which it runs off at whatever angle the rocks may be tilted.
CHAPTER XI
CONCLUSION

may begin this closing chapter by mentioning some


other specimens which I have discovered, or which my
sons have, for, thank God, I have raised up a race of
fossil hunters. My second son, Charles M. Sternberg, has
in his person recently fulfilled a dream of forty years of
my own, by discovering the most complete skeleton known of
Professor Marsh’s great toothed-bird, Hesperornis regalis, the Royal
Bird of the West. Unfortunately the skull is missing, otherwise the
nearly complete skeleton is present, and strange to say in normal
position, showing that Dr. F. A. Lucas is right in his restoration of the
Martin specimen as mounted in the National Museum, i. e., as a
loon, a diver instead of a wader, as had been supposed. Our
specimen, however, shows a much longer neck than he had
imagined. Strange indeed was this long-necked diver with its tarsus
at right angles with the body and its powerful web-footed feet. The
body was narrow, a little over four inches wide, with a backbone like
the keel of a boat. The head was ten inches long and armed with
sharp teeth. By keeping the body horizontal it could explore a
column of water six feet high and wide, for any unfortunate fish
within the zone of its activity. I would name this great loon the
Snake-Bird of the Niobrara Group. This specimen I longed to find for
so many years, but was glad to give the credit to my son. It is to be
mounted in the American Museum, and I picture it as it left my
laboratories (Fig. 41).
A word also about that great flying machine of the Cretaceous, the
flying lizard Pteranodon. The skeleton and a very fine skull, which
my son found on Hackberry Creek in 1906, is now mounted in the
British Museum, where my warm friend Dr. A. Smith Woodward
assures me “my specimens are greatly admired.”
Especially have I been fortunate in the Kansas Chalk where my son,
George Fryer, has charge as I write these lines of my twentieth
expedition to those beds, and where he has discovered, and safely
collected and shipped to my laboratory, a great plate of the beautiful
stemless Crinoid Uintacrinus socialis. I sent one section to Professor
M. Boule, of the National Natural History Museum of France, at
Paris. Hundreds of these rare animals are represented in this slab
(Fig. 42).

Fig. 41.—Skeleton of
Hesperornis regalis, the
Giant Toothed-bird of
the Kansas Cretaceous.

Discovered by Charles M.
Sternberg. In American
Museum of Natural
History.
Fig. 42.—Slab of Fossil Crinoids,
Unitacrinus socialis, CONTAINING 160
CALYCES, COVERING FOUR BY SEVEN FEET.

Before these pages go to press, and a year after I began work on


them, I am pleased to be able to tell my readers of two noble
specimens of the Pleistocene Age I have just secured from the plains
of Kansas, that great treasure house of the animals of the past. One is
a majestic Bison, whose head towering above that of his fellows
supported a pair of horn cores measuring six feet from tip to tip.
Along the curve the distance is eight feet. The length of the head is
two feet, the distance between the horns sixteen inches, and from the
center of the orbits, one foot. These splendid horn cores were
uncovered through a fortunate chance. It seems that the Missouri
Pacific Railway, wishing to shorten the creek in the vicinity of Hoxie,
Sheridan County, Kansas, cut a new right-of-way for it across a bend.
Their excavation came within two feet of the bones buried below,
thirty-five feet from the surface of the earth; a friendly freshet
washed them out, and they were discovered by Mr. Frank Lee and
Harley Henderson, of Hoxie, Kansas, June 15, 1902. I was so
fortunate as to secure them in June, 1908. I have filled them with
white shellac, and they are now in condition to be preserved always,
a specimen of the grand old bison of the Pleistocene time. Now their
burial places are three thousand feet nearer the stars than the day
they were buried there, as then the climate was semi-tropical and the
land they roamed over near sea level. The largest pair of horn cores
of a similar bison are preserved in the Cincinnati Natural History
Museum. I copy from one of their records: “The most conspicuous
figure on Plate IX, with immense horn cores, is of the long extinct
broad-fronted bison. This specimen, by far the finest of its kind in
existence, is the greatest prize in the Cincinnati Museum. It was
found in 1869 on Brush Creek, Brown County, Ohio, and through the
efforts of Dr. O. D. Norton it was acquired by the Museum in 1875.”
It gives me great pleasure to show my readers a photograph of the
Kansas form that measures along the curve of the horn cores a foot
and a half more than the famous Ohio specimen. (Fig. 43.)
The great Columbian Elephant, whose jaw I illustrate and have still
in my possession, represents one of the largest, or the largest, of its
kind ever discovered. It was found near the town of Ness City, in
Ness County, Kansas. This giant lived at the same time the great
Bison existed. The last molars have pushed out the worn premolars
and the other two molars, and occupy the entire jaw, having a
grinding surface of 5 × 9 inches. The lower parts of the teeth flare out
like a fan, and measure twenty inches along the top of the roots. The
greatest circumference of the jaws is 26½ inches, and the length 32
inches. Unfortunately, the articulations are worn away, likely by
rolling in some river bed. I secured this noble representative of
American Elephants in June, 1908 (Fig. 44).

Fig. 43.—Skull and Horns of Giant


Bison from Hoxie, Kansas.
Spread of horn cores six feet, one inch;
length along curve, eight feet.

Fig. 44.—Jaw of
Columbian Mammoth,
Elephas columbi.

Discovered in Ness County,


Kansas.

How rich are the strata that compose the earth’s crust only a fossil
hunter can fully realize. Take, for instance, western Kansas, where
the soil beneath our feet is one vast cemetery. I know of a ravine in
Logan County which cuts through four great formations. The lower
levels, of reddish and blue chalk, are filled with the remains of
swimming lizards, with the wonderful Pteranodonts, the most
perfect flying machines ever known, with the toothed bird
Hesperornis, the royal bird of the West, and the fish-bird
Ichthyornis, with fish-like biconcave vertebræ, with fishes small and
great (one form over sixteen feet long), and huge sea-tortoises. Above
are the black shales of the Fort Pierre Cretaceous, thousands of feet
of which are exposed in the bad lands of the upper Missouri. In this
formation the dinosaurs reign supreme. Still higher are the mortar
beds of the Loup Fork Tertiary, where the dominant type changes
from reptiles to mammals. Here, in western Kansas, are found great
numbers of the short-limbed rhinoceros, the large land-turtle,
Testudo orthopygia, several inferior tusked mastodons, the saber-
toothed tiger, the three-toed horse, and a deer only about eighteen
inches high. Higher still, where the grass roots shoot down to feed on
the bones, are the Columbian mammoth, the one-toed horse, like our
species of to-day, a camel like our South American llama, and a bison
far larger than the present species.
The living bison has become almost extinct itself, through the agency
of man. And in the layer of soil which covers all these formations, an
old arrowhead and the crumbling bones of a modern buffalo give an
object lesson in the manner in which these relics of the earlier world
have been preserved. So races of animals, as of men, reach their
highest state of development, retrograde, and give place to other
races, which, living in the same regions, obey the same laws of
progress.
My readers will be pleased, I am sure, to know that just before these
pages go to press I am permitted to tell the story of our last great
hunt in Converse County, Wyoming, during July, August, and
September, 1908, for the largest skull of any known vertebrate, the
great three-horned dinosaur, Triceratops (Fig. 45). Only thirteen
good specimens are known to American museums, 7 of which are in
Yale University Museum, and were collected, I believe, by J. B.
Hatcher. From his field notes Mr. Hatcher has made a map of this
region with crosses to indicate the localities in which skulls have
been found, and 30 are so indicated, but I soon learned that he noted
broken and poor material, as well as the more perfect. With my three
sons I entered the region with enthusiasm on the hunt for one of
these skulls for the British Museum of Natural History.
Fig. 45.—Three-horned Dinosaur,
Triceratops sp.

Restoration by Osborn and Knight.


(From painting in American Museum of
Natural History.)

Fig. 46.—Duck-billed Dinosaur,


Trachodon mirabilis.

Restoration by Osborn and Knight.


(From painting in American Museum of
Natural History.)

I was not employed by that institution, but the agreement was, in


case I secured a good specimen, it was to go to them. I must
acknowledge I felt rather dubious when Dr. Osborn of the American
Museum wrote me that he had had parties in these beds four years,
searching without success for a specimen. For weeks and weeks we
four examined every bit of exposed rock in vain. The rock consisted
of clay and sandstone, the latter both massive and cross-bedded.
Scattered through the great deposits of sandstone were peculiar-
shaped masses of very hard flinty rock, with the same physical
characteristics but with superior hardness. These added strange
forms to the land sculptury. Almost every form the mind can imagine
is found here, from colonies of giant mushrooms, to human faces so
startling as to secure instant attention from the observer. (Figs. 38
and 39.)
A general view of the country from an elevated butte shows many
cone-like mounds, resembling table mountains or even haystacks in
the hazy distance! As the rocks, and even the flint-like material,
readily disintegrate, the creeks that run east into the Cheyenne River
soon radiate like the rays of a fan and deeply scar the narrow divides
into rather deep canyons and narrow ravines. Perhaps a thousand
feet of these fresh-water beds, are laid down in a basin surrounded,
on all sides, by the marine, Fort Pierre, and Fox Hills Cretaceous.
Buck Creek on the south, Cheyenne River on north and east, and a
line through the mouth of Lightning Creek would roughly give the
area of the Laramie Beds we explored. They cover about a thousand
square miles. Here in a country given up entirely to cattle and sheep
ranges with but little of the country fenced, meeting no one but now
and then a lonely sheep herder, my tribe of fossil hunters entered
with bounding hope that we might find some of these famous
dinosaurs.
Here is the border land between the Age of Reptiles and of
Mammals, where mammals first appear as small marsupials. We
secured several teeth of these early mammals. Day after day hoping
against hope we struggled bravely on. Every night the boys gave
answer to my anxious inquiry, What have you found? Nothing. Often
we ran out of palatable food, as we were 65 miles from our base, and
did not always realize how our appetites would be sharpened by our
miles of tramping over the rough hills and ravines. One day in
August, Levi and I started in our one-horse buggy to a camp we had
made near the cedar hills on Schneider Creek. As we passed a small
exposure which I had not gone over, I left him to drive and went over
the beds of reddish shale, the remnant of an old peat-bog. I found the
end of a horn core of Triceratops, and further excavation showed I
had stumbled upon the burial place of one of these rare dinosaurs.
How thankful we were that after so much useless labor we had at last
secured the great object of our hunt. It will prove a beautiful skull
when prepared and mounted under the direction of Dr. Smith
Woodward, Keeper of Geology in the British Museum, where so
many of my discoveries have gone.
Unfortunately the skull was somewhat broken up, and one horn core
is missing. But one side of the face with the large horn core, the back
of the head, and the great posterior crest, seems entire, as well as
large pieces of the other side of the face, and a fine specimen will be
made of it. The total length of the skull is 6 feet 6 inches. The horn
core over the eye is 2 feet 4 inches high; while the circumference in
the middle is 2 feet 8 inches, and it is 15 inches in diameter at the
base.
This was a fully matured animal. As the bony ossicles of the head
armature are co-ossified with the margin and remain as undulations
more or less sharply defined, I am inclined to believe that they are
ornaments. They might assist a little in defense but not offense.
In the mean time my oldest son, George, told me of a region he had
explored a half-mile from our camp near the head of a ravine. Here
we had found a natural cistern full of rain-water, protected from the
sun and cattle by a couple of great concretion-like masses of rock
that covered it. Over the divide where I had found the great skull,
between Boggy and the breaks of Schneider near its mouth in
Cheyenne River, George took Levi and myself. The evening before, I
took the skull in to Lusk for shipment. George pointed out a locality
in which he had found a bone-bed, where we later secured many
teeth of reptiles and fishes, scales of ganoid fishes, bones of small
dinosaurs and crocodiles and the beautifully sculptured shells of
turtles, Trionyx, etc. As there was still a tract of a few hundred yards
to be explored the two boys started to go over it, while I went to the
bone-bed. They soon joined me with the information that they had
found some bones sticking out of a high escarpment of sandstone.
George had found part of the specimen in one place and Levi another
part soon afterwards. I requested George to carefully uncover the
floor on which the bones lay.
While we were taking in our skull, George and Levi ran nearly out of
provisions, and the last day of our absence lived on boiled potatoes.
But in spite of this they had removed a mass of sandstone 12 feet
wide, 15 feet deep, and 10 feet high.
Shall I ever experience such joy as when I stood in the quarry for the
first time, and beheld lying in state the most complete skeleton of an
extinct animal I have ever seen, after forty years of experience as a
collector! The crowning specimen of my life work!
A great duck-billed dinosaur, a relative of Trachodon mirabilis, lay
on its back with front limbs stretched out as if imploring aid, while
the hind limbs in a convulsive effort were drawn up and folded
against the walls of the abdomen. The head lay under the right
shoulder. One theory might be that he had fallen on his back into a
morass, and either broken his neck or had been unable to withdraw
his head from under his body, and had choked to death or drowned.
If this was so the antiseptic character of the peat-bog had preserved
the flesh until, through decay, the contents of the viscera had been
replaced with sand. It lay there with expanded ribs as in life,
wrapped in the impressions of the skin whose beautiful patterns of
octagonal plates marked the fine sandstone above the bones. George
had cut away the rock, leaving enough to give the impression that
even the flesh was replaced by sandstone, giving an exact picture of
him, as he breathed his last some five million of years ago.
A more probable explanation, judging from the shape of the skin
outline which covers the abdomen and is sunken into the body cavity
at least a foot, is that the great creature died in the water. The gases
forming in the body floated the carcass, which was then carried by
currents to the final burial place. When the gases escaped, the skin
collapsed and occupied their place; the carcass sank head first and
feet upward, the former dragging under the shoulder as the body
came to rest on the mud of the bottom.
Quite different indeed is this grand example of extinct life from the
one restored and of which an ideal picture is given in this book (Fig.
46). In the first place, in the specimen we discovered the ribs are
expanded, the great chest cavity measuring 18 inches deep, 24 inches
long, and 30 inches wide. I have no doubt but that with lungs
expanded to their full capacity, he often swam across streams of
water in the tropical jungle in which he lived and died. Further, the
front limbs are not mere arms, that never touched the ground, but
were used in locomotion, as there are toes with hoof-bones, not so
large as those of the hind feet but with the same pattern, and a
divergent thumb, that had a round bone for its ungual. Consequently
the animal could use the front feet as clumsy hands to hold down the
limb of a tree from which he was cropping the tender foliage, or
banners of moss. There were three powerful hoofs on each hind foot.
I do not question, in the presence of this individual, which is
complete excepting the hind feet, tail and left tibia and fibula, but
that the reptile often stood erect, supporting his ponderous weight
while feeding on the leaves of the forest. But when it walked it used
its front limbs as well. A remarkable character are the countless rods
of solid bone that lay along the backbone in the flesh, and appear like
ossified tendons similar to those in the leg of a turkey. Hundreds of
ossified rods appeared, row after row, shaped like Indian beads, as
thick as a lead pencil in the center and beveled off to a small round
point. It has occurred to me that these were for defense; that when a
great Tyrannosaurus rex leaped on his back, his powerful claws
found no lodgment in the flesh on account of these bony rods that
could not be penetrated. Thus our dinosaur would shake off his
enemy.

How wonderful are the works of an Almighty hand! The life that now
is, how small a fraction of the life that has been! Miles of strata,
mountain high, are but the stony sepulchers of the life of the past.
How rapidly has the field expanded which I entered as a pioneer
some forty years ago! In 1867 I knew only five paleontologists—
Agassiz, Lesquereux, Marsh, Cope, and Leidy, with but few followers;
while to-day, Harvard, Princeton, the American, the Carnegie, the
Field, and the National Museums have all built up great collections
of the animals and plants of the past, and the number of publications
on fossil animals has reached an enormous total.
I had the pleasure of attending the meeting of the American
Association for the Advancement of Science that met in the American
Museum in New York at the mid-winter session in 1906. Professor
Osborn introduced me to his splendid Head Preparator, Mr.
Hermann, who has mounted the skeletons of the great
Brontosaurus, Allosaurus, and so many other examples of extinct
animals. Mr. Hermann was requested by the Professor to devote all
his spare time to showing me anything the exhibition and
storerooms contained, prepared or unprepared, and to do all in his
power to make my visit pleasant. I certainly felt at home in that
paradise of ancient animals, many of which I had collected for
science on my own explorations. The magnificent halls in which they
are exhibited are a wonderful tribute paid by the wealth and
intelligence of the citizen of Greater New York to science. How
admirable that Mr. Jesup should use his private fortune as the means
to take from the obscurity of the private dwelling of the late Professor
Cope his great collection, to which I was a contributor for eight years;
and he has placed it under Professor Henry F. Osborn, who with the
assistance of Drs. J. L. Wortman, W. D. Matthew, and others, has
brought order out of chaos and presented in intelligible shape not
only that collection but many others from the fossil fields of the
West.
It is a glorious thought to me that I have lived to see my wildest
dreams come true, that I have seen stately halls rise to be graced with
many of the animals of the past that lived in countless thousands,
and that I have had the pleasure of securing some of the treasures, in
the shape of complete skeletons, which now adorn those halls.
I stood on Columbia Heights that same year of 1906, and my heart
swelled with pride when I looked down on that teeming metropolis
and remembered that I too was a native of the Empire State. Then I
thought of my distant prairie state of Kansas, and gloried in the
thought that the best years of my life had been spent in her ancient
ocean and lake beds, those old cemeteries of creation.
That past life, at least a very small fraction of it, I have sought to
bring before my readers with pen pictures. We have men among us
who can put their conceptions of the ancient inhabitants of land and
sea and air on canvas, and among them are Mr. Charles R. Knight, of
the American Museum, and Mr. Sidney Prentice, of the Carnegie
Museum. Mr. Prentice I knew as a boy, and he has done me the
honor to assure me that my words of counsel have done something at
least toward assisting him to make the choice of following the work
not only of an artist in a paleontological museum, but in portraying
with pencil and brush the ideal pictures of the early denizens of earth
as in life. His success is shown in his restorations of Clidastes. The
results of Mr. Knight’s restorations of many of the extinct animals
brighten my pages, thanks to my friend Professor Henry F. Osborn,
so if I have failed in my pen pictures to take my readers into the
misty past, these brilliant restorations will certainly have the desired
effect.
I cannot hope in this short space to have given more than a passing
glance at the life of a fossil hunter. It has been one of joy to me; I
should not like to have missed making the discoveries I have made,
and I would willingly undergo the same hardships to accomplish the
same results. And if my story does anything to interest people in
fossils, I shall feel that I have not written in vain.
When I requested Professor William K. Gregory of Columbia
University to be the final reader of the manuscript of this book, “The
Life of a Fossil Hunter,” shall I ever forget his kind words? “I hope
you will not feel that you are under any personal obligations
whatever, because this slight service is simply laid upon me by the
necessities of the case, i. e., by the fact that your whole life and work
have placed all paleontologists under lasting obligations to you.”
Surely “my cup runneth over; I have a goodly heritage.” Greater than
their obligations to me, are mine to the men of science who have
described, published, but, above all, have prepared and exhibited the
noble monuments of creative genius which I have been so fortunate
as to discover and make known to the civilized world. My own body
will crumble in dust, my soul return to God who gave it, but the
works of His hands, those animals of other days, will give joy and
pleasure “to generations yet unborn.”

FINIS
INDEX

Adocus, 77
Amphibian, Long-horned, 253
Anderson, A. E., 58
Anseres, Fossil, 160
Aphelops megalodus, 123
Archælurus debilis, 189
Aspidophyllum trilobatum, 19

Bad Lands, Expedition to, 61–98


Bailey, Dr., 260
Baird, Letter from Spencer F., 20
Basin, John Day, 173, 190
Batrachians, Fossil, 161
Beds, Laramie, 272
Benton, Fort, 79, 97, 98
Betulites westii, 30
Bison, Giant Fossil, 267, 268
Blackbird, Fossil, 161
Bourne, W. O., 58
Broili, Dr. F., 112, 234, 253, 254, 255, 258
Bromfield, Corporal, 226, 227
Brontosaurus, 78
Brouse, A. W., 101, 121, 141
Button, Mr. Lee, 157, 168, 169

Camel, Fossil, 187, 188, 242


Carboniferous, Upper, 135
Cardicephalus sternbergi, 255
Chalk, Expedition to Kansas, 32–60
Further Work in Kansas, 99–119
Clidastes, 53, 135, 280
tortor, 44
velox, 51, 53
westi, 135
College, Vassar, 53
Condon, Prof., 160, 161
Coots, Fossil, 161
Cope, Prof. E. D., Characteristics of, 45, 69, 74, 75, 83, 84, 89, 90, 91,
92, 93, 95, 239, 242, 243
Expedition to Bad Lands with, 61–89
Horned Dinosaurs Discovered by, 87
Letter from, 33, 142
News of Death of, 241
Speech Given by, 45
Memory and Imagination of, 75, 76
Wit of, 98, 99
Cormorants, Fossil, 160
Coulée, Grand, 175, 204
County, Converse, 270
Gove, 34, 118
Logan, 35, 38, 50, 54, 57, 60
Coyote, 211
Creek, Beaver, 138
Bushy, 234
Butte, 50
Chapman, 101
Coffee, 245, 246, 252
Cottonwood, 273
Deer, 126
Dog, 68, 77, 79, 81, 88
Gray, 250, 253
Hackberry 34, 35, 38, 107, 135, 266
Hay, 60
Indian, 241
Pine, 170
Pony, 261
Prairie Dog, 126, 127
Sappa, 120, 121, 140
Cretaceous, Life of the, 54
Crinoid, Stemless, 266

Davis, Leander, 196, 198, 202, 203


Day, Bill, 173, 178
Dayville, 189
Desert, Expedition to the Oregon, 144–169
Diceratherium nanum, 189
Dimetredon, 217, 256
Dinosaur, 77, 273
Duck-billed, 275
Horned, 87, 88
Three-horned, 270
Diplocaulus, 227, 257
copei, 254, 255
magnicornis, 240, 253, 255
Dissorophus, 242
Dolichorhynchus osborni, 111
Duncan, Mr., 154, 156, 158

Eastman, Dr., 114


Elephant, Columbian, 268
Elephas primigenius, 160
Elotherium humerosum, 186, 187
Enhydrocyon stenocephalus, 189
Eryops, 217, 227, 256
megacephalus, 251

Ficus, 23
Flamingo, Fossil, 161
Flora, Tertiary, 172
Fossils, Formation of, 258–260
Method of Excavating, 41, 42, 88, 109, 110, 130

Galyean, Frank, 230, 231, 232


Gar-pike, 253
Gorge, Picture, 173
Grebes, Fossil, 160
Gregory, Prof. William K., 280
Group, Fort Pierre, 70, 135
Loup Fork, 120
Niobrara, 50, 122
Grouse, Fossil, 161
Gulls, Fossil, 160
Hamman, George, 207, 209
Haploscapha grandis, 108
Hatcher, Prof. J. B., 70, 123, 133, 270
Hayden, Dr., 78, 205
Henry, Major, 229
Hermann, Adam, 58, 278
Heron, Fossil, 161
Hesperornis regalis, 265, 266
Hill, Mr. Russell, 101, 141
Hill, Smoky, 109, 113
Holland, Dr. W. J., 115
Hollick, Dr. A., 21, 22, 26
Horse, Three-toed, 126, 188
Howard, General, 191, 196, 197
Hoxie, 267
Huff, Joe, 170, 177

Ichthyornis, 269
Inoceramus, 135
Isaac, J. C., 47, 48, 61, 65, 74, 79, 80, 81, 83, 86, 93, 94, 98
Island, Cow, 79, 87, 89, 91, 98
Long, 132, 134

Klamath, Fort, 142, 146


Knight, Charles R., 279, 280
Knowlton, Dr. F. H., 24

You might also like