Вы находитесь на странице: 1из 19

# I.T.

S ENGINEERING COLLEGE
GR. NOIDA

& ENGINEERING

LAB MANUAL

RCS-454

## I.T.S Engineering College

Plot No. 46, Knowledge Park-III
Greater Noida-201308 (U.P)
Exp . 1. Demonstrate the working of ‘id’ and ‘type’ functions

## Sol. Python id()

The id() function returns identity (unique integer) of an object. This identity has to be unique
and constant for this object during the lifetime.The id() function takes a single
parameter object.

Program :- a=5

print('id of a =',id(a))

Output :- id of a = 140472391630016

Python type()
If a single argument (object) is passed to type() built-in, it returns type of the given object. If three
arguments (name, bases and dict) are passed, it returns a new type object.
Program:- a=5

print(type(a))

## Exp. 2. To find all prime numbers within a given range.

Program:- lower = 2
upper = 50
print("Prime numbers between",lower,"and",upper,"are:")
for num in range(lower,upper + 1):
# prime numbers are greater than 1

if num > 1:

for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)

Program

n1 = 0

n2 = 1

count = 0

print(n1)

nth = n1 + n2

# update values

n1 = n2

n2 = nth

count += 1

## Exp. 4. To demonstrate use of slicing in string

Program

pyString = 'Python'
sObject = slice(3)
print(pyString[sObject])
sObject = slice(1, 5, 2)
print(pyString[sObject])
Output
Pyt
Yh

Exp. 5. a. To add 'ing' at the end of a given string (length should be at least 3). If the given
string already ends with 'ing' then add 'ly' instead. If the string length of the given string is
less than 3, leave it unchanged.

## Expected Result : 'stringly'

Program

length = len(str1)

if length > 2:

if str1[-3:] == 'ing':

str1 += 'ly'

else:

str1 += 'ing'

return str1

Output

ab

abcing

stringly
Exp. 5. b. To get a string from a given string where all occurrences of its first char have been
changed to '\$', except the first char itself.

Program
s='asdaweaasq'
firstchar = s
modifiedstr = s[1:].replace(firstchar, "*")
print(firstchar + modifiedstr)
Output
asd*we**sq

Exp. 6. a. To compute the frequency of the words from the input. The output should output
after sorting the key alphanumerically.

Program

## freq = {} # frequency of words in text

line = raw_input()
for word in line.split():

freq[word] = freq.get(word,0)+1

words = freq.keys()

words.sort()

for w in words:

## print "%s:%d" % (w,freq[w])

Input : New to Python or choosing between Python 2 and Python 3? Read Python 2 or
Python 3.

Output:

2:2

3:1

3?:1

New:1

Python:5

And:1

Between:1

Chossing:1

Or:1

To:1

6 b. Write a program that accepts a comma separated sequence of words as input and
prints the words in a comma-separated sequence after sorting them alphabetically.

Program:
items=[x for x in
raw_input().split(',')
]
items.sort()
print ','.join(items)

Input: without,hello,bag,world
Output: bag,hello,without,world

## 7. Write a program that accepts a sequence of whitespace separated words as input

and prints the words after removing all duplicate words and sorting them
alphanumerically.

Program

s = raw_input()
words = [word for word in s.split(" ")]
print " ".join(sorted(list(set(words))))

Input: hello world and practice makes perfect and hello world again
Output: again and hello makes perfect practice world

## 8. To demonstrate use of list & related functions

my_list = ['p','r','o','b','e']
# Output: p
print(my_list)

# Output: o
print(my_list)

# Output: e
print(my_list)

# Output: e
print(my_list[-1])
Program :- # change the 1st item
My_list =
a = ["bee", "moth"]
print(a)
a.append("ant")
print(a)
output:-

## output: ['bee', 'moth']

['bee', 'moth', 'ant']

Program :-
a = ["bee", "moth"]
print(a)
a.insert(0, "ant")
print(a)
a.insert(2, "fly")
print(a)
output:-

['bee', 'moth']
['ant', 'bee', 'moth']
['ant', 'bee', 'fly', 'moth']
remove(x):- Removes the first item from the list that has a value of x. Returns an error if there
is no such item.
reverse():-Reverses the elements of the list in place.

## my_dict = {'name':'Jack', 'age': 26}

# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
# update value
my_dict['age'] = 27

print(my_dict)

## # Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}

print(my_dict)

clear(
Remove all items form the dictionary.
)
10. To demonstrate use of tuple, set& related functions

# empty tuple

# Output: ()

my_tuple = ()

print(my_tuple)

## # tuple having integers

# Output: (1, 2, 3)

my_tuple = (1, 2, 3)

print(my_tuple)

print(my_tuple)

# nested tuple

print(my_tuple)

print(my_tuple)

## # tuple unpacking is also possible

# Output:

#3

# 4.6

# dog

a, b, c = my_tuple

print(a)

print(b)

print(c)

## # set do not have duplicates

# Output: {1, 2, 3, 4}

my_set = {1,2,3,4,3,2}

print(my_set)
# set cannot have mutable items

## # we can make set from a list

# Output: {1, 2, 3}

my_set = set([1,2,3,2])

print(my_set)

## # Python code to demonstrate Implementing

# stack using list
stack = ["Amar", "Akbar", "Anthony"]
stack.append("Ram")
stack.append("Iqbal")
print(stack)
print(stack.pop())
print(stack)
print(stack.pop())
print(stack)

