Python 2 Techmax
Python 2 Techmax
WITH PYTHON – II
(As per the Syllabus 2016 - 17 of Mumbai University for FYB.Sc. – CS, Semester II)
Kiran Gurbani
B.E., MCA, M.Phil.,
Head of Computer Science Department,
R.K. Talreja College,
Ulhasnagar - 3.
Vijay Vastava
MCA,
Professor of Computer Science Department and Information Technology,
K.M. Agrawal College of Arts, Science & Commerce,
Kalyan.
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: himpub@vsnl.com; 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 : 5 Station Square, Bhubaneswar - 751 001 (Odisha).
Phone: 0674-2532129; Mobile: 09338746007
Kolkata : 108/4, Beliaghata Main Road, Near ID Hospital, Opp. SBI Bank,
Kolkata - 700 010. Phone: 033-32449649; Mobile: 07439040301
DTP by : Nilima Jadhav
Printed at : M/s. Aditya Offset Process (I) Pvt. Ltd., 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
I would like to dedicate this book to My father Late Shri Laxman B. Vastava and
My Mother Smt Kasturi L. Vastava.
Vijay Vastava
PREFACE
It is a great pleasure in presenting First Edition of this book “Programming with Python – II” to
the students of F.Y.C.S. (FYBSc. Computer Science). This book is written to cover all the topics of
syllabus prescribed by the University of Mumbai for F.Y.B.Sc. C.S.
Python is a widely used high-level programming language used for general-purpose
programming, created by Guido van Rossum and first released in 1991. Python has a design
philosophy which emphasizes code readability (notably using whitespace indentation to delimit code
blocks rather than curly braces or keywords), and a syntax which allows programmers to express
concepts in fewer lines of code than possible in languages such as C++ or Java.
Python is an interpreted, object-oriented, high-level programming language with dynamic
semantics. Its high-level built-in data structures, combined with dynamic typing and dynamic binding,
make it very attractive for Rapid Application Development, as well as for use as a scripting or glue
language to connect existing components together.
Python supports modules and packages, which encourages program modularity and code reuse.
The Python interpreter and the extensive standard library are available in source or binary form
without charge for all major platforms, and can be freely distributed.
Python 2.0 was released on 16 October 2000 and had many major new features.
Python 3.0 (which early in its development was commonly referred to as Python 3000 or py3k).
I recommend this book as a Programmer’s point of view. This book teaches Advance Python
starting with the file handling, Exception handling with Regular Expression and GUI Programming
along with Database Connectivity with MySQL and Sqlite3 and Networking.
This book offers you a comprehensive learning tool for Python. It covers almost everything you
need to know about programming in Python: Types and Operations, Statements and Syntax,
Functions and Iterators, Generators, Modules and Packages, Databases and much more.
Here, in this book, the concept of each topic is followed by the theoretical explanation, all
practical questions of Python programming with MCQ (Multiple Choice questions) according to
university pattern are provided at the end of this book, and along with those steps of program
execution is provided. Efforts have been made to make the text easy to read and understand. In this
book, we have covered all types of programs expected by University of Mumbai in practical
examination.
Constructive suggestion and comments from the users will be sincerely appreciated. We would
appreciate hearing from you about any textual errors or omissions which you identify. If you would
like to suggest improvements or to contribute in any way, we would be glad to hear from you.
Please send correspondence to kiranrktcollege@gmail.com and vvastava@gmail.com.
Last but not the least, we would like to give big lifetime thanks to Mr. S.K. Srivastava
(Himalaya Publishing House) for providing an environment which stimulates new thinking and
innovations and his support, motivation, guidance, cooperation and encouragement to write this book.
We are grateful for his support and thank him for his true blessings.
Unit I Python File Input-Output: Opening and closing file, various types of file modes, 15 L
reading and writing to files, manipulating directories.
Iterables, iterators and their problem solving applications.
Exception Handling: What is an exception? various keywords to handle exceptions
such as try, catch, except, else finally, raise.
Regular Expressions: Concept of regular expression, various types of regular
expressions, using match function.
Unit II GUI Programming in Python (using Tkinter/WxPython/Qt): 15 L
What is GUI? Advantages of GUI, Introduction to GUI library. Layout management.
events and bindings, fonts, colours, drawing on canvas on canvas (line, oval,
ractangle, etc.)
Widgets such as: framem label, button, checkbutton, entry, listbox, message,
radiobutton, text, spinbox etc.
Unit III Database Connectivity in Python: Installing My SQL connector, accessing 15 L
connector module module, using connect, cursor, execute and close functions,
reading single and multiple results of query execution, executing different types of
statements, executing transactions, understanding exceptions in database
conncectivity.
Network Connectivity: Socket module, creating server-client programs sending
email, reading from URL
Text Books:
1. Paul Gries, Jennifer Campbell and Jason Montoja, Practical Programming: An Introduction to
Computer Science using Python 3, Pragmatic Bookshell, 2/E 2014.
Additional References:
1. James Payne, Beginning Python: Using Python 2.6 and Python 3, Wiley India, 2010.
2. A. Lukaszewski, My SQL for Python: Database Access Made Easy, Pact Publisher, 2010.
Semester II – Practical
Practical of USCS201 + USCS202 + USCS203 + USCS204 + USCS205 + USCS206
(Credits: 6, Lectures/Week: 18)
Course: USCSP2
UNIT I
2 EXCEPTION HANDLING 40 – 62
3 REGULAR EXPRESSION 63 – 80
UNIT II
UNIT III
Chapter 1
Python File
Input-Output
Structure
1.1 Introduction to File Handling
1.1.1 Text File
1.1.2 Binary File
1.1.3 Differentiate between Text File and Binary File
1.1.4 File operations
1.2 Opening and Closing Files
1.2.1 Opening File by using Open( )
1.2.1.1 Open For Reading
1.2.1.2 Opening for Writing
1.3 Closing File by Using Close( )
1.3.1 Various Types ofFile Modes
1.3.2 Attributes of File Object
1.4 Reading and Writing to Files
1.4.1 Reading File through Read( ) and Readline( ) and readlines( )
1.4.2 Reading Input from Keyboard
1.4.3 Writing File through Write( )
1.5 Appending Text to a File
1.6 Renaming a File
1.7 Deleting a File
1.8 Python Different file Input Output Functions
1.9 File Positions
1.10 Manipulating Directories
1.10.1 Directories in Python
1.10.2 mkdir( ) Method
2 Programming with Python – II
1.10.3 chdir( ) Method
1.10.4 getcwd( ) Method
1.10.5 rmdir( ) Method
1.11 Python Iterators and Iterables
1.11.1 Python Iterators
1.11.2 Python Iterables
1.11.3 Creating Your Own Iterator in Python
1.11.4 Python Infinite Iterators
1.11.5 Generators
1.12 Iterations and their Problem Solving Applications
1.13 Questions
A text file is a file containing characters, structured as individual lines of text. In addition to
printable characters, text files also contain the nonprinting newline character, \n, to denote the end of
each text line. The newline character causes the screen cursor to move to the beginning of the next
screen line. Thus, text files can be directly viewed and created using a text editor.
Modes Description
r Opens a file for reading only. The file pointer is placed at the beginning of the file. This
is the default mode.
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not
exist, creates a new file for writing.
a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is,
the file is in the append mode. If the file does not exist, it creates a new file for writing.
All files must first be opened before they can be read from or written to.
Example of open method
#!/usr/bin/python
# Open a file
Modes Description
r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is
the default mode.
rb Opens a file for reading only in binary format. The file pointer is placed at the beginning of
the file. This is the default mode.
r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
rb+ Opens a file for both reading and writing in binary format. The file pointer placed at the
beginning of the file.
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist,
creates a new file for writing.
wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file
does not exist, creates a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the
file does not exist, creates a new file for reading and writing.
wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file if the
file exists. If the file does not exist, creates a new file for reading and writing.
a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is,
the file is in the append mode. If the file does not exist, it creates a new file for writing.
ab Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists.
That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
10 Programming with Python – II
a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the
file exists. The file opens in the append mode. If the file does not exist, it creates a new file
for reading and writing.
ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end
of the file if the file exists. The file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.
Once file is opened and you have one file object, Here is a list of all attributes related to file object.
file.mode Returns access mode with which file was opened. (i.e., ‘r’, ‘w’, ‘r+,’rb’, etc.)
file.softspace Returns false if space explicitly required with print, true otherwise.
>>> my_file.closed
False
>>> my_file.mode
'r'
>>> my_file.name
'mynewfile.txt'
Example: Write a program in GUI to show opening and closing file.
Program
fo=open("foo.txt","wb")
print"name of file:",fo.name
print"closed or not:",fo.closed
print"opening mode:",fo.mode
print"softspace flag:",fo.softspace
Output
name of file: foo.txt
closed or not: False
Python File Input-Output 11
opening mode: wb
softspace flag: 0
Hello
Hello\n input_fileobj =
How are You\n open(‘kiran.txt’,’r’)
How are You
Welcome to Python str=’ ’
Learning\n line = input_fileobj.readline( ) Welcome to Python
while line != str: Learning
print(line)
line=
input_fileobj.readline( )
input_fileobj.close( )
# ...and...
f = open('somefile.txt','r')
for line in f.read().split('\n'):
print (line)
f.close()
# Open a file
fo # open (“foo.txt”, “wb”)
#!/usr/bin/python
import os
# Rename a file from kiran.txt to ks.txt
os.rename( "kiran.txt", "ks.txt" )
You can use the remove() method to delete files by supplying the name of the file to be
deleted as the argument.
Example
Following is the example to delete an existing file ks.txt:
#!/usr/bin/python
import os
Python File Input-Output 19
Return Value
This method returns the current position of the file read/write pointer within the file.
Example
The following example shows the usage of tell() method.
Assume created a new file named as kiran.txt
Python is a great language
Python is also structured language
Python is also object oriented language
Python has tuples
20 Programming with Python – II
Current Position: 28
Example
Let us take a file kiran.txt, which we created above.
#!/usr/bin/python
# Open a file
fo = open("kiran.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
Example
#!/usr/bin/python
# Open a file
fo = open("kiran.txt", "rw+")
print "Name of the file: ", fo.name
line = fo.readline()
print "Read Line: %s" % (line)
# Again set the pointer to the beginning
fo.seek(0, 0)
22 Programming with Python – II
line = fo.readline()
print "Read Line: %s" % (line)
OS Object Methods
This provides methods to process files as well as directories
Sr. No. Methods with Description
1 os.access(path,mode) Use the real uid/gid to test for access to path.
2 os.chdir(path) Change the current working directory to path
3 os.chmod(path, mode) Change the mode of path to the numeric mode.
4 os.chown(path, uid, gid) Change the owner and group id of path to the numeric uid and gid.
5 os.chroot(path) Change the root directory of the current process to path.
24 Programming with Python – II
Example
Following is the example to create a directory kiran in the current directory −
#!/usr/bin/python
import os
# Create a directory "test"
os.mkdir("kiran")
Example
Following is the example to go into "/home/ks" directory −
#!/usr/bin/python
import os
# This would give location of the current directory
os.getcwd()
Example
Following is the example to give current directory −
#!/usr/bin/python
import os
# This would give location of the current directory
os.getcwd()
Example
Following is the example to remove "/home/ks" directory. It is required to give fully qualified
name of the directory, otherwise it would search for that directory in the current directory, only
condition is ks directory should be empty & you should not be in ks directory.
#!/usr/bin/python
import os