Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
164 views

N3887 Python Programming BCA Science Sem 6

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
164 views

N3887 Python Programming BCA Science Sem 6

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

Text Book Of

Python Programming
For
B.C.A. Science : Semester - VI

As Per New Syllabus

Dr. Ms. Manisha Bharambe


M.Sc (Comp. Sci.), M.Phil, Ph.D (Comp. Sci.)
Associate Professor, Computer Science Department
MES Abasaheb Garware College, Pune

Price ` 180.00

N3887
Python Programming ISBN 978-93-88706-83-4
First Edition : January 2019
© : Author
The text of this publication, or any part thereof, should not be reproduced or transmitted in any form or stored in any computer storage system or device for
distribution including photocopy, recording, taping or information retrieval system or reproduced on any disc, tape, perforated media or other information storage
device etc., without the written permission of Author with whom the rights are reserved. Breach of this condition is liable for legal action.
Every effort has been made to avoid errors or omissions in this publication. In spite of this, errors may have crept in. Any mistake, error or discrepancy so
noted and shall be brought to our notice shall be taken care of in the next edition. It is notified that neither the publisher nor the author or seller shall be
responsible for any damage or loss of action to any one, of any kind, in any manner, therefrom.
Published By : Printed By :
NIRALI PRAKASHAN STAR COPIERS PVT. LTD.
Abhyudaya Pragati, 1312, Shivaji Nagar Kumthekar Road, Sadashiv Peth
Off J.M. Road, PUNE – 411005 Pune - 411 030
Tel - (020) 25512336/37/39, Fax - (020) 25511379 Tel - (020) 24479201
Email : niralipune@pragationline.com

DISTRIBUTION CENTRES
PUNE
Nirali Prakashan : 119, Budhwar Peth, Jogeshwari Mandir Lane, Pune 411002, Maharashtra
(For orders within Pune) Tel : (020) 2445 2044, 66022708, Fax : (020) 2445 1538; Mobile : 9657703145
Email : niralilocal@pragationline.com
Nirali Prakashan : S. No. 28/27, Dhayari, Near Asian College Pune 411041
(For orders outside Pune) Tel : (020) 24690204 Fax : (020) 24690316; Mobile : 9657703143
Email : bookorder@pragationline.com
MUMBAI
Nirali Prakashan : 385, S.V.P. Road, Rasdhara Co-op. Hsg. Society Ltd.,
Girgaum, Mumbai 400004, Maharashtra; Mobile : 9320129587
Tel : (022) 2385 6339 / 2386 9976, Fax : (022) 2386 9976
Email : niralimumbai@pragationline.com

DISTRIBUTION BRANCHES
JALGAON
Nirali Prakashan : 34, V. V. Golani Market, Navi Peth, Jalgaon 425001, Maharashtra,
Tel : (0257) 222 0395, Mob : 94234 91860; Email : niralijalgaon@pragationline.com
KOLHAPUR
Nirali Prakashan : New Mahadvar Road, Kedar Plaza, 1st Floor Opp. IDBI Bank, Kolhapur 416 012
Maharashtra. Mob : 9850046155; Email : niralikolhapur@pragationline.com
NAGPUR
Nirali Prakashan : Above Maratha Mandir, Shop No. 3, First Floor,
Rani Jhanshi Square, Sitabuldi, Nagpur 440012, Maharashtra
Tel : (0712) 254 7129; Email : niralinagpur@pragationline.com
DELHI
Nirali Prakashan : 4593/15, Basement, Agarwal Lane, Ansari Road, Daryaganj
Near Times of India Building, New Delhi 110002 Mob : 08505972553
Email : niralidelhi@pragationline.com
BENGALURU
Nirali Prakashan : Maitri Ground Floor, Jaya Apartments, No. 99, 6th Cross, 6th Main,
Malleswaram, Bengaluru 560003, Karnataka; Mob : 9449043034
Email: niralibangalore@pragationline.com
Other Branches : Hyderabad, Chennai

Note : Every possible effort has been made to avoid errors or omissions in this book. In spite this, errors may have crept in. Any type of error or mistake so noted,
and shall be brought to our notice, shall be taken care of in the next edition. It is notified that neither the publisher, nor the author or book seller shall be responsible
for any damage or loss of action to any one of any kind, in any manner, therefrom. The reader must cross check all the facts and contents with original Government
notification or publications.

niralipune@pragationline.com | www.pragationline.com

Also find us on www.facebook.com/niralibooks


Syllabus...
1. Introduction to Python Scripting (04 L)
• Why Scripting is Useful in Computational Science?
• Classification of Programming Languages
• Productive Pairs of Programming Languages
• Gluing Existing Applications
• Scripting Yields Shorter Code, Efficiency
• Type-Specification (Declaration) of Variables
• Flexible Function Interfaces
• Interactive Computing
• Creating Code at Run Time
• Nested Heterogeneous Data Structures
• GUI Programming
• Mixed Language Programming
• When to Choose a Dynamically Typed Language?
• Why Python? Script or Program?
• Application of Python
• Concept (Immutable)
2. Basic Python (06 L)
• Python Identifiers and Reserved Words
• Lines and Indentation, Multi-line Statements
• Comments
• Input/Output with Print and Inputs Functions
• Command Line Arguments and Processing Command Line Arguments
• Standard Data Types – Basic, None, Boolean (True and False), Numbers
• Data Type Conversion
• Python Basic Operators (Arithmetic, Comparison, Assignment, Bitwise Logical)
• Python Members Operators (in and not in)
• Python Identify Operators (is and is not)
• Operator Precedence
• Control Statement, Python Loops, Iterating by subsequence index, Loop control statements (break,
Continue, Pass)
• Mathematical Functions and Constants (Import Math), Random Numbers Functions
3. Python Strings (06 L)
• Concept, Escape Characters
• String Special Operations
• String Formatting Operator
• Single Quotes, Double Quotes, Triple Quotes
• Raw String, Unicode String, Built-in String Methods
• Python Lists – Concept, Creating and Accessing Elements, Updating and Deleting List, Basic List
Operations, Reverse
• Indexing, Slicing and Matrices
• Built-in List Functions
• Functional Programming Tools - filter(), map(), and reduce()
• Using Lists as Stacks and Queues, List Comprehensions
4. Python Tuples and Sets (06 L)
• Creating and Deleting Tuples
• Accessing Values in a Tuple
• Updating Tuples, Delete Tuple Elements
• Basic Tuple Operations
• Indexing, Slicing and Matrices, Built-in Tuple Functions
• Sets – Concept, Operations
5. Python Dictionary (04 L)
• Concept (Mutable)
• Creating and Accessing Values in a Dictionary
• Updating Dictionary, Delete Dictionary Elements
• Properties of Dictionary Keys
• Built-in Dictionary Functions and Methods
6. Functions (08 L)
• Defining a Function (def),
• Calling a Function
• Function Arguments - Pass by Value, Keyword Arguments, Default Arguments
• Scope of Variable - Basic Rules
• Documentation Strings
• Variable Number of Arguments
• Call by Reference
• Order of Arguments (positional, extra and keyword)
• Anonymous Functions
• Recursion
• Treatment of Input and Output Arguments
• Unpacking Argument Lists
• Lambda Forms
• Function Objects
• Function Duck typing and Polymorphism
• Generators (Functions and Expressions) and Iterators, List Comprehensions
7. Files and Directories (06 L)
• Creating Files
• Operations on Files (open, close, read, write)
• File Object Attributes, File Positions, Listing Files in a Directory
• Testing File Types
• Removing Files and Directories
• Copying and Renaming Files
• Splitting Pathnames
• Creating and Moving to Directories
• Traversing Directory Trees
• Illustrative Programs: word count, copy file
8. Python Classes/Objects (08 L)
• Object Oriented Programming and Classes in Python - Creating Classes, Instance Objects, Accessing
Members
• Data Hiding (the double underscore prefix)
• Built-in Class Attributes
• Garbage Collection: the Constructor
• Overloading Methods and Operators
• Inheritance - Implementing a Subclass, Overriding Methods
• Recursive Calls to Methods
• Class Variables - Class Methods and Static Methods
9. Python Exceptions (02 L)
• Exceptional handling : Assert Statement
• Except Clause - with no Exceptions and Multiple Exceptions
• Try – Finally, Raising Exceptions, User-defined Exceptions
Contents...
1. Introduction to Python Scripting 1.1 – 1.14

2. Basic Python 2.1 – 2.32

3. Python Strings 3.1 – 3.24

4. Python Tuples and Sets 4.1 – 4.20

5. Python Dictionary 5.1 – 5.14

6. Functions 6.1 – 6.34

7. Files and Directories 7.1 – 7.24

8. Python Classes/Objects 8.1 – 8.30

9. Python Exceptions 9.1 – 9.12


CHAPTER
1
Introduction to Python Scripting
Contents …
1.1 Introduction
1.2 Why Scripting is Useful in Computational Science?
1.3 Classification of Programming Languages
1.4 Gluing Existing Applications
1.5 Productive Pairs of Programming Languages
1.6 Scripting Yields Shorter Code, Efficiency
1.7 Type-Specification (Declaration) of Variables, Flexible Function Interfaces
1.8 Interactive Computing
1.9 Creating Code at Run Time
1.10 Nested Heterogeneous Data Structures
1.11 GUI Programming
1.12 Mixed Language Programming
1.13 When to Choose a Dynamically Typed Language?
1.14 Why Python? Script or Program?
1.15 Application of Python
1.16 Concept (Immutable)
Summary
Practice Questions
Objectives …
After reading this chapter you will be able,
• To introduce the Python Scripting.
• To learn about different features of Python.

1.1 INTRODUCTION
• Python Programming Language is a high-level and interpreted programming language which was
created by Guido Van Rossum in 1989. It was first released in 1991, which results in a great general
purpose language capable of creating anything from desktop software to web applications and
frameworks.
• There are two major Python versions: Python 2 and Python 3. Both are quite different.
• Python scripts normally have the extension .py, but this is not required. You can execute the script by
the command: python hw.py
• This command specifies explicitly that a program python is to be used to interpret the contents of the
hw.py file.
• For the python hw.py … command and to work, you need to be in a console window, also known as a
Terminal Window on Unix, and as a command prompt or MS-DOS prompt on Windows. The Windows
habit of double-clicking on the file icon does not work for scripts requiring command-line
information, unless you have installed PythonWin.

1.1
Python Programming (BCA Science: VI) Introduction to Python Scripting

Install and Run Python in Windows:


• Go to Download Python page on the official site and click Download Python 3.6.0 (You may see
different version name).
• When the download is completed, double-click the file and follow the instructions to install it.
When Python is installed, a program called IDLE is also installed along with it. It provides graphical
user interface to work with Python.
• Open IDLE, copy the following code below and press enter.
print("Hello, World!")
• To create a file in IDLE, go to File > New Window (Shortcut: Ctrl+N).
• Write Python code (you can copy the code below for now) and save (Shortcut: Ctrl+S) with .py file
extension like: hello.py or your-first-program.py
print("Hello, World!")
Important Things to Remember:
• To represent a statement in Python, newline (enter) is used. The use of semicolon at the end of the
statement is optional (unlike languages like C/C++, PHP). In fact, it's recommended to omit semicolon
at the end of the statement in Python.
• Instead of curly braces { }, indentations are used to represent a block.

1.2 WHY SCRIPTING IS USEFUL IN COMPUTATIONAL SCIENCE?


• A scripting language is a language that is interpreted at run time, rather than compiled into a binary
executable.
• Scripting languages allow us to write simple script for GUI quickly, and run it without any
compilation. They also have good support for launching processes and controlling them, parsing text
files, etc.
• Scripting languages are becoming more popular due to the emergence of web-based applications. The
market for producing dynamic web content is now expanding extremely rapidly such that new
scripting languages have been developed to allow users with little or no programming expertise to
develop interactive web pages with minimum effort.
• Text manipulation, text processing and searching are faster in Scripting Languages.
• Python offers the clean and simple syntax of the popular scientific computing environments.
• The language is very powerful and there are lots of tools for gluing your favourite simulation,
visualization, and data analysis programs the way you want. In other words, Python allows you to
build your own Matlab-like scientific computing environment.
• The task such as shuffling data in and out of different tools, converting one data format to another,
extracting numerical data from a text, and administering numerical experiments involving a large
number of data files and directories are much faster to accomplish in a Python than in Fortran, C,
C++, C#, or Java.
• Python is interpreted scripting language, not be compiled. Fast code-run loops with an interpreted
language make it faster to develop than a complied language.
• Following are scripting techniques for computing:
o Code re-re-use:
use: Python offers the benefits of object-oriented and generic (template) programming,
together with a syntax that is simpler and clearer than C++ and Java. In addition, there exists
several tools which makes calling Fortran 77/90, C, C++, or Java code trivial, at least in principle.
o High-
High-level tools for simplifying Mixed-
Mixed-Language Integration:
Integration: To write Python code in one part of
an editor window and simply jump to another part to write number crunching code in Fortran, C,
or C++, often calling up your own libraries in those languages. With just pressing a button or
running a simple one-line command, the Python script works with the external numerical code.

1.2
1.2
Python Programming (BCA Science: VI) Introduction to Python Scripting

Scripting interfaces to existing libraries:


libraries:
• You can almost automatically build a complete Python interface to existing C/C++ or Fortran libraries
which is ideal for prototyping and testing as there is no waiting time for compilation and linking
when programming in Python. Hence, debugging or numerical experimentation is much faster than
in a compiled language. Declarations of variables is not necessary in Python, making the code
significantly simpler and more general than in C++ or Java (more like Matlab, Maple, or
Mathematical). At the same time you have access to the full power of object-oriented and generic
programming with complicated data structures. Collecting functions and data in Python classes is
efficient from a numerical point of view as long as the heavy operations on your data structures are
done in efficient C/C++ or Fortran code.
• GUI:
GUI: Python is easily combined with various GUI software, like Tk, Qt, Gtk, MFC, and java.swing.
Programming with Tk and Tk extensions (Pmw) from Python means that cross-platform GUIs can be
generated with a minimum of code.

1.3 CLASSIFICATION OF PROGRAMMING LANGUAGES


• Computer programming languages are used to communicate instructions to a computer. They are
based on certain syntactic and semantic rules, which define the meaning of each of the programming
language constructs. Today, there are many of programming languages used in the industry. We have
discussed here most important, relevant and in-demand of these languages.
The Programming Languages are classified as follows:
• Machine languages:
languages: It is the Lowest Level and named as First Generation of Programming Language.
Machine Level Language consist only two conditions i.e. either true (1) or false (0); this type of
language known as Binary Language. A computer system could understand only binary language i.e.
all the instruction feed into the computer system must be in the form of 0 or 1. Machine level
languages are very hard to understand.
• Assembly languages:
languages: It is a Middle Level and named as Second Generation Programming Language. It
contains the same instructions as Machine Level Language. Instructions and the variables have
specific name and called Commands. It also uses symbols to describe field of instructions. Every
aspect of machine variable in program, assembly language uses one statement per machine
instruction. It managed explicitly all instruction like register allocation, call, stack, timer, jump, loop
etc.
• To understand the Assembly language computer must require an Assembler which takes a part in
between assembly language and computer system to convert the assembly instructions into the
machine language. This assembler is software or a set of program which translates assemble
language programming instruction into the machine language.
Example:
Example:
LOAD BASIC
ADD FUNDS
STORE GROSS
• High-
High-level languages:
languages: All High Level Languages are procedure-oriented languages and are intended to
be machine independent. High level language is the upper level language and also known as third
generation programming language. These languages enable the programmer to write instruction
using English words and familiar mathematical symbols which makes it easier than technical details
of the computer. It makes the programs more readable too. Programs written in high level language
must require software or a set of program to translate that program into machine understandable.
This software called compiler and/or interpreter. The main task of compiler and translator is that to
take the source code of the program and convert that code into the machine understood code.
Example:
Example: FORTRAN, Pascal, C, C++, JAVA, ADA, COBOL, LISP, Prolog.
• System Languages: A System Programming Language refers to a Programming Language used
for system programming; such languages are designed for writing system software.
Example:
Example: PL/I, D, Rust, Swift.
1.3
1.3
Python Programming (BCA Science: VI) Introduction to Python Scripting

• Scripting Languages: A Scripting Language is a programming language designed for integrating and
communicating with other programming languages. These are generally extremely high-level and
powerful.
Example:
Example: JavaScript, VBScript, PHP, Perl, Python, Ruby, ASP and Tcl.
• Domain--specific Languages
Domain Languages:: A Domain-specific Language (DSL) is a programming language that is
developed to meet a specific need. These are used in highly special-purpose areas only.
Example:
Example: Cascading Style Sheets (CSS), Ant and SQL.
• Visual Languages:
Languages: Visual Programming Languages (VPL) allows users specify programs in a two-(or
more)-dimensional way, instead of as one-dimensional text strings, via graphic layouts of various
types .
Example:
Example: Analytica, Blockly, Toontalk.
• languages: An Esoteric Programming Language is a programming language designed as a test
Esoteric languages
of the boundaries of computer programming language design, as a proof of concept, or as a joke.
These are not really intended to be used, but are very interesting, funny, or educational in some way.
Example:
Example: Beatnik, Befunge, Piet, whitespace
• Language:: Glue language refers to a Programming Language that is designed specifically to
Glue Language
write and manage program and code, which connects together different software components. Glue
language primarily enables creating glue code. It enables interconnecting, support and the
integration of software programs and components created using different programming languages
and platforms. The Glue code written in glue language doesn’t provide any functional value to the
core software, but enables connecting the processes and features of multiple smaller and directly
incompatible components. The gluing of these components provides enhanced features and
functionality to the base software/solution.
Glue Language is very useful in rapid prototyping environments where multiple software utilities are
glued together quickly before being developed in a single programming language or framework.
Example: VBScript, Ruby, Python, Perl and PHP.
• Differences between Programming Vs Scripting:
Scripting:
1. Programming languages do not require a host; these are executable whereas Scripting languages
need a host.
2. Programming languages are complex and tedious to learn whereas Scripting languages are easier
to learn, write and master as compared to Programming languages.
3. Programming languages are generally compiled and create an executable file whereas Scripting
languages are interpreted and do not create an executable file.
4. Programming language code is compiled and byte code are converted into machine code in one
shot whereas, in Scripting, high-level instructions are converted into machine language
straightaway.
5. Programming languages are most often used to build something from scratch whereas Scripting
languages can be used to combined existing component or module.
6. Programming languages are designed in such a way a developer can take full advantage of
features of a language whereas Scripting languages are designed to make coding faster and
simpler.
7. With programming language, numerous lines of code are needed for each function whereas
Scripting languages require lesser lines of code to write functions.
8. Programming languages increased maintenance cost whereas with Scripting, maintenance cost is
drastically reduced.
9. C, C++, C#, Java, VC++, COBOL, Pascal etc., are examples of Programming languages whereas
JavaScript, VB Script, Python, Ruby etc., are examples of Scripting languages.

1.4
1.4
Python Programming (BCA Science: VI) Introduction to Python Scripting

1.4 GLUING EXISTING APPLICATIONS


• A script that glues existing components to form a new application often needs a Graphical User
Interface (GUI), and adding a GUI is normally a simpler task in dynamically typed languages than in
the type-safe languages,
• There are basically two ways of Gluing Existing Applications. The simplest approach is to launch
stand-alone programs and let such programs communicate through files. The other more
sophisticated way of gluing consists in letting the script call functions in the applications. This can he
done through direct calls to the functions and using pointers to transfer data mixtures between the
applications. Alternatively, one can use a layer of, e.g., CORBA or COM objects between the script and
the applications.
• The latter approach is very flexible as the applications can easily run on different machines but data
structures need to be copied between the applications and the script. Passing large data structures by
pointers in direct calls of functions in the applications therefore seems attractive for high-
performance computing.

1.5 PRODUCTIVE PAIRS OF PROGRAMMING LANGUAGES


• Unix and C: C is a low-level language, often claimed to be designed for computers. Unix is a very
productive software development environment. The Unix shell for gluing C programs to form new
applications. With C programs as building blocks, a user can solve a new problem by writing a shell
program combining existing tools in a simple way. For example, there is no basic Unix tool that
enables browsing a sorted list of the disk usage in the directories of a user, but it is trivial to combine
three
C programs, du for summarizing disk usage, sort for sorting lines of text, and less for browsing text,
together with the pipe functionality of Unix shells, to build the desired tool as a one-line shell
instruction as follows:
du -a $HOME | sort -rn | less
• C++ and Visual Basic
o C++ is classical system programming and the Visual Basic language is scripting language. C++ is a
richer language than C and supports working with high-level abstractions through concepts like
Object-oriented and Generic Programming. Visual Basic is also a richer language than Unix shells.
o Java and JavaScript:
JavaScript: Java is object oriented language, especially used for Internet programming,
JavaScript as some kind of scripting companion in Web pages. Java is much of a self-contained
language, and being simpler and safer to apply than C++, it has become very popular and
widespread for classical system programming.
o PHP and Java: These are also a popular pair, both are used for internet programming. PHP is a
related language, but more specialized towards making Web services. A promising scripting
companion to Java is Jython, the Java implementation of Python.
o Modern Scripting Languanges:
Languanges: During the last decade several powerful dynamically typed
languages have emerged and developed to a mature state. Bash, Perl, Python (and Jython), Ruby,
Scheme, and Tcl are examples of general-purpose, modern, wide spread languages that are
popular for scripting tasks. PHP is a related language, but more specialized towards making web
services.
o Powerful Dynamically typed languages,
languages such as Python, support numerous high-level constructs
and data structures enabling you to write programs that are significantly shorter than programs
with corresponding functionality coded in Fortran, C, C++, or Java.
1.5
1.5
Python Programming (BCA Science: VI) Introduction to Python Scripting

1.6 SCRIPTING YIELDS SHORTER CODE, EFFICIENCY


• Python is a powerful dynamically typed language which supports numerous high-level constructs and
data structures to write programs. The python program is significantly shorter than programs with
corresponding functionality coded in Fortran, C, C++, or Java. The efficiency is improved using
scripting languages. Scripts are first compiled to hardware-independent byte-code and then the byte-
code is interpreted. For a wide range of tasks, dynamically typed languages are efficient enough on
today's computers.
• Another important feature is that dynamically typed languages can sometimes give you optimal
efficiency. One more attractive feature is that they were designed for migrating CPU-critical code
segments to C, C++, or Fortran. This can often resolve bottlenecks, especially in numerical computing.

TYPE-SPECIFICATION (DECLARATION) OF VARIABLES AND FLEXIBLE


1.7
FUNCTION INTERFACES
• Type-safe languages like C, C++ require each variable to be explicitly declared of a specific type.
• In Dynamically typed languages, variables are not declared to be of any type, and there are no a
priori restrictions on how variables and functions are combined. When you need a variable, simply
assign it a value there is no need to mention the type.
• In a weakly typed language, a compiler / interpreter will sometimes change the type of a variable. For
example, in some languages (like JavaScript) you can add strings to numbers 'x' + 3 becomes 'x3'. This
can be a problem because if you have made a mistake in your program, instead of raising an
exception. Execution will continue but your variables now have wrong and unexpected values.
• In a strongly typed language (like Python), you can't perform operations inappropriate to the type of
the object - attempting to add numbers to strings will fail. Problems like these are easier to detect
because the exception is raised at the point where the error occurs rather than at some other,
potentially far removed, place.
• In a statically typed language, the type of variables must be known (and usually declared) at the point
at which it is used. Attempting to use it will be an error. In a dynamically typed language, objects still
have a type, but it is determined at runtime. You are free to bind names (variables) to different
objects with a different type. So long as you only perform operations valid for the type the interpreter
doesn't care what type they actually are.
• Example (type of variable n is not declared):
n=input("Enter number[0 – 2]:")
if n=='0':
number='Zero'
elif n=='1':
number="One"
elif n=='2':
number="Two"
print(number)
• Python offers keyword arguments in functions.
• The nature and functionality of Python give you a full-fledged, advanced programming language at
disposal, with the clean and easy-to-use interface syntax that has obtained great popularity through
environments like Maple and Matlab.
• Functions are the most basic way of avoiding code redundancy in Python—factoring code into
functions means that we have only one copy of an operations code to update in the future. Functions

1.6
1.6

You might also like