[go: up one dir, main page]

0% found this document useful (0 votes)
4 views147 pages

CS BY 8 Unit 4

The document discusses functional programming in Python, focusing on lambda functions, the map function, and the filter function. It explains the advantages of using these features for cleaner, more efficient code, and provides examples of their usage. Additionally, it introduces the reduce function from the functools module for reducing iterables to a single value.

Uploaded by

casecrafterclub
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views147 pages

CS BY 8 Unit 4

The document discusses functional programming in Python, focusing on lambda functions, the map function, and the filter function. It explains the advantages of using these features for cleaner, more efficient code, and provides examples of their usage. Additionally, it introduces the reduce function from the functools module for reducing iterables to a single value.

Uploaded by

casecrafterclub
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 147

PYTHON FOR COMPUTATIONAL

PROBLEM SOLVING
Functional Programming-Lambda & Map

Prof. Sindhu R Pai


PCPS Theory Anchor - 2024
Department of Computer Science and Engineering
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Functional Programming

• Functional programming is a programming paradigm where programs are


constructed by applying and composing functions.
• It is basically a study of computations with functions which uses pure
functions, recursive functions, nested functions ,lambda functions etc.
• The ability of functional programming languages to treat functions as values
and pass them to functions as parameters make the code more readable and
easily understandable.
• They depend only on the input given to them, and the output will be the
return value. Their function signature gives all the information about them i.e.
their arguments and return type etc.

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

Lambda (Anonymous function/Nameless Function/ Throw away function creation)

• Lambda functions are functions without the name.


• Its also called as anonymous functions or throw away functions.
• It can have any number of arguments but can have only one expression.
• The expression is executed and returned (Implicit return)
• Lambda functions are used when function objects are required.
• Lambda functions are used when you need a particular function for a short
period of time.

3
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
The keyword - lambda

Advantages:

•Lambda functions in Python are very useful in defining the in-line functions.

•Most suitable when it is used as a part of another function(especially with map,


filter and reduce functions)

•Less Code (Concise code)

4
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
The keyword - lambda

Syntax: lambda input arguments: expression / Output

• lambda is a keyword used to declare lambda function.


• Input arguments: It can have multiple arguments (if there are more than
one arguments, then separate the arguments by a comma).
• Expression or output: Expression gets evaluated and results are returned

5
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Examples
Example1: To find the square of a number (Comparison between
normal and lambda function)

Normal Function Lambda Function

def square(n): square=lambda n : n*n


return n*n

print(square(4)) print(square(4)) #Function Call

6
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Examples

Example 2: To find the greatest of two numbers using the relational


operator.

maximum=lambda a,b : a if a>b else b #max(a,b) can also be used


print("The maximum is ",maximum(6,7))
print(maximum,type(maximum))

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.

Syntax: map(function, iterables)

1. The map() function takes two arguments: a function and iterables.


2. The first argument for the map function should be a callable which takes one
argument – could be a free function, function of a type, user defined function, or a
lambda function.
3. This function will be applied to every element of the iterable, and creates a map
object which is also an iterable.

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.

• We can pass one or more iterable to the map() function.


11
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Map() Function
Lazy and Eager objects:
Under lazy object creation, the object is created when it is needed whereas in the case of
eager object creation, an object is created as soon it is instantiated. A lazy object
representing a function would be quick to create, and populate itself with information
when that information is requested. Built-in functions like range(),map(),zip() and open()
functions are basically lazy function objects.

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

Example 1 To double all numbers using map and lambda

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]

result = map(lambda x, y: x + y, num1, num2)


print(list(result))

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]

# Use map to apply the function to each element in the list


result = list(map(double_num, numbers))
print("The modified list is ",result)

Output: The modified list is [1, 4, 3, 8, 5] 16


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

18
PYTHON FOR COMPUTATIONAL
PROBLEM SOLVING
Functional Programming - Filter

Prof. Sindhu R Pai


PCPS Theory Anchor - 2024
Department of Computer Science and Engineering
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Filter() Function

•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.

•Syntax: filter(function, sequence/iterable)


•function: function that tests if each element of a sequence is true or not.

•sequence: The sequence which needs to be filtered, it can be sets, lists, tuples, or
containers of any iterators.

•Returns: an iterator that is already filtered. 1


PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Filter() Function

The filter function has the following characteristics.

• Input : an iterable of some number of elements (say n)

• Output: a lazy iterable of 0 to n elements (between 0 and n)

• Elements in the output: apply the callback on each element of the


iterable – if the function returns true, then the input element is
selected otherwise the input element is rejected.

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

Distinction = list(filter(myFunc, marks))


