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

Instant Access to Doing Math with Python Use Programming to Explore Algebra Statistics Calculus and More 1st Edition Amit Saha ebook Full Chapters

Statistics

Uploaded by

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

Instant Access to Doing Math with Python Use Programming to Explore Algebra Statistics Calculus and More 1st Edition Amit Saha ebook Full Chapters

Statistics

Uploaded by

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

Download Full Version ebook - Visit ebookmeta.

com

Doing Math with Python Use Programming to Explore


Algebra Statistics Calculus and More 1st Edition
Amit Saha

https://ebookmeta.com/product/doing-math-with-python-use-
programming-to-explore-algebra-statistics-calculus-and-
more-1st-edition-amit-saha/

OR CLICK HERE

DOWLOAD NOW

Discover More Ebook - Explore Now at ebookmeta.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Start reading on any device today!

Essential Math for Data Science: Take Control of Your Data


with Fundamental Calculus, Linear Algebra, Probability,
and Statistics 1st Edition Hadrien Jean
https://ebookmeta.com/product/essential-math-for-data-science-take-
control-of-your-data-with-fundamental-calculus-linear-algebra-
probability-and-statistics-1st-edition-hadrien-jean/
ebookmeta.com

Practical Weak Supervision Doing More with Less Data 1st


Edition Tok Wee Hyong Bahree Amit Filipi Senja

https://ebookmeta.com/product/practical-weak-supervision-doing-more-
with-less-data-1st-edition-tok-wee-hyong-bahree-amit-filipi-senja/

ebookmeta.com

Algebra and Geometry with Python 1st Edition Sergei


Kurgalin

https://ebookmeta.com/product/algebra-and-geometry-with-python-1st-
edition-sergei-kurgalin/

ebookmeta.com

Christmas A Story 1st Edition Zona Gale

https://ebookmeta.com/product/christmas-a-story-1st-edition-zona-gale/

ebookmeta.com
Aircraft Performance: An Engineering Approach, 2nd Edition
Mohammad H Sadraey

https://ebookmeta.com/product/aircraft-performance-an-engineering-
approach-2nd-edition-mohammad-h-sadraey/

ebookmeta.com

Society and Economy in Colonial Connecticut Jackson Turner


Main

https://ebookmeta.com/product/society-and-economy-in-colonial-
connecticut-jackson-turner-main/

ebookmeta.com

UNREDACTED Magazine Issue 003 July 2022 3rd Edition


Unredacted Magazine

https://ebookmeta.com/product/unredacted-magazine-
issue-003-july-2022-3rd-edition-unredacted-magazine/

ebookmeta.com

Outsmart Your Studies How To Study Effectively Hack Your


Memory and Learn Faster William Wadsworth

https://ebookmeta.com/product/outsmart-your-studies-how-to-study-
effectively-hack-your-memory-and-learn-faster-william-wadsworth/

ebookmeta.com

Mathematics and Its History 3rd Edition John Stillwell

https://ebookmeta.com/product/mathematics-and-its-history-3rd-edition-
john-stillwell/

ebookmeta.com
Bought To Carry His Heir Jane Porter

https://ebookmeta.com/product/bought-to-carry-his-heir-jane-porter/

ebookmeta.com
DOING MATH
EXPLORE MATH
WITH CODE

Doing Math with Python shows you how to use • Write programs to find derivatives and integrate
WITH PYTHON
Python to delve into high school–level math topics functions U S E P R O G R A M M I N G T O E X P L O R E A L G E B R A ,
like statistics, geometry, probability, and calculus.
Creative coding challenges and applied examples help S T A T I S T I C S , C A L C U L U S , AND MORE!
You’ll start with simple projects, like a factoring
you see how you can put your new math and coding
program and a quadratic-equation solver, and then
skills into practice. You’ll write an inequality solver, plot
create more complex projects once you’ve gotten
gravity’s effect on how far a bullet will travel, shuffle a
the hang of things. AMIT SAHA
deck of cards, estimate the area of a circle by throwing
Along the way, you’ll discover new ways to explore 100,000 “darts” at a board, explore the relationship
math and gain valuable programming skills that you’ll between the Fibonacci sequence and the golden ratio,
use throughout your study of math and computer and more.
science. Learn how to:
Whether you’re interested in math but have yet to dip
• Describe your data with statistics, and visualize it into programming or you’re a teacher looking to bring
with line graphs, bar charts, and scatter plots programming into the classroom, you’ll find that Python
makes programming easy and practical. Let Python
• Explore set theory and probability with programs for
handle the grunt work while you focus on the math.
coin flips, dicing, and other games of chance
ABOUT THE AUTHOR
• Solve algebra problems using Python’s symbolic math
functions Amit Saha is a software engineer who has worked
for Red Hat and Sun Microsystems. He created and
• Draw geometric shapes and explore fractals like
maintains Fedora Scientific, a Linux distribution for
the Barnsley fern, the Sierpiński triangle, and the
scientific and educational users. He is also the author
Mandelbrot set
of Write Your First Program (Prentice Hall Learning).

COVERS PYTHON 3

T H E F I N E ST I N G E E K E N T E RTA I N M E N T ™
w w w.nostarch.com

$29.95 ($34.95 CDN)


“ I L I E F L AT .”
PYTHON
PROGRAMMING LANGUAGES/
SHELVE IN:

This book uses a durable binding that won’t snap shut.

www.allitebooks.com
Doing Math with Python

www.allitebooks.com
www.allitebooks.com
Doing Math
with Python
Use Programming to
Explore Algebra, Statistics,
Calculus, and More!

b y Amit Sa ha

San Francisco

www.allitebooks.com
Doing Math with Python. Copyright © 2015 by Amit Saha.

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.

Printed in USA

First printing

19 18 17 16 15   1 2 3 4 5 6 7 8 9

ISBN-10: 1-59327-640-0
ISBN-13: 978-1-59327-640-9

Publisher: William Pollock


Production Editor: Riley Hoffman
Cover Illustration: Josh Ellingson
Interior Design: Octopod Studios
Developmental Editors: Seph Kramer and Tyler Ortman
Technical Reviewer: Jeremy Kun
Copyeditor: Julianne Jigour
Compositor: Riley Hoffman
Proofreader: Paula L. Fleming

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: 415.863.9900; [email protected]
www.nostarch.com

Library of Congress Cataloging-in-Publication Data

Saha, Amit, author.


Doing math with Python : use programming to explore algebra, statistics, calculus, and more! / by
Amit Saha.
pages cm
Summary: "Uses the Python programming language as a tool to explore high school-level mathematics
like statistics, geometry, probability, and calculus by writing programs to find derivatives, solve
equations graphically, manipulate algebraic expressions, and examine projectile motion. Covers
programming concepts including using functions, handling user input, and reading and manipulating
data"-- Provided by publisher.
Includes index.
ISBN 978-1-59327-640-9 -- ISBN 1-59327-640-0
1. Mathematics--Study and teaching--Data processing. 2. Python (Computer program language) 3.
Computer programming. I. Title.
QA20.C65S24 2015
510.285'5133--dc23
2015009186

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.

www.allitebooks.com
To Protyusha, for never giving up on me

www.allitebooks.com
www.allitebooks.com
Brief Contents

Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv

Chapter 1: Working with Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Chapter 2: Visualizing Data with Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

Chapter 3: Describing Data with Statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

Chapter 4: Algebra and Symbolic Math with SymPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93

Chapter 5: Playing with Sets and Probability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

Chapter 6: Drawing Geometric Shapes and Fractals . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149

Chapter 7: Solving Calculus Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177

Afterword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209

Appendix A: Software Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213

Appendix B: Overview of Python Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237

www.allitebooks.com
www.allitebooks.com
Conte nt s in De ta il

Acknowledgments xiii

Introduction xv
Who Should Read This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvi
What’s in This Book? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvi
Scripts, Solutions, and Hints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii

1
Working with Numbers 1
Basic Mathematical Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Labels: Attaching Names to Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Different Kinds of Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Working with Fractions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Complex Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Getting User Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Handling Exceptions and Invalid Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Fractions and Complex Numbers as Input . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Writing Programs That Do the Math for You . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Calculating the Factors of an Integer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Generating Multiplication Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Converting Units of Measurement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Finding the Roots of a Quadratic Equation . . . . . . . . . . . . . . . . . . . . . . . . . . 20
What You Learned . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Programming Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
#1: Even-Odd Vending Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
#2: Enhanced Multiplication Table Generator . . . . . . . . . . . . . . . . . . . . . . . . 23
#3: Enhanced Unit Converter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
#4: Fraction Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
#5: Give Exit Power to the User . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

2
Visualizing Data with Graphs 27
Understanding the Cartesian Coordinate Plane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Working with Lists and Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Iterating over a List or Tuple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Creating Graphs with Matplotlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Marking Points on Your Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Graphing the Average Annual Temperature in New York City . . . . . . . . . . . . . 35
Comparing the Monthly Temperature Trends of New York City . . . . . . . . . . . . 38
Customizing Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Saving the Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Plotting with Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Newton’s Law of Universal Gravitation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Projectile Motion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
What You Learned . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Programming Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
#1: How Does the Temperature Vary During the Day? . . . . . . . . . . . . . . . . . . 55
#2: Exploring a Quadratic Function Visually . . . . . . . . . . . . . . . . . . . . . . . . . 55

www.allitebooks.com
#3: Enhanced Projectile Trajectory Comparison Program . . . . . . . . . . . . . . . . 56
#4: Visualizing Your Expenses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
#5: Exploring the Relationship Between
the Fibonacci Sequence and the Golden Ratio . . . . . . . . . . . . . . . . . . . . . 59

