Download Python Programming 4th Edition Singh A. ebook now - free full chapters
Download Python Programming 4th Edition Singh A. ebook now - free full chapters
com
https://ebookgate.com/product/python-programming-4th-
edition-singh-a/
OR CLICK HERE
DOWLOAD NOW
https://ebookgate.com/product/python-programming-for-teens-1st-
edition-kenneth-a-lambert/
ebookgate.com
https://ebookgate.com/product/expert-python-programming-2nd-edition-
jaworski/
ebookgate.com
https://ebookgate.com/product/core-python-programming-2nd-edition-
wesley-chun/
ebookgate.com
https://ebookgate.com/product/programming-python-3rd-ed-edition-mark-
lutz/
ebookgate.com
Ultimate Python Programming 1st Edition Deepali Srivastava
https://ebookgate.com/product/ultimate-python-programming-1st-edition-
deepali-srivastava/
ebookgate.com
https://ebookgate.com/product/black-hat-python-python-programming-for-
hackers-and-pentesters-1st-edition-seitz/
ebookgate.com
https://ebookgate.com/product/practical-maya-programming-with-
python-1st-edition-galanakis/
ebookgate.com
https://ebookgate.com/product/learning-beaglebone-python-programming-
unleash-the-potential-of-beaglebone-using-python-1st-edition-hiam/
ebookgate.com
https://ebookgate.com/product/foundations-of-python-network-
programming-third-edition-brandon-rhodes/
ebookgate.com
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
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.
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.
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:
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
Lists
List Literal Values
List Operations
List Comparison Operations
List Statements
List Built-in Functions
List Methods
Stack & queue using list
Copy list
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.
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 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
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.
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-
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.
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
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.
Finally, if the installation process is a success, the following window will appear:
£• Python 3.10.5 (64-bit) Setup
See what's new in this release, or find more info about using
Python on Windows.
python
for
windows Close
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.
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
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.
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
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
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.
class Foo:
def _init_ (self, x: str):
self.x = x
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)
StrEnum
The StrEnum makes an appearance. It allows to automatically convert a character string into an Enum.
Path
The Path.glob() method of pathlib now allows you to specify whether you only want to retrieve folders.
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.
> > > 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
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:
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.
Exiting Python
To exit from Python, you can type any of these commands:
quit()
exit()
Control-Z then press enter
Recently added
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 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.
Save Ctrl+S
Save As... Ctrl*Shift*S
Save Copy As... Alt*Shift*S
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:
j untitled X
File Edit Format Run Options Window Help
For example, type/copy the command below. This command will print the famous expression of Hello World”
print ("Hello World")
This is how the syntax would look like in the “untitled” box:
“untitled* — OX
File Edit Format Run Options Window Help
print ("Hello World") a
Ln: 16 Col: 0
Press F5 on your keyboard. You will then get the following message to save your code:
Cancel
Once you’re done, press Save, and you’ll then see the “Hello World” expression printed on your Python Shell:
Chapter 4
Python Syntax
Python Coding Style:
• Use spaces per indentation and no tabs.
• Do not mix tabs and spaces. Tabs create confusion and it is recommended to use only spaces.
• Maximum line length: 79 characters which help users with a small display.
• Use blank lines to separate top-level function and class definitions and single blank line to
separate methods definitions inside a class and larger blocks of code inside functions.
• When possible, put inline comments (should be complete sentences).
Python provides no braces to indicate blocks of code for class and function definitions or flow control.
Blocks of code are denoted by line indentation, which is rigidly enforced.
Indentation
While most programming languages such as Java, C, and C++ use braces to denote blocks of code, Python
programs are structured through indentation. In Python, blocks of codes are defined by indentation not
as a matter of style or preference but as a rigid language requirement. This principle makes Python codes
more readable and understandable.
A block of code can be easily identified when you look at a Python program as they start on the same
distance to the right. If it has to be more deeply nestled, you can simply indent another block further to the
right. For example, here is a segment of a program defining car_rental_cost:
def car_rental_cost(days):
cost =35 *days
if days >= 8:
cost-= 70
elif days > = 3:
cost-= 20
return cost
You have to make sure that the indent space is consistent within a block. When you use IDLE and other
IDEs to input your codes, Python intuitively provides indentation on the subsequent line when you enter a
statement that requires indentation. Indentation, by convention, is equivalent to 4 spaces to the right.
The number of spaces in the indentation is variable, but all statements within the block must be indented
the same amount. For example -
if True:
print "True"
else:
print "False"
Keywords
Python keywords are reserved words in Python that should not be used as variable, constant, function
name, or identifier in your code. Take note of these keywords if you dont want to run into errors when you
execute your program:
and assert raise
break class try
continue def with
del elif True
else except None
exec finally return
for from while
Another Random Document on
Scribd Without Any Related Topics
[651] Calvin, Hist. de l'Esprit des Cordeliers d'Orléans. Geneva
MS. (Bulletin de l'Histoire du Protestantisme Français, iii.) Beza,
Hist. Eccles. p. 11. Sleidan, i. p. 361.
[652] Calvin's MS. Bulletin de l'Hist. du Prot. Fran. iii. p. 36.
[653] Lutheri Opp. xxii. p. 1463.
[654] History of the Reformation of the Sixteenth Century,
vol. ii. bk. viii. ch. ii.
CHAPTER XXXVI.
FRANCIS PROPOSES A REFORMATION TO THE SORBONNE.
(Autumn 1534.)
Sorbonne.
'We have heard his Majesty's good and holy words, for which we
all thank God, praying him to give the king grace to persevere.'[667]
This was doubtless a mere compliment.
~QUESTIONS DISCUSSED.~
Ministers.
'Above all things, let us remember that the doctors of the Word of
God ought not to fight like gladiators, and defend all their opinions
mordicus (tooth and nail);[668] but rather, imitating St. Augustin in his
Retractations, they should be willing to give way a little to one
another ... without prejudice to truth.'
Sorbonne.
'Open your eyes, Sire; the Germans desire, in opposition to your
catholic intention, that we should give way to them by retrenching
certain ceremonies and ordinances which the Church has hitherto
observed. They wish to draw us to them, rather than be converted
to us.'[669]
Ministers.
'You are mistaken: important concessions have been obtained.
The Germans are of opinion that bishops must hold the chief place
among the ministers of the Churches, and that a pontiff at Rome
should hold the first place among the bishops. But, on the other
hand, the pontifical power must have respect for consciences,
consult their wants, and be ready to concede to them some
relaxation.'[670]
Sorbonne.
'It must not be forgotten that the ecclesiastical hierarchy is of
divine institution, and will last until the end of time; that man can
neither establish nor destroy it, and that every christian must submit
to it.'[671]
Ministers.
'Having established the catholicity of the Church, let us consider
what reforms must be effected in order to preserve it. First, there
are indifferent matters, such as food, festivals, ecclesiastical
vestments, and other ceremonials, on which we shall easily come to
an understanding. Let us beware of constraining men to fast by
commandments which nobody observes ... and least of all those
who make them.'[672]
Sorbonne.
Ministers.
'Certain doctors of the Church, making use of a holy prosopopœia,
have introduced into their discourses the saints whom they were
eulogising, and have prayed for their intercession as if they were
present before them;[674] but they only desired by this means to
excite admiration for these godly persons, rather than to obtain
anything by their intercession.... Let the people, then, be exhorted
not to transfer to the saints the confidence which is due to Jesus
Christ alone. It is Christ's will to be invoked and to answer
prayer.'[675]
Here the French mind indulged in a sly hit which would not have
occurred to the German mind; and the king's councillors,
determining to strike hard, continued:
'What abuses and disorders have sprung out of this worship of
man! Observe the words, the songs, the actions of the people on the
saints' days, near their graves or near their images! Mark the
eagerness with which the idle crowd hurries off to banquets, games,
dances, and quarrels. Watch the practices of all those paltry,
ignorant, greedy priests, who think of nothing but putting money in
their purses; and then ... tell us whether we do not in all these
things resemble pagans, and revive their shameful superstitions?'[676]
Not a word of this popular description of saints' days will be found
in Melanchthon's memoir: it is entirely the work of Francis and his
councillors.
Sorbonne.
'Let us beware how we forsake ancient customs. Let us address
our prayers directly to the saints who are our patrons and
intercessors under Jesus Christ. To assert that they have not the
prerogative of healing diseases, is in opposition to your Majesty's
personal experience and the gift you have received from God of
curing the king's evil.... Let us also pay our devotions to statues and
images, since the seventh general council commands them to be
adored.'[677]
When the Sorbonne, in order to defend the prerogatives of the
saints, cited the miraculous powers of the king, they employed an
argument to which it was dangerous to reply; and, accordingly, we
find nothing on this point in the answers of the opponents of the
faculty. The discussion, getting off this shoal, turned to the act which
is the essence of the Romish doctrine, and priests were once more
lashed by the royal hand, which was even more skilful at this work
than in curing the evil.
Ministers.
'There ought to be in the Church a living communion of the
members of Christ.[678] But, alas! what do we find there? A crowd of
ignorant and filthy priests, the plague of society, a burden to the
earth, a slothful race who can do nothing but say mass, and who,
while saying it, do not even utter those five intelligible words,
preferable, as St. Paul thinks, to ten thousand words in an unknown
tongue.... We must get rid of these mercenaries, these mass-
mongers, who have brought that holy ceremony into contempt, and
we must supply their place with holy, learned, and experienced men.
[679] Then perhaps the Lord's Supper will recover the esteem it has
Sorbonne.
'The mass is a real sacrifice, of great benefit to the living and the
dead, and its excellence is founded on the passion of Jesus Christ. It
is right, therefore, to bestow temporal gifts on those who celebrate
it, be they good or bad; and the priests who receive them ought not
to be called mass-mongers, even though they are paid.'[681]
The king's ministers now came to the much disputed doctrine of
the presence of Christ in the communion.
Ministers.
'Let us put aside the disputes that have divided us so long.[682] Let
us all confess that in the eucharist the Lord truly gives believers his
body to eat and his blood to drink to feed our souls in life
everlasting; and that in this manner Christ remains in us and we in
Christ. Whether this sacrament be called the Lord's Supper, the
Lord's bread and wine, mass, eucharist, love-feast, or sacrifice, is of
little moment. Christians ought not to dispute about names, if they
possess the things; and, as the proverb says, "When we have the
bear before us, let us not look after his track."[683] Communion with
Christ is obtained by faith, and cannot be demonstrated by human
arguments. When we treat of theology, let us not fall into
matæology.'[684]
The Sorbonne could not overlook this side-blow aimed at the
scholastic style.
Sorbonne.
'It is very useful, and often very necessary for the extirpation of
heresy, to employ words not to be found in Scripture, such as
transubstantiation, &c.[685] Yes, the bread and the wine are truly
changed in substance, preserving only the accidents, and becoming
the body and blood of Christ. It is not true that the panitas or
corporitas of the bread combines with the corporitas of Christ. The
transubstantiation is effected in instanti and not successivè; and it is
certain that neither laymen nor women can accomplish this
miraculous act, but priests only.'
The controversy next turned on confession, justification, faith,
works, and free-will; after which they came to practical questions.
Ministers.
'Good men do not ask that the monasteries should be destroyed,
but be turned into schools;[686] so that thus the liberality of our
brethren may serve to maintain, not idle people, but men who will
instruct youth in sound learning and morality.'
Sorbonne.
'What! the pope should permit the friars to leave their monasteries
whenever they wish! This clearly shows us that the Germans are
aiming at the overthrow, the ruin of all religion.'[687]
Ministers.
'And what prevents our restoring liberty of marriage to the
ministers of the Church? Did not Bishop Paphnucius acknowledge at
the Nicene council that those who forbid it encourage licentiousness?
In that great crowd of priests and monks it is impossible for purity of
life to be restored otherwise than by the divine institution which
dates from Eden.'[688]
Sorbonne.
'An article quite as dangerous as the secularisation of monks.'
=AN ASSEMBLY OF LAITY AND CLERGY.=
Ministers.
'In this age, when everything is in a ferment,[689] and when so
many sects are raising their heads in various places, the interest of
the christian Church requires that there should be an assembly
composed not only of priests and theologians, but also of laymen
and upright, sensible, courageous magistrates, who have at heart
the glory of the Lord, public morality, and general usefulness.... Ah!
it would be easy to agree if we thought of Christ's glory rather than
of our own!'[690]
The doctors of the Sorbonne had no great liking for deliberative
assemblies where they would sit with laymen and even with heretics.
Sorbonne.
'Beware! ... it is to be feared that, under the pretext of uniting
with us, the heretics are conspiring to lead the people astray.... Have
we not seen such assemblies in Germany, called together on a
pretence of concord, produce nothing but divisions, discord, and
infinite ruin of souls?'[691]
But the Sorbonne warned the king in vain. Francis at this time,
through policy no doubt, was opposed to the doctrines maintained
by the priests. He desired to be freed at home from that papal
supremacy which presumed to direct the policy and religion of his
kingdom; and abroad he knew that a league with England and
Germany could alone destroy the overwhelming preponderance of
Charles V. And hence the meetings of the Sorbonne grew more and
more agitated; the doctors repeated to one another all the alarming
reports they had heard; there was sorrow and anger; never, they
thought, had Roman-catholicism in France been threatened with
such terrible danger. It was no longer a few obscure sects; no longer
a Brueys, a Henry of Lausanne, a Valdo, Albigenses, or Waldenses,
who attacked the Church: no! powerful states, Germany and
England, were separating from the papacy, and the absolute
monarch of France was endeavouring to introduce revolutionary
principles into his kingdom. The Church, as its Head had once been,
was deserted by its friends. The grandees who were subsequently to
form a league around the Guises, were silent now; the rough and
powerful Montmorency himself seemed dumb; and, accordingly,
agitation and alarm prevailed in the corporation. Certain
ultramontane fanatics proposed petitioning the king to put down
heresy by force, and to uphold the Roman dogmas by fire and
sword. More moderate catholics, observing with sorrow the
catholicity so dear to them rent by schism, sought for more rational
means of restoring the unity destroyed by the Reformation.
Everybody saw clearly that the enemy was at the gate, and that no
time must be lost in closing it.
=DANGER OF CATHOLICISM.=
Alas! they had to deal with others besides heretics. All reflecting
minds in Europe, and especially in France, were struck with the
example set by the King of England, and the members of the Roman
party thought that Francis was about to adopt the same course in
his kingdom. There was indeed a difference between the systems of
these two princes. Henry desired the doctrine of Rome, but not its
bishop; Francis accepted the bishop, but rejected the doctrine.
Nevertheless, as each of these reforms was a heavy blow aimed at
the system of the middle ages, they were looked upon as identical.
The success which Henry's plan had met with in England was an
indication of what Francis's plan would meet with in France. The two
monarchs who reigned on each side of the Channel were equally
absolute.
The Roman doctors, finding that their controversy had not
succeeded, resolved to go to work in a more cunning way, and,
without seeming to reject a union with Germany, to oppose the
heretics by putting them out of court. 'Sire,' they said to Francis,
'your very humble servants and most obedient subjects of the
Faculty of Theology pray you to ask the Germans whether they
confess that the Church militant, whose head (under Jesus) is Peter
and his successors, is infallible in faith and morals? whether they
agree to obey him as his subjects, and are willing to admit all the
books contained in the Bible,[692] as well as the decisions of the
councils, popes, and doctors?'[693] Obedience to the pope and to
tradition, without discussing doctrines, was their summary of the
controversy. It did not succeed.
=SHOULD KINGS FEAR PROTESTANTISM?=
The doctors of the faculty, finding that the king would not aid
them, applied to the papal nuncio. They found him also a prey to
fear. They began to consult together on the best means of keeping
France in communion with the holy see. As Francis was deaf to
theological arguments, the Sorbonne and the nuncio agreed that
some other means must be used. The prelate went to the Louvre,
carrying with him a suggestion which the Sorbonne had prompted.
'Sire,' he said, 'be not deceived. The protestants will upset all civil as
well as religious order.... The throne is in as much danger as the
altar.... The introduction of a new religion must necessarily introduce
a new government.'[694]
That was indeed the best way of treating the affair; the nuncio
had found the joint in the armour, and the king was for a moment
staggered; but the pope's conduct restored his confidence. Rome
began to proceed against Henry VIII. as she had formerly done
against kings in the middle ages. This proceeding, so offensive to
the royal dignity, drew Francis towards the Reformation. If there is
danger towards royal power, it exists on both sides, he thought. He
believed even that the danger was greater on the side of Rome than
of Germany, since the protestants of that country showed their
princes the most loyal submission, and the most religious and
profound respect. He had observed, that while the pope desired to
deprive the King of England of his states and release his subjects
from their obedience, the reformation which that prince had carried
out had not prejudiced one of his rights; that there was a talk,
indeed, of insurrections against Henry VIII., but they were got up by
Rome and her agents. Enlightened men suggested to Francis, that
while popery kept the people in slavery, and caused insurrection and
rebellion against the throne, the Reformation would secure order
and obedience to kings, and liberty to the people. He seems to have
been convinced ... for the moment at least. 'England and I,' he said,
'are accustomed to keep together and to manage our affairs in
harmony with each other, and we shall continue to do so.'[695]
This new movement on the part of Francis emboldened the
evangelicals. They hoped that he would go on to the end, and would
not leave the pope even the little place which he intended to reserve
for him. If a prince like Louis IX. maintained the rights of the
Gallican Church in the thirteenth century; if a king like Charles VII.
restored ecclesiastical liberty in the fifteenth; shall we not see in this
universal revival of the sixteenth century a monarch like Francis I.
emancipating France from the Roman yoke? At a great sacrifice he
has just done much for Wurtemberg, and will he do nothing for his
own kingdom? The friends of the Reformation encouraged one
another to entertain the brightest hopes. 'What a noble position!'
they said.[696] Whenever they met, whether in the university, in the
country, or in the town, they exchanged congratulations.[697] In their
opinion, old things had passed away.
=UNEASINESS OF THE REFORMERS.=
But there were other evangelicals—men more decided and more
scriptural—who looked with a distrustful eye upon these mysterious
conferences between Francis and the protestants of Germany. Those
fine speeches of Du Bellay, and that remarkable conference at Bar-
le-Duc, were in their eyes policy and diplomacy, but not religion.
They felt uneasy and alarmed; and when they met to pray in their
obscure conventicles, these humble christians said to one another
with terror: 'Satan is casting his net to catch those who are not on
the watch. Let us examine the colours in which he is disguised.'
Astonished and even distressed, they asked if it was not strange to
assert, as Melanchthon had done, 'that no good man would protest
against the monarchy of the Roman bishop,[698] and that, in
consideration of certain reforms, we should hasten to recognise
him!' No, the Roman episcopate will never be reformed, they said.
Remodel it as you like, it will always betray its domineering spirit,
revive its ancient tricks, and regain its ascendency, even by fire. We
must be on our guard.... Between Rome and the Reformation it is a
matter of mere yes or no: the pope or Jesus Christ! Unable to
conquer the new Church in fair fight, they hope to strangle it in their
embraces. Delilah will lull to sleep in her lap the prophet whom the
strong men have been unable to bind with green withes and new
ropes. Under the pretence of screening the Reform from evil
influences, they desire to set it, like a flower of the field, in some
place without light and air, where, fading and pining away ... it will
perish. Thanks to the protection of the Queen of Navarre, the gallant
and high-spirited charger that loved to sport in the meadows is
about to be taken to the king's stable, where it will be adorned with
a magnificent harness ... but its mouth will be deformed by the bit,
its flanks torn by the spur, and even the plaits of its mane will bear
witness to its degradation.
This future was not reserved for the Reform. While the mild and
prudent voices of Melanchthon and Bucer were soothing it to sleep,
innocently enough no doubt, bolder and freer voices, those of a
Farel and a Calvin, were preparing to arouse it. While the papers of
the conciliating theologians were lying on the velvet cover of the
royal table, another paper, whose lines of fire seemed penned by the
thunderbolt, was about to circulate through the kingdom, and be
posted even at the door of the king's chamber by a too daring hand,
which was to arouse in that prince one of the most terrible bursts of
passion ever recorded in history. A loud peal of thunder would be
heard, and the heavy atmosphere which stifled men's minds would
be followed by a pure and reviving air. There would be furious
tempests; but the christians of the scriptural, practical, and radical
Reformation rejoiced at witnessing the failure of this specious but
impossible project, which aimed at reforming the Church even while
preserving Roman-catholicism. The system of the Queen of Navarre
will have to be abandoned; that of Calvin will prevail. To uphold
truth, the evangelicals were about to sacrifice unity. No doubt furious
persecutions would be the consequence, but they said to each other
that it was better to live in the midst of hurricanes that awaken, than
in mephitic vapours which lull men into the sleep of death.
We shall describe hereafter the event which had so notable an
influence on the destinies of the Reformation in France. They were
Frenchmen who caused it; it was a Frenchman who was the principal
author; but it was from Switzerland, as we shall see, that this
formidable blow was to come, and to that country we must now
return.
[655] 'Dadurch Ich in gute Hoffnung kommen die Sachen
sollten auf gute Wege gerichtet werden.' This German
translation of the king's letter is given in the Corp. Ref. ii. pp.
828-835.
[656] 'Rex suus cognoscit nunc errorem suum in religione.'—
Lanz, Correspondance de l'Empereur Charles-Quint, ii. p. 144.
[657] 'Quod isti Germani Lutherum sequentes de Christo et de
fide illius recte sentiant.'—Ibid.
[658] 'Fuerunt illi (Melanchthonis articuli) a quamplurimis in
Gallia excerpti, sed non integri verum mutilati.'—Gerdesius,
Hist. Evang. renov. iv. p. 124.
[659] This memoir is printed in the Corpus Reformatorum, ii.
pp. 765-775; and while Melanchthon's is entitled Consilium
Gallis Scriptum, this is headed Idem Scriptum a Gallis editum.
[660] 'Qua de re Melanchthon ipse conqueritur.'—Gerdesius,
iv. p. 124.
[661] 'Eosdem articulos Romam misisse dicitur, quo pontificis
ipsius quoque impetraret vel emendationem vel consensum.'—
Gerdesius, Hist. Evang. renov. iv. p. 124.
[662] D'Argentré, De novis Erroribus, i. p. 3553. Gerdesius, iv.
App. xiii.
[663] Letter from the Faculty of Theology to Francis I.
D'Argentré, i. p. 3953. Gerdesius, iv. App. xiii.
[664] D'Argentré, i. p. 3953. Gerdesius, iv. App. xiii.
[665] Gerdesius, i. App. xiii. p. 75.
[666] 'Necessarium ut in Christum omnes spectemus.'—
Scriptum a Gallis editum, Corp. Ref. ii. p. 765.
[667] Facultatis Theologiæ Parisiensis Responsum ad Regem
Franciscum, D'Argentré, i. p. 3953.—Gerdesius, iv. App. p. 75.
[668] 'Nec geramus alterutri gladiatorios animos nostra
mordicus defendendi.'—Scriptum a Gallis editum, Corp. Ref. ii.
p. 765.
[669] Facultatis Theol. Paris. Resp. ad Regem. Gerdesius, iv.
App. p. 75.
[670] 'Ut consulat conscientiis, aliquando concedere
relaxationem.'-Scriptum a Gallis editum, Corp. Ref. ii. p. 766.
[671] 'Jure divino institutam, quæ usque ad consummationem
sæculi perduratura est.'—Gerdesius, iv. App. p. 78.
[672] 'Quæ tamen nemo observat, atque hi minime omnium
qui præcipiunt.'—Corp. Ref. ii. p. 767.
[673] D'Argentré, i. p. 397. Gerdesius, iv. App. p. 79.
[674] 'Pia mortuorum facta prosopopœia ... quasi præsentes
a præsentibus orasse.'—Scriptum a Gallis editum, Corp. Ref. ii.
p. 768.
[675] 'Qui et velit invocari et velit exaudire.'—Ibid.
[676] 'Videbimus nos minime abesse a superstitione
Ethnicorum.'—Scriptum a Gallis editum, Corp. Ref. ii. p. 768.
[677] 'Statuas et imagines sanctorum quas adorandas sept.
œcum. synodus decernit.'—Facultatis Theol. Paris. Resp.
[678] 'Viva membrorum Christi communione.'—Scriptum a
Gallis ed. Corp. Ref. ii. p. 769.
[679] 'Semotis his missarum conducticiis nundinatoribus.'—
Ibid.
[680] 'Præpostera ejus operis fiducia quæ plerosque sic
seduxit.'—Ibid.
[681] 'Vocari non debent nundinatores.'—Facult. Theol. Paris
Resp.
[682] 'Sublatis quæ inter nos diu viguerunt altercationibus.'—
Script. a Gallis ed., Corp. Ref. ii. p. 770.
[683] 'Præsente urso, quod dicitur, vestigia non quæramus.'—
Ibid.
[684] 'Theologiam sic tractemus ut non incidamus in
matæologiam.'—Ibid.
[685] 'Utile et necessarium certa verborum forma uti, in sacra
scriptura non expressa.'—Facult. Theol. Paris. Resp. p. 82.
[686] 'Non petunt boni ut monasteria deleantur, sed ut sint
scholæ.'—Script. a Gallis ed., Corp. Ref. ii. p. 773.
[687] Facultatis Theologiæ Parisiensis Responsum. Gerdesius,
Hist. Evang. renov. p. 76.
[688] 'In tanta sacerdotum et monachorum turba restitui
aliter vitæ puritas non poterit.'—Scriptum a Gallis editum,
Corpus Reformatorum, ii. p. 774.
[689] 'Hoc fermentato sæculo.'—Ibid.
[690] 'Perfacile autem coalescere possumus.'—Ibid.
[691] Facultatis Theologiæ Parisiensis Responsum. Gerdesius,
Hist. Evang. renov. p. 77.
[692] Including the apocryphal books.
[693] Facultatis Theologiæ Parisiensis Responsum. Gerdesius,
Hist. Evang. renov. iv. App. p. 77.
[694] Du Bellay, Mémoires, ed. Petitot, Introd. p. 123.
Schmidt, Hist. Theol. p. 36 (ed. 1850).
[695] 'England und Ich pflegen zusammen zu halten und
sämmtlich unsere Sachen vornehmen.'—Rex Galliæ ad
principes protest. Corp. Ref. ii. p. 830.
[696] 'Quam pulchre staremus.'—Sturm to Melanchthon, MS.
[697] Ibid.
[698] 'Neque bonus ullus erit, qui reclamet in pontificis
monarchiam.—Corp. Ref. ii. p. 762.
BOOK III.
FALL OF A BISHOP-PRINCE, AND FIRST EVANGELICAL BEGINNINGS IN GENEVA.
CHAPTER I.
THE RENAISSANCE, THE REFORMATION, THE MIDDLE AGES.
(1526.)
ebookgate.com