print("Students with marks greater than 70 are",Distinction)

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

characters = ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r','l','d']


vowels = list(filter(fun, characters))
print('The filtered letters are:’,vowels)
Output
The filtered letters are: ['e', 'o', 'o']
4
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Examples
Example 3 –Use of lambda function to filter out the odd and even
numbers from a list.
sequence = [0,1, 1, 2, 3, 5, 8,19]
# result contains list of odd numbers
result = filter(lambda x: x % 2 != 0, sequence)
print("The odd number list is",list(result))

# result contains list of even numbers


result = filter(lambda x: x % 2 == 0, sequence)
print("The even number list is",list(result))
Output:
The odd number list is [1, 1, 3, 5, 19]
The even number list is [0, 2, 8] 5
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Examples
Example 4: Function to check whether a number is a multiple of 3
using Lambda function in filter function

#def is_multiple_of_3(num):
return num % 3 == 0

# Create a list of numbers to filter


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = list(filter(lambda x: is_multiple_of_3(x), numbers))
print("The list of multiples of 3 is", result)
Output:
The list of multiples of 3 is [3, 6, 9]

6
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Examples

Example 5 : To pickup all words whose length exceeds 5 using map,filter


and Lambda function.

Names=[ 'Ram', 'Tejas', 'Aditya', 'Ravi', 'Dinesh', 'Raghu' ]


#finds all names whose length exceeds 5 and converts them to uppercase
print(list(map(str.upper, filter(lambda name : len(name) > 5, Names))))

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

Working of 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 2. To find the sum of first 10 numbers using reduce() function


import functools
print(functools.reduce(int.__add__, range(10)))
output
The sum of first 10 numbers is 55 10
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Examples

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

• Python zip() method takes iterable containers and returns a single


iterator object, having mapped values from all the containers.
• It is used to map the similar index of multiple containers so that they can
be used just using a single entity.
• The function zip is used to associate the corresponding elements of two
or more iterables into a single lazy iterable of tuples.
• It does not have any callback function.

Syntax : zip(*iterators)
2
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Zip() function

Working

• The zip() function is used to combine two or more lists (or


any other iterables) into a single iterable.

• Elements from corresponding positions are paired


together.

• The resulting iterable contains tuples, where the first


element from each list is paired together, the second
element from each list is paired together, and so on.
3
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Examples
Example 1: Consider the code below which pairs the two lists:
m=[1,2,3]
n=[4,5,6]
l_new=[]
for i in range(len(m)):
l_new.append((m[i],n[i]))
print(l_new)
The above can be done very easily and with less code using zip. We
can observe the same output.

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

name = [ "Sudha", "Suma", "Sara", "Asha" ]


roll_no = [ 404, 112, 393, 223 ]

# using zip() to map values


mapped = zip(name, roll_no)

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)

#lists along with the 'ages' tuple


zipped_result = zip(persons,ages)

print("Zipped result as a list:")


for i in list(zipped_result):
print(i) 7
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Examples
Example 5: Zipping list with unequal size.(Two ways)
lis1 = [1,2,3]
lis2 = [4,5,6,7]
print(list(zip(lis1,lis2)))

The same can be acheived using the directory comprehension as:

print({k:v for k,v in (zip(lis1,lis2))})

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

For ex: n = '1729’


output= summation of 1,7,2,9=19

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

Procedure Oriented Programming (POP)


• Focus is on procedures.
• Procedure is a set of instructions used to accomplish a specific task.
• It can be routines, sub-routines, functions etc.

Examples : C, Pascal, Fortran, Cobol, Algol etc.


2
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming

Object Oriented Programming (OOP)

Focus is on the data and the operations that manipulate the data.

Helps in organizing and designing code by representing real-world entities as


objects.

OOP is mainly useful to develop big and complex projects carried out by large
teams.

Ex: Java, C#, C++, Python etc.

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

Example 3: class with methods (behaviour)


class Car:
def fuel():
print("Petrol")
Car.fuel()
Output:
8
Petrol
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming
Example 4: Class having data and a method.

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:

1.Identity: Each object has a unique identity throughout its lifetime.


The id() function can be used to get the identity of an object.

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:

<__main__.Car object at 0x000001C9E2200DC0>


<class '__main__.Car'>
1966593805760 12
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming

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

• It is a special function of the class which is called when an object is created


• The name of the this function (constructor) is __init__
• It is invoked automatically and implicitly when the object of the class is created.
• The constructor can be used to initialize the internal state of an object, and create
instance variables

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.

• The destructor is automatically called just before an object is removed from


memory by the garbage collector.

