Unit 3 SEP Python
Unit 3 SEP Python
A Python Tuple is a group of items that are separated by commas. The indexing, nested objects,
and repetitions of a tuple are somewhat like those of a list, however unlike a list, a tuple is
immutable.
The distinction between the two is that while we can edit the contents of a list, we cannot alter the
elements of a tuple once they have been assigned.
Example
o Tuples are an immutable data type, which means that once they have been generated,
their elements cannot be changed.
o Since tuples are ordered sequences, each element has a specific order that will never
change.
Creating of Tuple:
To create a tuple, all the objects (or "elements") must be enclosed in parenthesis (), each one
separated by a comma. Although it is not necessary to include parentheses, doing so is advised.
A tuple can contain any number of items, including ones with different data types (dictionary,
string, float, list, etc.).
Code:
Output:
Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))
Tuples can be constructed without using parentheses. This is known as triple packing.
Operations on Tuples
Tuples respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new tuple, not a string.
In fact, tuples respond to all of the general sequence operations we used on strings in the prior
chapter −
1 cmp(tuple1, tuple2)
Compares elements of both tuples.
2 len(tuple)
Gives the total length of the tuple.
3 max(tuple)
Returns item from the tuple with max value.
4 min(tuple)
Returns item from the tuple with min value.
5 tuple(seq)
Converts a list into tuple.
Tuple Methods
Python has two built-in methods that you can use on tuples.
Method Description
index() Searches the tuple for a specified value and returns the position of where it was
found
Tuple1 = (0, 1, 2, 3, 2, 3, 1, 3, 2)
res = [Link](3)
res = [Link]('python')
Output:
Count of 3 in Tuple1 is: 3
Count of Python in Tuple2 is: 3
Index() Method
The Index() method returns the first occurrence of the given element from the tuple.
Syntax:
Parameters:
start (Optional): The starting index from where the searching is started
end (Optional): The ending index till where the searching is done
Note: This method raises a ValueError if the element is not found in the tuple.
Example 1: Using Tuple Index() Method
# Creating tuples
Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)
res = [Link](3)
# index
res = [Link](3, 4)
Output:
First occurrence of 3 is 3
First occurrence of 3 after 4th index is: 5
SET
A Set in Python programming is an unordered collection data type that is iterable, mutable and
has no duplicate elements.
The major advantage of using a set, as opposed to a list, is that it has a highly optimized method
for checking whether a specific element is contained in the set. This is based on a data structure
known as a hash table. Since sets are unordered, we cannot access items using indexes as we do
in lists.
This is based on a data structure known as a hash table. If Multiple values are present at the
same index position, then the value is appended to that index position, to form a Linked List.
In, Python Sets are implemented using a dictionary with dummy variables, where key beings the
members set with greater optimizations to the time complexity.
Set Implementation:
A set can have any number of items and they may be of different types (integer, float,
tuple, string etc.). But a set cannot have mutable elements like lists, sets or dictionaries as
its elements.
Let's see an example,
# create a set of integer type
student_id = {112, 114, 116, 118, 115}
print('Student ID:', student_id)
# create a set of string type
vowel_letters = {'a', 'e', 'i', 'o', 'u'} print('Vowel
Letters:', vowel_letters)
# create a set of mixed data types mixed_set =
{'Hello', 101, -2, 'Bye'}
print('Set of mixed data types:', mixed_set)
Operations On Sets
Python Set provides different built-in methods to perform mathematical set operations like
union, intersection, subtraction, and symmetric difference.
The union of two sets A and B include all the elements of set A and B.
# second set B
= {0, 2, 4}
Output
Set Intersection
The intersection of two sets A and B include the common elements between set A and B.
# second set B
= {1, 2, 3}
Output
Intersection using &: {1, 3}
Intersection using intersection(): {1, 3}
The difference between two sets A and B include elements of set A that are not present on set B.
# second set B
= {1, 2, 6}
Output
The symmetric difference between two sets A and B includes all elements of A and B without
the common elements.
Set Symmetric Difference in Python
In Python, we use the ^ operator or the symmetric_difference() method to perform symmetric
difference between two sets. For example,
# first set A =
{2, 3, 5}
# second set B
= {1, 2, 6}
# using symmetric_difference()
print('using symmetric_difference():', A.symmetric_difference(B))
Run Code
Output
using ^: {1, 3, 5, 6}
using symmetric_difference(): {1, 3, 5, 6}
Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are
commonly used with sets to perform different tasks.
Function Description
all() Returns True if all elements of the set are true (or if the set is empty).
Returns True if any element of the set is true. If the set is empty, returns
any()
False.
Returns an enumerate object. It contains the index and value for all the
enumerate()
items of the set as a pair.
Returns a new sorted list from elements in the set(does not sort the set
sorted()
itself).
Set Methods
There are many set methods, some of which we have already used above. Here is a list of all the
methods that are available with the set objects:
Method Description
update() Updates the set with the union of itself and others
File Handling
The file handling plays an important role when the data needs to be stored permanently into the
file. A file is a named location on disk to store related information. We can access the stored
information (non-volatile) after the program termination.
In Python, files are treated in two modes as text or binary. The file may be in the text or binary
format, and each line of a file is ended with the special character.
o Open a file
o Read or write - Performing operation
o Close the file
1. Text File
Text file store the data in the form of characters.
Text file are used to store characters or strings.
Usually we can use text files to store character data
eg: [Link]
Ⅳ SEM BCA PYTHON
2. Binary File
Binary file store entire data in the form of bytes.
Binary file can be used to store text, image, audio and video.
Usually we can use binary files to store binary data like images,video files, audio files etc
Operations on Files-
1. Open
Before performing any operation on the file like reading or writing, first, we have to open that
file. For this, we should use Python’s inbuilt function open() but at the time of opening, we have
to specify the mode, which represents the purpose of the opening file.
f = open(filename, mode)
2. Read
There is more than one way to read a file in Python
Eample 1: The open command will open the file in the read mode and the for loop will print each
line present in the file.
Output:
Hello world
GeeksforGeeks
123 456
Example 2: In this example, we will extract a string that contains all characters in the file then
we can use [Link]().
print ([Link]())
Output:
Hello world
GeeksforGeeks
123 456
Example 3: In this example, we will see how we can read a file using the with statement.
Python3
data = [Link]()
print(data)
Output:
Hello world
GeeksforGeeks
123 456
3. Write
To write some text to a file, we need to open the file using the open method with one of the
following access modes.
w: It will overwrite the file if any file exists. The file pointer is at the beginning of the file.
a: It will append the existing file. The file pointer is at the end of the file. It creates a new file if
no file exists.
Example:
# open the [Link] in append mode. Create a new file if no such file exists.
fileptr = open("[Link]", "w")
# appending the content to the file
[Link]('''''Python is the modern day language. It makes things so simple.
It is the fastest-growing programing language''')
# closing the opened the file
[Link]()
Output:
[Link]
Python is the modern-day language. It makes things so simple. It is the faste fastest-
growing programing language
4. Close Files
Once all the operations are done on the file, we must close it through our Python script using
the close() method. Any unwritten information gets destroyed once the close() method is called on
a file object.
We can perform any operation on the file externally using the file system which is the currently
opened in Python; hence it is good practice to close the file once all the operations are done.
The syntax to use the close() method is given below.
Syntax
1. [Link]()
An absolute path specifies the location of the file relative to the root directory or it contains the
complete location of the file or directory, whereas relative paths are related to the current
working directory.
[Link]() is used to get the current path. The pathlib module provides us with the
function cwd() by which we can fetch the current working directory.
Code:
Output:
C:\Users\Dell
Using [Link]():
The function [Link]() returns the current working directory. Here getcwd stands for Get
Current Working Directory.
Code:
import os
cwd = [Link]() # This fn will return the Current Working Directory
print("Current working directory:", cwd)
Output:
Using [Link]().absolute():
[Link]().absolute() is used to get the current path. The pathlib module provides us with
the function absolute() by which we can fetch the path of the current working directory.
Code:
import pathlib
print([Link]().absolute())
Output:
C:\Users\Dell
Using [Link]():
The OS module provides numerous functions. [Link]() returns the name of the
currently running Python file. And if we want to get the whole path of the directory in which our
Python file is residing, then we can use [Link]().
Code:
import os
print('File name:', [Link]( file ))
print('Directory Name: ', [Link]( file ))
Output:
Using [Link]():
import os
print('absPath: ', [Link]( file ))
print('absDirname: ', [Link]([Link]( file )))
Output:
absPath: c:\Users\Dell\OneDrive\Desktop\Lang\[Link]
absDirname: c:\Users\Dell\OneDrive\Desktop\Lang
Format Operator:
The argument of write has to be a string, so if we want to put other values in a file, we have to
convert them to strings. The easiest way to do that is with str:
x = 52
fout = open('[Link]', 'w')
[Link](str(x))
An alternative is to use the format operator, %. When applied to integers, % is the modulus
operator. But when the first operand is a string, % is the format operator.
The first operand is the format string, which contains one or more format sequences, which
specify how the second operand is formatted. The result is a string.
For example, the format sequence '%d' means that the second operand should be formatted as an
integer (d stands for “decimal”):
>>> camels = 42
>>> '%d' % camels
'42'
The result is the string '42', which is not to be confused with the integer value 42.
A format sequence can appear anywhere in the string, so you can embed a value in a sentence:
>>> camels = 42
>>> 'I have spotted %d camels.' % camels
'I have spotted 42 camels.'
If there is more than one format sequence in the string, the second argument has to be a tuple.
Each format sequence is matched with an element of the tuple, in order.
The following example uses '%d' to format an integer, '%g' to format a floating-point number
(don’t ask why), and '%s' to format a string:
Suppose a class is a prototype of a building. A building contains all the details about the floor, rooms, doors,
windows, etc. we can make as many buildings as we want, based on these details. Hence, the building can
be seen as a class, and we can create as many objects of this class.
Syntax
class ClassName:
#statement_suite
We must notice that each class is associated with a documentation string which can be accessed by
using <class-name>. doc . A class contains a statement suite including fields, constructor, function, etc.
class Person:
def init (self, name, age):
# This is the constructor method that is called when creating a new Person object
# It takes two parameters, name and age, and initializes them as attributes of the object
[Link] = name
[Link] = age
def printMe(self):
# This is a method of the Person class that prints a message
print("Hello, my name is " + [Link])
Name and age are the two properties of the Person class. Additionally, it has a function called printMe that
prints a msg.
Objects in Python:
An object is a particular instance of a class with unique characteristics and functions. After a class has been
established, you may make objects based on it. By using the class constructor, you may create an object of
a class in Python. The object's attributes are initialised in the constructor, which is a special procedure with
the name init .
Syntax:
# Declare an object of a class
object_name = Class_Name(arguments)
class Person:
def init (self, name, age):
[Link] = name
[Link] = age
def printMe(self):
print("Hello, my name is " + [Link])
# Create a new instance of the Person class and assign it to the variable person1
person1 = Person("Ayan", 25)
[Link]()
The self-parameter
The self-parameter refers to the current instance of the class and accesses the class variables. We can use
anything instead of self, but it must be the first parameter of any function which belongs to the class.
_ _init_ _ method
In order to make an instance of a class in Python, a specific function called init is called. Although it is used
to set the object's attributes, it is often referred to as a constructor.
The self-argument is the only one required by the init method. This argument refers to the newly generated
instance of the class. To initialise the values of each attribute associated with the objects, you can declare
extra arguments in the init method.
class Person:
count = 0 # This is a class variable
def init (self, name, age):
[Link] = name # This is an instance variable
[Link] = age
[Link] += 1 # Accessing the class variable using the name of the class
person1 = Person("Ayan", 25)
person2 = Person("Bobby", 30)
print([Link])
Output: 2
Whereas, instance variables are specific to each instance of a class. They are specified using the self-
argument in the init method. Here's an illustration:
class Person:
def init (self, name, age):
[Link] = name # This is an instance variable
[Link] = age
person1 = Person("Ayan", 25)
person2 = Person("Bobby", 30)
print([Link])
print([Link])
Output: Ayan
30
Class variables are created separately from any class methods and are shared by all class copies. Every
instance of a class has its own instance variables, which are specified in the init method utilising the self-
argument.
Python Constructor
A constructor is a special type of method (function) which is used to initialize the instance members of the
class. In C++ or Java, the constructor has the same name as its class, but it treats constructor differently in
Python. It is used to create an object.
Output:
ID: 101
Name: John
ID: 102
Name: David
Counting the number of objects of a class
The constructor is called automatically when we create the object of the class. Consider the following
example.
class Student:
count = 0
def init (self):
[Link] = [Link] + 1
s1=Student()
s2=Student()
s3=Student()
print("The number of students:",[Link])
Output:
The number of students: 3
SN Function Description
2 setattr(obj, name,value) It is used to set a particular value to the specific attribute of an object.
4 hasattr(obj, name) It returns true if the object contains some specific attribute.
getattr(obj,name,default)
class Student:
def__init__(self,name)
[Link]=name
s=Student(“Ram”)
print(getattr(s,”name”))
setattr(obj,name,value)
class Student:
def__init__(self,name)
[Link]=name
s=Student(“Ram”)
setattr(s,”name”,”shyam”)
print([Link])
delattr(obj,name)
s=Student(“Ram”)
delattr(s,”name”)
hasattr(obj,name)
s=Student(“Ram”)
print(hasattr(s,”name”)
print(hasattr(s,”age”) output: True
False
class Student:
def init (self, name, roll):
[Link] = name
[Link] = roll
# creating list
list = []
# appending instances to list
[Link](Student('Akash', 2))
[Link](Student('Deependra', 40))
[Link](Student('Reena', 44))
[Link](Student('Veena', 67))
print("")
# Accessing individual elements
print(list[3].name)
print(list[2].name)
print(list[1].name)
print(list[0].name)
Output
Akash 2
Deependra 40
Reena 44
Veena 67
Veena
Reena
Deependra
Akash
Python program to pass objects as arguments and return objects from function
Python allows its programmers to pass objects to method. And also return objects from a method. Here is a
program to illustrate this,
class TwoNum:
def GetNum(self):
self. x = int(input("Enter value of x : "))
self. y = int(input("Enter value of y : "))
def PutNum(self):
print("value of x = ", self. x,"value of y = ", self. y, )
def Add(self,T):
R=TwoNum()
R. x=self. x+T. x
R. y=self. y+T. y
return R
obj1 = TwoNum()
obj2 = TwoNum()
print("Enter values of object 1 ")
[Link]()
print("Enter values of object 2 ")
[Link]()
obj3 = [Link](obj2)
print("Values of object 1 ")
[Link]()
print("Values of object 2 ")
[Link]()
print("Values of object 3 (sum object) ")
[Link]()
Output:
Enter values of object 1
Enter value of x : 43
Enter value of y : 65
Enter values of object 2
Enter value of x : 34
Enter value of y : 65
Values of object 1
value of x = 43 value of y = 65
Values of object 2
value of x = 34 value of y = 65
Values of object 3 (sum object)
value of x = 77 value of y = 130
Python Inheritance
Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides code reusability to
the program because we can use an existing class to create a new class instead of creating it from scratch.
In inheritance, the child class acquires the properties and can access all the data members and functions
defined in the parent class. A child class can also provide its specific implementation to the functions of the
parent class. In python, a derived class can inherit base class by just mentioning the base in the bracket after
the derived class name. Consider the following syntax to inherit a base class into the derived class.
Syntax
class derived-class(base class):
<class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the following
syntax.
class derive-class(<base class 1>, <base class 2>,.......<base class n>):
<class - suite>
Single Inheritance
A child class inherits from only one parent class
Syntax:
class base:
<class suite>
class derived:
<class suite>
Example
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
[Link]()
[Link]()
Output:
dog barking
Animal Speaking
Python Multi-Level inheritance
Multi-Level inheritance is possible in python like other object-oriented languages. Multi-level inheritance is
achived when a derived class inherits another derived class. There is no limit on the number of levels up to
which, the multi-level inheritance is achived in python.
Syntax
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
.
.
Example
class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
[Link]()
[Link]()
[Link]()
Output:
dog barking
Animal Speaking
Eating bread...
Syntax
class Base1:
<class-suite>
class Base2:
<class-suite>
.
.
.
class BaseN:
<class-suite>
Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print([Link](10,20))
print([Link](10,20))
print([Link](10,20))
Output:
30
200
0.5
Multipath Inheritance
When a class is derived from two or more classes which are derived from the same base class then such type
of inheritance is called multipath inheritance.
Syntax
class Base A:
def show(self):
print(“class A”)
class B(A):
def display(self):
print(“class B”)
class C(A):
def print_msg(self):
print(“class C”)
class D(B,C):
def output(self):
print(class D”)
obj=D()
[Link]()
[Link]()
obj.print_msg()
[Link]()
output
class A
class B
class C
class D
Here class 'D' derived from classes 'B' and 'C', which are derived from same base class 'A'.
Encapsulation
Encapsulation is one of the key concepts of object-oriented languages like Python, Java, etc. Encapsulation
is used to restrict access to methods and variables. In encapsulation, code and data are wrapped together
within a single unit from being modified by accident.
Encapsulation is a mechanism of wrapping the data (variables) and code acting on the data (methods)
together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can
be accessed only through the methods of their current class.
Encapsulation Example
Let’s say we have a company selling courses to students, engineers and professionals. The different sections
of this company include, operations, finance, accounts, sales, etc. Now, if an employee from the accounts
section needs the records of sales in 2022, then he/ she cannot directly access it.
To access, the employee of the account sections needs to get permission from the sales section team member.
Therefore, the sales data is hidden from other departments, In the same way, the financials of the company
is accessible to only the finance data and is hidden from other sections. The accounts, sales, finance,
operations, marketing, etc. data is hidden from other sections.
Access Modifiers in Python : Public, Private and Protected
Various object-oriented languages like C++, Java, Python control access modifications which are used to
restrict access to the variables and methods of the class. Most programming languages has three forms of
access modifiers, which are Public, Protected and Private in a class.
Python uses ‘_’ symbol to determine the access control for a specific data member or a member function of
a class. Access specifiers in Python have an important role to play in securing data from unauthorized access
and in preventing it from being exploited.
Below is a program to illustrate the use of all the above three access modifiers (public,
protected, and private) of a class in Python:
class Super:
# public data member
var1 = None
# protected data member
_var2 = None
# private data member
var3 = None
# constructor
def init (self, var1, var2, var3):
self.var1 = var1
self._var2 = var2
self ___ ar3 = var3
# derived class
class Sub(Super):
# constructor
def init (self, var1, var2, var3):
Super. init (self, var1, var2, var3)
# public member function
def accessProtectedMembers(self):
# accessing protected member functions of super class
self._displayProtectedMembers()
# object can not access private member, so it will generate Attribute error
#print(obj. var3)
Output:
Public Data Member: College
Protected Data Member: 4
Private Data Member: College!
Polymorphism in Python
Polymorphism refers to having multiple forms. Polymorphism is a programming term that refers to the use
of the same function name, but with different signatures, for multiple types.
class xyz():
def websites(self):
print("Google is a website out of many availabe on net.")
def topic(self):
print("Python is out of many topics about technology.")
def type(self):
print("Google is an developed website.")
class PQR():
def websites(self):
print("Pinkvilla is a website out of many availabe on net. .")
def topic(self):
print("Celebrities is out of many topics.")
def type(self):
print("pinkvilla is a developing website.")
obj_jtp = xyz()
obj_pvl = PQR()
for domain in (obj_jtp, obj_pvl):
[Link]()
[Link]()
[Link]()
Output:
Google is a website out of many availabe on net.
Python is out of many topics about technology.
Google is an developed website.
Pinkvilla is a website out of many availabe on net.
Celebrities is out of many topics.
pinkvilla is a developing website.
The user define methods or functions in the class and the operator works according to that behaviour defined
in the functions. When the user uses the "+" operator, it will change the code of a magic function, and the
user has an extra meaning of the "+" operator.
| or (self, other)
Comparison Operators:
== EQ (SELF, OTHER)
!= NE (SELF, OTHER)
Assignment Operators:
Unary Operator: