New Unit 5
New Unit 5
5.1 FILES
Persistence
Most of the programs are transient which means that they run for a short time and produce
some output. But, when the program terminates, their data get vanished. When the program started
again, it starts with a clean slate. However, there are some other programs which are persistent that
they run for a long time (or all the time), maintain at least few of their data in permanent storage
(for example, a hard drive) and if the system set to shut down and restart, the program takes the data
from where it resides.
Examples of persistent programs are operating systems that run better whenever a computer
is on and web servers that run all the time and is waiting for requests to come in on the network.
One of the simplest ways for programs to maintain their data is by reading and writing text files.
Output:
Enter your input: Hello Python
Received input is : Hello Python
Output:
Enter your input: [x*5 for x in range(2,10,2)]
Recieved input is : [10, 20, 30, 40]
Now, we will see how to use actual data files. A text file is a sequence of characters stored on
a permanent storage medium such as hard drive, flash memory, or CD-ROM. Python offers some
basic functions and methods necessary to manipulate files by default. The file manipulation can be
done using a file object. The basic file operations are open, close, read and write files.
Syntax
fileobject = open(file_name [, access_mode][, buffering])
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.
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.
Attribute Description
file.closed Returns true if the file is closed, otherwise false.
file.mode Returns the file access mode with which file was opened.
file.name Returns name of the file.
file.softspace Returns false if space explicitly required with print, otherwise true.
The following illustrate the file attribute description using file object.
f = open(“file1.txt”, “w+”)
print “Name of the file: “, f.name
print “Closed or not : “, f.closed
print “Opening mode : “, f.mode
print “Softspace flag : “, f.softspace
5.4 Problem Solving and Python Programming
Output:
Name of the file: file1.txt
Closed or not: False
Opening mode: w+
Softspace flag: 0
Syntax
fileObject.close();
Output:
Name of the file: file1.txt
Syntax
fileObject.write(string);
The argument passed is the content to be written into the opened file. The following program
illustrates the file write operation.
f = open(“file1.txt”, “wb”)
print f
f.write( “Python is a programming language.\nIt is very flexible\n”);
Files, Modules, Packages 5.5
Output:
open file ‘file1.txt’, mode ‘wb’ at 0xb7eb2410
Python is a programming language.
It is very flexible
The above program creates a file file1.txt and writes the given content in that file and finally
it closes that file. If the file is opened, then it would have content what is written.
If the file already exists, then opening it in write mode erases the old data and starts fresh. If
the file doesn’t exist, then a new one is created.
for example,
line1 = “Python is a programming language, \n”
f.write (line1)
Here, the file object keeps track of where it is pointing to, so if write function is called again,
it adds the new data to the end of the file. For example,
line2 = “It is very flexible .\n”
f.write (line2)
If no more operations, need to be performed, then the file could be closed using file close()
function.
f.close()
Syntax
fileObject.read([count]);
The argument passed is the number of bytes to be read from the opened file. This method
starts reading from the beginning of the file and if the argument count is missing, then it tries to read
as much as possible, till the end of file.
Example
To read from the file file1.txt
# Open a file
f=open(“file1.txt”, “w+”)
5.6 Problem Solving and Python Programming
Output:
The string read is : Python is a program
The first operand is the format string that contains one or more format sequences, to specify
how the second operand is formatted. The result is a string. For example, the format sequence ‘%d’
means that the second operand should be formatted as an integer (d stands for “decimal”): consider
the simple example.
x = 15
print ‘%d’ % x
Output:
15
The result is the string ‘15’, which is not to be confused with the integer value 15. A format
sequence can appear anywhere in the string, so you can embed a value in a sentence:
bugs= 10
print ‘I have spotted %d bugs.’ % bugs
Output:
I have spotted 10 bugs
If there is more than one format sequence in the string, the second argument must be a tuple.
Each format sequence is matched with an element of the tuple, in sequence. The various format
sequences are ‘%d’ to format an integer, ‘%g’ to format a floating-point number and ‘%s’ to format
a string.
Files, Modules, Packages 5.7
Output:
In 2 years I have spotted 0.3 bugs.
The number of elements in the tuple has to match the number of format sequences in the
string. The types of the elements have to match the format sequences also.
Example:
print ‘%d %d %d’ % (1, 2)
Output:
Traceback (most recent call last):
File “main.py”, line 1, in
print ‘%d %d %d’ % (1, 2)
TypeError: not enough arguments for format string
Example:
print ‘%d’ % ‘dollars’
Output:
Traceback (most recent call last):
File “main.py”, line 1, in
print ‘%d’ % ‘dollars’
TypeError: %d format: a number is required, not str
In the first example, there are three format sequences and only two elements; in the second,
the format sequence is for integer but the element is string. The format operator is more effective,
however it is difficult to use.
Method Description
close() Close an open file. It has no effect if the file is already closed.
Separate the underlying binary buffer from the TextIOBase
detach()
and return it.
fileno() Return an integer number (file descriptor) of the file.
flush() Flush the write buffer of the file stream.
isatty() Return True if the file stream is interactive.
5.8 Problem Solving and Python Programming
Read atmost n characters form the file. Reads till end of file
read(n)
if it is negative or None.
readable() Returns True if the file stream can be read from.
Read and return one line from the file. Reads in at most n
readline(n=-1)
bytes if specified.
Read and return a list of lines from the file. Reads in at most
readlines(n=-1)
n bytes/characters if specified.
Change the file position to offset bytes, in reference to from
seek(offset,from=SEEK_SET)
(start, current, end).
seekable() Returns True if the file stream supports random access.
tell() Returns the current file location.
Resize the file stream to size bytes. If size is not specified,
truncate(size=None)
resize to current location.
writable() Returns True if the file stream can be written to.
Write string s to the file and return the number of characters
write(s)
written.
writelines(lines) Write a list of lines to the file.
File Positions
The tell() method gives the current object position within the file; in other words, the
next read or write will occur at that many bytes from the beginning of the file. The seek (offset
[, from]) method modifies the current file position. The offset argument specifies the number of
bytes to be moved. The from argument specifies the reference position from where the bytes are to
be moved. If from is set to 0, it means use the beginning of the file as the reference position and 1
means use the current position as the reference position and if it is set to 2 then the end of the file
would be taken as the reference position. The following program explains the functions of tell() and
seek() functions.
# Open a file
f=open(“file1.txt”, “w+”)
f.write(“ Python is a programming language”)
f.close()
f = open(“file1.txt”, “r+”)
str = f.read(20);
print “ The string read is : “, str
# Check current position
pos = f.tell();
print “current file position:”, pos
Files, Modules, Packages 5.9
Example:
Following is the example to delete an existing file file2.txt −
import os
# Delete file file2.txt
os.remove(“file2.txt”)
os.mkdir(“test”)
5.10 Problem Solving and Python Programming
The two files are opened in reading mode and iterate over each name using a for loop. A
new file with the name “[name].txt” is created, where name is the name of that person. Here, the
strip() method is used to clean up leading and trailing whitespaces (reading a line from the file
also reads the newline ‘\n’ character). Finally, we write the content of the mail into this file using
the write() method.
import sys
print ‘No. of arguments:’, len(sys.argv)
print ‘Argument List:’,str(sys.argv)
Files, Modules, Packages 5.11
A string like cwd that identifies a file is called a path. A relative path starts from the current
directory; an absolute path starts from the topmost directory in the file system. The paths we have
seen so far are simple filenames, so they are relative to the current directory. To find the absolute
path to a file, you can use os.path.abspath:
abs_path=os.path.abspath(‘file1.txt’)
print abs_path
Output:
/web/com/1493114533_4353/file1.txt
os.path.exists checks whether a file or directory exists:
print os.path.exists(‘file1.txt’)
Output:
True
If it exists, os.path.isdir checks whether it’s a directory:
print os.path.isdir(‘file1.txt’)
Output:
False
5.12 Problem Solving and Python Programming
To demonstrate these functions, the following example “walks” through a directory, prints
the names of all the files, and calls itself recursively on all the directories.
def walk(dirname):
for name in os.listdir(dirname):
path = os.path.join(dirname, name)
if os.path.isfile(path):
print path
else:
walk(path)
os.path.join takes a directory and a file name and joins them into a complete path.
•• Syntax errors
•• Runtime errors
•• Logical errors
Syntax Errors
Syntax errors, also known as parsing errors are identified by Python while parsing the
program. It displays error message and exit without continuing execution process. They are similar
to spelling mistakes or grammar mistakes in normal language like English. Some common Python
syntax errors include:
•• leaving out a keyword
•• putting a keyword in the wrong place
•• leaving out a symbol, such as a colon, comma or brackets
•• misspelling a keyword
•• incorrect indentation
•• empty block
Files, Modules, Packages 5.13
Error Message:
File “main.py”, line 3
if a<b
^
if True:
prnt ‘Hello’
Error Message:
File “main.py”, line 2
prnt ‘Hello’
^
Logical errors
Logical errors occur due to mistake in program’s logic. Here program runs without any error
messages, but produces an incorrect result. These errors are difficult to fix. Here are some examples
of mistakes which lead to logical errors:
•• using the wrong variable name
•• indenting a block to the wrong level
•• using integer division instead of floating-point division
•• getting operator precedence wrong
•• making a mistake in a boolean expression
•• off-by-one, and other numerical errors
5.14 Problem Solving and Python Programming
Sample Output:
Fact:0
In this example for computing factorial of 5, the obtained output is 0. There are no syntax
errors. The wrong output occurs due to logical error fact=0. To compute factorial, the fact value
must be initialized to 1. As it is assigned as 0, it results in wrong output.
5.2.2 Exceptions
An exception is an error that occurs during execution of a program. It is also called as run
time errors. Some examples of Python runtime errors:
•• division by zero
•• performing an operation on incompatible types
•• using an identifier which has not been defined
•• accessing a list element, dictionary value or object attribute which doesn’t exist
•• trying to access a file which doesn’t exist
Python has many built-in exceptions which forces your program to output an error when
something in it goes wrong. When these exceptions occur, it stops the current process and passes the
control to corresponding exception handler. If not handled, our program will crash.
Handling Exceptions
The simplest way to handle exceptions is with a “try-except” block. Exceptions that are
caught in try blocks are handled in except blocks. The exception handling process in Python is
shown in Figure.5.1. If an error is encountered, a try block code execution is stopped and control
transferred down to except block.
5.16 Problem Solving and Python Programming
Syntax:
try:
# statements
break
except ErrorName:
# handler code
Sample Output:
divide by zero
To display built-in error message of exception, you could have :
(x,y) = (5,0)
try:
z = x/y
Files, Modules, Packages 5.17
except ZeroDivisionError as e:
z = e # representation: “<exceptions.ZeroDivisionError instance at 0x817426c>”
print z # output: “integer division or modulo by zero”
Sample Output:
integer division or modulo by zero
A try statement may have more than one except clause, to specify handlers for different
exceptions. If an exception occurs, Python will check each except clause from the top down to see
if the exception type matches. If none of the except clauses match, the exception will be considered
unhandled, and your program will crash:
Syntax:
try:
# statements
break
except ErrorName1:
# handler code
except ErrorName2:
# handler code
A simple example to handle multiple exceptions is as follows.
try:
dividend = int(input(“Please enter the dividend: “))
divisor = int(input(“Please enter the divisor: “))
print(“%d / %d = %f” % (dividend, divisor, dividend/divisor))
except ValueError:
print(“The divisor and dividend have to be numbers!”)
except ZeroDivisionError:
print(“The dividend may not be zero!”)
Sample input/output (successful):
Please enter the dividend: 10
Please enter the divisor: 2
10 / 2 = 5.000000
Example:
try:
dividend = int(input(“Please enter the dividend: “))
divisor = int(input(“Please enter the divisor: “))
print(“%d / %d = %f” % (dividend, divisor, dividend/divisor))
except(ValueError, ZeroDivisionError):
print(“Oops, something went wrong!”)
Sample Input/Output:
Please enter the dividend: 10
Please enter the divisor: 0
Oops, something went wrong!
To catch all types of exceptions using single except clause, simply mention except keyword
without specifying error name. It is shown in following example.
try:
dividend = int(input(“Please enter the dividend: “))
divisor = int(input(“Please enter the divisor: “))
print(“%d / %d = %f” % (dividend, divisor, dividend/divisor))
except:
print(“Oops, something went wrong!”)
Raising Exceptions
The raise statement initiates a new exception. It allows the programmer to force a specified
exception to occur. The raise statement does two things: it creates an exception object, and
immediately leaves the expected program execution sequence to search the enclosing try statements
for a matching except clause. It is commonly used for raising user defined exceptions. Two forms
of the raise statement are:
Syntax:
raise ExceptionClass(value)
raise Exception
Files, Modules, Packages 5.19
Example:
try:
raise NameError
except NameError:
print(‘Error’)
Sample Output:
Error
raise without any arguments is a special use of python syntax. It means get the exception
and re-raise it. The process is called as reraise. If no expressions are present, raise re-raises the last
exception that was active in the current scope.
Example:
try:
raise NameError
except NameError:
print(‘Error’)
raise
Sample Output:
Error
Traceback (most recent call last):
File “main.py”, line 2, in <module>
raise NameError(‘Hi’)
NameError: Hi
In the example, raise statement inside except clause allows you to re-raise the exception
NameError.
try:
age = int(input(“Please enter your age: “))
except ValueError:
print(“Hey, that wasn’t a number!”)
else:
print(“I see that you are %d years old.” % age)
5.20 Problem Solving and Python Programming
Sample input/output:
Please enter your age: 10
I see that you are 10 years old.
Please enter your age: ‘a’
Hey, that wasn’t a number!
In addition to using except block after the try block, you can also use the finally block. The
code in the finally block will be executed regardless of whether an exception occurs and even if we
exit the block using break, continue, or return.
try:
age = int(input(“Please enter your age: “))
except ValueError:
print(“Hey, that wasn’t a number!”)
else:
print(“I see that you are %d years old.” % age)
finally:
print(“Goodbye!”)
Sample input/output:
Please enter your age: 20
I see that you are 20 years old.
Goodbye!
Sample input/output:
Enter a number: 12
This value is positive!
In the example, the user defined exception class Error is derived from built-in class
Exception. It handles two user defined exceptions: PosError, raised when input value is positive
and NegError, raised when input value is negative. The pass keyword indicates null block. The
main program reads user input and compares input value with 0. If input>0, the exception PosError
is raised using raise keyword else the exception NegError is raised.
5.3 MODULES
A Python module is a file that consists of Python code. It allows us to logically arrange
related code and makes the code easier to understand and use. It defines functions, classes and
variables.
Python has many useful functions and resources in modules. Functions such as abs() and
round() from __builtin__ module are always directly accessible in every Python code. But, the
programmer must explicitly import other functions from the modules in which they are defined.
import statement
An import statement is used to import Python module in some Python source file.
5.22 Problem Solving and Python Programming
Example:
import math
For example, math is a built-in module that offers several built-in functions for carrying out
basic mathematical operations. The following code imports math module and lists a directory of its
resources:
import math
print dir(math)
Output:
[‘__doc__’, ‘__file__’, ‘__name__’, ‘__package__’, ‘acos’, ‘acosh’, ‘asin’,
‘asinh’, ‘atan’, ‘atan2’, ‘atanh’, ‘ceil’, ‘copysign’, ‘cos’, ‘cosh’, ‘degrees’, ‘e’,
‘erf’, ‘erfc’, ‘exp’, ‘expm1’, ‘fabs’, ‘factorial’, ‘floor’, ‘fmod’, ‘frexp’, ‘fsum’,
‘gamma’, ‘hypot’, ‘isinf’, ‘isnan’, ‘ldexp’, ‘lgamma’, ‘log’, ‘log10’, ‘log1p’,
‘modf’, ‘pi’, ‘pow’, ‘radians’, ‘sin’, ‘sinh’, ‘sqrt’, ‘tan’, ‘tanh’, ‘trunc’]
The usage of some built-in functions of math module is shown in the following code along with
its output:
import math # Import built-in module math
print math.floor(6.9)
print math.ceil(6.9)
print math.pow(3,4)
Output:
6.0
7.0
81.0
The following table gives description about a few modules of Python:
support.py
def add( a, b ):
print ‘Result is ‘, a+b
return
def display(p):
print ‘Welcome, ‘,p
return
This support.py file can be imported as a module in another Python source file and its
functions can be called from the new file as shown in the following code:
Result is ab
Result is RamKumar
Welcome, Ram
from...import Statement
It allows us to import specific attributes from a module into the current namespace.
Syntax:
from modulename import name1[, name2[, ... nameN]]
The first statement of the following code does not import the entire module support into the
current namespace; it just introduces the item add from the module support into the global symbol
table of the importing module. Hence, a call to display() function generates an error as shown in the
output.
from support import add # Import module support
add(3,4) # calling add() of support module with two integer values
add(3.5,4.7) # calling add() of support module with two real values
add(‘a’,’b’) # calling add() of support module with two character values
add(‘Ram’,’Kumar’) # calling add() of support module with two string values
display(‘Ram’) # calling display() of support module with a string value
Output:
Result is 7
Result is 8.2
Result is ab
Result is RamKumar
Traceback (most recent call last):
File “main.py”, line 8, in
display(‘Ram’) # calling display() of support module with a string value
NameError: name ‘display’ is not defined
from...import * Statement:
It allows us to import all names from a module into the current namespace.
Syntax:
from modulename import *
Sample Code:
from support import * # Import module support
add(3,4) # calling add() of support module with two integer values
Files, Modules, Packages 5.25
Sample Output:
Result is 7
Result is 8.2
Result is ab
Result is RamKumar
Welcome, Ram
Programs that will be imported as modules often use the following expression:
if __name__ == ‘__main__’:
# test code
Here, __name__ is a built-in variable and is set when the program starts execution. If the
program runs as a script, __name__ has the value __main__ and the test code is executed. Else, the
test code is skipped.
Sample Code:
from support import * # Import module support
if __name__ == ‘__main__’: # add() and display() are called only if this pgm runs as
a script.
add(3,4)
display(‘Ram’)
Sample Output:
Result is 7
Welcome, Ram
reload()
When the module is already imported into a script, the module is not re-read eventhough it
is modified. The code of a module is executed only once. To reload the previously imported module
again, the reload() function can be used.
Syntax:
reload(modulename)
5.4 PACKAGES
When we have a large number of Python modules, they can be organized into
packages such that similar modules are placed in one package and different modules are
placed in different packages. A package is a hierarchical file directory structure that defines a
single Python application environment that consists of modules, sub-packages, sub-subpackages,
and so on. In another words, it is a collection of modules. When a package is imported, Python
explores in list of directories on sys.path for the package subdirectory.
Example:
Assume we are creating a package named Animals with some subpackages as shown in
Figure.5.2.
Animals
(Package)
_init_.py _init_.py
(Module) (Module)
create.py create.py
(Module) (Module)
print.py display.py
(Module) (Module)
Method 1:
Consider, we import the display.py module in the above example. It is accomplished by the
following statement.
import Animals.Birds.display
Now if this display.py module contains a function named displayByName(), we must use
the following statement with full name to reference it.
Animals.Birds.display.displayByName()
Method 2:
On another way, we can import display.py module alone as follows:
from Animals.Birds import display
Then, we can call displayByName() function simply as shown in the following statement:
display.displayByName()
5.28 Problem Solving and Python Programming
Method 3:
In the following statement, the required function alone is imported from a module within a
package:
from Animals.Birds.display import displayByName
Though this method is simple, usage of full namespace qualifier avoids confusion and
prevents two similar identifier names from colliding.
In the above example, __init__.py of Animals package contains the following code:
from Mammals import Mammals
from Birds import Birds
In python, module is a single Python file and package is a directory of Python modules
containing an additional __init__.py file. Packages can be nested to any depth, but the
corresponding directories should include their own __init__.py file.
5.5.2 Python program to raise an exception when the user input is negative
try:
a = int(input(“Enter a positive integer value: “))
if a <= 0:
raise ValueError(“This is not a positive number!!”)
except ValueError as ve:
print(ve)
Files, Modules, Packages 5.29
Sample input:
Enter a positive integer value: -1
Error:
This is not a positive number!!
Sample Output:
The number of words are: 20
Sample Output:
This 1
program 2
example 1
Python 2
5.30 Problem Solving and Python Programming
Program 2:
with open(“in.txt”) as f:
with open(“out.txt”, “w”) as f1:
for line in f:
if “ROW” in line:
f1.write(line)
Program 3:
# The shutil module offers a number of high-level operations on files and collections
of files
from shutil import copyfile
copyfile(‘test.py’, ‘abc.py’) # copy content of test.py to abc.py
Sample Output:
Python Exercises
Java Exercises
Files, Modules, Packages 5.31
Random access file - Python program to read a random line from a file.
A random-access data file enables you to read or write information anywhere in the file.
You can use seek() method to set the file marker position and tell() method to get the current
position of the file marker. In a sequential-access file, you can only read and write information
sequentially, starting from the beginning of the file.
f=open(‘Python_source\\test.txt’,’w’)
f.write(‘DearChanna ‘)
f.seek(4) #move file pointer to 4th position from beginning of file
f.write(‘ Mr.Channa’)
f.close()
f=open(‘Python_source\\test.txt’,’r’)
f.read()
Sample Output:
Dear Mr.Channa
Program that asks the user to input customer information, call writetofile method to
write data to the file and call getall method to retrieve customer information from file.
#write data to file
def writetofile(Name,Email=’’,Tel=’’,Address=’’):
try:
f=open(r’customerlist.txt’,’a’)
f.write(Name+’:’+Email+’:’+Tel+’:’+Address+’\n’)
except Exception:’Print error in writing to file...’
finally:
5.32 Problem Solving and Python Programming
f.flush()
f.close()
#Get all customers’information and display
def getall():
f=open(r’customerlist.txt’,’r’)#open file for reading
content=f.readlines()#read all lines
f.close()
return content
def add():
Name=raw_input(‘Name:’)
Email=raw_input(‘Email:’)
Tel=raw_input(‘Tel:’)
Address=raw_input(‘Address:’)
writetofile(Name,Email,Tel,Address)
#main program
add()
print getall()
With reference to previous program, write a method to search for a customer by name.
#Search customer by name. If match is found, it returns the position of the name
else returns -1.
def search(Name):
global flag#declare global variable
try:
f=open(r’customerlist.txt’,’r’)#open file for reading
f.seek(0)
content=f.readline()
while content!=’’:
if content.find(Name)!=-1:
print content
flag=1
return int(f.tell())-int(len(content)+1) # return the position of the
matched name
else:
Files, Modules, Packages 5.33
content=f.readline()
flag=0
except Exception:print ‘Error in reading file...’
finally:
f.close()
if flag==0:
print ‘Not found’ #Inform the use if the record does not exist
return -1 # The record not found-->return -1
Using previous search method, write a program to delete a customer name from file.
#delete customer’s information by name
def delete(Name):
print search(Name)
p=search(Name) # returns position of given customer name
print “x=”,p
if p!=-1: #Make sure the record exists
st=getall() #retrieve content about cutomer
f=open(r’customerlist.txt’,’w’)#open file for writing
f.writelines(st)
f.seek(p)
f.write(‘*****’)#write 5 starts to override the 5 characters of the name to
be deleted
else:
print ‘No record to delete’#Inform the use if the record does not exist
f.close()
5.34 Problem Solving and Python Programming
3. Name few Python modules for Statistical, Numerical and Scientific computations.
Module Usage
numPy provides an array/matrix type, and it is useful for doing computations on
arrays
scipy provides methods for doing numeric integrals and solving differential equa-
tions
pylab generating and saving plots
matplotlib managing data and generating plots
4. Define Package.
A package is a hierarchical file directory structure that defines a single Python application
environment that consists of modules, sub-packages, sub-subpackages, and so on. In another
words, it is a collection of modules. When a package is imported, Python explores in list of
directories on sys.path for the package subdirectory.
5. Define Exception.
An exception is an error that occurs during execution of a program. It is also called as run time
errors. Some examples of Python runtime errors:
•• division by zero
•• performing an operation on incompatible types
Syntax:
try:
# statements
break
except ErrorName:
# handler code
15. Name few Python modules for Statistical, Numerical and Scientific computations.
Module Usage
numPy provides an array/matrix type, and it is useful for doing
computations on arrays
Files, Modules, Packages 5.37
26. Explain how to redirect the output of a python script from standout (monitor) on to a file?
They are two possible ways of redirecting the output from standout to a file.
1. Open an output file in “write” mode and the print the contents in to that file, using sys.
stdout attribute.import sys
filename = “outputfile” sys.stdout = open() print “testing”
2. You can create a python script say .py file with the contents, say print “testing”
and then redirect it to the output file while executing it at the command prompt.
Eg: redirect_output.py has the following code:
27. Explain the shortest way to open a text file and its contents?
The shortest way to open a text file is by using “with” command as follows:
with open("file-name", "r") as fp:
fileData = fp.read()
#to print the contents of the file print(fileData)
1 Java
2 C++
29. How do you perform pattern matching in Python? Explain.
Regular Expressions/REs/ regexes enable us to specify expressions that can match specific
“parts” of a given string. For instance, we can define a regular expression to match a single
character or a digit, a telephone number, or an email address, etc.The Python’s “re” module
provides regular expression patterns and was introduce from later versions of Python 2.5.
“re” module is providing methods for search text strings, or replacing text strings along with
methods for splitting text strings based on the pattern defined.
30. Name few methods for matching and searching the occurrences of a pattern in a given text
string?
There are 4 different methods in “re” module to perform pattern matching. They are:
match() – matches the pattern only to the beginning of the String. search() – scan the string and
look for a location the pattern matches findall() – finds all the occurrences of match and return
them as a list
finditer() – finds all the occurrences of match and return them as an iterator.
33. What is JSON? How would convert JSON data into Python data?
JSON – stands for JavaScript Object Notation. It is a popular data format for storing data in
NoSQL databases. Generally JSON is built on 2 structures.
1. A collection of <name, value> pairs.
2. An ordered list of values.
As Python supports JSON parsers, JSON-based data is actually represented as a dictionary in
Python. You can convert json data into python using load() of json module.
GUI applications. The common attributes of them include Dimensions, Colors, Fonts, Cursors,
etc.
35. Name and explain the three magic methods of Python that are used in the construction and
initialization of custom objects.
The 3 magic methods of Python that are used in the construction and initialization of custom
Objects are: init__, new, and del__.
new – this method can be considered as a “constructor”. It is invoked to create an instance of a
class with the statement say, myObj = MyClass () init__ — It is an “initializer”/ “constructor”
method. It is invoked whenever any arguments are passed at the time of creating an object.
myObj = MyClass(‘Pizza’,25) del- this method is a “destructor” of the class. Whenever an
object is deleted, invocation of del__ takes place and it defines behaviour during the garbage
collection.
Note: new, del are rarely used explicitly.
>>> if voting_age < 18: raise ValueError(“voting age should be atleast 18 and above”)
output: ValueError: voting age should be atleast 18 and above 2. assert statement assert
statements are used to tell your program to test that condition attached to assert keyword,
and trigger an exception whenever the condition becomes false. Eg: >>> a = -10 >>> assert
a > 0 #to raise an exception whenever a is a negative number output: AssertionError Another
5.42 Problem Solving and Python Programming
way of raising and exception can be done by making a programming mistake, but that’s not
usually a good way of triggering an exception.
38. How do you check the file existence and their types in python?
os.path.exists() – use this method to check for the existence of a file. It returns True if the file
exists, false otherwise. Eg: import os; os.path.exists(‘/etc/hosts’)
os.path.isfile() – this method is used to check whether the give path references a file or not. It
returns True if the path references to a file, else it returns false. Eg: import os; os.path.isfile(‘/
etc/hosts’)
os.path.isdir() – this method is used to check whether the give path references a directory or
not. It returns
True if the path references to a directory, else it returns false. Eg: import os; os.path.isfile(‘/etc/
hosts’)
os.path.getsize() – returns the size of the given file
os.path.getmtime() – returns the timestamp of the given path.