100% found this document useful (3 votes)
39 views

Python Programming 4th Edition Singh A. instant download

The document provides an overview of the 4th Edition of 'Python Programming' by Ajit Singh, detailing its content, structure, and educational approach. It emphasizes the book's comprehensive coverage of Python programming concepts, including advanced topics like Pandas, GUI programming, and database connectivity. The author expresses gratitude to those who contributed to the book's development and invites feedback for future improvements.

Uploaded by

gruelzemeri3
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 (3 votes)
39 views

Python Programming 4th Edition Singh A. instant download

The document provides an overview of the 4th Edition of 'Python Programming' by Ajit Singh, detailing its content, structure, and educational approach. It emphasizes the book's comprehensive coverage of Python programming concepts, including advanced topics like Pandas, GUI programming, and database connectivity. The author expresses gratitude to those who contributed to the book's development and invites feedback for future improvements.

Uploaded by

gruelzemeri3
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/ 73

Python Programming 4th Edition Singh A.

download

https://ebookgate.com/product/python-programming-4th-edition-
singh-a/

Get Instant Ebook Downloads – Browse at https://ebookgate.com


Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats

Python Programming for Teens 1st Edition Kenneth A.


Lambert

https://ebookgate.com/product/python-programming-for-teens-1st-
edition-kenneth-a-lambert/

Expert Python Programming 2nd Edition Jaworski

https://ebookgate.com/product/expert-python-programming-2nd-
edition-jaworski/

Core Python Programming 2nd Edition Wesley Chun

https://ebookgate.com/product/core-python-programming-2nd-
edition-wesley-chun/

Programming Python 3rd ed Edition Mark Lutz

https://ebookgate.com/product/programming-python-3rd-ed-edition-
mark-lutz/
Ultimate Python Programming 1st Edition Deepali
Srivastava

https://ebookgate.com/product/ultimate-python-programming-1st-
edition-deepali-srivastava/

Black hat Python Python programming for hackers and


pentesters 1st Edition Seitz

https://ebookgate.com/product/black-hat-python-python-
programming-for-hackers-and-pentesters-1st-edition-seitz/

Practical Maya Programming with Python 1st Edition


Galanakis

https://ebookgate.com/product/practical-maya-programming-with-
python-1st-edition-galanakis/

Learning BeagleBone Python Programming Unleash the


potential of BeagleBone using Python 1st Edition Hiam

https://ebookgate.com/product/learning-beaglebone-python-
programming-unleash-the-potential-of-beaglebone-using-python-1st-
edition-hiam/

Foundations of Python Network Programming Third Edition


Brandon Rhodes

https://ebookgate.com/product/foundations-of-python-network-
programming-third-edition-brandon-rhodes/
Ajit Singh

Python
Programming
4th Edition

Featured With......
ISBN-13 :979-8321458457

Pandas
GUI Programming
Modules & Library
Database Connectivity
101 Python Programs

Copyrighted Material
AKNOWLEDGEMENT
This piece of study of python is an outcome of the encouragement, guidance, help and assistance provided
to us by our colleagues, faculties, Tech-friends and my family members.

As an acknowledgement, I would like to take the opportunity to express my deep sense of gratitude to all
those who played a crucial role in the successful completion of this book, especially to my senior scholars;
this book certainly has been benefited from discussions held with many IT professionals (Ex-students)
over the years it took to write it.

Python reflects on a number of growing trends in software development, putting it at or near the leading
edge of good programming languages. It is a very simple language surrounded by a vast library of add­
on modules. It is an open source project, supported by many individuals. It is an object-oriented language,
binding data and processing into class definitions. It is a platform-independent, scripted language, with
complete access to operating systems APIs. It supports integration of complex solutions from pre-built
components. It is a dynamic language, which avoids many of the complexities and overheads of compiled
languages.

Three Faces of a Language. There are three facets to a programming language: how you write it, what it
means, and the additional practical considerations that make a program useful. While many books cover
the syntax and semantics of Python, in this book, the pragmatic considerations are also covered. My core
objective is to build enough language skills with a good object-oriented design so that the students can have
an efficient knowledge about python on windows platform.
Special thanks goes to our respected professor Prof. Dr. Bal Gangadhar Prasad, who is not only my role
model in learning and teaching but, also a source of encouragement who has always pushed me forward to
utilize my skills in a timely manner and have ever obliged for bearing with me from time to time, insisting
me on sticking to my determination all throughout.

I would also like to thank those who provided the odd suggestions via email to me. All feedbacks were
listened to, as you will no doubt see some content influenced by your suggestions.

I hope that the reader likes this book and finds it useful in learning the concepts of python.

Thank You!!

Ajit Singh!!

PREFACE

Share the knowledge........


Strengthen the sur­
roundings........
Python Simply In Depth provides all essential programming concepts and information one shall need in
order to start developing their own Python program. The book provides a comprehensive walk-through of
Python programming in a clear, straightforward manner that beginners will appreciate. Important con­
cepts are introduced through a step-by-step discussion and reinforced by relevant examples and illustra­
tions. This book can be used as a guide to help explore, harness, and gain appreciation of the capabilities
and features of Python.

This book encapsulates rich practical hands-on experience in developing python based applications,
combined with teaching the subject for graduate/post-graduate students. The book is therefore a culmi­
nation of putting together what has been both practiced as well as preached, which is the one of the most
compelling differentiators for this book. It can also be used for independent study by anyone interested in
getting a broad introduction to a core useful set of the python language.

This book isfeatured with advanced topics, such as Python Pandas, Database Connectivity, Python GUI
Programming and Python Libraries apartfrom the core concepts like Multithreading, Exception Handling
and Useful Modules. We explained these because they can solve some problems better than standard solutions.

My approach in this book is to regard python as a language that readers will want to use as a primary tool
in many different areas of their programming work - not just for creating programs with graphical content.
Nevertheless, I recognized that visual examples are much more fun to create and work with.
This book is a close-to-complete presentation of the Python language. Whether you are new to program­
ming or a professional developer, this book’s goal is to bring you quickly up to speed on the fundamentals of
the core Python language. After reading this book, you will know enough about Python to apply it in what­
ever application domains you choose to explore in your career.

Compatible with CBSE and AICTE Syllabus........

About This Forth Edition

In the four years since the first edition of this book was published in late 2019, there have been sub­
stantial changes in Python itself. Although I have attempted to retain as much of the prior version of
this text as possible, this new edition reflects many recent changes in the Python language, as well as a
handful of structural changes.

This Book’s Prerequisites

There are no absolute prerequisites to speak of, really. Both true beginners and crusty programming
veterans have used this book successfully. If you are motivated to learn Python, this text will probably
work for you. In general, though, we have found that any exposure to programming or scripting before
this book can be helpful, even if not required for every reader.

Feedback
I have tried to wash out every error in our third edition of this book after being reviewed by lots of bachelor of
Computer Science, but as happens with any programming language - A few difficult to understand bugs shall
remain and of course, typos - and therefore, suggestions from students that may lead to improvement in next
edition in shortcomingfuture are highly appreciated.

Constructive suggestions and criticism always go a long way in enhancing any endeavour. I request all readers
to email me their valuable comments / views /feedback for the betterment of the book at ajit_singh24@ya-
hoo.com, mentioning the title and author name in the subject line. Please report any piracy spotted by you as
well. I would be glad to hear suggestionsfrom you.

Python Programming
4th Edition

Copyrighted Material
Copyright © 2024-25 by Ajit Singh, All Rights Reserved.

No part of this publication may be reproduced, stored in a retrieval system or transmitted, in any
form or by any means — electronic, mechanical, photocopying, recording or otherwise— without
prior written permission from the author, except for the inclusion of brief quotations in a review.
For information about this title or to order other books and/or electronic media, contact the
publisher:

Ajit Singh - 24+ years of experience in academics.


M.Phil, UGC NET Qualified

PYTHON
? INSTITUTE
MnM r.to*
PCAP: Programming Essentials in Python

Statement of Achievement
Presented To:

Ajit Singh
Warne

During the Cisco Networking Academy® self-paced course.the student has studied the following Skills:

• the universal concepts of computer programing (i e variables, flow control, data structures, algorrthms, condtional execution loops, functions, etc,)
• developer teds and the runtime environment;
• lire syntax and semantics of the Python language;
• the fundamentals d cbicct oncnlod programing and the way they arc acoprtcd m Python .
• the means by which to rcsdvc typ<cal implementation problems
• the writing of Python programs using standard language infrastructure.
• fundamental programing techniques, best practices, customs and vocabulary, inducing the most common library function in Python 3;

17 Jan 2020
Date

By completing the course. tha student is no* randy Io atisrn.nl rhn quaincaron PCAP-Ceditmri Assoc nte in Python Programing certification, from ths OpnnEDG Python Inshtuls
. rotacad com |mm pythoninstttixe <x g
CONTENTS

Chapter Topic(s) Page