3
Describing Data with Statistics 61
Finding the Mean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Finding the Median . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Finding the Mode and Creating a Frequency Table . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Finding the Most Common Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Finding the Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Creating a Frequency Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Measuring the Dispersion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Finding the Range of a Set of Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Finding the Variance and Standard Deviation . . . . . . . . . . . . . . . . . . . . . . . . 72
Calculating the Correlation Between Two Data Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Calculating the Correlation Coefficient . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
High School Grades and Performance on College Admission Tests . . . . . . . . . 78
Scatter Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Reading Data from Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Reading Data from a Text File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Reading Data from a CSV File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
What You Learned . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Programming Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
#1: Better Correlation Coefficient–Finding Program . . . . . . . . . . . . . . . . . . . . 89
#2: Statistics Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
#3: Experiment with Other CSV Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
#4: Finding the Percentile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
#5: Creating a Grouped Frequency Table . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

4
Algebra and Symbolic Math with SymPy 93
Defining Symbols and Symbolic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Working with Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Factorizing and Expanding Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Pretty Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Substituting in Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
Converting Strings to Mathematical Expressions . . . . . . . . . . . . . . . . . . . . . . 103
Solving Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
Solving Quadratic Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Solving for One Variable in Terms of Others . . . . . . . . . . . . . . . . . . . . . . . . 106
Solving a System of Linear Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
Plotting Using SymPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
Plotting Expressions Input by the User . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Plotting Multiple Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
What You Learned . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Programming Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
#1: Factor Finder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
#2: Graphical Equation Solver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
#3: Summing a Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
#4: Solving Single-Variable Inequalities . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

x   Contents in Detail
5
Playing with Sets and Probability 121
What’s a Set? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Set Construction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Subsets, Supersets, and Power Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
Set Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
Probability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
Probability of Event A or Event B . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Probability of Event A and Event B . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
Generating Random Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
Nonuniform Random Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
What You Learned . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Programming Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
#1: Using Venn Diagrams to Visualize Relationships Between Sets . . . . . . . . . 140
#2: Law of Large Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
#3: How Many Tosses Before You Run Out of Money? . . . . . . . . . . . . . . . . . 144
#4: Shuffling a Deck of Cards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
#5: Estimating the Area of a Circle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145

6
Drawing Geometric Shapes and Fractals 149
Drawing Geometric Shapes with Matplotlib’s Patches . . . . . . . . . . . . . . . . . . . . . . . . 150
Drawing a Circle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Creating Animated Figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Animating a Projectile’s Trajectory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
Drawing Fractals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
Transformations of Points in a Plane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
Drawing the Barnsley Fern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
What You Learned . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
Programming Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
#1: Packing Circles into a Square . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
#2: Drawing the Sierpiński Triangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
#3: Exploring Hénon’s Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
#4: Drawing the Mandelbrot Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172

7
Solving Calculus Problems 177
What Is a Function? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
Domain and Range of a Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
An Overview of Common Mathematical Functions . . . . . . . . . . . . . . . . . . . . 178
Assumptions in SymPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Finding the Limit of Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
Continuous Compound Interest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
Instantaneous Rate of Change . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
Finding the Derivative of Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
A Derivative Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
Calculating Partial Derivatives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
Higher-Order Derivatives and Finding the Maxima and Minima . . . . . . . . . . . . . . . . . 188
Finding the Global Maximum Using Gradient Ascent . . . . . . . . . . . . . . . . . . . . . . . . 191
A Generic Program for Gradient Ascent . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
A Word of Warning About the Initial Value . . . . . . . . . . . . . . . . . . . . . . . . 196
The Role of the Step Size and Epsilon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197

Contents in Detail   xi
Finding the Integrals of Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
Probability Density Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
What You Learned . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
Programming Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
#1: Verify the Continuity of a Function at a Point . . . . . . . . . . . . . . . . . . . . . 205
#2: Implement the Gradient Descent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
#3: Area Between Two Curves . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
#4: Finding the Length of a Curve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207

Afterword 209
Things to Explore Next . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
Project Euler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
Python Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
Books . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
Getting Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211

A
Software Installation 213
Microsoft Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
Updating SymPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
Installing matplotlib-venn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
Starting the Python Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
Updating SymPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
Installing matplotlib-venn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
Starting the Python Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
Mac OS X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
Updating SymPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
Installing matplotlib-venn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
Starting the Python Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220

B
Overview of Python Topics 221
if __name__ == '__main__' . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
List Comprehensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
Dictionary Data Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
Multiple Return Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
Specifying Multiple Exception Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
The else Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
Reading Files in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
Reading All the Lines at Once . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
Specifying the Filename as Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
Handling Errors When Reading Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
Reusing Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235

Index 237

xii   Contents in Detail
Ac k n o w l ed g me n t s

I would like to thank everyone at No Starch Press for making this book
possible. From the first emails discussing the book idea with Bill Pollock
and Tyler Ortman, through the rest of the process, everyone there has
been an absolute pleasure to work with. Seph Kramer was amazing with his
technical insights and suggestions and Riley Hoffman was meticulous in
checking and re-checking that everything was correct. It is only fair to say
that without these two fine people, this book wouldn’t have been close to
what it is. Thanks to Jeremy Kun and Otis Chodosh for their insights and
making sure all the math made sense. I would also like to thank the copy-
editor, Julianne Jigour, for her thoroughness.
SymPy forms a core part of many chapters in this book and I would
like to thank everyone on the SymPy mailing list for answering my queries
patiently and reviewing my patches with promptness. I would also like to
thank the matplotlib community for answering and clearing up my doubts.
I would like to thank David Ash for lending me his Macbook, which
helped me when writing the software installation instructions.
I also must thank every writer and thinker who inspired me to write,
from humble web pages to my favorite books.
I n t r o duc t i o n

This book’s goal is to bring together three


topics near to my heart—programming,
math, and science. What does that mean
exactly? Within these pages, we’ll programmati-
cally explore high school–level topics, like manipulating
units of measurement; examining projectile motion;
calculating mean, median, and mode; determining linear correlation;
solving algebraic equations; describing the motion of a simple pendulum;
simulating dice games; creating geometric shapes; and finding the limits,
derivatives, and integrals of functions. These are familiar topics for many,
but instead of using pen and paper, we’ll use our computer to explore them.
We’ll write programs that will take numbers and formulas as input, do
the tedious calculations needed, and then spit out the solution or draw a
graph. Some of these programs are powerful calculators for solving math
problems. They find the solutions to equations, calculate the correlation
between sets of data, and determine the maximum value of a function,
among other tasks. In other programs, we’ll simulate real-life events, such
as projectile motion, a coin toss, or a die roll. Using programs to simulate
such events gives us an easy way to analyze and learn more about them.
You’ll also find topics that would be extremely difficult to explore with-
out programs. For example, drawing fractals by hand is tedious at best and
close to impossible at worst. With a program, all we need to do is run a for
loop with the relevant operation in the body of the loop.
I think you’ll find that this new context for “doing math” makes learn-
ing both programming and math more exciting, fun, and rewarding.

Who Should Read This Book


If you yourself are learning programming, you’ll appreciate how this book
demonstrates ways to solve problems with computers. Likewise, if you teach
such learners, I hope you find this book useful to demonstrate the applica-
tion of programming skills beyond the sometimes abstract world of com-
puter science.
This book assumes the reader knows the absolute basics of Python
programming using Python 3—specifically, what a function is, function
arguments, the concept of a Python class and class objects, and loops.
Appendix B covers some of the other Python topics that are used by the
programs, but this book doesn’t assume knowledge of these additional
topics. If you find yourself needing more background, I recommend
reading Python for Kids by Jason Briggs (No Starch Press, 2013).

What’s in This Book?


This book consists of seven chapters and two appendices. Each chapter
ends with challenges for the reader. I recommend giving these a try, as
there’s much to learn from trying to write your own original programs.
Some of these challenges will ask you to explore new topics, which is a
great way to enhance your learning.

• Chapter 1, Working with Numbers, starts off with basic mathematical


operations and gradually moves on to topics requiring a higher level of
math know-how.
• Chapter 2, Visualizing Data with Graphs, discusses creating graphs
from data sets using the matplotlib library.
• Chapter 3, Describing Data with Statistics, continues the theme of
processing data sets, covering basic statistical concepts—mean, median,
mode, and the linear correlation of variables in a data set. You’ll also
learn to handle data from CSV files, a popular file format for distribut-
ing data sets.

xvi   Introduction
• Chapter 4, Algebra and Symbolic Math with SymPy, introduces sym-
bolic math using the SymPy library. It begins with the basics of repre-
senting and manipulating algebraic expressions before introducing
more complicated matters, such as solving equations.
• Chapter 5, Playing with Sets and Probability, discusses the representa-
tion of mathematical sets and moves on to basic discrete probability.
You’ll also learn to simulate uniform and nonuniform random events.
• Chapter 6, Drawing Geometric Shapes and Fractals, discusses using
matplotlib to draw geometric shapes and fractals and create animated
figures.
• Chapter 7, Solving Calculus Problems, discusses some of the math-
ematical functions available in the Python standard library and SymPy
and then introduces you to solving calculus problems.
• Appendix A, Software Installation, covers installation of Python 3,
matplotlib, and SymPy on Microsoft Windows, Linux, and Mac OS X.
• Appendix B, Overview of Python Topics, discusses several Python
topics that may be helpful for beginners.

Scripts, Solutions, and Hints


This book’s companion site is http://www.nostarch.com/doingmathwithpython/.
Here, you can download all the programs in this book as well as hints
and solutions for the challenges. You’ll also find links to additional math,
science, and Python resources I find useful as well as any corrections or
updates to the book itself.
Software is always changing; a new release of Python, SymPy, or
matplotlib may cause a certain functionality demonstrated in this book to
behave differently. You’ll find any of these changes noted on the website.
I hope this book makes your journey into computer programming
more fun and immediately relevant. Let’s do some math!

