3 Programming-In-python Key Notes j Rexy
3 Programming-In-python Key Notes j Rexy
• Errors are the problems in a program due to which the program will stop
the execution.
Page 1 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
Page 2 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
COMMON EXCEPTIONS:
• ZeroDivisionError: Occurs when a number is divided by zero.
• EOFError: It occurs when the end of the file is reached, and yet
operations are being performed.
Page 3 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
Page 4 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
EXAMPLE:
Page 5 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
RAISE AN EXCEPTION:
• x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
• x = "hello"
Page 6 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print "a/b result is 0"
else:
print c
# Driver program to test above function
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)
OUTPUT:
-5.0
a/b result is 0
Page 7 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
ASSERTION IN PYTHON
• In testing code.
def avg(marks):
assert len(marks) != 0
return sum(marks)/len(marks)
mark1 = []
print("Average of mark1:",avg(mark1))
Page 8 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
Using assert with Error Message
LOGGING AN EXCEPTION
Page 9 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
• Logging module provides a set of functions for simple logging and for
following purposes
DEBUG
INFO
WARNING
ERROR
CRITICAL
Page 10 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
Logging Variable Data:
dynamic information from application in the logs.
import logging
name = 'John‘
logging.error('%s raised an error', name)
ERROR:root:John raised an error
Displaying Date/Time For Python Logging:
• logging.basicConfig(format=’%(asctime)s %(message)s’)
FILE IN PYTHON
• A file is a chunk of logically related data or information
which can be used by computer programs.
• Files on most modern file systems are composed of three
main parts:
• Header: metadata about the contents of the file (file name,
size, type, and so on)
• Data: contents of the file as written by the creator or editor
Page 11 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
• End of file (EOF): special character that indicates the end
of the file
In Python, there is no need for importing external library to read
and write files. Python provides an inbuilt function for creating,
writing, and reading files.
• Python has several functions for creating, reading,
updating, and deleting files.
• There are two types of files in Python
Binary file
Text file
Page 12 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
FILE open() function
The Python file open function returns a file object that contains methods and
attributes to perform various operations for opening files in Python.
filename: gives name of the file that the file object has opened.
mode: attribute of a file object tells you which mode a file was opened in.
Page 13 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
File Modes:
MODES DESCRIPTION
Page 14 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
It opens the file in append mode. The offset goes to the
<a> end of the file. If the file doesn’t exist, then it gets
created.
Syntax:
EG
• f = open("demofile.txt", "r")
Page 15 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
EXAMPLE:
s = "WELCOME\n"
file1.write(s)
file1.writelines(L)
# Closing file
file1.close()
print(file1.read())
file1.close()
Page 16 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
APPEND
# Append-adds at last
file1.close()
print(file1.read())
print()
file1.close()
Page 17 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
EXAMPLE:
# Opening a file
file = open("IIBSC_CS.txt","r")
Counter = 0
Content = file.read()
CoList = Content.split("\n")
for i in CoList:
if i:
Page 18 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
Counter += 1
print(Counter)
EXAMPLE:
file.write(data)
file.close()
h = open('SUM.txt', 'r')
content = h.readlines()
a=0
for i in line:
if i.isdigit() == True:
a += int(i)
Page 19 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
EXAMPLE
file.write(data)
file.close()
d = dict()
line = line.strip()
line = line.upper()
if word in d:
d[word] = d[word] + 1
else:
d[word] = 1
Page 20 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
for key in list(d.keys()):
FILE METHODS:
Page 21 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
read() Returns the file content
Page 22 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
FILE:RANDOM ACCESS
FILE
The tell() method returns the current file position in a file stream.
file.tell()
f = open("demofile.txt", "r")
print(f.readline())
print(f.tell())
seek()
f = open("testFile.txt", "r")
f.seek(9)
print(f.readline())
Using the mmap module allows the user to randomly access locations in a file
by mapping the file into memory. This is an alternative to using normal file
operations.
import mmap
Page 25 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY