Python Programming - Unit 4 (1)
Python Programming - Unit 4 (1)
PROGRAMMING AND
Exceptions, I/O and OOP PRODUCT DEVELOPMENT
CO 1
Course description
This course aims to teach everyone the core of
programming computers using Python. We cover
CO 2
python programming from basics to core. The course
has no pre-requisites and avoids all but the simplest
mathematics. Anyone with moderate computer
experience should be able to master the materials in
this course. This course will cover Python data types,
functions, control and looping constructs, regular
expressions, user interface modules and the data
analytic packages. Once a student completes this
CO 4. course, they will be ready to perform core python
problem solving and also develop their own python
packages. This course covers Python 3.
CO 5.
Topic 2
Errors and Exception
Topic 3
Error Types
Topic 4
Exception Handling
•Error handling increases the robustness of your code, which guards against potential failures that would
cause your program to exit in an uncontrolled fashion.
•Errors cannot be handled, while Python exceptions can be handled at the run time.
•An error can be a syntax (parsing) error, while there can be many types of exceptions that could occur
during the execution and are not unconditionally inoperable.
•An Error might indicate critical problems that a reasonable application should not try to catch.
•An Exception might indicate conditions that an application should try to catch.
•Errors are a form of an unchecked exception and are irrecoverable like an OutOfMemoryError, which a
programmer should not try to handle.
•Syntax Error
•Recursion Error
•Exceptions
Syntax errors often called as parsing errors, are predominantly caused when the parser detects a syntactic
issue in your code.
Syntax Error
The above red mark indicates when the parser ran into an error while executing the code. The token
preceding the red mark causes the failure. To rectify such fundamental errors, Python will do most of your
job since it will print for you the file name and the line number at which the error occurred.
•Memory errors are mostly dependent on your systems RAM and are related to Heap.
•If you have large objects (or) referenced objects in memory, then you will see OutofMemoryError
(Source). It can be caused due to various reasons:
• Using a 32-bit Python Architecture (Maximum Memory Allocation given is very low, between 2GB - 4GB).
• Loading a very large data file
• Running a Machine Learning/Deep Learning model and many more.
•As the name suggests, recursion error transpires when too many methods, one inside another is executed
(one with an infinite recursion), which is limited by the size of the stack.
Recursion
Error
•Indentation error is similar in spirit to the syntax error and falls under it.
Indentation
Error
Even if the syntax of a statement or expression is correct, it may still cause an error when executed.
Python exceptions are errors that are detected during execution and are not unconditionally fatal.
•When an error occurs, or exception as we call it, Python will normally stop and generate an error message.
•The try block lets you test a block of code for errors.
•The finally block lets you execute code, regardless of the result of the try- and except blocks.
output
amount = 10000
output
marks = 10000
output
except IndexError:
print "An error occurred"
output
Second element = 2
An error occurred
output
output
-5.0
a/b result in 0
try:
k = 5//0 # raises divide by zero exception.
print(k)
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed’)
output
try:
raise NameError("Hi there") # Raise Error
except NameError:
print "An exception"
raise # To determine whether the exception was raised or not
output
data = 50
try:
data = data/0
except ZeroDivisionError:
print('Cannot divide by 0 ', end = '')
else:
print('Division successful ', end = '')
try:
data = data/5
except:
print('Inside except block ', end = '')
else:
print('GFG', end = ‘’)
output
data = 50
try:
data = data/10
except ZeroDivisionError:
print('Cannot divide by 0 ', end = '')
finally:
print('GeeksforGeeks ', end = '')
else:
print('Division successful ', end = ‘’)
output
Runtime error
value = [1, 2, 3, 4]
data = 0
try:
data = value[4]
except IndexError:
print('GFG', end = '')
except:
print('GeeksforGeeks ', end = ‘’)
output
GFG
value = [1, 2, 3, 4, 5]
try:
value = value[5]/0
except (IndexError, ZeroDivisionError):
print(‘Great ', end = '')
else:
print('GFG ', end = '')
finally:
print(‘Welcome ', end = ‘’)
output
Great Welcome
def foo():
try:
return 1
finally:
return 2
k = foo()
print(k)
output
def foo():
try:
print(1)
finally:
print(2)
foo()
output
12
def f(x):
yield x+1
g=f(8)
print(next(g))
output
try:
if '1' != 1:
raise "someError"
else:
print("someError has not occurred")
except "someError":
print ("someError has occurre d")
output
invalid code
def f(x):
yield x+1
print("test")
yield x+2
g=f(9)
output
No output
def f(x):
yield x+1
print("test")
yield x+2
g=f(10)
print(next(g))
print(next(g))
output
11 test 12
def a():
try:
f(x, 4)
finally:
print('after f')
print('after f?')
a()
output
error
def f(x):
for i in range(5):
yield i
g=f(8)
print(list(g))
output
[0, 1, 2, 3, 4]
g = (i for i in range(5))
type(g)
output
class <’generator’>
a=False
while not a:
try:
f_n = input("Enter file name")
i_f = open(f_n, 'r')
except:
print("Input file not found")
output
No error
output
IndexError
output
TypeError
int('65.43')
output
ValueError
def getMonth(m):
if m<1 or m>12:
raise ValueError("Invalid")
print(m)
getMonth(6)
output
valid = False
while not valid:
try:
n=int(input("Enter a number"))
while n%2==0:
print("Bye")
valid = True
except ValueError:
print("Invalid")
output
❑Error handling increases the robustness of your code, which guards against potential failures that would
cause your program to exit in an uncontrolled fashion.
❑ Errors cannot be handled, while Python exceptions can be handled at the run time.
❑ Recursion error is is related to stack and occurs when you call functions.
❑ Indentation error is similar in spirit to the syntax error and falls under it.
❑ When an error occurs, or exception as we call it, Python will normally stop and generate an error
message.
•The io module provides Python’s main facilities for dealing with various types of I/O.
•There are three main types of I/O: text I/O, binary I/O and raw I/O.
•These are generic categories, and various backing stores can be used for each of them.
•A concrete object belonging to any of these categories is called a file object. Other common terms are
stream and file-like object.
•Independent of its category, each concrete stream object will also have various capabilities: it can be read-
only, write-only, or read-write.
•It can also allow arbitrary random access (seeking forwards or backwards to any location), or only
sequential access (for example in the case of a socket or pipe)
•All streams are careful about the type of data you give to them. For example giving a str object to the
write() method of a binary stream will raise a TypeError.
•So will giving a bytes object to the write() method of a text stream.
•Changed in python version 3.3: Operations that used to raise IOError now raise OSError, since IOError
is now an alias of OSError
•Text I/O expects and produces str objects. This means that whenever the backing store is natively made of
bytes (such as in the case of a file), encoding and decoding of data is made transparently as well as
optional translation of platform-specific newline characters.
•The easiest way to create a text stream is with open(), optionally specifying an encoding:
•Binary I/O (also called buffered I/O) expects bytes-like objects and produces bytes objects.
•This category of streams can be used for all kinds of non-text data, and also when manual control over the
handling of text data is desired.
•The easiest way to create a binary stream is with open() with 'b' in the mode string:
•Raw I/O (also called unbuffered I/O) is generally used as a low-level building-block for binary and text
streams;
•It is rarely useful to directly manipulate a raw stream from user code. Nevertheless, you can create a raw
stream by opening a file in binary mode with buffering disabled:
•The key function for working with files in Python is the open() function.
•The open() function returns a file object, which has a read() method for reading the content of the file:
•By default the read() method returns the whole text, but you can also specify how many characters you
want to return:
•By looping through the lines of the file, you can read the whole file, line by line:
•It is a good practice to always close the file when you are done with it.
•To write to an existing file, you must add a parameter to the open() function:
▪ "a" - Append - will append to the end of the file
▪ "w" - Write - will overwrite any existing content
•Open the file in “w” mode to overwrite the contents of the file
•To create a new file in Python, use the open() method, with one of the following parameters:
▪ "x" - Create - will create a file, returns an error if the file exist
▪ "a" - Append - will create a file if the specified file does not exist
▪ "w" - Write - will create a file if the specified file does not exist
To delete a file, you must import the OS module, and run its os.remove() function
To avoid getting an error, you might want to check if the file exists before you try to delete it
fo = open("sample.txt", "wb")
print ("File Name: ", fo.name)
data = f.read()
with open('filename.txt') as f:
for line in f :
print
file1 = open("myfile.txt","w") file1.seek(0)
L = ["This is Delhi \n","This is Paris \n","This is London \n"] print "Output of Readline(9) function is "
# \n is placed to indicate EOL (End of Line) print file1.readline(9)
file1.write("Hello \n")
file1.seek(0)
file1.writelines(L)
file1.close() #to change file access modes
# readlines function
file1 = open("myfile.txt","r+") print "Output of Readlines function is "
print "Output of Read function is " print file1.readlines()
print file1.read() print
Print file1.close()
# seek(n) takes the file handle to the nth
# bite from the beginning. output
file1.seek(0)
print "Output of Readline function is " Output of Read function is
print file1.readline() Hello
print
This is Delhi
file1.seek(0)
This is Paris
# To show difference between read and readline
print "Output of Read(9) function is " This is London
print file1.read(9)
file1 = open("myfile.txt","w")
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
file1.close() output
# Append-adds at last
file1 = open("myfile.txt","a")#append mode
file1.write("Today \n")
Output of Readlines after appending
file1.close() ['This is Delhi \n', 'This is Paris \n', 'This is London \n', 'Today
file1 = open("myfile.txt","r") \n']
print "Output of Readlines after appending"
print file1.readlines() Output of Readlines after writing
print ['Tomorrow \n']
file1.close()
# Write-Overwrites
file1 = open("myfile.txt","w")#write mode
file1.write("Tomorrow \n")
file1.close()
file1 = open("myfile.txt","r")
print "Output of Readlines after writing"
print file1.readlines()
print
file1.close()
❑ Python consists of three main types of I/O: text I/O, binary I/O and raw I/O.
❑ Independent of its category, each concrete stream object will also have various capabilities: it can be
read-only, write-only, or read-write.
❑ There are four different methods (modes) for opening a file: read 'r', append 'a', write 'w', create 'c'
❑ In addition you can specify if the file should be handled as binary 'b' or text 't' mode
❑ To delete a file, you must import the OS module, and run its os.remove() function
f = None
for i in range (5):
with open("data.txt", "w") as f:
if i > 2:
break
print(f.closed)
output
True
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
output
Displays Output
import sys
sys.stdout.write(' Hello\n')
sys.stdout.write('Python\n’)
output
Hello Python
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
fo.flush()
fo.close()
output
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
fo.flush()
fo.close()
output
Topic 2
Object
Topic 3
Inheritance
Topic 4
Encapsulation
Topic 5
Polymorphism
Fourth Lesson Outline
We will be learning about Object Oriented
Programming
An object (instance) is an instantiation of a class. When class is defined, only the description for the object
is defined. Therefore, no memory or storage is allocated.
The example for object of parrot class can be:
Obj=student()
Here Obj is an object of class student
output
Blu is a Student
Woo is also a Student
Blu regno is 10
Woo regno is 15
output
Blu sings 'Happy'
Blu is now dancing
Inheritance is a way of creating a new class for using details of an existing class without modifying it. The
newly formed class is a derived class (or child class). Similarly, the existing class is a base class (or parent
class).
Using OOP in Python, we can restrict access to methods and variables. This prevents data from direct
modification which is called encapsulation.
Polymorphism is an ability (in OOP) to use a common interface for multiple forms (data types).
Suppose, we need to color a shape, there are multiple shape options (rectangle, square, circle). However
we could use the same method to color any shape. This concept is called Polymorphism.
Python is an object oriented programming language. Unlike procedure oriented programming, where the main
emphasis is on functions, object oriented programming stresses on objects.
An object is simply a collection of data (variables) and methods (functions) that act on those data. Similarly, a
class is a blueprint for that object.
We can think of class as a sketch (prototype) of a house. It contains all the details about the floors, doors,
windows etc. Based on these descriptions we build the house. House is the object.
As many houses can be made from a house's blueprint, we can create many objects from a class. An object is
also called an instance of a class and the process of creating this object is called instantiation.
Like function definitions begin with the def keyword in Python, class definitions begin with a class
keyword.
A class creates a new local namespace where all its attributes are defined. Attributes may be data or
functions.
output
10
<function Person.greet at >
This is a person class
We saw that the class object could be used to access different attributes.
It can also be used to create new object instances (instantiation) of that class. The procedure to create an
object is similar to a function call.
Syntax
Ram = Person()
def greet(self):
print('Hello')
# create a new object of Person class
ram = Person()
# Output: <function Person.greet>
print(Person.greet)
Class functions that begin with double underscore are called special functions as they have special
meaning.
class Test:
# A sample method
def fun(self):
print("Hello")
# Driver code
obj = Test()
obj.fun()
output
Hello
class Person:
# init method or constructor
def init (self, name):
self.name = name
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
p = Person(‘John')
p.say_hi()
output
# Class Variable
# Class Variable
stream = 'cse'
stream = 'cse'
# The init method or constructor
# The init method or constructor def init (self, roll):
def init (self, roll):
# Instance Variable
self.roll = roll
# Instance Variable
self.roll = roll # Adds an instance variable
def setAddress(self, address):
# Objects of CSStudent class self.address = address
a = CSStudent(101)
# Retrieves instance variable
b = CSStudent(102) def getAddress(self):
return self.address
print(a.stream) # prints "cse"
print(b.stream) # prints "cse" # Driver Code
print(a.roll) # prints 101 a = CSStudent(101)
a.setAddress(“Tamilnadu, India")
print(a.getAddress())
# Class variables can be accessed using class
# name also output
print(CSStudent.stream) # prints "cse
Tamilnadu India
output
From str method of Test: a is 1234,b is 5678
[Test a:1234 b:5678]
output
# Driver Code
t = Test(1234, 5678)
print(t)
output
output
(‘emp1', False)
(‘emp2', True
class Derived(Base):
pass # Empty Class
# Driver Code
print(issubclass(Derived, Base))
print(issubclass(Base, Derived))
d = Derived()
b = Base()
output
True
False
False
True
output
Base1
Base2
Derived
('Geek1', 'Geek2')
output
(10, 20)
output
Base1
Base2
Derived
(‘emp1', ‘emp2')
output
(10, 20)
output
4
8
24
def isEmployee(self):
return True
def getID(self):
return self.empID
# Driver code
emp = Employee(“emp1", "E101")
print(emp.getName(), emp.isEmployee(), emp.getID())
output
(‘emp1', True, 'E101')
21 output
21
True
class Student:
def init (self,name,id):
self.name=name
self.id=id
print(self.id
)
std=Student("Simon",1)
std.id=2
print(std.id)
output
1
2
class A:
def init (self):
self.count=5
self.count=count+1
a=A()
print(a.count)
output
Error
class Book:
definit (self,author):
self.author=author
book1=Book("V.M.Shah")
book2=book1
output
class A:
def init (self,num):
num=3
self.num=num
def change(self):
self.num=7
a=A(5)
print(a.num)
a.change()
print(a.num)
output
3
7
1
23
456
7 8 9 10
11 12 13 14 15
Example: Half Pyramid of Stars (*)
*
**
***
****
*****
Example:Inverted Half Pyramid of Stars (*)
*****
****
***
**
*
Example: Full Pyramid of Stars (*)
>>> class A:
pass
>>> class B(A):
pass
>>> obj=B()
>>> isinstance(obj,A)
output
True
class A:
def init (self):
self. x = 1
class B(A):
def display(self):
print(self. x)
def main():
obj = B()
obj.display()
main()
output
class A:
def init (self):
self._x = 5
class B(A):
def display(self):
print(self._x)
def main():
obj = B()
obj.display()
main()
output
class A:
def init (self,x=3):
self._x = x
class B(A):
def init (self):
super(). init (5)
def display(self):
print(self._x)
def main():
obj = B()
obj.display()
main()
output
5
class A:
def test1(self):
print(" test of A called ")
class B(A):
def test(self):
print(" test of B called ")
class C(A):
def test(self):
print(" test of C called ")
class D(B,C):
def test2(self):
print(" test of D called ")
obj=D()
obj.test()
output
test of B called
class A:
def str (self):
return '1'
class B(A):
def init (self):
super(). init ()
class C(B):
def init (self):
super(). init ()
def main():
obj1 = B()
obj2 = A()
obj3 = C()
print(obj1, obj2,obj3)
main()
output
111
class Demo:
def init (self):
self.x = 1
def change(self):
self.x = 10
class Demo_derived(Demo):
def change(self):
self.x=self.x+1
return self.x
def main():
obj = Demo_derived()
print(obj.change())
main()
output
class A:
def repr (self):
return "1"
class B(A):
def repr (self):
return "2"
class C(B):
def repr (self):
return "3"
o1 = A()
o2 = B()
o3 = C()
print(obj1, obj2, obj3)
output
123
output
30
class Demo:
def check(self):
return " Demo's check "
def display(self):
print(self.check())
class Demo_Derived(Demo):
def check(self):
return " Derived's check "
Demo().display()
Demo_Derived().display()
output
class A:
def init (self):
self.multiply(15)
def multiply(self, i):
self.i = 4 * i;
class B(A):
def init (self):
super(). init ()
print(self.i)
output
30
output
output
True
output
output
output
output
output
output
class student:
def init (self):
self.marks = 97
self. cgpa = 8.7
def display(self):
print(self.marks)
obj=student()
print(obj._student cgpa)
output
output
Topic 2
Abstract Super Class
In object-oriented languages like Python, the interface is a collection of method signatures that should be
provided by the implementing class. Implementing an interface is a way of writing an organized code and
achieve abstraction.
In python, interface is defined using python class statements and is a subclass of interface.Interface which
is the parent interface for all interfaces.
Syntax :
class IMyInterface(zope.interface.Interface):
# methods and attributes
# get attribute
x = MyInterface['x']
print(x)
print(type(x))
output
<class zope.interface.interface.InterfaceClass>
main
MyInterface
<zope.interface.interface.Attribute object at 0x00000270A8C74358>
<class 'zope.interface.interface.Attribute'>
An abstract class can be considered as a blueprint for other classes. It allows you to create a set of
methods that must be created within any child classes built from the abstract class.
A class which contains one or more abstract methods is called an abstract class. An abstract method is a
method that has a declaration but does not have an implementation. While we are designing large
functional units we use an abstract class. When we want to provide a common interface for different
implementations of a component, we use an abstract class.
By subclassing directly from the base, we can avoid the need to register the class explicitly. In this case,
the Python class management is used to recognize Plugin Implementation as implementing the abstract
Plugin Base.
In object-oriented languages like Python, the interface is a collection of method signatures that should be
provided by the implementing class. Implementing an interface is a way of writing an organized code and
achieve abstraction.
In python, interface is defined using python class statements and is a subclass of interface.Interface which
is the parent interface for all interfaces.
Syntax :
class IMyInterface(zope.interface.Interface):
# methods and attributes
import abc
class parent:
def geeks(self):
pass
class child(parent):
def geeks(self):
print("child class")
# Driver code
print( issubclass(child, parent))
print( isinstance(child(), parent))
output
True
True
Concrete classes contain only concrete (normal)methods whereas abstract classes may contain both
concrete methods and abstract methods. The concrete class provides an implementation of abstract
methods, the abstract base class can also provide an implementation by invoking the methods via super().
output
Abstract classes include attributes in addition to methods, you can require the attributes in concrete classes
by defining them with @abstractproperty.
class parent(ABC):
@abc.abstractproperty
def geeks(self):
return "parent class"
class child(parent):
@property
def geeks(self):
return "child class"
try:
r =parent()
print( r.geeks)
except Exception as err:
print (err)
r = child()
print (r.geeks).
output
Can't instantiate abstract class parent with abstract methods geeks
child class
© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING
Abstract Class Instantiation :
Abstract classes are incomplete because they have methods that have nobody. If python allows creating an
object for abstract classes then using that object if anyone calls the abstract method, but there is no actual
implementation to invoke.
class Lion(Animal):
def move(self):
print("I can roar")
c=Animal()
output
Traceback (most recent call last):
File "/home/ffe4267d930f204512b7f501bb1bc489.py", line 19, in
c=Animal()
TypeError: Can't instantiate abstract class Animal with abstract methods move
class test:
def init (self,a="Hello World"):
self.a=a
def display(self):
print(self.a)
obj=test()
obj.display(
output
class change:
def init (self, x, y, z):
self.a = x + y + z
x = change(1,2,3)
y = getattr(x, 'a')
setattr(x, 'a', y+1)
print(x.a)
output
class test:
def init (self,a):
self.a=a
def display(self):
print(self.a)
obj=test()
obj.display()
output
class test:
def init (self):
self.variable = 'Old'
self.Change(self.variable)
def Change(self, var):
var = 'New'
obj=test()
print(obj.variable
)
output
‘Old’ is printed
class fruits:
def init (self, price):
self.price = price
obj=fruits(50)
obj.quantity=10
obj.bags=2
print(obj.quantity+len(obj. dict ))
output
13
class Demo:
def init (self):
pass
def test(self):
print( name )
obj = Demo()
obj.test()
output
main
def add(c,k):
c.test=c.test+1
k=k+1
class A:
def init (self):
self.test = 0
def main():
Count=A()
k=0
for i in range(0,25):
add(Count,k)
print("Count.test=", Count.test)
print("k =", k)
main()
output
Count.test=25 k=0
output
str called
output
str called
class stud:
def init (self, roll_no, grade):
self.roll_no = roll_no
self.grade = grade
def display (self):
print("Roll no : ", self.roll_no, ", Grade: ", self.grade)
stud1 = stud(34, 'S')
stud1.age=7
print(hasattr(stud1, 'age’))
output
True
class stud:
‘Base class for all students’
def init (self, roll_no, grade):
self.roll_no = roll_no
self.grade = grade
def display (self):
print("Roll no : ", self.roll_no, ", Grade: ", self.grade)
print(student. doc )
output
class stud:
‘Base class for all students’
def init (self, roll_no, grade):
self.roll_no = roll_no
self.grade = grade
def display (self):
print("Roll no : ", self.roll_no, ", Grade: ", self.grade)
print(student. doc )
output
class People():
def namePrint(self):
print("Name: " + self.name)
person1 = People("Sally")
person2 = People("Louise")
person1.namePrint()
output
Sally
class People():
def namePrint(self):
print("Name: " + self.name)
person1 = People("Sally")
person2 = People("Louise")
person1.namePrint()
output
As we are not updating any values, 'self' is not needed in def namePrint(self):
class Test:
def init (self):
self.x = 0
class Derived_Test(Test):
def init (self):
Test. init (self)
self.y = 1
def main():
b = Derived_Test()
print(b.x,b.y)
main()
output
01
class A:
def init (self, x= 1):
self.x = x
class der(A):
def init (self,y = 2):
super(). init ()
self.y = y
def main():
obj = der()
print(obj.x, obj.y)
main(
output
12
class A:
def one(self):
return self.two()
def two(self):
return 'A'
class B(A):
def two(self):
return 'B'
obj1=A()
obj2=B()
print(obj1.two(),obj2.two())
output
AB
class A:
def init (self):
self. x = 1
class B(A):
def display(self):
print(self. x)
def main():
obj = B()
obj.display()
main()
output
class A:
def init (self):
self. x = 5
class B(A):
def display(self):
print(self. x)
def main():
obj = B()
obj.display()
main()
output
class A:
def init (self,x=3):
self._x = x
class B(A):
def init (self):
super(). init (5)
def display(self):
print(self._x)
def main():
obj = B()
obj.display()
output
5
class A:
def test1(self):
print(" test of A called ")
class B(A):
def test(self):
print(" test of B called ")
class C(A):
def test(self):
print(" test of C called ")
class D(B,C):
def test2(self):
print(" test of D called ")
obj=D()
obj.test()
output
test of B called
class A:
def test(self):
print("test of A called")
class B(A):
def test(self):
print("test of B called")
super().test()
class C(A):
def test(self):
print("test of C called")
super().test()
class D(B,C):
def test2(self):
print("test of D called")
obj=D()
obj.test(
output
test of B called
test of C called
test of A called
class A:
def repr (self):
return "1"
class B(A):
def repr (self):
return "2"
class C(B):
def repr (self):
return "3"
o1 = A()
o2 = B()
o3 = C()
print(obj1, obj2, obj3)
output
123
class A:
def init (self):
self.multiply(15)
print(self.i)
class Demo:
def check(self):
return " Demo's check "
def display(self):
print(self.check())
class Demo_Derived(Demo):
def check(self):
return " Derived's check "
Demo().display()
Demo_Derived().display()
output
class A:
def init (self):
self.multiply(15)
def multiply(self, i):
self.i = 4 * i;
class B(A):
def init (self):
super(). init ()
print(self.i)
output
30
class Demo:
def check(self):
return " Demo's check "
def display(self):
print(self.check())
class Demo_Derived(Demo):
def check(self):
return " Derived's check "
Demo().display()
Demo_Derived().display()
output
class A:
def init (self, x, y):
self.x = x
self.y = y
def str (self):
return 1
def eq (self, other):
return self.x * self.y == other. x * other.y
obj1 = A(5, 2)
obj2 = A(2, 5)
print(obj1 == obj2)
output
True
class A:
def one(self):
return self.two()
def two(self):
return 'A'
class B(A):
def two(self):
return 'B'
obj2=B()
print(obj2.two()))
output
B
class fruits:
def init (self):
self.price = 100
self. bags = 5
def display(self):
print(self. bags)
obj=fruits()
obj.display()
output
class student:
def init (self):
self.marks = 97
self. cgpa = 8.7
def display(self):
print(self.marks)
obj=student()
print(obj._student cgpa)
output
class objects:
def init (self):
self.colour = None
self._shape = "Circle"
output
x=10
y=8
assert x>y, 'X too small')
output
No Output
def f(x):
yield x+1
g=f(8)
print(next(g))
output
def f(x):
yield x+1
print("test")
yield x+2
g=f(9)
output
No Output
def f(x):
yield x+1
print("test")
yield x+2
g=f(9)
output
No Output
def f(x):
yield x+1
print("test")
yield x+2
g=f(10)
print(next(g))
print(next(g))
output
11
def a():
try:
f(x, 4)
finally:
print('after f')
print('after f?')
a()
output
error
def f(x):
for i in range(5):
yield i
g=f(8)
print(list(g))
output
[0,1,2,3,4]
import itertools
l1=(1, 2, 3)
l2=[4, 5, 6]
l=itertools.chain(l1, l2)
print(next(l1))
output
g = (i for i in range(5))
type(g)
output
Class<‘generator’>