0% found this document useful (0 votes)
9 views

python lab solutions (1)

python solutions

Uploaded by

rebellion1452
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

python lab solutions (1)

python solutions

Uploaded by

rebellion1452
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Experiment-1

a) Practice Python Installation

AIM: To practice Python Installation


Step - 1: Select the Python's version to download.

Step - 2: Click on the Install Now

Step - 3 Installation in Process

Now, try to run python on the command prompt. Type the command python -version in case of
python3.
b)Declaring variables
AIM: To implement variable declaration
a = 20
b = 10.5
c = "Hello"
d = False
e = 5 + 3j
print(str(a))
print(float(a))
print(bool(a))
print(complex(a))
print(str(b))
print(int(b))
print(bool(b))
print(complex(b))
print(str(e))
print(bool(e))

OUTPUT:

c) Basic data types


#Text type:
a = "hello" #string
#Boolean type:
e = True #boolean
#Numeric type:
b = 10 #int
c = 5.5 #float
d = 10 + 3j #complex
#Sequence type:
f = [1,2,3,4,5] #list
g = (10,20,30,40,50) #tuple
h = range(25,50) #range
#Mapping type:
i = {"CSE":1,"ECE":2,"EEE":3,"CIVIL":4,"MECH":5} #dictionary
#Set type:
j = {"a","b","c","d","e"} #set
k = frozenset({"a","b","c","d","e"}) #frozenset
#Binary type:
l = b"Hello" #byte
m = bytearray(5) #bytearray

d) Type of a variable
a = 20
b = 10.5
c = "Hello"
d = False
e = 5 + 3j
f = [1,2,3,4,5]
g = {1:"a",2:"b",3:"c"}
h = (1,2,3,4,5)
i = range(10,20)
j = {"abc","efg","uvw","xyz"}
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
print(type(f))
print(type(g))
print(type(h))
print(type(i))
print(type(j))
e) Multiple assignments
#Assign the same value to multiple variables
a = b = c = 30
p = q = r = [100,200,300]
#Assign multiple values to multiple variables
x, y, z = 10, 15, 20
u, v, w = 0.453, "hey", True
print(a)
print(b)
print(c)
print(p)
print(q)
print(r)
print(x)
print(y)
print(z)
print(u)
print(v)
print(w)
OUTPUT:

f) Multiple statements in a single line


a = 2; b = 5; c = a**b; print(c)
a = "Hello"; b = " CSE"; c = a + b; print(c)
a = [10,20,30]; b = [40,50,60]; c = a + b; print(c)

OUTPUT:

g) Input and type conversion

a = input("Enter your name:")


print(a)
b = int(input("Enter your age:"))
print(b)
c = float(input("Enter your percentage:"))
print(c)
d = str(input("Enter a string:"))
print(d)
e = list(input("Enter a list:"))
print(e)
f = bool(input("Enter input:"))
print(f)

OUTPUT:

h) Use different operators in programs

AIM: To use different operators in programs

i) Arithmetic operators
x = 15
y=4
print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x // y =',x//y)
print('x ** y =',x**y)

OUTPUT:

ii) Comparison operators


x = 10
y = 12
print('x > y is',x>y)
print('x < y is',x<y)
print('x == y is',x==y)
print('x != y is',x!=y)
print('x >= y is',x>=y)
print('x <= y is',x<=y)

OUTPUT:

iii) Logical operators


x = True
y = False
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)

OUTPUT:
iv) Bitwise operators
a = 10
b=4
print("a & b =", a & b)
print("a | b =", a | b)
print("~a =", ~a)
print("a ^ b =", a ^ b)
# shift operators
a = 10
b = -10
print("a >> 1 =", a >> 1)
print("b >> 1 =", b >> 1)
a=5
b = -10
print("a << 1 =", a << 1)
print("b << 1 =", b << 1)

OUTPUT:

v) Assignment operators
a = 21
b = 10
c=0
c=a+b
print("Initial value=",c)
c += a
print("c+a=",c)
c -= a
print("c-a=",c)
c *= a
print("c*a=",c)
c /= a
print("c/a=",c)
c =2
c %= a
print("c%a=",c)
c **= a
print("c**a=",c)
c //= a
print("c//a=",c)

OUTPUT:

vi) Identity operators


x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
print(x1 is not y1)
print(x2 is y2)
print(x3 is y3)

OUTPUT:

False
True
False

vii) Membership operators


x = 'Hello world'
y = {1:'a',2:'b'}
print('H' in x)
print('hello' not in x)
print(1 in y)
print('a' in y)

OUTPUT:

True
True
True
False
EXPERIMENT-2

Python programs on Decision Control Statements:

a)Write Programs using selection statements


