Unit 1
Unit 1
PROGRAMMING
Team Python
Chitra G M
Department of Computer Science and Engineering
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Introduction
• Based on procedures
Procedure • Routines,subroutines,functio
ns
Oriented • Series of computational
Programming steps to be carried out
• Fortran,Algol,C,Cobol
• Based on Objects-interact
with real world
Object • properties and behaviors are
Oriented bundled into
Programming individual objects
• Java,C#,C++,Python
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Object(1)
• Python supports different kinds of data
For Ex:10,10.57,”python”,
[1,5,7,8,9],{“language1”:”Python”,”language2”:”c”}
•Each data is considered as an object and each object
has
•An object has a name that uniquely identifies it
•An object has a set of individual properties which make it
original, unique or outstanding
•An object is an instance of a type.
•An object has a set of abilities to perform specific
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Object(1)
• Python supports different kinds of data
For Ex:10,10.57,”python”,
[1,5,7,8,9],{“language1”:”Python”,”language2”:”c”}
•Each data is considered as an object and each object
has
•An object has a name that uniquely identifies it
•An object has a set of individual properties which make it
original, unique or outstanding
•An object is an instance of a type.
•An object has a set of abilities to perform specific
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Object(2)
class ClassName:
<statement-1>
.
.
.
<statement-N>
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Classes
class student:
pass
print(student, type(student))
Output:
<class '__main__.student'> <class 'type'>
Instantiation
Attribute
A class can have
References
behavior
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Classes
Creating a variables of a given type(student)is called
as instantiation
class student:
pass
a = student()
print(a, type(a))
Output:
<__main__.student object at 0x7fdb9d725e48>
<class '__main__.student'>
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Classes
constructor.
Output:
constructor called
self : <__main__.abc object at 0x7f43d4e87860>
a : <__main__.abc object at 0x7f43d4e87860>
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Classes
• An object can have attributes
Output:
__init__ 20 10
20 10
Parameterized
Non-Parameterized
There are 2 types of constructors namely
class Person:
def __init__(self,name,age):
self.name = name
self.age = age Output:
def display(self):
print(self.name,self.age) joe 30
p = Person("joe",30)
p.display()
Instance
There are 2variables
types of constructors namelyto each instance and class variables are for attributes and methods shared by all instances of the class.
are for data unique
class Animal:
kind = 'dog' # class variable shared by all instances
def __init__(self, name):
self.name = name # instance variable unique to each
instance
dog
a= Animal('pinky') pinky
b = Animal('snow') snow
print( a.kind ) # shared by all dogs
print( b.kind ) # shared by all dogs
print( a.name) # unique to a
print( b.name ) # unique to b
THANK YOU
Team Python*
Department of Computer Science and Engineerin
Team Python
Chitra G M
Department of Computer Science and Engineering
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Introduction
Fundamental Concepts Of OOP in Python
• B i n di n g t oge t h e r d a t a a n d
Encapsulation
functions
class Person:
def __init__(self,name,age): Output:
self.name = name shaun
self.age = age
p = Person("shaun",14)
print(p.name)
Add
Output:
p.name =
Vinay
"Vinay"
print(p.name)
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an Attribu
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Encapsulation(3)
private attribute
•A double underscore __ is prefixed to a variable to make it
private
• It gives a strong suggestion not to touch it from outside the
class.class A:
def __init__(self,name,age):
•Any attempt to do so will result in an AttributeError
self.__name = name # Output:
private attribute AttributeError: 'A'
self.__age = age# private object has no
attribute attribute
x = A("Shaun",14) '__name'
print(x.__name)
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an Attribu
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Encapsulation(3)
Getter and Setter methods
• getters are the methods which help access the private
attributes or get the value of the private attributes
• setters are the methods which help change or set the
value of private attributes
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an Attribu
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Encapsulation(3)
class A:
def __init__(self,name =
"Shaun"):
self.__name = name
# make getter method Output:
def getname(self): Shaun
return self.__name joe
# make setter method
def setname(self,name):
self.__name = name
x = A()
print(x.getname())
x.setname("joe")
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an Attribu
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Inheritance(1)
•Powerful feature in object oriented programming
• Defines a class that inherits all the methods and
properties from another class.
•The new class is called derived (or child) class
•The one from which it inherits is called the base (or
parent) class.
• Derived class inherits features from the base class,
adding new features to it.
• Provides re-usability of code
•Inheritance establishes “is a” relationship between
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an Attribu
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Inheritance(2)
Syntax:
class Baseclass(Object):
body_of_base_class class
DerivedClass(BaseClass):
body_of_derived_class
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an Attribu
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Inheritance(3)
class A:
pass
Output:
class B(A):
True
pass
issubclass(B,A)
Output
dog barking
Animal Speaking
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an Attribu
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Inheritance(5)
class Base:
def __init__(self,subject):
self.subject= subject
def __str__(self):
return "The subject name is " + Output:
self.subject + "." The subject
class Derived(Base): name is Python
def __init__(self, name):
Base.__init__(self, name)
obj = Derived("Python")
print(obj)
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an Attribu
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Inheritance(5)
class A1:
def __init__(self):
self.abc = 111
class B1(A1):
def __init__(self): Output:
super().__init__() 111
self.pqr = 222 222
obj = B1()
print(obj.abc)
print(obj.pqr)
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an Attribu
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Inheritance(6)-Order to access an object’s entity
class myObj:
name = "John" Output:
y = myObj() True
x = isinstance(y, myObj)
print(x)
THANK YOU
Team Python*
Department of Computer Science and Engineerin
Chitra G M
Computer Science and
Engineering
PYTHON APPLICATION PROGRAMMING
Introduction
Chitra G M
Department of Computer Science and Engineering
PYTHON APPLICATION PROGRAMMING
Design Pattern
(wiki definition)
PYTHON APPLICATION PROGRAMMING
Design Pattern
Singleton class
s1=single()
print(s1)
THANK YOU
Chitra G M
Department of Computer Science and Engineering
[email protected]
+91 9900300411
PYTHON APPLICATION
PROGRAMMING
Chitra G M
Computer Science and
Engineering
PYTHON APPLICATION PROGRAMMING
Introduction
Chitra G M
Department of Computer Science and Engineering
PYTHON APPLICATION PROGRAMMING
Design Pattern
Facade
Courtesy :Study.com
PYTHON APPLICATION PROGRAMMING
Design Pattern
Facade
Courtesy :Study.com
PYTHON APPLICATION PROGRAMMING
Design pattern
Façade Example
PYTHON APPLICATION PROGRAMMING
Program
class ProcessingUnit:
'''Subsystem #1'''
def process(self):
print("Processing...")
class DisplayUnit:
'''Subsystem #2'‘’
def display(self):
print("Displaying...")
class Memory:
'''Subsystem #3'‘’
def ioOperation(self):
print("Reading and writing to memory...")
PYTHON APPLICATION PROGRAMMING
Program
class ProcessingUnit:
'''Subsystem #1'''
def process(self):
print("Processing...")
class DisplayUnit:
'''Subsystem #2'‘’
def display(self):
print("Displaying...")
class Memory:
'''Subsystem #3'‘’
def ioOperation(self):
print("Reading and writing to memory...")
PYTHON APPLICATION PROGRAMMING
Design Pattern
class Computer:
'''Facade'''
def __init__(self):
self.processingUnit = ProcessingUnit()
self.displayUnit = DisplayUnit()
self.memory = Memory()
def bootUp(self):
self.processingUnit.process()
self.memory.ioOperation()
self.displayUnit.display()
computer = Computer()
computer.bootUp()
THANK YOU
Chitra G M
Department of Computer Science and Engineering
[email protected]
+91 9900300411
PYTHON APPLICATION
PROGRAMMING
Chitra G M
Exceptions
Chitra G M
Department of Computer Science and Engineering
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Introduction
Example
a=8
b = 10
c=ab Syntax Error :Invalid syntax
(3+4]
Built-In exceptions
There are a number of exceptions which Python knows. We call
them built-in exceptions. The table below lists few of the built-in
exceptions.
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Built-in Exceptions
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 an I/O operation fails for an
I/O related reason
Index Error Raised when a sequence index is outside
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Built-in Exceptions Contd..
Exceptions Output
>>> 6/0 ZeroDivisionError: division by zero
>>> lst=[1,4,5] IndexError: list index out of range
>>> lst[3]
>>> a+10 NameError: name 'a' is not defined
>>> '2'*'6' TypeError: can't multiply sequence by
non-int of type 'str'
>>> int('3.5') ValueError: invalid literal for int() with
base 10: '3.5'
try :
#statements in try block
except :
#executed when error in try block
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
try, except blocks
The try: block contains one or more statements which are likely
to encounter an exception. If the statements in this block are
executed without an exception, the subsequent except: block is
skipped.
try:
print(x)
except:
print("An exception occurred as x is not defined ")
Output:
An exception occurred as x is not defined
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
try, except – example -2
Output:
Python exception raised
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Multiple except clause
• It is always the first match and not the best match. The code
following the first match is executed. If no match occurs and
there is an default except block (with no exception specified),
then that block will be executed.
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Multiple except clause – example
try:
a=5
b=0
print (a/b)
except TypeError:
print('Unsupported operation')
except ZeroDivisionError:
print ('Division by zero not allowed')
print ('Out of try except blocks')
Output:
Division by zero not allowed
Out of try except blocks
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
else keyword in try – except block
try:
print("Hello") Output:
except: Hello
print("Something went wrong") Nothing went wrong
else:
print("Nothing went wrong")
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Raising exception
raise Exception1name(<message>)
def Foo(number):
raise ZeroDivisionError Output:
try: An error occurred
Foo(0) terminate
except ArithmeticError:
print("An error occurred")
print("terminate")
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Raising exception – example 2
try:
x=int(input('Enter a number upto 100: '))
if x > 100:
raise ValueError(x)
except ValueError:
print(x, "is out of allowed range")
else:
print(x, "is within the allowed range")
Output: Output:
Enter a number upto 100: 45 Enter a number upto 100: 120
45 is within the allowed range 120 is out of allowed range
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Finally keyword in try except block
i) Normal flow
try block – finally block if any – code following try block
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Finally keyword in try except block
Syntax
try:
#statements in try block
except:
#executed when error in try block
finally:
#executed irrespective of exception occurred or not
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Finally keyword – example
def division(n):
try:
n=1/n Output:
except ZeroDivisionError: code is correct
print("Division failed") finally is executed
n = None 0.25
else: Division failed
print("code is correct")
finally:
print("finally is executed")
return n
print(division(4))
print(division(0))
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
User defined Exceptions
Most of the built-in exceptions are also derived from this class.
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
User defined Exceptions – example
class MyException(Exception):
def __init__(self, str): Output: When
self.str = str 1<=n<=100
def __str__(self): enter a number:5
return self.str number is fine : 5
n = int(input("enter a number:")) thats all
try:
if not 1 <= n <= 100 :
raise MyException("number Output: When n>=100
not in range") enter a number:105
print("number is fine : ", n) number not in range
except MyException as e: thats all
print(e)
print("thats all")
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception propagation
def mathOp(n):
try: Output: When n=0
return 1 / n Division not possible
except ArithmeticError: successfully completed
print("Division not possible")
return None
Output: When n=10
mathOp(0) successfully completed
mathOp(10)
print("successfully completed")
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception propagation – example 2
Team Python*
Department of Computer Science and Engineering
Prof. Shilpa S
Assistant Professor
Prof. Shilpa S
Department of Computer Science and Engineering
PYTHON APPLICATION PROGRAMMING
Iterators
Example:
string = “PYTHON"
ch= iter(string)
Output:
print(next(ch)) P
print(next(ch)) Y
print(next(ch)) T
print(next(ch)) H
print(next(ch)) O
print(next(ch)) N
PYTHON APPLICATION PROGRAMMING
Iterable vs Iterator
Example:
#Function to check object is iterable or not
def it(ob):
34 is iterable : False
try:
iter(ob) [4, 5] is iterable : True
return True (4, 5) is iterable : True
except TypeError: {'a': 4} is iterable : True
return False
dfsdf is iterable : True
for i in [34, [4, 5], (4, 5),{"a":4}, "dfsdf", 4.5]:
print(i,"is iterable :",it(i)) 4.5 is iterable : False
PYTHON APPLICATION PROGRAMMING
Generators
In this example, we will create two generators for Fibonacci Numbers, first a simple
generator and second generator using a for loop. def fib(limit):
a, b = 0, 1
0 while a < limit:
1 yield a
1 a, b = b, a + b
x = fib(5)
2
print(next(x))
3 print(next(x))
Using for in loop print(next(x))
0 print(next(x))
1 print(next(x))
1
print("\nUsing for in loop")
2 for i in fib(5):
3 print(i)
PYTHON APPLICATION PROGRAMMING
Closures
A function object that remembers values in enclosing scopes even when the
variable goes out of scope
Output:
this is an example of closure
PYTHON APPLICATION PROGRAMMING
Closures
• The function print() has its scope only inside the print_msg. But with the use
of closures we can easily extend its scope to invoke a function outside its
scope
PYTHON APPLICATION PROGRAMMING
Closures
1. Example:
def f1(): #outer function Output:
def f2(): #inner function f2= 2908823806840
print ("Hello") Hello
print ("world") world
print('f2=',id(f2)) c= 2908823806840
return f2
c=f1() #refers to f2()
c()
print('c=',id(c)) #id of f2() and c() are same
PYTHON APPLICATION PROGRAMMING
Closures
2. Example:
def outerfunc(x):
Output:
def innerfunc():
7 49
print(x*x)
7 49
return innerfunc
myfunc=outerfunc(7)
myfunc() #refers to innerfunc()
del outerfunc
myfunc() #still refers to innerfunc() retaining the value of enclosing scope of x
PYTHON APPLICATION PROGRAMMING
Callback
def fun1():
print("Within fun1")
def fun2():
print("Within fun2") Within fun1
def outer(x): Within fun2
x()
outer(fun1)
outer(fun2)
PYTHON APPLICATION PROGRAMMING
Callback : Example2
def fun1():
a,b = 12,45
sum = a+b
57
print(sum)
Within fun1
print("Within fun1")
5
def fun2(p,q):
Within fun2
div = p//q
print(div)
print("Within fun2")
def outer(x,y):
v1,v2 = 25,5
x()
y(v1,v2)
outer(fun1,fun2)
PYTHON APPLICATION PROGRAMMING
Callback : Example3
def fun1(*a):
sum = a[0]+a[1]+a[2]//a[0]-a[1]
print(sum) 25
print("Within fun1") Within fun1
def fun2(*p): 120
div = p[0]*p[1]*p[2]*p[3] Within fun2
print(div)
print("Within fun2")
def outer(x,*v1):
x(*v1)
outer(fun1,23,45,67)
outer(fun2,5,2,3,4)
PYTHON APPLICATION PROGRAMMING
Memoization
memory = {}
def memoize_factorial(f):
# This inner function has access to memory and 'f'
def inner(num):
if num not in memory:
memory[num] = f(num)
print('result saved in memory')
else:
print('returning result from saved memory')
return memory[num]
return inner
PYTHON APPLICATION PROGRAMMING
Memoization
Prof. Shilpa S
Assistant Professor