Dsa Lab 3
Dsa Lab 3
MARKS AWARDED:
Introduction:
1. Functions in Python:
A function is a block of code which only runs when it is called. You can pass data,
known as parameters, into a function. A function can return data as a result. A function in
python is declared by the keyword ‘def’ before the name of the function. The return type of
the function need not be specified explicitly in python. The function can be invoked by
writing the function name followed by the parameter list in the brackets.
i. Creating a Function:
In Python a function is defined using the def keyword:
Example 01:
def my_function():
print("Hello from a function")
Calling a Function: To call a function, use the function name followed by parenthesis:
Example 02:
def my_function():
print("Hello from a function")
my_function()
Parameters:
Information can be passed to functions as parameter. Parameters are specified after the
function name, inside the parentheses. You can add as many parameters as you want, just
separate them with a comma. The following Example has a function with one parameter
(fname).
When the function is called, we pass along a first name, which is used inside the
function to print the full name:
Example 03:
def my_function(fname):
print(fname + " is an engineering university")
Return Values
To let a function, return a value, use the return statement:
Example Output:
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Keyword Arguments
You can also send arguments with the key = value syntax. This way the order of the
arguments does not matter.
Example Output:
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
Arbitrary Arguments
If you do not know how many arguments that will be passed into your function, add a
* before the parameter name in the function definition. This way the function will receive a
tuple of arguments, and can access the items accordingly:
If the number of arguments are unknown, add a * before the parameter name:
Example Output:
def my_function(*kids):
print("The youngest child is " + kids[2])
Parameter passing in Python follows the semantics of the standard assignment statement.
When a function is invoked, each identifier that serves as a formal parameter is assigned, in
the function’s local scope, to the respective actual parameter that is provided by the caller of
the function.
class MyClass:
x=5
Create Object
Now we can use the class named MyClass to create objects:
Example
Create an object named p1, and print the value of x:
p1 = MyClass ( )
print (p1.x )
All classes have a function called init (), which is always executed when the class is
being initiated.
Use the init () function to assign values to object properties, or other operations that
are necessary to do when the object is being created:
Example: Create a class named Person, use the init () function to assign values for name and
age:
class Person: Output:
def init (self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name) print(p1.age)
Note: The init () function is called automatically every time the class is being
used to create a new object.
Object Methods
Objects can also contain methods. Methods in objects are functions that belong to the
object. Methods are functions defined inside the body of a class. They are used to define the
behaviors of an object
def myfunc(self):
print("Hello my name is "
+
self.name)
p1 = Person("John", 36)
p1.myfunc()
Note: The self parameter is a reference to the current instance of the class, and is
used to access variables that belong to the class.
p1 = Person("John", 36)
p1.myfunc()
Example
Set the age of p1 to 40:
p1.age = 40
Example
Delete the age property from the p1 object:
del p1.age
Delete Objects
You can delete objects by using the del keyword:
Example
Delete the p1 object:
del p1
Inheritance
Inheritance is a way of creating new class for using details of 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).
Example: Use of Inheritance in Python When we run this program, the # parent class output will be:
class Bird:
def init (self):
print("Bird is
ready")
def
whoisThis(self):
print("Bird")
def swim(self):
print("Swim
faster")
# child class
class Penguin(Bird):
def init (self):
# call super() function
super(). init ()
print("Penguin is
ready")
def
whoisThis(self):
print("Penguin")
def run(self):
print("Run
In the above program, we created two classes i.e. Bird (parent class) and Penguin (child
class). The child class inherits the functions of parent class. We can see this from swim()
method. Again, the child class modified the behavior of parent class. We can see this from
whoisThis() method.
Furthermore, we extend the functions of parent class, by creating a new run() method.
Additionally, we use super() function before init () method. This is because we want to
pull the content of init () method from the parent class into the child class.
Encapsulation
Using OOP in Python, we can restrict access to methods and variables. This
prevent data from direct modification which is called encapsulation. In Python, we
denote private attribute using underscore as prefix i.e single “ “ or double “ “.
class Computer:
def init (self):
self. maxprice = 900
def sell(self):
print("Selling Price: {}".format(self. maxprice))
def setMaxPrice(self,
price): self. maxprice =
price
c=
Computer()
c.sell()
# using setter
function
In the above program, we defined a class Computer. We use init__() method to store the
maximum selling price of computer. We tried to modify the price. However, we can’t change
it because Python treats the maxprice as private attributes. To change the value, we used a
setter function i.e setMaxPrice() which takes price as parameter.
Polymorphism
Polymorphism is an ability (in OOP) to use common interface for multiple form
(data types). Suppose we need to color a shape, there are multiple shape option (rectangle,
square, circle). However, we could use same method to color any shape. This concept is
called Polymorphism.
class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim") # common interface
flying_test(blu) flying_test(peggy)
In the above program, we defined two classes Parrot and Penguin. Each of them have
common method fly() method. However, their functions are different. To allow
polymorphism, we created common interface i.e flying_test() function that can take any
object. Then, we passed the objects blu and peggy in the flying_test() function, it ran
effectively.
EXERSIZE TASKS
1. Write a Python class named Rectangle constructed by a length and width and a
method which will compute the area of a rectangle. Make a child class named
Circle constructed by a radius and two methods which will compute the area and
the perimeter of a circle.
2. Create a python code using classes and functions that takes username, roll
number and section as objects and print the statements as:
class Rectangle:
def _init_(self, y , l):
self.y = 0
self.l = 0
def area(l, y):
a=l*y
return a
class circle(Rectangle):
def _init_(self, r):
self.r = 0
def area(r):
a = 3.14 * r *r
return a
def perm(r):
p = 2 * 3.14 * r
return p
x = int(input("Enter the length of the rectangle : "))
y = int(input("Enter the width of the rectangle : "))
obj = Rectangle
print("The area of rectangle is : ",obj.area(x,y))
z = int(input("Enter the radius of the circle : "))
obj = circle
print("The area of circle is : ",obj.area(z))
print("The perimeter of circle is : ",obj.perm(z))
#Q2
class line:
def _inti_(self,name,roll,sec):
self.name=""
self.roll=""
self.sec=""
def display(name,roll,sec):
print ('\n\n\n',name,", having roll number : ",roll, " is alloted section ", sec)
obj = line
n = input("Please enter the name of the student : ")
r = input("Please enter the roll number of the student : ")
s = input("Please enter the section of the student : ")
obj.display(n,r,s)
#Q3
def power(n,p):
x=1
for i in range(1,p+1):
x=x*n
print(x)
power(2,8)