0% found this document useful (0 votes)
76 views13 pages

Dsa Lab 3

1. The document introduces functions and classes in Python. It defines functions, how to create them, pass parameters, return values, and use keyword arguments. It also defines classes, how to create classes and objects, use the init method, add methods to classes, and modify, delete, and inherit from classes and objects. 2. Key concepts covered include defining functions with def, passing data as parameters, returning values, and different ways of passing arguments. For classes, it defines how to create a class and objects, use the init method to initialize objects, add methods to classes, and modify class properties and delete objects. 3. The document provides examples for each concept to demonstrate how to properly structure and
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
76 views13 pages

Dsa Lab 3

1. The document introduces functions and classes in Python. It defines functions, how to create them, pass parameters, return values, and use keyword arguments. It also defines classes, how to create classes and objects, use the init method, add methods to classes, and modify, delete, and inherit from classes and objects. 2. Key concepts covered include defining functions with def, passing data as parameters, returning values, and different ways of passing arguments. For classes, it defines how to create a class and objects, use the init method to initialize objects, add methods to classes, and modify class properties and delete objects. 3. The document provides examples for each concept to demonstrate how to properly structure and
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

LAB 03

Introduction to Functions and


Classes

STUDENT NAME ROLL NO SEC

SIGNATURE & DATE

MARKS AWARDED:

NATIONAL UNIVERSITY OF COMPUTER AND EMERGING


SCIENCE (NUCES) KARACHI

Prepared by: Engr. Syed Asim Mahmood Summer 2022


[INTRODUCTION TO FUNCTIONS AND CLASSES] LAB: 03

Lab Session 03: Introduction to Functions and Classes


Objectives:
i. Learn the concepts of functions in python.
ii. Learn the concepts of classes in python.

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

my_function("FAST") my_function("UET") my_function("NUST")

National University of Computer & Emerging Sciences, Karachi Page | 2


LAB: 03 [INTRODUCTION TO FUNCTIONS AND CLASSES]

Default Parameter Value:


The following Example shows how to use a default parameter value. If we call the
function without parameter, it uses the default value:

Example 04: Output:

def my_function(country = "Norway"):


print("I am from " + country)
my_function("Pakistan")
my_function("Turkey")
my_function()
my_function("Brazil")

Passing a List as a Parameter:


You can send any data types of parameter to a function (string, number, list, dictionary
etc.), and it will be treated as the same data type inside the function. E.g., if you send a List as
a parameter, it will still be a List when it reaches the function:
Example Output:
def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana",


"cherry"] my_function(fruits)

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.

Page | 3 National University of Computer & Emerging Sciences, Karachi


[INTRODUCTION TO FUNCTIONS AND CLASSES] LAB: 03

Example Output:
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function (child1 = "Emil",


child2 = "Tobias",
child3 = "Linus")

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

my_function("Emil", "Tobias", "Linus")

# Function for checking the divisibility


def checkDivisibility (a, b):
if a % b == 0 :
print ("a is divisible by b")
else:
print ("a is not divisible by b")

#Driver program to test the above function


checkDivisibility (4, 2)

To be a successful programmer, one must have clear understanding of the mechanism


in which a programming language passes information to and from a function. In the context
of a function signature, the identifiers used to describe the expected parameters are known as
formal parameters, and the objects sent by the caller when invoking the function are the
actual parameters.

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.

2. CLASSES AND OBJECTS:


Python is an object-oriented programming language. Almost everything in Python is an
object, with its properties and methods.
Page | 4
National University of Computer & Emerging Sciences, Karachi
LAB: 03 [INTRODUCTION TO FUNCTIONS AND CLASSES]

A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class: To create a class, use the keyword class:


Example: Create a class named MyClass, with a property named x:

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 )

The init () Function


The Examples above are classes and objects in their simplest form, and are not really
useful in real life applications. To understand the meaning of classes we have to understand
the built-in init () function.

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)

Page | 5 National University of Computer & Emerging Sciences, Karachi


[INTRODUCTION TO FUNCTIONS AND CLASSES] LAB: 03

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

Let us create a method in the Person class:


Example
Insert a function that prints a greeting, and execute it on the p1 object:

class Person: Output:


def init (self, name, age):
self.name = name
self.age = age

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.

The self Parameter:


The self parameter is a reference to the current instance of the class and is used to
access variables that belongs to the class. It does not have to be named self, you can call it
whatever you like, but it has to be the first parameter of any function in the class:
Example
Use the words mysillyobject and abc instead of self:

National University of Computer & Emerging Sciences, Karachi Page | 6


LAB: 03 [INTRODUCTION TO FUNCTIONS AND CLASSES]

class Person: Output:


def init (mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age

def myfunc(abc): print("Hello my name is "


+ abc.name)

p1 = Person("John", 36)
p1.myfunc()

Modify Object Properties


You can modify properties on objects like this:

Example
Set the age of p1 to 40:

p1.age = 40

Delete Object Properties


You can delete properties on objects by using the del keyword:

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

Page | 7 National University of Computer & Emerging Sciences, Karachi


[INTRODUCTION TO FUNCTIONS AND CLASSES] LAB: 03

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.

National University of Computer & Emerging Sciences, Karachi Page | 8


LAB: 03 [INTRODUCTION TO FUNCTIONS AND CLASSES]

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

# change the price


c. maxprice = 1000
c.sell() # direct change of maxprice has no effect

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

Page | 9 National University of Computer & Emerging Sciences, Karachi


[INTRODUCTION TO FUNCTIONS AND CLASSES] LAB: 03

Example 5: Using Polymorphism in Python When we run this program, the


output will be: Parrot can fly Penguin can't fly
class Parrot:
def fly(self):
print("Parrot can fly") def swim(self):
print("Parrot can't swim")

class Penguin:
def fly(self):
print("Penguin can't fly")

def swim(self):
print("Penguin can swim") # common interface

def flying_test(bird): bird.fly()


#instantiate objects

blu = Parrot() peggy = Penguin()

# passing the object

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.

National University of Computer & Emerging Sciences, Karachi Page | 10


LAB: 03 [INTRODUCTION TO FUNCTIONS AND CLASSES]

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:

Name: “Zara”, having roll number: K17-2000 is allotted section “B”

3. Python program to implement pow (x, n).

Page | 11 National University of Computer & Emerging Sciences, Karachi


[INTRODUCTION TO FUNCTIONS AND CLASSES] LAB: 03
Lab Report:
(It is recommended to write Lab Report in bullet Form)

National University of Computer & Emerging Sciences, Karachi Page | 12


#Q1

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)

You might also like