Python Lab Manual
Python Lab Manual
id(object)
Return Value from id():The id() function returns identity of the object. This is an integer which is unique for
the given object and remains constant during its lifetime
Program 1:
Demonstrate the working of ‘id’ and ‘type’ functions.
(i)Program:-
>>>list=[1,2,3]
>>>id(list[0])
21127896
>>>id(list[1])
21127884
>>>id(list[2])
21127872
(ii)Program:-
print('id of 5 =',id(5))
a=5
print('id of a =',id(a))
b=a
print('id of b =',id(b))
c = 5.0
print('id of c =',id(c))
Output:-
id of 5 = 140472391630016
id of a = 140472391630016
id of b = 140472391630016
id of c = 140472372786520
Hence, integer 5 has a unique id. The id of the integer 5 remains constant during the lifetime. Similar is
the case for float 5.5 and other objects.
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.
type(object)
type(name, bases, dict)
If the single object argument is passed to type(), it returns type of the given object.
(i)Program:-
numberList = [1, 2]
print(type(numberList))
print(type(numberDict))
class Foo:
a=0
InstanceOfFoo = Foo()
print(type(InstanceOfFoo))
Output:-
<class 'dict'>
<class 'Foo'>
Output:-
<class 'type'>
{'b': 12, 'a': 'Foo', '__dict__': <attribute '__dict__' of 'X' objects>, '__doc__': None,
'__weakref__': <attribute '__weakref__' of 'X' objects>}
<class 'type'>
{'b': 12, 'a': 'Foo', '__doc__': None}
In the program, we have used Python vars() function return the __dict__ attribute. __dict__is used to store
object's writable attributes.
Program 2:
Python Program to Print all the Prime Numbers within a Given Range.
Program:-
# Python program to display all the prime numbers within an interval
lower = 900
upper = 1000
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
Output:-
907
911
919
929
937
941
947
953
967
971
977
983
991
997
Program 3:
To Print ‘n terms of the Fibonacci series.
Program:-
# Program to display the Fibonacci sequence up to n-th term where n is provided by the user
# change this value for a different result
nterms = 10
# uncomment to take input from the user
#nterms = int(input("How many terms? "))
# first two terms
n1 = 0
n2 = 1
count = 0
A Python slice extracts elements, based on a start and stop. We take slices on many types in Python.
We specify an optional first index, an optional last index, and an optional step.
Output
[200, 300]
Negative. The second index in slice notation may be negative. This means counting begins from
the last index. So a negative one means the same as "length minus one."
Output
[300, 400]
Start, end. In slicing, if you omit the first or second index, it means "start" or
"end." This is clearer than specifying 0 or the length.
Output
[100, 200]
[300, 400, 500]
Strings. We use the slice notation on strings. In this example, we omit the first
index to start at the beginning, and then consume four characters total. We
extract the first four letters.Substring
Python program that slices string
word = "something"
# Get first four characters.
part = word[:4]
print(part)
Output
some
Copy. With slicing, we can copy sequences like lists. We assign a new list
variable to a slice with no specified start or stop values. So the slice copies the
entire list and returns it.Copy List
Python program that uses step, slices
values = "AaBbCcDdEe"
Output
ABCDE
Program 5:
(a)Program to add 'ing' at the end of a given string (length should be at least 3). If
the given string is already ends with 'ing' then add 'ly' instead. If the string length
of the given string is less than 3, leave it unchanged
Program:-
1. def add_string(str1):
2. length = len(str1)
3.
4. if length > 2:
5. if str1[-3:] == 'ing':
6. str1 += 'ly'
7. else:
8. str1 += 'ing'
9.
10. return str1
11. print(add_string('ab'))
12. print(add_string('abc'))
13. print(add_string('string'))
Output:-
14. ab
15. abcing
16. stringly
(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:
str1=input(“Enter a String:”)
Print(“Original String:”str1)
char=str1[0]
str1=str1.replace(char,’$’)
str1=char+str1[1:]
Print(“Replaced String:”,str1)
Output:
Enter a String:onion
Original String:onion
Replaced String:oni$n
Program 6:
(a)Write a program 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])
Output:
Suppose the following input is supplied to the program:
New to Python or choosing between Python 2 and Python 3? Read Python 2 or
Python 3.
Then, the output should be:
2:2
3.:1
3?:1
New:1
Python:5
Read:1
and:1
between:1
choosing:1
or:2
to:1
(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:-
Output:-
Program:-
s = raw_input()
words = [word for word in s.split(" ")]
print " ".join(sorted(list(set(words))))
Output:-
The list is a most versatile datatype available in Python which can be written as a list of comma-
separated values (items) between square brackets. Important thing about a list is that items in a
list need not be of the same type.
Program:-
#!/usr/bin/python
list2 = [1, 2, 3, 4, 5, 6, 7 ];
Output:-
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
(ii)Updating Lists
#!/usr/bin/python
print list[2]
list[2] = 2001;
print list[2]
Output:-
Output:-
1
1
-1
(ii) len(list)
Gives the total length of the list.
#!/usr/bin/python
Output:-
(iii) max(list)
#!/usr/bin/python
Output:-
Max value element : zara
Max value element : 700
(iv) list(seq)
aList = list(aTuple)
Output:-
List elements : [123, 'xyz', 'zara', 'abc']
Program 9:
To demonstrate use of Dictionary & related functions.
To access dictionary elements, you can use the familiar square brackets along with the key to
obtain its value.
#!/usr/bin/python
Output:-
dict['Name']: Zara
dict['Age']: 7
Updating Dictionary
#!/usr/bin/python
Output:-
dict['Age']: 8
dict['School']: DPS School
(iii)
(ii) len(dict): Gives the total length of the dictionary. This would be equal to the
number of items in the dictionary.
#!/usr/bin/python
Output:-
Length : 2
#!/usr/bin/python
Output:-
Equivalent String : {'Age': 7, 'Name': 'Zara'}
(iv) type(variable)
Output:-
Variable Type : <type 'dict'>
Program 10:
To demonstrate use of tuple & related functions.
To access values in tuple, use the square brackets for slicing along with the index or indices to
obtain value available at that index.
#!/usr/bin/python
tup2 = (1, 2, 3, 4, 5, 6, 7 );
Output:-
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Updating Tuples
#!/usr/bin/python
# tup1[0] = 100;
print tup3;
Output:
(12, 34.56, 'abc', 'xyz')
(ii)len(tuple)
Output:
First tuple length : 3
Second tuple length : 2
(iii) max(tuple)
Output:
Max value element : zara
Max value element : 700
(iv) tuple(seq)
aTuple = tuple(aList)
Output:
Tuple elements : (123, 'xyz', 'zara', 'abc')
Program 11:
To implement stact using list.
Stack works on the principle of “Last-in, first-out”. Also, the inbuilt functions in Python make the code short and
simple. To add an item to the top of the list, i.e., to push an item, we use append() function and to pop out an
element we use pop() function. These functions work quiet efficiently and fast in end operations.
Output:-
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'])
Program 13:
To read and write from a file.
file1 = open("myfile.txt","r+")
file1.seek(0)
file1.seek(0)
file1.seek(0)
# readlines function
print "Output of Readlines function is "
print file1.readlines()
print
file1.close()
Output:-
Output of Read function is
Hello
This is Delhi
This is Paris
This is London
Th
while True:
print("Do you like to print the file ? (y/n): ")
check = input()
if check == 'n':
break
elif check == 'y':
file = open(target, "r")
print("\nHere follows the file content:\n")
print(file.read())
file.close()
print()
break
else:
continue
Program 15:
To demonstrate working of classes and objects.
class MyClass:
"This is my second class"
a = 10
def func(self):
print('Hello')
# Output: 10
print(MyClass.a)
# Output: <function MyClass.func at 0x0000000003079BF8>
print(MyClass.func)
# Output: 'This is my second class'
print(MyClass.__doc__)
Output:-
10
10
<function MyClass.func at 0x7fe50c74d598>
This is my second class
In [1]:
Objects:-
Program:-
class MyClass:
"This is my second class"
a = 10
def func(self):
print('Hello')
Output:-
<function MyClass.func at 0x7fe50f75a048>
<bound method MyClass.func of <__main__.MyClass object at 0x7fe50f7577b8>>
Hello
Program 16:
To demonstrate Constructors.
Program:-
class ComplexNumber:
def __init__(self,r = 0,i = 0):
self.real = r
self.imag = i
def getData(self):
print("{0}+{1}j".format(self.real,self.imag))
Output:-
2+3j
(5, 0, 10)