No
1 Getting Started with Python 09
History
Evolution
Features of Python
Limitation of Python
Comparisons
Some Jargon
2 Installing Python 17
Windows Installation
Customizing Environment
Whats new
3 Interacting with Python 26
Running Python
Command-Line Interaction
The IDLE Development Environment
Script Mode
Getting Help
4 Python Syntax 34
Syntax Formalities
Indentation
Keywords
Identifiers
Statements
Comments
print() and input() functions
5 Variables and Data Types 41
Variables
Several Data Types
Numeric Conversion (or Factory) Functions
Math function
6 Operators in Pyhton 51
Types of operators
Example of each type of operators.
7 Built-in Functions 61
8 Conditional Statements 66
Conditional Processing: the if Statement
The pass Statement
The assert Statement
The if-else Operator
9 Loops 72
Iterative Processing: The for Statement
Iterative Processing: The while Statement
More Iteration Control: break and continue
Infinite loop
Nested loop
10 User-Defined Functions 78
Function Definition: The def and return Statements
Function Use
Function Varieties
Some Examples
More Function Definition Features
Local and global variable
Lamda
Functions and Namespaces
The global Statement
11 Python Useful Modules 90
Module Definition
Module Use: The import Statement
Finding Modules: The Path
Math
datetime
os
zipfileurllib
winsound
finding module PYTHONHOME & PYTHONPATH
The exec Statement
12 Classes and Object-Oriented Programming 100
Class Definition: the class Statement
Class Responsibilities
Creating and Using Objects
Constructor
Instance & global variable
Static Methods and Class Method
Object Lifecycle
Special Method Names
Inheritance
Polymorphism
13 Exception Handling in Python 113
Basic Exception Handling
Raising Exceptions
An Exceptional Example
Complete Exception Handling and The finally Clause
Exception Functions
Exception Attributes
Built-in Exceptions
14 Multithreading 124
Defination
Starting new thread
The threading module
Synchronizing thread
Multithreaded priority queue
15 Text Files in Python 133
File semantics
File Organization and Structure
Additional Background
Built-in Functions
File Statements
File Methods
File and directory related methods
16 Regular Expression in Python
Creating a Regular Expression
Using a Regular Expression
Regular Expression Exercises
17 String, List & Dictionary
String Literal Values
String Operations
String Comparison Operations
String Statements
String Built-in Functions
String Methods
String Modules
Digression on Immutability of Strings

Lists
List Literal Values
List Operations
List Comparison Operations
List Statements
List Built-in Functions
List Methods
Stack & queue using list
Copy list

Mappings and Dictionaries


Dictionary Literal Values
Dictionary Operations
144

150
Dictionary Comparison Operations
Dictionary Statements
Dictionary Built-in Functions
Dictionary Methods
Iterators
18 Python Pandas 166
Introduction to Pandas
Key features of Pandas
Anaconda Pythons Distribution
Downloading, installing and customizing Anaconda on Windows
Working with Numpy
Working with Series
Working with DataFrame
Working with Panel
Data transferring from CSV files to data frame and vice versa.
Data transferring from Excel files to data frame and vice versa.
Data transferring from SQLite to data frame and vice versa.
19 Python GUI Programming 201
Introduction to TKinter
GUI Components
Label, Button, Entry Box, Textbox, Frame, Dialog, Windows,Radio,
Checkbok
Event & Event Handling
20 Database Connectivity In Python 222
Database
Database Interface
Phythons Database API
Python Database Programming Using MySQL
Python Database Programming Using ORACLE
Handling errors in Database Programming
21 The Python Library 223
Overview of the Python Library
Most Useful Library Sections
22 101 Python Programs 243

Chapter 1
Getting Started with Python
Python is an open source, high-level programming language developed by Guido van Rossum in the late
1980s and presently administered by Python Software Foundation. It came from the ABC language that he
helped create early on in his career.

Python is an interpreted language. This means that every time a program is run, its interpreter runs through
the code and translates the codes into machine-readable byte code.
Python is an object-oriented language that allows users to manage and control data structures or objects to
create and run programs. Everything in Python is, infact,jirst class. All objects, data types, junctions, meth­
ods, and classes take equal position in Python.

The official introduction to Python is


Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a
simple but effective approach to object-oriented programming. Pythons elegant syntax and dynamic typing,
together with its interpreted nature, make it an ideal language for scripting and rapid application develop­
ment in many areas on most platforms.

It is a high-level language. Reading and writing codes in Python is much like reading and writing simple
regular English statements. Python is a powerful language that you can use to create games, write GUIs,
and develop web applications.

History of Python
Python language was developed by Guido van Rossum in the late eighties and early nineties at
the National Research Institute for Mathematics and Computer Science in the Netherlands.

Python is derived from many other languages, including Modula-3, ABC, C, C+


+, Algol-68, SmallTalk, and UNIX shell and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available
under the GNU General Public License (GPL).

Python is now maintained by a core development team at the institute, although


Guido van Rossum still holds a major role in directing its development.

Python is implemented in C, and relies on the extensive, well understood, portable C libraries. It fits seam­
lessly with Unix, Linux and POSIX environments. Since these standard C libraries are widely available for
the various MS-Windows variants, and other non-POSIX operating systems, Python runs similarly in all
environments.

Evolution of Python

The development of Python occurred at a time when many other dynamic (and open-source) program­
ming languages such as Tel, Perl, and (much later) Ruby were also being actively developed and gaining
popularity.

Version 1 of Python : Python 1.0 was released in January 1994. The major release included a number of
new features and functional programming tools including lambda, filter, map and reduce.

Version 2 of Python: In October 2000, Python 2.0 was released with the new list comprehension feature
and a garbage collection system. The Python Software Foundation has already announced that there
would be no Python 2.8. However, the Foundation will provide support to version 2.7 of the programming
language till 2020.

Version 3 of Python : Python 3.0 was released in December 2008. It came with a several new features
and enhancements, along with a number of deprecated features. The deprecated features and backward
incompatibility make version 3 of Python completely different from earlier versions. So many Python
developers still use Python 2.6 or 2.7 to avail the features deprecated from last major release.

As Python 3 is backward incompatible, the programmers cannot access features like string exceptions, old-
style classes, and implicit relative imports. Also, the developers must be familiar with changes made to
syntax and APIs. They can use a tool called 2to3 to migrate their application from Python 2 to 3 smoothly.
The tool highlights incompatibility and areas of concern through comments and warnings. The comments
help programmers to make changes to the code, and upgrade their existing applications to the latest ver­
sion of programming language.

The version 2 and version 3 of Python are completely different from each other. So each programmer must
understand the features of these distinct versions, and compare their functionality based on specific needs
of the project. Also, he needs to check the version of Python that each framework supports. However, each
developer must take advantage of the latest version of Python to avail new features and long-term support.
The difference between
"Python Implementation" vs. "Python distribution" vs. Python

Python itself is a programming language as per the behavior defined by the documentation available on
python.org. Anything that does what that documentation says it's supposed to do would "count" as being
Python....

An implementation of Python is an actual program that provides the behavior defined by the documenta­
tion available on python.org. It has various implementations which allow you to run programs written in
it. To give you a better idea, msvc, clang, gcc are implementations of C. Here are some python implementa­
tions:
• CPython: this is the default, and what you should be using if you have no idea.
• Jython: implementation in java, allows you to use the java api.
• IronPython: implementation for .net, allows you to use the .net api.
• PyPy: JIT implementation.

