CS BY 8 Unit 4
CS BY 8 Unit 4
PROBLEM SOLVING
Functional Programming-Lambda & Map
1
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Functional Programming
• Higher order functions are the functions that take other functions as
arguments and they can also return functions. (Ex: Callback Functions)
• They are deterministic in nature .
• They can be understood very easily as they don’t change states of any
variables.
• Testing and debugging is easier. They use immutable values
• Offers better modularity with a shorter code
• Increased productivity of the developer
• It adopts lazy evaluation which avoids repeated evaluation because the value
is evaluated and stored only when it is needed.
• Example: Functional Constructs like Lazy Map & Lists ,tuples, sets etc. 2
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
The keyword - lambda
3
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
The keyword - lambda
Advantages:
•Lambda functions in Python are very useful in defining the in-line functions.
4
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
The keyword - lambda
5
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Examples
Example1: To find the square of a number (Comparison between
normal and lambda function)
6
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Examples
Output:
The maximum is 7
<function <lambda> at 0x00000217A6F93550> <class 'function'>
7
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Examples
The power of lambda is better understood when you use them as an anonymous
•
function inside another function.
Example 3
Suppose we have a function definition that takes one argument, and that
argument will be multiplied with an unknown number.
def myfunc(n):
return lambda a : a * n
double_N = myfunc(2)
print(double_N(12)) Output:24 8
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Examples
We can use the same function definition to make two functions (doube_N and triple_N
functions) in the same program. •
Example 4
def myfunc(n):
return lambda a : a * n
double_N = myfunc(2)
triple_N = myfunc(3) Output
30
print(double_N(15)) 45
print(triple_N(15))
9
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Map() Function
Python map() function is a built in function which is utilized to apply a function to each
element of an iterable (like a list or a tuple) and returns a new iterable object.
10
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Map() Function
Working:
• The map function causes iteration through the iterable, and applies the callable
on each element of the iterable
• All these happen only conceptually as the map function is lazy and the above
said operations happen only after the map object is iterated.
• We can force an iteration of the map object by passing the map object as an
argument for the list or set constructor.
Example:
As map object can be iterated over, the computation will be done for only one item in each
loop. In contrast, when we use list, which is an eager object, it basically computes all the
values at one time.
Lazy evaluation can be a powerful technique for optimizing code and improving
performance, but it is only sometimes necessary or appropriate. 12
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Map() Function
Choosing between lazy and eager evaluation
• When deciding which evaluation strategy to use for a given programming problem,
there is no one-size-fits-all answer. The choice depends on the nature of the problem,
the characteristics of the data, the requirements of the solution, and the preferences
of the programmer.
• However, some general guidelines can be followed to help make an informed
decision. For instance, lazy evaluation should be used when you want to delay or
avoid computations that are not needed, save memory by avoiding intermediate
results, create and manipulate infinite or recursive data structures, or explore
multiple possibilities without committing to one.
• On the other hand, eager evaluation is preferable when you want to perform
computations as soon as possible, exploit parallelism or concurrency, or ensure
predictable and consistent performance.
13
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Map() Function
numbers = (1, 2, 3, 4)
result = map(lambda x: x + x, numbers)
print(list(result))
Output:
<class 'map'>
[2, 4, 6, 8]
14
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Map() Function
Example 2 – To add two lists using map and lambda
num1 = [4, 2, 5]
num2 = [6, 8, 9]
Output:
[10, 10, 14]
15
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Map() Function
Example 3 – Function that doubles even numbers present in the list.
def double_num(n):
if n% 2 == 0:
return n * 2
else:
return n
numbers = [1, 2, 3, 4, 5]
18
PYTHON FOR COMPUTATIONAL
PROBLEM SOLVING
Functional Programming - Filter
•Filter function filters the given sequence with the help of a function that tests each
element in the sequence to be true or not.
•There are cases where we want to remove a few elements of the input iterable.
Then we make use of the filter function.
•sequence: The sequence which needs to be filtered, it can be sets, lists, tuples, or
containers of any iterators.
2
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Examples
Example 1: Program to list the marks which are greater than 70
marks = [55, 78, 90, 87, 65, 45]
def myFunc(m):
if m <70 :
return False
else:
return True
Output:
Students with marks greater than 70 are [78, 90, 87] 3
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Examples
Example 2: Function that filters vowels
def fun(char):
letters = ['a', 'e', 'i', 'o', 'u']
if (char in letters):
return True
else:
return False
#def is_multiple_of_3(num):
return num % 3 == 0
6
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Examples
Output:
['ADITYA', 'DINESH']
THANK YOU
Department of Computer Science and Engineering
Dr. Shylaja S S, Director, CDSAML & CCBD, PESU
Prof. Sindhu R Pai – sindhurpai@pes.edu
Prof. C N Rajeswari
9
PYTHON FOR COMPUTATIONAL
PROBLEM SOLVING
The function: reduce
Prof. Sindhu R Pai
PCPS Theory Anchor - 2024
Department of Computer Science and Engineering
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
reduce() Function
Introduction
The reduce() is a function that applies a given function to the elements of an iterable,
reducing them to a single value. This function is defined in “functools” module.
Syntax
functools.reduce(function, iterable[, initializer])
• The function argument is a function that takes two arguments and returns a single
value. The first argument is the accumulated value, and the second argument is the
current value from the iterable.
• The iterable argument is the sequence of values to be reduced.
• The optional initializer argument is used to provide an initial value. If no initializer is
specified, the first element of the iterable is used as the initial value.
1
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
reduce() Function
•At first step, first two elements of the sequence are picked and the result is
obtained.
•The same function is applied to the previously attained result and the number just
succeeding the second element and the result is again stored.
•This process continues till no more elements are left in the container.
•There will be n – 1 calls if no initializer is specified.(n is the number of elements in
the input iterable)
•The final result is returned as a single value.
9
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Examples
Example 1.To find the factorial of a number using reduce() function
import functools
n=5
print("The factorial is ",functools.reduce(int.__mul__ , range(1, n + 1)))
Output:
The factorial is 120
Example 3.To find the product of numbers with 100 as the initial value.
def product(x, y):
print("product : ", x, y)
return x * y
print("The product with 100 as initial value
is",functools.reduce(product, [11, 22, 33, 44], 100))
Output:
product : 100 11
product : 1100 22
product : 24200 33
product : 798600 44
The product with 100 as initial value is 35138400 11
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Examples
Example 4: To find the sum and maximum temperature
import functools
temperature = [22.5, 24.6, 26, 32, 27.5]
# using reduce to compute sum of temperature
sum=functools.reduce(lambda a, b: a+b, temperature)
print("The average temperature is ", sum/5)
# using reduce to compute maximum temperature in the list
print("The maximum temperature is : ", end="")
print(functools.reduce(lambda a, b: a if a > b else b,
temperature))
Output:
The average temperature is 26.52 12
The maximum temperature is : 32
THANK YOU
Department of Computer Science and Engineering
Dr. Shylaja S S, Director, CDSAML & CCBD, PESU
Prof. Sindhu R Pai – sindhurpai@pes.edu
Prof. C N Rajeswari
7
PYTHON FOR COMPUTATIONAL
PROBLEM SOLVING
The function: Zip
Prof. Sindhu R Pai
PCPS Theory Anchor - 2024
Department of Computer Science and Engineering
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Zip() function
Syntax : zip(*iterators)
2
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Zip() function
Working
print(list(zip(m,n)))
Output
[(1, 4), (2, 5), (3, 6)]
[(1, 4), (2, 5), (3, 6)] 4
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Examples
Example 2: Combining two iterables (tuples) into a single iterable
print(set(mapped))
Output:
{('Sudha', 404), ('Suma', 112), ('Sara', 393), ('Asha', 223)}
5
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Examples
Example 3: Combining two iterables (lists) into a single list
a = [1, 2, 3, 4, 5]
b = list(map(lambda x : x * x * x, a))
print(a)
print(b)
print(list(zip(a, b)))
Output:
[1, 2, 3, 4, 5]
[1, 8, 27, 64, 125]
6
[(1, 1), (2, 8), (3, 27), (4, 64), (5, 125)]
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Examples
Example 4: Zipping list and tuple with unequal size
#Define lists for 'persons’,and a tuple for 'ages'
persons = ["Baskar", "Monica", "Riya", "Madhav", "John",
"Prashanth"]
ages = (35, 26, 28, 14)
Output
[(1, 4), (2, 5), (3, 6)]
{1: 4, 2: 5, 3: 6}
8
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Practice programs
1.Given list of circle areas all in five decimal places, round each element
in the list up to its position decimal places, meaning round up the first
element in the list to one decimal place, the second element to two
decimal places, the third element to three decimal places and so on.
2.Given
list= [1,2,3,4,5]
Chars= [‘a’, ’b’, ’c’, ’d’, ’e’]
Output the following.
('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
3.The following are the scores of chemistry exam . Filter out those who
passed with scores >75. Use an appropriate function
9
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Practice programs
4.You are given a list of fruits names. Using lambda and map function
print the list of fruit names starting with ‘A’
Lst=[‘Orange’, ’Apple’ , ’ Mango’, ‘ Apricot’]
Output=[‘Apple’, ‘Apricot’]
5.Using reduce function find the sum of the digits of the digits of the
given number
6. Using the min and reduce function find the smallest number in a
given list of 10 numbers.
10
THANK YOU
Department of Computer Science and Engineering
Dr. Shylaja S S, Director, CDSAML & CCBD, PESU
Prof. Sindhu R Pai – sindhurpai@pes.edu
Prof. C N Rajeswari
11
PYTHON FOR COMPUTATIONAL
PROBLEM SOLVING
Object Oriented Programming
Prof. Sindhu R Pai
PCPS Theory Anchor - 2024
Department of Computer Science and Engineering
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming
Programming Paradigm: Style or way or strategy using which we write the solution
Focus is on the data and the operations that manipulate the data.
OOP is mainly useful to develop big and complex projects carried out by large
teams.
3
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming
Features of OOP
Data Abstraction:
• The way you view an object(Ex: employee, library, customers etc)
• Represents the essential features without background details.
• Depending on the application, abstraction has to be implemented.
Data encapsulation:
• Binding of data and procedures as a single unit.
• Encapsulation is a way to implement data abstraction.
4
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming
Data Hiding:
• Its about who can access the data .
• Implemented using access specifiers.
Inheritance:
• Capability of one class (child) to derive the capabilities of another class(parent)
• Code reusability is the major benefit of inheritance.
Polymorphism:
• Capability of an object of a class to behave differently in response to the data.
5
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming
Key concepts in OOP:
class:
• It is a methodology to create an entity.
• Blueprint or template for creating objects.
• Defines attributes (variables) and methods (functions) that all objects of that class
will have.
• The class by itself is a type and implementation.
• A class specifies the set of instance variables and methods that are “bundled
together” 6
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming
Syntax: (To create a class)
class ClassName:
<statement-1>
.
<statement-N>
Example 1
class Ex1:
pass
print(Ex1, type(Ex1))
Output:
<class '__main__.Ex1'> <class 'type’>
So, Ex1 is a type in the package __main__ 7
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming
Example 2: class with attributes (fields or variables)
class Car:
car_name="Benz"
print(Car.car_name)
Output:
Benz
class Car:
car_name="Benz"
def display():
print("This is a Petrol Car")
print(Car.car_name)
Car.display()
Output:
Benz
This is a Petrol Car
9
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming
Objects (Instances):
• It is a a physical instance of a class.
• Represents the real-world entities
• Have their own attributes (class variables/instance variables) and
methods(class functions), as defined by the class.
10
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming
Objects have:
2.Type: The type() function can be used to determine the type of an object.
3.Value: Objects have a value that can be modified or accessed (like integers,
strings, lists)
11
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming
Example 5:
class Car:
pass
c1 = Car()
print(c1)
print(type(c1))
print(id(c1))
Output:
Instantiation
• The existence of a class does not create the object.
• Object must be created explicitly
• To create an object of the class, use the function which has the same name as class.
Ex: c1= Car() will create an object(c1) of class Car
• (.)Dot operator notation can be used to access attributes of the class.
Ex: c1.car_name
13
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming
Constructor
14
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming
Destructor
• It is a special function within the class by name __del__, that performs the clean-
up actions when an object is destroyed or deleted.
• It is often used to release resources before an object is removed from the system.
15
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming
Example 6
class Car:
def __init__(self):
print("constructor called")
print('self : ', self)
c1= Car()
print('c1 : ', c1)
Output:
constructor called
self : <__main__.Car object at 0x000001F214B30DC0>
c1 : <__main__.Car object at 0x000001F214B30DC0> #Same output
Note: self is a reference to the instance of a class and is used to access the
attributes and methods within that instance and should be the first parameter.16
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming
Example 7:
class Car:
def __init__():
print("constructor called")
c1 = Car()
Output:
Traceback (most recent call last):
File "C:/Users/ADMIN/Desktop/practice programs.py", line 38, in
<module> car() TypeError: __init__() takes 0 positional arguments but 1
was given
As we see in the output, the constructor needs a parameter called self
17
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming
Example 8: Use of constructor and destructor
class MyClass:
def __init__(self, name):
self.name = name
print(f"Constructor called. {self.name} created.")
def some_method(self):
print(f"Hello from {self.name}!")
def __del__(self):
print(f"Destructor called.{self.name} deleted.")
Note: The destructor is called when the object obj1 is explicitly deleted
using “del obj1”
19
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming
Types of Constructors :
1. Parameterized constructor
2. Non Parameterized constructor
def display(self):
print(f"Rectangle dimensions: {self.length} x {self.width}")
def __del__(self):
print("Rectangle object destroyed.")
Getter:
• Used to retrieve the value of attribute of a class without directly exposing it.
Setter:
• Used to modify the value of attribute of a class.
obj = getset("Arun")
print("Name:: before calling setter",obj.get_name()) # Output: Arun
obj.set_name("Ram")
print("Name:: after calling setter",obj.get_name()) # Output: Ram
24
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming
Practice programs
1.Define a class called “candidate” which has the Registration number and
Score as the data members.
Write a function Input() which allows the user to enter values for the above
data members.
Write a function called Selection() which assigns remarks as per the score
obtained by the candidate as follows.
If score>=60 then assign remarks=“Selected” else remarks= “Not selected”
Write a display() function to view the data members.
Test this created class for all its functionality by creating objects
27
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming
Define a constructor which initializes the above class members with the values 105,
“Bombay”,15, and 5 respectively.
Take the input() from the user for all the data members.
Also assign the number of buses equal to 1 if number of travelers is greater or equal
to 10 otherwise no bus is assigned.
Test this created class for all its functionality by creating objects
28
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming
Test this created class for all its functionality by creating objects
29
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming
30
THANK YOU
Department of Computer Science and Engineering
Dr. Shylaja S S, Director, CDSAML & CCBD, PESU
Prof. Sindhu R Pai – sindhurpai@pes.edu
Prof. C N Rajeswari
31
PYTHON FOR COMPUTATIONAL
PROBLEM SOLVING
Inheritance
Prof. Sindhu R Pai
PCPS Theory Anchor - 2024
Department of Computer Science and Engineering
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance
Introduction
• Allows programmers to define a new class which inherits almost all the
properties(data members and methods) of existing class.
Is – a relationship: Indicates that one class gets most or all of its features
from a parent class.
When this kind of specialization occurs, there are three ways in which
parent and child can interact.
class B(A):
pass
a1=A()
a1.disp()
b1=B()
b1.disp() 4
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance
2. Action on the child override the action on the parent
Example
class A: Output:
def disp(self):
print("in disp A") in disp A
in disp B
class B(A):
def disp(self):
print("in disp B")
a1=A()
a1.disp()
b1=B()
b1.disp()
5
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance
3. Action on the child alter the action on the parent
Example
class A: Output:
def disp(self):
in disp A
print("in disp A")
in disp A
class B(A): in disp B
def disp(self):
A.disp(self)
print("in disp B")
a1=A()
a1.disp()
b1=B() 6
b1.disp()
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance
1. Single level inheritance: Sub classes inherit the features of one super class.
2. Multi Level inheritance: A class is inherited from another class which is in
turn inherited from another class and so on.
3. Multiple inheritance: A class can have more than one super class and
inherit the features from all parent classes.
4. Hierarchical inheritance: One class serves as super class for more than one
sub classes
5. Hybrid inheritance: A mix of two or more above types of inheritance. Also
known as Diamond shaped inheritance
7
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance
Benefits of inheritance:
class BaseClass1
#Body of base class
class DerivedClass(BaseClass1):
#body of derived - class
9
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance
class A:
Output:
def __init__(self, n='Rahul'): Traceback (most recent call last):
self.name = n File
class B(A): "C:\Users\ADMIN\Desktop\inheritance.py",
def __init__(self, roll): line 101, in <module> print(b1.name)
self.roll = roll AttributeError: 'B' object has no attribute
'name'
b1 = B(23)
print(b1.name)
12
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance
Super() Function
13
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance
Example 4:Assume the parent class has thousands of instance variables
class sample:
def __init__(self,m,n,o):
self.a=m
self.b=n
self.c=o
class sample_child(sample):
def __init__(self,m,n,o,q):
#super().__init__(m,n,o)
Sample.__init__(self,m,n,o)
self.e=q
def display(self):
print(self.a,"--",self.b,"--",self.c,"--",self.d,"--",self.e)
s1=sample_child(1,2,3,4,90)
14
s1.display()
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance
Example 5: Using super() a subclass can override methods or attributes
from its superclass
class ParentClass:
def __init__(self):
self.parent_attribute = "Parent Attribute"
def parent_method(self):
print("Parent Method")
class ChildClass(ParentClass):
def __init__(self):
super().__init__() # Calling the parent class constructor
self.child_attribute ="Child Attribute"
15
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance
def child_method(self):
super().parent_method()
print("Child Method")
child_obj = ChildClass()
Multiple inheritance
It provides the flexibility to inherit attributes and methods from more than
one class
17
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance
Example 6
class A: Note:
def disp(self): • When there is implicit action on class C, then the
class hierarchy of A is considered.
print("in disp A")
class B: • super() refers to only the first Parent mentioned
def disp(self): in the subtype creation
print("in disp B")
class C(A,B): #reverse the order of A and B and observe the output
def disp(self):
Output: in disp A
super().disp() if reversed as in C(B, A)
print("in disp C")Output: in disp B
c1=C() 18
c1.disp()
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance
Multi-Level inheritance
It refers to a type of inheritance where a subclass inherits from another
subclass, forming a hierarchical chain of classes.
Syntax:
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
19
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance
triangle = Triangle("Triangle")
print(triangle.info())
quadrilateral = Quadrilateral("Quadrilateral")
print(quadrilateral.info())
Output
issubclass(sub, sup)
isinstance(obj,class)
22
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance
class mult:
def Multiplication(self,a,b):
return a*b
class Derived(add,mult):
def Divide(self,a,b):
return a//b
23
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance
d = Derived()
print(issubclass(Derived,mult)) Output:
print(issubclass(add,mult)) True
False
True
print(isinstance(d,Derived))
Summation of a and b:
32
print("Summation of a and b: ",d.Summation(12,20)) Product of a and b: 72
print("Product of a and b: ",d.Multiplication(9,8)) Quotient: 2
print("Quotient:“ ,d.Divide(20,10))
24
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance
Composition: When one object contains another object as a part or member.
Ex: Library has books
26
PYTHON FOR COMPUTATIONAL
PROBLEM SOLVING
Polymorphism
Prof. Sindhu R Pai
PCPS Theory Anchor - 2024
Department of Computer Science and Engineering
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Polymorphism
Introduction
• refers to the use of the same function name, but with different signatures
• This concept enables a single interface to be used for entities of different types.
2
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Polymorphism
Runtime Polymorphism
• Python supports runtime polymorphism by using techniques like method
overloading and method overriding
3
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Polymorphism
Key Aspects of Runtime Polymorphism:
1.Inheritance:
• Runtime polymorphism is closely associated with inheritance.
2.Method Overriding:
• Subclasses override methods from their superclass to provide their
own specialized implementation.
• The method signature remains the same in both the superclass and
subclass. 4
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Polymorphism
3.Dynamic Binding:
4.Common Interface:
This happens at the runtime and method execution is dynamically bound to the
object’s specific implementation.
6
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Polymorphism
class Shape:
def calculate_area(self):
pass
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def calculate_area(self):
return self.length * self.width
7
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Polymorphism
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def calculate_area(self):
return 3.14 * self.radius * self.radius
print(rect.calculate_area())
print(circle.calculate_area())
8
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Polymorphism
Practice Program
Build a music player program where ‘Audiofile’ is the base class.
Implement sub classes ‘MP3File’ and ‘WAVFile’ inheriting from
‘AudioFile’. Both classes should have a ‘play’ method but provide
different functionalities for playing MP3 and WAV files.
9
THANK YOU
Department of Computer Science and Engineering
Dr. Shylaja S S, Director, CDSAML & CCBD, PESU
Prof. Sindhu R Pai – sindhurpai@pes.edu
Prof. C N Rajeswari
10
PYTHON FOR COMPUTATIONAL
PROBLEM SOLVING
Iterators in Python
Prof. Sindhu R Pai
PCPS Theory Anchor - 2024
Department of Computer Science and Engineering
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Introduction
__iter__():: returns the iterator object itself and is called when the iterator
is initialized.
2
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Introduction
3
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Custom Iterable Objects
The container class (like list) should support a function
2. __next__(callable as next(iterator_object))
c = MyContainer(a)
for w in c :
print(w)
c = MyContainer(a)
6
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Working of iterators
This __iter__ function adds a position attribute i to the object and then
returns the MyContainer object itself as the iterator object.
The __next__ function has the logic to return the next element from the list
and update the position and also raise the exception stop iteration when the
end of the list is reached.
7
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Examples
Example 2
squares = SquareNum(5)
class SquareNum:
# Using the iterable class
def __init__(self, n):
self.n = n
for num in squares:
self.current = 0
print(num)
def __iter__(self):
SquareNum is a class that generates a sequence of
return self
squares of numbers from 0 to n-1
def __next__(self):
It has __iter__() and __next__() methods
if self.current >= self.n:
implemented, making it iterable.
raise StopIteration
When instance of this class in a for loop, it iterates
square = self.current ** 2
through the sequence, printing the squares of the
self.current += 1
numbers from 0 to 4 8
return square
THANK YOU
Department of Computer Science and Engineering
Dr. Shylaja S S, Director, CDSAML & CCBD, PESU
Prof. Sindhu R Pai – sindhurpai@pes.edu
Prof. C N Rajeswari
9
PYTHON FOR COMPUTATIONAL
PROBLEM SOLVING
Exception handling in Python
Prof. Sindhu R Pai
PCPS Theory Anchor - 2024
Department of Computer Science and Engineering
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling
Introduction:
2
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling
Based on when the error occurs, errors are classified into two types:
1. Syntax errors
This occurs when there a deviation from the rules of the language.
A component of python’s interpreter called parser discover these errors. If
hybrid interpreter, compiler finds this error.
Ex: print("good morning)
print("good morning“
4
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling
5
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling
Exceptions Explanation
Overflow Error Raised when a floating-point expression evaluates to a value that is too large
IO Error Raised when a sequence index is outside the range of valid indexes
Type Error Raised when an operation or function is applied to an object wrong type
6
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling
• It may have more than one except clause to specify handlers for different
exceptions.
• Handlers only handle exceptions that occur in the corresponding try-block, not
in the other handlers of the same try block.
8
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling
except :
• The exception thrown in try block, is caught in except block and the statements in
this block are executed.
• If many except clauses are there, then the specific classes are specified first and
then the parent classes are specified.
• Last except clause provide a common and default way of handling all exceptions.
9
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling
else :
• This block will be executed if no errors were raised.
• That is , this block gets executed when try is successful
Finally:
• The statements in this clause will executed regardless of whether an exception
occurred or not in the try block.
• Its primary purpose is to perform clean up actions or tasks and close the
resources used in the program.
raise
• Is used to forcefully throw an exception 10
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling
Basic Structure
try:
# This is a block of code where an exception might occur
except SomeException:
# This is the except block to handle the exception
else:
# This is executed if no exceptions were raised in the "try" block
finally:
#This is executed whether an exception occurs or not
11
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling
Example 1: (with try and except only)
try:
print(x)
Output
An exception occurred as x is not defined
12
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling
Example 2: (with try and except only-ZeroDivision Error)
try:
y = 10 / 0
Output
except ZeroDivisionError:
Python exception raised
13
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling
Example 3: (with try,except ,else and finally)
try:
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError as e:
print("Error:", e) # Handling the ZeroDivisionError
Output:
else: Error: division by zero
print("No exceptions occurred.") This will always execute,
regardless of exceptions.
finally:
print("This will always execute, regardless of exceptions.")
14
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling
Example 4 (with try except else and finally)
try:
file = open("example.txt", "r")
Output:
except FileNotFoundError:
print("File not found.") File not found.
File closure commands can be given here
else:
print("File operations completed successfully.")
finally:
print("File closure commands can be given here") 15
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling
Raising Exceptions:
Exceptions can be raised manually using the raise statement, which raises the
custom exceptions. Ca also be used to raise builtin exceptions.
Example 5
try:
Output:
age = int(input("Enter your age: ")) Enter your age: -7
Error: Age cannot be negative.
if age < 0:
raise ValueError("Age cannot be negative.")
When an exception occurs, you can access information about the exception
using “as” to assign it to a variable.
Output:
try: Exception type: ZeroDivisionError
Exception details: division by zero
res= 20 / 0
except Exception as e:
•The raised or thrown exception object is matched with the except blocks in
the order in which they occur in the try-except statement.
•It is always the first match and not the best match.
18
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling
Handling Multiple Exceptions:
Example 6
try:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
my_list = [1, 2, 3]
except ZeroDivisionError:
print("ZeroDivisionError: Cannot divide by zero.")
Output:
except IndexError:
Enter first number: 4
print("IndexError: Index is out of range.") Enter second number: 2
Enter an index for the list: 6
else: IndexError: Index is out of range.
print("No exceptions occurred.") This will always execute, regardless
of exceptions.
finally: 20
print("This will always execute, regardless of exceptions.")
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling
2.User defined exceptions
•Most of the built-in exceptions are also derived from this class.
•The new exception, like other exceptions, can be raised using the raise
statement with an optional error message.
21
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling
Example 7
class MyException(Exception): #inherits from the Exception class
def __str__(self):
return self.str
22
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling
try:
n = int(input("Enter the number"))
if not 1 <= n <= 100 :
raise MyException("Number not in range")
except MyException as e:
print(e)
Output:
else:
Enter the number200
print("Number well within the range") Number not in range
Program Terminated
print("Program Terminated")
23
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling
Example 8
class FiveDivisionError(Exception): Output:
pass Enter the first number 7
try: Enter the second number 5
n1=int(input("Enter the first number")) Dividing by 5 not possible
n2=int(input("Enter the second number")) Program ends
if n2==5:
raise FiveDivisionError("Dividing by 5 not possible")
d=n1/n2
print("The answer is",d)
except (FiveDivisionError,ZeroDivisionError) as e:
print(e)
print("Program ends") 24
THANK YOU
Department of Computer Science and Engineering
Dr. Shylaja S S, Director, CDSAML & CCBD, PESU
Prof. Sindhu R Pai – sindhurpai@pes.edu
Prof. C N Rajeswari
25