Aim: To Write Programs using selection statements
The selection statements are also known as decision making statements
or branching statements. The selection statements are used based on a
condition.
Python provides the following selection statements.
1.if statement
2.if-else statement
3.if-elif statement
If-statement:
Syntax:
if test-expression==True:
statement(s)
Program:
Program to print the largest of the three numbers.
a =int(input(“Enter a”))
b=int(input(“Enter b”))
c=int(input(“Enter c”))

if a>b and a>c:


print(“a is largest”)
if b>a and b>c:
print(“b is largest”)
if c>a and c>b:
print(“c is largest”)

OUTPUT:

If-else statement:
Syntax:
if condition:
#block of statements
else:
#another block of statements (else-block)
Program:
Program to check if a number is even or odd using if-else statement.

num = int(input("enter the number?"))

if num%2 == 0:
print("Number is even...")
else:
print("Number is odd...")

OUTPUT:

If-elif statement:

if expression 1:
# block of statements
elif expression 2:
# block of statements
else:
# block of statements

Program:
marks = int(input("Enter the marks? "))
if marks > 85 and marks <= 100:
print("You scored grade A ...")
elif marks > 60 and marks <= 85:
print("You scored grade B + ...")
elif marks > 40 and marks <= 60:
print("You scored grade B ...")
elif (marks > 30 and marks <= 40):
print("You scored grade C ...")
else:
print("Sorry you failed")

OUTPUT:
b)Implement python program on and conditional branching statements:
AIM: To Implement python program on and conditional branching statements:
1. If-statement:
Syntax:
if test-expression==True:
statement(s)

Program:
a=int(input(“enter a”))
b=int(input(“enter b”))
if a > b:
print("a is greater than b")

OUTPUT:

If-else statement:
Syntax:
if condition:
#block of statements
else:
#another block of statements (else-block)

Program:
x=int(input("enter a value"))
if x > 0:
print("It's a positive number")
else:
print("It's not a positive number")

OUTPUT:
If-elif statement:
if expression 1:
# block of statements
elif expression 2:
# block of statements
else:
# block of statements

Program:
x=int(input("enter value of x"))
if x < 0:
print("x is a negative")
elif x == 0:
print("x is 0")
else:
print("x is positive")

OUTPUT:
Experiment-3
Python programs on looping control structures

a) Design and develop programs using Iterative statements- while, for, nested
loops

AIM: To design and develop programs using Iterative statements- while, for, nested
loops

PROGRAM:

while looP

count = 0

while (count < 3):

count = count + 1

print("Hello CSE")

OUTPUT:

for loop

n=4

for i in range(0, n):

print(i)

OUTPUT:
Nested loops
for i in range(1, 11):

# nested loop

for j in range(1, 11):

print(i * j, end=' ')

print()

b) Use Break, continue, pass statements in programs

AIM: To use break, continue, pass statements in programs

PROGRAM:

for i in range(1,11):

if i == 2**3:

break

print(i)

OUTPUT:
Continue statement
for i in range(1,21):

if i%2 == 0:

continue

print(i)

OUTPUT:

Pass statement
s = "python"

for i in s:

pass

for i in s:

if i == 'o':
print('Pass executed')

pass

print(i)

OUTPUT:

c) Understand the usage of else statement in loops with a case study

AIM: To understand the usage of else statement in loops with a case study

PROGRAM:

count=1

while(count<6):

print(count)

count+=1

else:

print("Inside the else block")

OUTPUT:
EXPERIMENT-4

Identify the need and importance in the creation of python Functions and modules

a)Write programs for defining and calling functions.

AIM: To write program to define a function and call it.

Syntax:
def function_name():
statements

function call:
function_name()
Program:
Function to find number is even or odd:
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
# Driver code to call the function
evenOdd(2)
evenOdd(3)

OUTPUT:

b)To understand Scope of a variable and Use global statement .

AIM: To write program to understand the scope of variables.

Program:

def func():
l="local variable" #local scope
print(l)
print(s+" inside function ")
s="global variable" #global scope
func()
print(s+ " outside function")

OUTPUT:

Using global keyword:


We only need to use the global keyword in a function if we want to do
assignments or change the global variable.

Program:

def f():
global s
s += "world"
print(s)
s = "Changed the global variable"
print(s)
# Global Scope
s = "Hello"
f()
print(s)

OUTPUT:

c)Differentiate fruitful and void functions through a case study

AIM: Program to differentiate between fruitful and void functions.

Fruitful functions:
The functions with a return value.
Void functions:
The functions which donot have a return value.

Program (for void function):


def mul_v(a, b, c):
print("multiplication result")
print(a * b * c)
# Function Call
mul_v(2, 4, 6)

OUTPUT:

Program (for fruitful function):


def mul_f(a, b, c):
d=a*b*c
return d
# Function call
x = mul_f(2, 4, 6)
print("multiplication result "+str(x))