• 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.")

obj1 = MyClass("Object 1") # Creating objects


obj1.some_method() 18
del obj1 # Explicitly deleting an object
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming
Output

Constructor called. Object 1 created.


Hello from Object 1!
Destructor called. Object 1 deleted.

Note: The destructor is called when the object obj1 is explicitly deleted
using “del obj1”

The module garbage collector automatically manages memory and calls


destructors when objects are not needed.

19
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming

Types of Constructors :
1. Parameterized constructor
2. Non Parameterized constructor

Example 9: Non-parameterized constructors

#when no parameters are passed for invoking constructor


class Person:
def __init__(self):
print("Constructor without parameters")
p = Person()
Output:
Constructor without parameters 20
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming

Example 10: Parameterized constructors


#Parameters are passed for invoking the constructor
class Person:
def __init__(self,name,age):
self.name = name #instance variables
self.age = age
def display(self):
print(self.name,self.age) #all names must be fully qualified
p = Person("joe",30) # value of self will be implicitly assigned
p.display()
p.gender=‘M’ # add instance variables to the object outside the class
print(p.gender)
21
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming(Practice Program)
Example 11:Demonstration class & object with constructor and destructor.
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width

def display(self):
print(f"Rectangle dimensions: {self.length} x {self.width}")

def __del__(self):
print("Rectangle object destroyed.")

# Creating a Rectangle object


rect = Rectangle(5, 10) 22
rect.display()
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming

Getter and Setter Method:

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.

• Allows controlled modification of the attribute's value by performing checks or


validations before assigning the new value.
23
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming

Ex: Getter and setter using user defined functions


class getset:
def __init__(self, name):
self.name = name
def get_name(self):
return self.name
def set_name(self,new_name):
self.name=new_name

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

Use of predefined functions


1 setattr() function sets the value of the specified attribute of the specified
object.
Syntax setattr(object, attribute, value)
2 getattr() function returns the value of the specified attribute from the
specified object.
Syntax: getattr(object, attribute, default)
3 hasattr() function returns True if the specified object has the specified
attribute, otherwise False.
Syntax hasattr(object, attribute)
4 delattr() function will delete the specified attribute from the specified
object.
25
Syntax delattr(object, attribute)
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming

Ex: Getter setter using predefined functions


class Person:
name = "John"
age = 36
country = "Norway"
person=Person()
x = getattr(person, 'age')
print(x) 36
setattr(person,'age',"40")
x = getattr(person, 'age')
print(x) 40
x =hasattr(person,"age")
print(x) True 26
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

2. Define a class called Travel with the following descriptions:


Class members: Travel _Code, Place, Number _of _travelers, Number _of _buses

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

3. Define a class called “ Stock” with following data members


item _code, item _name, price, quantity , Discount.

Define a member function CalcDisc() to calculate the discount as per the


following:
If quantity<=100 then discount=0
If quantity <=150 then discount is 5%
If quantity >150 then discount is 10%
Write a function Enter_Details() which allows the user to enter values to the
data members and call CalcDisc() to calculate the discount.
Write a function Display() to view the contents of all the data members.

Test this created class for all its functionality by creating objects
29
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Object oriented Programming

4.Define a class to represent the bank account of a customer with the


information like Name of the depositor, Account number and type of the
account(Savings, Current) and Balance amount.

Define separate methods for the following:


1. To initialize the data member
2. To Deposit the amount
3. To withdraw the amount after checking the balance amount
4. To display the data members

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

• Acquiring or obtaining the features of one type in another type.

• Allows programmers to define a new class which inherits almost all the
properties(data members and methods) of existing class.

• Two ways of relationships: Is – a relationship and Has-a relationship

• Is – a relationship is also known as parent-child relationship

• Has – a relationship is nothing but containership or composition or


collaboration 2
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance

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.

1. Action on child imply an action on the parent

2. Action on the child override the action on the parent

3. Action on the child alter the action on the parent


3
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance
1. Action on child imply an action on the parent
Example
class A: Output:
def disp(self):
in disp A
print("in disp A")
in disp A

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

Types of Is-a relationships:

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:

• It allows to inherit the properties of a base class, to another class


(derived) representing the real-world relationship.

• It provides the reusability of a code.

• Allows us to add more features to a class without modifying it.

• Transitive in nature, which means that if class B inherits from class A,


then all the subclasses of B would automatically inherit from class A.

• Less development and maintenance expenses 8


PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance

Single Level Inheritance

class BaseClass1
#Body of base class

class DerivedClass(BaseClass1):
#body of derived - class

9
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance

