Unit-4 NOTES
Unit-4 NOTES
Q1Sieve of Eratosthenes is a method for finding all primes up to (and possibly including) a
given natural. This method works well when is relatively small, allowing us to determine
whether any natural number less than or equal to is prime or composite.
Implementation:
Given a number n, print all primes smaller than or equal to n. It is also given that n is a small
number. For instance here if n is 10, the output should be “2, 3, 5, 7”. If n is 20, the output
should be “2, 3, 5, 7, 11, 13, 17, 19”.
# Python program to print all Primes Smaller
# than or equal to N using Sieve of Eratosthenes
def SieveOfEratosthenes(num):
prime = [True for i in range(num+1)]
# boolean array
p = 2
while (p * p <= num):
# If prime[p] is not
# changed, then it is a prime
if (prime[p] == True):
# Driver code
if __name__ == '__main__':
num = 30
print("Following are the prime numbers smaller"),
print("than or equal to", num)
SieveOfEratosthenes(num)
Output
Following are the prime numbers smaller
than or equal to 30
2
3
5
7
11
13
17
19
23
29
Time Complexity: O(n*log(log(n)))
Auxiliary Space: O(n)
If the program is bug-free then, these types of conditions will never occur in the future. Otherwise,
if they occur then, the program will clash with the errors. This tool makes it easy for the developers
to track the errors and fix them.
If we can catch an error then we can write code to handle it. An uncaught error will crash our
program.
We can keep our code inside a block placed within try and then keep another code block under
except to handle in case of error. If the code within try block generate some error , the code
block within except will be executed. If there is no error then except part of the code will not
be executed.
Python error handling using try catch else & finally with system Exception message & specific
errors
Output is here
some error occured
Output is here
This is a key error
finally
The code block within finally code block is executed in all conditions ( error or no error )
my_dict={1:'Alex',2:'Ronald'}
try:
print(my_dict[3])
except (KeyError):
print (" This is a key error ")
except :
print (" some error occured ")
finally :
print ( " I came out " )
Output is here
This is a key error
I came out
else:
If there is no error then code block within else will be executed.
my_dict={1:'Alex',2:'Ronald'}
try:
print(my_dict[2])
except (KeyError):
print (" This is a key error ")
except :
print (" some error occured ")
else :
print ( " within else ")
Output is here
Ronald
within else
except (KeyError):
print (" This is a key error ")
except :
print (" some error occured ")
else :
print ( " within else ")
finally:
print ( " I am within finally")
Output
Ronald
within else
I am within finally
Output is here
not integer : Welcome
not integer : to
The interger is : 45
not integer : town
Output
Value of x is greater than 10
i) ZerroDivisionError #program
i= 0 # change the value to 'a'
try:
r=1/i # Generate error as i = 0
print("The result is :",i)
except ZeroDivisionError as my_msg:
print(" This is a ZeroDivisionError ")
print(my_msg)
except:
print ("Some other error has occured : ",i)
Output is here
This is a ZeroDivisionError
division by zero
ii)ValueError
try:
x=int('plus2net')
print("No error in Try Block")
except ValueError as my_msg:
print ("This is a ValueError")
print (my_msg)
except:
print ("Some other error has occured")
Output is here
This is a ValueError
invalid literal for int() with base 10: 'plus2net'
iii)ImportError
try:
import calendar1 # It should be
calendar
print("No error in Try")
except ImportError as my_msg:
print (" This is an ImportError ")
print(my_msg)
except:
print ("Some other error has occured")
Output is here
This is an ImportError
No module named 'calendar1'
iv)KeyError
my_dict={'a':'Alex','b':'Ronald'}
try:
print(my_dict['c']) # key is not present
print("No error in Try")
except KeyError as my_msg:
print (" This is an KeyError")
print(my_msg)
except:
print ("Some other error has occured")
Output is here
This is an KeyError
'c'
v) NameError
try:
print(i)
print("No error in Try Block")
except NameError as my_msg:
print ("This is a NameError")
print(my_msg)
except:
print ("Some other error has occured")
Output is here
This is a NameError
name 'i' is not defined
Since many houses can be made from the same description, we can create many objects
from a class.
class ClassName:
# class definition
class Bike:
name = ""
gear = 0
Here,
Python Objects
An object is called an instance of a class. For example, suppose Bike is a class then we
can create objects like bike1, bike2, etc from the class.
Here's the syntax to create an object.
objectName = ClassName()
Let's see an example,
# create class
class Bike:
name = ""
gear = 0
Here, bike1 is the object of the class. Now, we can use this object to access the class
attributes.
Here, we have used bike1.name and bike1.gear to change and access the value
of name and gear attribute respectively.
Output
Name: Mountain Bike, Gears: 11
In the above example, we have defined the class named Bike with two
attributes: name and gear.
We have also created an object bike1 of the class Bike.
Finally, we have accessed and modified the attributes of an object using the . notation.
# define a class
class Employee:
# define an attribute
employee_id = 0
Output
In the above example, we have created two objects employee1 and employee2 of
the Employee class.
Python Methods
We can also define a function inside a Python class. A Python Function defined inside a
class is called a method.
Let's see an example,
# create a class
class Room:
length = 0.0
breadth = 0.0
Output
study_room.calculate_area()
Here, we have used the . notation to call the method. Finally, the statement inside the
method is executed.
Python Constructors
Earlier we assigned a default value to a class attribute,
class Bike:
name = ""
...
# create object
bike1 = Bike()
However, we can also initialize values using the constructors. For example,
class Bike:
# constructor function
def __init__(self, name = ""):
self.name = name
bike1 = Bike()
Here, __init__() is the constructor function that is called whenever a new object of that
class is instantiated.
The constructor above initializes the value of the name attribute. We have used
the self.name to refer to the name attribute of the bike1 object.
If we use a constructor to initialize values inside a class, we need to pass the
corresponding value during the object creation of the class.
An object is any entity that has attributes and behaviors. For example, a parrot is an
object. It has
attributes - name, age, color, etc.
behavior - dancing, singing, etc.
Similarly, a class is a blueprint for that object.
# class attribute
name = ""
age = 0
# create parrot1 object
parrot1 = Parrot()
parrot1.name = "Blu"
parrot1.age = 10
# access attributes
print(f"{parrot1.name} is {parrot1.age} years old")
print(f"{parrot2.name} is {parrot2.age} years old")
Run Code
Output
In the above example, we created a class with the name Parrot with two
attributes: name and age.
Then, we create instances of the Parrot class. Here, parrot1 and parrot2 are references
(value) to our new objects.
We then accessed and assigned different values to the instance attributes using the
objects name and the . notation.
To learn more about classes and objects, visit Python Classes and Objects
Python Inheritance
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).
def eat(self):
print( "I can eat!")
def sleep(self):
print("I can sleep!")
# derived class
class Dog(Animal):
def bark(self):
print("I can bark! Woof woof!!")
Output
I can eat!
I can sleep!
I can bark! Woof woof!!
Here, dog1 (the object of derived class Dog) can access members of the base class
Animal. It's because Dog is inherited from Animal.
Object 1
Python Encapsulation
Encapsulation is one of the key features of object-oriented programming. Encapsulation
refers to the bundling of attributes and methods inside a single class.
It prevents outer classes from accessing and changing attributes and methods of a class.
This also helps to achieve data hiding.
In Python, we denote private attributes using underscore as the prefix i.e single _ or
double __. For example,
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
c = Computer()
c.sell()
Output
c.__maxprice = 1000
Here, we have tried to modify the value of __maxprice outside of the class. However,
since __maxprice is a private variable, this modification is not seen on the output.
As shown, to change the value, we have to use a setter function i.e setMaxPrice() which
takes price as a parameter.
Polymorphism
Polymorphism is another important concept of object-oriented programming. It simply
means more than one form.
That is, the same entity (method or operator or object) can perform different operations
in different scenarios.
class Polygon:
# method to render a shape
def render(self):
print("Rendering Polygon...")
class Square(Polygon):
# renders Square
def render(self):
print("Rendering Square...")
class Circle(Polygon):
# renders circle
def render(self):
print("Rendering Circle...")
# create an object of Square
s1 = Square()
s1.render()
Output
Rendering Square...
Rendering Circle...
Polymorphism allows the same interface for different objects, so programmers can write
efficient code.
• Types of Inheritance
Single Inheritance
Single inheritance is one of the types of inheritance in Python, where there is only one base class
and one child class. It is the inheritance type that is most frequently used.
In the diagram above, the downward arrow indicates that class B is descended from class A. This
implies that class B inherits class A's members and functions designated as public or protected,
enabling class B objects to access class A's methods and properties.
Example of Single Inheritance:
# Python program to demonstrate single inheritance
# Base class
class Father:
def function_1(self):
print ('I am father.')
# Child class
class Children(Father):
def function_2(self):
print ('I am son.')
object = Children()
object.function_1()
object.function_2()
Output:
Explanation: In the above example, class children inherit the property and data of the father's class
having inheritance relations.
Multiple Inheritance
Multiple inheritances are another types of inheritance in Python, which refer to deriving a class
from multiple base classes.
In the diagram above, class C comes from classes A and B. Classes A and B's attributes and
operations will be present in class C.
Example of Multiple Inheritance:
# Python program to demonstrate multiple inheritances
# Base class1
class A:
aname = ''
def aclass(self):
print (self.aname)
# Base class2
class B:
bname = ''
def bclass(self):
print (self.bname)
# Child class
def cname(self):
print ('B :', self.bname)
print ('A :', self.aname)
s1 = C()
s1.bname = 'Mohit'
s1.aname = 'Ashutosh'
s1.cname()
Output:
Explanation:
In the above example, class C is inheriting the property of class B and class A having a multiple
inheritance relationship among us.
Multilevel Inheritance
When there are multiple levels of inheritance, the new derived class receives an additional
inheritance from both the base class and the derived class. This type of inheritance in Python is
referred to as multilevel inheritance.
In the above diagram, class C is descended from class B, which is from class A.
Example of Multilevel Inheritance:
# Python program to demonstrate multilevel inheritance
class A:
# Intermediate class
class B(A):
A.__init__(self, aname)
# Derived class
class C(B):
def __init__(
self,
cname,
bname,
aname,
):
self.cname = cname
def display(self):
print ('A name :', self.aname)
print ('B name :', self.bname)
print ('C name :', self.cname)
# Driver code
Output:
Explanation:
In the above example, class B is inheriting the property of class A and class C is inheriting the class
B property i.e. class C inheriting the property of class A also.
Hierarchical Inheritance
Hierarchical inheritance is the term used to describe situations with multiple derived classes from a
single base class.
Here in the above block diagram, class A and B inherit the property of class C, which shows
hierarchical inheritance.
Example of Hierarchical Inheritance:
# Python program to demonstrate Hierarchical inheritance
# Base class
class A:
def function_1(self):
print ('Parent of B and C')
# Derived class1
class B(A):
def function_2(self):
print ('Child class of A')
# Derivied class2
class C(A):
def function_3(self):
print ('Child class of A')
object1 = C()
object2 = B()
object1.function_1()
object1.function_3()
object2.function_1()
object2.function_2()
Output:
Explanation:
In the above example, class B and class C inherit the property of class A having a hierarchical
relationship among them.
Next topic:
Python __str__ Method
In Python, class objects are represented as strings with the help of the
python __str__ method. This method is also called as magic method or dunder
method. The python __str__ method returns the string representation of the
object. The same method is also called when the str() or print() function is
invoked on an object. We'll see examples of such instances in the article below.
Let's take a look at the syntax of the python str() method.
object.__str__(self)
The python __str__ method returns the object representation in a string format. This method is
supposed to return a human-readable format which is used to display some information about the
object.
How to Call __str__ Method
Now, let’s see how you can use the python __str__ method. There are multiple ways in which you
can call this method and these are explained below with examples.
Default Implementation
class Employee:
self.name = name
self.age = age
self.id = id
print(employeeObject)
print(employeeObject.__str__())
print(employeeObject.__repr__())
The above example shows the default implementation of the __str__ method. In the above example
neither __str__ nor __repr__ methods are defined. Therefore, calling the __str__ method calls the
default __repr__ method as explained above in the article. And as you can see in the output, all