Python Asmt1
Python Asmt1
4.How does try-except statement work? Demonstrate with an example python code
A.
The python try-except statement helps handle exceptions, the try-except statement runs the
code under the ‘try’ statement . If this code doesn’t execute successfully, the program will
stop at the line that caused the error and the “except” code will run.
Ex: try:
print(variable)
except:
Print(‘error returned’)
5.Explain the following file built-in functions and method with clear syntax, description and
illustration: a) open( ) b) file( ) c) seek( ) d) tell( ) e)read( )
A.
a). open(): This built-in function returns a file object on a successful opening of the file.
Syntax :- file_object = open(file_name,access_mode=’r’,buffering=1)
The file_name is a string containing the name of the file to open.
The access_mode is not given , it defaults automatically to ‘r’.
The buffering is used to indicate the type of buffering that should be performed when
accessing the file.
b). file(): This built-in function came into later versions of python and can be used as a
substitute for the open() function as the functionality of both the functions are the same.
c). seek(): This function moves the file pointer to different positions within the file.
Syntax :- file.seek(off,whence)
off bytes offset from
whence beginning , current location or end of file
d). tell(): It is a complimentary method to seek()
Syntax :- file.tell()
e). read(): It is a file input method which is used to read bytes directly into a string, reading
at most number of times indicated.
Syntax :- file.read(number of times)
X X X