Example 1: Program to create a parent class and child class objects


class Person: class stud(Person):
#Constructor def Print(self):
def __init__(self, name, id_no): print("stud class called")
self.name = name
self.id_no = id_no student = stud("Madan", 103)

def Display(self): # Calling child class function


print(self.name, self.id_no) student.Print()

#creating an object of a person # calling parent class function


p = Person("Akash", 1001) student.Display()
p.Display() 10
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance
Example 2: Program to demonstrate the parent constructors
class Person:
def __init__(self, name, idnumber):
self.name = name
self.idnumber = idnumber
def display(self):
print(self.name)
print(self.idnumber)
class Employee(Person):
def __init__(self, name, idnumber, salary, desgn):
self.salary = salary
self.desgn = desgn
Person.__init__(self, name, idnumber) #observe carefully
emp = Employee('Riya', 802, 50000, "Admin")
11
emp.display()
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance
Example 3: Demo of the error if __init__() of the parent is not invoked

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

• It is a built-in function that provides a way to access methods and


properties from a parent class within a subclass.

• There might be situations where the overridden method as well as


the functionality of the parent method is required. That's where super()
becomes helpful.

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")

# Creating an instance of the ChildClass

child_obj = ChildClass()

# Accessing attributes and calling methods


print(child_obj.child_attribute)
print(child_obj.parent_attribute)
child_obj.child_method()
16
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance

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

Example 7: Use of super() in multi level inheritance

class Shape: def info(self):


def __init__(self, name): return f"A {self.name} is a polygon with
self.name = name {self.sides} sides."

def info(self): class Triangle(Polygon):


return f"This is a {self.name}." def __init__(self, name):
super().__init__(name, 3)
class Polygon(Shape):
def __init__(self, name, sides): class Quadrilateral(Polygon):
super().__init__(name) def __init__(self, name):
self.sides = sides super().__init__(name, 4) 20
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance

# Creating instances and accessing methods

triangle = Triangle("Triangle")
print(triangle.info())

quadrilateral = Quadrilateral("Quadrilateral")
print(quadrilateral.info())

Output

A Triangle is a polygon with 3 sides.


A Quadrilateral is a polygon with 4 sides.
21
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance

issubclass() and isinstance() methods

issubclass(sub, sup)

Used to check the relationships between the specified classes.


Returns True if the first class is the subclass of the second and False otherwise.

isinstance(obj,class)

Used to check the relationship between the objects and classes.


Returns True if the object is the instance of the specified class.

22
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Inheritance

Example 8: (use of issubclass() and isinstance())


class add:
def Summation(self,a,b):
return a+b

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

class Author: Output:


def __init__(self, name):
self.name = name 'Harry Potter and the Sorcerer's Stone' was written
by J.K. Rowling
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
author1 = Author("J.K. Rowling")
book1 = Book("Harry Potter and the Sorcerer's Stone", author1)
# Accessing Book and Author attributes
25
print(f"The book '{book1.title}' was written by {book1.author.name}")
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

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

• Polymorphism refers to having multiple forms.

• refers to the use of the same function name, but with different signatures

• allows objects of different classes to be treated as objects of a common


superclass.

• 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

• Runtime polymorphism is the ability of an object to behave differently based


on its actual type during program execution

• It is also known as dynamic polymorphism

• It enables the same method name to behave differently based on


the specific class instance at runtime.

3
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Polymorphism
Key Aspects of Runtime Polymorphism:
1.Inheritance:
• Runtime polymorphism is closely associated with inheritance.

• Subclasses inherit methods from their superclass, and they can


provide their own implementation for these methods.

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:

• During runtime, the appropriate method to execute is dynamically determined

• It is based on the actual type of the object invoking the method

4.Common Interface:

• Different subclasses sharing a common superclass interface

• Exhibits different behaviors based on their specific implementations.


5
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Polymorphism
The following example (Refer next slide) demonstrates all these key features of
runtime polymorphism.

In this example ‘Rectangle ‘ and ‘circle’ subclasses override the ‘calculate_area’


method from the ‘shape’ superclass to provide their specific area calculation.

The method ‘calculate_area’ is called on objects of different types(‘rect’ or ‘circle’) .


The appropriate overridden method is executed based on the object’s actual type.

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

rect = Rectangle(5, 10)


circle = Circle(4)

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.

Create a base class ‘Vehicle’ with a method ‘calculate_speed’.


Derive subclasses ‘Car’ and ‘Bike’ from ‘Vehicle’. Override the
‘calculate_speed’ method in each subclass to calculate their
specific speed based on different parameters.

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