OUTPUT:

d)Apply Recursive and lambda functions.


AIM: Write program to execute Recursive and lambda function

RECURSIVE:
It is a process in which a function calls itself directly or indirectly.

Program(recursive):

Python program to find factorial of number using recursion.

def recursive_fact(n):
if n == 1:
return n
else:
return n * recursive_fact(n-1)

# user input
num = int(input("enter a number"))
print(“factorial”+str(recursive_fact(num)))

OUTPUT:

LAMBDA:

Python Lambda Functions are anonymous function means that the function is
without a name.
lambda arguments: expression
Program(lambda):
Python program to find cube of a number using lambda function:

cube = lambda y: y*y*y

n=int(input("enter a number"))
print(cube(n))

OUTPUT:

Enter a number : 3
27

e)Understand Different kinds of arguments through a case study:

AIM: To implement different kinds of arguments.

1. Keyword arguments:
The idea is to allow the caller to specify the argument name with values so
that caller does not need to remember the order of parameters .

Program:
def student(firstname, lastname):
print(firstname, lastname)

# Keyword arguments
student(firstname="Hello", lastname='World')
student(lastname='World', firstname='Hello')

OUTPUT:

Hello World
Hello World

2. Default arguments:
A default argument is a parameter that assumes a default value if a value is
not provided in the function call for that argument.

Program:
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)

myFun(10)

OUTPUT:
x: 10
y: 50

3. Variable Length arguments:


We can pass a variable number of arguments to a function using special
symbols

Program:

def myFun(*argv):
for arg in argv:
print(arg)
myFun('Hello', 'Welcome', 'to', 'Python')
OUTPUT:

f) Installing and usage of standard library modules.

Install Modules:
You can install modules or packages with the Python package manager (pip). To install a module
system wide, open a terminal and use the pip command. If you type the code below it will
install the module.
sudo pip install module-name

In order for this to work, you need to have pip installed. The installation process depends on
your platform.

You can check your version of python with the command

python –version

AIM: To install the standard library modules and use them .

Math(module):
The math module is a collection of mathematical functions.
Program:
import math
print(math.pi)
print(math.ceil(3.3))
print(math.floor(3.3))
print(math.sqrt(10))

OUTPUT:

Random module:
Program:

import random
print(random.random())
pets = ["cat", "dog", "fish"]
print(random.choice(pets))
print(random.randint(1, 10))

OUTPUT:

g) Python Packages:
A package is a hierarchical file directory structure that has modules and other packages within
it. Every package in Python is a directory which must have a special file called __init__.py. It is
simply added to indicate that this directory is an ordinary directory and contains a Python
package .You can import a package as the same way as a module.
To create a package called MyPackage ,create a directory called MyPackage having the module
MyModule and the __init__.py file. Now to use MyModule in program you must first import it.

Import MyPackage.MyModule
Or

From MyPackage import MyModule


The __init__.py is a very important file that also determines which modules that the package
exports as the API,while keeping other modules internal ,by overriding the __all__ variable
__init__.py:
__all__=[“MyModule”]
Experiment-5

Solve the problems using Strings and understanding the methods and operations on Lists.

a)Apply string formatting operator.

AIM: To perform string formatting.

Program:

1. Formatting with % operator:

x = 'dance'
print("Geeta could both %s and %s. "%('sing',x))

print('There are %d dogs.' %4)

2. Formatting string using format() method.

print('We all are {}.'.format('equal'))

print('{2} {1} {0}'.format('XYZ.','am', 'I'))

b)Use built in string methods, functions and regular expressions


AIM: To use string methods,functions and regular expressions.
. capitalize()
replace()
split()
islower()
isupper()
isalpha()
isdigit()
swapcase()

Program:
String methods:
txt = "I love apples, apple are my favorite fruit"
x = txt.count("apple")
print(x)
k=txt.capitalize()
print(k)
p=txt.find(“apples”)
print(p)
l = txt.islower()
print(l)
r = txt.replace("apples", "oranges")
print(r)
h = txt.split()
print(h)
str= "CompanyX"
n= str.isalpha()
print(n)
str1=”35667”
print(str1.isnumeric())
str2=”THIS IS IT!”
print(str2.isupper())
str3=” hi I am PETER”
print(str3.swapcase())

OUTPUT:
REGULAR EXPRESSIONS:

import re
string = """Hello my Number is 123456789 and
my friend's number is 987654321"""
regex = '\d+'
match = re.findall(regex, string)
print(match)
print(re.split('\W+', 'Words, words , Words'))
print(re.split('\d+', 'On 12th Jan 2016, at 11:02 AM'))
regex1 = r"([a-zA-Z]+) (\d+)"
s = "Welcome to Python"
res = re.search(r"\bP", s)
print(res.start())
print(res.end())
print(res.span())

