Python Lab Manual
Python Lab Manual
S ENGINEERING COLLEGE
GR. NOIDA
LAB MANUAL
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))
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
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.
Program
def add_string(str1):
length = len(str1)
if length > 2:
if str1[-3:] == 'ing':
str1 += 'ly'
else:
str1 += 'ing'
return str1
print(add_string('ab'))
print(add_string('abc'))
print(add_string('string'))
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[0]
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
line = raw_input()
for word in line.split():
freq[word] = freq.get(word,0)+1
words = freq.keys()
words.sort()
for w in words:
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
Read:1
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
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
my_list = ['p','r','o','b','e']
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
# Output: e
print(my_list[-1])
Program :- # change the 1st item
My_list[0] =
a = ["bee", "moth"]
print(a)
a.append("ant")
print(a)
output:-
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.
clear(
Remove all items form the dictionary.
)
10. To demonstrate use of tuple, set& related functions
# empty tuple
# Output: ()
my_tuple = ()
print(my_tuple)
# Output: (1, 2, 3)
my_tuple = (1, 2, 3)
print(my_tuple)
# nested tuple
print(my_tuple)
print(my_tuple)
# Output:
#3
# 4.6
# dog
a, b, c = my_tuple
print(a)
print(b)
print(c)
# Output: {1, 2, 3, 4}
my_set = {1,2,3,4,3,2}
print(my_set)
# set cannot have mutable items
# Output: {1, 2, 3}
my_set = set([1,2,3,2])
print(my_set)
Output:-
['Amar', 'Akbar', 'Anthony', 'Ram', 'Iqbal']
Iqbal
['Amar', 'Akbar', 'Anthony', 'Ram']
Ram
['Amar', 'Akbar', 'Anthony']
12. To implement queue using list
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
with open("test.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
f1.write(line)
class MyClass:
"This is my second class"
a = 10
def func(self):
print('Hello')
class Mathematics:
def addNumbers(x, y):
return x + y
class TestClass:
def __init__(self):
print ("constructor")
def __del__(self):
print ("destructor")
if __name__ == "__main__":
obj = TestClass()
del obj
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
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
This will output all data in the Users table from the database: