Q.What Are The Uses of File Object: Except (Exception1, Exception2, Exceptionn) As E

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

Unit 2

Q.What are the uses of file object.


A file object allows us to use, access and manipulate all the user accessible files. One can
read and write any such files. When a file operation fails for an I/O-related reason, the exception
IOError is raised.

Q.How to handle multiple exceptions using single except clause


It is possible to define multiple exceptions with the same except clause. It means that if the
Python interpreter finds a matching exception, then it’ll execute the code written under except
clause.
Syntax:
Except(Exception1, Exception2,…ExceptionN) as e:

Q.What happens if we use semicolon at the end of the statement in python

A semi-colon in Python denotes separation, rather than termination. It allows you to

write multiple statements on the same line.


print('Statement 1'); print('Statement 2'); print('Statement 3')

Q.Name some standard exceptions with examples

SyntaxError Raised when there is an error in Python syntax.

IndentationError Raised when indentation is not specified properly.

ZeroDivisonErro Raised when division or modulo by zero takes place for all numeric types.
r

IOError Raised when an input/ output operation fails, such as the print statement or the
open() function when trying to open a file that does not exist. Also raised for
operating system-related errors.

RuntimeError Raised when a generated error does not fall into any category.

ImportError Raised when an import statement fails.


Q.How to import modules. Give examples

We can import the definitions inside a module to another module or the interactive interpreter in
Python.
We use the import keyword to do this. To import our previously defined module example, we
type the following in the Python prompt.
Example: import example

3marks
Q.Give a brief description of built in attributes related to file objects.
A file object has a lot of attributes. You can see a list of all methods and attributes of the file
object here: https://docs.python.org/2.4/lib/bltin-file-objects.html. Following are some of the
most used file object methods −

 close() - Close the file.

 next() - When a file is used as an iterator, typically in a for loop (for example, for line in f:
print line), the next() method is called repeatedly. This method returns the next input
line, or raises StopIteration when EOF is hit.

 read([size]) - Read at most size bytes from the file.

 readline([size]) - Read one entire line from the file.

 seek(offset[, whence]) - Set the file's current position, like stdio's fseek(). The whence
argument is optional and defaults to 0 (absolute file positioning); other values are 1
(seek relative to the current position) and 2 (seek relative to the file's end).

 tell() - Return the file's current position, like stdio's ftell().

 write(str) - Write a string to the file.

 writelines(sequence) - Write a sequence of strings to the file.


Following are file object's most used attributes −

 closed - bool indicating the current state of the file object.


 encoding - The encoding that this file uses.

 mode - The I/O mode for the file.

 name - If the file object was created using open(), the name of the file. Otherwise, some
string that indicates the source of the file object

Q.What is the difference between interpreted and compiled languages? What


are mutable and immutable types.

Mutable types:
The data types or data structures which can be changed or manipulated is known as mutable
types
immutable :
The data types or data structures which can not be changed or manipulated is known as
mutable types

Write a short note on context management protocol

Context managers allow you to allocate and release resources precisely when you want
to. The most widely used example of context managers is the  with  statement. Suppose
you have two related operations which you’d like to execute as a pair, with a block of
code in between. Context managers allow you to do specifically that. For example:

with open('some_file', 'w') as opened_file:


opened_file.write('Hola!')

The above code opens the file, writes some data to it and then closes it. If an error
occurs while writing the data to the file, it tries to close it. The above code is equivalent
to:

file = open('some_file', 'w')


try:
file.write('Hola!')
finally:
file.close()

as we can notice that lot of code has been reduced which makes it less
complicated.
Q.Write syntax to create exceptions. Write 3 examples
In Python, users can define custom exceptions by creating a new class. This exception
class has to be derived, either directly or indirectly, from the built-in Exception class.
Most of the built-in exceptions are also derived from this class.
Example
# define Python user-defined exceptions

class Error(Exception):
"""Base class for other exceptions"""
pass

class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass

class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass

# you need to guess this number


number = 10

# user guesses a number until he/she gets it right


while True:
try:
i_num = int(input("Enter a number: "))
if i_num < number:
raise ValueTooSmallError
elif i_num > number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")
print()
except ValueTooLargeError:
print("This value is too large, try again!")
print()

print("Congratulations! You guessed it correctly.")

o/p

Enter a number: 12
This value is too large, try again!

Enter a number: 0
This value is too small, try again!

Enter a number: 8
This value is too small, try again!

Enter a number: 10
Congratulations! You guessed it correctly.

1. A namespace (sometimes also called a context) is a naming system for making


names unique to avoid ambiguity.
2. In Python, you can imagine a namespace as a mapping of every name, you
have defined, to corresponding objects.
3. A namespace containing all the built-in names is created when we start the Python
interpreter and exists as long we don't exit.
4. This is the reason that built-in functions like id(), print() etc. are always available
to us from any part of the program.
5. When we create variables or define our own functions, these are also added to the
same namespace.

Although there are various unique namespaces defined, we may not be able to access all of
them from every part of the program. The concept of scope comes into play.

Scope is the portion of the program from where a namespace can be accessed directly without
any prefix.

At any given moment, there are at least three nested scopes.


1. Scope of the current function which has local names
2. Scope of the module which has global names
3. Outermost scope which has built-in names
When a reference is made inside a function, the name is searched in the local
namespace, then in the global namespace and finally in the built-in
namespace.
If there is a function inside another function, a new scope is nested inside the local scope.

Unit 3
Q.Explain about the following re patern (a)[dn]ot (b)[A-Za-z]\w*

[dn]ot - ”d” or ”n”, followed by an ”o” and, at most one ”t” after that; do, not, dot, not.
A-Za-z]\w* - a to z or A to z followed by a non word character atleast 0 or more times

Explain about match() and how can we match more than one string
The  re.match() is a function of re module in python. These function very
efficient and fast for searching in strings. The function searches for some
substring in a string and returns a match object if found, else it returns none.
re.match() searches only from the beginning of the string and return match
object if found. But if a match of substring is found somewhere in the middle of
the string, it returns none.

Explain in detail about the following functions (a)findall() (b)sub() (c)subn()


(d)search compile() and split()
findall() module is used to search for “all” occurrences that match a given pattern. In
contrast. findall() will iterate over all the lines of the file and will return all non-overlapping
matches of pattern in a single step.
sub() function is used to replace occurrences of a particular sub-string with another sub-
string. This function takes as input the following: The sub-string to replace. The sub-string to
replace with. The actual string.
The re module in python refers to the module Regular Expressions (RE). It specifies a set of
strings or patterns that matches it. ... subn()method is similar to sub() and also returns the new
string along with the no. of replacements.
The Python "re" module provides regular expression support. The re.search() method takes a
regular expression pattern and a string and searches for that pattern within the string. If the
search is successful, search() returns a match object or None otherwise.

compile() method is used if the Python code is in string form or is an AST object, and you want
to change it to a code object. The code object returned by compile() method can later be called
using methods like: exec() and eval() which will execute dynamically generated Python code.

The Python split() method divides a string into a list. Values in the resultant list
are separated based on a separator character. The separator is a whitespace by
default. ... The split() method allows you to break up a string into a list of
substrings, based on the separator you specify.

You might also like