OUTPUT:
EXPERIMENT-6
Programs on the implementation of methods and operations of List data Structure.

a)Define a list and write a programs to access and modify element of a list.

AIM: To define a list and write program to access and modify the elements in it.

Program:

1) Creating a list:
l1 = [1, 2, 3]
l2 = []
l3 = [1, "Hello", 3.4]
l4= ["mouse", [8, 4, 6], ['a']]
print(l1)
print(l2)
print(l3)
print(l4)

OUTPUT:

2) Accessing a list:
my_list = ['h', 'e', 'l', 'l', 'o']
print(my_list[0])
print(my_list[2])
for i in my_list:
print(i)
n_list = ["Hello", [2, 0, 1, 5]]
print(n_list[0][1])
print(n_list[1][3])

OUTPUT:
3) Modifying list elements:
nums= [2, 4, 6, 8]
nums[0] = 1
print(nums)
nums[1:4] = [3, 5, 7]
print(nums)
nums.append(7)
print(nums)
print(nums+ [9, 7, 5])
nums.insert(1,10)
print(nums)

OUTPUT:

b)Implement basic list operations and methods.


AIM : To implement the basics of list operations and methods.

Operations: 1. Append()
2.extend()
3.insert()
4.remove()
5.pop()
6.slice
7.len()
8.min()or max()

Program:
l= [2, 4, 6, 8]
l.append(7)
l.append(9)
print(l)
l.extend([10,12,14])
print(l)
l.insert(3,20)
print(l)
l.remove(10)
print(l)
l.pop(0)
print(l)
print(l[2:4])
l.reverse()
print(l)
print("length":+str(len(l)))
print("max:" +str(max(l)))
print("min:" +str(min(l)))
OUTPUT:

List methods:
1. Sort()
2. Reverse()
3. Sum()
4. Index()
5. Count()
6. Min() or max()

Program:

l= [5,2, 4, 2, 8]
l.sort()
print("sorted list:")
print(l)
l.reverse()
print("reversed list")
print(l)
print("sum:"+str(sum(l)))
print("len:"+str(len(l)))
print("count:"+str(l.count(2)))
print("index of:"+ str(l.index(2)))
print("max:"+str(max(l)))
print("min:"+str(min(l)))

OUTPUT:

c)Write programs to use list as a stack and Queue.


AIM: To implement list as stack and Queue.
List as a stack:
Stack works on the principle of “Last-in, first-out”. To push an item, we
use append() function and to pop out an element we use pop() function.
Program:

stack = [1, 2, 3]
stack.append(4)
stack.append(5)
print(stack)
print(stack.pop())
print(stack)
print(stack.pop())
print(stack)

OUTPUT:
List as a Queue:
Queue works on the principle of “First-in, first-out”. Below is list implementation of
queue. We use pop(0) to remove the first item from a list.

Program:
queue = [1,2,3]
queue.append(4)
queue.append(5)
print(queue)
print(queue.pop(0))
print(queue)
print(queue.pop(0))
print(queue)
OUTPUT:
Experiment-7
Implement programs to solve the problems using Python other data structures: Tuples and
Dictionaries

a)Write programs to define a dictionary and write programs to modify values,


adding new keys

AIM: To write programs to define a dictionary and write programs to modify values, adding
new keys

PROGRAM:
i) Create a dictionary:
d1 = {}
d2 = {1:'a',2:'b',3:'c'}
d3 = {'a':'Hello','b':[1,2,3],'c':3}
d4 = dict([('a',10),('b',20)])
d5 = {1:'a',2:{'b':'two','c':'three'},3:'d'}
print(d1)
print(d2)
print(d3)
print(d4)
print(d4)
OUTPUT:

ii) Modifying values in a dictionary:


d={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(d)

d["year"] = 2018
d["model"] = "Figo"
print(d)

OUTPUT:
iii) Adding new keys into a dictionary:
d={
'key1':'Welcome',
'key2':'CSE'
}
print(d)

d['key2'] = 'to'
d['key3'] = 'CSE'
print(d)

OUTPUT:

b)Apply looping over a dictionary


AIM: To apply looping over a dictionary

PROGRAM:
i) Iterate through keys:
statesAndCapitals = {
'Gujarat' : 'Gandhinagar',
'Maharashtra' : 'Mumbai',
'Rajasthan' : 'Jaipur',
'Bihar' : 'Patna'
}

print('List Of given states:\n')


for state in statesAndCapitals:
print(state)

OUTPUT:

List Of given states:

Gujarat
Maharashtra
Rajasthan
Bihar
ii) Iterate through values:
statesAndCapitals = {
'Gujarat' : 'Gandhinagar',
'Maharashtra' : 'Mumbai',
'Rajasthan' : 'Jaipur',
'Bihar' : 'Patna'
}

