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

Impractical Python Projects Playful Programming Activities to Make You Smarter 1st Edition Lee Vaughan download

Impractical Python Projects by Lee Vaughan offers a collection of playful programming activities designed to enhance coding skills in Python. The book includes various projects ranging from silly name generators to simulations of alien volcanoes, catering to both beginners and non-specialists. It aims to make programming accessible and enjoyable while providing practical coding experience.

Uploaded by

belalozakestm
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)
41 views

Impractical Python Projects Playful Programming Activities to Make You Smarter 1st Edition Lee Vaughan download

Impractical Python Projects by Lee Vaughan offers a collection of playful programming activities designed to enhance coding skills in Python. The book includes various projects ranging from silly name generators to simulations of alien volcanoes, catering to both beginners and non-specialists. It aims to make programming accessible and enjoyable while providing practical coding experience.

Uploaded by

belalozakestm
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/ 58

Impractical Python Projects Playful Programming

Activities to Make You Smarter 1st Edition Lee


Vaughan download

https://textbookfull.com/product/impractical-python-projects-
playful-programming-activities-to-make-you-smarter-1st-edition-
lee-vaughan/

Download more ebook from https://textbookfull.com


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

Impractical Python Projects Playful Programming


Activities to Make You Smarter 1st Edition Lee Vaughan

https://textbookfull.com/product/impractical-python-projects-
playful-programming-activities-to-make-you-smarter-1st-edition-
lee-vaughan-2/

Python for kids a playful introduction to programming


1st Edition Briggs

https://textbookfull.com/product/python-for-kids-a-playful-
introduction-to-programming-1st-edition-briggs/

Real World Python A Hacker s Guide to Solving Problems


with Code 1st Edition Lee Vaughan

https://textbookfull.com/product/real-world-python-a-hacker-s-
guide-to-solving-problems-with-code-1st-edition-lee-vaughan/

Python Projects for Beginners: A Ten-Week Bootcamp


Approach to Python Programming Milliken

https://textbookfull.com/product/python-projects-for-beginners-a-
ten-week-bootcamp-approach-to-python-programming-milliken/
Make Your Own Python Text Adventure: A Guide to
Learning Programming 1st Edition Phillip Johnson

https://textbookfull.com/product/make-your-own-python-text-
adventure-a-guide-to-learning-programming-1st-edition-phillip-
johnson/

Efficient R Programming A Practical Guide to Smarter


Programming 1st Edition Colin Gillespie

https://textbookfull.com/product/efficient-r-programming-a-
practical-guide-to-smarter-programming-1st-edition-colin-
gillespie/

JavaScript for Kids A Playful Introduction to


Programming 1st Edition Nick Morgan

https://textbookfull.com/product/javascript-for-kids-a-playful-
introduction-to-programming-1st-edition-nick-morgan/

Bite Size Python An Introduction to Python Programming


1st Edition April Speight

https://textbookfull.com/product/bite-size-python-an-
introduction-to-python-programming-1st-edition-april-speight/

Investing Between the Lines How to Make Smarter


Decisions By Decoding CEO Communications 1st Edition
L.J. Rittenhouse

https://textbookfull.com/product/investing-between-the-lines-how-
to-make-smarter-decisions-by-decoding-ceo-communications-1st-
edition-l-j-rittenhouse/
IMPRACTICAL PYTHON PROJECTS
Playful Programming Activities to Make You
Smarter

by Lee Vaughan

San Francisco
IMPRACTICAL PYTHON PROJECTS. Copyright © 2019 by Lee Vaughan.

All rights reserved. No part of this work may be reproduced or transmitted in any
form or by any means, electronic or mechanical, including photocopying, recording, or
by any information storage or retrieval system, without the prior written permission of
the copyright owner and the publisher.

ISBN-10: 1-59327-890-X
ISBN-13: 978-1-59327-890-8

Publisher: William Pollock


Production Editor: Janelle Ludowise
Cover Illustration: Josh Ellingson
Interior Design: Octopod Studios
Developmental Editor: Zach Lebowski
Technical Reviewers: Jeremy Kun, Michael Contraveos, and Michele Pratusevich
Copyeditor: Rachel Monaghan
Compositor: David Van Ness
Proofreader: Paula L. Fleming
Indexer: Beth Nauman-Montana

The following images are reproduced with permission: Figure 4-1 courtesy of the
Library of Congress; Figure 7-1 created by vecteezy.com; rat silhouette in Figure 7-2
created by vecteezy.com; door image in Figures 11-1, 11-3, 11-4, 11-5, and 11-6 created
by Dooder at Freepik.com; goat and moneybag images in Figures 11-1, 11-4, 11-5, and
11-6 created by Freepik.com; Figures 10-1, 10-7, 13-1, 14-21, and 15-1 from NASA;
satellite images in Figures 14-13 and 14-24 courtesy of www.aha-soft.com/; output in
Figure 12-5 supplied by ifa.com

For information on distribution, translations, or bulk sales, please contact No Starch


Press, Inc. directly:
No Starch Press, Inc.
245 8th Street, San Francisco, CA 94103
phone: 1.415.863.9900; [email protected]
www.nostarch.com

Library of Congress Cataloging-in-Publication Data


Names: Vaughan, Lee, author.
Title: Impractical Python projects : playful programming activities to
make
you smarter / Lee Vaughan.
Description: First edition. | San Francisco : No Starch Press, Inc.,
[2019]
| Includes bibliographical references and index.
Identifiers: LCCN 2018027576 (print) | LCCN 2018029119 (ebook) | ISBN
9781593278915 (epub) | ISBN 1593278918 (epub) | ISBN 9781593278908
(pbk. :
alk. paper) | ISBN 159327890X (pbk. : alk. paper)
Subjects: LCSH: Python (Computer program language)
Classification: LCC QA76.73.P98 (ebook) | LCC QA76.73.P98 V38 2019
(print) |
DDC 005.13/3--dc23
LC record available at https://lccn.loc.gov/2018027576

No Starch Press and the No Starch Press logo are registered trademarks of No Starch
Press, Inc. Other product and company names mentioned herein may be the
trademarks of their respective owners. Rather than use a trademark symbol with every
occurrence of a trademarked name, we are using the names only in an editorial fashion
and to the benefit of the trademark owner, with no intention of infringement of the
trademark.