Output:-
['Amar', 'Akbar', 'Anthony', 'Ram', 'Iqbal']
Iqbal
['Amar', 'Akbar', 'Anthony', 'Ram']
Ram
['Amar', 'Akbar', 'Anthony']
12. To implement queue using list

## # Python code to demonstrate Implementing

# Queue using deque and list
from collections import deque
queue = deque(["Ram", "Tarun", "Asif", "John"])
print(queue)
queue.append("Akbar")
print(queue)
queue.append("Birbal")
print(queue)
print(queue.popleft())
print(queue.popleft())
print(queue)

Output:-
deque(['Ram', 'Tarun', 'Asif', 'John'])
deque(['Ram', 'Tarun', 'Asif', 'John', 'Akbar'])
deque(['Ram', 'Tarun', 'Asif', 'John', 'Akbar', 'Birbal'])
Ram
Tarun
deque(['Asif', 'John', 'Akbar', 'Birbal'])
13. To read and write from a file

## # Program to show various ways to read and

# write data in a file.
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]

# \n is placed to indicate EOL (End of Line)
file1.write("Hello \n")
file1.writelines(L)
file1.close() #to change file access modes

file1 = open("myfile.txt","r+")

print "Output of Read function is "
print

# seek(n) takes the file handle to the nth
# bite from the beginning.
file1.seek(0)

print "Output of Readline function is "
print

file1.seek(0)

print "Output of Read(9) function is "
print

file1.seek(0)

print "Output of Readline(9) function is "

file1.seek(0)
print "Output of Readlines function is "
print
file1.close()
Output:-

Hello
This is Delhi
This is Paris
This is London

Hello

Hello
Th

Hello

## Output of Readlines function is

['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']
14. To copy a file

with open("test.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
f1.write(line)

## 15. To demonstrate working of classes and objects

class MyClass:
"This is my second class"
a = 10
def func(self):
print('Hello')

ob = MyClass()

## # Output: <function MyClass.func at 0x000000000335B0D0>

print(MyClass.func)

## # Output: <bound method MyClass.func of <__main__.MyClass object at

0x000000000332DEF0>>
print(ob.func)

# Output: Hello
ob.func()

## 16. To demonstrate class method & static method

class Mathematics:
return x + y

## print('The sum is:', Mathematics.addNumbers(5, 10))

Output:- the sum is 15

## 17. To demonstrate constructors

class TestClass:

def __init__(self):

print ("constructor")

def __del__(self):

print ("destructor")

if __name__ == "__main__":

obj = TestClass()

del obj

## 18. To demonstrate inheritance

class Polygon:
def __init__(self, no_of_sides):
self.n = no_of_sides
self.sides = [0 for i in range(no_of_sides)]

def inputSides(self):
self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i in range(self.n)]

def dispSides(self):
for i in range(self.n):
print("Side",i+1,"is",self.sides[i])
class Triangle(Polygon):
def __init__(self):
Polygon.__init__(self,3)

def findArea(self):
a, b, c = self.sides
# calculate the semi-perimeter
s = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)

Output:-

>>> t = Triangle()
>>> t.inputSides()
Enter side 1 : 3
Enter side 2 : 5
Enter side 3 : 4

>>> t.dispSides()
Side 1 is 3.0
Side 2 is 5.0
Side 3 is 4.0

>>> t.findArea()
The area of the triangle is 6.00

## 19. To demonstrate aggregation/composition

Composition

In compostion one of the classes is composed of one or more instance of other classes. In other
words one class is container and other class is content and if you delete the container object
then all of its contents objects are also deleted.

Now lets see an example of composition in Python 3.5. Class Employee is container and class
Salary is content.

class Salary:
def __init__(self,pay):
self.pay=pay

def get_total(self):
return (self.pay*12)

class Employee:
def __init__(self,pay,bonus):
self.pay=pay
self.bonus=bonus
self.obj_salary=Salary(self.pay)

def annual_salary(self):
return "Total: " + str(self.obj_salary.get_total()+self.bonus)

obj_emp=Employee(100,10)
print (obj_emp.annual_salary())

Aggregation

Aggregation is a week form of compostion. If you delete the container object contents objects
can live without container object.

Now lets see an example of aggregation in Python 3.5. Again Class Employee is container and
class Salary is content.

class Salary:
def __init__(self,pay):
self.pay=pay

def get_total(self):
return (self.pay*12)

class Employee:
def __init__(self,pay,bonus):
self.pay=pay
self.bonus=bonus

def annual_salary(self):
return "Total: " + str(self.pay.get_total()+self.bonus)

obj_sal=Salary(100)
obj_emp=Employee(obj_sal,10)
print (obj_emp.annual_salary())

20. To create a small GUI application for insert, update and delete in a table using Oracle as
backend and front end for creating form

The script below will store data into a new database called user.db

## import sqlite3 as lite

import sys

con = lite.connect('user.db')

with con:

cur = con.cursor()
cur.execute("CREATE TABLE Users(Id INT, Name TEXT)")
cur.execute("INSERT INTO Users VALUES(1,'Michelle')")

This will output all data in the Users table from the database:

## import sqlite3 as lite

import sys

con = lite.connect('user.db')

with con:

cur = con.cursor()
cur.execute("SELECT * FROM Users")

rows = cur.fetchall()

for row in rows:
print row