print('List Of given capitals:\n')

for capital in statesAndCapitals.values():


print(capital)

OUTPUT:
List Of given capitals:

Gandhinagar
Mumbai
Jaipur
Patna

iii) Iterate through key, value pairs:


statesAndCapitals = {
'Gujarat' : 'Gandhinagar',
'Maharashtra' : 'Mumbai',
'Rajasthan' : 'Jaipur',
'Bihar' : 'Patna'
}

print('List Of given states and their capitals:\n')

for state, capital in statesAndCapitals.items():


print(state, ":", capital)

OUTPUT:
List Of given states and their capitals:

Gujarat : Gandhinagar
Maharashtra : Mumbai
Rajasthan : Jaipur
Bihar : Patna

c)Use built in dictionary methods, functions


AIM: To use built in dictionary methods, functions

METHODS:
->keys()
->values()
->items()
->pop()
->get()
->update()
->copy()
->clear()

PROGRAM:
d={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97}
print(d.keys())
print(d.items())
print(d.values())
d.pop('Marks')
print(d)
d['Marks']=97
dict_new=d.copy()
print(dict_new)
print('Name: ', d.get('Name'))
print('Age: ', d.get('Age'))
d.update({'Age':22})
print(d)
d.clear()
print(d)

OUTPUT:

d)Create a tuple and assign values


AIM: To create a tuple and assign values

PROGRAM:
my_tuple = ()
print(my_tuple)
my_tuple = (1, 2, 3)
print(my_tuple)
my_tuple = (1, "Hello", 3.4)
print(my_tuple)
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)

OUTPUT:

e)Use basic tuple operations and comparisons


AIM: To use basic tuple operations and comparisons

PROGRAM:
Tuple operations:
fruits = "apple", "orange", "banana", "berry"
#indexing
print (fruits[0])
#addition
fruits=fruits+("mango",)
print(fruits)
#slicing
print(fruits[2:4])
#multiplication
print(fruits*3)
#in operator
print("berry" in fruits)
print("grapes" in fruits)
#length of tuple
print(len(fruits))
#max() and min()
print(max(fruits),min(fruits))
#deleting a tuple
del(fruits)
print(fruits)
OUTPUT:
Tuple comparisons:
cmp() method in Python compares two integers and returns -1, 0, 1 according
to comparison.
a = (1, 2, 3)
b = (1, 2, 5)
print(a < b)
a = (1, 2, 3, 4, 5)
b = (9, 8, 7, 6, 5)
print(set(a) & set(b))
a = (1, 2, 3, 4, 5)
b = (9, 8, 7, 6, 5)
a=set(a)
b=set(b)
print(a.intersection(b))
OUTPUT:
True
{5}
{5}
Experiment-8

a)Define class and objects for real-world scenario.


AIM: To define class and objects for real-world scenario.

Program:
class Dog:
a = "mammal"
b= "dog"
def fun(self):
print("I'm a", self.a)
print("I'm a", self.b)
Rodger = Dog()
print(Rodger.a)
Rodger.fun()

OUTPUT:

b. Defining Constructors and using self.


AIM: To define constructors

Program:
class user:
def __init__(self,name,age,gender):
self.name=name
self.age = age
self.gender = gender

def get_details(self):
print("Person details :")
print("\t Name :",self.name)
print("\t Age :",self.age)
print("\t Gender :",self.gender)
s=user("harry",20,"male")
s.get_details()

OUTPUT:
c)Understanding public and private members
AIM: To understand public and private members

Program:
class user:
def __init__(self,name,age,gender):
self.__name=name
self.__age = age
self.gender = gender
def get_details(self):
print("Person details :")
print("\t Name :",self.__name)
print("\t Age :",self.__age)
print("\t Gender :",self.gender)
def set_name(self,name):
self.__name = name
class Bank_Account(user):
def __init__(self,name,age,gender):
super().__init__(name,age,gender)
self.__balance=0
print("Hello!!! Welcome to the Deposit & Withdrawal Machine")
def get_user(self):
self.get_details()
s = Bank_Account("Harry",20,"Male")
s.get_user()

OUTPUT:

d)Calling class methods from another class


AIM: To implement calling class methods from another class
Program:
class Parent:
def __init__(self):
self.String1 ="Hello"
self.String2 ="World"
def Function2(self):
print("Function2 : ", self.String1)
return
class Child(Parent):
def Function1(self):
# calling Function2 Method in parent class
self.Function2()
print("Function1 : ", self.String2)
return
Object1 = Parent()
Object2 = Child()
Object2.Function1()

OUTPUT:

e) Write built-in functions to check ,get ,set and delete attributes.

