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

Download Full Python for the Busy Java Developer: The Language, Syntax, and Ecosystem 1st Edition Deepak Sarda (Auth.) PDF All Chapters

Deepak

Uploaded by

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

Download Full Python for the Busy Java Developer: The Language, Syntax, and Ecosystem 1st Edition Deepak Sarda (Auth.) PDF All Chapters

Deepak

Uploaded by

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

Download the Full Version of textbook for Fast Typing at textbookfull.

com

Python for the Busy Java Developer: The Language,


Syntax, and Ecosystem 1st Edition Deepak Sarda
(Auth.)

https://textbookfull.com/product/python-for-the-busy-java-
developer-the-language-syntax-and-ecosystem-1st-edition-
deepak-sarda-auth/

OR CLICK BUTTON

DOWNLOAD NOW

Download More textbook Instantly Today - Get Yours Now at textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Biota Grow 2C gather 2C cook Loucas

https://textbookfull.com/product/biota-grow-2c-gather-2c-cook-loucas/

textboxfull.com

Microorganisms for Green Revolution Volume 2 Microbes for


Sustainable Agro ecosystem 1st Edition Deepak G. Panpatte

https://textbookfull.com/product/microorganisms-for-green-revolution-
volume-2-microbes-for-sustainable-agro-ecosystem-1st-edition-deepak-g-
panpatte/
textboxfull.com

Java EE Development with Eclipse 1st Edition Vohra Deepak

https://textbookfull.com/product/java-ee-development-with-eclipse-1st-
edition-vohra-deepak/

textboxfull.com

Java quick syntax reference Second Edition Olsson

https://textbookfull.com/product/java-quick-syntax-reference-second-
edition-olsson/

textboxfull.com
Haskell Quick Syntax Reference: A Pocket Guide to the
Language, APIs, and Library 1st Edition Stefania Loredana
Nita
https://textbookfull.com/product/haskell-quick-syntax-reference-a-
pocket-guide-to-the-language-apis-and-library-1st-edition-stefania-
loredana-nita/
textboxfull.com

C++17 quick syntax reference: apocket guide to the


language, apis and library 2 edition Edition Olsson

https://textbookfull.com/product/c17-quick-syntax-reference-apocket-
guide-to-the-language-apis-and-library-2-edition-edition-olsson/

textboxfull.com

C++17 quick syntax reference: a pocket guide to the


language, APIs and library Third Edition Olsson

https://textbookfull.com/product/c17-quick-syntax-reference-a-pocket-
guide-to-the-language-apis-and-library-third-edition-olsson/

textboxfull.com

C# 7 Quick Syntax Reference: A Pocket Guide to the


Language, APIs, and Library Mikael Olsson

https://textbookfull.com/product/c-7-quick-syntax-reference-a-pocket-
guide-to-the-language-apis-and-library-mikael-olsson/

textboxfull.com

Python Natural Language Processing Advanced machine


learning and deep learning techniques for natural language
processing 1st Edition Jalaj Thanaki
https://textbookfull.com/product/python-natural-language-processing-
advanced-machine-learning-and-deep-learning-techniques-for-natural-
language-processing-1st-edition-jalaj-thanaki/
textboxfull.com
Python for
the Busy Java
Developer
The Language, Syntax, and
Ecosystem

Deepak Sarda
Python for the Busy
Java Developer
The Language, Syntax, and
Ecosystem

Deepak Sarda
Python for the Busy Java Developer
Deepak Sarda
Singapore, Singapore

ISBN-13 (pbk): 978-1-4842-3233-0 ISBN-13 (electronic): 978-1-4842-3234-7


