Chapter 3122
Chapter 3122
Chapter 3122
Programming
Published by : Mrs. Meena Pandey for Himalaya Publishing House Pvt. Ltd.,
“Ramdoot”, Dr. Bhalerao Marg, Girgaon, Mumbai - 400 004.
Phone: 022-23860170, 23863863; Fax: 022-23877178
E-mail: [email protected]; Website: www.himpub.com
Branch Offices :
New Delhi : “Pooja Apartments”, 4-B, Murari Lal Street, Ansari Road, Darya Ganj, New
Delhi - 110 002. Phone: 011-23270392, 23278631; Fax: 011-23256286
Nagpur : Kundanlal Chandak Industrial Estate, Ghat Road, Nagpur - 440 018.
Phone: 0712-2738731, 3296733; Telefax: 0712-2721216
Bengaluru : Plot No. 91-33, 2nd Main Road, Seshadripuram, Behind Nataraja Theatre,
Bengaluru - 560020. Phone: 08041138821;
Mobile: 09379847017, 09379847005
Hyderabad : No. 3-4-184, Lingampally, Besides Raghavendra Swamy Matham,
Kachiguda, Hyderabad - 500 027. Phone: 040-27560041, 27550139
Chennai : New No. 48/2, Old No. 28/2, Ground Floor, Sarangapani Street, T. Nagar,
Chennai - 600 012. Mobile: 09380460419
Pune : First Floor, “Laksha” Apartment, No. 527, Mehunpura, Shaniwarpeth (Near
Prabhat Theatre), Pune - 411 030. Phone: 020-24496323, 24496333;
Mobile: 09370579333
Lucknow : House No. 731, Shekhupura Colony, Near B.D. Convent School, Aliganj,
Lucknow - 226 022. Phone: 0522-4012353; Mobile: 09307501549
Ahmedabad : 114, “SHAIL”, 1st Floor, Opp. Madhu Sudan House, C.G. Road, Navrang
Pura, Ahmedabad - 380 009. Phone: 079-26560126; Mobile: 09377088847
Ernakulam : 39/176 (New No. 60/251) 1st Floor, Karikkamuri Road, Ernakulam,
Kochi - 682011. Phone: 0484-2378012, 2378016; Mobile: 09387122121
Bhubaneswar : Plot No. 214/1342, Budheswari Colony, Behind Durga Mandap,
Bhubaneswar - 751 006. Phone: 0674-2575129; Mobile: 09338746007
Kolkata : 108/4, Beliaghata Main Road, Near ID Hospital, Opp. SBI Bank,
Kolkata - 700 010. Phone: 033-32449649; Mobile: 07439040301
DTP by : Sneha Gaonkar
Printed at : M/s Sri Sai Art Printer, Hyderabad. On behalf of HPH.
Dedication
“Behind every young child who believe in herself is a parent
who believe first.” So, I would like to dedicate this book to my
mother and father Kavita S. Bajaj and Sahijram Bajaj. I would
like to thank my son Chirag Gurbani for being my stress buster
and a motivating force for putting a better performance every time.
My sincerest big thanks for a lifetime to Mr. S.K. Srivastava
of Himalaya publication for giving me best writing advice and
motivation. His impressive career advancement inspired me to
climb more and more success ladder in my life.
Kiran Gurbani
PREFACE
1. Introduction to Python 1 - 18
3. Conditional Statements 41 - 50
4. Looping 51 - 61
5. Control Statement 62 - 68
6. Functions 69 - 89
7. Strings 90 - 99
Introduction to
Python
Structure:
1.1 Introduction to python programming Language
1.1.1 History
1.1.2 Features
1.1.3 Installing Python
1.1.4 Running Python program
1.1.5 Debugging
1.1.5.1 Syntax Errors
1.1.5.2 Runtime Errors
1.1.5.3 Semantic Errors
1.1.5.4 Experimental Debugging
1.1.5.5 Formal and Natural Languages
1.1.5.6 The Difference Between Brackets, Braces, and Parentheses
Python is easy to learn yet powerful and versatile scripting language which makes it
attractive for Application Development.
Python’s syntax and dynamic typing with its interpreted nature make it an ideal language
for scripting and rapid application development in many areas.
Python supports multiple programming pattern, including object oriented programming,
imperative and functional programming or procedural styles.
Python is not intended to work on special area such as web programming. That is why it
is known as multipurpose because it can be used with web, enterprise, 3D CAD etc.
We don’t need to use data types to declare variable because it is dynamically typed so we
can write a=10 to declare an integer value in a variable.
Python makes the development and debugging fast because there is no compilation step
included in python development and edit-test-debug cycle is very fast.
Python is Interpreted: Python is processed at runtime by the interpreter. You do not
need to compile your program before executing it. This is similar to PERL and PHP.
Python is Interactive: You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
Python is Object-Oriented: Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
Python is a Beginner’s Language: Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from simple
text processing to WWW browsers to games.
1.1.1 History
Python 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 ABC, Modula–3, 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), hence called Open source language
Python is now maintained by a core development team at the institute, although Guido van
Rossum still holds a vital role in directing its progress.
Many of Python’s features originated from an interpreted language called ABC.
Rossum wanted to correct some of ABC’s problems and keep some of its features.
At the time he was working on the Amoeba distributed operating system group and was
looking for a scripting language with syntax like ABC but with the access to the Amoeba
system calls, so he decided to create a language that was generally extensible.
Since he had some experience with using Modula–2+, he decided to talk with the designers
of Modula–3. Modula–3 is the origin of the syntax and semantics used for exceptions, and
some other Python features.
In 1989, during the Christmas holidays, he decided to give it a try and design a language
which he later called Python.
Introduction to Python 3
Just in case you’re wondering how the language got its name, well it’s not from those
dangerous reptiles.
Python actually got is name from a BBC comedy series from the seventies “Monty Python’s
Flying Circus”. The designer needed a name that was short, unique, and slightly mysterious.
Since he was a fan of the show he thought this name was great
1.1.2 Features
Python Features
Python’s features include:
Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax.
This allows the student to pick up the language quickly.
Simple: Python is a simple and minimalistic language This pseudo-code nature of Python is
one of its greatest strengths. It allows you to concentrate on the solution to the problem
rather than the syntax i.e. the language itself.
Easy-to-read: Python code is more clearly defined and visible to the eyes.
Easy-to-maintain: Python’s source code is fairly easy-to-maintain.
A broad standard library: Python’s bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
Interactive Mode: Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.
Portable: Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
Extendable: You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
Databases: Python provides interfaces to all major commercial databases.
GUI Programming: Python supports GUI applications that can be created and ported to
many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and
the X Window system of Unix.
Scalable: Python provides a better structure and support for large programs than shell
scripting.
Free and Open Source: Python is an example of a FLOSS (Free/Libre and Open Source
Software).
In simple terms, you can freely distribute copies of this software, read the software’s source
code, make changes to it, use pieces of it in new free programs, and that you know you can
do these things. FLOSS is based on the concept of a community which shares knowledge.
4 Python Programming
High-level Language:
When you write programs in Python, you never need to bother about low-level details such
as managing the memory used by your program. It is purely high level language just like a
English language.
Interpreted: This requires a little explanation.
A program written in a compiled language like C or C++ is translated from the source
language i.e. C/C++ into a language spoken by your computer (binary code i.e. 0s and 1s)
using a compiler with various flags and options.
When you run the program, the linker/loader software just stores the binary code in the
computer’s memory and starts executing from the first instruction in the program.
When you use an interpreted language like Python, there is no separate compilation and
execution steps. You just run the program from the source code. Internally, Python
converts the source code into an intermediate code form called bytecodes and then
translates this into the native language of your specific computer and then runs it. All this
makes using Python so much easier. You just run your programs - you never have to
worry about linking and loading with libraries, etc.
Embeddable: You can embed Python within your C/C++ program to give scripting
capabilities for your program’s users.
Extensive Libraries: The Python Standard Library is huge indeed. It can help you do
various things involving regular expressions, documentation generation, unit testing,
threading, databases, web browsers, CGI, ftp, email, XML, XML-RPC, HTML, WAV files,
cryptography, GUI(graphical user interfaces) using Tk, and also other system-dependent
stuff.
All this is always available wherever Python is installed. This is called the “batteries
included” philosophy of Python
Apart from the above-mentioned features, Python has a big list of good features, few are
listed below:
IT supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for building large
applications.
It provides very high-level dynamic data types and supports dynamic type checking.
IT supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Introduction to Python 5
2. Move this file to a more permanent location, so that you can install Python (and
reinstall it later, if necessary).
3. Start the Installing instructions directly below.
6 Python Programming
Installing
(i) Double-click the icon labeling the file python-3.4.3.msi.
An Open File - Security Warning pop-up window will appear.
1. Click Run.
A Python 3.4.3 Setup pop-up window will appear.
Ensure that the Install for all users radio button is pressed.
Introduction to Python 7
Note that if you have installed an earlier version of Python 3.4, the following pop-
up window will appear.
Use the default customization, which selects the Python Interpreter and all its
libraries (about 42 Mb).
4. Click the Next > button.
In a few seconds a pop-up window titled User Account Control will appear,
posing the question Do you want the following program to install software on
this computer?
Introduction to Python 9
Eventually a new Python 3.4.3 Setup pop-up window will appear (Complete the
Python 3.4.3 Installer).
(IDE). An IDE is a bundled set of software tools for program development. This typically
includes an editor for creating and modifying programs, a translator for executing programs, and a
program debugger. A debugger provides a means of taking control of the execution of a program to
aid in finding program errors.
Python is most commonly translated by use of an interpreter. Thus, Python provides the very
useful ability to execute in interactive mode. The window that provides this interaction is referred to as
the Python shell .
Interacting with the shell is much like using a calculator, except that, instead of being limited to
the operations built into a calculator (addition, subtraction, etc.), it allows the entry and creation of any
Python code. Example use of the Python shell is demonstrated
2. Python 3.4.5
1.1.5 Debugging
Debugging is the routine process of locating and removing computer program bugs, errors
or abnormalities, which is methodically handled by software programmers via debugging
tools.
Debugging checks, detects and corrects errors or bugs to allow proper program operation
according to set specifications.
Debugging is also known as debug
Developing software programs undergo heavy testing, updating, troubleshooting and
maintenance. Normally, software contains errors and bugs, which are routinely removed.
In the debugging process, complete software programs are regularly compiled and executed
to identify and rectify issues.
Large software programs, which contain millions of source code lines, are divided into small
components.
For efficiency, each component is debugged separately at first, followed by the program as a
whole.
Syntax Error. A Python program must have correct syntax. If it does not, a Syntax Error will
occur. The program will not be executed.
This error, unlike other errors, does not terminate a running program—an “except”
statement cannot handle it.
Example. Here I wrote an important program to loop over a list of cat names. But in the for-
statement, I omitted the trailing colon.
This results in a Syntax Error, which politely points out the missing colon character.
To fix the program, we can add a colon to the indicated location. Until then, the program
cannot be executed.
Example Based on: Python 3
Python program that causes Syntax Error
cats = [“Fluffy”, “Mildred”, “Joe”]
for cat in cats
print(cat)
Output:
File “C:\programs\file.py”, line 5
for cat in cats
^
Syntax Error: invalid syntax
Usual Causes:
A mistyped variable or function name.
Using a variable before it is defined.
The name was intended to be enclosed in quotes.
Logic errors:
These errors are often caused by accidentally using one variable in a place where a different
variable is intended, or by simply doing some math incorrectly.
Consider the following example:
apples = 0
pickedApples = input(“Pick some apples: ”)
apples = apples + pickedApples
pickedApples = input(“Pick some more apples: ”)
apples = apples + pickedApples
print “You have a total of %d apples” % pickedApples
The above code will execute, but it will not output the total number of apples picked.
Instead, it will output the amount that was picked the last time! This simple example is easy
to fix, but in a more complicated program it can be difficult to find such problems.
Literalness:
Natural languages are full of idiom and metaphor.
If I say, “The penny dropped,” there is probably no penny and nothing dropping1.
Formal languages mean exactly what they say.
Introduction to Python 17
(People who grow up speaking a natural language everyone often have a hard time adjusting to
formal languages.
(In some ways, the difference between formal and natural language is like the difference between
poetry and prose, but more so:
Poetry:
Words are used for their sounds as well as for their meaning, and the whole poem together
creates an effect or emotional response.
Ambiguity is not only common but often deliberate.
Prose:
The literal meaning of words is more important, and the structure contributes more meaning.
Prose is more amenable to analysis than poetry but still often ambiguous.
Programs:
The meaning of a computer program is unambiguous and literal, and can be understood
entirely by analysis of the tokens and structure.
Here are some suggestions for reading programs (and other formal languages).
First, remember that formal languages are much more dense than natural languages, so it
takes longer to read them.
Also, the structure is very important, so it is usually not a good idea to read from top to
bottom, left to right. Instead, learn to parse the program in your head, identifying the tokens
and interpreting the structure.
Finally, the details matter. Small errors in spelling and punctuation, which you can get away
with in natural languages, can make a big difference in a formal language.
Braces:
“Curly Braces” are used in python to define a dictionary.
A dictionary is a data structure that maps one value to another - kind of how an English
dictionary maps a word to its definition.
Representation: {}
Each key is separated from its value by a colon (:), the items are separated by commas, and
the whole thing is enclosed in curly braces.
An empty dictionary without any items is written with just two curly braces, like this: {}.
Example: dict = {‘Name’: ‘Ravi’, ‘dob’: 26/08/91, ‘Designation’: ‘First’}
Parentheses:
A tuple is a sequence of immutable Python objects.
Tuples are sequences, just like lists.
The differences between tuples and lists are, the tuples cannot be changed unlike lists and
tuples use parentheses, whereas lists use square brackets.
Represenation: ()
Creating a tuple is as simple as putting different comma-separated values. Optionally you
can put these comma-separated values between parentheses also.
For example: tup2 = (1, 2, 3, 4, 5 );
tup3 = “a”, “b”, “c”, “d”;
Questions
1. What is python language state History of python.
2. Explain Python Features in detail.
3. State Installing procedure of python.
4. Explain steps of Running Python program.
5. Explain what is Debugging in python and what are different errors can be encountered while
debugging.
6. Explain Syntax error and Runtime Error.
7. Explain Semantic and Syntax errors.
8. Define Formal and Natural Languages.
9. State the Difference Between Brackets, Braces, and Parentheses.