Introduction   xvii
1
W o r k i n g w i t h Numbe r s

Let’s take our first steps toward using


Python to explore the world of math and
science. We’ll keep it simple now so you can
get a handle on using Python itself. We’ll start
by performing basic mathematical operations, and
then we’ll write simple programs for manipulating
and understanding numbers. Let’s get started!

Basic Mathematical Operations


The Python interactive shell is going to be our friend in this book. Start the
Python 3 IDLE shell and say “hello” (see Figure 1-1) by typing print('Hello
IDLE') and then pressing enter. (For instructions on how to install Python
and start IDLE, see Appendix A.) IDLE obeys your command and prints
the words back to the screen. Congratulations—you just wrote a program!
When you see the >>> prompt again, IDLE is ready for more instructions.

www.allitebooks.com
Figure 1-1: Python 3 IDLE shell

Python can act like a glorified calculator, doing simple computations.


Just type an expression and Python will evaluate it. After you press enter,
the result appears immediately.
Give it a try. You can add and subtract numbers using the addition (+)
and subtraction (–) operators. For example:

>>> 1 + 2
3
>>> 1 + 3.5
4.5
>>> -1 + 2.5
1.5
>>> 100 – 45
55
>>> -1.1 + 5
3.9

To multiply, use the multiplication (*) operator:

>>> 3 * 2
6
>>> 3.5 * 1.5
5.25

To divide, use the division (/) operator:

>>> 3 / 2
1.5
>>> 4 / 2
2.0