A distribution of Python is a bundle that contains an implementation of Python along with a bunch of
libraries or tools or packages. In theory, a distribution of Python could use any implementation, although
all the ones I know of use CPython. The download from python.org could also be considered a distribution
(a minimal distribution that doesn't contain any "extras").

In practice, most people using Python for practical purposes are using CPython (the de facto standard
implementation), so the real choice is among different distributions of that. Among those, you mainly
choose based on what extras you want to come with it. You can choose to use the "bare" distribution from
python.org and then install packages yourself, or if you plan on doing scientific/analytics computing, you
could choose one of the distributions geared towards that (e.g., Anaconda or Canopy).
Features/Advantages of Using Python Language

The features/advantages of Python language are as follows;


1. Interpreted Language - as well as also compiled to bytecode. Modules are automatically compiled
(to .pyc) when imported as well as also be explicitly compiled as per the requirement. It facilitates an inter­
active command line and interpreter shell.

2. Object Oriented Language - Almost everything is an object in this language. It supports Data hiding,
Multiple inheritance, Interfaces and polymorphism.

3. Runs across different platforms - Python works on Windows, Linux/UNIX, Mac OS X, other operating
systems and small-form devices as well as it also runs on microcontrollers used in appliances, toys, remote
controls, embedded devices, and other similar devices.
4. Highly Structured Language - Statements, functions, classes, modules, and packages enable us to write
large, well structured applications so that to have the feature of readability, locate ability, modifiability.

5. Higher Productive Language - Pythons codes are considerably shorter, simpler, and less verbose than
other high-level programming languages such as Java and C++. In addition, it has well-designed built-in
features and standard library as well as access to third party modules and source libraries. These features
enable programming in Python more efficient.

6. Dynamic Language - It is dynamic language as types are bound to values, not to variables, function and
method lookup is done at runtime, values are inspectable and we can list the methods supported by any
given object.

7. Strongly Typed Language - at runtime rather than compile time. Objects (values) have a type, but vari­
ables do not have in this language.

8. Embedding and Extending Language - Python provides a well documented and supported way
(1) to embed the Python interpreter in C/C++ applications and
(2) to extend Python with modules and objects implemented in C/C++.
Cython enables us to generate C code from Python and to "easily" create wrappers for C/C++ functions.
To embed and extend Python with Java, there is Jython.

9. Reasonably High level - It contains high level builtin data types as well as high level control structures.

10. Less Learning Time - Python is relatively easy to learn as compare to other languages. Python is a a
good to first language for learning programming because it uses simple syntax and shorter codes.

Limitations/Disadvantages of Python Language

Python has varied advantageous features, and programmers prefer this language to other programming
languages because it is easy to learn and code too. But, this language has still not made its place in some
computing arenas that includes Enterprise Development houses. Therefore, this language may not solve
some of the enterprise solutions, and limitations include-

1. Difficulty in Using Other Languages


The Python lovers become so accustomed to its features and its extensive libraries, so they face problem in
learning or working on other programming languages. Python experts may see the declaring of cast values
or variable types, syntactic requirements of adding curly braces or semi colons as an onerous task.

2. Weak Language in Mobile Computing


Python has made its presence on many desktop and server platforms, but it is seen as a weak language for
mobile computing. That is why very few mobile applications are built in it like Carbonnelle.
3. Gets Slow in Speed
Python executes with the help of an interpreter instead of the compiler, which causes it to slow down
because compilation and execution help it to work normally. On the other hand, it can be seen that it is fast
for many web applications too.

4. Run-time Errors
The Python language is dynamically typed so it has many design restrictions that are reported by some
Python developers. It is even seen that it requires more testing time, and the errors show up when the ap­
plications are finally run.

5. Underdeveloped Database Access Layers


As compared to the popular technologies like JDBC and ODBC, the Pythons database access layer is found to
be bit underdeveloped and primitive. It cannot be applied in the enterprises that need smooth interaction
of complex legacy data.

Varieties of Python Language:

Jython Python for the Java environment http://www.jython.org/


PyPy Python with a JIT compiler and stackless mode http://pypy.org/
CPython Standard Python 2.xx implemented in C.
Stackless Python with enhanced thread support and microthreads etc.
http://www.stackless.com/
IronPython Python for .NET and the CLR http://ironpython.net/
Python 3 The new, new Python. This is intended as a replacement for Python
2.x. http://www.python.org/doc/

Some Jargon

For folks new to developing software, it might help to understand a few distinctions made above.
Interpreted
Not Interpreted (i.e., Compiled)

Python is a byte-code interpreter. A Python code object is a sequence of bytes that represent various opera­
tions and values. The Python interpreter steps through the bytes, performing the operations.

A compiled language (e.g., C, C++, etc.) is translated from source form to executable binary specific to oper­
ating system and hardware platform.
Java is similar to Python: its compiled and the Java Virtual Machine is a byte-code interpreter.
Dynamic
Not Dynamic (i.e., Static)
Python is a dynamic language. Variables and functions do not have defined data types. Instead, a variable
is simply a label attached to an object. A function is a callable object with parameters, but no declared result
type. Each object has a strongly-defined permanent class.
There is no sophisticated compile-time type checking. Instead, any type mismatches will be detected at
run-time. Since many types are nearly interchangeable, there isnt a need for a lot of type checking. For ex­
amples of interchangeable (polymorphic) types, see Simple Numeric Expressions and Output.
Languages like C, C++ and Java have statically-declared variables and functions.
Scripting
Non-Scripting

The scripting distinction is an operational feature of POSIX-compliant operating systems. Files which
begin with the #!/path/to/interpreter will be used as scripts by the OS. They can be executed from the com­
mand-line because the interpreter is named in the first line of the file.

Languages like Java, C and C++ do not have this feature; these files must be compiled before they can be
executed.

Chapter 2
Installing Python
Installing Python in Windows

To install Python, you must first download the installation package of your preferred version from this
link:

https://www.python.org/downloads/

On this page, you will be asked to choose the recent versions for Python 3.11.x/3.12.x which was released
on 8th Feb 2023. Alternatively, if you are looking for a specific release, either Python 2 or 3, you can scroll
down the page to find download links for earlier versions.

python i
About Downloads Documentation Community

Download the latest version for Windows


Download Python 3.11.2

Looking for Python with a different OS? Python for Windows,


Linux/UNIX, macOS, Other

Want to help test development versions of Python? Prereleases,


Docker images
You would normally opt to download the latest version, which is Python 3.12.x. However, you may opt for the latest
version of Python 2, 2.7.18. Your preferences will usually depend on which version will be most usable for your
curriculum / project. While Python 3 is the present and future of the language, issues such as third party utility or
compatibility may require you to download Python 2.

Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept
the default settings, wait until the install is finished, and you are done.

£* Python 3.11.2 (64-bit) Setup

Install Python 3.11.2 (64-bit)


Select Install Now to install Python with default settings, or choose
Customize to enable or disable features.

—> Install Now


C:\Users\vignan\AppData\Local\Programs\Python\Python311

Includes IDLE, pip and documentation


Creates shortcuts and file associations

—> Customize installation


Choose location and features

python Use admin privileges when installing py.exe


for
0 Add python.exe to PATH Cancel
windows
Note that depending on your needs, you may also check the box to add Python to the Path. It will inform the
python file installer that the executable python path folder will be added to the environment variable with
the name of ‘Path’.

Finally, if the installation process is a success, the following window will appear:
£• Python 3.10.5 (64-bit) Setup

Setup was successful


New to Python? Start with the online tutorial and
documentation. At your terminal type "py" to launch Python,
or search for Python in your Start menu.

See what's new in this release, or find more info about using
Python on Windows.

S Disable path length limit


Changes your machine configuration to allow programs, including Python, to
bypass the 260 character "MAX-PATH'' limitation.

python
for
windows Close

Windows Configuration (Optional)


Windows users will need to be sure that python.exe is on their PATH. This is done with the System control
panel. Click on the Advanced tab. Click on the Environment Variables... button. Click on the System vari­
ables Path line, and click the Edit... button. This will often have a long list of items, sometimes starting
with %SystemRoot%. At the end of this list, add and the direction location of Python.exe. On my ma­
chine, I put it in D:\Softwares\Python\.

For Windows programmers, the windows command interpreter uses the last letters of the file name to
associate a file with an interpreter. You can have Windows run the python.exe program whenever you dou­
ble-click a .py file. This is done with the Folder Options control panel. The File Types tab allows you to pair
a file type with a program that processes the file.

Follow the below steps to add Python Path to Environment Variables.

Step 1: Click on Start Button and Open the Run Program.


Step 2: Now type sysdm.cpl and click OK. This opens the System Properties Dialog Box.
Step 3: Go to Advanced Tab and and Click on Environment Variables.
Step 4: In the System Variable section, Select the path variable.
Step 5: Click on Edit button and add python path to variable value.
Step 6: Click OK.

You can get your python path in the folder where you have installed python. Example - for us it D:\Soft-
wares\Python\
How to Test the Python in Microsoft Windows

The last part, it will display on how to test the result of the python installation in the previous part. It is
actually very simple as it exist in the following steps:
As usual, just execute the Command Prompt.
Following after, type the command below to test whether ‘python’ is available and it is exist in the environ­
ment variable of ‘Path’:

C:\Users\Personal>python
Python 3.11.2 (tags/v3.11.2:f377153, Jun 6 2022,16:14:13) [MSC v.1929 64 bit (AMD64)] on Win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Last but not least, just perform another test to make sure. The following test is executing a certain com­
mand to check the version of the installed python as follows :

C:\Users\Personal>python -V
Python 3.11.2
C:\Users\Personal>

As it appear in the output of the above command execution, the version is matched. It is python with the
version of‘3.11.2’.

Python Editors
> Vim http://www.vim.org/
> Emacs See http://www.gnu.org/software/emacs/
> SciTE http://www.scintilla.org/SciTE.html.
> MS Windows only
(1) TextPad http://www.textpad.com;
(2) UltraEdit http://www.ultraedit.com/.
> Jed See http://www.jedsoft.org/jed/.
> jEdit Requires a bit of customization for Python See http://jedit.org.
> Geany http://www.geany.org/

Interactive Interpreters:
> python
> ipython
> Idle IDEs

Integrated Development Environments for Python:


> PyWin MS Windows only. Available at: http://sourceforge.net/projects/pywin3 2/
> Kdevelop Linux/KDE See http://www.kdevelop.org/
> Eric Linux KDE? See http://ericide.pythonprojects.org/index.html
> WingIDE See http://wingware.com/wingide/
> Eclipse http://eclipse.org/ There is a plug in that supports Python.
> Emacs and SciTE will evaluate a Python buffer within the editor.
Whats new in Python 3.11.x

This new version of Python mainly focuses on improving the performance of the language. A few nice features
around exception handling and error display should also improve the development experience.

1. Improved performance

On average, a 25% performance gain compared to Python 3.11 is announced. Some operations are even up to 60%
faster than the latest version. The start-up time is reduced by 10% on average.
The measurements were performed with performance using CPython compiled with GCC under Ubuntu.

The performance gain comes mainly from the specialization of some instructions when the calls to a code are repet­
itive. The fact that the code repeats itself without necessarily changing allows the interpreter to analyze the running
code and replace the generic code with type-specific pieces.
Another improvement comes from reducing the number of calls to the system memory in favor of allocating more
space. If these performance gains are always good to take, they do not turn Python into an efficient programming
language.

An increase in memory consumption of around 20% is anticipated following the implementation of these changes on
CPython.
Further performance gains are already planned in versions 3.12 and later.

2. Better exception handling

Special work has been done on error management. It is now possible to add annotations on exceptions.

try:
raise ExceptionGroup("Exception Group", (
TypeErrorf'Type error"),
KeyError("Key error"),
ValueError("Value error"),
except* (ValueError, TypeError) as exc:
exc.add_note("Add more information about the error")
raise exc

except* KeyError as exc:


raise exc
Similarly, a new syntax is emerging. It is now possible to create groups of exceptions and break down the use of except
to catch certain exceptions contained in a group.

3. A more accurate traceback

The error messages returned by Python are now more precise and include the position of the error on the faulty line
of code. This function is very similar to what other modern languages can offer.
+--------------------------
I Traceback (most recent call last):
I File "test.py", line 5, in test
I assertx < 0
|AAAAAAAAAAAA

I AssertionError: assert 0 < 0


+--------------------------

4. Improved typing
As we know, Python is a dynamically typed language, which is not always appreciated by developers. The latest
Python updates have already started the integration of an optional type system. This release continues that trend by
adding more types like Self, Literalstring, Required, and NotRequired.

from typing import Self

class Foo:
def _init_ (self, x: str):
self.x = x

def bar(self, y: str) -> Self:


return Foo(y)

5. An update to the standard library

The standard Python library is not left out and is experiencing some changes.

TOML
First of all, the tomllib module is added to the standard library to parse TOML. This addition follows support for the
pyproject.toml file, added in a previous version of Python.
This library remains limited in terms of functionalities and has only one purpose: file parsing.

import tomllib
with open("pyproject.toml", "rb") as f:
data = tomllib.load(f)
print(data["project"]["name"])

AsyncIO
The asyncio library is also entitled to an update with the addition of Task Group to replace the use of the .gather()
method on asynchronous operations.
import asyncio
async def task 1():
print("Foo")
await asyncio.sleep(5)

async def task2():


print("Bar")
await asyncio.sleep(2)

async def main():


try:
async with asyncio.TaskGroupO as task_group:
task_group.create_task(task 1 ())
task_group.create_task(task2())
except* ValueError as exc:
print(exc.exceptions)

if_ name_ == "__ main_


asyncio.run(main())
This update makes the syntax more pleasant, but does not bring any other major changes to the library.

StrEnum

The StrEnum makes an appearance. It allows to automatically convert a character string into an Enum.

from enum import StrEnum, auto


class Foo(StrEnum):
BAR = auto()
print(Foo.BAR.value) # "bar"

Path
The Path.glob() method of pathlib now allows you to specify whether you only want to retrieve folders.

from pathlib import Path


p = Path("/Users/foobar/")
everything = p.glob("*")
dirs = p.glob("7")

6. Miscellaneous deprecation

Finally, this version brings a background cleanup and removes support for many legacy modules: aifc, chunk, msilib,
pipes, telnetlib, audioop, crypt, nis, sndhdr, uu, cgi, imghdr, nntplib, spwd, xdrlib, cgitb, mailcap, ossaudiodev,
sunau...

Some of these modules will not be removed from the standard library until Python 3.13. Others will simply be re­
placed by alternative solutions, more modern and better maintained, already present in the standard library.

In conclusion, if this update does not bring anything revolutionary, it continues the Python projects already launched
with regard to the improvement of the performances of CPython, the improvement of the error management and the
addition of solutions for typing requested by part of the community.

Chapter 3
Interacting with Python
Python is a flexible and dynamic language that you can use in different ways. You can use it interactively
when you simply want to test a code or a statement on a line-by-line basis or when youre exploring its
features. You can use it in script mode when you want to interpret an entire file of statements or applica­
tion program.
To use Python interactively, you can use either the Command Line window or the IDLE Development
Environment.

Command Line Interaction


The command line is the most straightforward way to work with Python. You can easily visualize how
Python works as it responds to every completed command entered on the

> > > prompt. It may not be the most preferred interaction with Python, but it is the simplest way to explore
how Python works.

Running Python
There are three different ways to start Python -
1. Interactive Interpreter
From Windows
Start-> All Programs -> Python 3.11 -> Python 3.11
2. Script from the Command-line
A Python script can be executed at command line by invoking the interpreter on your application, as in the
following -
C: >python script.py

3. Integrated Development Environment


You can run Python from a Graphical User Interface (GUI) environment as well, if you have a GUI applica­
tion on your system that supports Python.
Windows - PythonWin is the first Windows interface for Python and is an IDE with a GUL
From Windows
Start-> All Programs -> Python 3.11 -> IDLE
Note: If youre using GNU/Linux, UNIX, and Mac OS systems, you have to run the Terminal Tool and enter
the Python command to start your session.

We use commands to tell the computer what to do. When you want Python to do something for you, you
have to instruct it by entering commands that it is familiar with. Python will then translate these com­
mands to instructions that your computer or device can understand and execute.

To see how Python works, you can use the print command to print the universal program Hello, World!
Open Pythons command line.
At the >>>prompt, type the following: print(Hello, World!)
Press enter to tell Python that youre done with your command. Very quickly, the command line window
will display Hello, World! on the following line:

Type "help", "copyright", "credits" or "license" for more information.


»> print(”hello”>
hello
»>
Python responded correctly because you gave it a command in a format that it requires. To see how it
responds when you ask it to print the same string using a wrong syntax for the print command, type and
enter the following command on the Python command prompt:
Print(Hello, World!)
This is how Python will respond:
Syntax error: invalid syntax

Youll get syntax error messages whenever you enter invalid or incomplete statements. In this case, you
typed print with a capital letter which is a big no to a case-sensitive language like Python.

If youre just using Python interactively, you can do away with the print command entirely by just typing
your statement within quotes such as Hello, World!

Getting Help
Python has two closely-related help modes. One is the general help utility, the other is a help function that
provides the documentation on a specific object, module, function or class.

The help() Utility


Help is available through the help() function.
If you enter just help() you will enter the online help utility. This help utility allows you to explore the
Python documentation.
The interaction looks like this:
> > > help
Type help() for interactive help, or help(object) for help about object.
>>> help()

Help on a specific topic


If you enter help( object) for some object, you will be given help on that specific object. This help is dis­
played using a help viewer.
Youll enter something like this:
»> help("EXPRESSIONS")

Exiting Python
To exit from Python, you can type any of these commands:
quit()
exit()
Control-Z then press enter

IDLE: Pythons Integrated Development Environment (IDE)


The IDLE (Integrated Development and Learning Environment) tool is included in Pythons installation
package but you can choose to download more sophisticated third party IDEs.
The IDLE tool offers a more efficient platform to write your code and work interactively with Python. You
can access IDLE on the same folder where you found the command line icon or on the start menu. As soon
as you click on the IDLE icon, it will take you to the Python Shell window.
You can run a code in Python via the Python IDLE.
A quick way to find your Python IDLE on Windows is by clicking on the Start menu. You should then see the
IDLE under “Recently added”.

Recently added

|L IDLE (Python 3.9 64-bit)

|L Python 3.9 Module Docs (64-bit)

B? Python 3.9 Manuals (64-bit)


Once you click on the Python IDLE, you’ll see the Shell screen.

The Python Shell Window


The Python Shell Window has dropdown menus and a > > > prompt that you have seen earlier in the com­
mand line window. Here you can type and enter statements or expressions for evaluation in the same way
that you used the command line earlier. This time however, IDLES editing menu allows you to scroll back to
your previous commands, cut, copy, and paste previous statements and make modifications. IDLE is quite
a leap from the command line interaction.

The Python Shell window has the following menu items: File, Edit, Shell, Debug, Options, Windows, and
Help.
Python 3.9.0 Shell — □ X
File Edit Shell Debug Options Window Help
Pychon 3.9.0 (cags/v3.9.O:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927
64 bit (AMD64)] on Win32
Type "help", "copyright", "credits" or "license()" for more informati
on .
»> I

Ln: 3 Col: 4
The Shell and Debug menus provide capabilities you would find useful when creating larger programs.

The Shell menu allows you to restart the shell or search the shells log to find the most recent reset.
The Debug Menu has useful menu items for tracing the source file of an exception and highlighting the
erring line. The Debugger option will usher in an interactive debugger window that will allow you to step
through the running program. The Stack Viewer option displays the current Python stack through a new
window.

The Options menu allows you to configure IDLE to suit your Python working preferences.

The Help menu opens Python Help and documentation.

The File Menu


The items on the File menu allows you to create a new file, open an old file, open a module, and/or save your
session. When you click on the New File option, you will be taken to a new window, a simple and standard
text editor where you can type or edit your code. Initially, this file window is named untitled but its name
will soon change as you save your code.

The windows menu bar varies only slightly with the Shell Window. It doesnt have the Shell and Debug
menu found in the Shell Window but it introduces two new menus: the Run and the Format menu. When
you choose to Run your code on the file window, you can see the output on the Shell Window.

The Script Mode


When working in script mode, you wont automatically see results the way you would in interactive mood.
To see an output from a script, youll have to run the script and/or invoke the print() function within your
code.
Python 3.9.0 Shell — □ X
File | Edit Shell Debug Options Window Help

New File Ctrl*N :9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927


Open... Ctrl+O
_ .... ... .. "credits" or "license ()" for more informati
Open Module... Alt+M
Recent Files ►
Module Browser Alt*C
Path Browser

Save Ctrl+S
Save As... Ctrl*Shift*S
Save Copy As... Alt*Shift*S

Print Window Ctrl+P

Close Alt*F4
Exit Ctrl+Q

Click on File and then select New File (alternatively, you may use the keyboard shortcut of Ctrl+N):
You would now see the following “untitled” box, where you can type your Python code:
Discovering Diverse Content Through
Random Scribd Documents
Figs. 53 and 54.—Arrangement of Drill
Holes in the Heading of the Fort George
Tunnel.

In the center-cut method, which is the one commonly employed


in America, the holes are arranged in vertical rows, and are driven
from 8 to 10 ft. deep. Fig. 53 shows the arrangement of the holes,
and the method of blasting them, as used in the excavation of the
heading for the Fort George tunnel of the New York rapid transit.
The two center rows of holes converge toward each other so as to
take out a wedge of rock; others are bored straight, or parallel, with
the vertical plane of the tunnel. Those bored around the perimeter
are driven either outward or upward, according as they are located,
close to the sides or roof of the tunnel. In this case, the holes of the
center cut were driven 9 ft. deep, while all the other holes were
bored to a depth of 8 ft.
The width of the advanced gallery or heading depends upon the
quality of the rock. In hard rock American engineers give it the full
width of the tunnel section; but this cannot be done in loose or
fissured rock, which has to be supported, the headings here being
usually made about 8 × 8 ft. The wider heading is always preferable,
where it is possible, since more room is available for removing the
rock, and deeper holes can be bored and blasted.
The important rôle played by the power plant and other
mechanical installations in constructing tunnels through rock has
already been mentioned. In some methods of soft-ground tunneling,
and particularly in soft-ground subaqueous tunneling, it is also often
necessary to employ a mechanical installation but slightly inferior in
size and cost to those used in tunneling rock. It is proposed to
describe very briefly here a few typical individual plants of this
character, which will in some respects give a better idea of this
phase of tunnel work than the more general descriptions.
Rock Tunnels.—The tunnels selected to illustrate the mechanical
installations employed in tunneling through rock are: The Mont
Cenis, Hoosac Tunnel, the Cascade Tunnel, the Niagara Falls Power
Tunnel, the Palisades Tunnel, the Croton Aqueduct Tunnel, the
Strickler Tunnel in America, and the Graveholz Tunnel and the
Sonnstein Tunnel in Europe. In addition there will be found in
another chapter of this book a description of the mechanical
installations at the St. Gothard, Pennsylvania and other tunnels.
Mont Cenis Power Plant.—The mechanical installation consisted of
the Sommeilier air compressors built near the portals. The
Sommeilier compressors, Mr. W. L. Saunders says, were operated as
a ram, utilizing a natural head of water to force air at 80 lbs.
pressure into a receiver. The column of water contained in the long
pipe on the side of the hill was started and stopped automatically by
valves controlled by engines. The weight and momentum of the
water forced a volume of air with such a shock against the discharge
valve that it was opened, and the air was discharged into the tank;
the valve was then closed, the water checked; a portion of it was
allowed to discharge, and the space was filled with air, which was in
turn forced into the tank. Only 73% of the power of the water was
available, 27% being lost by the friction of the water in the pipes,
valves, bends, etc. Of the 73% of net work, 49.4 was consumed in
the perforators, and 23.6 in a dummy engine for working the valves
of the compressors and for special ventilation.
The compressed air was conveyed from each end through a cast-
iron pipe 75⁄8 in. in diameter, up to the front of the excavation. The
joints of the pipes were made with turned faces, grooved to receive
a ring of oakum which was tightly screwed and compressed into the
joint. To ascertain the amount of leakage of the pipes, they and the
tanks were filled with air compressed to 6 atmospheres, and the
machines stopped; after 12 hours the pressure was reduced to 5.7
atmospheres, or to 95% of the original pressure.
Sommeilier’s percussion drilling machines were used in the
excavation of this tunnel. They were provided with 8 or 10 drills
acting at the same time, and mounted on carriages running on
tracks. These were withdrawn to a safe place during the blasting,
and advanced again after the broken rock was removed from the
front and the new tracks laid.
Machine shops were built at both ends of the tunnel for building
and repairing the drilling machines, bits, tools, etc. A gas factory was
built at each end for lighting purpose.
Hoosac Tunnel.—The Hoosac tunnel on the Fitchburg R.R. in
Massachusetts is 25,000 ft. long, and the longest tunnel in America.
The material through which the tunnel was driven was chiefly hard
granitic gneiss, conglomerate, and mica-schist rock. The excavation
was conducted from the entrances and one shaft, the wide heading
and single-bench method being employed, with the center-cut
system of blasting which was here used for the first time. The tunnel
was begun in 1854, and continued by hand until 1866, when the
mechanical plant was installed. Most of the particular machines
employed have now become obsolete, but as they were the first
machines used for rock tunneling in America they deserve mention.
The drills used were Burleigh percussion drills, operated by
compressed air. Six of these drills were mounted on a single
carriage, and two carriages were used at each front. The air to
operate these drills was supplied by air compressors operated by
water-power at the portals and steam-power at the shaft. The air
compressors consisted of four horizontal single-acting air cylinders
with poppet valves and water injection. The compressors were
designed by Mr. Thomas Deane, the chief engineer of the tunnel.
Palisades Tunnel.—The Palisades tunnel was constructed to carry a
double track railway line through the ridge of rocks bordering the
west bank of the Hudson River and known as the Palisades. It was
located about opposite 116th St. in New York City. The material
penetrated was a hard trap rock very full of seams in places, which
caused large fragments to fall from the roof. The excavation was
made by a single wide heading and bench, employing the center-cut
method of blasting with eight center holes and 16 side holes for the
7 × 18 ft. heading. Ingersoll-Sergeant 21⁄2 in. drills were used, four
in each heading and six on each bench, and 30 ft. per 10 hours was
considered good work for one drill.
The power-plant was situated at the west portal of the tunnel,
and the power was transmitted by electricity and compressed air to
the middle shaft and east portal workings. The plant consisted of
eight 100 H. P. boilers, furnishing steam to four Rand duplex 18 × 22
in. air compressors, and an engine running a 30 arc light dynamo.
The compressed air was carried over the ridge by pipes, varying
from 10 ins. to 5 ins. in diameter, to the shaft and to the east portal,
and was used for operating the hoisting engines as well as the drills
at these workings. Inside the tunnel, specially designed derrick cars
were employed to handle large stones, they being also operated by
compressed air. This car ran on a center track, while the mucking
cars ran on side tracks, and it was employed to lift the bodies of the
cars from the trucks, place them close to the front, being worked
where large stone could be rolled into them, and return them to the
trucks for removal. In addition to handling the car bodies the derrick
was used to lift heavy stones. The hauling was done first by horse-
power, and later by dummy locomotives.
Croton Aqueduct Tunnel.—In the construction of the Croton
Aqueduct for the water supply of New York City, a tunnel 31 miles
long was built, running from the Croton Dam to the Gate House at
135th St. in New York City. The section of the tunnel varies in form,
but is generally either a circular or a horseshoe section. In all cases
the section was designed to have a capacity for the flow of water
equal to a cylinder 14 ft. in diameter. To drive the tunnel, 40 shafts
were employed. The material penetrated was of almost every
character, from quicksand to granitic rock, but the bulk of the work
was in rock of some character. The excavation in rock was conducted
by the wide heading and bench method, employing the center-cut
method of blasting. Four air drills, mounted on two double-arm
columns were employed in the heading. The drills for the bench
work were mounted on tripods. Steam-power was used exclusively
for operating the compressors, hoisting engines, ventilating fans and
pumps; but the size and kind of boilers used, as well as the kind and
capacity of the machines which they operated, varied greatly, since a
separate power-plant was employed for each shaft with a few
exceptions. A description of the plant at one of the shafts will give
an indication of the size and character of those at the other shafts,
and for this purpose the plant at shaft 10 has been selected.
At shaft 10 steam was provided by two Ingersoll boilers of 80 H.
P. each, and by a small upright boiler of 8 H. P. There were two 18 ×
30 in. Ingersoll air compressors pumping into two 42 in. × 10 ft. and
two 42 in. × 12 ft. Ingersoll receivers. In the excavation there were
twelve 31⁄2 in. and six 31⁄8 in. Ingersoll drills, four drills mounted on
two double arm columns being used on each heading, and the
remainder mounted on tripods being used on the bench. Two
Dickson cages operated by one 12 × 12 in. Dickson reversible
double hoisting engine provided transportation for material and
supplies up and down the shaft. A Thomson-Houston ten-light
dynamo operated by a Lidgerwood engine provided light. Drainage
was effected by means of two No. 9 and one No. 6 Cameron pumps.
At this particular shaft the air exhausted from the drills gave ample
ventilation, especially when after each blast the smoke was cleared
away by a jet of compressed air. In other workings, however, where
this means of ventilation was not sufficient, Baker blowers were
generally employed.
Strickler Tunnel.—The Strickler tunnel for the water supply of
Colorado Springs, Col., is 6441 ft. long with a section of 4 ft. × 7 ft.
It penetrates the ridge connecting Pike’s Peak and the Big Horn
Mountains, at an elevation of 11,540 ft. above sea level. The
material penetrated is a coarse porphyritic granite and morainal
débris, the portion through the latter material being lined. The
mechanical installation consisted of a water-power electric plant
operating air compressors. The water from Buxton Creek having a
fall of 2400 ft. was utilized to operate a 36 in. 220 H. P. Pelton
water-wheel, which operated a 150 K. W. three-phase generator.
From this generator a 3500 volt current was transmitted to the east
portal of the tunnel, where a step-down transformer reduced it to a
220 volt current to the motor. The transmission line consisted of
three No. 5 wires carried on cross-arm poles and provided with
lightning arresters at intervals. The plant at the east portal of the
tunnel consisted of a 75 H. P. electric motor, driving a 75 H. P. air
compressor, and of small motors to drive a Sturtevant blower for
ventilation, to run the blacksmith shop, and to light the tunnel, shop,
and yards. From the compressor air was piped into the tunnel at the
east end, and also over the mountain to the west portal workings.
Two drills were used at each end, and the air was also used for
operating derricks and other machinery. For removing the spoil a
trolley carrier system was employed. A longitudinal timber was
fastened to the tunnel roof, directly in the apex of the roof arch. This
timber carried by means of hangers a steel bar trolley rail on which
the carriages ran. Outside of the portal this rail formed a loop, so
that the carriage could pass around the loop and be taken back to
the working face. Each carriage carried a steel span of 11⁄2 cu. ft.
capacity, so suspended that by means of a tripping device it was
automatically dumped when the proper point on the loop was
reached.
Niagara Falls Power Tunnel.—The tail-race tunnel built to carry
away the water discharged from the turbines of the Niagara Falls
Power Co., has a horse-shoe section 19 × 21 ft. and a length of
6700 ft. It was driven through rock from three shafts by the center-
cut method of blasting. In sinking shaft No. 0 very little water was
encountered, but at shafts Nos. 1 and 2 an inflow of 800 gallons and
600 gallons per minute, respectively, was encountered. The principal
plant was located at shaft No. 2, and consisted of eight 100 H.P.
boilers, three 18 × 30 in. Rand duplex air compressors, a Thomson-
Houston electric-light plant, and a sawmill with a capacity of 20,000
ft. B. M. per day. The shafts were fitted with Otis automatic hoisting
engines, with double cages at shafts Nos. 1 and 2, and a single cage
at shaft No. 0. The drills used were 25 Rand drills and three
Ingersoll-Sergeant drills. The pumping plant at shaft No. 2 consisted
of four No. 7 and one No. 9 Cameron pumps, and that at shaft No. 2
consisted of two No. 7 and two No. 9 Cameron pumps and three
Snow pumps. An auxiliary boiler plant consisting of two 60 H. P.
boilers was located at shaft No. 1, and another, consisting of one 75
H. P. boiler, was located at shaft No. 0.
Cascade Tunnel.—The Cascade tunnel was built in 1886-88 to
carry the double tracks of the Northern Pacific Ry. through the
Cascade Mountains in Washington. It is 9850 ft. long with a cross-
section 161⁄2 ft. wide and 22 ft. high, and is lined with masonry. The
material penetrated was a basaltic rock, with a dip of the strata of
about 5°. The rock was excavated by a wide heading and one
bench, using the center-cut system of blasting. A strutting consisting
of five-segment timber arches carried on side posts, spaced from 2
ft. to 4 ft. apart, and having a roof lagging of 4 × 6 in. timbers
packed above with cord-wood. The mechanical plant of the tunnel is
of particular interest, because of the fact that all the machinery and
supplies had to be hauled from 82 to 87 miles by teams, over a road
cut through the forests covering the mountain slopes. This work
required from Feb. 22 to July 15, 1886, to perform. In many places
the grades were so steep that the wagons had to be hauled by block
and tackle. The plant consisted of five engines, two water-wheels,
five air compressors, eight 70 H. P. steam-boilers, four large exhaust
fans, two complete electric arc-lighting plants, two fully equipped
machine-shop outfits, 36 air drills, two locomotives, 60 dump cars,
and two sawmill outfits, with the necessary accessories for these
various machines. This plant was divided about equally between the
two ends of the tunnel. The cost of the plant and of the work of
getting it into position was $125,000.
Graveholz Tunnel.—The Graveholz tunnel on the Bergen Railway in
Norway is notable as being the longest tunnel in northern Europe,
and also as being built for a single-track narrow-gauge railway. This
tunnel is 17,400 feet long, and is located at an elevation of 2900 feet
above sea-level. Only about 3% of the length of the tunnel is lined.
The mechanical installation consists of a turbine plant operating the
various machines. There are two turbines of 100 H. P. and 120 H. P.
taking water from a reservoir on the mountain slope, and furnishing
220 H. P., which is distributed about as follows: Boring-machines, 60
H. P.; ventilation, 30 to 40 H. P.; electric locomotives, 15 H. P.;
machine shop, 15 H. P.; electric-lighting dynamo, 25 H. P.; electric
drills, the surplus, or some 40 H. P. The boring-machines and electric
drills will be operated by the smaller 100 H. P. turbine.
Sonnstein Tunnel.—The Sonnstein tunnel in Germany is
particularly interesting because of the exclusive use of Brandt rotary
drills. The tunnel was driven through dolomite and hard limestone by
means of a drift and two side galleries. The dimensions of the drift
were 71⁄2 × 71⁄2 ft. The power plant consisted of two steam
pressure pumps, one accumulator, and four drills. The steam-boiler
plant, in addition to operating the pumps, also supplied power for
operating a rotary pump for drainage and a blower for ventilation.
The hydraulic pressure required was 75 atmospheres in the
dolomite, and from 85 to 100 atmospheres in the limestone. The
drift was excavated with five 31⁄2 in. holes, one being placed at the
center and driven parallel to the axis of the tunnel, and four being
placed at the corners of a rectangle corresponding to the sides of
the drift, and driven at an angle diverging from the center hole. The
average depths of the holes were 4.3 ft., and the efficiency of the
drills was 1 in. per minute. One drill was employed at each front,
and was operated by a machinist and two helpers, who worked
eight-hour shifts, with a blast between shifts at first, and later
twelve-hour shifts, with a blast between shifts. The 24 hours of the
two shifts were divided as follows: boring the holes, 10.7 hours;
charging the holes, 1.1 hours; removing the spoil, 11.7 hours;
changing shifts, 0.5 hour. The average progress per day for each
machine was 6.7 ft. The total cost of the plant was $17,450.
St. Clair River Tunnel.—The submarine double-track railway tunnel
under the St. Clair River for the Grand Trunk Ry. is 8500 ft. long, and
was driven through clay by means of a shield, as described in the
succeeding chapter on the shield system of tunneling. The
mechanical plant installed for prosecuting the work was very
complete. To furnish steam to the air compressors, pumps, electric-
light engines, hoisting-engines, etc., a steam-plant was provided on
each side of the river, consisting of three 70 H. P. and four 80 H. P.
Scotch portable boilers. The air-compressor plant at each end
consisted of two 20 × 24 in. Ingersoll air compressors. To furnish
light to the workings, two 100 candle-power Edison dynamos were
installed on the American side, and two Ball dynamos of the same
size were installed on the Canadian side. The dynamos on both sides
were driven by Armington & Sims engines. These dynamos furnished
light to the tunnel workings and to the machine-shops and power-
plant at each end. Root blowers of 10,000 cu. ft. per minute capacity
provided ventilation. The pumping plant consisted of one set of
pumps installed for permanent drainage, and another set installed
for drainage during construction, and also to remain in place as a
part of the permanent plant. The latter set consisted of two 500
gallon Worthington duplex pumps set first outside of each air lock,
closing the ends of the river portion of the tunnel. For permanent
drainage, a drainage shaft was sunk on the Canadian side of the
river, and connected with a pump at the bottom of the open-cut
approach. In this shaft were placed a vertical, direct-acting,
compound-condensing pumping engine with two 191⁄2 in. high-
pressure and two 333⁄8 in. low-pressure cylinders of 24 in. stroke,
connected to double-acting pumps with a capacity of 3000 gallons
per minute, and also two duplex pumps of 500 gallons capacity per
minute. For permanent drainage on the American side, four
Worthington pumps of 3000 gallons’ capacity were installed in a
pump-house set back into the slope of the open-cut approach. For
the permanent drainage of the tunnel proper two 400 gallon pumps
were placed at the lowest point of the tunnel grade. Spoil coming
from the tunnel proper was hoisted to the top of the open cut by
derricks operated by two 50 H. P. Lidgerwood hoisting-engines. The
pressure pumping plant for supplying water to the hydraulic shield-
jacks at each end of the tunnel consisted of duplex direct-acting
engines with 12 in. steam cylinders and 1 in. water cylinders,
supplying water at a pressure of 2000 lbs. per sq. in.
CHAPTER X.

TUNNELS THROUGH HARD ROCK (Continued).

EXCAVATION BY DRIFTS: THE SIMPLON AND MURRAY HILL


TUNNELS.
General Description.—The
method of tunneling through hard rock
by drifts is preferred by European
engineers. All the great Alpine tunnels,
from the Mont Cenis tunnel to the
Simplon, are examples of tunneling by
drifts. In this method the sequence of
excavation is shown diagrammatically
by Fig. 55. The work begins by
excavating a drift close to the floor of
the proposed tunnel (as shown in the
Fig. 55.—Diagram Showing center of the figure) and far in
Sequence of Excavations in advance of the excavation of any other
Drift Method of Tunneling part. The section marked 2 is next
Rock.
removed and still later the portions
marked 3. Then with the removal of the parts marked 4 the whole
section of the tunnel will be open.
The drift is usually strutted by means of side posts carrying a
cap-piece placed at intervals, and having a ceiling of longitudinal
planks resting on the successive caps. In hard rock the roof of the
section does not, as a rule, require regular strutting, occasional
supports being placed at intervals to prevent the fall of isolated
fragments: When the rock is disintegrated or full of seams, a regular
strutting may be necessary, and this may be either longitudinal or
polygonal in type. When longitudinal strutting is employed, a sill is
laid across the roof of the drift, and upon this are set up two struts
converging toward the top and supporting a cap-piece close to the
roof. On this cap-piece are placed the first longitudinal crown bars
carrying transverse poling-boards. Additional props standing on the
sill and radiating outward are inserted as parts No. 3 are excavated.
These radial props carry longitudinal bars which in turn support
transverse poling-boards. When polygonal strutting is used, it may
take the form of three or five segment arches of heavy timbers.
In hard rock tunnels, as a rule, there is no danger of caving in
because of heavy pressures, and the whole section is left open for
some time before it is lined. The lining may be of concrete masonry,
but in many long tunnels, excavated through hard rock, the side
walls are lined with rubble masonry and the arch with brick, and, in
some instances, even the arch has been lined with rubble masonry.
With skilful laborers at hand the rubble masonry lining has proved
most efficient and economical, because the rock is utilized as it is
excavated without any further operation. Concrete, however, is more
extensively employed for lining tunnels than any other material.
Tunnels excavated by drifts enable simple means of hauling to be
employed, and this is one of the reasons why the method finds so
much favor with European engineers. The tracks are laid along the
floor of the drift, and carry all the spoil from parts Nos. 2, 3, and 4,
as well as from the front of the drift itself. As fast as the full section
is completed, this single track in the drift is replaced by two tracks
running close to the sides of the tunnel, or by a broad-gauge track
with a third rail.

THE SIMPLON TUNNEL.[8]

Before entering upon a description of the constructive details of


this, the longest railway tunnel in the world, it may be well to give a
general idea of the undertaking. Many schemes for the connection of
Italy and Switzerland by a railway near the Simplon Road Pass have
been devised, including one involving no great length of
underground work, the line mounting by steep gradients and sharp
curves. The present scheme, put forward in 1881 by the Jura-
Simplon Ry. Co., consists broadly of piercing the Alps between
Brigue, the present railway terminus in the Rhone Valley, and Iselle,
in the gorge of the Diveria, on the Italian side, from which village
the railway will descend to the existing southern terminus at Domo
d’Ossola, a distance of about 11 miles.
[8] Abstract from a paper read before the Institution of Civil Engineers by
Charles B. Fox, Jan. 26, 1900.
In conjunction with this scheme a second tunnel is proposed, to
pierce the Bernese Alps under the Lötschen Pass from Mittholz to a
point near Turtman in the Rhone Valley; and thus, instead of the
long détour by Lausanne and the Lake of Geneva, there will be an
almost direct line from Berne to Milan via Thun, Brigue, and Domo
d’Ossola.
Starting from Brigue, the new line, running gently up the valley
for 11⁄4 miles, will, on account of the proximity of the Rhone, which
has already been slightly diverted, enter the tunnels on a curve to
the right of 1050 ft. radius. At a distance of 153 yards from the
entrance, the straight portion of the tunnel commences, and extends
for 12 miles. The line then curves to the left with a radius of 1311 ft.
before emerging on the left bank of the Diveria. Commencing at the
northern entrance, a gradient of 1 in 500 (the minimum for efficient
drainage) rises for a length of 51⁄2 miles to a level length of 550
yards in the center, and then a gradient of 1 in 143 descends to the
Italian side. On the way to Domo d’Ossola one helical tunnel will be
necessary, as has been carried out on the St. Gothard. There will be
eventually two parallel tunnels having their centers 56 ft. apart, each
carrying one line of way; but at the present time only one heading,
that known as No. 1, is being excavated to full size, No. 2 being left,
masonry lined where necessary, for future developments. By means
of cross headings every 220 yds. the problems of transport and
ventilation are greatly facilitated, as will be seen later. As both
entrances are on curves, a small “gallery of direction” is necessary,
to allow corrections of alinement to be made direct from the two
observatories on the axis of the tunnel.
The outside installations are as nearly in duplicate as
circumstances will allow, and consist of the necessary offices,
workshops, engine-sheds, power-houses, smithies, and the
numerous buildings entailed by an important engineering scheme.
Great care is taken that the miners and men working in the tunnel
shall not suffer from the sudden change from the warm headings to
the cold Alpine air outside; and for this purpose a large building is in
course of erection, where they will be able to take off their damp
working clothes, have a hot and cold douche, put on a warm dry
suit, and obtain refreshments at a moderate cost before returning to
their homes. Instead of each man having a locker in which to stow
his clothes, a perfect forest of cords hangs down from the wooden
ceiling, 25 ft. above floor-level, each cord passing over its own
pulleys and down the wall to a numbered belaying-pin. Each cord
supports three hooks and a soap-dish, which, when loaded with their
owner’s property, are hauled up to the ceiling out of the way. There
are 2000 of these cords, spaced 1 ft. 6 ins. apart, one to each man.
The engineers and foremen are more privileged, being provided with
dressing-rooms and baths, partitioned off from the two main halls.
An extensive clothes washing and drying plant has been laid down,
and also a large restaurant and canteen. At Iselle, a magazine
holding 2200 lbs. of dynamite is surrounded and divided into two
separate parts by earth-banks, 16 ft. high. The two wooden houses,
in which the explosive is stored, are warmed by hot-water pipes to a
temperature between 61° F. and 77° F., and are watched by a
military patrol; but at Brigue a dynamite manufactory, started by an
enterprising company at the time of the commencement of the
works, supplies this commodity at frequent intervals, thereby
avoiding the necessity of storing in such large quantities. This
dynamite factory has been largely increased, and supplies dynamite
to nearly all the mining and tunneling enterprises in Switzerland.
Geological Conditions.—Before the Simplon tunnel was
authorized, expert evidence was taken as to the feasibility of the
project. The forecasts of the three engineers chosen, in reference to
the rock to be encountered and its probable temperature, have, as
far as the galleries have gone (an aggregate distance of nearly 21⁄2
miles), generally been found correct. At the north end, a dark
argillaceous schist veined with quartz was met with, and from time
to time beds of gypsum and dolomite have been traversed, the dip
of the strata being on the whole favorable to progress, though
timbering is resorted to at dangerous places. Water was plentiful at
the commencement; in fact, one inrush has not been stopped, and is
still flowing down the heading. The total quantity of water flowing
from the tunnel mouth is 16 gallons per second, of which 2 gallons
per second are accounted for by the drilling machines. At Iselle,
however, a very hard antigorio gneiss obtains, and is likely to extend
for 4 miles. Very dry and very compact, it requires no timbering, and
represents no great difficulty to the powerful Brandt rock-drills,
which work under a head of 3280 ft. of water.
The temperature of the rock depends not only on the depth from
the surface, but largely upon the general form of that surface
combined with the conductivity of the rock. Taking these points into
consideration with the experience gained from the construction of
the St. Gothard tunnel, 95° F. was estimated as the probable
maximum temperature, owing to the height of Monte Leone (11,660
ft.), which lies almost directly over the tunnel axis.
Survey.—After having determined upon the general position of
the tunnels, taking into consideration the necessary gradients, the
temperature of the rock, and a large bed of troublesome gypsum on
the north side, two fixed points on the proposed center line were
taken, one at each entrance of tunnel No. 1, and the bearings of
these two points, with reference to a triangulation survey made in
1876, were calculated sufficiently accurately to determine, for the
time being, the direction of the tunnel. In 1898, a new triangulation
survey was made, taking in eleven summits, Monte Leone holding
the central position. This survey was tied into that of the Wasenhorn
and Faulhorn, made by the Swiss Government, and the accuracy was
such that the probable error in the meeting of the two headings is
only 6 cms. or 21⁄2 ins.
On the top of each summit is placed a signal, consisting of a
small pillar of masonry founded on rock, and capped with a sharp
pointed cone of zinc, 1 ft. 6 ins. high. An observatory was built at
each end of the tunnel in such a position that three of the summits
could be seen, a condition very difficult to fulfill on the south side
owing to the depth of the gorge, the mountains on either side being
over 7000 ft. high. Having taken the angles to and from each visible
signal, and therefrom having calculated the direction of the tunnel, it
was necessary to fix, with extreme accuracy, sighting-points on the
axis of the tunnel, in order to avoid sighting on to the surrounding
peaks for each subsequent correction of the alinement of the
galleries. To do this, a theodolite 24 ins. long and 23⁄8 ins. in
diameter, with a magnifying power of 40 times, was set up in the
observatory, and about 100 readings were taken of the angles
between the surrounding signals and the required sighting-points. In
this manner the error likely to occur was diminished to less than 1′.
Thus at the north end two points were found about 550 yds. before
and behind the observatory, while on the south side, owing to the
narrowness of the gorge, the points could only be placed at 82 yds.
and 126 yds. in front. One of these sighting-points consists of a fine
scratch ruled on a piece of glass fixed in an iron frame, behind which
is placed an acetylene lamp,—corrections of alinement are always
done by night,—the whole being rigidly fixed into a niche cut in the
rock and protected from climatic and other disturbing agencies by an
iron plate.
Method of Checking Alinement.—The direction of heading No.
1 is checked by experts from the Government Survey Department at
Lausanne about three times a year, and for this purpose a transit
instrument is set up in the observatory. A number of three-legged
iron tables are placed at intervals of 1 mile or 2 miles along the axis
of tunnel No. 1, and upon each of these is placed a horizontal plane,
movable by means of an adjusting screw, in a direction at right
angles to the axis, along a graduated scale. On this plane are small
sockets, into which the legs of an acetylene lamp and screen, or of
the transit instrument, can be quickly and accurately placed. The
screen has a vertical slit, 3 ins. in height, and variable between 13⁄16
in. and 3⁄16 in. in breadth, according to the state of the atmosphere,
and at a distance shows a fine thread of light. The instrument,
having first been sighted on to the illuminated scratch of the
sighting-point, is directed up the tunnel, where a thread of light is
shown from the first table. With the aid of a telephone this light is
adjusted so that its image is exactly coincident with the cross hairs,
and the reading on the graduated scale is noted. This is done four or
five times, the average of these readings being taken as correct, and
the plane is clamped to that average. The instrument is then taken
to the first table and is placed quickly and accurately over the point
just found (by means of the sockets), and the lamp is carried to the
observatory. After first sighting back, a second point is given on the
second table, and so on. These points are marked either temporarily
in the roof of the heading by a short piece of cord hanging down, or
permanently by a brass point held by a small steel cylinder, 8 ins.
long and 3 ins. in diameter, embedded in concrete in the rock floor,
and protected by a circular casting, also sunk in cement concrete,
holding an iron cover resembling that of a small manhole. From time
to time the alinement is checked from these points by the engineers,
and after each blast the general direction is given by the hand from
the temporary points. To check the results of the triangulation
survey, astronomical observations have been taken simultaneously at
each end. With regard to the levels, those given on the excellent
Government surveys have been taken as correct, but they have also
been checked over the pass.
Details of Tunnels.—In cross-section, tunnel No. 1 is 13 ft. 7
ins. wide at formation level, increasing to 16 ft. 5 ins., with a total
height of 18 ft. above rail-level, and a cross-sectional area of about
250 sq. ft. This large section will allow of small repairs being
executed in the roof without interruption of the traffic, and will also
allow of strengthening the walls by additional masonry on the inside.
The thickness of the lining, never wholly absent, and the material of
which it is composed, depend upon the pressure to be resisted, and
only in the worst case is an invert resorted to. The side drain, to
which the rock floor is made to slope, will be composed of half-pipes
of 7 to 1 cement concrete. The roof is constructed of radial stones.
Tunnel No. 2, being left as a heading, is driven on that side
nearest to No. 1, to minimize the length of the cross-headings, and
measures 10 ft. 2 ins. wide by 6 ft. 7 ins. high. Masonry is used only
where necessary, and in that case is so built as to form part of the
lining of the tunnel when eventually completed. Concrete is put in to
form a foundation for the side wall, and a water channel. The cross-
headings, connecting the two parallel headings, occur every 220
yds., and are placed at an angle of 56° to the axis of the tunnel, to
avoid sharp curves in the contractors’ railway lines. They will
eventually be used as much as possible for refuges, chambers for
storing the tools and equipment of the platelayers, and signal-
cabins. The refuges, 6 ft. 7 ins. wide by 6 ft. 7 ins. high and 3 ft. 3
ins. deep, occur every 110 yards, every tenth being enlarged to 9 ft.
10 ins. wide by 9 ft. 10 ins. deep and 10 ft. 2 ins. high, still larger
chambers being constructed at greater intervals.
Method of Excavation.—The work at each end of the tunnel is
carried on quite independently, consequently, though similar in
principle, the methods vary in detail, apart from the fact that
different geological strata require different treatment. Broadly
speaking, the two parallel headings, each 59 sq. ft. in section, are
first driven by means of drilling-machines and the use of dynamite,
this work being carried on day and night, seven days in the week;
No. 1 heading is then enlarged to full size by hand-drilling and
dynamite. On the Italian side, where the rock is hard and compact,
breakups are made at intervals of 50 yds., and a top gallery is driven
in both directions, but, for ventilation reasons, is never allowed to
get more than 4 yds. ahead of the break-up, which is gradually
lengthened and widened to the required section. No timbering is
required, except to facilitate the excavation and the construction of
the side walls. Steel centers are employed for the arch; they entail
fewer supports, give more room, and are capable of being used over
again more frequently without damage. They consist of two I-beams
bent to a template and riveted together at the crown, resting at
either side on scaffolding at intervals of 6 ft.; longitudinals 12 ft. by
4 ins. by 4 ins. support the roof. Hand rock-drilling is carried out in
the ordinary way, one man holding the tool and a second striking;
measurements of excavation are taken every 2 or 3 yds., a plumb-
line is suspended from the center of the roof, and at every half-
meter (20 ins.) of height horizontal measurements are taken to each
side.
At the Brigue end a softer rock is encountered, necessitating at
times heavy timbering in the heading, and especially in the final
excavation to full size, Fig. 56. The bottom heading, 6 ft. 6 in. high,
is driven in the center, and the heading is then widened to the full
extent and timbered; the concrete forming the water channel and
the foundation for one side wall is put in; the side walls are built to a
height of 6 ft. 6 ins., and the tunnel is fully excavated to a further
height of 6 ft. 6 ins. from the first staging. The side walls are then
continued up for the second 6 ft. 6 ins., and from the second floor a
third height of 6 ft. 6 ins. is excavated and timbered. Finally the
crown is cleared out, heavy wooden centers are put in, the arch is
turned and all timbers are withdrawn except the top poling-boards,
supporting the loose rock.

1 2

3 4
5 6

7 8

Fig. 56.—Sketches Showing Sequence of Work in Excavating and Lining the


Simplon Tunnel.

The masonry for the side walls is obtained either from the tunnel
itself or from a neighboring quarry, and varies in character according
to the pressure; but the face of the arch is always of cut or artificial
stones, the latter being 7 to 1 cement concrete. Where the
alinement heading, or the “gallery of direction,” joins the curving
portion of tunnel No. 1, the section is very much greater, and
necessitates special timbering.
Transport (Italian Side).—A small line of railway, 2 ft. 71⁄2 ins.
gauge, with 40-lb. rails, enters all three portals; but since the
construction of a wooden bridge over the Diveria, the route through
the “gallery of direction,” across heading No. 2, to tunnel No. 1, is
used exclusively; this railway leads to the face in both headings,
and, where convenient, from one heading to the other by the cross-
galleries. Different types of wagons are in use; but in general they
are four-wheeled, non-tipping box wagons, supplied with brakes and
holding 2 cu. yds. of débris. A special type of locomotive is used,
designed to pass round curves of 50 ft. radius, and supplied with a
specially large boiler to avoid firing in the tunnel.
Fig. 57.—General Details of the Brandt Rotary Drills Employed at the Simplon
Tunnel.
Larger illustration

Method of Working.—The drilling-machines employed are of the


Brandt type, Fig. 57, and are mounted in the following manner: A
small four-wheeled carriage supports at its center a beam, the
shorter arm of which carries the boring mechanism and the longer a
counterpoise; near its center is the distributor. In the short arm is a
clamp holding the rack-bar or butting column, which is a wrought-
iron cylinder with a plunger constituting a ram, and is jammed by
hydraulic pressure between the walls of the heading, thus forming a
rigid support for the boring-machine, and an efficient abutment
against the reaction of the drill. This rack-bar can be rotated on its
clamp in a plane parallel to the axis of the beam. Three or four
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like