AIM: To write built-in functions to check,get,set and delete attributes

getattr() – used to access the attribute of object.


hasattr() – used to check if an attribute exist or not.
setattr() – used to set an attribute.
delattr() – This function is used to delete an attribute

Program:
class emp:
name='Harsh'
salary='25000'
def show(self):
print (self.name)
print (self.salary)
e1 = emp()
# Use getattr instead of e1.name
e1.show()
print (getattr(e1,'name'))
# returns true if object has attribute
print (hasattr(e1,'name'))
setattr(e1,'height',152)
print (getattr(e1,'height'))
delattr(emp,'salary')

OUTPUT:
Experiment-9
a)Types of Inheritance in Python:
Aim: To implement different types of inheritance in Python
1. Single Inheritance:

class Parent:
def func1(self):
print("This function is in parent class.")
# Derived class
class Child(Parent):
def func2(self):
print("This function is in child class.")

object = Child()
object.func1()
object.func2()
Output:

2. Multiple Inheritance :

class Mother:
mothername = ""
def mother(self):
print(self.mothername)

# Base class2
class Father:
fathername = ""
def father(self):
print(self.fathername)

# Derived class
class Son(Mother, Father):
def parents(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)

s1 = Son()
s1.fathername = "RAM"
s1.mothername = "SITA"
s1.parents()
Output:

3. Multilevel Inheritance:

class Base:

def __init__(self, Basename):


self.Basename = Basename

# Intermediate class
class derived1(Base):
def __init__(self, derivedname, Basename):
self.derivedname = derivedname

# invoking constructor of Base class


Base.__init__(self, Basename)

# Derived class
class Son(derived):
def __init__(self,sonname, derivedname, Basename):
self.sonname = sonname

# invoking constructor of derived class


derived1.__init__(self, derivedname, Basename)

def print_name(self):
print('Base name :', self.Basename)
print("derived name :", self.derivedname)
print("Son name :", self.sonname)

s1 = Son('Prince', 'Rampal', 'Lal mani')


print(s1.Basename)
s1.print_name()
Output:

4.Hierarchical Inheritance :

# Base class
class Parent:
def func1(self):
print("This function is in parent class.")

# Derived class1
class Child1(Parent):
def func2(self):
print("This function is in child 1.")

# Derived class2
class Child2(Parent):
def func3(self):
print("This function is in child 2.")

object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()
Output:
5.Hybrid Inheritance :

class School:
def func1(self):
print("This function is in school.")

class Student1(School):
def func2(self):
print("This function is in student 1. ")

class Student2(School):
def func3(self):
print("This function is in student 2.")

class Student3(Student1, School):


def func4(self):
print("This function is in student 3.")

object = Student3()
object.func1()
object.func2()

OUTPUT:

b) Polymorphism using classes and method overriding:

AIM: To implement Polymorphism and method overriding


Polymorphism:

class A():
def show(self):
print("This is from Class A.")

class B():
def show(self):
print("This is from Class B.")
obj_A = A()
obj_B = B()
obj_A.show()
obj_B.show()

Output:

Method Overriding:

class Bird:
def intro(self):
print("There are many types of birds.")

def flight(self):
print("Most of the birds can fly but some cannot.")

class sparrow(Bird):
def flight(self):
print("Sparrows can fly.")

class ostrich(Bird):
def flight(self):
print("Ostriches cannot fly.")

obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()

obj_bird.intro()
obj_bird.flight()

obj_spr.intro()
obj_spr.flight()

obj_ost.intro()
obj_ost.flight()
Output:
c) Abstract classes:
AIM: To implement program for abstract classes

from abc import ABC, abstractmethod


class Animal(ABC):
def move(self):
pass

class Human(Animal):
def move(self):
print("I can walk and run")

class Snake(Animal):
def move(self):
print("I can crawl")

class Dog(Animal):
def move(self):
print("I can bark")

class Lion(Animal):
def move(self):
print("I can roar")

R = Human()
R.move()

K = Snake()
K.move()

R = Dog()
R.move()

K = Lion()
K.move()
OUTPUT:
Experiment-10

a )Exception Handling using try and except


AIM: To handle exceptions using try and except

Program:

def divide(x, y):


try:

result = x // y
print("Yeah ! Your answer is :", result)
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")

divide(3, 0)
Output:

b)Write a program for catching Multiple exceptions:

AIM: To write program to handle multiple exceptions

def test(x,y):

try:
print(x+y)
except (TypeError, ValueError) as e:
print(e)

test(‘a’,2)
OUTPUT:
c)Raising and Re-raising Exceptions
AIM: Program to Raise and Re-Raise exception

Program:

try:
raise NameError("Hi there") # Raise Error
except NameError:
print ("An exception")
raise
OUTPUT:

