- Subin <subins2000@gmail.com>
- 21/11/2017
- https://gist.github.com/subins2000/62db12a493f74d768b41934876f30aa5
-
- The following code sequence fails with a traceback when user enters a file that does not exist. How would you avoid the traceback and make it so you could print out your own error message when a bad file name was entered ?
fname = raw_input('Enter name: ') fhand = open(fname)
Justify your answer.
-
Answer
A try-except block can be used to catch the error when the filename inputted by user doesn't exist :
#Python3 fname = input('Enter name: ') try: fhand = open(fname) except IoError: print('Unable to open file. Make sure the file exists')
When the file doesn't exist, calling
open()
will throw an exceptionIoError
. This error will be caught in the program and a message will be printed.
-
- Compare class and object. Generate a class to represent a rectangle.
-
Answer
class object Class is a blueprint or template from which objects are created Object is an instance of class Class is declared once Object is created many times as per requirement Class is defined with class
keyword :
class student:
name = ''Object is created from class :
s1 = student()This is a class to represent a rectangle :
class rectangle: length = 0 breadth = 0
-
- What is pickling ? How does it aid in putting values into a file? Also, what happens when the "load" method is invoked ?
-
Answer
Pickling is used for serializing and de-serializing a Python object structure. Any object in Python can be pickled so that it can be saved on disk and reused later. What pickle does is that it “serialises” the object first before writing it to file. Pickling is a way to convert a python object (list, dict, etc.) into a character stream.
#Python3 import pickle fp = open('file.txt', 'r') # load the object from the file into var b b = pickle.load(fp)
When the
load()
function is called, the passed string is de-serialized and made into the original object. This object will be stored in the variableb
in the above example.
-
- b) Write a program that reads a file and writes out a new file with the lines in reversed order (7)
-
Answer
#Python3 file = open('a.txt', 'r') out = open('out.txt', 'a') contents = file.readlines() contents = reversed(contents) for s in contents: out.write(s) file.close() out.close()
-
24 a) Write a function that gets input from the user and handles the Value Error exception. Describe how exceptions are handled in python (8)
b) Create a class Student with attributes name and roll no. and a method dataprint() for displaying the same. Create two instances of the class and call the method for each instance.
-
Answer
a.
#Python3 def getInput(): a = input('Enter an input: ') # Check if it only has non alphabets if a.isalpha() == False: raise ValueError('Only alphabets are allowed')
In Python, exceptions are handled with a
try-except
block :try: # Call our function getInput() # Do something else except ValueError: # Handle the error
In the try block, the code to run is added. We can mention the exception to be caught after the
except
keyword. When the code is ran and the exception occurs, the rest of the code intry
block is halted and the code insideexcept
block is ran.Exception will contain more information about the error. It can be received by using
as
keyword mentioning a variable :try: getInput() except ValueError as error: # Handle error print(error) # Prints "Only alphabets are allowed"
Handling exceptions are extremely useful because the program can be prevented from stopping execution when an error occurs.
-
-
- Distinguish between object identity and structural equivalence.
-
Answer
Object Identity Structural Equivalence Two objects are considered to be the same object based on having identical properties Two objects are structurally equivalent if they have the same physical instance Objects are identical if they are instances of the same class Objects are structural equivalent if class and all attributes of both are the same a = myClass()
b = myClass()
b.property = 1
a is b # Returns Truea = myClass()
b = myClass()
b.property = 1
a.property == b.property # Returns False
-
- List out the different modes in which a file can be opened in Python
-
Answer
open('filename', 'w')
This mode is used to write to a file. The file will be created if it doesn't exist.
open('filename', 'r')
This mode is used to read from a file. The file should exist. Otherwise an IoError is thrown.
open('filename', 'a')
This mode is used to append contents to a file.
-
- What do you mean by pickling in python? Explain its significance with the help of example.
-
Answer
Pickling is used for serializing and de-serializing a Python object structure. Any object in Python can be pickled so that it can be saved on disk and reused later. What pickle does is that it “serialises” the object first before writing it to file. Pickling is a way to convert a python object (list, dict, etc.) into a character stream.
#Python3 import pickle fp = open('file.txt', 'w') a = ['hello', 'world'] pickle.dump(a, fp) fp = open('file.txt', 'r') b = pickle.load(fp) print(a == b) # Prints True
-
24 (a) Define the terms class,attribute,method and instance with the help of an example. (4)
(b) Create a class person with attributes Name, age, salary and a method display() for showing the details. Create two instances of the class and call the method for each instance. (5)
(c) Write a python program that opens a file for input and prints the count of four letter words in it. (5)
-
Answer
a)
#Python3 class student: name = '' def printHello(self): print('Hello')
Class is a data structure that combines multiple types of data into one. Here,
student
is the class.Attributes are properties of a class to which values are stored. Here,
name
is an attributeMethods are the functions inside the class. Here,
printHello()
is a method.#Python3 s1 = student() s1.name = 'Vyshak'
An object of a class is called an instance. Any changes to it will reflect only in that object
b)
#Python3 class person: name = '' age = 0 salary = 0 def display(self): print('Name: ', self.name) print('Age: ', self.age) print('Salary: ', self.salary) p1 = person() p1.name = 'Vishnu' p1.age = 19 p1.salary = 40000 p2.name = 'Sudeep' p2.age = 19 p2.salary = 40000 p1.printDetails() p2.printDetails()
c)
#Python3 fp = open('file.txt', 'r') s = fp.read() count = 0 for word in s.split(' '): if len(word) == 4: count += 1 fp.close() print('Number of 4 letter words: ', count)
-
-
- Why exception handling is required in programming
-
Answer
When runtime errors occur in a program, the whole program will be stopped. To prevent this, we can catch the errors and still continue the execution of the program.
The caught errors can be outputted to a log file for debugging. Thus the problem can be found out and the program will still run without stopping.
-
- Differentiate Shallow equality and Deep equality
-
Answer
Shallow Equality = Object Identity Deep Equality = Structural Equivalence
See answer of 12th question of January 2017 paper
-
-
Repeatation of quetion 16 of January 2017 paper
List advantage of using Pickling
-
Answer
- Objects can be saved to and read from file
- Objects can be reused later
- User data can be conveniently saved
-
-
- b) Repeatation of a previous question (try-except)
-
-
a) Write a Python code to read a text file, copy the contents to another file after removing the blank lines
b) Repeatation of previous question (class, attributes, instances)
-
Answer
a.
#Python3 inputFile = open('file.txt', 'r') outFile = open('out.txt', 'w') while True: line = inputFile.readline() if line == '': break # \n indicates a newline (linebreak). A blank line means that it has nothing but a linebreak if line != '\n': outFile.write(line) inputFile.close() outFile.close()
-
-
- Repeat of question January 2017 question 16
-
- Repeat of question August 2017 question 24 a.
-
-
b) Write a Python program to create a text file and to input a line of text to it. Display the line of text with all punctuation marks removed.
-
Answer
#Python3 toWrite = input('Enter a text: ') fp = open('file.txt', 'w') fp.write(toWrite) fp.close() fp = open('file.txt', 'r') contents = fp.read() for l in contents: if l != '.' and l != '!' and l != '?' print(l, end='') fp.close()
-
-
-
24 a) Repeat of question 24(a) of January 2017
c) Write a Python program to create a file containing 10 numbers. Read the contents of the file and display the square of each number.
-
Answer
c)
#Python3 fp = open('file.txt', 'w') for i in range(0, 10): number = input('Enter a number: ') fp.write(number) fp.close() fp = open('file.txt', 'r') while True: line = fp.readline() if line == '': break # Line will have a number only. So square it print(line * line) fp.close()
-