Data Abstraction
• Like other programming languages, python does not have
keyword “abstract” to define abstract function of class. But
have a module which provides the base for defining Abstract
Base Classes(ABC) and that module name is ABC. ABC works
by marking methods of base class as abstract.
from abc import ABC
class Polygon(ABC): T = Triangle()
def noofsides(self): T.noofsides()
pass P = Pentagon
class Triangle(Polygon): P.noofsides()
def noofsides(self): H = Hexagon()
print(“Triangle has 3 sides”) H.noofsides()
class Pentagon(Polygon):
def noofsides(self):
print(“Pentagon has 5 sides”)
class Hexagon(Polygon):
def noofsides(self):
print(“Hexagon has 6 sides”)
Method Overloading
• Method overloading means defining multiple method with same
name but with different parameter list.
• But, python does not support method overloading.
class sample:
def add(self, a, b):
return (a+b)
def add(self, a, b, c):
return (a+b+c)
def add(self, a, b, c, d):
return (a+b+c+d)
s = sample()
s.add(10,20,30,40)
s.add(10,20,30)
s.add(10,20)
class sample:
def add(self, a=0, b=0, c=0, d=0)
return (a+b+c+d)
s = sample()
s.add(10,20,30,40)
s.add(10,20,30)
s.add(10,20)
class sample:
def add(self, *var_args)
sum = 0
for ele in var_arg:
sum = sum + ele
return sum
s = sample()
s.add(10,20,30,40)
s.add(10,20,30)
s.add(10,20)
Method Overriding
• Method overriding needs support of inheritance. Method
overriding means re-defining method of base class into
derived class.
• Re-defined method of derived class hides the accessibility of
original method of base class. Thus the object of derived
class will by default gets access of new method of derived
class only.
class A:
def sample(self):
print(“Hello from class A”)
class B(A):
def sample(self):
print(“Hello from class B”)
b1 = B()
b1.sample()
class A:
def sample(self):
print(“Hello from class A”)
Use of class B(A):
def sample(self):
Super print(“Hello from class B”)
Keywor def show(self):
A.sample(self) OR
d super(B, self).sample()
self.sample()
b1 = B()
b1.show()
File I/O Handling and
Exception Handling
I/O Operations
• Reading Input
print(“Enter your Name:”)
n = input()
print(“Enter your Age:”)
n = int(input())
• Printing to Screen
print(“Hello all”)
print(“How are you?”)
print(“How your study is going so far?”)
Print() Function’s keyword
argument
• sep = : This keyword argument allow user to give a separator
that will appear between multiple values to be printed.
print(10,20,30)
print(27,03,2025,sep=“/”)
• end = : “end” argument use to end any print statement with
specified string. Default value of end argument is “\n”.
print(“Hello all”, end=“!!!!!!!”)
print(“Have a nice day”, end=“ ”)
Hello all!!!!!!!Have a nice day
• file = : By default, print() sends its output to a default stream
called sys.stdout, which is usually equivalent to the console
where we get all our output message.
• flush = : This attribute is related to flush the buffer memory
after print() function gets executed. This attribute requires
Boolean True or False.
print(“Hello”, flush=True)
Output formatting OR Formatted String Output
• format() function uses pair of empty curly braces({ }) as
placeholders and order of values to be printed are specified in
Tuple form as parameter of format() function.
x=5
y = 10
print(“Value of x is {} and y is {}”, format(x , y))
print(“I want {0} and {1}”, format(“Fruits”, “Juice”))
File Handling
• The application of file handling is to store the data on
permanent basis in text files and retrieve it back whenever it
required. File handling is important because every value/data
that we have in our program are actually in temporary memory
blocks which gets erased as the program execution ends.
Opening file in Different Modes
• Built-in function open() is used to open a file.
object = open(“Filename”, “Filemode”)
f = open(“sample.txt”)
f = open(“sample.txt”, “w”)
File modes
• ‘r’ : (default mode) Read mode which is used when the file is only
being read. Places file pointer at the beginning of file.
• ‘w’ : Write mode which is used to edit and write new information to
the file. Truncates and overwrites the file , if the file exist and
creates new file, if the file does not exist.
• ‘a’ : Appending mode, which is used to add new data to the end of
file.
• ‘r+’ : Special read and write mode, which is used to handle both
actions when working with a file.
• rb : opens a file for reading only in a binary format.
• rb+ : opens a file for both reading and writing in a binary format.
• w+ : opens a file for both reading and writing. Truncates and
overwrites the file , if the file exist and creates new file, if the file
does not exist.
• wb+ : opens a file for both reading and writing in binary format.
Truncates and overwrites the file , if the file exist and creates new
file, if the file does not exist.
• ab : Opens a file for appending in binary format. The file opens in
append mode. The file pointer is at the end if file is existing.
• a+ : Opens file for both appending and reading. The file opens in
append mode. The file pointer is at the end of the file if the file
exists. If the file does not exist, it creates a new file for reading and
writing.
• ab+ : Opens file for both appending and reading in binary format.
The file opens in append mode. The file pointer is at the end of the
file if the file exists. If the file does not exist, it creates a new file for
reading and writing.
Exception Handling
try:except Statement
try:
suspicious code
…….
except exception_name:
solution statements
……..
……..
a = [10, 20, 30]
try:
print(“First element : ”, a[0])
print(“First element : ”, a[1])
print(“First element : ”, a[2])
print(“First element : ”, a[3])
except IndexError:
print(“Exception occurs: Invalid index”)
try:
suspicious code
try ……
except exception_name-I:
with solution statements for exception-I
Multipl ……..
e except exception_name-II:
solution statements for exception-II
Except ……..
Blocks except exception_name-n:
solution statements for exception-n
……..
try:
a = 15 / 0
print(“Division is : ”, a)
print(“Value of b is : ”, b)
except ZeroDivisionError:
print(“Cannot divide by zero”)
except NameError:
print(“No such variable name”)
i=0
while i<=1:
try:
a = 15 / i
print(“Division is : ”, a)
print(“Value of b is : ”, b)
except ZeroDivisionError:
print(“Cannot divide by zero”)
except NameError:
print(“No such variable name”)
i = i+1
try:
suspicious code
……
except exception_name-I:
try: solution statements for exception-I
except: ……..
except exception_name-II:
else solution statements for exception-II
Blocks ……..
except exception_name-n:
solution statements for exception-n
……..
else:
statement for else block
import os
try:
os.rename(“testfile.txt”, “testfile1.txt”)
print(“Rename Successful”)
except FileNotFoundError:
print(“No such file found”)
else:
print(“No exception occured”)
import sys
Except Block list1 = [‘a’, 0, 2]
without for ele in list1:
Exception try:
print(“Working on : ”, ele)
Name
r = 1/int(ele)
OR
break
Generic except:
except: print(sys.exc_info()[0], “occured”)
block print(“Try next element”)
print(“Result = ”, r)
Except block with Multiple
Exception
try:
suspicious code
……
except (Exception1, Exception2, …….., ExceptionN ):
…...
else:
statements for else block
import sys
i=0
while i<=1:
try:
a = 15 / i
print(“Division is : ”, a)
print(“Value of b is : ”, b)
except (ZeroDivisionError, NameError):
print(sys.exc_info(), “occured”)
i = i+1
try: finally Blocks
try:
suspicious code
…….
finally:
statements that must execute
try:
f = open(“testfile2.txt”, “w”)
f.write(“……………………”)
print(“Data Written”)
finally:
print(“Task Done”)
try: except: finally Blocks
try:
suspicious code
…..
except exception_name:
solution ststements for specified exception
……
finally:
statements that must execute
……..
a = [10, 20, 30]
try:
print(“First element : ”, a[0])
print(“First element : ”, a[1])
print(“First element : ”, a[2])
print(“First element : ”, a[3])
except IndexError:
print(“Exception occurs: Invalid index”)
finally:
print(“This has to be executed”)
The Raise Statement OR Manually
Raising Exception
import sys
try:
print(“Try block start”)
raise NameError
except NameError:
print(sys.exc_info(), “Occured”)
import sys
class MyError(Exception):
pass
print(“enter a number”)
User num = int(input( ))
Defined try:
Excepti if num < 5:
raise MyError
on mul = 10 * num
print(“Multiplication = ”, mul)
except MyError:
print(sys.exc_info( ), “occured”)