https://doi.org/10.1007/978-1-4842-3234-7
Library of Congress Control Number: 2017960940
Copyright © 2017 by Deepak Sarda
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or
part of the material is concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way,
and transmission or information storage and retrieval, electronic adaptation, computer software,
or by similar or dissimilar methodology now known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark
symbol with every occurrence of a trademarked name, logo, or image we use the names, logos,
and images only in an editorial fashion and to the benefit of the trademark owner, with no
intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if
they are not identified as such, is not to be taken as an expression of opinion as to whether or not
they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of
publication, neither the authors nor the editors nor the publisher can accept any legal
responsibility for any errors or omissions that may be made. The publisher makes no warranty,
express or implied, with respect to the material contained herein.
Cover image designed by Freepik
Managing Director: Welmoed Spahr
Editorial Director: Todd Green
Acquisitions Editor: Todd Green
Development Editor: James Markham
Technical Reviewer: Chaim Krause
Coordinating Editor: Jill Balzano
Copy Editor: Kim Burton weisman
Compositor: SPi Global
Indexer: SPi Global
Artist: SPi Global
Distributed to the book trade worldwide by Springer Science+Business Media New York,
233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505,
e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a
California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc
(SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail rights@apress.com, or visit http://www.apress.
com/rights-permissions.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook
versions and licenses are also available for most titles. For more information, reference our Print
and eBook Bulk Sales web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available
to readers on GitHub via the book’s product page, located at www.apress.com/9781484232330.
For more detailed information, please visit http://www.apress.com/source-code.
Printed on acid-free paper
Table of Contents
About the Author����������������������������������������������������������������������������������v
About the Technical Reviewer������������������������������������������������������������vii
Acknowledgments�������������������������������������������������������������������������������ix
Introduction�����������������������������������������������������������������������������������������xi

Chapter 1: The Language������������������������������������������������������������������  1


What Is Python?������������������������������������������������������������������������������������������������  1
History���������������������������������������������������������������������������������������������������������������  3
Installation��������������������������������������������������������������������������������������������������������  5
Tools������������������������������������������������������������������������������������������������������������������  6
Summary���������������������������������������������������������������������������������������������������������� 12

Chapter 2: The Syntax���������������������������������������������������������������������� 13


Hello World�������������������������������������������������������������������������������������������������������� 13
Basic Constructs����������������������������������������������������������������������������������������������� 14
Basic Types������������������������������������������������������������������������������������������������������� 16
Numbers������������������������������������������������������������������������������������������������������ 16
Strings��������������������������������������������������������������������������������������������������������� 17
Collections��������������������������������������������������������������������������������������������������� 18
Fun with Lists���������������������������������������������������������������������������������������������������� 19
Functions���������������������������������������������������������������������������������������������������������� 25
Functions and Tuples����������������������������������������������������������������������������������� 29
Functions Inside Functions�������������������������������������������������������������������������� 31

iii
Table of Contents

Classes�������������������������������������������������������������������������������������������������������������� 34
Inheritance�������������������������������������������������������������������������������������������������� 37
Polymorphism���������������������������������������������������������������������������������������������� 38
Getting Dynamic!����������������������������������������������������������������������������������������� 39
Protocols����������������������������������������������������������������������������������������������������������� 42
Organizing Code������������������������������������������������������������������������������������������������ 45
Importing code�������������������������������������������������������������������������������������������� 45
The main() Method�������������������������������������������������������������������������������������� 48
Summary���������������������������������������������������������������������������������������������������������� 57

Chapter 3: The Ecosystem���������������������������������������������������������������� 59


A Rich Ecosystem��������������������������������������������������������������������������������������������� 59
Popular Tools����������������������������������������������������������������������������������������������� 60
Popular Frameworks����������������������������������������������������������������������������������� 62
Summary���������������������������������������������������������������������������������������������������������� 65

Chapter 4: The Zen of Python����������������������������������������������������������� 67


Appendix: References����������������������������������������������������������������������� 69
Index������������������������������������������������������������������������������������������������� 71

iv
About the Author
Deepak Sarda has been working as a software
developer for more than twelve years, in
multiple business domains and in a variety of
technologies. He has worked on several high-
performance, server-side applications written
in Java, and has done web development and
systems automation work in Python.
He lives in Singapore with his lovely wife
and their adorable daughters. He can be found
online at antrix.net or @antrix on Twitter.
He’d love to hear what you’ve to say about this book. Please email him
at deepak@antrix.net.

v
About the Technical Reviewer
Chaim Krause is an expert computer
programmer with over 30 years of experience
to prove it. He has worked as a lead tech
support engineer for ISPs as early as 1995,
as a senior developer support engineer with
Borland for Delphi, and has worked in Silicon
Valley for over a decade in various roles,
including technical support engineer and
developer support engineer. He is currently
a military simulation specialist for the US
Army’s Command and General Staff College, working on projects such as
developing serious games for use in training exercises.
He has also authored several video training courses on Linux topics
and has been a technical reviewer on more than 20 books, including
iOS Code Testing by Abhishek Mishra (Apress, 2017), Android Apps for
Absolute Beginners by Wallace Jackson (Apress, 2017), and C# and XML
Primer: XML Essentials for C# and .NET Development by Jonathan Hartwell
(Apress, 2017). It seems only natural that he would be an avid gamer
and have his own electronics lab and server room in his basement. He
currently resides in Leavenworth, Kansas, with his loving partner, Ivana,
and a menagerie of four-legged companions: their two dogs, Dasher and
Minnie, and their three cats, Pudems, Talyn, and Alaska.

vii
Acknowledgments
I’d always heard it being said, but only now do I truly realize it: writing a
book is hard work! It would have been harder still had it not been for the
support from my family and friends.
I wish to especially thank Hitesh Sarda, Rohit Sharma, and Srijith Nair
for the incredibly detailed and thoughtful feedback that they provided as I
wrote this book. I owe many thanks to them.
I must also acknowledge the constant encouragement that I received
from my wife, Sonika. I can’t thank her enough for her patience and
support as I took time out to write this book.

ix
Introduction
Hello There!
If you are reading this book, then chances are that you are a busy Java
developer who is interested in learning Python. If so, I hope that by the
time you are done reading this short book.

• You will have gained sufficient familiarity with the


Python language syntax so that you’re able to read
some code and understand what it is doing.

• You will have had enough orientation to be able to


navigate the Python ecosystem of libraries and tools.

This book is not for the beginner programmer. I assume that you
are comfortable programming in Java (or a similar language like C#),
and hence, I will not bore you with explanations of basic concepts like
variables, functions, and classes.

About the Book


This book is divided into three broad chapters:

• The Language

• The Syntax

• The Ecosystem

In the first chapter, we take a brief look at the Python language and
learn what it has to offer. Next, we’ll get down to the details of the syntax
before wrapping up with a look at the wider ecosystem surrounding the
Python language.
xi
CHAPTER 1

The Language
Let’s start our Python journey by first gaining an understanding of what
Python has to offer that’s different from Java. I’ll then help you get setup
with Python before we dive into the language’s syntax in the next chapter.

What Is Python?
Python is an “open source, general-purpose programming language that is
dynamic, strongly typed, object-oriented, functional, memory-managed,
and fun to use.” Those are a lot of adjectives for one sentence! Let’s unpack
them one at a time.
Python is distributed under an open source, BSD-style license called the
Python Software Foundation License Agreement. It is a very permissive
license that allows great flexibility in how Python can be used. Python’s
development is done in the open by a large and diverse community of
volunteers.
Python is general purpose in that you can use it to build a variety
of applications running the gamut from simple scripts and command-­
line tools to desktop and web applications, network servers, scientific
applications, and more.
We know that Java is a statically typed language; that is, the types are
checked and enforced at compile time. In contrast, Python is dynamic,
which means that the types are checked only at runtime. But Python is

© Deepak Sarda 2017 1


D. Sarda, Python for the Busy Java Developer, https://doi.org/10.1007/978-1-4842-3234-7_1
Chapter 1 The Language

also strongly typed, just like Java. You can only execute operations that are
supported by the target type.
Another way to think about this is that in Java, both variables and
objects have types associated with them; whereas in Python, only objects
have types, not the variables that they are bound to. In Java, when we
declare

MyType obj = new MyType()

The obj variable is declared of type MyType and then the newly
instantiated object of type MyType is assigned to it. In contrast, in Python,
the same declaration would read

obj = MyType()

Ignoring the missing new keyword (which Python doesn’t have), obj is
simply a name that is bound to the object on the right, which happens to
be of type MyType. We can even reassign obj in the very next line—obj =
MyOtherType()—and it wouldn’t be a problem. In Java, this reassignment
would fail to compile1 while in Python, the program will run and will only
fail at runtime if we try to execute an operation via obj that is incompatible
with the type assigned to it at that point in time.
Python is object oriented and supports all the standard OOP features
that Java has like creation of types using classes, encapsulation of state,
inheritance, polymorphism, and so forth. It even goes beyond Java and
supports features such as multiple inheritance, operator overloading,
meta-programming, and so forth.
Python also supports a rich set of functional programming features
and idioms. In Python, functions are first-class objects that can be created,
manipulated, and passed around just like any other object. While its
emphasis on functional programming might not be as focused as say

1
Unless MyOtherType happens to be a subclass of MyType.

2
Chapter 1 The Language

Clojure, Python certainly offers much more to the functional programmer


than Java.2
Another similarity between the languages is in terms of manual
memory management, in that there is none. The language runtime takes
care of correctly allocating and freeing up memory, saving the programmer
from the drudgery—and mistakes—of manually managing memory.
Having said that, the JVM garbage collectors are much, much better
performing than the Python GC. This can become a concern depending on
the type of application you are building.
Finally, and above all, Python is fun and a joy to use. This is a strong
claim to make but I hope that by the time you are done reading this book,
you’ll agree with me and the millions of other Python programmers out
there!

H
 istory
Python is the brainchild of a Dutch programmer named Guido van
Rossum. He started working on it when he got frustrated with the ABC
language in the late 1980s and after some years of private development,
he released the first version of Python in 1994. This actually makes
Python older than Java, the first version of which was released in 1996,
a full two years later! A comparison of the two languages is shown in
Table 1-1.

2
Even after the introduction of lambdas in Java 8.

3
Chapter 1 The Language

Table 1-1. Historical comparison of


Java and Python

Java Python

James Gosling Guido van Rossum


From C++/Oak From ABC
1.0 - Jan 1996 1.0 - Jan 1994
9.0 - Sep 2017 3.6 - Dec 2016
JSR PEP
Commercial Community

Note I’ll use this tabular format to compare and contrast Python
and Java whenever it makes sense.

Since then, the language has continued to refine and evolve, with
Python 2.0 being released in 2000. As of this writing, the 2.x versions are
the most widely deployed.
In version 3.0, the language designers decided to break backward
compatibility in order to clean up some of the accumulated language
warts. Although this has been good from a language perspective, it has
been a significant hindrance to those upgrading from 2.x to 3.x. Imagine
if Sun had decided to introduce generics in Java 5 without type erasure,
thus breaking backward compatibility. The Java language would’ve been
much nicer today but the transition period would’ve been difficult, to say
the least. That is the kind of transition the Python user community is going
through right now.

4
Chapter 1 The Language

Note Since 2.x is still the most widely used version of Python,
this book will cover Python 2.x features and syntax, calling out any
differences with 3.x from time to time.

From the outset, Python’s development has been done in the open
with a community of volunteers contributing to the language and the core
libraries. Any language changes are proposed and discussed through a
process called PEP (Python Enhancement Proposals), with Guido having
final say in deciding the outcome. For his stewardship and continuous
involvement in the development of Python, Guido is affectionately called
the “Benevolent Dictator For Life.” He also periodically writes a Python
History blog3 chronicling the evolution of various language features.

I nstallation
This book is full of example code, and the best way to follow along is to
actually try these examples by yourself. To do this, you’ll obviously need to
install Python on your system. But an easier way is to check if you already
have access to a system with Python installed! Almost all systems running
Linux should have Python preinstalled. Recent versions of Mac OS X also
come with Python preinstalled. Just open a command shell on either of
these two systems and type in python. If you get a Python shell prompt,
you are all set! The version of Python installed may be a bit outdated but it
should be sufficient to get started.

3
http://python-history.blogspot.com/

5
Chapter 1 The Language

Tip As a lightweight alternative, you can try an online Python


environment, such as http://repl.it/. The examples in this book
are all simple enough to work there.

T ools
Python source code is organized in files with a .py extension. The python
executable interprets the source code and translates it into a Python
language–specific bytecode that is stored in .pyc files. This bytecode is
then executed by the Python virtual machine, which is also invoked by the
same python executable. Although this sounds like two steps, in reality, it
is just one step with the bytecode generation happening on the fly.
This is in contrast to Java (see Table 1-2), where the responsibilities for
the parsing and compilation of source code and the actual execution of
the compiled bytecode are split between javac and java respectively. In
Python, the python executable handles both steps. In fact, .pyc files are,
in effect, just intermediate caches to hold the translated bytecode. They
are not strictly necessary for execution. If you deleted the .pyc files, they’d
simply be regenerated the next time you ran the .py files.

Table 1-2. Comparison of Tools


Java Python

.java .py
.class .pyc
Java.exe + javac.exe python.exe
IntelliJ IDEA PyCharm
Eclipse JDT PyDev
Java 9 JShell REPL

6
Chapter 1 The Language

There are multiple IDEs available for writing Python code. PyDev,
based on the Eclipse framework, and PyCharm, based on the IntelliJ IDEA
framework, are two of the more popular choices. While having an IDE is
nice, it is perfectly feasible to write Python code using a plain text editor
such as Vim4 or Sublime Text.
One interesting feature of Python that’s missing in Java is the REPL,
short for Read Eval Print Loop. A quick demo would be useful here. If
you’ve got access to a Python installation (follow the instructions in the
“Installation” section of this chapter), go ahead and launch a python shell,
as follows:

antrix@dungeon:~$ python
Python 2.7.5+ (default, Feb 27 2014, 19:39:55)
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more
information.
>>>

When you run the python executable in this manner, it starts up in


an interactive mode. The first few lines contain information such as the
version and the underlying operating system. After that, you are presented
with the >>> prompt. This is where all your interaction with Python will
occur. The python shell is running a loop, which will read everything that
you type in at this prompt, evaluate what it has read, and then print the
result. Thus the name, REPL.
Let’s try it out:

>>> 10 + 10
20
>>>

4
Yes, Emacs is fine too.

7
Chapter 1 The Language

We typed in 10 + 10 at the prompt and hit the Enter key. The Python
REPL read this value, evaluated it, and printed the result. Then it went back
to the prompt to wait for our next input. Let’s try the following variable
assignment:

>>> x = 10
>>>

In this case, we didn’t see any output because what we entered was just
a statement, not an expression. But it did modify the state of the python
shell. If we query for x again, we’ll find this:

>>> x = 10
>>> x
10
>>>

Let’s call one of the built-in functions named help.

>>> help(x)

Help on int object:


class int(object)
|  int(x=0) -> int or long
|  int(x, base=10) -> int or long
|
|  Convert a number or string to an integer, or return 0 if no
arguments are given
:q

>>>

Calling help on any object brings up a paged view of what is,


effectively, the Javadoc for the object’s class. To exit the help view, just type
q at the : prompt and you’ll be back at the >>> prompt.

8
Chapter 1 The Language

The full documentation view for an object can be quite verbose. If you
just want a quick overview of what attributes an object supports, use the
dir function.

>>> dir(x)

['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__


coerce__', '__delattr__', '__div__', '__divmod__', '__doc__',
'__float__', '__floordiv__', '__format__', '__getattribute__',
'__getnewargs__', '__hash__', '__hex__', '__index__', '__
init__', '__int__', '__invert__', '__long__', '__lshift__',
'__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__
oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__',
'__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__
repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__',
'__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__',
'__rtruediv__', '__rxor__', '__setattr__', '__sizeof__',
'__str__', '__sub__', '__subclasshook__', '__truediv__', '__
trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator',
'imag', 'numerator', 'real']

>>>

Ignoring the funky double-underscores for now, what dir(x) returned


is effectively a directory of all the attributes available on the object. You can
access any of them using the . (dot) syntax.

>>> x.numerator
10
>>> x.denominator
1
>>> x.conjugate
<built-in method conjugate of int object at 0x9e9a274>

9
Chapter 1 The Language

>>> x.conjugate()
10

You can also use the dir() function without any argument to get a list
of built-ins.

>>> dir()

['__builtins__', '__doc__', '__name__', '__package__']

>>> dir(__builtins__)

['ArithmeticError', 'AssertionError', 'AttributeError',


'BaseException', 'BufferError', 'BytesWarning',
'DeprecationWarning', 'EOFError', 'Ellipsis',
'EnvironmentError', 'Exception', 'False', 'FloatingPointError',
'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError',
'ImportWarning', 'IndentationError', 'IndexError', 'KeyError',
'KeyboardInterrupt', 'LookupError', 'MemoryError',
'NameError', 'None', 'NotImplemented', 'NotImplementedError',
'OSError', 'OverflowError', 'PendingDeprecationWarning',
'ReferenceError'ror', 'RuntimeError', 'RuntimeWarning',
'StandardError', 'StopIteration', 'SyntaxError',
'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError',
'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',
'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',
'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning',
'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__',
'__name__', '__package__', 'abs', 'all', 'any', 'apply',
'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes',
'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile',
'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir',
'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file',

10
Chapter 1 The Language

'filter', 'float', 'format', 'frozenset', 'getattr', 'globals',


'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int',
'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license',
'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min',
'next', 'object', 'oct', 'open', 'ord', 'pow', 'print',
'property', 'quit', 'range', 'raw_input', 'reduce', 'reload',
'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple',
'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']

>>>

This gives a list of functions and other objects that are built-in and do
not have to be imported from other packages. This is analogous to how
everything defined in the java.lang package is available everywhere in
Java without having to explicitly import it.

Tip The dir and help functions are extremely useful when doing
exploratory development in a Python interactive shell.

There’s one last thing I wish to show before we wrap up this section.
Let’s create a new file named hello.py with the following contents:

print "Hello There!"


x = 10 + 10
print "The value of x is", x

Now execute python, passing in this file as an argument:

antrix@dungeon:~$ python hello.py


Hello There!
The value of x is 20
antrix@dungeon:~$

11
Chapter 1 The Language

This is more along the lines of a traditional development process: write


code in a file and then execute that file. This also demonstrates how the
python executable combines the role of javac and java in one process.
With that brief demo of Python, we are ready to explore the language’s
syntax.

Summary
In this chapter, we learned that Python is not just a scripting language but a
general-purpose programming language with a long history behind it. We
then got familiar with the python executable, the Python counterpart of the
java and javac executables.
We also looked at the Python REPL environment, which is a great way
to interactively try out Python. If you still don’t have the REPL set up, I urge
you to do so now because the next chapter makes extensive use of it as we
dive into the nitty-gritty details of the language’s syntax!

12
CHAPTER 2

The Syntax
This chapter is the heart of the book. It is a deep dive into Python language
features. I explain them using short code fragments that you can easily try
out yourself.
We start by introducing the basic data types and built-in collections
such as dictionaries and sets, with a special emphasis on lists. We’ll then
dive into functions and discover their power as a first-class language
feature.
Moving on to classes, we’ll find out how flexible Python is as an
object-oriented language, especially compared to Java. We’ll then explore
protocols, which extend the language’s syntax to your own types.
Finally, we’ll discuss the concepts of modules and packages as a means
of organizing Python code.
As you can see, it is going to be a long chapter. So grab some coffee and
let’s get started!

H
 ello World
>>> print "Hello World"
Hello World
>>>

Well, that was easy! Moving on …

© Deepak Sarda 2017 13


D. Sarda, Python for the Busy Java Developer, https://doi.org/10.1007/978-1-4842-3234-7_2
Chapter 2 The Syntax

Tip In Python 3, the print keyword has been replaced with the
print() function.

Basic Constructs
Here’s a bit of Python code that, well, I don’t have to tell you what it
does, do I? Most Python code is like this: eminently readable and almost
pseudo-code-like.

>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]                     ①


>>> odd_numbers = []                                          ②
>>>
>>> # What are the odds?                                      ③
>>> for num in numbers:                                       ④
...   if num % 2 != 0:                                        ⑤
...     odd_numbers.append(num)                               ⑥
...
>>> print "the odd numbers are:", odd_numbers                 ⑦
the odd numbers are: [1, 3, 5, 7, 9]
>>>

You must have noticed a few things, such as the lack of semicolons as
statement separators. Let’s work through this code one line at a time to see
what else is new and different compared to Java.

1. In the first line, we are declaring a list of numbers.


Lists are one of the built-in data structures in
Python, along with tuples, dicts, and sets. Notice that
we didn’t declare any types nor did we use any new
keyword to allocate the list.

14
Chapter 2 The Syntax

2. Next, we declare another list, named odd_numbers,


which is initialized empty.

3. Moving further down, we find a comment starting


with the # token. Comments extend to the end of
line, just like they do in Java with the // token.

4. Here, we come upon a for loop, which should


remind you of a more English version of Java’s
foreach loop. Block scopes, like in this for loop or
the if conditional in the next line, are denoted using
indentation instead of curly ({..}) braces. Using just
whitespace indentation to define blocks may sound
weird and even prone to errors! But just give it a
chance and you’ll find it to quickly become second
nature. Note that the Python REPL uses ellipsis (...)
to indicate a block scope, you don’t type the ellipsis.
The next three lines start with an ellipsis, which is
the scope of this for loop.

5. On this line is an if statement that is quite similar to


Java, except for the lack of parentheses. Parentheses
around for and if conditional expressions are
optional. Include them only when they add clarity.
Apart from the for and if constructs shown here,
Python also has elif, while, and so forth.

6. Here, we append the current loop number to the


odd_numbers list. The list, like almost everything in
Python, is an object that supports several operations
on it, including the append operation.

7. Finally, we print the results to console. No more


typing of the decidedly more verbose System.out.
println!

15
Chapter 2 The Syntax

Caution Never mix tabs and whitespaces in Python source code.


While you can use either tabs or whitespace to denote indentation,
mixing the two in the same source file may lead to parsing errors.
My recommendation: just don’t use tabs and stick to spaces. Set your
text editor to insert four space characters per tab.

Basic Types
Some of the basic data types in Python are numbers, strings, and
collections.

Numbers
Numbers come in the following variety.

Type Example value

int 1000
long 1000L
float 1000.12
complex 1000 + 12j

Although int and long are different data types, in practice, you only
need to worry about them when declaring literal values; that is, literal
longs need to be declared with a L suffix. During arithmetic operations,
Python automatically converts int values to long values as needed. This
also prevents overflow-related bugs.

Note In Python 3, there’s no distinction between int and long;


there’s only one arbitrary length integer type.

16
Chapter 2 The Syntax

Strings
As in Java, strings are immutable in Python. String values can be wrapped
in either single or double quotes. To differentiate between vanilla ASCII
strings and Unicode strings, Python uses the u prefix to denote the latter.
Unicode strings provide additional operations related to encoding/
decoding from various character sets.

Type Example value

str 'apple'
unicode u'äþþĺė'
str r'C:\temp'

A third type of string is the raw string denoted by the r prefix. This is
just an indication to the Python parser to not apply any backslash escaping
rules to the string. Here’s a quick example that illustrates the difference.

>>> print 'c:\temp\dir'        ①


c:      emp\dir
>>> print 'c:\\temp\dir'       ②
c:\temp\dir
>>> print r'c:\temp\dir'       ③
c:\temp\dir
>>>

1. The \t is interpreted as the tab character, resulting


in a tab being printed.

2. Escaping the \t with an additional backslash helps,


but makes the string harder to read.

3. Now the \t is left as-is since the r prefix is used to


mark the string as a raw string.

17
Chapter 2 The Syntax

As you can imagine, raw strings are extremely useful when denoting
file system paths or regular expressions.

Note In Python 3, all strings are unicode by default. Strings


without encoding are treated as bytes without any text semantics.

Collections
The built-in Python collections come in four varieties.

Collection Type Java Equivalent Example Value

list java.util.ArrayList ['apple', 'ball', 'ball']


tuple java.util.ArrayList ('apple', 'ball', 'ball')
dict java.util.HashMap {'fruit': 'apple', 'toy':
'ball'}
set java.util.HashSet {'apple', 'ball'}

Each of these collection types provides several useful operations, such


as sort, subsequence, and so forth. Another key property is that all these
data types are heterogeneous and can host values of differing data types.
Think Collection<Object> and not Collection<T>.

Tip While tuple and list may look similar, the distinction is that
a tuple is immutable.

Having these basic collections built into the language syntax is


immensely useful. It makes a lot of day-to-day code quite succinct without
the overhead of importing collection APIs and their associated baggage.

18
Chapter 2 The Syntax

Fun with Lists


Lists are the workhorse data structure in Python and I exaggerate only
slightly when I say that mastering them is the key to mastering Python!
Although earlier I said that they are like java.util.ArrayList, they
are truly much more than that. But first, let’s look at a short example
demonstrating their use as a basic array.

>>> numbers = [0, 1, 2, 'three', 4, 5, 6, 7, 8, 9]    ①


>>> numbers[0]                                        ②
0
>>> numbers[-1]                                       ③
9

1. The first thing to note is that the numbers list is not


homogeneous and can host values of different types,
be it numbers, strings, other objects or even other lists!

2. The individual element access is using the well-


known array index syntax: L[index].

3. Python allows passing in a negative value for the


index, in which case, it adds the length of the list to
the index and returns the corresponding element.

Apart from single element access, what sets apart Python lists is the
ability to extract element ranges from lists. This is accomplished using the
slice syntax. Here’s how.

>>> numbers[0:4]               ①
[0, 1, 2, 'three']

>>> numbers[:4]                ②
[0, 1, 2, 'three']

19
Chapter 2 The Syntax

>>> numbers[4:]                    ③
[4, 5, 6, 7, 8, 9]

>>> numbers[2:-2]                  ④
[2, 'three', 4, 5, 6, 7]

>>> numbers[0:9:2]                 ⑤
[0, 2, 4, 6, 8]

>>> numbers[::2]                   ⑥
[0, 2, 4, 6, 8]

>>> numbers[::-1]                  ⑦
[9, 8, 7, 6, 5, 4, 'three', 2, 1, 0]

1. The slice syntax—L[start:stop]—returns a


subsequence of the list as a new list.

2. The start index is optional and when omitted,


defaults to 0.

3. The stop index is also optional and defaults to the


length of the list.

4. A negative stop index counts off from the end, in


accordance with the rule described for line 3 of this
code example.

5. The full slice syntax is actually L[start:stop:step]


where the step, when omitted, defaults to 1. Here, we
set it to 2 and it skips every other element of the list.

6. Another example showing default values for start


and stop.

7. A negative step reverses the direction of iteration.

20
Exploring the Variety of Random
Documents with Different Content
just so will the most highly trained men in the future outdistance all
others in endurance.
Navy. We now come to the consideration of the Navy. The Navy
will use gas both in its guns and in smoke clouds, and in some form
of candle that will float. The toxic smokes that in high enough
concentrations will kill are extraordinarily irritating in minute
quantities—so minute they cannot be seen or felt for a few moments.
Every human being on a ship must breathe every minute just as
every human being everywhere must breathe every minute or die. A
gas that gets into the ventilating system of a ship will go all through it
and the Navy realizes it.
The Navy is studying how to keep the gas out of their own ships,
and how to get it into the enemy’s ships. The toxic smokes may be
dropped from aeroplanes or turned loose from under water by
submarines. In either case they will give off smokes over wide areas
through which ships must pass. Any defects will let these toxic
smokes in and will force every man to wear a mask. Aeroplane
bombs will come raining down on the ship or alongside of it either
with toxic smokes or other terrible gases. White phosphorus that
burns and cannot be put out wet or dry will be rained on ships. Yes,
chemical warfare materials will be used by the Navy.
Gas Against Landing Parties. The use of gas against landing
parties or to aid landing parties has come up in many ways. Our
studies to date indicate that gas is a greater advantage to the
defense against landing parties than to the offense. Mustard gas and
the like may be sprinkled from aeroplanes, and while it will not float
long on the water, it will float long enough to smear any small boats
attempting to land. It can be sprinkled over all the areas that landing
parties must occupy. Mustard gas may be placed in bombs or drums
around all areas that are apt to be used as landing places and
exploded in the face of advancing troops.
Storing Reserve Gases in Peace. And a word here about how
long gases may be stored. One of the statements made by
opponents of chemical warfare was that gas is a purely war time
project and could not be stored up in peace. We have today at
Edgewood Arsenal some 1,400 tons of poisonous gases not
including chlorine. Those gases have been manufactured, practically
every ounce of them, for three years, and are yet in almost perfect
condition. Our chemists believe they can be kept in the future for ten
years and perhaps longer. Our gas shells then will have the life
almost of a modern battleship, while the cost of a million will be but a
fraction of the cost of a battleship. What I have just said applies
particularly to liquid gases such as phosgene, chlorpicrin, and
mustard gas. We know that many of the solids may be kept for far
longer periods.
Storing Gas Masks. Our masks, too, we believe can be kept for
at least ten years. Experience to date indicates that rubber
deteriorates mainly through the action of sunlight and moisture that
cause oxidation or other change in the crystalline structure of cured
rubber. Accordingly, we are putting up masks today in hermetically
sealed boxes. It is thus evident that we can store a reserve of masks
and gases in peace the same as other war materials.
Use of Gas by Gas Troops. Now we come to the use of gas by
special gas troops. In the war, Gas Troops used 4-inch Stokes’
mortars and 8-inch Livens’ projectors and in a very short time would
have used a new portable cylinder for setting off cloud gas, using
liquid gases, such as phosgene. They will use these same weapons
in future wars. All of these are short-range weapons, but since the
Livens’ bomb or drum contains 50 per cent of its weight in gas while
the artillery shell contains 10 per cent, they have an efficiency away
beyond that of artillery or any other method of discharging gas
except cloud gas. They will, therefore, produce more casualties than
any other method known for the amount of material taken to the
front. These short-range weapons were developed by the British for
trench use and not for open warfare, and yet our troops developed
methods with the Stokes’ mortars that enabled them to keep up with
many of the Infantry divisions.
Phosphorus and Thermit Against Machine Gun Nests. The
use of phosphorus and thermit against German machine gun nests
by the Gas Troops is well known. How effective it was is not known
to so many. Phosphorus and thermit were so used from the early
days of the Marne fight in the latter part of July, 1918, to the very
close of the war. There is no recorded instance where the Gas
Troops failed to silence machine gun nests once the machine guns
were located. In the future Gas Troops will put off the majority of all
cloud gas attacks even with toxic smoke candles.
Necessity for Training in Peace. This is an outline of the
subject of chemical warfare. As stated in the beginning, the
fundamental underlying principles for the successful use of
poisonous gas is necessarily the same as for any other war
materials. The necessity for continuous training in peace is just the
same with chemical warfare as with the rifle, the machine gun, with
field artillery or any other weapon of war. Indeed it is more so
because the use of gas is so perfectly adaptable to night work. Men
must be taught to take precautionary measures when so sleepy, tired
and worn out that they will sleep through the roar of artillery.
How Chemical Warfare Should be Considered. We ask you
only to look at the use of chemical warfare materials as you look at
the use of the artillery, infantry, cavalry, tanks or aeroplanes.
Measure its possible future use; not simply by its use in the World
War, but by considering all possible developments of the future.
Remember that its use was barely four years old when the war
closed, while the machine gun, the latest type of infantry weapon,
had been known for more than one-third of a century. Chemical
warfare developments are in the infant stage. Even those on the
inside of chemical warfare when the Armistice was signed can see
today things that are certain to come that were undreamed of at that
time. This is bound to be so with a new weapon.
To sum up, gas is a universal weapon, applicable to every arm
and every sort of action. Since we can choose gases that are either
liquid or solid, that are irritating only or highly poisonous, that are
visible or invisible, that persist for days or that pass with the wind, we
have a weapon applicable to every act of war and for that matter, to
every act of peace. But we must plan its use, remembering there is
no middle ground in war, it is success or failure, life or death.
Remember also that training outruns production in a great war, that
5,000,000 men can be raised and trained before they can be
equipped unless we with proper foresight build up our essential
industries, keep up our reserve of supplies, and above all, keep such
perfect plans that we can turn all the wheels of peace into the wings
of war on a moment’s notice.
CHAPTER XXIII
THE OFFENSIVE USE OF GAS

What Chemical Warfare Includes


Chemical Warfare includes all gas, smoke and incendiary
materials and all defensive appliances, of which the mask is the
principal item, used by the Army. Some of the items or materials in
both offense and defense are used by the entire Army, while a few
are used only by Chemical Warfare troops.

The Term “Gas”


The term “gas” is now taken to include all materials that are
carried to the enemy by the air, after their liberation from cylinders,
bombs or shell. It is necessary that this broad use of the term “gas”
be thoroughly understood, because some of these materials are
solids, while all others are liquids, until liberated from the containers
at the time of the attack. These containers may be special cylinders
for cloud gas attacks, special bombs for Livens’ projectors and
mortars, or artillery shell, and even aviation bombs. Some of the
liquids which have a very low boiling point volatilize quickly upon
exposure to air, and hence require only enough explosive to open
the shell and allow the liquid to escape. Practically all solids have to
be pulverized by a large amount of high explosive, or driven off as
smoke by some heating mixture.

Technical Nature
Chemical warfare, besides being the newest, is the most
technical and most highly specialized Service under the War
Department. There is no class of people in civil life, and no officers
or men in the War Department, who can take up chemical warfare
successfully until they have received training in its use. This applies
not only to the use of materials in attack, but to the use of materials
for defense. Ten years from now perhaps this will not be true. It is
certainly hoped that it will not be. By that time the entire Army should
be pretty thoroughly trained in the general principles and many of the
special features of chemical warfare. If not, chemical warfare cannot
be used in the field with the efficiency and success with which it
deserves to be used. Furthermore, it is believed that within ten years
the knowledge of the gases used in chemical warfare will be so
common through the development of the use of these same
materials in civil life, that it will not be so difficult, as at the present
date, to get civilians who are acquainted with Chemical Warfare
Service materials.

Effectiveness of Gas
Chemical warfare materials were used during the war by
Chemical Warfare Service troops, by the Artillery and by the Infantry.
In the future the Air Service and Navy will be added to the above list.
Chemical warfare, even under the inelastic methods of the Germans,
proved one of the most powerful means of offense with which the
American troops had to contend. To realize its effectiveness we need
only remember that more than 27 out of every 100 casualties on the
field of battle were from gas alone. Unquestionably many of those
who died on the battlefield from other causes suffered also from gas.
No other single element of war, unless you call powder a basic
element, accounted for so many casualties among the American
troops. Indeed, it is believed that a greater number of casualties was
not inflicted by any other arm of the Service, unless possibly the
Infantry, and even in that case it would be necessary to account for
all injured by bullets, the bayonet, machine guns and hand grenades.
This is true, in spite of the fact that the German was so nearly
completely out of gas when the Americans began their offensive at
St. Mihiel and the Argonne, that practically no gas casualties
occurred during the St. Mihiel offensive, and only a very few until
after a week of the Argonne fighting. Furthermore, the Germans
knew that an extensive use of mustard gas against the American
lines on the day the attack was made, and also on the line that
marked the end of the first advance a few days later, would have
produced tremendous casualties. Judging from the results achieved
at other times by an extensive use of mustard gas, it is believed that
had the German possessed this gas and used it as he had used it a
few other times, American casualties in the Argonne would have
been doubled. In fact, the advance might even have been entirely
stopped, thus prolonging the war into the year 1919.

Humanity of Gas
A few words right here about the humanity of gas are not out of
place, notwithstanding the Army and the general public have now so
completely indorsed chemical warfare that it is believed the
argument of inhumanity has no weight whatever. There were three
great reasons why chemical warfare was first widely advertised
throughout the world as inhumane and horrible. These reasons may
be summed up as follows:
In the first place, the original gas used at Ypres in 1915 was
chlorine, and chlorine is one of a group of gases known as
suffocants—gases that cause death generally by suffocating the
patient through spasms of the epiglottis and throat. That is the most
agonizing effect produced by any gas.
The second reason was unpreparedness. The English had no
masks, no gas-proof dugouts, nor any of the other paraphernalia that
was later employed to protect against poisonous gas. Consequently,
the death rate in the first gas attack at Ypres was very high, probably
35 per cent. As a matter of fact, every man who was close to the
front line died. The only ones who escaped were those on the edges
of the cloud of gas or so far to the rear that the concentration had
decreased below the deadly point.
The third great reason was simply propaganda. It was good war
propaganda to impress upon everybody the fact that the German
was capable of using any means that he could develop in order to
win a victory. He had no respect for previous agreements or ideas
concerning warfare. This propaganda kept up the morale and
fighting spirit of the Allies, and was thoroughly justifiable upon that
score, even when it led to wild exaggeration.
The chlorine used in the first attack by the German is the least
poisonous of the gases now used. Those later introduced, such as
phosgene, mustard gas and diphenylchloroarsine are from five to ten
times as effective.
The measure of humanity for any form of warfare is the
percentage of deaths to the total number injured by the particular
method of warfare under consideration.
American Gas Casualties. The official list of casualties in battle
as compiled by the Surgeon General’s office covering all cases
reported up to September 1, 1919, is 258,338. Of these 70,752, or
27.4 per cent, were gas casualties. Also of the above casualties
46,519 resulted in death, of whom about 1,400 only were due to gas.
From these figures it is readily deduced that while 24.85 per cent of
all casualties from bullets and high explosives resulted in death, only
2 per cent of those wounded by gas resulted in death. That is, a man
wounded on the battle field with gas had twelve times as many
chances of recovery as the man who was wounded with bullets and
high explosives.

Fundamentals of Chemical Warfare


Before taking up in some detail the methods of projecting gas
upon the enemy, it is very desirable to understand the fundamentals
of chemical warfare, in so far as they pertain to poisonous gases.
Following the first use of pure chlorine all the principal nations
engaged in the war began investigations into a wide range of
substances in the hope of finding others more poisonous, more
easily produced, and more readily projected upon the enemy. These
investigations led to the use of a large number of gases which
seriously complicated manufacture, supply, and the actual use of the
gases in the field. Gradually a more rational conception of chemical
warfare led both the Allies and the enemy to restrict the numbers of
gases to a comparative few, and still later to divide all gases into
three groups. Thus the German divided his into three groups known
as (1) Green Cross, the highly poisonous non-persistent gases, (2)
Blue Cross, or diphenylchloroarsine, popularly known as sneezing
gas, and (3) Yellow Cross, highly persistent gases, such as mustard
gas. In the American Chemical Warfare Service we have finally
divided all gases into two primary groups. These groups are known
as “Non-persistent” and “Persistent.” The “Non-persistent” gases are
those quickly volatilizing upon exposure to the air, and hence those
that are carried away at once by air currents, or that in a dead calm
will be completely dissipated into the surrounding air in a few hours.
If sufficient high explosive be used to pulverize solids, they may be
used in the same way, and to a large extent certain highly persistent
liquid gases may have their persistency greatly reduced by using a
large amount of high explosive, which divides the liquid into a fine
spray. The “Persistent” group constitutes those gases that are very
slowly volatilized upon exposure to the atmosphere. The principal
ones of these now used or proposed are mustard gas and
bromobenzylcyanide. For purposes of economy, and hence
efficiency, certain gases, both persistent and non-persistent, are
placed in a third group known as the “Irritant Group.” These gases
are effective in extremely low concentrations against the lungs and
other air passages, or the eyes. Diphenylchloroarsine, and some
other solids when divided into minute particles by high explosive or
heat, irritate the nose, throat and lungs to such an extent in a
concentration of one part in ten millions of air as to be unbearable in
a few minutes. The tear gases are equally powerful in their effects on
the eyes. The irritating gases are used to force the wearing of the
mask, which in turn reduces the physical vigor and efficiency of the
troops. This reduction in efficiency, even with the best masks, is
probably 25 per cent for short periods, and much more if prolonged
wearing of the mask is forced.
Efficiency of Irritant Gases
One pound of the irritant gases is equal to 500 to 1,000 pounds
of other gases when forcing the wearing of the mask alone is
desired. The great economy resulting from their use is thus
apparent. Due to the rapid evaporation of the non-persistent gases
they are used generally only in dense clouds, whether those clouds
be produced from cylinders or from bombs. These gases are used
only for producing immediate casualties, as the necessary amount of
gas to force the enemy to constantly wear his mask by the use of
non-persistent gases alone could not possibly be taken to the front.
Mustard gas, which is highly persistent and also attacks the
lungs, eyes and skin of the body, may and will be used to force the
wearing of the mask. It has one disadvantage when it is desired to
force immediately the wearing of the mask, and that is its delayed
action and the fact that it acts so slowly, and is usually encountered
in such slight concentrations that several hours’ exposure are
necessary to produce a severe casualty. For these reasons the
enemy may often take chances in the heat of battle with mustard
gas, and while himself becoming a casualty, inflict quite heavy
casualties upon opposing troops by continuing to operate his guns or
rifles without masks. A powerful tear gas on the other hand forces
the immediate wearing of the mask.

Material of Chemical Warfare


Used by C. W. S. Troops
Chemical warfare troops, in making gas attacks, use cylinders for
the cloud or wave attack, and the Livens’ projector and the 4-inch
Stokes’ mortar for attacks with heavy concentrations of gas projected
by bombs with ranges up to a mile. This distance will in the future
probably be increased to 1½ or 1¾ miles. The original cylinders used
in wave attacks were heavy, cumbersome and very laborious to
install, and notwithstanding the wave attack was known to be the
deadliest form of gas attack used in the war, fell into disrepute after
the use of gas became general in artillery shells and in special
bombs.
Cloud Gas. The Americans at once concluded that since cloud
gas attacks were so effective, efforts should be made to make these
attacks of frequent occurrence by decreasing the weight of the
cylinders, and by increasing the portability and methods of
discharging the cylinders. As early as March, 1918, specifications for
cylinders weighing not more than 65 pounds, filled and completely
equipped for firing, were cabled to the United States. They would
have been used in large numbers in the campaign of 1919 had the
enemy not quit when he did. Toxic smoke candles that are filled with
solids driven off by heat will probably be the actual method in the
future for putting off cloud attacks. The toxic smoke candle is
perfectly safe under all conditions and can be made in any size
desired. Cloud gas attacks will be common in the future, and all
plans of defense must be made accordingly. They will usually be
made at night, when, due to fatigue and the natural sleepiness which
comes at that time, men are careless, lose their way, or neglect their
masks, and are thus caught unprepared. Experience in the war
proved that a wave attack always produced casualties even, as
several times occurred, when the enemy or the Allied troops knew
some hours beforehand that the attack was coming. The English
estimated these casualties to be 10 or 11 per cent of the troops
exposed.
Livens’ Projectors. The second most effective weapon for using
gas by gas troops was and will be the Livens’ projector. This
projector is nothing less than the simplest form of mortar, consisting
of a straight drawn steel tube and a steel base plate. As used during
the World War by the Allies it did not even have a firing pin or other
mechanism in the base, the electric wires for firing passing out
through the muzzle and alongside the drum or projectile which was
small enough to permit that method of firing. These were set by the
hundreds, very close behind or even in front of the front line
trenches. They were all fired at the same instant, or as nearly at the
same instant as watches could be synchronized, and firing batteries
operated. As discussed on 18 these mortars were emplaced deep
enough in the ground to bring their muzzles practically level with the
surface. It usually took several days to prepare the attack, and
consequently allowed an opportunity for the enemy to detect the
work by aeroplane photographs or by raids, and destroy the
emplacements by artillery fire. It should be added, however, that
notwithstanding this apparent great difficulty, very few attacks were
broken up in that way. Nevertheless, in line with the general policy of
the American troops to get away from anything that savored of
trench warfare, and to make the fighting as nearly continuous as
possible with every means available, the American Chemical
Warfare Service set at work at once to develop an easy method of
making projector attacks.
It was early found, that, if the excavation was made just deep
enough so that the base plate could be set at the proper angle, the
drums or projectiles were fired as accurately as when the projectors
or mortars were set so that the muzzles were level with the surface.
The time required to emplace a given number of mortars in this way
was only about one-fifth of that required for digging them completely
in.
Coupled of course with these proposed improvements in
methods, studies were being made and are still being made to
produce lighter mortars, better powder charges, and better gas
checks in order to develop the full force of the powder. Many
improvements along this line can be made, all of which will result in
greater mobility, more frequent attacks, and hence greater efficiency.
4-Inch Stokes’ Mortar. The Stokes’ mortar is not different from
that used by the Infantry, except that it is 4-inch, while the Infantry
Stokes’ is 3-inch. The 4-inch was chosen by the British for gas, as it
was the largest caliber that could be fired rapidly and yet be
moderately mobile. Its range of only about 1,100 yards handicapped
it considerably. The poor design of the bomb was partly responsible
for this. The powder charges also were neither well chosen nor well
designed. It is believed that great improvements can be made in the
shape of the bomb and in the powder charge, which will result in
much longer range and high efficiency, while in no way increasing
the weight of the bomb or decreasing the rate of fire. These last two
weapons were used during the World War, and will be very
extensively used in the future for firing high explosive, phosphorus,
thermit and similar materials that non-technical troops might handle.
Since gas has proven without the shadow of a doubt, that it will
produce more casualties for an equal amount of material transported
to the front than any other substance yet devised, all troops using
short range guns or mortars should be trained to fire gas whenever
weather conditions are right. When weather conditions are not right,
they should fire the other substances mentioned. The Livens’
projector with its 60 pound bomb, of which 30 pounds will be gas or
high explosive, is a wonderful gun up to the limit of its range. The
bomb, not being pointed, does not sink into the ground, and hence
upon exploding exerts the full force of high explosive upon the
surroundings, whether bombs, pill boxes, barbed wire or trenches, to
say nothing of personnel.
High Explosive in Projectors. When these are burst by the
hundreds on a small area everything movable is blotted out. Thus
concrete machine gun emplacements, lookout stations, bomb-proofs
and wire entanglements are destroyed, trenches filled up, and the
personnel annihilated. This was amply demonstrated on the few
occasions when it was actually used at the front. The American
Infantry, wherever they saw it tried out, were wild to have more of it
used. The German was apparently equally anxious to have the use
stopped. It is, however, one of the things that must be reckoned with
in the future. It means practically that No Man’s Land in the future
will be just as wide as the extreme range of these crude mortars—
and here a word of caution. While efforts have been made to
increase the range of these mortars, whether of the Livens’ projector
or Stokes’ variety, no further increase will be attempted when that
increase reduces the speed of firing or the efficiency of the projectile.
In other words results depend upon large quantities of material
delivered at the same instant on the point attacked, and if this cannot
be obtained the method is useless. For this reason these mortars will
never be a competitor of the artillery. The artillery will have all that it
can do to cover the field within its range—beyond that reached by
the mortars.
Phosphorus in 4-Inch Stokes. Phosphorus will be used largely
by gas troops, but only in the 4-inch or other Stokes’ mortar that may
be finally adopted as best. The Livens’ projector carries too great a
quantity, and being essentially a single shot gun, is not adapted to
keeping up a smoke screen by slow and continued firing, or of being
transported so as to keep up with the Infantry. Phosphorus has also
very great value for attacking personnel itself. Any one who has
been burned with phosphorus or has witnessed the ease with which
it burns when exposed to air, wet or dry, has a most wholesome fear
of it. The result of it in the war showed that the enemy machine
gunners or other troops would not stand up under a bombardment of
phosphorus fired from the 4-inch Stokes’ mortar—each bomb
containing about seven pounds.
Thermit. Thermit is used in the same way, and while the idea of
molten metal, falling upon men and burning through clothing and
even helmets, is attractive in theory, it proved absolutely worthless
for those purposes on the field of battle. It was found impossible to
throw sufficiently large quantities of molten metal on a given spot to
cause any considerable burn. In other words, the rapid spreading out
and cooling of the metal almost entirely ruined its effectiveness,
except its effect on the morale. This latter, however, was
considerable, as one might judge from seeing the thermit shells burst
in air. For this reason thermit may find a limited use in the future.

The Spread of Gas


Height of Gas Cloud. The height to which gas rises in a gas
cloud is not exactly known, but it is believed to be not much more
than fifty feet, and then only at a considerable distance from the
point of discharge. Moving pictures taken of gas clouds show this to
be true. It is also indicated by the fact that pigeons, which are very
susceptible to poisonous gas, practically always return to their cages
safely when liberated in a gas cloud. This was a good deal of a
mystery until it was realized that the pigeon escaped through his
rising so quickly above the gas. This of course would be expected
when it is known that practically all gases successfully used were
two or more times as heavy as air. Such gases rise only by slow
diffusion, or when carried upwards by rising currents. The absence
of these upward currents at night is one of the reasons why gas
attacks are more effective at night than during the day.
Horizontal Spread of Gas. Another important thing to know in
regard to the behavior of the wave of gas is the horizontal spread of
a cloud. If gas be emitted from a cylinder the total spread in both
directions from that point is from 20° to 30° or an average of 25°.
This varies, of course, with the wind. The higher the wind the less
the angle, though the variation due to wind is not as great as might
be expected. This horizontal spread of the gas cloud was measured
experimentally, and the results checked by aeroplane pictures of
heavy wave attacks over the enemy line. In the latter case the path
of the gas was very closely indicated by the dead vegetation. This
vegetation was killed and bleached so that it readily showed up in
aeroplane photographs. The visibility of a gas cloud arises from the
fact that when a large amount of liquid is suddenly evaporated, the
air is cooled and moisture condensed, thereby creating a fog. With
gases such as mustard gas and others of slight volatility, a visible
cloud is not formed. For purposes of identification of points struck by
shell, smoke substances are occasionally added, or a few smoke
shell fired with the gas shell. As future battle fields will be dotted
everywhere with smoke clouds, a point that will be discussed more
fully later, the firing of smoke with gas shell will probably be the rule
and not the exception.

Requirements of Successful Gas


If we succeed in getting a poisonous gas that has no odor it will
be highly desirable to fire it so that it will not be visible. In that case
no smoke will be used. Carbon monoxide is such a gas, but there
are several important reasons why it has not been used in war. (See
page 190). These considerations indicate the general requirements
for a successful poisonous gas. If non-persistent it must be quickly
volatilized, or must be capable of being driven off by heat or by other
means, which can be readily and safely produced in the field. It must
be highly poisonous, producing deaths in high concentrations, and
more or less serious injuries when taken into the system in quantities
as small as one-tenth of that necessary to produce death. If it has a
slightly delayed action with no intervening discomfort, it is still better
than one that produces immediate discomfort and more or less
immediate action. It must be readily compressed into a liquid and
remain so at ordinary temperatures, with the pressure not much
above 25 or 30 pounds per square inch.
As a persistent gas it must be effective in extremely low
concentrations, in addition to having the other qualities mentioned
above.
These general characteristics concerning gases apply whether
used by Chemical Warfare troops, the Artillery, the Air Service, the
Navy, or the Infantry. In speaking of these substances being used by
the Infantry, it is understood that an ample number of Chemical
Warfare officers will be present to insure that the gases may not be
turned loose when weather conditions are such that the gas might
drift back and become a menace to our own troops. This is
absolutely essential since no troops who have as varied duties to
perform as the Infantry, can be sufficiently trained in the technical
side of chemical warfare to know when to put it off on a large scale
with safety and efficiency.

Artillery Use of Gas


The Artillery of the future will probably fire more gas than any
other one branch of the Army. There are two reasons for this—first,
the large number of guns now accompanying every Army, and
second, the long range of many of these guns. As before indicated,
the gases are adaptable to various uses, and hence to guns differing
both in caliber and range. The gas will be fired by practically all guns
—from the 75 mm. to the very largest in use. It is even possible that
if guns smaller than the 75 mm. become generally useful that certain
gases will be fired by them.
Efficiency of Artillery Gas Shell. It is well to remember in the
beginning that all artillery shell so far designed and used, contain
only about 10 per cent gas, i.e., 10 per cent of the total weight of
shell and gas. It is hoped that gas shell may later be so designed
that a somewhat greater proportion of the total weight of the shell will
be gas than is now true. This is very desirable from the point of
efficiency. As stated above the bombs used by Chemical Warfare
troops contain nearly 50 per cent of their total weight in gas, and
hence are nearly five times as efficient as artillery shell within the
limit of range of these bombs. This fact alone is enough to warrant
the use of gas troops to their full maximum capacity in order that the
artillery may not fire gas at the ranges covered.

Guns Firing Persistent and


Non-Persistent Gases
Considering the firing of non-persistent and persistent gases, it
may be said generally that non-persistent gases will be fired only by
the medium caliber guns which are available in large numbers. In
fact, the firing of non-persistent gases will be confined mainly to the
6-inch or 155 mm. Howitzer and gun.
As our Army was organized in France, and as it is organized at
present, the number of 155 mm. guns will be greater than all others
put together, except the 75 mm. In order that a non-persistent gas
may be most effective a high concentration must be built up very
quickly. This necessitates the use of the largest caliber shell that are
available in large numbers. Of course, a certain percentage of the
gas shell of other calibers may consist of non-persistent gases in
order to help out the 155 mm. gun. This is in accordance with the
present program for loading gas shell and applies particularly to the
8-inch and 240 mm. Howitzer.
Few Ideally Persistent or Non-Persistent Gases. Naturally
there will be very few gases that are ideally non-persistent or ideally
persistent. The groups will merge into one another. Those on the
border line will be arbitrarily assigned to one group or the other. It
might be said definitely, however, that a gas which will linger more
than six or possibly eight hours under any conditions, except great
cold, will not be considered non-persistent. For reasons of efficiency
and economy persistent gases will not be chosen unless they will
persist under ordinary conditions for two or three days or more.
Accordingly, a gas which would persist for one day only would have
to be extraordinarily useful to lead to its adoption.
Firing Non-Persistent Gases. Of the non-persistent gases
phosgene is the type and the one most used at present.
Furthermore, so far as can now be foreseen, it will continue to be the
non-persistent gas most used. It volatilizes very quickly upon the
bursting of the shell. Accordingly, in order that the shell fired at the
beginning of a gas “shoot,” as they are generally referred to in the
field, shall still be effective when the last shell are fired, it is
necessary that the whole number be fired within two to three
minutes. The temperature and velocity of the wind both affect this. If
it be in a dead calm, the time may be considerably extended; if in a
considerable wind, it must be shortened. Another important
consideration requiring the rapid firing of non-persistent gases is the
fact that nearly all masks thoroughly protect against phosgene and
similar gases. It is accordingly necessary to take the enemy
unawares and gas him before he can adjust his mask; otherwise,
practically no harm will result. From the considerations previously
mentioned, these “gas shoots” are usually made at night when, as
before stated, carelessness, sleepiness and the resulting confusion
of battle conditions always insure more casualties than firing gas in
the daytime.
Firing Persistent Gases. The persistent gases will be fired by all
caliber guns, but to a less extent by the 155 mm. than by the other
calibers. Persistent gases must be sufficiently effective in low
concentrations to act more or less alone. If it be desirable to fill an
atmosphere over a given area with mustard gas, the firing may
extend for two or three, or even five or six hours and all shell still act
together. The same is true of bromobenzylcyanide. This, then,
permits the minimum number of guns to be used in firing these
persistent gases. Inasmuch as they persist and force the wearing of
the mask, they are available for use in long-range, large-caliber guns
for interdiction firing on cross-roads, in villages, and on woods that
afford hiding places, as well as on other similar concentration points.
Firing Irritant Gases. The irritant gases will be fired by the
various caliber guns, in the same manner as the persistent and non-
persistent gases. We will have non-persistent irritant gases and
persistent irritant gases. They are, however, considered as a group
because they are used for harassing purposes, due to their
efficiency in forcing the wearing of the mask.
Before the signing of the Armistice, the General Staff, A. E. F.,
had authorized, beginning January 1, 1919, the filling of 25 per cent
of all shell with Chemical Warfare materials. The interpretation there
given to shell was that it included both shrapnel and high explosive.
Of the field guns in use, the 75 mm. will be best, up to the limit of
its range, for persistent gases such as mustard gas, and the tear
gas, bromobenzylcyanide. A considerable number, however, were
filled with non-persistent gases and probably will continue to be so,
since, due to the very large number of 75 mm. guns available, they
can be used to add greatly at times to the amount of non-persistent
gas that can be fired upon a given point.

Use of Gas by the Aviation Service


No gas was used by aeroplanes in the World War. Many rumors
were spread during the latter part of the war to the effect that the
Germans had dropped gas here or there from aeroplanes. Every
such report reaching the Chemical Warfare Service Headquarters
was run down and in every case was found to be incorrect. However,
there was absolutely no reason for not so using gas, except that the
German was afraid. In the early days of the use of gas he did not
have enough gas, nor had he developed the use of aeroplanes to
the point where it would have seemed advisable. When, however, he
had the aeroplanes the war had not only begun to go against him,
but he had become particularly fearful of gas and of aeroplane
bombing.
It does not seem to be generally known, but it is a fact, that after
three or four months’ propaganda he made a direct appeal to the
Allies to stop the use of gas sometime during the month of March,
1918. This propaganda took the form of an appeal by a Professor of
Chemistry who had access to Switzerland, to prevent the annihilation
of the Allied forces by a German gas that was to make its
appearance in 1918. This German professor claimed that, while
favoring the Germans winning the war, he had too much human
sympathy to desire to see the slaughter that would be caused by the
use of the new gas. The Allies in the field felt that this was simply an
expression of fear and that he did not have such a gas. The
Germans were accordingly informed that the Allies would not give up
the use of gas. Later events proved these conclusions to be
absolutely correct. The German evidently felt that the manufacturing
possibilities of the Allies would put them in a more predominant
position with gas than with anything else. In that he was exactly
correct.
The use of gas by aeroplanes will not differ from its use in artillery
or by Chemical Warfare Troops. Non-persistent gases may be
dropped on the field of battle, upon concentration points, in rest
areas, or other troop encampments to produce immediate casualties.
Persistent gases will be dropped particularly around cross-roads,
railroad yards, concentration points and encampments that cannot
be reached by the artillery. The sprinkling of persistent gases will be
one of the best ways for aeroplanes to distribute gas.
It might be said here that the aviation gas bomb will be highly
efficient, inasmuch as it has to be only strong enough to withstand
the low pressure of the gas and ordinary handling, whereas artillery
shell must be strong enough to withstand the shock of discharge in
the gun.

Infantry and Gas Warfare


When one suggests the possibility of the infantry handling gas, it
is at once argued that the infantry is already overloaded. That is true,
but in the future, as in the past, the infantryman will increase or
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like