Unit III
BCA 4rth Semester
FILES
File is a named location on disk to store related information.
Data for python program can come from difference sources such
as keyboard, text file, web server, database.
To store data permanently. Stored non-volatile memory.
We can retrieve whenever required.
Ex: Student.txt
Two types of files
Text files : A text file can be a sequence of
lines without any images, tables etc. Ex: text,
json.
Binary files : Files are capable of storing text,
image, video, audio, database files, etc which
contains the data in the form of bits.
File Handling:
Opening files
Reading files
Writing files
Closing files
age =input(“Enter your age”)
print(age)
Above statement age will be lost once application
is closed.
To store data permanently using files
age =input(“Enter your age”)
f=open(“data.txt”,’w’)
f.write(age)
f.close()
statement
automatically closes the file.
syntax:
open(“filename “, mode=‘r’, buffering,
encoding=None, errors=None, newline=None,
closefd=True)
f= open(“filename”, “mode”)
//mode : reading, writing, appending etc.
If mode is not specified , by default, open( ) uses
mode ‘r’ for reading
files in python
collection of data stored on a secondary storage device.
RAM(volatile)
ROM(non-volatile)
file path:
every file identified by its path.
relative path and absolute path.
file path
absolute path : always contains the root to the
complete dictionary.
relative path:start with respect to the current working
directory.
example:
c:\students\undergraduate\BTech_cs.dcox
why we need file?
types of file
what is file handling
creating file
open function
file open()
read() operation
example:
example 1
#example1
f=open("D:/test1.txt",'r')
print(f.read())
-------
output:
hello everyone welcome to python classes
example2
f=open("D:/test.txt","r")
print(f.read(5))
---------
output:
hello
append()-example
#append example
f=open("D:/test.txt","a")
print(f.write("this is a appending operation in file"))
-------------------------
output:
37
example
Counts number of lines and print them.
f=open("D:/test.txt","r")
for x in f:
print (x)
_______
output:
hello everyone, welcome to python programming classes
this is a appending operation in file
access modes:read
r-read: only reading
file must exsits before opening file
file pointer points at the begining of the file.
write mode
w-writing contents into the file
file exists-begining of file and over writtens the data
not exists-new files is created
append()
file exists :pointer points at the end of the content.
new file is created
writing to the file
write()- single line
writelines()-multi line
example:
#reading file and display the contents
f=open("D:/test.txt","r")
print(f.read())
_____________
output:
hello everyone, welcome to python programming classes
example:
f=open("D:/test.txt","w")
print(f.write("this is a appending operation in file"))
--------------
output:
37
contin
f=open("D:/test.txt","r")
for x in f:
print (x)
--------------------
output:
this is a appending operation in file
delete()
first close the opened file.
f.close()
import library os
syntax:
os.remove(“path of file”)
Delete()
#example
f=open("D:/test.txt","r")
for x in f:
print (x)
-----------------------
output:
this is a appending operation in file
conti...
#delete a file
import os
os.remove("D:/test.txt")
various access modes
Mode purpose
r default mode
rb binary format
r+ reading and writing
rb+ reading and writing in binary
format
write()
mode purpose
w only for writing
wb binary format for writing
only
w+ read and write
wb+ binary format for read and
write
append()
mode purpose
a appending
ab binary format
a+ reading and append
ab+ binary format reading
and appending
Classes and objects
Python is an object-oriented programming language
Everything in Python is an object, with its properties
and methods
Class definition
class ClassName: //'Optional class documentation string' class_suite
list the difference Procedural and
Object Oriented Programming
Definition
Security
Method
Division of Program
Movement of Data
Approach
Inheritance
Reusability of Code
oops concepts
class
object
abstraction
encapsultaion
inheritance
polymorphism
blue print which followed by objects.
logical structure with behavior
object:
instance of class
class
attributes
functions
class is logical structure object is physical entity
XYZ
student
roll_no roll
name name
write branch
read read()
write()(
Inheritance
derived class inherits properties from base class
derived class
based class
Polymorphism
implementing same method in different context.
method with same name implementing different way
+
For Instance
Institution:
Faculty Details
Students Details
Non Faculty Details
Other Details
Personal Details : : Name , DOB, Address
Faculty Details : Designation, salary, Attendence
Students Details : Progress, Attendence
Non Faculty Details : Designation, salary, Attendence
class Point:
def init (self,a=0,b=0):
self.x=a
self.y=b
def str (self):
return "(%d,%d)"%(self.x, self.y)
def add (self, p2):
p3=Point()
p3.x=self.x+p2.x
p3.y=self.y+p2.y
return p3
p1=Point(10,20)
p2=Point()
print("P1 is:",p1)
print("P2 is:",p2)
p4=p1+p2
print("Sum is:",p4)
Key points to remember
Create a Class : class MyClass:
Create Object : p1 = MyClass()
The __init__() :
the built-in __init__() function every class
which is always executed when the class is being initiated
We use to assign values to object properties
Object Methods : p1.myfunc()
The self Parameter :
reference to the current instance of the class
Modify Object Properties : p1.age = 40
Delete Object Properties : del p1.age
delete properties on objects by using the del keyword
Delete Objects : del p1
delete objects by using the del keyword
The pass Statement :
Class cannot be empty class Person:
For some reason have a class definition with no content pass
Self Parameter
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
Class
data
functions
student
roll_no
name
write
read
syntax:
object.name=class_name()
Class class Student:
Student_RollNo=10
Student_Name=“John”
data
functions
student
roll_no
name
write
read
functions
syntax:
object.name=class_name()
class Dog:
# A simple class
# attribute
attr1 = "mammal"
attr2 = "dog"
# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)
# Driver code
# Object instantiation
Rodger = Dog()
# Accessing class attributes
# and method through objects
print(Rodger.attr1)
Rodger.fun()
example:
self: implict instance s1=student()
print("roll_no:",s1.roll_no)
#example for simple class print("Name:",s1.name)
class student: print("branch:",s1.branch)
roll_no=77 s1.read()
name="sukshma" -------
branch="cse" roll_no: 77
def read(self): Name: sukshma
print("reading...") branch: cse
reading...
example 2
#example for simple class s1=student()
class student: print("roll_no:",s1.roll_no)
roll_no=77 print("Name:",s1.name)
name="sukshma" print("branch:",s1.branch)
branch="cse" s1.read()
def read(self): ----
rollno=5 output:
print("rollno:",rollno) ???
print("reading...")
example3:
#example for simple class
class student:
roll_no=77
name="sukshma"
branch="cse"
def read(self):
rollno=5
print("rollno:",rollno)
print("instance variable",self.roll_no)
print("reading...")
example 3(conti..)
s1=student()
print("roll_no:",s1.roll_no)
print("Name:",s1.name)
print("branch:",s1.branch)
s1.read()
----------------
output:roll_no: 77
Name: sukshma
branch: cse
rollno: 5
instance variable 77
reading...
example 4:
#example for simple class
class student:
roll_no=77
name="sukshma"
branch="cse"
def read(self):
rollno=5
print("rollno:",rollno)
conti..
print("instance variable",self.roll_no)
print("reading...")
def write(self):
print("writing..")
s1=student()
print("roll_no:",s1.roll_no)
print("Name:",s1.name)
print("branch:",s1.branch)
s1.read()
s1.write()
Object as Arguments:
class Emp:
def __init__(self, name, designation):
self.name=name
self.designation=designation
def print_emp_info(emplist):
print(f’Emp Name is “{emplist.name}”)
print(f”Designation is “{emplist.designation}”)
e1 = Emp(“John”,”Manager”)
print_emp_info(e1)
class Track:
def __init__(self, song, art):
self.song=song
self.art=art
def print_track_info(vocalist):
print(f”Song is “{vocalist.song}”)
print(f”Artist is “{vocalist.art}”)
singer = Track(“Song name”,”Robert”)
print_track_info(singer)
Object as Return Values:
class Circle:
def __init__(self,radius):
self.radius=radius
self.status=""
def check_point_status(self):
if self.radius<30:
self.status="Green"
return self def main():
point = Circle(10)
obj=point.check_point_status()
print(obj.status)
print(isinstance(point,Circle))
print(isinstance(obj,Circle))
print(id(point))
print(id(obj))
if __name__ == "__main__":
main()
Class Attributes & Data Attributes
Encapsulation
Using Private Instance Variables
Inheritance
Accessing Inherited Variables & Methods
Use of super()
Polymorphism
Operator Overloading & Magic Methods
Encapsulation
In Python, encapsulation refers to the bundling of data
(attributes) and methods (functions) that operate on
the data into a single unit
Encapsulation features :
Organized variable and its methods.
Avoids unnecessary modification of variable.
Can use across the modular programming.
Example
class Public:
def __init__(self ):
self.name = "John" # Public attribute
def display_name(self):
print(self.name) # Public method
obj = Public()
obj.display_name() # Accessible
print(obj.name) # Accessible
Polymorphism
Polymorphism means that you can have multiple
classes where each class implements the same
variables or methods in different ways. Polymorphism
takes advantages of inheritance in order to make this
happen.
Example:
def add(a, b):
return a + b
print(add(3, 4)) # Integer addition
print(add("Hello, ", "World!")) # String concatenation
print(add([1, 2], [3, 4])) # List concatenation
Example 2:
class Shape: class Circle(Shape):
def area(self): def __init__(self, radius):
return "Undefined" self.radius = radius
def area(self):
class Rectangle(Shape): return 3.14 * self.radius ** 2
def __init__(self, length, width):
self.length = length shapes = [Rectangle(2, 3),
self.width = width Circle(5)]
def area(self): for shape in shapes:
return self.length * self.width print(f"Area: {shape.area()}")
Operator Overloading
Normally operators like +,-,/,*, works fine with built-in datatypes.
Changing the behavior of an operator so that it works with programmer
defined types(class) is called operator overloading.
Basic operators like +, -, * etc. can be overloaded. To overload an operator, one
needs to write a method within user-defined class. The method should consist
of the code what the programmer is willing to do with the operator.
Let us consider an example to overload + operator to add two Time
objects by defining add method inside the class.
In the above example,
when the statement t3=t1+t2 is used, it invokes a special method add ()
written inside the class. Because, internal meaning of this statement is t3 = t1.
add (t2)
Here, t1 is the object invoking the method. Hence, self inside add () is the
reference (alias) of t1. And, t2 is passed as argument explicitly.
Python provides a special set of methods which have to be used for overloading
operator. Following table shows gives a list of operators and their respective
Python methods for overloading.
Exception Handling
Using try… except… finally
The try block lets you test a block of code for errors.
The except block lets you handle the error.
The else block lets you execute code when there is no
error.
The finally block lets you execute code, regardless of the
result of the try- and except blocks.
When an error occurs, or exception as we call it, Python
will normally stop and generate an error message. These
exceptions can be handled using the try statement:
Raise an exception
As a Python developer you can choose to throw an
exception if a condition occurs.
raise keyword : is used to throw an exception
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
Types of Errors in Python
Syntax errors:
Syntax errors occur when the code violates the rules of the Python
language syntax. These errors are detected by the Python interpreter
when it is parsing the code. (Missing colon, Unmatched
parentheses, Missing quotes, Using a keyword as a variable name,
Missing indentation)
Runtime errors:
Runtime errors occur when the code is syntactically correct but causes
an error when it is executed. These errors can be caused by a variety of
reasons, such as invalid input data, division by zero, or accessing an
undefined variable.
Logical errors:
Logical errors occur when the code is syntactically correct and runs
without causing any errors, but the output is not what you expected.
These errors can be caused by incorrect algorithmic design,
mathematical errors, or a misunderstanding of the problem
requirements.
Examples
if x>0
print(“x is positive”) x=”20”
y=10
********************** z=x/y #TypeError
list1=[10,20,30]
print(list1[4]) ***********************
#IndexError
str1=”Hello, Sam”
*********************** str1.reverse() #AttributeError
a=5
b=10 ************************
average = a+b /2 x=0
print(average) while x<20:
print(x)
*******************
a=20
print(b) # Name Error
Build-in exceptions in python
1) SyntaxError: Raised when there is a syntax error in the Python code
2) Type Error: Raised when an operation or function is applied to an object of
inappropriate type.
3) ValueError: Raised when a built-in operation or function receives an argument
that has the right type but an inappropriate value.
4) IndexError: Raised when trying to access an index that does not exist in a
sequence.
5) KeyError: Raised when trying to access a key that does not exist in a dictionary.
6) NameError: Raised when a variable name is not defined.
7) AttributeError: Raised when trying to access an attribute that does not exist.
8) I/OError: Raised when an input/output operation fails.
9) ZeroDivisionError: Raised when trying to divide a number by zero.
10) MemoryError: Creating a large list or array that exceeds the available memory
11) ImportError: Raised when an import statement fails to find and load the
requested module.
Program to check for ValueError Exception
while True:
try:
number = int(input("Enter a number:"))
print(f"The number you have entered is {number}")
break
except ValueError:
print("Oops! That was no valid number. Try again...")
Output:
Enter a number: wer
Oops! That was no valid number. Try again...
Enter a number:4.0
Oops! That was no valid number. Try again...
Enter a number:
Program to check for ZeroDivisionError
x=int(input("Enter value of x:")) Output:
y=int(input("Enter value of y:")) Enter value of x:4
try: Enter value of y:2
result=x/y Result is 2.0
except ZeroDivisionError: Executing finally clause
print("Division by zero")
else: Enter value of x:2
print(f"Result is {result}") Enter value of y:0
finally: Division by zero
print("Executing finally Executing finally clause
clause")
Encapsulation
In Python, encapsulation refers to the bundling of data
(attributes) and methods (functions) that operate on
the data into a single unit
Encapsulation features :
Organized variable and its methods.
Avoids unnecessary modification of variable.
Can use across the modular programming.
Encapsulation in python
Wrapping of variables and functions under a single unit
data hiding, private
Ex: Class Encap:
Class Encap: __a=10
a=10 def display(self):
def display(self):
print(self.a) print(self.__a)
e=Encap() e=Encap()
e.display() e.display()
print(e.a) print(e.a)
# Invalid cannot access private var
Here, a is a public variable, which can be accessed anywhere in the program
Inorder, to provide data hiding we have to provide private access specifier.
Python doesn’t support private access specifier
Python provides _ _
__a =10 is represented as private variable
__display(self): is represented as private method
Class Encap:
__a=10
def __display(self ):
print(self.__a)
def show(self):
self.__display()
e=Encap()
e.display() # Invalid cannot access private var
print(e.a) # Invalid cannot access private var
e.show()
Class Encap:
__a=10
def setA(self,a):
self.a=a
def getA(self):
return(self.a)
e=Encap()
e.setA(30)
print(e.getA())
Consider I have 2 forms :
Student register form
Student login form
Student register form:
Student name, age, class, branch, year, address, city,
state, phone number, username, password
Student login form:
Student username, password
Class StudentEncap:
class StudentRegisterForm:
__name=“”
__age=0 pass
__username=“” class StudentLoginForm:
__password=“” pass
def setNAME(self,name):
self.__name=name Event: Btn_Save()
def getNAME(self):
return(self.__name)
def setAGE(self,age): objStudent= StudentEncap()
self.__age=age objStudent.setName(txtName.text())
def getAGE(self): objStudent.setAge(txtAge.text())
return(self.__age)
def setUSERNAME(self,username): InsertToDatabase(objStudent)
self.__username=username
********************************************
def getUSERNAME(self):
return(self.__username) Event: Btn_View()
def setPASSWORD(self,password):
self.__password=password objStudent = StudentEncap()
def getPASSWORD(self):
return(self.__password) objStudent=GetDetailsFromDatabase()
txtName.text=s1.getName()
txtAge.text=s1.getAge()
Variables & Methods in python
Instance variables
Static variables // Class level var : Value is same for all
objects
Local variables
class Student:
def __init__(self,rno,name):
self.rno=rno
S1=Student(72,”John”)
self.name=name S1.display()
Student.uni=“MLR” S2.Student(73,”Smith”)
def display(self):
print(self.ro,self.name)
S2.display()
class Student:
uni=“Mlore”
def __init__(self,rno,name): @staticmethod
self.rno=rno def show(): No self paramtere
self.name=name Student.uni=“MLOR”
def display(self): print(Student.uni)
print(self.ro,self.name)
print(Student.uni) S1=Student(72,”John”)
S1.display()
S2.Student(73,”Smith”)
S2.display()
Student.show()
# program to illustrate access modifiers of a class # public member function
def displayPublicMembers(self):
# super class
# accessing public data members
class Super:
print("Public Data Member:", self.var1)
# public data member # protected member function
var1 = None def _displayProtectedMembers(self):
# protected data member # accessing protected data members
print("Protected Data Member:", self._var2)
_var2 = None
# private member function
# private data member def __displayPrivateMembers(self):
__var3 = None
# accessing private data members
# constructor print("Private Data Member:", self.__var3)
def __init__(self, var1, var2, var3):
# public member function
self.var1 = var1
def accessPrivateMembers(self):
self._var2 = var2
self.__var3 = var3 # accessing private member function
self.__displayPrivateMembers()
# derived class # calling public member functions of the class
class Sub(Super): obj.displayPublicMembers()
obj.accessProtectedMembers()
obj.accessPrivateMembers()
# constructor print()
def __init__(self, var1, var2, var3):
Super.__init__(self, var1, var2, var3) # Can also be accessed using
obj._displayProtectedMembers()
obj._Super__displayPrivateMembers()
# public member function
print()
def accessProtectedMembers(self):
self._displayProtectedMembers()# Object can access protected member
print("Object is accessing protected member:", obj._var2)
# creating objects of the derived class print("Object is accessing private member:", obj._Super__var3
obj = Sub("Geeks", 4, "Geeks!")
# object can not access private member, so it will generate
Attribute error
# print(obj.__var3)
Abstraction:
Abstract Class is a collection of abstract methods
Abstract class cannot be instantiated (Cannot create an object)
If there is inherited, only we can implement abstract class
Abstract Method contains only declaration (No definition)
@abstractmethod decorator
from abc import ABC, abstractmethod
Class AbstractDemo1(ABC):
@abstractmethod #decorator
def display(self):
pass
class AbstractDemo2(AbstractDemo1):
def display(Self):
print(“AD@ display”)
Obj=AbsractDemo2()
Obj.display()
from abc import ABC, abstractmethod
Class AbstractDemo1(ABC): #abstract class
@abstractmethod #decorator
def display(self):
pass
@abstractmethod #decorator
def show(self):
pass
class AbstractDemo2(AbstractDemo1): #abstract class Its not having all methods of abstract class
def display(Self):
print(“AD2 display”)
class AbstractDemo3(AbstractDemo1):
def display(Self):
print(“AD3 display”)
def Show(Self):
print(“AD3 display”)
Obj=AbsractDemo3()
Obj.display()
Obj.show()
Polymorphism:
Operator Overloading:
Using same operator for different purpose
We can provide extra meaning to existing operator
without changing its previous meaning
+ add 2 numbers; concatenate 2 strings;
cannot add 2 objects, but can be done using operator
overloading
Method Overloading
Method Overriding
Method Overloading class Number:
class Number: def __init__(Self,a,b,c):
def __init__(Self,a,b,c): Self.a=a
Self.b=b
Self.a=a Self.c=c
Self.b=b #Predefined syntax
Self.c=c def __add__(Self,other):
N1=Number(1,2,3) a=Self.a+other.a
b=Self.b+other.b
N2=Number(4,5,6) c=Self.c+other.c
res=Number(a,b,c)
N1+N2 (5,7,9) return res
def __lt__(Self,other):
o1=self.a+self.b+self.c
o2=other.a+other.b+other.c
if(o1<o2):
return True
else:
N1=Number(1,2,3) return False
N2=Number(4,5,6)
N3=N1+N2 (5,7,9) #N1 is assigned to self, N2 is for
other
print(N3.a,N3.b,N3.c)
Method Overloading
Python doesn’t support Method Overloading we have to
use default arguments.
If we use default arguments in method declaration
class MethodOverloading:
def display(self, a=None, b=None, c=None):
print(a,b,c)
Obj=MethodOverloading()
Obj.display()
Obj.display(10)
Obj.display(10,20)
Obj.display(10,20,30)
Method Overriding
Is implemented only during Inheritance:
class Base:
def display(Self):
print(“Base Class display”)
class Derived(Base): #if it is not satisfied base class methods definition
def display(Self): #Derived class is redefining the base class method
print(“Derived Class display()”)
obj=Derived()
obj.display()