An iterator is an object that allows iteration through a sequence of


elements, one at a time. It implements two main methods: __iter__() and
__next__().

__iter__():: returns the iterator object itself and is called when the iterator
is initialized.

__next__():: returns the next item in the sequence.

When there are no more elements to return, it raises the StopIteration


exception.

2
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Introduction

Iterators lazy object or Eager object?

Lazy Evaluation: Iterators follow the principle of lazy evaluation, meaning


they generate values on-demand rather than computing all values at once.

This can be memory-efficient when dealing with large datasets as it only


retrieves elements as needed.

3
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Custom Iterable Objects
The container class (like list) should support a function

1. __iter__(callable as iter(container-object)) which returns an object of a


class called an iterator.

2. __next__(callable as next(iterator_object))

These two functions are interfaces which can be implemented by


traversing through a container

Ex. we may visit only elements in odd position or elements satisfying a


boolean condition – like elements greater than 100
4
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Examples
Example 1:Creates an object of MyContainer whose attribute mylist refers to
the list a.
class MyContainer:
def __init__(self, mylist):
self.mylist = mylist
def __iter__(self):
self.i=0
return self
def __next__ (self):
self.i += 1
if self.i <= len(self.mylist):
return self.mylist[self.i - 1]
else: 5
raise StopIteration
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Examples

a = ['apple', 'banana', 'orange', 'dates', 'cherry’]

c = MyContainer(a)

for w in c :
print(w)

c = MyContainer(a)

Here, observe that it creates an object of MyContainer whose attribute


mylist refers to the list a

6
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Working of iterators

The for statement calls iter(c) which is changed to MyContainer.__iter__(c)

This __iter__ function adds a position attribute i to the object and then
returns the MyContainer object itself as the iterator object.

The for statement keeps calling next on this iterable 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:

• Programming error is an error which may occur because of various reasons.


Program can produce some errors even if the program is perfect.

• This may be because of


1. Exceptional situations that may occur during the execution of a program.
2. The data coming from outside the program which is malformed .

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“

2. Runtime Errors (Exceptions)


These are the errors which are detected during execution. This disrupts the
normal flow of execution of instructions.
Ex: Print("Good Morning")
#NameError: No name 'Print' found 3
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling

Exception Tree-Partial View

4
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling

Two categories of Exceptions:

1. Built-In exception (System defined exceptions )


Those exceptions which Python knows by default.

2. User defined exceptions


User-defined type/class written for handling the exceptions

5
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling
Exceptions Explanation

Keyboard Interrupt Raised when users hit Ctrl-C,the interrupt key

Overflow Error Raised when a floating-point expression evaluates to a value that is too large

ZeroDivision Error Raised when attempting to divide by 0

IO Error Raised when a sequence index is outside the range of valid indexes

Name Error Raised when attempting to evaluate an unassigned identifier

Type Error Raised when an operation or function is applied to an object wrong type
6
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling

Exception Handling( How to deal with errors?)


• Exception handling is a way to deal with errors or exceptional situations that
may occur during the execution of a program.
• It allows you to gracefully manage these situations instead of letting the
program crash.
• Python provides try, except, else, and finally blocks for handling exceptions.

Constructs used in Exception handling -


try, except, else, finally, raise
7
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling
try:

• Contains the code which might cause an exception

• It may have more than one except clause to specify handlers for different
exceptions.

• At most one handler(except) will be executed.

• 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.

• Can have multiple exceptions as a parameterized tuple.

• 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)

except: #default block

print("An exception occurred as x is not defined ")

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

print("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.")

except ValueError as e: #as keyword is used to create an object


print("Error:", e)
16
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling
Accessing Exception Information:

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:

print("Exception type:", type(e).__name__)


print("Exception details:", e) 17
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling
Matching of except blocks:

•The raised or thrown exception object is matched with the except blocks in
the order in which they occur in the try-except statement.

•The code following the first match is executed.

•It is always the first match and not the best match.

• If no match occurs and if there is a default except block, this will be


executed.

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: "))

result = num1 / num2 # This might raise a ZeroDivisionError

my_list = [1, 2, 3]

index = int(input("Enter an index for the list: "))


value = my_list[index] # This might raise an IndexError
19
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception Handling
except ValueError:
print("ValueError: Please enter a valid number.")

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

•Users can define custom exceptions by creating a new class.

•This exception class has to be derived, either directly or indirectly, from


the built-in Exception class.

•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 __init__(self, str):


self.str = str

def __str__(self):
return self.str

# check whether n is between 1 and 100


n = int(input("Enter a number:"))

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

You might also like