Re-raising exception:
Program:

def example():
try:
int('N/A')
except ValueError:
print("Didn't work")
raise

example()

OUTPUT:
d)Apply else and finally clause:
AIM: To apply else and finally clause

Program

(Else):

def divide(x, y):


try:

result = x // y
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
else:
print("Yeah ! Your answer is :", result)

divide(3, 2)
divide(3, 0)

OUTPUT:

(finally):

def divide(x, y):


try:

result = x // y
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
else:
print("Yeah ! Your answer is :", result)
finally:
print('This is always executed')

divide(3, 2)
divide(3, 0)
OUTPUT:

e)Demonstrate usage of polymorphism in overloading of operators.


AIM: To write program to overload operators

Program:
class complex:
def __init__(self, a, b):
self.a = a
self.b = b

def __add__(self, other):


return self.a + other.a, self.b + other.b

Ob1 = complex(1, 2)
Ob2 = complex(2, 3)
Ob3 = Ob1 + Ob2
print("Result: ")
print(Ob3)

OUTPUT:
Experiment-11

a)Create a series from a list, numpy array and dict

# Inputs

import numpy as np

mylist = list('abcedfghijklmnopqrstuvwxyz')

myarr = np.arange(26)

mydict = dict(zip(mylist, myarr))

# Solution

ser1 = pd.Series(mylist)

ser2 = pd.Series(myarr)

ser3 = pd.Series(mydict)

print(ser3.head())

a 0

b 1

c 2

d 4

e 3

dtype: int64

b)Convert the index of a series into a column of a dataframe


# Input
mylist = list('abcedfghijklmnopqrstuvwxyz')
myarr = np.arange(26)
mydict = dict(zip(mylist, myarr))
ser = pd.Series(mydict)

# Solution
df = ser.to_frame().reset_index()
print(df.head())

index 0
0 a 0
1 b 1
2 c 2
3 d 4
4 e 3

c)Combine many series to form a dataframe


# Input
import numpy as np
ser1 = pd.Series(list('abcedfghijklmnopqrstuvwxyz'))
ser2 = pd.Series(np.arange(26))

# Solution 1
df = pd.concat([ser1, ser2], axis=1)

# Solution 2
df = pd.DataFrame({'col1': ser1, 'col2': ser2})
print(df.head())
col1 col2
0 a 0
1 b 1
2 c 2
3 e 3
4 d 4

d)Assign name to the series’ index


# Input

ser = pd.Series(list('abcedfghijklmnopqrstuvwxyz'))

# Solution
ser.name = 'alphabets'

ser.head()

0 a

1 b

2 c

3 e

4 d

Name: alphabets, dtype: object

e)Get the items not common to both series A and series B


# Input

ser1 = pd.Series([1, 2, 3, 4, 5])

ser2 = pd.Series([4, 5, 6, 7, 8])

# Solution

ser_u = pd.Series(np.union1d(ser1, ser2)) # union

ser_i = pd.Series(np.intersect1d(ser1, ser2)) # intersect

ser_u[~ser_u.isin(ser_i)]

0 1
1 2

2 3

5 6

6 7

7 8

dtype: int64

f)Get the minimum, 25th percentile, median, 75th, and max of a numeric series
# Input

state = np.random.RandomState(100)

ser = pd.Series(state.normal(10, 5, 25))

# Solution

np.percentile(ser, q=[0, 25, 50, 75, 100])

array([ 1.39267584, 6.49135133, 10.2578186 , 13.06985067,


25.80920994])

g)Get frequency counts of unique items of a series


# Input
ser = pd.Series(np.take(list('abcdefgh'), np.random.randint(8,
size=30)))

# Solution
ser.value_counts()
f 8
g 7
b 6
c 4
a 2
e 2
h 1
dtype: int64

h)Bin a numeric series to 10 groups of equal size

# Input

ser = pd.Series(np.random.random(20))

print(ser.head())

# Solution

pd.qcut(ser, q=[0, .10, .20, .3, .4, .5, .6, .7, .8, .9, 1],

labels=['1st', '2nd', '3rd', '4th', '5th', '6th', '7th',


'8th', '9th', '10th']).head()

0 0.556912

1 0.892955

2 0.566632

3 0.146656

4 0.881579

dtype: float64

0 7th

1 9th

2 7th
3 3rd

4 8th

dtype: category

Categories (10, object): [1st < 2nd < 3rd < 4th ... 7th < 8th < 9th <
10th]

i)Find the positions of numbers that are multiples of 3 from a series

# Input

ser = pd.Series(np.random.randint(1, 10, 7))

ser

# Solution

print(ser)

np.argwhere(ser % 3==0)

0 6

1 8

2 6

3 7

4 6

5 2

6 4

