Python Unit 2
Python Unit 2
Lecture Notes
Unit II
Prepared By:
Dr. M. Shanmugam
Mr. D. Rajesh.
Mrs. S. Deeba
Mrs. M. Hemalatha
Ms. A. Amala Margret
Verified By Approved By
---------------------------------------------------------------------------------------------------------------------
2 marks Questions and Answers
3. How can you check if a string contains only numeric characters in Python?
isdigit() method is used to check if a string contains only numeric characters. This
method returns True if all characters in the string are digits, otherwise False.
8. Write a Python program to iterate over a dictionary and print keys and their
corresponding values.
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in dictionary.items():
print(key, ":", value)
13. Write a Python program to create a class named Car with attributes make and model.
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
# Example usage
car1 = Car("Toyota", "Corolla")
print(car1.make, car1.model)
# Output: Toyota Corolla
18. Take dictionary and delete an element and delete the dictionary?
#program
my_dictionary ={“apple”: “a fruit that grows on tree”, “banana”: “a long curved
fruit that grows in clusters.”}
del my_dictionary[“banana”]
Print(“dictionary after deleting banana”,my_dictionary)
del my_dictionary #If you print the delted dictionary it will return a name error.
19. Write a program in python to get 5 elements from using and add into a dictionary ?
my_dictionay={}
for _in range(5):
key=input(“Enter a key:”)
Value=input(“Enter a value”)
my_dictionary[key]=value
Print(“dictionary:”,my_dictionary)
In order to create a custom exception, we need to extend the Exception class that belongs
to java. lang package.To create your own exception in Python, you can define a new class that
inherits from the built-in Exception class.
Syntax:
class CustomError(Exception)
...
pass
try:
...
except CustomError:
...
LIST TUPLES
• Lists are mutable. • Tuples are immutable.
• List are enclosed within square • Tuples are enclosed within parenthesis ().
brackets [ ]. Lists • The implication of iterations is
• The implication of iterations is comparatively Faster.
Time-consuming. • A tuple data type is appropriate for
• The list is better for performing accessing the elements.
operations, such as insertion • Tuple consumes less memory.
and deletion. • Tuple does not have many build-in
• List consumes more memory. methods.
• List have several build-in • Example for Tuples:(10,30,6)
methods.
• Example for List: [10,30,50]
31. How will you find a max and min element from a tuple?
We can find the maximum and minimum elements from a tuple using the max() and
min() functions in Python.
PROGRAM
my_tuple= (3, 7, 1, 9, 5)
max_element = max(my_tuple)
min_element = min(my_tuple)
print("Maximum element:", max_element)
print("Minimum element:", min_element)
Output:
Maximum element: 9
Minimum element: 1
Eg:
index() find()
• Returns an exception if substring • Returns -1 if substring isn’t
isn’t found found.
• It shouldn’t be used if you are not • It is the correct function to use
sure about the presence of the when you are not sure about
substring. the presence of a substring.
• This can be applied to strings, lists • This can only be applied to
and tuples. strings.
• It cannot be used with conditional • It can be used with conditional
statement statement to execute a
statement if a substring is
found as well if it is not.
44. What is a constructor? Write about the feature of the constructor in python.
A constructor is a special method in object-oriented programming that is
automatically called when an object of a class is created.
• Automatic Invocation: The init constructor method in Python is
automatically called when an object of the class is created, eliminating the
need for explicit invocation.
• Attribute Initialization: Python's constructor allows for the initialization of
object attributes, providing a convenient means to set initial values for object
properties during object creation.
46. Differentiate getter and setter methods with ordinary member methods.
getter() setter()
Getters are the methods that are used in The setter is a method that is used to set
Object-Oriented Programming (OOPS) the property's value
to access a class's private attributes.
The setattr() function in Python It is very useful in object-oriented
corresponds to the getattr() function in programming to set the value of private
Python. It alters an object's attributes in a class.
attribute values.
S. No Add() Update()
Use add() function to add a single use update() function to add multiple
1 element. elements to the set.
Example:
5 MARKS
1. Program to get the values for dictionary and print the elements one by one.
#program
my_dictionary={ ‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’:4, }
for value in my_dict.values():
print(value)
Output:
1
2
3
4
2. Program to print the word count using dictionary?
Sentence=”my name is Praveen i am a good boy.”
Words=sentence.split()
Word_count={}
For word in words:
Word_count[word]=word_count.get(word,0)+1
For word_count in word_count.items():
print(f“ ‘{word}’ occurs {count} time(s).”)
The Else and Finally block are optional but it is considered a good programming practice to
include them.
Type of error messages
There are two types of error that can occur:
• Syntax Error/Parsing Error: When the Python parser is unable to understand a line of
code.
• Exception: When the error is detected during execution, e.g.,ZeroDivisionError.
Some of the common Exception Errors are:
• IOError: if the file can’t be opened
• KeyboardInterrupt: when an unrequired key is pressed by the user
• ValueError: when the built-in function receives a wrong argument
• EOFError: if End-Of-File is hit without reading any data
• ImportError: if it is unable to find the module
The finally block in Python's exception handling mechanism is important for several reasons:
1. Resource Management: It ensures that critical resources, such as file handles, database
connections, or network connections, are properly released and closed, preventing
resource leaks and improving system stability.
2. Cleanup Actions: It allows you to define cleanup actions that should always be
performed, such as logging, resetting variables, or releasing locks, regardless of whether
an exception occurred or not. This promotes clean and maintainable code.
3. Error Handling: It complements the try and except blocks by providing a way to
execute cleanup code even if an exception occurs, ensuring that your program can
gracefully handle errors and recover from exceptional situations.
4. Predictable Behavior: The finally block guarantees that certain actions are always
executed, improving the predictability and reliability of your code, especially in complex
applications where error handling and resource management are crucial.
Example Program1:
def divide(a, b):
try:
result = a / b
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Division by zero.")
finally:
print("Cleanup: Resetting variables.")
a=0
b=0
divide(10, 2)
divide(10, 0)
Example Program 2:
try:
file = open("example.txt", "w")
file.write("Hello, world!")
except FileNotFoundError:
print("File not found.")
finally:
file.close()
print("File closed successfully.")
6. Write a program in python to write content into a file and reading the same from the file.
If the file is not present raise your own exception 'FNF' exception and handle?
Algorithm:
1. Start by defining a function write_and_read_file that takes a file name and content as
parameters.
2. Attempt to open the file in write mode ("w").
• If successful, write the content to the file and close it.
• If the file is not found (FileNotFoundError), raise a custom "FNF" exception.
3. Define a function main to call write_and_read_file with a file name and content.
4. Call the main function to execute the program.
Program:
# Define a custom exception for File Not Found
class FNFException(Exception):
pass
# Function to write content to a file and read it
def write_and_read_file(file_name, content):
try:
# Attempt to open the file in write mode
with open(file_name, 'w') as file:
file.write(content)
print("Content written to the file successfully.")
except FileNotFoundError:
# Raise custom "FNF" exception if file is not found
raise FNFException("File Not Found.")
except FileNotFoundError:
print("File not found while reading.")
try:
write_and_read_file(file_name, content)
except FNFException as e:
print(f"Custom exception caught: {e}")
EXAMPLE PROGRAM
my_tuple = (5, 3, 1, 4, 2)
sorted_tuple = sorted(my_tuple)
print(sorted_tuple)
Output: [1, 2, 3, 4, 5]
TUPLE()
tuple(): Converts an iterable (such as a list) into a tuple.
EXAMPLE PROGRAM
my_list = [1, 2, 3, 4, 5]
converted_tuple = tuple(my_list)
print(converted_tuple)
Output: (1, 2, 3, 4, 5)
MIN()
min(): Returns the smallest element in the tuple.
EXAMPLE PROGRAM
my_tuple = (10, 5, 20, 8, 15)
print(min(my_tuple))
Output: 5
MAX()
max(): Returns the largest element in the tuple.
EXAMPLE PROGRAM
my_tuple = (10, 5, 20, 8, 15)
print(max(my_tuple))
Output: 20
class Dog:
sound = "bark"
Objects:
➢ An Object is an instance of a Class.
➢ Python Objects are basically an encapsulation of data variables and methods acting on
that data into a single entity.
➢ Syntax: Object Definition
obj = ClassName()
print(obj.atrr)
➢ Instance defining represent memory allocation necessary for storing the actual data of
variables.
➢ Each time when you create an object of class a copy of each data variable defined in
that class is created.
➢ An object consists of:
o State: It is represented by the attributes of an object. It also reflects the properties
of an object.
o Behavior: It is represented by the methods of an object. It also reflects the
response of an object to other objects.
o Identity: It gives a unique name to an object and enables one object to interact
with other objects.
# Python3 program to
# demonstrate instantiating
# a class
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()
EXAMPLE:
a=7
b=2
# addition
print ('Sum: ', a + b)
# subtraction
print ('Subtraction: ', a - b)
# multiplication
print ('Multiplication: ', a * b)
# division
print ('Division: ', a / b)
# floor division
print ('Floor Division: ', a // b)
# modulo
print ('Modulo: ', a % b)
# a to the power b
print ('Power: ', a ** b)
OUTPUT:
Sum: 9
Subtraction: 5
Multiplication: 14
Division: 3.5
Floor Division: 3
Modulo: 1
Power: 49
OUTPUT:100
➢ We may define many methods of the same name and different arguments, but we can
only use the latest defined method. Calling the other method will produce an error.
➢ Like here calling product(4,5) will produce an error as the latest defined product method
takes three arguments.
To simulate method overloading, we can use a workaround by defining default value to
method arguments as None, so that it can be used with one, two or three arguments.
EXAMPLE:
class example:
def add(self, a = None, b = None, c = None):
x=0
if a !=None and b != None and c != None:
x = a+b+c
elifa !=None and b != None and c == None:
x = a+b
return x
obj = example()
print (obj.add(10,20,30))
print (obj.add(10,20))
OUTPUT:
60
30
By Using Multiple Dispatch Decorator :
➢ In Backend, Dispatcher creates an object which stores different implementation and
on runtime, it selects the appropriate method as the type and number of parameters
passed.frommultipledispatch import dispatch
EXAMPLE:
# passing one parameter
@dispatch(int, int)
def product(first, second):
result = first*second
print(result)
# you can also pass data type of any value as per requirement
@dispatch(float, float, float)
def product(first, second, third):
result = first * second * third
print(result)
OUTPUT:
6
12
17.985999999999997
EXAMPLE:
# Python program to demonstrate single inheritance
# Base class
class Parent:
def func1(self):
print("This function is in parent class.")
# Derived class
class Child(Parent):
def func2(self):
print("This function is in child class.")
# Driver's code
object = Child()
object.func1()
object.func2()
OUTPUT:
This function is in parent class.
This function is in child class.
Multiple Inheritance:
➢ When a class can be derived from more than one base class this type of inheritance is
called multiple inheritances.
➢ In multiple inheritances, all the features of the base classes are inherited into the
derived class.
➢ The syntax of multiple inheritance in Python is as follows:
class BaseClass1:
{Body}
class BaseClass2:
{Body}
class DerivedClass(BaseClass1,BaseClass2):
{Body}
EXAMPLE:
# Python program to demonstrate multiple inheritance
# Base class1
class Mother:
mothername = ""
def mother(self):
print(self.mothername)
# Base class2
class Father:
fathername = ""
def father(self):
print(self.fathername)
# Derived class
class Son(Mother, Father):
def parents(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)
# Driver's code
s1 = Son()
s1.fathername = "RAM"
s1.mothername = "SITA"
s1.parents()
OUTPUT:
Father : RAM
Mother : SITA
Multilevel Inheritance:
➢ In multilevel inheritance, features of the base class and the derived class are further
inherited into the new derived class. This is similar to a relationship representing a
child and a grandfather.
➢ The syntax of multilevel inheritance in Python is as follows:
class BaseClass1:
{Body}
class DerivedClass1(BaseClass1):
{Body}
class DerivedClass2(DerivedClass1):
{Body}
EXAMPLE:
# Python program to demonstrate multilevel inheritance
# Base class
class Grandfather:
def __init__(self, grandfathername):
self.grandfathername = grandfathername
# Intermediate class
class Father(Grandfather):
def __init__(self, fathername, grandfathername):
self.fathername = fathername
# Derived class
class Son(Father):
def __init__(self, sonname, fathername, grandfathername):
self.sonname = sonname
def print_name(self):
print('Grandfather name :', self.grandfathername)
print("Father name :", self.fathername)
print("Son name :", self.sonname)
# Driver code
s1 = Son('Prince', 'Rampal', 'Lal mani')
print(s1.grandfathername)
s1.print_name()
OUTPUT:
Lal manis
Grandfather name : Lal mani
Father name : Rampal
Son name : Prince
Hierarchical Inheritance:
➢ When more than one derived class are created from a single base this type of
inheritance is called hierarchical inheritance. In this program, we have a parent
(base) class and two child (derived) classes.
➢ The syntax of hierarchical inheritance in Python is as follows:
class BaseClass1:
{Body}
class DerivedClass1(BaseClass1):
{Body}
class DerivedClass2(BaseClass1):
{Body}
class DerivedClass3(BaseClass1):
{Body}
EXAMPLE:
# Python program to demonstrate Hierarchical inheritance
# Base class
class Parent:
def func1(self):
print("This function is in parent class.")
# Derived class1
class Child1(Parent):
def func2(self):
print("This function is in child 1.")
# Derived class2
class Child2(Parent):
def func3(self):
print("This function is in child 2.")
# Driver's code
object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()
OUTPUT:
This function is in parent class.
This function is in child 1.
This function is in parent class.
This function is in child 2.
Hybrid Inheritance:
➢ Inheritance consisting of multiple types of inheritance is called hybrid inheritance.
EXAMPLE:
# Python program to demonstrate hybrid inheritance
class School:
def func1(self):
print("This function is in school.")
class Student1(School):
def func2(self):
print("This function is in student 1. ")
class Student2(School):
def func3(self):
print("This function is in student 2.")
class Student3(Student1, School):
def func4(self):
print("This function is in student 3.")
# Driver's code
object = Student3()
object.func1()
object.func2()
OUTPUT:
This function is in school.
This function is in student 1.
class Car(ABC):
def mileage(self):
pass
class Tesla(Car):
def mileage(self):
print("The mileage is 30kmph")
class Suzuki(Car):
def mileage(self):
print("The mileage is 25kmph ")
class Duster(Car):
def mileage(self):
print("The mileage is 24kmph ")
class Renault(Car):
def mileage(self):
print("The mileage is 27kmph ")
# Driver code
t= Tesla ()
t.mileage()
r = Renault()
r.mileage()
s = Suzuki()
s.mileage()
d = Duster()
d.mileage()
OUTPUT:
The mileage is 30kmph
The mileage is 27kmph
The mileage is 25kmph
The mileage is 24kmph
EXAMPLE:
# program to determine the method overriding
# Defining a parent class
class Parent():
# producer
def __init__(self):
self.value = "Inside Parent"
# showing a parents method
def show(self):
print(self.value)
# Defining a child class
class Child(Parent):
# Constructor
def __init__(self):
self.value = "Inside Child"
# showing the child's method
def show(self):
print(self.value)
# Chauffeur's code
obj1 = Parent()
obj2 = Child()
obj1.show()
obj2.show()
OUTPUT:
Inside Parent
Inside Child
➢ The overridden methods may also invoke methods from the parent class. There are
typically two ways to accomplish this.
a) Using Class name: Inside the overridden method, use the Parent classname-method to invoke
methods from the Parent's class.
EXAMPLE:
# program to determine calling the Parent's class method In the overridden method
class Parent ():
def show(self):
print ("Inside Parent")
class Child (Parent):
def show(self):
# child's class method is called
Parent.show(self)
Print ("Inside Child")
obj = Child ()
obj. show ()
OUTPUT:
Inside Parent
Inside Child
b) Using Super (): The Super () function in Python allows us to refer to the parent class
explicitly. It comes in handy when we need to call superclass functions. It gives us the proxy
object to use "super" to refer to the parent class.
EXAMPLE:
super ().sub_JTP(b + 1)
# function main
if __name__ == '__main__':
jtp = JTP3()
jtp.sub_JTP(10)
OUTPUT:
import re
txt = "The rain in Spain"
x = re.search("\s", txt)
print("The first white-space character is located in position:", x.start())
e) Match Object
➢ A Match Object is an object containing information about the search and the result.
➢ Note: If there is no match, the value None will be returned, instead of the Match Object.
import re
txt = "The rain in Spain"
x = re.search("ai", txt)
print(x) #this will print an object
19. Create a set and apply the union, intersection, difference and symmetric difference.
Let us define two sets:
Set A: {1, 2, 3, 4, 5}
Set B: {4, 5, 6, 7, 8}
Operations performed on Set:
Union: The union of two sets contains all unique elements from both sets.
Intersection: The intersection of two sets contains only the elements that are common to
both sets.
Difference: The difference between two sets contains elements that are in the first set but
not in the second set.
Symmetric Difference: The symmetric difference contains elements that are in either of
the sets but not in both.
EXAMPLE PROGRAM:
# Define the two sets
set_A = {1, 2, 3, 4, 5}
set_B = {4, 5, 6, 7, 8}
# Union
union_set = set_A.union(set_B)
print("Union:", union_set)
# Intersection
intersection_set = set_A.intersection(set_B)
print("Intersection:", intersection_set)
# Difference
difference_set_A = set_A.difference(set_B)
print("Difference (A - B):", difference_set_A)
difference_set_B = set_B.difference(set_A)
print("Difference (B - A):", difference_set_B)
# Symmetric Difference
symmetric_difference_set = set_A.symmetric_difference(set_B)
print("Symmetric Difference:", symmetric_difference_set)
OUTPUT:
Union: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection: {4, 5}
Difference (A - B): {1, 2, 3}
Difference (B - A): {8, 6, 7}
Symmetric Difference: {1, 2, 3, 6, 7, 8}
20. Write any five built-in function related to sets in python and explain.
1. add()
• Syntax: set.add(element)
• This function adds a single element to the set. If the element is already present in
the set, the set remains unchanged.
• EXAMPLE:
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}
2. remove()
• Syntax: set.remove(element)
• This function removes a specified element from the set. If the element is not
present, it raises a KeyError.
• EXAMPLE:
my_set = {1, 2, 3}
my_set.remove(2)
print(my_set) # Output: {1, 3}
3. pop()
• Syntax: set.pop()
• This function removes and returns an arbitrary element from the set. If the set is
empty, it raises a KeyError.
• EXAMPLE:
my_set = {1, 2, 3}
popped_element = my_set.pop()
print(popped_element) # Output: 1
print(my_set) # Output: {2, 3}
4. clear()
• Syntax: set.clear()
• This function removes all elements from the set, making it empty.
• EXAMPLE:
my_set = {1, 2, 3}
my_set.clear()
print(my_set) # Output: set()
5. copy()
• Syntax: set.copy()
• This function returns a shallow copy of the set. Modifications to the copy do not
affect the original set, but modifications to the elements inside the set are reflected
in both sets if they are mutable objects.
• EXAMPLE:
my_set = {1, 2, 3}
copied_set = my_set.copy()
copied_set.add(4)
print(my_set) # Output: {1, 2, 3}
print(copied_set) # Output: {1, 2, 3, 4}
21. Write a program in python to eliminate the duplicate values with and without using set.
# METHOD 1: USING SETS
PROGRAM 1:
def remove_duplicates_with_set(input_list):
# Convert the list to a set to remove duplicates
unique_set = set(input_list)
# Convert the set back to a list to preserve the original order
result_list = list(unique_set)
return result_list
# Example usage:
input_list = [1, 2, 3, 3, 4, 5, 5, 6]
result = remove_duplicates_with_set(input_list)
print("Without Duplicates (using set):", result)
OUTPUT:
Without Duplicates (using set): [1, 2, 3, 4, 5, 6]
else:
i += 1
print("List with duplicates removed:", my_list)
OUTPUT:
List with duplicates removed: [10, 20, 30, 40, 50]
EXAMPLE PROGRAM:
# Example with multiple iterables
def add(x, y):
return x + y
numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]
result = map(add, numbers1, numbers2)
print(list(result)) # Output: [5, 7, 9]