The information in this book is distributed on an “As Is” basis, without warranty.
While every precaution has been taken in the preparation of this work, neither the
author nor No Starch Press, Inc. shall have any liability to any person or entity with
respect to any loss or damage caused or alleged to be caused directly or indirectly by
the information contained in it.
For the Accidental Programmers, the Dedicated Non-Specialists, the
Dibblers and Dabblers: all the non-professionals who find themselves
writing code every day. May this help you on your way.
About the Author
Lee Vaughan is a geologist with more than 30 years of experience in the
petroleum industry. As the Senior Technical Professional for Geological
Modeling at a major international oil company, he was involved in the
construction and review of computer models; the development, testing,
and commercialization of software; and the training of geoscientists and
engineers. An advocate for nonprogrammers who must use
programming in their careers, he wrote Impractical Python Projects to
help self-learners hone their skills with the Python language.
About the Technical Reviewer
Jeremy Kun graduated with his PhD in mathematics from the
University of Illinois at Chicago. He writes the blog Math ∩
Programming (https://jeremykun.com/) and currently works on datacenter
optimization at Google.
BRIEF CONTENTS
Acknowledgments
Introduction
Chapter 1: Silly Name Generator
Chapter 2: Finding Palingram Spells
Chapter 3: Solving Anagrams
Chapter 4: Decoding American Civil War Ciphers
Chapter 5: Encoding English Civil War Ciphers
Chapter 6: Writing in Invisible Ink
Chapter 7: Breeding Giant Rats with Genetic Algorithms
Chapter 8: Counting Syllables for Haiku Poetry
Chapter 9: Writing Haiku with Markov Chain Analysis
Chapter 10: Are We Alone? Exploring the Fermi Paradox
Chapter 11: The Monty Hall Problem
Chapter 12: Securing Your Nest Egg
Chapter 13: Simulating an Alien Volcano
Chapter 14: Mapping Mars with the Mars Orbiter
Chapter 15: Improving Your Astrophotography with Planet Stacking
Chapter 16: Finding Frauds with Benford’s Law
Appendix: Practice Project Solutions
Index
CONTENTS IN DETAIL
ACKNOWLEDGMENTS

INTRODUCTION
Who This Book Is For
What’s in This Book
Python Version, Platform, and IDE
The Code
Coding Style
Where to Get Help
Onward!

1
SILLY NAME GENERATOR
Project #1: Generating Pseudonyms
Planning and Designing a Project
The Strategy
The Pseudocode
The Code
Using the Python Community’s Style Guide
Checking Your Code with Pylint
Describing Your Code with Docstrings
Checking Your Code Style
Summary
Further Reading
Pseudocode
Style Guides
Third-Party Modules
Practice Projects
Pig Latin
Poor Man’s Bar Chart
Challenge Projects
Poor Foreign Man’s Bar Chart
The Middle
Something Completely Different

2
FINDING PALINGRAM SPELLS
Finding and Opening a Dictionary
Handling Exceptions When Opening Files
Loading the Dictionary File
Project #2: Finding Palindromes
The Strategy and Pseudocode
The Palindrome Code
Project #3: Finding Palingrams
The Strategy and Pseudocode
The Palingrams Code
Palingram Profiling
Palingram Optimization
dnE ehT
Further Reading
Practice Project: Dictionary Cleanup
Challenge Project: Recursive Approach

3
SOLVING ANAGRAMS
Project #4: Finding Single-Word Anagrams
The Strategy and Pseudocode
Anagram-Finder Code
Project #5: Finding Phrase Anagrams
The Strategy and Pseudocode
The Anagram Phrase Code
Project #6: Finding Voldemort: The Gallic Gambit
Project #7: Finding Voldemort: The British Brute-Force
Strategy
The British Brute-Force Code
Summary
Further Reading
Practice Project: Finding Digrams
Challenge Project: Automatic Anagram Generator

4
DECODING AMERICAN CIVIL WAR CIPHERS
Project #8: The Route Cipher
The Strategy
The Pseudocode
The Route Cipher Decryption Code
Hacking the Route Cipher
Adding a User Interface
Project #9: The Rail Fence Cipher
The Strategy
The Rail Fence Cipher Encryption Code
The Rail Fence Cipher Decryption Code
Summary
Further Reading
Practice Projects
Hacking Lincoln
Identifying Cipher Types
Storing a Key as a Dictionary
Automating Possible Keys
Route Transposition Cipher: Brute-Force Attack
Challenge Projects
Route Cipher Encoder
Three-Rail Fence Cipher

5
ENCODING ENGLISH CIVIL WAR CIPHERS
Project #10: The Trevanion Cipher
Strategy and Pseudocode
The Trevanion Cipher Code
Project #11: Writing a Null Cipher
The List Cipher Code
The List Cipher Output
Summary
Further Reading
Practice Projects
Saving Mary
The Colchester Catch

6
WRITING IN INVISIBLE INK
Project #12: Hiding a Vigenère Cipher
The Platform
The Strategy
Creating Invisible Ink
Manipulating Word Documents with python-docx
Downloading the Assets
The Pseudocode
The Code
Importing python-docx, Creating Lists, and Adding a
Letterhead
Formatting and Interleaving the Messages
Adding the Vigenère Cipher
Detecting the Hidden Message
Summary
Further Reading
Practice Project: Checking the Number of Blank Lines
Challenge Project: Using Monospace Font

7
BREEDING GIANT RATS WITH GENETIC ALGORITHMS
Finding the Best of All Possible Solutions
Project #13: Breeding an Army of Super-Rats
Strategy
The Super-Rats Code
Summary
Project #14: Cracking a High-Tech Safe
Strategy
The Safecracker Code
Summary
Further Reading
Challenge Projects
Building a Rat Harem
Creating a More Efficient Safecracker

8
COUNTING SYLLABLES FOR HAIKU POETRY
Japanese Haiku
Project #15: Counting Syllables
The Strategy
Using a Corpus
Installing NLTK
Downloading CMUdict
Counting Sounds Instead of Syllables
Handling Words with Multiple Pronunciations
Managing Missing Words
The Training Corpus
The Missing Words Code
The Count Syllables Code
Prepping, Loading, and Counting
Defining the main() Function
A Program to Check Your Program
Summary
Further Reading
Practice Project: Syllable Counter vs. Dictionary File

9
WRITING HAIKU WITH MARKOV CHAIN ANALYSIS
Project #16: Markov Chain Analysis
The Strategy
Choosing and Discarding Words
Continuing from One Line to Another
The Pseudocode
The Training Corpus
Debugging
Building the Scaffolding
Using the logging Module
The Code
Setting Up
Building Markov Models
Choosing a Random Word
Applying the Markov Models
Generating the Haiku Lines
Writing the User Interface
The Results
Good Haiku
Seed Haiku
Summary
Further Reading
Challenge Projects
New Word Generator
Turing Test
Unbelievable! This Is Unbelievable! Unbelievable!
To Haiku, or Not to Haiku
Markov Music

10
ARE WE ALONE? EXPLORING THE FERMI PARADOX
Project #17: Modeling the Milky Way
The Strategy
Estimating the Number of Civilizations
Selecting Radio Bubble Dimensions
Generating a Formula for the Probability of Detection
The Probability-of-Detection Code
Calculating Probability of Detection for a Range of
Civilizations
Generating a Predictive Formula and Checking the Results
Building the Graphical Model
Scaling the Graphical Model
The Galaxy Simulator Code
Results
Summary
Further Reading
Practice Projects
A Galaxy Far, Far Away
Building a Galactic Empire
A Roundabout Way to Predict Detectability
Challenge Projects
Creating a Barred-Spiral Galaxy
Adding Habitable Zones to Your Galaxy
11
THE MONTY HALL PROBLEM
Monte Carlo Simulation
Project #18: Verify vos Savant
The Strategy
The vos Savant Verification Code
Project #19: The Monty Hall Game
A Brief Introduction to Object-Oriented Programming
The Strategy and Pseudocode
Game Assets
The Monty Hall Game Code
Summary
Further Reading
Practice Project: The Birthday Paradox

12
SECURING YOUR NEST EGG
Project #20: Simulating Retirement Lifetimes
The Strategy
Historical Returns Matter
The Greatest Uncertainty
A Qualitative Way to Present Results
The Pseudocode
Finding Historical Data
The Code
Importing Modules and Defining Functions to Load Data and
Get User Input
Getting the User Input
Checking for Other Erroneous Input
Defining the Monte Carlo Engine
Simulating Each Year in a Case
Calculating the Probability of Ruin
Defining and Calling the main() Function
Using the Simulator
Summary
Further Reading
Challenge Projects
A Picture Is Worth a Thousand Dollars
Mix and Match
Just My Luck!
All the Marbles

13
SIMULATING AN ALIEN VOLCANO
Project #21: The Plumes of Io
A Slice of pygame
The Strategy
Using a Game Sketch to Plan
Planning the Particle Class
The Code
Importing Modules, Initiating pygame, and Defining Colors
Defining the Particle Class
Ejecting a Particle
Updating the Particle and Handling Boundary Conditions
Defining the main() Function
Completing the main() Function
Running the Simulation
Summary
Further Reading
Practice Project: Going the Distance
Challenge Projects
Shock Canopy
The Fountainhead
With a Bullet
14
MAPPING MARS WITH THE MARS ORBITER
Astrodynamics for Gamers
The Law of Universal Gravity
Kepler’s Laws of Planetary Motion
Orbital Mechanics
Project #22: The Mars Orbiter Game
The Strategy
Game Assets
The Code
Importing and Building a Color Table
Defining the Satellite Class Initialization Method
Setting the Satellite’s Initial Position, Speed, Fuel, and Sound
Firing Thrusters and Checking for Player Input
Locating the Satellite
Rotating the Satellite and Drawing Its Orbit
Updating the Satellite Object
Defining the Planet Class Initialization Method
Rotating the Planet
Defining the gravity() and update() Methods
Calculating Eccentricity
Defining Functions to Make Labels
Mapping Soil Moisture
Casting a Shadow
Defining the main() Function
Instantiating Objects, Setting Up Orbit Verification, Mapping,
and Timekeeping
Starting the Game Loop and Playing Sounds
Applying Gravity, Calculating Eccentricity, and Handling
Failure
Rewarding Success and Updating and Drawing Sprites
Displaying Instructions and Telemetry and Casting a Shadow
Summary
Challenge Projects
Game Title Screen
Smart Gauges
Radio Blackout
Scoring
Strategy Guide
Aerobraking
Intruder Alert!
Over the Top

15
IMPROVING YOUR ASTROPHOTOGRAPHY WITH PLANET
STACKING
Project #23: Stacking Jupiter
The pillow Module
Working with Files and Folders
Directory Paths
The Shell Utilities Module
The Video
The Strategy
The Code
The Cropping and Scaling Code
The Stacking Code
The Enhancing Code
Summary
Further Reading
Challenge Project: Vanishing Act

16
FINDING FRAUDS WITH BENFORD’S LAW
Project #24: Benford’s Law of Leading Digits
Applying Benford’s Law
Performing the Chi-Square Test
The Dataset
The Strategy
The Code
Importing Modules and Loading Data
Counting First Digits
Getting the Expected Counts
Determining Goodness of Fit
Defining the Bar Chart Function
Completing the Bar Chart Function
Defining and Running the main() Function
Summary
Further Reading
Practice Project: Beating Benford
Challenge Projects
Benfording the Battlegrounds
While No One Was Looking

APPENDIX
PRACTICE PROJECT SOLUTIONS
Chapter 1: Silly Name Generator
Chapter 2: Finding Palingram Spells
Chapter 3: Solving Anagrams
Chapter 4: Decoding American Civil War Ciphers
Chapter 5: Encoding English Civil War Ciphers
Chapter 6: Writing in Invisible Ink
Chapter 8: Counting Syllables for Haiku Poetry
Chapter 10: Are We Alone? Exploring the Fermi Paradox
Chapter 11: The Monty Hall Problem
Chapter 13: Simulating an Alien Volcano
Chapter 16: Finding Frauds with Benford’s Law
INDEX
ACKNOWLEDGMENTS

Writing a book is a family affair, and I couldn’t have succeeded without


the support of both my real family and my surrogate family at No
Starch Press. First, thanks to my wife, Hannah, and daughters, Sarah
and Lora, for their understanding, patience, and endless editing support.
At No Starch, thanks to Bill Pollock and Tyler Ortman for accepting
my proposal; Zach Lebowski for making sense of what I was trying to
say; Janelle Ludowise for a highly professional job of production
editing; Rachel Monaghan and Paula Fleming for taking on the difficult
job of copyediting and proofing a technical book; David Van Ness for
composition; and Serena Yang and Josh Ellingson for the awesome
cover design. Thanks also to my technical reviewers, Jeremy Kun,
Michael Contraveos, and Michele Pratusevich, for significantly
improving the book with invaluable suggestions and corrections.
External to No Starch, Sarah Vaughan, Eric Evenchick, Xiao-Hui
Wu, Brooks Clark, Brian Proett, Brent Francis, and Glenn Krum
provided significant technical support.
Finally, thanks to Mark Nathern for introducing me to Python, and
to Guido van Rossum for inventing the thing in the first place!
INTRODUCTION

Welcome to Impractical Python Projects! Here, you’ll use the Python


programming language to explore Mars, Jupiter, and the farthest
reaches of the galaxy; the souls of poets; the world of high finance; the
underworld of espionage and vote tampering; the trickery of game
shows; and more. You’ll use techniques such as Markov chain analysis to
write haiku, Monte Carlo simulation to model financial markets, image
stacking to improve your astrophotography, and genetic algorithms to
breed an army of gigantic rats, all while gaining experience with
modules like pygame, Pylint, pydocstyle, tkinter, python-docx, matplotlib,
and pillow. And most of all, you’ll have fun.

Who This Book Is For


You can think of this as your second Python book. It’s designed to
follow and complement either a complete beginner’s book or an
introductory class. You’ll be able to continue self-training using a
project-based approach, without wasting your money or shelf space on a
thorough rehashing of concepts you’ve already learned. But don’t worry,
I won’t leave you hanging; all the code is annotated and explained.
These projects are for anyone who wants to use programming to
conduct experiments, test theories, simulate nature, or just have fun.
This includes people who use programming as part of their jobs (like
scientists and engineers) but who aren’t programmers per se, as well as
those I call the “determined non-specialists”—dilettantes and dabblers
who enjoy programming problems as a fun pastime. If you’ve wanted to
toy with the concepts presented here but found starting potentially
complicated projects from scratch too daunting or time-consuming, this
book is for you.

What’s in This Book


As you work through the projects, you’ll increase your knowledge of
useful Python libraries and modules; learn more shortcuts, built-in
functions, and helpful techniques; and practice designing, testing, and
optimizing programs. Additionally, you’ll be able to relate what you’re
doing to real-world applications, datasets, and issues.
To quote Ralph Waldo Emerson, “Nothing great was ever achieved
without enthusiasm.” This includes the learning experience. The
ultimate goal of this book is to spark your imagination and lead you to
develop interesting projects of your own. Don’t worry if they seem too
ambitious at first; a little diligence and a lot of googling can work
miracles—and faster than you think.
The following is an overview of the chapters in this book. You don’t
have to work through them sequentially, but the easiest projects are at
the beginning, and I explain new concepts, modules, and techniques
more thoroughly when they’re first introduced.
Chapter 1: Silly Name Generator This warm-up project
introduces the Python PEP 8 and PEP 257 style guides as well as
the Pylint and pydocstyle modules, which analyze your code’s
conformance to these guidelines. The end product is a goofy-name
generator inspired by the USA Network TV show Psych.
Chapter 2: Finding Palingram Spells Learn how to profile your
code while saving DC Comics sorceress Zatanna from a painful
death. Search online dictionaries for the magical palingrams that
Zatanna needs to beat a time-reversing villain.
Chapter 3: Solving Anagrams Write a program that helps a user
create a phrase anagram from their name; for example, Clint
Eastwood yields old west action. Then help Tom Marvolo Riddle derive
his anagram, “I am Lord Voldemort,” using linguistic sieves.
Chapter 4: Decoding American Civil War Ciphers Investigate
and crack one of the most successful military ciphers in history, the
Union route cipher. Then help spies on both sides send and decode
secret messages using the zig-zagging rail fence cipher.
Chapter 5: Encoding English Civil War Ciphers Read a message
hidden in plain sight by decoding a null cipher from the English
Civil War. Then save the head of Mary, Queen of Scots, by
designing and implementing code to accomplish the more difficult
task of writing a null cipher.
Chapter 6: Writing in Invisible Ink Help a corporate mole betray
Sherlock Holmes’s dad and evade detection with invisible electronic
ink. This chapter is based on an episode of the CBS television show
Elementary.
Chapter 7: Breeding Giant Rats with Genetic Algorithms Use
genetic algorithms—inspired by Darwinian evolution—to breed a
race of super-rats the size of female bullmastiffs. Then help James
Bond crack a safe with 10 billion possible combinations in the blink
of an eye.
Chapter 8: Counting Syllables for Haiku Poetry Teach your
computer to count syllables in English as a prelude to writing
Japanese poetry, or haiku, in the next chapter.
Chapter 9: Writing Haiku with Markov Chain Analysis Teach
your computer to write haiku by combining the syllable-counting
module from Chapter 8 with Markov chain analysis and a training
corpus of several hundred ancient and modern haiku.
Chapter 10: Are We Alone? Exploring the Fermi Paradox
Investigate the absence of alien radio signals using Drake’s equation,
the dimensions of the Milky Way galaxy, and assumptions about the
size of detectable “emissions bubbles.” Learn and use the popular
tkinter module to build a graphical display of the galaxy and Earth’s
own radio bubble.
Chapter 11: The Monty Hall Problem Help the world’s smartest
woman win the Monty Hall problem argument. Then use object-
oriented programming (OOP) to build a version of Monty’s famous
game with a fun graphical interface.
Chapter 12: Securing Your Nest Egg Plan your (or your parents’)
secure retirement using a Monte Carlo–based financial simulation.
Chapter 13: Simulating an Alien Volcano Use pygame to simulate a
volcanic eruption on Io, one of Jupiter's moons.
Chapter 14: Mapping Mars with the Mars Orbiter Build a
gravity-based arcade game and nudge a satellite into a circular
mapping orbit without running out of fuel or burning up in the
atmosphere. Display readouts of key parameters, track orbital paths,
add the planet’s shadow, and spin Mars slowly on its axis, all while
learning orbital mechanics!
Chapter 15: Improving Your Astrophotography with Planet
Stacking Reveal Jupiter’s cloud bands and Great Red Spot by
optically stacking poor-quality video images using the Python
imaging library. Learn how to work with files, folders, and directory
paths using the built-in os and shutil modules.
Chapter 16: Finding Frauds with Benford’s Law Use Benford’s
law to investigate vote tampering in the 2016 presidential election.
Use matplotlib to summarize the results in a chart.

Each chapter ends with at least one Practice Project or Challenge


Project. Each Practice Project comes with a solution. That doesn’t mean
it’s the best solution—you may come up with a better one on your own,
so don’t peek ahead!
With the Challenge Projects, however, you’re truly on your own.
When Cortez invaded Mexico in 1519, he burned his caravels so that
his conquistadors would realize there was no going back; they would
have to face the Aztecs with grim and unwavering determination. Thus,
the expression “burn your boats” has come to represent
wholeheartedness or full commitment to a task. This is how you should
face the Challenge Projects—as if your boat were burned—and if you
do, you’re likely to learn more from these exercises than from any other
part of the book!

Python Version, Platform, and IDE


I constructed each of the projects in this book with Python v3.5 in a
Microsoft Windows 10 environment. If you’re using a different
operating system, no problem: I suggest compatible modules for other
platforms, where appropriate.
The code examples and screen captures in this book are from either
the Python IDLE text editor or the interactive shell. IDLE stands for
integrated development and learning environment. It’s an integrated
development environment (IDE) with an L added so that the acronym
references Eric Idle of Monty Python fame. The interactive shell, also
called the interpreter, is a window that lets you immediately execute
commands and test code without needing to create a file.
IDLE has numerous drawbacks, such as the lack of a line-number
column, but it is free and bundled with Python, so everyone has access
to it. You are welcome to use whichever IDE you wish. There are many
choices available online, such as Geany (pronounced genie), PyCharm,
and PyScripter. Geany works with a wide range of operating systems,
including Unix, macOS, and Windows. PyCharm works with Linux,
Windows, and macOS. PyScripter works with Windows. For an
extensive listing of available Python development tools and compatible
platforms, visit https://wiki.python.org/moin/DevelopmentTools/.

The Code
Every line of code is provided for each project in this book, and I
recommend you enter it by hand whenever possible. A college professor
once told me that we “learn through our hands,” and I have to agree
that keying in code forces you to pay maximum attention to what’s
going on.
But if you want to complete a project quickly or you accidentally
delete all your work, you can download all of the code, including
solutions to the Practice Projects, from
https://www.nostarch.com/impracticalpython/.

Coding Style
This book is about problem solving and beginner-level fun, so the code
may deviate at times from best practices and peak efficiency.
Occasionally, you may use list comprehension or a special operator, but
for the most part, you’ll focus on simple, approachable code that’s easy
to learn.
Keeping things simple is important for the programming
nonprogrammers who read this book. Much of their code may be
“Kleenex code”—used once or twice for a specific purpose and then
thrown away. This is the type of code that might be shared with
colleagues, or thrust upon them during staff changes, so it should be
easy to pick up and understand.
All of the main project code is annotated and explained in a stand-
alone manner, and it generally follows the style recommendations from
Python Enhancement Proposal 8, otherwise known as PEP 8. Details on
PEP 8, and software to help you honor these guidelines, are in Chapter
1.

Where to Get Help


Taking on a programming challenge can be, well, challenging. Coding
isn’t always something that you can intuitively figure out—even with a
language as friendly as Python. Throughout the following chapters, I
Other documents randomly have
different content
Government, in which his colleagues had never concurred, and to
which the Queen had never given her sanction. He thought,
therefore, that he could not without degrading the Crown, advise her
Majesty longer to retain Lord Palmerston in the Foreign department,
and he had accordingly advised her to request his resignation, which
she had done. In continuing his remarks Lord John expressed his
belief that the President of France had acted under a belief that the
course he had taken was the one best calculated to insure the
welfare of his country; and proceeded to censure the course of the
English press toward Louis Napoleon, as calculated to excite the
animosity of the French nation, and perhaps to involve the two
countries in war. Lord Palmerston replied in a very moderate tone,
substantially admitting the truth of Lord John's statements, though
denying the justice of his inferences. He repelled the intimation that
he had abandoned the principles he had always maintained—that he
had become the advocate of absolute power, or in favor of the
abolition of Constitutional governments. He concurred in what Lord
John had said of the relations that ought to exist between the
Foreign Secretary and the Crown, and said he had done nothing
inconsistent with them. In regard to the deputation he had received,
he admitted that he had been surprised into a false position. His
delay in answering the letters of Lord John Russell had been entirely
owing to the great pressure of business; and his expressions of
opinion concerning Louis Napoleon were unofficial and in
conversation. Other members of the cabinet had expressed the
same opinions, and under circumstances quite as objectionable,
certainly, as those under which his own conversation was held. Lord
Palmerston rehearsed the outlines of the policy he had pursued in
managing the foreign relations of Great Britain, and concluded by
saying that, on quitting office, he left the character and reputation of
England unsullied, and standing high among the nations of the
world.——In the House of Lords the debates following the reading of
the Queen's speech, had greater incidental than direct interest. The
Earl of Derby took occasion to speak in very strong terms of what he
termed "the injudicious and unjustifiable language of a large portion
of the English press upon the French government." He insisted that
it was the duty of the press to maintain the same tone of
moderation in discussing public affairs which is required of public
men; and he styled it worse than folly for the press in one breath to
provoke a French invasion, and in the next to proclaim the
unpreparedness of the English people to meet it. He was followed by
Earl Grey, who expressed his hearty concurrence in what he had said
of the press, as did also Lord Brougham. The London journals, and
among them pre-eminently the Times and the Examiner, have taken
up the challenge thus thrown down, and have vindicated the press
from the censures of the Lords in some of the ablest writing of the
day.

On the 9th, Lord John Russell introduced his new Reform Bill. Its
provisions may be very briefly stated. The £10 franchise was to be
reduced to £5; the £50 county franchise gives way to one of £20;
that of copyholders and long leaseholders is to be reduced from £10
to £5; and a new class of voters is to be created out of those who,
resident in either county or borough, pay direct taxes to the amount
of 40 shillings. In 67 boroughs additions are proposed to the
electoral boundaries; the property qualification is to be abolished,
and the oaths of members to be put in such a form as to create no
invidious distinctions. A member taking office under the crown
vacates his seat; but if he merely changes it, he may retain his
representative capacity. The Premier made a speech upon the
subject, over an hour in length, and remarkably free from feeling of
any sort. The main objections urged to the bill are that it does not
concede the ballot, that it does not remedy the evils of unequal
representation, and that the changes it does make in the existing
law are of very little importance. Notice has been given of an
intention to move amendments to the bill which would remedy these
defects.——On the 19th, Lord Naas proposed a resolution severely
censuring the Earl of Clarendon's employment of the World
newspaper to support the government, as being "of a nature to
weaken the authority of the executive, and to reflect discredit on the
administration of public affairs." The Earl was defended warmly by
Lords Russell and Palmerston, both of whom urged that, irregular as
the proceeding might have been, it was of trifling consequence
compared with his lordship's eminent services to the country. The
resolution was rejected 229 to 137.——On the 16th, Lord John
Russell introduced a bill for the establishment of a local militia force.
He gave a sketch of the recent history of the military organization of
England, and set forth the reasons which, in his judgment, rendered
it important that some more effectual provision should be made for
the defense of the country against possible hostilities. The general
provisions of the bill were that persons of the age of 20 and 21
years should be subject to being balloted for as militia men—that
one-fifth of the whole number should be chosen—and that they
should be drilled for 14 or 28 days each year. The entire force thus
raised, he thought, would be about 70,000 the first year, 100,000
the second, and 130,000 after that; the forces could not be taken
out of their own counties, without their consent, except in case of
invasion or danger. The subject was very slightly discussed at that
time, but came up again on the 20th, when Lord John Russell again
spoke in support of the bill. Lord Palmerston expressed his entire
concurrence in the principle of the bill, but moved as an
amendment, to strike out the word local from the title, in order to
make the title correspond with the character of the bill itself. Lord
John Russell said he could not understand the object of such a
motion, and that he should oppose it. After some further debate the
amendment was put and carried, ayes 136, noes 125, showing a
majority against the Ministry of 11. Lord John Russell expressed
great surprise at the vote, and said that he should hold office no
longer. The resignation of the Ministry under such circumstances
created a good deal of surprise. In the course of three or four days a
new cabinet was formed under the leadership of the Earl of Derby—
late Lord Stanley—which is thoroughly Protectionist in its sentiments.
The Earl is Prime Minister; Mr. Disraeli is Chancellor of the Exchequer
and leader in the House of Commons; Mr. G. F. Young is Vice
President of the Board of Trade; Duke of Northumberland, first Lord
of the Admiralty; Lord John Manners, Commissioner of Woods and
Forests; Sir F. Thesiger, Attorney General; Earl of Eglintoun, Lord
Lieutenant of Ireland; Duke of Montrose, Lord Steward; Lord
Stanley, Under Secretary for Foreign Affairs. It is supposed that the
new Ministry will break ground at once against the corn-law policy
established by Sir Robert Peel, hostility to which is the only bond of
union among its members; and the universal belief is that the new
administration will fail to be sustained by the country on that
question.

One of the earliest topics to which the attention of the Earl of


Granville, Lord Palmerston's immediate successor, was called, was
the degree of protection which England should afford to political
refugees from other countries. In reply to representations on this
subject from the Austrian Government, Earl Granville, in a dispatch
dated January 13, spoke of the right of asylum which England
always had granted, and could never refuse to political refugees;
and added that the English government would, nevertheless,
consider any intrigues, carried on there against governments with
which they were at peace, as a breach of hospitality, and would not
fail to watch the conduct of suspected refugees, and to prevent
them from abusing the privileges afforded them by English laws.
Prince Schwarzenberg, in reply, expressed satisfaction at the tenor of
these assurances, but said, that until the words of the English
government were followed by deeds, it would be necessary for
Austria to take measures of precaution and protection against the
dangers which the ceaseless machinations of foreign refugees on
English soil created. The Imperial government would be especially
rigid in regard to English travelers, and would, moreover, reserve the
right of taking into consideration ulterior measures, if, unhappily, the
need of them should still make itself felt.——A terrible disaster from
floods occurred in the north of England on the 5th of February.
Several of the factories of the town of Holmfrith, near Huddersfield,
were supplied with water by large reservoirs, in which an immense
body of water had been accumulated. Owing to the heavy rains one
of the largest of them broke its banks, and the water poured
through the town, sweeping houses away in its path and causing an
immense loss of life and property. Over one hundred persons were
drowned. Very great injury had been sustained by other towns in
that vicinity. In the south of Ireland also, especially in the counties of
Limerick and Clare, much property and some lives have been lost by
the swelling of the smaller streams.——The dispatches of Earl Grey
recalling Sir Harry Smith from the government of the Cape, have
been published: they show that his incompetence for the post has
been the real cause of his removal, and that the policy of the
government is to prosecute the war with increased vigor, so as to
reduce the Kaffirs and Hottentots to unconditional submission.——
We mentioned in our Record for March, the repulse of the English
slave squadron while attempting to ascend the river, to the town of
Lagos, on the coast of Africa, contrary to the commands of the chief.
Later advices report the renewal of the attempt, and the overthrow
of the chief's authority, though at a very heavy cost on the part of
the English. The town of Lagos has long been the stronghold of the
slave trade on that part of the coast, and the English have directed
their efforts toward the suppression of the traffic there. The chief of
the town named Kosoko, was actively engaged in the trade himself,
in connection with Portugese and Brazilian dealers. He had obtained
power by expelling a rival named Akitoye, who sought aid against
him in an alliance with the English. When Kosoko, therefore, refused
permission to the English to bring their armed boats to Lagos, the
commander of the squadron concerted an attack upon the town,
with the adherents of the expelled chief. The town was defended
with a good deal of skil and bravery, and the assault upon it lasted
three days, at the end of which time it was found to have been
deserted. The English lost 16 killed and 64 wounded. It is said that
the destruction of this town will do much toward the suppression of
the slave trade.——A new expedition in search of Sir John Franklin
has been resolved upon by the British Government, and Sir Edward
Belcher has been appointed to the command. He will leave England
about the middle of April, with the four ships which composed
Captain Austin's late expedition. His attention will first be directed to
Beechey Island, where Sir John is known to have passed the winter
of 1845-6. The great object of this new expedition is to examine the
upper part of Wellington Strait as far as possible beyond Captain
Penny's northwest advance.
FRANCE.
Political affairs in France remain substantially unchanged. The law
organizing the Legislative body has been published. The Legislature
is to consist of 261 deputies, elected by the people, in the proportion
of one for every 35,000 electors in the first instance, with one more
deputy for every 25,000 beyond that number. Algeria and the
Colonies are not to be represented. All electors are eligible except
public functionaries. Every Frenchman of the age of twenty-one, who
has not forfeited his civil rights, has the vote.——We mentioned in
our last Record the protest of the testamentary executors of Louis
Philippe against the decree of confiscation, issued by the President.
The Princes of Orleans—the Duke de Nemours, and the Prince de
Joinville—have addressed a letter of thanks to the executors, in
which they resent with becoming indignation the insults heaped
upon the memory of their father, which they say are "especially
odious when brought forward by a man who on two different
occasions received proofs of the magnanimity of King Louis Philippe,
and whose family never received any thing from him but benefits."
To the honor of the country which they had always loyally served
and would ever love, they say, "these disgraceful decrees, and their
still more disgraceful preambles, have not dared to appear except
under the régime of a state of siege, and after the suppression of all
the guaranties which protected the liberties of the nation." The
Duchess of Orleans has also addressed the following brief and
indignant protest to the President:—"Monsieur—As I do not
acknowledge your right to plunder my family, neither do I
acknowledge your right to assign to me a dotation in the name of
France. I refuse the dowry.—Helena d'Orleans."——The new Ministry
of Police has been organized by decree. The Minister is to have
attached to his office three directors-general, who are to appoint
inspector-general, special inspectors, and commissaries of police in
the departments. Prominent among the duties of all of these officials
are those of watching and reporting every attempt to influence
public opinion against the government, keeping a close eye on the
press and on publications of every sort—upon theatres, prisons,
schools, and political and commercial associations. They are all to be
under the immediate direction and control of the Minister of Police.
The organization spreads a complete network of precaution over
every form of public opinion in France.——Louis Napoleon gave a
magnificent entertainment to a large number of the English nobility
at Paris, on the 1st of February, at the Elysée—-the whole party
numbering 44. It is stated that after the dinner was over, he took
occasion to complain of the attacks upon him in the English press,
and to say that he should be obliged to exclude them from France.
He also spoke of the rumors that he intended to invade England as
absurd.——Jerome Bonaparte is appointed President of the Senate,
with the petit Luxembourg as his official residence in Paris, the
Palace of Meudon for his country-seat, and a salary of 150,000
francs, besides 800,000 francs for entertaining, a year.——It is stated
that Madame George Sand recently had an interview with the
President, and made very strong representations to him of the
sufferings of the peasantry in the rural districts from the immense
number of arrests that had been made of suspected persons, and
urgently requesting him to grant a general amnesty. The President is
said to have expressed great interest in the subject, but to have
declined any compliance with the request.——The decree for the
regulation of the press has been promulgated. It is almost needless
to say that it destroys every semblance of freedom of the press, and
makes it a mere subservient tool in the hands of the Government. It
consists of four chapters, and the following are their provisions: (1.)
No journal can be published without first obtaining permission of the
Government; nor can any foreign journal be admitted into France
except by the same permission: and any person bringing into France
an unauthorized paper will be liable to a year's imprisonment and to
a fine of 5000 francs. Every publisher must deposit caution-money,
from 15,000 to 50,000 francs, before he can issue a paper, under
heavy penalties. (2.) Stamp duties are imposed upon all journals
whether published in France, or introduced from other countries;
and the authorities are enjoined to seize all publications violating
these regulations. (3.) Every violation of the article of the
Constitution which prohibits Legislative reports, is punishable by fine
of from 1000 to 5000 francs. The publication of false news subjects
to a fine, and if it be of a tendency to disturb the public peace,
imprisonment is added. No account of the proceedings of the Senate
or Council of State, and no report of trials for press offenses, can be
published; and in all affairs, civil, correctional, or criminal, the courts
may forbid the publication of their proceedings. Every editor is
bound to publish official documents, relations, and rectifications
which may be addressed to him by any public authority; if he fail to
do so, he may be fined and his journal seized No one can carry on
the bookseller's trade, or issue or sell engravings, medals, or prints
of any kind, without obtaining permission of the authorities, and
becoming subject to the same restrictions as are imposed upon
journals. (4.) With regard to existing journals, three months are
allowed for them to deposit the caution money required, and to
conform to the other provisions of the new law.——The President, by
decree, has abolished all fête days except the birth-day of the
Emperor, on the ground that their celebration recalls the
remembrance of civil discord; and that the only one observed should
be that which best tends to unite all minds in the common sentiment
of national glory——The Paris correspondent of the London Times
reports that a correspondence of general interest has taken place
between the governments of France and Russia. It is said that the
Czar wrote to his minister in Paris, expressing dissatisfaction at the
adoption by the President of the emblems of the Empire, stating that
he saw in all these movements the preliminaries of the re-
establishment of the Imperial era. While he approved of the coup
d'état which had put an end to republicanism in France, he could
only regard Louis Napoleon as the temporary chief, and could not
approve any attempt to give another and more important character
to his authority. It is said that Louis Napoleon replied to this note,
when it was read to him, by complaining that his intentions had
been misunderstood and misrepresented;—that, in re-establishing
the emblems of the Empire, and in reverting to the constitution of
the year VIII., he only meant to establish a strong authority in his
hands; that the recollections of the Empire constituted his strength,
and invested him with popularity among the masses; that there was
nothing astonishing in the fact of his seeking in the institutions of
the Empire what was certain to re-establish authority in France; that
he had no intention of re-establishing the Empire, or of making
himself Emperor; that he did not want either, for the
accomplishment of the mission to which he had been called; that his
title of President sufficed for him; that he had no reason to trouble
himself about an Imperial dynasty which has no existence; and that
there was no reason for the Emperor Nicholas troubling himself
about it.

The relations of France to Belgium are assuming a character of


considerable interest and importance. The fact that most of the
exiled Frenchmen found refuge in Belgium, excited the fears of the
government that they would thence exert a dangerous influence
upon French affairs. Strong representations were therefore made to
the Belgian authorities, who have adopted every possible means of
satisfying the French government, by suppressing distrusted
journals, exercising strict vigilance over refugees, and ordering many
of them out of the country, or away from Brussels. It is also stated
that the Duke of Bassano, the new French envoy to the Belgian
court, has been authorized to demand from that government the
removal of the monumental lion erected by the British government
to commemorate the battle of Waterloo, and to demolish the other
trophies. The rumors of hostile designs on the part of Louis
Napoleon, have led to the publication of an official denial in the
Moniteur. That article states that the French government has
addressed no demands whatever to foreign powers, excepting
Belgium, where it was necessary, in order to prevent a system of
incessant aggression. It has not armed a single soldier, neither has it
done any thing to awaken the least susceptibility in its neighbors. All
the views of the power in France are bent upon interior
improvements. "It will not depart from its calm demeanor, except on
the day when an attack shall have been made on the national honor
and dignity." The London Morning Chronicle states, as a fact of
considerable historical interest, that, as early as 1849, Louis
Napoleon distinctly solicited General Changamier to join with him in
such a usurpation as he has since achieved, offering to make him
Constable of France, with a million of francs a year and the palace of
the Elysée for a residence; and that he was met by a peremptory
refusal.

SPAIN.
An attempt to assassinate the Queen of Spain was made by a priest
named Martin Marino, on the 2d of February. The Queen was
proceeding along the principal gallery of her palace toward the
grand staircase, intending to go out upon a fête occasion, for which
splendid preparations had been made, when she was approached by
the priest, who kneeled to present a memorial. Her Majesty reached
out her hand to take it, when he suddenly drew a dirk and made a
stab at her side. Her arm, however, partially averted the blow,
though she was severely wounded. She leaned against the wall, and
one of her aids came up just in time to prevent a second blow. The
assassin was arrested and confessed the crime—saying that his
object was to render a service to humanity; and denying that he had
any accomplices. He was tried on the 3d, and sentenced to death by
strangulation. On the 7th, he was executed by the garote vil. He
conducted himself with the most brutal indifference, refusing any of
the usual offices of religion, and abusing all who came near him. The
Queen suffered considerably from the wound, but was convalescent
at the last accounts. Several arrests had been made, of persons
suspected of having been concerned as accomplices with him, but
no evidence was found to implicate any.

CENTRAL AND EASTERN EUROPE.


o events of special importance have occurred in any of the
continental nations. All the governments seem to be more or less
agitated by rumors of differences with England and France, and their
policy is somewhat affected by them. The suspicion of hostile
intentions on the part of Louis Napoleon toward Belgium has enlisted
a good deal of suspicion, and letters from Brussels, dated the 19th
February, state positively that a convention had been entered into,
by which Russia agrees to furnish 100,000 men for the defense of
that territory in case it should be invaded or seriously menaced by
France. Prussia has also promised similar assistance, and the Prince
de Ligne is said to be now in Berlin for the purpose of arranging the
details. These important statements, however, do not seem to be
made on authority sufficient to command full credit.

In Austria, it is said, that Prince Schwartzenberg is preparing a


general statement of the views of Austria concerning the state of
Europe, and an indication of the line of policy which she will pursue.
The mediation of Austria between Sardinia and the Pope has also
been proposed, and amicable relations are again to be established
between the Sardinian and Austrian governments. A new treaty has
been concluded, by which Austria is to supply Russia annually with
large quantities of salt.

In Switzerland the only movements of importance relate to the


demand made by the French government that the Council should
promise hereafter to expel any fugitive who might be designated as
dangerous. The Federal Government, while firmly refusing to enter
into any such engagement, avowed its readiness to take all proper
and necessary precautions against the sojourn of political refugees
in Switzerland becoming a source of disquietude to neighboring
states. An official report on the subject states that in June last there
were but 235 political refugees in the Swiss states, and that they
were all under the strict surveillance of the police. Those who had
taken any active steps likely to compromise the interests of other
states, had been promptly expelled. There was a great deal of public
interest manifested throughout Switzerland concerning the relations
between their country and France, and considerable apprehension
prevailed that their rights and liberties might not always be rigidly
respected.
The government of the Duchy of Holstein was formally transferred by
the Commissaries of Prussia and Austria to the Commissary of
Denmark, Count Reventlow-Criminil, on the 8th of February, in an
official conference held at Kiel.

In both Greece and Turkey there have been changes of Ministry. In


the former country the change has no general importance. In
Turkey, it is significant of reaction. Reschid Pacha, the most liberal
and enlightened minister ever placed at the head of affairs in the
Ottoman empire, has been dismissed, and is succeeded by Raaf
Pacha, a man upward of eighty years of age, who was prime
minister in 1838. The negotiation in regard to the Holy Sepulchre
has been abandoned, and the French minister was to leave
Constantinople forthwith.
Editor's Table.

S cience, it has been said, is essentially unpoetical. It must be


acknowledged, nevertheless, that it not unfrequently furnishes
some of our choicest similes. Homer had, indeed, long ago
compared thought to the lightning; but how much more definite,
and, on this account, more effective, is the kindred simile drawn
from the discovery of the modern electric telegraph. And yet, is
there not here something more than simile? Is not the
communication from soul to soul literally, as well as figuratively tele-
graphic, that is, far-writing, or writing from afar? We hope to interest
our readers by a brief examination of the query we have started.

An identity might, perhaps, be shown in the very medium of


communication, so far as the process has a material medium. There
is no difficulty, and no danger, in admitting that the electric fluid may
be the agent in the cerebral and organic transmission, as well as in
the galvanic battery. But it is mainly in the process itself that we may
trace the striking correspondence between the two modes of
intelligence. The primary element of all thought is a spiritual
emotion. The end of all communication, mediate or immediate, is to
produce the same emotion or feeling in another soul. To this every
other step is subordinate. Even thought is not so much an end, in
itself, as is the spiritual feeling, or exercise of soul corresponding to
it. This spiritual emotion, then, must first be brought under the form
of a conception, or an objective picture, without which it can not be
distinctly read and understood, even by the soul in which it first
exists, much less communicated to another. So far the process is
strikingly the same with that adopted in the telegraphic dispatch.
The soul, by its own spiritual energy, first turns the emotion or
feeling into a thought. It translates the thought from the abstract to
the concrete, from the intuitional to the conceptive. It brings it down
into the soul's chamber of imagery, and imprints it on the brain. In
other words, the message is reduced to writing and given to the
clerk at the station-house, who translates it into telegraphic signals.
The more immediate transmitting power is now set in operation. An
influence is imparted from the brain to the nerves (or wires) of the
vocal organs. It is continued to the lungs, and sets in motion a
current of air. This impinges on the outward atmosphere, and is
carried on through successive undulations until it reaches the other
station for which it was designed. It enters the office-chamber of the
ear, communicates with the other cerebral battery, and then writes
off from the auditory nerve or wire, the signals which, by the other
logical and linguistic faculty, or the clerk at the second station, are
translated into the pictorial symbols understood by all, and thus
written on the second brain. The spiritual inhabitant to whom it is
directed, again translates it, in a reverse order, from the verbal to
the conceptive, from the conceptive to the emotional—the intuition
is spiritually seen—the emotion is felt—and thus the circuit is
completed.

This is substantially the process every time we hold intercourse by


means of speech. The operation is ever imperfect in all, and more
imperfect in some than in others. We make mistakes in translating
our own intuitions and emotions. We make still greater mistakes in
taking off from the wires, and in re-translating the conceptual
language which brings to us the feelings and intuitions of others. But
there is no other way. The author of our spiritual and material
constitution hath literally shut us up to this, and we can not get out
of the limits within which He has confined our intercourse with other
spirits. Clairvoyance boasts of having broken through them, or over
them; but clairvoyance is yet a fact to be established. Even, too, if it
has any claims upon our belief, it will doubtless be found, in the end,
to be only a stenographic shortening of some of the steps, without
being, in reality, any more an immediate action of mind upon mind
than the ordinary process.
Spirit can only communicate with spirit through outward symbols,
and by more or less steps, all of which may be regarded as outward
to the most interior effect. By long familiarity this circuitous chain
assumes to us the appearance of directness. But in truth we never
see each other; we never hear each other; if by the terms be meant
our very self—our very spiritual form, our very spiritual voice. Even
to our human soul may be accommodated without irreverence the
language which Paul applies to the Deity. Even of us it may be said,
although in a far lower sense, "Our invisible things are only
understood by the things that are done," even our temporal power
and humanity. Each soul is shut up in an isolation as perfect, in one
sense, as that which separates the far distant worlds in the universe.
Had there been round each one of us a wall of adamant a thousand
feet in thickness, with only the smallest capillary apertures through
which to carry the wires of telegraphic signals, we could not, as to
the essential action of the spirit, be more secluded than we are at
present. We say the essential, or first action of the soul—for
doubtless there may be various degrees of difficulty or facility in the
modes of mediate communication. But in this more spiritual sense
each one of us exists by himself. We live apart in utter loneliness.
The seclusion of each spirit knows no infraction. Its perfect solitude
has never been invaded by any foreign intrusion.

To one who deeply reflects on the fact to which we have been calling
attention, the first feeling, and a just feeling too, might be one of
pride. The dignity of our nature would seem enhanced by such a
constitution. Each man's "mind is his kingdom," in which he may be
as autocratic as he wills. It makes even the lowest in the scale of
humanity such an absolute sovereign within his own spiritual
boundaries, so perfectly secure, if he please, against all foreign
intervention. It sets in so striking a light what in its physical and
etymological, rather than its moral sense, may be styled the holiness
—the wholeness, hale-ness, or separate integrity of each man's
essential being. It is in this point of view, too, that to every hale
mind the pretensions of clairvoyance must appear so inexpressibly
revolting. We allude to its assumption of having the power of
committing what, for the want of a better name, we can only
characterize as spiritual burglary—in other words, of breaking into
our spiritual house, and taking its seat in the very shrine of the
interior consciousness. What can be more degrading to our human
nature than to admit that any other human power, or human will,
can at any time, and from any motive, even for purposes of the most
frivolous amusement, actually enter this inner sanctuary, turning the
immortal spirit into a paltry show-house, and rudely invading, or
pretending to invade, the soul's essential glory, its sacred and
unapproachable individuality?

There is, however, another aspect of the thought in which it may


give rise to a very different, if not an opposite emotion. There may
be, too, at times, a feeling of the deepest melancholy called out by
that other consideration of our spiritual solitude, of our being so
utterly alone upon the earth—a feeling which has never been set
forth with so much power and, at the same time, truthful simplicity,
as in the touching language of inspiration—"The heart knoweth its
own bitterness, and a stranger meddleth not with its joy." And then,
again, although we would in general shrink from it as a painful
ordeal, there are periods when we long for a more searching
communion with other spirits than can ever be expected from the
most intimate methods of mediate intercourse. There are periods
when we are irresistibly drawn out to say—O that some other soul
were acquainted with us as we think we are acquainted with
ourselves, not only with our fancied virtues and our mere real sins,
as they appear imperfectly manifested by misinterpreted signals
from within, but with our very soul itself. Yes, there is sadness in the
thought that we are so unknown, even to those who would be
thought to know us best—unknown alike in that which makes us
better as in that which makes us worse than we seem;—for we are
all better, and we are all worse than we appear to our fellow-men.

And here, we think, may be found an argument for the existence of


Deity, built on stronger and more assuring ground than is furnished
by any of the ordinary positions of natural theology. It is an
argument derived from one of the most interior wants of our moral
constitution. There is no doubt that in our fallen state a feeling of
pain—at times of intense pain—may connect itself in our minds with
the recognition of the Divine idea; but there is also an element of
happiness, and, if cherished, of the highest and most serious
happiness, in the thought that there is One Great Soul that does
penetrate into our most interior spirituality. There is one Soul that is
ever as intimately present with us as our own consciousness—that
holds communion with us, and with whom we may hold communion,
in a manner impossible for any other. There is One that thinks our
thoughts, and feels our feelings, even as we think them, and as we
feel them, although, along with this, in another manner, too, of its
own, that transcends our thinking "even as the heavens are high
above the earth," and is as far removed from all the imperfections of
our own spiritual exercises. There may seem an inconsistency in this
apparent mingling of the finite and the infinite in the Divine Nature,
but it is the belief of both which unlocks for us the meaning of the
Scriptures, and sheds light over every page of revelation and of
providence. There is a higher Soul that pervades our spiritual entity,
not as an impersonal or pantheistic abstraction, but as the most
distinctly personal of all personalities—not as a mere Law of nature,
but as a Father "who careth for us," as a Guardian "who numbereth
the very hairs of our heads," as a Judge who taketh note of every
thought, and gives importance to all our forgotten sins, while He is,
at the same time, present with, and caring for every other individual
soul in the universe. As in some previous musings of our Editorial
Table, we might have adverted to the Divine physical power as the
ever-present dynamical entity in the seeming vacuities of space, and
binding together the isolated material worlds, so here we may
regard the Higher Spiritual Presence as the true bond of union
among all those isolated souls that fill the spiritual universe. Thus
viewed, the fact of such communion would be the highest truth in
philosophy, as a belief in the reality of its possible consciousness
would be the highest article of faith.
History is Philosophy teaching by Example.
The thought has been deemed so profound as to give rise to some
discussion respecting its origin. As a definition, however, the maxim
is liable to serious objection. It presents, rather, the uses, or the
chief use, of history, than the essential idea. The individual memory
may also be said to be philosophy teaching by example; but then it
becomes only another name for that experience which is but the
application of remembered facts to the guidance of the future life.
So history may be called the World's Memory—the memory of a race
—of a nation—of a collective humanity.

It is in vain, then, for us to say what facts, in themselves, ought to


constitute history. The matter is settled. It is not what any
philosophy, or any theology, or any science of history may deem
worthy of remembrance, but what has actually been thus
remembered, or is now so entering into the common mind as to
form the ground of memory in the future. The parallelism in this
respect between the individual and this national, or common mind, is
striking and complete. The true history of each man is not so much
what he has done, as what he has thought and felt. The thought is
the form of the feeling, and the act merely the outward testimony by
which both are revealed. It is not, therefore, every act, or doing,
which enters into his history—not even those which have formed the
greater part of his constant daily exercise—but simply such as for
any reason have made the deepest impression on the inner man,
and which, therefore, stand out in the records of his memory when
all else has perished. What this chronicles is the man's veritable
history. However important other parts of his conduct may appear
externally, this is his true spiritual life. It is the record, the
imperishable record of that which has reached and stirred the depths
of his soul, while other acts, and other events, have had their
lodgment only in the outward un-emotional existence.
Such memory, or such history, may not be what it ought to have
been; it may not be the measure of accountability. All that we insist
upon is the fact, that, whether right or wrong, it is the true history of
the individual, because it is his real life. But then there are degrees
of memory. It is not always, in all its parts, either present to the
mind, or capable of recall at will. Still, what has once in this manner
truly affected his soul, has by this become a part of it, and can,
therefore, never be lost. Like some old historical record it may be
laid aside for a season, but sooner or later must it come forth, and
claim its place as belonging to that individual personality into which
it enters as a constituent and inseparable portion.

The parallel may be traced to almost any extent. Like the memory of
our earliest years, so is the dawning history of a young world or
nation, except so far as positive revelation has shed its light upon it.
Both are mythical. In other words, facts are remembered, not as
they are in themselves, but as seen through the magnifying and
coloring influence of the emotional medium with which they are ever
afterward associated. Like stars observed through a densely
refracting atmosphere, they stand apart, each in its own seclusion,
and hence they loom upon the vision without any of those mutually
connecting associations that belong to our subsequent thinking.
There is, too, in both cases, the same chronicler—the pure
remembrance, a tradition unaided by any of those outward helps
that are afterward employed. At a later period more regular annals
succeed this mythic handing down of isolated facts. The state has its
formal remembrancer, its συγγραφεύς, or historical arranger of
events in a connected story, and in their mutual relations.
Corresponding to this, then, arises in the individual that orderly habit
of thinking which produces associations, having a similar effect in
causing a stricter union between the outer and inner relations of the
soul.

Again, there are times when the man gets to himself what may be
called an artificial memory. He would change the natural flow of
thought, and determine what he will remember, and what he ought
to remember—forgetting that before he can effectually do this he
must be changed himself in the innermost springs of his being. He
studies mnemonics. He manufactures new laws of association. But
this effort ever fails in the end. Nature will have her way. The old
course of memory will return; and with it the spiritual history of the
man will go on as before.

So, too, the state or nation may have its artificial periods, and its
systems of political mnemonics. The mythical, the epic, the heroic,
and not only these, but the later, yet not less thrilling chronicles of
stirring events that carried with them the whole heart of the national
humanity, give way to statistics, and documents of trade, or tables of
revenue, or in a word, to what are deemed the more important
records of political economy. Here, too, there may be an attempt to
change the course of nature, and make that to be history which
never can be such, except at the expense of some of those
attributes, which, although liable to great and dangerous
perversions, are still the noblest parts of our humanity.

Such artificial records of history may be highly useful in their


connection with the interests of particular classes and occupations.
The time also may come in which they may gather around them an
antiquarian value, blending with some of the more universal
emotions of our common nature. But aside from this, although they
may furnish rich materials for other departments of useful
knowledge, they are not history, simply because they lack that
catholic element, by which alone they enter into the common
memory, and thus become a part of the common national mind.

Some say the world has heretofore been all wrong in the matter.
History has been but a record of wars, of tumultuous national
movements, of theological dogmas, of religious and political
excitements. It has been but the biography of monarchs and royal
families, or a narrative of popular commotions as connected with
them. It has presented us only with names of isolated pre-eminence.
The time has now come when we "must change all that." The daily
pursuits of the masses, and all the statistics of ordinary life—these
ought to have been history, and good writers will henceforth make
them so, not only for our times, but for the periods that are past.
"The history of the world," it has been said, "is yet to be written."
But, alas! for these plausible and philanthropic reforms, there are
two serious obstacles in the way. In the first place, the records of
such matters as they would make the grounds of history are too
scanty and uncertain, because they never have had that catholic
interest which would give them an abiding place in the common
national memory. In the second place, it will be equally difficult to
secure for them such lodgment in the universal thinking of the
present age, or of ages yet to come. Not that the world will always
continue the same, or that there will not be ever new matters of
genuine historical interest. The course of things and thinking may
greatly change. Wars may cease. Monarchy may expire. Even
democracies may become obsolete. Such changes may be for the
better or the worse. Faith may go out. Those religious dogmas and
discussions, which politicians and political economists have regarded
as such useless and troublesome intruders into the province of
history, may lose their hold upon the mind. Still our essential position
remains unchanged. It will not be what the masses severally do but
what moves the masses, not their several occupations and pursuits,
but what has a deep and moving interest for the common national
soul, that will constitute history. The wars of the White and Red
Roses were the true history of England for that period, because they
were the only subjects that could be said to occupy all minds alike.
It was not because the chronicler forgot the masses, and thought
only of the great, but because he wrote for the masses, and for the
masses not only of his own time, but of times to come.

Events may have more or less of a personal connection with


monarchs, but it would not follow from this that the history which
records them is a history alone of kings and statesmen. It is only so
far as they and their acts were the representatives of the national
heart, and the national thought, that they came down in the national
memory, and the national records. The separate ordinary pursuits of
men may, in one sense, occupy more of our ordinary thinking, but
the other or historic interest we recognize as being of a higher, a
more exciting, and even a more absorbing kind, because belonging
to us, and felt by us in common with multitudes of other souls. The
mechanic or farmer may consult books of a professional or statistical
nature, but as history they will be ever unreadable. Even in the
workshop and in the field, although the habitual current of his
thoughts may be upon what would seem to him the nearest, and
therefore the more important concerns of life, these other elements
of history will yet have the greater charm, and occupy a higher place
both in his feelings and his intelligence.

It is what he thinks with others that constitutes the higher life of his
being. Hence the tendency of the popular mind, in all ages, to be
absorbed in the recital of deeds most remote from the daily
associations of ordinary life. Hence the popularity of the rhapsodist,
the minstrel, the chronicler, and, in our own age, of the Magazine
and the Newspaper. Hence, too, in the more free and popular
governments of modern times, the universal devotion to what is
called politics. Why is the farmer more excited by an election than by
the sale of his wheat? Most false as well as unphilosophical is the
view which would ascribe this to any calculating patriotism, to any
utilitarian vigilance, or to what is commonly called an enlightened
self-interest. The mechanic thinks more of politics than of his trade;
for the same reason that led his ancestor to the crusade or the
tournament. Instead of being the offspring of utilitarian views, this
public spirit is often most blindly destructive of the private interest,
and most directly opposed to all the teachings of that political
economy which recognizes its own utilities as alone the true and
rational ends of human action. In a much higher sense, too, is all
this true, when a religious element enters into the common or
catholic feeling.

To illustrate the view we have endeavored to present, let us select


some particular date—say the 5th day of March, in the year of our
Lord one thousand seven hundred and seventy. What was the
history of our own country for that day? What the masses were
doing would be the answer which some of the new school would
promptly make. But even could this be ascertained it would not be
history. On that day the three millions of our land were engaged in
the various avocations connected with their ordinary life and
ordinary interests. On that day, too, there was a particular, and,
perhaps, ascertainable state of agriculture, of the mechanic arts, of
education, &c., such as might furnish the ground of a most valuable
statistical essay. There were also, doubtless, thousands of striking
incidents every where transpiring. But none of these constituted the
then history of our country. This was all taking place in one narrow
street of one single city, away off in one remote corner of our land. A
quarrel had arisen between a few foreign soldiers and a collection of
exasperated citizens, in the course of which some few of the latter
were slain. In this event was centred, for the time, the whole history
of the English colonies in North America, and of what afterward
became the great American nation. Among all the acts and states,
and influences of that day, this alone was history, because it alone,
whether right or not, entered into the universal national memory. It
was thought by all, felt by all, and therefore became, for the time in
which it was so thought and felt, the one common history of all.
Again—on the 19th day of April, 1775, the one fact which afterward
formed the common thought and the common memory, was the
battle of Lexington. On the 4th of July, 1776, it was the Declaration
of American Independence. On the 23d day of September, 1780,
there might have been seen, in a secluded valley of the Hudson,
three rustic militia men busily examining the dress of a British officer.
One of them is in the act of taking a piece of paper from the
prisoner's boot. This, in a most emphatic sense, was American
history for that day; may we not say the history of Europe also, and
of the world. And so in other departments. A single man is standing
before a company of statesmen and ecclesiastics. It is Luther before
the Diet of Worms. This is the one common thought which
represents that momentous period in the records of the Church. The
subject tempts us with further illustrations, but we call to mind that
our Drawer and Easy Chair are waiting impatiently for the delivery of
their contents. It is time, therefore, to exchange the prosings of the
Editor's Table for their more varied, and, as we trust the reader will
judge, more attractive materials.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like