dtype: int64
array([[0],

[2],

[4]])

j)Get the positions of items of series A in another series B

# Input

ser1 = pd.Series([10, 9, 6, 5, 3, 1, 12, 8, 13])

ser2 = pd.Series([1, 3, 10, 13])

# Solution 1

[np.where(i == ser1)[0].tolist()[0] for i in ser2]

# Solution 2

[pd.Index(ser1).get_loc(i) for i in ser2]

[5, 4, 0, 8]
Experiment-12
a.create a 1D array
arr = np.arange(10)
arr
#> array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

b.Extract items that satisfy a given condition from 1D array

# Input
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

# Solution
arr[arr % 2 == 1]
#> array([1, 3, 5, 7, 9])

c.Replace items that satisfy a condition without affecting the original array
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Desired Output:
#> array([ 0, -1, 2, -1, 4, -1, 6, -1, 8, -1])
arr[arr % 2 == 1] = -1
arr
#> array([ 0, -1, 2, -1, 4, -1, 6, -1, 8, -1])

d.Reshape an array
np.arange(10)

#> array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])


Desired Output:
#> array([[0, 1, 2, 3, 4],
#> [5, 6, 7, 8, 9]])

arr = np.arange(10)
arr.reshape(2, -1) # Setting to -1 automatically decides the number of cols
#> array([[0, 1, 2, 3, 4],
#> [5, 6, 7, 8, 9]])

e.Extract all numbers between a given range from a numpy array


a = np.array([2, 6, 1, 9, 10, 3, 27])
Desired Output:
(array([6, 9, 10]),)
a = np.arange(15)
# Method 1
index = np.where((a >= 5) & (a <= 10))
a[index]

# Method 2:
index = np.where(np.logical_and(a>=5, a<=10))
a[index]
#> (array([6, 9, 10]),)

# Method 3:
a[(a >= 5) & (a <= 10)]

f.Swap two columns in a 2d numpy array


Input
arr = np.arange(9).reshape(3,3)
arr

# Solution
arr[:, [1,0,2]]
#> array([[1, 0, 2],
#> [4, 3, 5],
#> [7, 6, 8]])

g.Import a dataset with numbers and texts keeping the text intact in python
numpy

url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')
names = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')

# Print the first 3 rows


iris[:3]
#> array([[b'5.1', b'3.5', b'1.4', b'0.2', b'Iris-setosa'],
#> [b'4.9', b'3.0', b'1.4', b'0.2', b'Iris-setosa'],
#> [b'4.7', b'3.2', b'1.3', b'0.2', b'Iris-setosa']], dtype=object)

h. Compute the mean, median, standard deviation of a numpy array

# Input
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')
sepallength = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0])
# Solution
mu, med, sd = np.mean(sepallength), np.median(sepallength),
np.std(sepallength)
print(mu, med, sd)
#> 5.84333333333 5.8 0.825301291785

i) Insert values at random positions in an array


# Input
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_2d = np.genfromtxt(url, delimiter=',', dtype='object')

# Method 1
i, j = np.where(iris_2d)

# i, j contain the row numbers and column numbers of 600 elements of iris_x
np.random.seed(100)
iris_2d[np.random.choice((i), 20), np.random.choice((j), 20)] = np.nan

# Method 2
np.random.seed(100)
iris_2d[np.random.randint(150, size=20), np.random.randint(4, size=20)] =
np.nan

# Print first 10 rows


print(iris_2d[:10])
#> [[b'5.1' b'3.5' b'1.4' b'0.2' b'Iris-setosa']
#> [b'4.9' b'3.0' b'1.4' b'0.2' b'Iris-setosa']
#> [b'4.7' b'3.2' b'1.3' b'0.2' b'Iris-setosa']
#> [b'4.6' b'3.1' b'1.5' b'0.2' b'Iris-setosa']
#> [b'5.0' b'3.6' b'1.4' b'0.2' b'Iris-setosa']
#> [b'5.4' b'3.9' b'1.7' b'0.4' b'Iris-setosa']
#> [b'4.6' b'3.4' b'1.4' b'0.3' b'Iris-setosa']
#> [b'5.0' b'3.4' b'1.5' b'0.2' b'Iris-setosa']
#> [b'4.4' nan b'1.4' b'0.2' b'Iris-setosa']
#> [b'4.9' b'3.1' b'1.5' b'0.1' b'Iris-setosa']]

j) Find the count of unique values in a numpy array

url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')
names = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')

# Solution
# Extract the species column as an array
species = np.array([row.tolist()[4] for row in iris])

# Get the unique values and the counts


np.unique(species, return_counts=True)
#> (array([b'Iris-setosa', b'Iris-versicolor', b'Iris-virginica'],
#> dtype='|S15'), array([50, 50, 50]))

You might also like