As you can see, when you ask Python to perform a division operation,
it returns the fractional part of the number as well. If you want the result in
the form of an integer, with any decimal values removed, you should use the
floor division (//) operator:

>>> 3 // 2
1

2   Chapter 1
The floor division operator divides the first number by the second
number and then rounds down the result to the next lowest integer. This
becomes interesting when one of the numbers is negative. For example:

>>> -3 // 2
-2

The final result is the integer lower than the result of the division oper-
ation (-3/2 = -1.5, so the final result is -2).
On the other hand, if you want just the remainder, you should use the
modulo (%) operator:

>>> 9 % 2
1

You can calculate the power of numbers using the exponential (**)
operator. The examples below illustrate this:

>>> 2 ** 2
4
>>> 2 ** 10
1024
>>> 1 ** 10
1

We can also use the exponential symbol to calculate powers less than 1.
For example, the square root of a number n can be expressed as n1/2 and the
cube root as n1/3 :

>>> 8 ** (1/3)
2.0

As this example shows, you can use parentheses to combine mathe­


matical operations into more complicated expressions. Python will evalu-
ate the expression following the standard PEMDAS rule for the order of
calculations—parentheses, exponents, multiplication, division, addition,
and subtraction. Consider the following two expressions—one without
parentheses and one with:

>>> 5 + 5 * 5
30
>>> (5 + 5) * 5
50

In the first example, Python calculates the multiplication first: 5 times 5


is 25; 25 plus 5 is 30. In the second example, the expression within the paren-
theses is evaluated first, just as we’d expect: 5 plus 5 is 10; 10 times 5 is 50.
These are the absolute basics of manipulating numbers in Python. Let’s
now learn how we can assign names to numbers.

Working with Numbers   3


Labels: Attaching Names to Numbers
As we start designing more complex Python programs, we’ll assign names
to numbers—at times for convenience, but mostly out of necessity. Here’s a
simple example:

u >>> a = 3
>>> a + 1
4
v >>> a = 5
>>> a + 1
6

At u, we assign the name a to the number 3. When we ask Python to


evaluate the result of the expression a + 1, it sees that the number that
a refers to is 3, and then it adds 1 and displays the output (4). At v, we
change the value of a to 5, and this is reflected in the second addition
operation. Using the name a is convenient because you can simply change
the number that a points to and Python uses this new value when a is
referred to anywhere after that.
This kind of name is called a label. You may have been introduced to
the term variable to describe the same idea elsewhere. However, consider-
ing that variable is also a mathematical term (used to refer to something like
x in the equation x + 2 = 3), in this book I use the term variable only in the
context of mathematical equations and expressions.

Different Kinds of Numbers


You may have noticed that I’ve used two kinds of numbers to demonstrate
the mathematical operations—numbers without a decimal point, which you
already know as integers, and numbers with a decimal point, which program-
mers call floating point numbers. We humans have no trouble recognizing
and working with numbers whether they’re written as integers, floating
point decimals, fractions, or roman numerals. But in some of the programs
that we write in this book, it will only make sense to perform a task on a
particular type of number, so we’ll often have to write a bit of code to have
the programs check whether the numbers we input are of the right type.
Python considers integers and floating point numbers to be different
types. If you use the function type(), Python will tell you what kind of num-
ber you’ve just input. For example:

>>> type(3)
<class 'int'>

>>> type(3.5)
<class 'float'>

>>> type(3.0)
<class 'float'>

4   Chapter 1
Here, you can see that Python classifies the number 3 as an integer
(type 'int') but classifies 3.0 as a floating point number (type 'float'). We
all know that 3 and 3.0 are mathematically equivalent, but in many situa-
tions, Python will treat these two numbers differently because they are two
different types.
Some of the programs we write in this chapter will work properly only
with an integer as an input. As we just saw, Python won’t recognize a num-
ber like 1.0 or 4.0 as an integer, so if we want to accept numbers like that
as valid input in these programs, we’ll have to convert them from floating
point numbers to integers. Luckily, there’s a function built in to Python that
does just that:

>>> int(3.8)
3
>>> int(3.0)
3

The function int() takes the input floating point number, gets rid of
anything that comes after the decimal point, and returns the resulting inte-
ger. The float() function works similarly to perform the reverse conversion:

>>> float(3)
3.0

float() takes the integer that was input and adds a decimal point to
turn it into a floating point number.

Working with Fractions


Python can also handle fractions, but to do that, we’ll need to use Python’s
fractions module. You can think of a module as a program written by someone
else that you can use in your own programs. A module can include classes,
functions, and even label definitions. It can be part of Python’s standard
library or distributed from a third-party location. In the latter case, you
would have to install the module before you could use it.
The fractions module is part of the standard library, meaning that it’s
already installed. It defines a class Fraction, which is what we’ll use to enter
fractions into our programs. Before we can use it, we’ll need to import it,
which is a way of telling Python that we want to use the class from this mod-
ule. Let’s see a quick example—we’ll create a new label, f, which refers to
the fraction 3/4:

u >>> from fractions import Fraction


v >>> f = Fraction(3, 4)
w >>> f
Fraction(3, 4)

We first import the Fraction class from the fractions module u.


Next, we create an object of this class by passing the numerator and

Working with Numbers   5


denominator as parameters v. This creates a Fraction object for the frac-
tion 3/4. When we print the object w, Python displays the fraction in the
form Fraction(numerator, denominator).
The basic mathematical operations, including the comparison opera-
tions, are all valid for fractions. You can also combine a fraction, an integer,
and a floating point number in a single expression:

>>> Fraction(3, 4) + 1 + 1.5


3.25

When you have a floating point number in an expression, the result of


the expression is returned as a floating point number.
On the other hand, when you have only a fraction and an integer in the
expression, the result is a fraction, even if the result has a denominator of 1.

>>> Fraction(3, 4) + 1 + Fraction(1/4)


Fraction(2, 1)

Now you know the basics of working with fractions in Python. Let’s
move on to a different kind of number.

Complex Numbers
The numbers we’ve seen so far are the so-called real numbers. Python also
supports complex numbers with the imaginary part identified by the letter j
or J (as opposed to the letter i used in mathematical notation). For example,
the complex number 2 + 3i would be written in Python as 2 + 3j:

>>> a = 2 + 3j
>>> type(a)
<class 'complex'>

As you can see, when we use the type() function on a complex number,
Python tells us that this is an object of type complex.
You can also define complex numbers using the complex() function:

>>> a = complex(2, 3)
>>> a
(2 + 3j)

Here we pass the real and imaginary parts of the complex number as
two arguments to the complex() function, and it returns a complex number.
You can add and subtract complex numbers in the same way as real
numbers:

>>> b = 3 + 3j
>>> a + b
(5 + 6j)
>>> a - b
(-1 + 0j)

6   Chapter 1
Multiplication and division of complex numbers are also carried out
similarly:

>>> a * b
(-3 + 15j)
>>> a / b
(0.8333333333333334 + 0.16666666666666666j)

The modulus (%) and the floor division (//) operations are not valid for
complex numbers.
The real and imaginary parts of a complex number can be retrieved
using its real and imag attributes, as follows:

>>> z = 2 + 3j
>>> z.real
2.0
>>> z.imag
3.0

The conjugate of a complex number has the same real part but an imagi-
nary part with an equal magnitude and an opposite sign. It can be obtained
using the conjugate() method:

>>> z.conjugate()
(2 - 3j)

Both the real and imaginary parts are floating point numbers. Using the
real and imaginary parts, you can then calculate the magnitude of a complex
number with the following formula, where x and y are the real and imaginary
parts of the number, respectively: . In Python, this would look like
the following:

>>> (z.real ** 2 + z.imag ** 2) ** 0.5


3.605551275463989

A simpler way to find the magnitude of a complex number is with the


abs() function. The abs() function returns the absolute value when called
with a real number as its argument. For example, abs(5) and abs(-5) both
return 5. However, for complex numbers, it returns the magnitude:

>>> abs(z)
3.605551275463989

The standard library’s cmath module (cmath for complex math) provides
access to a number of other specialized functions to work with complex
numbers.

Working with Numbers   7


Getting User Input
As we start to write programs, it will help to have a nice, simple way to
accept user input via the input() function. That way, we can write programs
that ask a user to input a number, perform specific operations on that num-
ber, and then display the results of the operations. Let’s see it in action:

u >>> a = input()
v 1

At u, we call the input() function, which waits for you to type something,
as shown at v, and press enter. The input provided is stored in a:

>>> a
w '1'

Notice the single quotes around 1 at w. The input() function returns


the input as a string. In Python, a string is any set of characters between two
quotes. When you want to create a string, either single quotes or double
quotes can be used:

>>> s1 = 'a string'


>>> s2 = "a string"

Here, both s1 and s2 refer to the same string.


Even if the only characters in a string are numbers, Python won’t treat
that string as a number unless we get rid of those quotation marks. So
before we can perform any mathematical operations with the input, we’ll
have to convert it into the correct number type. A string can be converted
to an integer or floating point number using the int() or float() function,
respectively:

>>> a = '1'
>>> int(a) + 1
2
>>> float(a) + 1
2.0

These are the same int() and float() functions we saw earlier, but this
time instead of converting the input from one kind of number to another,
they take a string as input ('1') and return a number (2 or 2.0). It’s impor-
tant to note, however, that the int() function cannot convert a string con-
taining a floating point decimal into an integer. If you take a string that has
a floating point number (like '2.5' or even '2.0') and input that string into
the int() function, you’ll get an error message:

>>> int('2.0')
Traceback (most recent call last):

8   Chapter 1
File "<pyshell#26>", line 1, in <module>
int('2.0')
ValueError: invalid literal for int() with base 10: '2.0'

This is an example of an exception—Python’s way of telling you that it


cannot continue executing your program because of an error. In this case,
the exception is of the type ValueError. (For a quick refresher on exceptions,
see Appendix B.)
Similarly, when you supply a fractional number such as 3/4 as an input,
Python cannot convert it into an equivalent floating point number or inte-
ger. Once again, a ValueError exception is raised:

>>> a = float(input())
3/4
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
a=float(input())
ValueError: could not convert string to float: '3/4'

You may find it useful to perform the conversion in a try...except block


so that you can handle this exception and alert the user that the program
has encountered an invalid input. We’ll look at try...except blocks next.

Handling Exceptions and Invalid Input


If you’re not familiar with try...except, the basic idea is this: if you execute
one or more statements in a try...except block and there’s an error while
executing, your program will not crash and print a Traceback. Instead, the
execution is transferred to the except block, where you can perform an
appropriate operation, for instance, printing a helpful error message or
trying something else.
This is how you would perform the above conversion in a try...except
block and print a helpful error message on invalid input:

>>> try:
a = float(input('Enter a number: '))
except ValueError:
print('You entered an invalid number')

Note that we need to specify the type of exception we want to handle.


Here, we want to handle the ValueError exception, so we specify it as except
ValueError.
Now, when you give an invalid input, such as 3/4, it prints a helpful
error message, as shown at u:

Enter a number: 3/4


u You entered an invalid number

Working with Numbers   9


You can also specify a prompt with the input() function to tell the user
what kind of input is expected. For example:

>>> a = input('Input an integer: ')

The user will now see the message hinting to enter an integer as input:

Input an integer: 1

In many programs in this book, we’ll ask the user to enter a number
as input, so we’ll have to make sure we take care of conversion before we
attempt to perform any operations on these numbers. You can combine the
input and conversion in a single statement, as follows:

>>> a = int(input())
1
>>> a + 1
2

This works great if the user inputs an integer. But as we saw earlier, if
the input is a floating point number (even one that’s equivalent to an inte-
ger, like 1.0), this will produce an error:

>>> a = int(input())
1.0
Traceback (most recent call last):
File "<pyshell#42>", line 1, in <module>
a=int(input())
ValueError: invalid literal for int() with base 10: '1.0'

In order to avoid this error, we could set up a ValueError catch like the
one we saw earlier for fractions. That way the program would catch float-
ing point numbers, which won’t work in a program meant for integers.
However, it would also flag numbers like 1.0 and 2.0, which Python sees as
floating point numbers but that are equivalent to integers and would work
just fine if they were entered as the right Python type.
To get around all this, we will use the is_integer() method to filter out
any numbers with a significant digit after the decimal point. (This method
is only defined for float type numbers in Python; it won’t work with num-
bers that are already entered in integer form.)
Here’s an example:

>>> 1.1.is_integer()
False

Here, we call the method is_integer() to check if 1.1 is an integer, and


the result is False because 1.1 really is a floating point number. On the other

10   Chapter 1
hand, when the method is called with 1.0 as the floating point number, the
result is True:

>>> 1.0.is_integer()
True

We can use is_integer() to filter out noninteger input while keeping


inputs like 1.0, which is expressed as a floating point number but is equiva-
lent to an integer. We’ll see how the method would fit into a larger program
a bit later.

Fractions and Complex Numbers as Input


The Fraction class we learned about earlier is also capable of converting a
string such as '3/4' to a Fraction object. In fact, this is how we can accept a
fraction as an input:

>>> a = Fraction(input('Enter a fraction: '))


Enter a fraction: 3/4
>>> a
Fraction(3, 4)

Try entering a fraction such as 3/0 as input:

>>> a = Fraction(input('Enter a fraction: '))


Enter a fraction: 3/0
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
a = Fraction(input('Enter a fraction: '))
File "/usr/lib64/python3.3/fractions.py", line 167, in __new__
raise ZeroDivisionError('Fraction(%s, 0)' % numerator)
ZeroDivisionError: Fraction(3, 0)

The ZeroDivisionError exception message tells you (as you already know)
that a fraction with a denominator of 0 is invalid. If you’re planning on hav-
ing users enter fractions as input in one of your programs, it’s a good idea
to always catch such exceptions. Here is how you can do something like that:

>>> try:
a = Fraction(input('Enter a fraction: '))
except ZeroDivisionError:
print('Invalid fraction')

Enter a fraction: 3/0


Invalid fraction

Now, whenever your program’s user enters a fraction with 0 in the


denominator, it’ll print the message Invalid fraction.

Working with Numbers   11

www.allitebooks.com
Discovering Diverse Content Through
Random Scribd Documents
staff changed frequently. Generally speaking, with very few
exceptions, commanding officers received their instruction from the
staff of Commander in Chief U-boats after I myself had given them
their instructions. Commanding officers were generally speaking in
much closer personal contact with these young staff officers than
they were with myself as senior officer of a purely transit flotilla.
There were many commanding officers whom I only saw and got to
know for a few days in Kiel while they were fitting their boats out for
operations.
Having given considerable thought to the whole of this matter I now
remember that during one of my visits to Commander in Chief U-
boats' staff in the winter of 1942/3 or the summer '43, one of the
staff officers, Korvettenkapitaen Hessler or perhaps more likely
Korvettenkapitaen Kuppisch, with whom because of very close ties of
friendship I used to converse intimately as long as he was
Commander in Chief U-boats' staff, told me of the following
occurrence (whether I broached the subject or how the matter came
up I can no longer remember).
A type VII boat (500-tonner) reported in her war log that when
outward bound from a base in France, she met far out in the Bay of
Biscay a raft with five enemy airmen, but was not able to take them
on board owing to shortage of room (she had a complement of 54
and carried full provisions for 14 weeks). The boat therefore
proceeded without taking any notice of the survivors.
This action of the U-boat was vehemently denounced by the
Commander in Chief U-boats' staff. It was stated that she would
have acted more correctly in destroying this raft since it was highly
probable that the enemy air crew would be rescued by the enemy
and in the meantime might once more have destroyed a German U-
boat.
This occurrence made the views of the Commander in Chief U-boats
clear to me.
As concerns making the order known to commanding officers: the
order was always passed on during a commanding officers'
conference while their boats were having their final overhaul or
while they were being fitted out in Kiel for operational patrols;
during these conferences I passed on to commanding officers once
again all important orders about the equipping of their boats,
procedure on departure, in home waters and while in convoy to
Norway. Operational orders were not given by the flotilla; they were
always given by the Commander in Chief U-boats himself or by
Captain U-boats West on his behalf.
I was wont to pass on this controversial and serious order with more
or less the following words:—"I have now to inform you of a High
Command order concerning conduct towards survivors. It is a very
ticklish matter. Commander in Chief U-boats in September 1942 gave
the following order in an 'officers only' signal ( ... the exact words of
the order were then read out)."
Since I am myself in my innermost conscience in disagreement with
this order, I was very glad that in most cases commanding officers
raised no queries and I was therefore relieved of any further
discussion on this point.
Sometimes however queries were raised and I was wont to answer
somewhat as follows:—
"I will explain the viewpoint of the High Command, which gave this
order, by reference to the following event": I then mentioned the
example of the Type VII boat in the Bay of Biscay together with the
explanation and viewpoint expressed to me by Commander in Chief
U-boats' staff. I then went on to say, "Gentlemen, you must
yourselves decide what is compatible with own consciences. The
safety of your own boat must always remain your prime
consideration."
Since the introduction of total underwater war ("Schnorchel"), I have
in this connection in various ways further stated that commanding
officers were in a much easier position in this respect since they had
no occasion to surface and that the order was therefore illusory for
them. They had to keep clear of everything which was not worth the
firing of a torpedo.
I also remember that many commanding officers after the order of
September 1942 had been read said, "That is quite clear and
unequivocal however hard it may be". Had this order been given to
me as a commanding officer I would have taken note of it in silence
but in practice would always have been able with a clear conscience
not to carry it out since I consider I would endanger my own boat by
acting in this way, (i.e., by shooting at life-boats).
If therefore U-boat commanding officers state that they had received
from me the order to destroy life-boats, this does not correspond
with the facts, but they received from me quite insufficiently clearly
expressed instructions from the High Command together with my
personal views thereon.
Before the order of September 1942 was issued I never discussed
this difficult question at a commanding officers' conference and the
subject of conduct towards survivors was never broached.
B. Conduct Towards Neutral and Hospital Ships
On this matter, which I treated together with what has gone before,
I gave commanding officers the following directions:
There was an express order of the High Command, and Commander
in Chief U-boats was adamant on this point and would relentlessly
pursue the breach of it by court martial (i.e., he insisted on the order
being strictly obeyed), that no neutral or Red Cross ship might be
molested even if the enemy misused neutral flags or the Red Cross.
The political results of sinking a neutral were much more serious
than would have been the usefulness of the tonnage sunk.
I told commanding officers for their guidance in doubtful cases—in
bad visibility, when neutral markings were not distinct, etc.—that it
was better to allow five enemy vessels to go free than to sink one
neutral.
So far as concerns the stopping and examination of neutrals, an
order was made in January 1944 that in particular Spanish and
Portuguese steamers in the North and Central Atlantic were to be
stopped and examined for contraband and members of enemy
nations of military age. I told commanding officers "Don't touch
them. Stay underwater. You are endangering yourselves too much by
that because you will certainly be reported by wireless and we know
from experience that when such examinations are made
watchfulness is liable to suffer. You are only exposing yourself to the
danger of being surprised. If a ship carries neutral markings let it go
by unscathed."
Objection was often made that German hospital ships had often
been destroyed by the enemy, as German propaganda had stressed
for years. My answer was: That does not matter, however
unpleasant it may be. The order of the High Command is decisive
and binding. Politics come before warfare.
C. Rendering of Reports
There was an order—I do not remember whether it was in the form
of a written or verbal instruction—that no events during a war patrol
which contravened established international agreements should be
entered in the war log. I believe that the reason for this order was
that eight copies were made of war logs and were available to many
authorities; there was always the danger therefore that events of
this nature would become known and it was undoubtedly
undesirable for reasons of propaganda that this should be so.
Events of this nature were only to be reported if asked for when
commanding officers made their personal reports; these were
invariably made after every patrol to Commander in Chief U-boats or
later in certain instances to Captain U-boats.
I also gave the commanding officers instructions on this point.
To conclude, I can only stress that the order of September 1942
appeared to me personally to go too far and I am in total
disagreement with it at heart. As a serving officer I had however to
carry out the command to pass on this order to commanding officers
for their instruction.
During the long time that I was senior officer of the Flotilla no single
commanding officer mentioned to me that he could not reconcile
obedience to this order with his conscience and that he was
therefore unable to carry it out.
An order of this nature was never given by me, i.e. on my own
initiative, and could not be given by me since, had I exceeded my
authority in so serious a way, I would immediately and without
question have been relieved.
[signed] MOEHLE
Korvettenkapitaen

TRANSLATION OF DOCUMENT
386-PS
Berlin, 10 Nov 1937

NOTES on the Conference in the Reichskanzlei


on 5 Nov 37 from 1615-2030 hours
Present: The Fuehrer and Reich Chancellor
The Reichsminister for War, Generalfeldmarschall v. BLOMBERG
The C-in-C Army, Generaloberst Freiherr von FRITSCH
The C-in-C Navy, Generaladmiral Dr. h. c. RAEDER
The C-in-C Luftwaffe, Generaloberst GOERING
The Reichsminister for Foreign Affairs Freiherr v. NEURATH
Oberst HOSSBACH
The Fuehrer stated initially that the subject matter of today's
conference was of such high importance, that its further detailed
discussion would probably take place in Cabinet sessions. However,
he, the Fuehrer, had decided NOT to discuss this matter in the larger
circle of the Reich Cabinet, because of its importance. His
subsequent statements were the result of detailed deliberations and
of the experiences of his 4-1/2 years in Government; he desired to
explain to those present his fundamental ideas on the possibilities
and necessities of expanding our foreign policy and in the interests
of a far-sighted policy he requested that his statements be looked
upon in the case of his death as his last will and testament.
The Fuehrer then stated:
The aim of German policy is the security and the preservation of the
nation, and its propagation. This is, consequently, a problem of
space.
The German nation is composed of 85 million people, which,
because of the number of individuals and the compactness of
habitation, form a homogeneous European racial body which cannot
be found in any other country. On the other hand, it justifies the
demand for larger living space more than for any other nation. If no
political body exists in space, corresponding to the German racial
body, then that is the consequence of several centuries of historical
development, and should this political condition continue to exist, it
will represent the greatest danger to the preservation of the German
nation [Volkstum] at its present high level. An arrest of the
deterioration of the German element in Austria and Czechoslovakia is
just as little possible as the preservation of the present state in
Germany itself. Instead of growth, sterility will be introduced, and as
a consequence, tensions of a social nature will appear after a
number of years, because political and philosophical ideas are of a
permanent nature only as long as they are able to produce the basis
for the realization of the actual claim of existence of a nation. The
German future is therefore dependent exclusively on the solution of
the need for living space. Such a solution can be sought naturally
only for a limited period, about 1-3 generations.
Before touching upon the question of solving the need for living
space, it must be decided whether a solution of the German position
with a good future can be attained, either by way of an autarchy or
by way of an increased share in universal commerce and industry.
Autarchy: Execution will be possible only with strict National-Socialist
State policy, which is the basis; assuming this can be achieved the
results are as follows:
A. In the sphere of raw materials, only limited, but NOT total
autarchy can be attained:
1. Wherever coal can be used for the extraction of raw materials
autarchy is feasible.
2. In the case of ores the position is much more difficult.
Requirements in iron and light metals can be covered by ourselves.
Copper and tin, however, can NOT.
3. Cellular materials can be covered by ourselves as long as
sufficient wood supplies exist. A permanent solution is not possible.
4. Edible fats—possible.
B. In the case of foods, the question of an autarchy must be
answered with a definite "NO".
The general increase of living standards, compared with 30-40 years
ago, brought about a simultaneous increase of the demand for an
increase of personal consumption even among the producers, the
farmers, themselves. The proceeds from the production increase in
agriculture have been used for covering the increase in demands,
therefore they represent no absolute increase in production. A
further increase in production by making greater demands on the
soil is not possible because it already shows signs of deterioration
due to the use of artificial fertilizers, and it is therefore certain that,
even with the greatest possible increase in production, participation
in the world market could NOT be avoided.
The considerable expenditure of foreign currency to secure food by
import, even in periods when harvests are good, increases
catastrophically when the harvest is really poor. The possibility of
this catastrophe increases correspondingly to the increase in
population, and the annual 560,000 excess in births would bring
about an increased consumption in bread, because the child is a
greater bread eater than the adult.
Permanently to counter the difficulties of food supplies by lowering
the standard of living and by rationalization is impossible in a
continent which had developed an approximately equivalent
standard of living. As the solving of the unemployment problem has
brought into effect the complete power of consumption, some small
corrections in our agricultural home production will be possible, but
NOT a wholesale alteration of the standard of food consumption.
Consequently autarchy becomes impossible, specifically in the
sphere of food supplies as well as generally.
Participation in World Economy. There are limits to this which we are
unable to transgress. The market fluctuations would be an obstacle
to a secure foundation of the German position; international
commercial agreements do NOT offer any guarantee for practical
execution. It must be considered on principle that since the World
War (1914-18) an industrialization has taken place in countries
which formerly exported food. We live in a period of economic
empires, in which the tendency to colonize again approaches the
condition which originally motivated colonization; in Japan and Italy
economic motives are the basis of their will to expand, the economic
need will also drive Germany to it. Countries outside the great
economic empires have special difficulties in expanding economically.
The upward tendency, which has been caused in world economy,
due to armament competition, can never form a permanent basis for
an economic settlement, and this latter is also hampered by the
economic disruption caused by Bolshevism. It is a pronounced
military weakness of those States who base their existence on
export. As our exports and imports are carried out over those sea
lanes which are ruled by Britain, it is more a question of security of
transport rather than one of foreign currency, and this explains the
great weakness in our food situation in wartime. The only way out,
and one which may appear imaginary, is the securing of greater
living space, an endeavor which at all times has been the cause of
the formation of states and of movements of nations. It is explicable
that this tendency finds no interest in Geneva and in satisfied States.
Should the security of our food position be our foremost thought,
then the space required for this can only be sought in Europe, but
we will not copy liberal capitalist policies which rely on exploiting
colonies. It is NOT a case of conquering people, but of conquering
agriculturally useful space. It would also be more to the purpose to
seek raw material producing territory in Europe directly adjoining the
Reich and not overseas, and this solution would have to be brought
into effect in one or two generations. What would be required at a
later date over and above this must be left to subsequent
generations. The development of great world-wide national bodies is
naturally a slow process and the German people, with its strong
racial root, has for this purpose the most favorable foundations in
the heart of the European Continent. The history of all times—
Roman Empire, British Empire—has proved that every space
expansion can only be effected by breaking resistance and taking
risks. Even setbacks are unavoidable; neither formerly nor today has
space been found without an owner; the attacker always comes up
against the proprietor.
The question for Germany is where the greatest possible conquest
could be made at lowest cost.
German politics must reckon with its two hateful enemies, England
and France, to whom a strong German colossus in the center of
Europe would be intolerable. Both these states would oppose a
further reinforcement of Germany, both in Europe and overseas, and
in this opposition they would have the support of all parties. Both
countries would view the building of German military strongpoints
overseas as a threat to their overseas communications, as a security
measure for German commerce, and retrospectively a strengthening
of the German position in Europe.
England is NOT in a position to cede any of her colonial possessions
to us owing to the resistance which she experiences in the
Dominions. After the loss of prestige which England has suffered
owing to the transfer of Abyssinia to Italian ownership, a return of
East Africa can no longer be expected. Any resistance on England's
part would at best consist in the readiness to satisfy our colonial
claims by taking away colonies which at the present moment are
NOT in British hands, e.g. Angola. French favors would probably be
of the same nature.
A serious discussion regarding the return of colonies to us could be
considered only at a time when England is in a state of emergency
and the German Reich is strong and well-armed. The Fuehrer does
not share the opinion that the Empire is unshakable. Resistance
against the Empire is to be found less in conquered territories than
amongst its competitors. The British Empire and the Roman Empire
cannot be compared with one another in regard to durability; since
the Punic Wars the latter did not have a serious political enemy. Only
the dissolving effects which originated in Christendom, and the signs
of age which creep into all states, made it possible for the Ancient
Germans to subjugate Ancient Rome.
Alongside the British Empire today a number of States exist which
are stronger than it. The British Mother Country is able to defend its
colonial possessions only allied with other States and NOT by its own
power. How could England alone, for example, defend Canada
against an attack by America or its Far Eastern interests against an
attack by Japan.
The singling out of the British Crown as the bearer of Empire unity is
in itself an admission that the universal empire cannot be maintained
permanently by power politics. The following are significant pointers
in this respect.
a. Ireland's tendency for independence.
b. Constitutional disputes in India where England, by her half-
measures, left the door open for Indians at a later date to utilize the
nonfulfillment of constitutional promises as a weapon against Britain.
c. The weakening of the British position in the Far East by Japan.
d. The opposition in the Mediterranean to Italy which—by virtue of
its history, driven by necessity and led by a genius—expands its
power position and must consequently infringe British interests to an
increasing extent. The outcome of the Abyssinian War is a loss of
prestige for Britain which Italy is endeavoring to increase by stirring
up discontent in the Mohammedan world.
It must be established in conclusion that the Empire cannot be held
permanently by power politics by 45 million Britons, in spite of all
the solidity of her ideals. The proportion of the populations in the
Empire, compared with that of the Motherland is 9:1, and it should
act as a warning to us that if we expand in space, we must NOT
allow the level of our population to become too low.
France's position is more favorable than that of England. The French
Empire is better placed geographically, the population of its colonial
possessions represents a potential military increase. But France is
faced with difficulties of internal politics. At the present time only 10
per cent approximately of the nations have parliamentary
governments whereas 90 per cent of them have totalitarian
governments. Nevertheless we have to take the following into our
political considerations as power factors:
Britain, France, Russia and the adjoining smaller States.
The German question can be solved only by way of force, and this is
never without risk. The battles of Frederick the Great for Silesia, and
Bismarck's wars against Austria and France had been a tremendous
risk and the speed of Prussian action in 1870 had prevented Austria
from participating in the war. If we place the decision to apply force
with risk at the head of the following expositions, then we are left to
reply to the questions "when" and "how". In this regard we have to
decide upon three different cases.
Case 1. Period 1943-45. After this we can only expect a change for
the worse. The re-arming of the Army, the Navy and the Air Force,
as well as the formation of the Officers' Corps, are practically
concluded. Our material equipment and armaments are modern,
with further delay the danger of their becoming out-of-date will
increase. In particular the secrecy of "special weapons" cannot
always be safeguarded. Enlistment of reserves would be limited to
the current recruiting age groups and an addition from older
untrained groups would be no longer available.
In comparison with the re-armament, which will have been carried
out at that time by the other nations, we shall decrease in relative
power. Should we not act until 1943/45, then, dependent on the
absence of reserves, any year could bring about the food crisis, for
the countering of which we do NOT possess the necessary foreign
currency. This must be considered as a "point of weakness in the
regime". Over and above that, the world will anticipate our action
and will increase counter-measures yearly. Whilst other nations
isolate themselves we should be forced on the offensive.
What the actual position would be in the years 1943-1945 no one
knows today. It is certain, however, that we can wait no longer.
On the one side the large armed forces, with the necessity for
securing their upkeep, the aging of the Nazi movement and of its
leaders, and on the other side the prospect of a lowering of the
standard of living and a drop in the birth rate, leaves us no other
choice than to act. If the Fuehrer is still living, then it will be his
irrevocable decision to solve the German space problem no later
than 1943-45. The necessity for action before 1943-45 will come
under consideration in cases 2 and 3.
Case 2. Should the social tensions in France lead to an internal
political crisis of such dimensions that it absorbs the French Army
and thus renders it incapable for employment in war against
Germany, then the time for action against Czechoslovakia has come.
Case 3. It would be equally possible to act against Czechoslovakia if
France should be so tied up by a war against another State, that it
cannot "proceed" against Germany.
For the improvement of our military political position it must be our
first aim, in every case of entanglement by war, to conquer
Czechoslovakia and Austria simultaneously, in order to remove any
threat from the flanks in case of a possible advance Westwards. In
the case of a conflict with France it would hardly be necessary to
assume that Czechoslovakia would declare war on the same day as
France. However, Czechoslovakia's desire to participate in the war
will increase proportionally to the degree to which we are being
weakened. Its actual participation could make itself felt by an attack
on Silesia, either towards the North or the West.
Once Czechoslovakia is conquered—and a mutual frontier, Germany-
Hungary is obtained—then a neutral attitude by Poland in a German-
French conflict could more easily be relied upon. Our agreements
with Poland remain valid only as long as Germany's strength remains
unshakeable; should Germany have any setbacks then an attack by
Poland against East Prussia, perhaps also against Pomerania, and
Silesia, must be taken into account.
Assuming a development of the situation, which would lead to a
planned attack on our part in the years 1943-45, then the behavior
of France, Poland and Russia would probably have to be judged in
the following manner:
The Fuehrer believes personally that in all probability England and
perhaps also France have already silently written off Czechoslovakia,
and that they have got used to the idea that this question would one
day be cleaned up by Germany. The difficulties in the British Empire
and the prospect of being entangled in another long-drawn-out
European War, were decisive factors in the non-participation of
England in a war against Germany. The British attitude would
certainly NOT remain without influence on France's attitude. An
attack by France without British support is hardly probable assuming
that its offensive would stagnate along our Western fortifications.
Without England's support, it would also NOT be necessary to take
into consideration a march by France through Belgium and Holland,
and this would also not have to be reckoned with by us in case of a
conflict with France, as in every case it would have as consequence
the enmity of Great Britain. Naturally, we should in every case have
to bar our frontier during the operation of our attacks against
Czechoslovakia and Austria. It must be taken into consideration here
that Czechoslovakia's defence measures will increase in strength
from year to year, and that a consolidation of the inside values of the
Austrian army will also be effected in the course of years. Although
the population of Czechoslovakia in the first place is not a thin one,
the embodiment of Czechoslovakia and Austria would nevertheless
constitute the conquest of food for 5-6 million people, on the basis
that a compulsory emigration of 2 million from Czechoslovakia and of
1 million from Austria could be carried out. The annexation of the
two States to Germany militarily and politically would constitute a
considerable relief, owing to shorter and better frontiers, the freeing
of fighting personnel for other purposes and the possibility of re-
constituting new armies up to a strength of about 12 Divisions,
representing a new division per 1 million population.
No opposition to the removal of Czechoslovakia is expected on the
part of Italy; however, it cannot be judged today what would be her
attitude in the Austrian question since it would depend largely on
whether the Duce were alive at the time or not.
The measure and speed of our action would decide Poland's
attitude. Poland will have little inclination to enter the war against a
victorious Germany, with Russia in its rear.
Military participation by Russia must be countered by the speed of
our operations; it is a question whether this need be taken into
consideration at all in view of Japan's attitude.
Should Case 2 occur—paralyzation of France by a Civil War—then
the situation should be utilized at any time for operations against
Czechoslovakia, as Germany's most dangerous enemy would be
eliminated.
The Fuehrer sees Case 3 looming nearer; it could develop from the
existing tensions in the Mediterranean, and should it occur he has
firmly decided to make use of it any time, perhaps even as early as
1938.
Following recent experiences in the course of the events of the war
in Spain, the Fuehrer does NOT see an early end to hostilities there.
Taking into consideration the time required for past offensives by
Franco, a further three years duration of war is within the bounds of
possibility. On the other hand, from the German point of view a 100
per cent victory by Franco is not desirable; we are more interested in
a continuation of the war and preservation of the tensions in the
Mediterranean. Should Franco be in sole possession of the Spanish
Peninsula it would mean the end of Italian intervention and the
presence of Italy on the Balearic Isles. As our interests are directed
towards continuing the war in Spain, it must be the task of our
future policy to strengthen Italy in her fight to hold on to the
Balearic Isles. However, a solidification of Italian positions on the
Balearic Isles can NOT be tolerated either by France or by England
and could lead to a war by France and England against Italy, in
which case Spain, if entirely in white (i.e. Franco's) hands, could
participate on the side of Italy's enemies. A subjugation of Italy in
such a war appears very unlikely. Additional raw materials could be
brought to Italy via Germany. The Fuehrer believes that Italy's
military strategy would be to remain on the defensive against France
on the Western frontier and carry out operations against France from
Libya against North African French colonial possessions.
As a landing of French-British troops on the Italian coast can be
discounted, and as a French offensive via the Alps to Upper Italy
would be extremely difficult and would probably stagnate before the
strong Italian fortifications, French lines of communication by the
Italian fleet will to a great extent paralyze the transport of fighting
personnel from North Africa to France, so that at its frontiers with
Italy and Germany France will have at its disposal solely the
metropolitan fighting forces.
If Germany profits from this war by disposing of the Czechoslovakian
and the Austrian questions, the probability must be assumed that
England—being at war with Italy—would not decide to commence
operations against Germany. Without British support a warlike action
by France against Germany is not to be anticipated.
The date of our attack on Czechoslovakia and Austria must be made
dependent on the course of the Italian-English-French war and
would not be simultaneous with the commencement of military
agreements with Italy, but of full independence and, by exploiting
this unique favorable opportunity he wishes to begin to carry out
operations against Czechoslovakia. The attack on Czechoslovakia
would have to take place with the "speed of lightning" [blitzartig
schnell].
Feldmarschall von Blomberg and Generaloberst von Fritsch in giving
their estimate on the situation, repeatedly pointed out that England
and France must not appear as our enemies, and they stated that
the war with Italy would NOT bind the French army to such an
extent that it would NOT be in a position to commence operations
on our Western frontier with superior forces. Generaloberst von
Fritsch estimated the French forces which would presumably be
employed on the Alpine frontier against Italy to be in the region of
20 divisions, so that a strong French superiority would still remain on
our Western frontier. The French would, according to German
reasoning, attempt to advance into the Rhineland. We should
consider the lead which France has got in mobilization, and quite
apart from the very small value of our then existing fortifications—
which was pointed out particularly by Generalfeldmarschall von
Blomberg—the four motorized divisions which had been laid down
for the West would be more or less incapable of movement. With
regard to our offensive in a South-Easterly direction, Feldmarschall
von Blomberg draws special attention to the strength of the
Czechoslovakian fortifications, the building of which had assumed
the character of a Maginot line and which would present extreme
difficulties to our attack.
Generaloberst von Fritsch mentioned that it was the purpose of a
study which he had laid on for this winter to investigate the
possibilities of carrying out operations against Czechoslovakia with
special consideration of the conquest of the Czechoslovakian system
of fortifications; the Generaloberst also stated that owing to the
prevailing conditions he would have to relinquish his leave abroad,
which was to begin on 10 November. This intention was
countermanded by the Fuehrer who gave as a reason that the
possibility of the conflict was not to be regarded as being so
imminent. In reply to the remark by the Minister for Foreign Affairs,
that an Italian-English-French conflict be not as near as the Fuehrer
appeared to assume, the Fuehrer stated that the date which
appeared to him to be a possibility was summer 1938. In reply to
statements by Generalfeldmarschall von Blomberg and Generaloberst
von Fritsch regarding England and France's attitude, the Fuehrer
repeated his previous statements and said that he was convinced of
Britain's non-participation and that consequently he did not believe
in military action by France against Germany. Should the
Mediterranean conflict already mentioned lead to a general
mobilization in Europe, then we should have to commence
operations against Czechoslovakia immediately. If, however, the
powers who are not participating in the war should declare their
disinterestedness, then Germany would, for the time being, have to
side with this attitude.
In view of the information given by the Fuehrer, Generaloberst
Goering considered it imperative to think of a reduction or
abandonment of our military undertaking in Spain. The Fuehrer
agreed to this in so far as he believed this decision should be
postponed for a suitable date.
The second part of the discussion concerned material armament
questions.
(Signed) HOSSBACH
TRANSLATION OF DOCUMENT
388-PS
APPERTAINING TO WAR HISTORY
[pencil note]
S.O. Only
"FALL GRUEN"
CZECHOSLOVAKIA
[ITEM 1] [Handwritten notes]
* * * of the Fuehrer: [semi-illegible]
1. Does Mussolini regard his work as completed or not.
a. if so, close future boundary of Czechoslovakia, West; then wait
and see. "Return with the bag empty."
b. if not, then the "Empire" of Africa. Impossible without German
help. Czechoslovakia is a preliminary condition. "Return with
Czechoslovakia in the bag."
2. Mussolini, who is no illusionist, can definitely assess Germany's
military potentialities. Therefore he will suit timing of his aims with
that.
3. Against France and England problem of Czechoslovakia can be
settled only if still allied with Italy. France and England will not
intervene. (Only to overcome the four-week re-grouping period.)
4. Living under a common fate. (Example, 1805 and 1806)
5. State of Armament: comparisons relative but in our favor:
a. Deliveries of ores: France—600,000 tons; Germany—2 million
tons.
b. Britain has been arming for 9 months. Launchings not for 2 years.
c. Out of date air force equipment.
6. No general staff conferences of the various branches of the Armed
Forces. Would have to retract permission to the Army. Only through
Supreme Command. Very important that actual intentions be kept
secret.
7. Arming progressing too slowly: Guns not only for constituted
units, but also in reserve for replacement. Fortifications. Range of
guns.
8. Replacement of officers doubtful.

Schm
[Major Schmundt's writing and initialled by him]

[ITEM 2] [Typed notes]


S.O. Only
Berlin, 22 April 1938
BASES OF THE DISSERTATION ON "GRUEN"
Summary of discussion between Fuehrer and General Keitel of 21
April:
A. Political Aspect
1. Strategic surprise attack out of a clear sky without any cause or
possibility of justification has been turned down. As result would be:
hostile world opinion which can lead to a critical situation. Such a
measure is justified only for the elimination of the last opponent on
the mainland.
2. Action after a time of diplomatic clashes, which gradually come to
a crisis and lead to war.
3. Lightning-swift action as the result of an incident (e.g.
assassination of German ambassador in connection with an anti-
German demonstration).
B. Military Conclusions
1. The preparations are to be made for the political possibilities 2
and 3. Case 2 is the undesired one since "Gruen" will have taken
security measures.
2. The loss of time caused by transporting the bulk of the divisions
by rail—which is unavoidable but should be cut down as far as
possible—must not impede a lightning-swift blow at the time of the
action.
3. "Separate thrusts" are to be carried out immediately with a view
to penetrating the enemy fortification lines at numerous points and
in a strategically favorable direction. The thrusts are to be worked
out to the smallest detail (knowledge of roads, of targets,
composition of the columns according to their individual tasks).
Simultaneous attacks by the Army and Air Force.
The Air Force is to support the individual columns, (e.g. dive-
bombers: sealing off installations at penetration points, hampering
the bringing up of reserves, destroying signal communications
traffic, thereby isolating the garrisons.)
4. Politically, the first 4 days of military action are the decisive ones.
If there are no effective military successes, a European crisis will
certainly arise. Accomplished facts must prove the senselessness of
foreign military intervention, draw Allies into the scheme (division of
spoils!) and demoralize "Gruen".
Therefore: bridging the time gap between first penetration and
employment of the forces to be brought up, by a determined and
ruthless thrust by a motorized army. (e.g. via Pi past Pr) [Pilsen,
Prague],
5. If possible, separation of transport movement "Rot" from "Gruen".
A simultaneous strategic concentration "Rot" can lead "Rot" to
undesired measures. On the other hand it must be possible to put
"Fall Rot" into operation at any time.
C. Propaganda
1. Leaflets on the conduct of Germans in Czechoslovakia
(Gruenland).
2. Leaflets with threats for intimidation of the Czechs (Gruenen).
Schm
[initialled by Schmundt]

Written by an officer
[The following are handwritten notes]

22 April
A. POLITICAL POSSIBILITIES
1. Sudden surprise attack out of clear sky not possible. World
opinion can produce critical situation. Would be thinkable only for
ultimate conflict without the threat of other opponents.
2. Action after a period of tension and constant aggravation of the
situation.
3. Action as the result of an incident. (example)
B. MILITARY NECESSITIES
Cases 2 and 3 can be considered. In case 2 "security measures" will
be taken. Duration of transporting by rail to be looked into.
1. Invasion by columns ready to march at points which lie in a
direction, strategically important. (Permanent fortifications must be
known, columns assembled to suit particular situations, roads
reconnoitred.) Simultaneous attack by Luftwaffe, cooperation with
Luftwaffe, isolation of garrisons of the fortifications, cutting of
communications.
2. "Dead Space" in first 4 days prior to actual operation must be
avoided under all circumstances. Must be bridged through motorized
army. Penetrating via Pilsen. Hamper mobilization.
3. Separation of transport movement "Rot" and "Gruen",
a. in order not to aggravate "Rot",
b. but also so as not to arrive late, if necessary.
Basic Principle: Create Accomplished Facts so that
a. help comes too late—other powers do not intervene
b. Allies take part (like wolves also want something out of it)
c. State collapse from within.
Propaganda: Directions to Germans. Threats to others.
Submit:
1. Fortifications (strength in detail)
2. Distribution of nationalities within Wehrmacht.

[ITEM 3] [Four Telegrams]


MOS 1 16/5 0925— Supreme Command of the Armed Forces
ZEITZLER Most Secret—1. Which divisions on the "Gruen" frontiers
ready to march within 12 hours, in the case of mobilization? 2. What
is the final day of mobilization?
SCHMUNDT
MOS 1 1930 MELDAU MBZ
[the same also in Schmundt's handwriting]
MOS No. 2 1115—
MBZ 02 16/5 1114—
Major Schmundt, Armed Forces Adjutant to the Fuehrer—
Most Secret to Question 1, 12 of them—in garrisons
to Question 2, Third day—Please state time of
receipt. Teleprint left my room at 1110—NN.
ZEITZLER Oberstleutnant on the General Staff

MOS 03 16/5 1155


OKW for Oberstleutnant Zeitzler—Most Secret
1. Teleprint received 1115
2. Please send the numbers of the divisions.
Schmundt
1159 MOS 03 Wagner (?)
[the same also in Schmundt's handwriting]

MBZ 04 16/5 1302—


Major Schmundt Armed Forces Adjutant to the Fuehrer—
Most Secret to message 1155 7, 17, 10, 24, 4, 14, 3, 18, 28, 8,
armored and mountain.
Zeitzler Oberstleutnant on the General Staff.

[ITEM 4] [Telegram]
MBZ 05 17/5 1505
TO MAJOR SCHMUNDT, ARMED FORCES ADJUTANT TO THE
FUEHRER—MOST SECRET
IN ANSWER TO OBERST LEUTNANT ZEITZLER AND WITH REGARD
TO MAP OF FORTIFICATIONS:
FORTIFIED CONSTRUCTION CONSISTS OF FAIRLY LARGE NUMBER
OF STEEL AND CONCRETE FORTIFICATIONS AS WELL AS LIGHT,
MEDIUM AND HEAVY MG EMPLACEMENTS TO CLOSE GAPS
BETWEEN FORTIFICATIONS. NUMBER OF STEEL AND CONCRETE
FORTIFICATIONS VARIES FROM ONE TO NINE PER KILOMETER.
POSITIONS CONSTRUCTED CONSIST OF LIGHT, MEDIUM AND
HEAVY MG EMPLACEMENTS AND AN OCCASIONAL STEEL AND
CONCRETE FORTIFICATION IN BETWEEN. NUMBER OF MG
EMPLACEMENTS VARIES FROM TWO TO NINE PER KILOMETER.
BLOCK CONSTRUCTION CONSISTS OF LIGHT, SOMETIMES MEDIUM
AND HEAVY MG EMPLACEMENTS AT MAIN ROADS AND
THOROUGHFARES. DEFENSIVE POTENTIALITIES: STEEL AND
CONCRETE FORTIFICATIONS BULLET PROOF AGAINST ALL KNOWN
CALIBRES. LIGHT MG EMPLACEMENTS BULLET PROOF AGAINST ALL
CALIBRES UP TO 10.5 CM., MEDIUM MG EMPLACEMENTS BULLET
PROOF AGAINST CALIBRES UP TO 10.5 CM., HEAVY MG
EMPLACEMENT BULLET PROOF AGAINST CALIBRES UP TO 21.00
CM., SOMETIMES AGAINST THE LARGEST CALIBRES.
ZEITZLER OBERSTLEUTNANT ON THE GENERAL STAFF

[ITEM 5] [Covering letter, with draft for Gruen attached]

MOST SECRET

Berlin, 20 May 1938


Tirpitzufer 72.76

Chief of the Supreme Command of the Armed Forces


L Ia No. 38/38 S.O. Only
S.O. Only
access only through Officer

Schm [initialled by Schmundt]

My Fuehrer!
Effective 1 October 1938 (beginning of the new mobilization year for
the army) new strategic directives must be issued, whose political
bases and stipulations you, my Fuehrer, yourself intend to make.
For the meantime, however, it is necessary that the "Gruen" section
of the strategic directives be replaced by a new version that takes
into account the situation which has arisen as a result of the
incorporation of Austria into the Reich and the newly-suspected
intentions of the Czech General Staff.
A draft of this kind is attached. It has not yet been discussed with
the Commanders in Chief. I intend to do this only after this draft in
its fundamental ideas has been approved by you my Fuehrer, so that
it can then be resubmitted to be signed.
Heil, my Fuehrer
[signed] Keitel

L Ia to No. 38/38 S.O. Only

written by an officer
MOST SECRET
S.O. Only
access only through officer

Berlin, 20 May 1938

DRAFT for THE NEW DIRECTIVE "GRUEN"


3 Copies
1st Copy
(Provisional)-[pencil note]
1. Political Prerequisites: It is not my intention to smash
Czechoslovakia without provocation, in the near future through
military action. Therefore inevitable political developments within
Czechoslovakia must force the issue, or political events in Europe
create an especially favorable opportunity and one which may never
come again.
2. Political Possibilities for the Commencement of the Action: An
invasion without suitable obvious cause and without sufficient
political justification cannot be considered with reference to the
possible consequences of such an action in the present situation.
Rather will the action be initiated either:
a. after a period of increasing diplomatic clashes and tension, which
is coupled with military preparations and is made use of to push the
war-guilt onto the enemy. Even such a period of tension preceding
the war however will terminate in sudden military action on our part,
which must come with all possible surprise as to time and extent, or
b. by lightning-swift action as a result of a serious incident, through
which Germany is provoked in an unbearable way and for which at
least part of the world opinion will grant the moral justification of
military action.
"b" is militarily and politically the more favorable.
3. Conclusions for the Preparations of "Fall Gruen"; which must take
into account the possibilities mentioned in 2 a and 2 b.
a. For Armed War it is essential to create—already in the first 4 days
—a military situation which plainly proves to hostile nations eager to
intervene, the hopelessness of the Czechoslovakian military
situation, and gives the nations with territorial claims on
Czechoslovakia an incentive to immediate intervention against
Czechoslovakia. In such a case the intervention of Poland and
Hungary against Czechoslovakia can be expected, especially if
France, due to Italy's clearly pro-German attitude fears, or at least
hesitates, to unleash a European war by her intervention against
Germany.
It is very probable that attempts by Russia to give military support to
Czechoslovakia are to be expected. If concrete successes are not
achieved as a result of the ground operations during the first few
days, a European crisis will certainly arise.
b. The Propaganda War must, on one hand, intimidate
Czechoslovakia by threats and reduce her power of resistance, on
the other hand, give instructions to the national minorities for
supporting the Armed War and influence the neutrals into our way of
thinking.
c. The Economic War has the task of employing all means at the
disposal of economy to hasten the final collapse of Czechoslovakia.
The opening of the Economic and Propaganda war can precede the
Armed war. I myself will determine the date.
Z
[initialled at end by Zeitzler]
[Paragraphs 4, 5, and 6 of this draft are set forth with minor
changes under ITEM 11.]

[ITEM 6] [Typescript]

Questions on "Gruen"
1. Peace-time strength of divisions prepared for march readiness.
2. Strength of mobile divisions.
3. Composition of 2nd Armored Division in the case of mobilization.
4. Strength, possibilities and composition of a motorized unit
(motorized divisions) to be used for independent thrust.
5. When can the field units be equipped with 15 cm. mortars?
6. What calibres and how large a number of artillery pieces are
available for combating fortifications such as fortresses?

MOST SECRET

L Ia

Berlin, 23 May

Questionnaire of 23 May
1. Peace-time strength of divisions prepared for march readiness.
Strength of a peacetime division 14,000 men
Strength of a division made ready to march 14,000 men
(but composition is different from that of a peacetime division, i.e.
some men are left out and others included).
2. Strength of mobile divisions.
Strength of a mobile division 17,000 men
3. Composition of the 2nd Armored Division in the case of
Mobilization. In the case of mobilization the 2nd Armored Division is
composed of 1 rifle brigade, one tank brigade and divisional troops.
The rifle brigade has one Infantry regiment motorized of 2 battalions
and one motorcycle rifle battalion.
The tank brigade has two tank regiments of two battalions.
The Divisional Troops will include 1 Artillery Regiment motorized of 2
light Battalions, 1 Reconnaissance Battalion motorized, 1 Anti-Tank
Battalion, 1 Engineer Battalion motorized, and 1 Signal Battalion
motorized.
Altogether the 2nd Armored Division (mobile) has 807 light Machine
guns, 250 heavy Machine guns, 18 light mortars, 12 heavy mortars,
8 light Infantry howitzers, 48 Anti-Tank guns, 122 2 cm. guns, 16 37
cm. guns, 16 7.5 cm. guns and 24 light field howitzers.
4. Strength, possibilities and composition of a motorized unit
(motorized divisions) for independent thrust. In the case of
mobilization, C-in-C Army is in command of the motorized units. C-
in-C Army must therefore be questioned as regards any new
employment.
Altogether the 1st, 2nd and 3rd Armored Divisions (rapid march
readiness is intended) 4 motorized divisions and the light division
(for the moment not yet intended for rapid march readiness;
presumably from 1 October).
5. When can the field units be equipped with 15 cm. mortars?
Mobilization of the infantry guns (= 15 cm. mortars) planned only for
the fall, as ammunition for them will only then be available. For
training purposes nearly all corps except the 3 corps have the heavy
infantry guns at the moment without live ammunition, however.
6. What calibres and how large a number of artillery pieces are
available for combatting fortifications such as fortresses? Only 21
cm. howitzers. Altogether 23 (of which 8 are in East Prussia) with
16,000 rounds (of which 4,000 in East Prussia).
[In Schmundt writing]: In general, single experimental artillery piece
(guns).
Z
[Initialled by Zeitzler]
[On next page the questions are put again, plus the following
additional questions:]
7. What do the individual types of Czechoslovakian permanent
frontier fortifications look like? Profile?
8. Is cooperation between infantry and bombers assured for attacks
against enemy strong points etc.?
9. Can the construction of fortifications in the West, in the form of
MG strong points and road blocks, be hastened by the employment
of work columns of the Inspector of Road Construction?
10. What progress has been made in the howitzer (Moerser)
programme? What progress has been made in the conversion of
heavy naval guns?

[Next three pages contain the first 6 questions above and answers
to them in a teleprint message, beginning: "I am answering several
questions which the Fuehrer put to me during conferences. I request
that you report the answers to the Fuehrer."]

[ITEM 8] [Telegram]
1. INFORM GENERAL KEITEL: THE FUEHRER IS GOING INTO
"GRUEN" IN DETAIL. BASIC IDEAS NOT CHANGED. SURPRISE
ELEMENT TO BE EMPHASIZED MORE. CONFERENCE WITH
PARTICIPANTS WILL TAKE PLACE AFTER RETURN, AT THE LATEST.
CONFERENCE HERE NOT OUT OF THE QUESTION. RETURN
PROBABLY BEGINNING NEXT WEEK.
2. INFORM COLONEL GENERAL VON BRAUCHITSCH AND GENERAL
KEITEL:

You might also like