Python Lab Manual 2023
Python Lab Manual 2023
LAB FILE
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
Table of Contents
UNIT-I
II. Program to demonstrate the use of if, if-else, while, for, break and continue
IV. Program to demonstrate the various kind of operations that can be applied
to the string.
X Program to demonstrate read and write data to the file in various modes.
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
UNIT – 1
Experiment – 1.1
Writing python programs in various modes and printing and assigning values
assigned to the variables
C:\>
You need to realize that your Python scripts have to be processed by another program called the
Python interpreter. The interpreter reads your script, compiles it into byte codes, and then executes
the byte codes to run your program. So, how do you arrange for the interpreter to handle your
Python?
First, you need to make sure that your command window recognizes the word “python” as an
instruction to start the interpreter. If you have opened a command window, you should try entering
the command python and hitting return.
C:\Users\YourName> python
Python 2.7.3 (default, Apr 10 2012, 22.71:26) [MSC v.1500 32 bit (Intel)] on win32
>>>
You have started the interpreter in “interactive mode”. That means you can enter Python
statements or expressions interactively and have them executed or evaluated while you wait. This
is one of Python’s strongest features. Check it by entering a few expressions of your choice and
seeing the results:
Hello
>>> "Hello" * 3
'HelloHelloHello'
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
On Windows, the standard Python installer already associates the .py extension with a file type
(Python.File) and gives that file type an open command that runs the interpreter (D:\Program
Files\Python\python.exe "%1" %*). This is enough to make scripts executable from the command
prompt as ‘foo.py’. If you’d rather be able to execute the script by simple typing ‘foo’ with no
extension you need to add .py to the PATHEXT environment variable.
What is IDLE?
IDLE is the integrated development environment (IDE) provided with Python. An IDE combines
a program editor and a language environment as a convenience to the programmer. Using IDLE
is not a requirement for using Python. There are many other IDEs that can be used to write Python
programs, not to mention a variety of text-based programmer's editors that many programmers
prefer to IDEs.
We are covering IDLE because it comes with Python, and because it is not too complex for
beginning programmers to use effectively. You are welcome to use another editor or IDE if you
wish, but if you don't already know one, IDLE is a good choice.
The top of IDLE's Python Shell window will look something like this:
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
Let's give it a try. Click on the Python Shell window (to make sure that it has the keyboard's
attention) and then type this line, just like you see it:
In interactive mode, Python displays the results of expressions. In script mode, however, Python
doesn’t automatically display results.
In order to see output from a Python script, we’ll introduce the print statement and the print()
function.
The print()function is a new Python 3 construct that will replace the print statement. We’llvisit this
topic in depth in Seeing Output with the print() Function (or print Statement).
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
For now, you can use either one. We’ll show both. In the future, the print statement will be
removed from the language.
The print statement takes a list of values and prints their string representation on the standard
output file. The standard output is typically directed to the Terminal window.
We can have the Python interpreter execute our script files. Application program scripts can be
of any size or complexity. For the following examples, we’ll create a simple, two-line script,
called example1.py.
example1.py
The print()function
The print()functions takes a list of values and prints their string representation on the standard
output file. The standard output is typically directed to the Terminal window.
Until Python 3, we have to request the print()function with a special introductory statement:
from future import print_function .
We can have the Python interpreter execute our script files. Application program scripts can be
of any size or complexity. For the following examples, we’ll create a simple, two-line script,
called example1.py.
example1.py
Running a Script
There are several ways we can start the Python interpreter and have it evaluate our script file.
Explicitly from the command line. In this case we’ll be running Python and providing the
name of the script as an argument.
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
Implicitly from the command line. In this case, we’ll either use the GNU/Linux shell
comment (sharp-bang marker) or we’ll depend on the file association in Windows.
This is slightly more complex, and we’ll look at this in detail below.
Manually from within IDLE . It’s important for newbies to remember that IDLE
shouldn’t be part of the final delivery of a working application. However, this is a great
way to start development of an application program.
Running Python scripts from the command-line applies to all operating systems. It is the core of
delivering final applications. We may add an icon for launching the application, but under the
hood, an application program is essentially a command-line start of the Python interpreter.
In algebra, variables represent numbers. The same is true in Python, except Python variables also
can represent values other than numbers. Listing 2.1 (variable.py) uses a variable to store an integer
value and then prints the value of the variable.
x = 10
print(x)
x = 10
This is an assignment statement. An assignment statement associates a value with a variable. The
key to an assignment statement is the symbol = which is known as the assignment operator. The
statement assigns the integer value 10 to the variable x. Said another way, this statement binds
the variable named x to the value 10. At this point the type of x is int because it is bound to an
integer value.
A variable may be assigned and reassigned as often as necessary. The type of a variable will change
if it is reassigned an expression of a different type.
print(x)
This statement prints the variable x’s current value. Note that the lack of quotation marks here is
very important. If x has the value 10, the statement
print(x)
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
print('x')
The meaning of the assignment operator (=) is different from equality in mathematics. In
mathematics, asserts that the expression on its left is equal to the expression on its right. In Python,
= makes the variable on its left take on the value of the expression on its right. It is best to read x
= 5 as “x is assigned the value 5,” or “x gets the value 5.” This distinction is important since in
mathematics equality is symmetric: if x = 5, we know 5 = x. In Python this symmetry does not
exist; the statement
5=x
attempts to reassign the value of the literal integer value 5, but this cannot be done because 5 is
always 5 and cannot be changed. Such a statement will produce an error.
>>>x = 5
>>>x
5
>>> 5 = x
File "<stdin>", line 1
Syntax Error: can’t assign to literal
2: multipleassignment.py
x = 10
x = 20
x = 30
Observe that each print statement in Listing 2.2 (multipleassignment.py) is identical, but when the
program runs (as a program, not in the interactive shell) the print statements produce differentresults:
>X=10
X=20
X=30
The variable x has type int, since it is bound to an integer value. Observe how Listing 2.2
(multipleassignment.py) uses the str function to treat x as a string so the + operator will use
string concatenation:
Output:
>>>
10
ravi
20000.67
>>>
print x
print y
print z
Output:
>>>
50
50
50
>>>
a,b,c=5,10,15
print a
print b
print c
Output:
>>>
5
10
15
>>>
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
Experiment – 1.2
Program to demonstrate the use of if, if-else, while, for, break and continue
a=10
if a==10:
print "Hello User"
Output:
Hello User
year=2000
if year%4==0:
print "Year is Leap"else:
print "Year is not Leap"
Output:
Year is Leap
a=10
if a>=20:
print "Condition is True"else:
if a>=15:
print "Checking second value"else:
print "All Conditions are false"
Output:
All Conditions are false.
sum=0
for n in range(1,11):
sum+=n
print sum
Output:
55
for i in range(1,6):
for j in range (1,i+1):
print i,
print
Output:
>>>
1
22
333
4444
55555
>>>
n=153
sum=0
while n>0:r=n%10
sum+=rn=n/10
print sum
Output:
>>>
9
>>>
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
for i in [1,2,3,4,5]: if
i==4:
print "Element found"
break
print i,
Output:
>>>
1 2 3 Element found
>>>
a=0
while a<=5:
a=a+1
if a%2==0:
continue
print a
print "End of Loop"
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
Experiment-1.3
Program to demonstrate the use of functions and passing different types of
arguments to functions.
def sum(x,y):
"Going to add x and y"
s=x+y
print "Sum of two numbers is"print
s
#Calling the sum Function
sum(10,20)
sum(20,30)
>>>
Sum of two numbers is
30
Sum of two numbers is
50
>>>
def sum(a,b):
"Adding the two values"
print "Printing within Function"print
a+b
return a+b
def msg():
print "Hello"
return
total=sum(10,20)
print ?Printing Outside: ?,total
msg()
print "Rest of code"
Output
>>>
Printing within Function
30 CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
Printing outside: 30
Hello
Rest of code
>>>
def addition(x,y):
print x+y
x=15
addition(x,10)
addition(x,x)
y=20
addition(x,y)
Output:
>>>
25
30
35
>>>
#Function Definition
def msg(Id,Name,Age=21): "Printing
the passed value"print Id
print Name
print Age
return
#Function call
msg(Id=100,Name='Ravi',Age=20)
msg(Id=101,Name='Ratan')
Output:
>>>
100
Ravi
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
20
101
Ratan
21
>>>
def msg(id,name):
"Printing passed value"
print id
print name
return
msg(id=100,name='Raj')
msg(name='Rahul',id=101)
Output:
>>>
100
Raj
101
Rahul
>>>
msg()
print a #it will show error since variable is local
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
Value of a is 10
Global Variable:
b=20
def msg():
a=10
print "Value of a is",a
print "Value of b is",b
return
msg()
print b
Output:
>>>
Value of a is 10
Value of b is 20
20
>>>
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
UNIT-II
Experiment-2.1
Program to demonstrate the various kind of operations that can be applied
to the string.
Output:
>>>
R t
a a
j j
a a
t R
>>>
Output:
'ratanjaiswal'
>>>
Output:
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
'VimalVimalVimalVimalVimal'
>>> str1="javatpoint"
>>> str2='sssit'
>>> str3="seomount"
>>> str4='java'
>>> st5="it"
>>> str6="seo"
>>> str4 in str1
True
>>> str5 in str2
>>> st5 in str2
True
>>> str6 in str3
True
>>> str4 not in str1
False
>>> str1 not in str4
True
>>> "RAJAT"=="RAJAT"
True
>>> "afsha">='Afsha'
True
>>> "Z"<>"z"
True
>>> str="Nikhil"
>>> str[0:6]
'Nikhil'
>>> str[0:3]
'Nik'
>>> str[2:5]
'khi'
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
>>> str[:6]
'Nikhil'
>>> str[3:]
'hil'
>>> str="Mahesh"
>>> str[:6]+str[6:]
'Mahesh'
1) capitalize()
>>> 'abc'.capitalize()
Output:
'Abc'
2) count(string)
msg = "welcome to sssit";
substr1 = "o";
print msg.count(substr1, 4, 16)
substr2 = "t";
print msg.count(substr2)
Output:
>>>
2
2
>>>
3) endswith(string)
string1="Welcome to SSSIT";
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
substring1="SSSIT";
substring2="to"; substring3="of";
print string1.endswith(substring1);
print string1.endswith(substring2,2,16);
print string1.endswith(substring3,2,19);
print string1.endswith(substring3);
Output:
>>>
True
False
False
False
>>>
4) find(string)
str="Welcome to SSSIT";
substr1="come";
substr2="to";
print str.find(substr1);
print str.find(substr2);
print str.find(substr1,3,10);
print str.find(substr2,19);
Output:
>>>
3
8
3
-1
>>>
5) index(string)
substr2="of";
print str.index(substr1); print
str.index(substr2); print
str.index(substr1,3,10); print
str.index(substr2,19);
Output:
>>>
3
17
3
Traceback (most recent call last):
File "C:/Python27/fin.py", line 7, in
print str.index(substr2,19);
ValueError: substring not found
>>>
6) isalnum()
str="Welcome to sssit";
print str.isalnum();
str1="Python47"; print
str1.isalnum();
Output:
>>>
False
True
>>>
7) isalpha()
8) isdigit()
string1="HelloPython";
print string1.isdigit();
string2="98564738" print
string2.isdigit();
Output:
>>>
False
True
>>>
9) islower()
string1="Hello Python";
print string1.islower();
string2="welcome to "
print string2.islower();
Output:
>>>
False
True
>>>
10) isupper()
string1="Hello Python"; print
string1.isupper();
string2="WELCOME TO"print
string2.isupper();
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
Output:
>>>
False
True
>>>
11) isspace()
string1=" ";
print string1.isspace();
string2="WELCOME TO WORLD OF PYT"
print string2.isspace();
Output:
>>>
True
False
>>>
12) len(string)
string1=" ";
print len(string1);
string2="WELCOME TO SSSIT"
print len(string2);
Output:
>>>
4
16
>>>
13) lower()
string1="Hello Python";
print string1.lower();
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
string2="WELCOME TO SSSIT"
print string2.lower();
Output:
>>>
hello python
welcome to sssit
>>>
14) upper()
string1="Hello Python";
print string1.upper();
string2="welcome to
SSSIT"
print string2.upper();
Output:
>>>
HELLO PYTHON
WELCOME TO SSSIT
>>>
15) startswith(string)
string1="Hello Python";
print string1.startswith('Hello');
string2="welcome to SSSIT"
print string2.startswith('come',3,7);
Output:
>>>
True
True
>>>
16) swapcase()
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
Output:
>>>
hELLO pYTHON
WELCOME TO sssit
>>>
17) lstrip()
Output:
>>>
Hello Python
welcome to world to SSSIT
>>>
18) rstrip()
Output:
>>>
Hello Python
@welcome to SSSIT
>>>
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
Experiment-2.2
Program to demonstrate creation and accessing of lists and apply different
kinds of operations on them.
data1=[1,2,3,4];
data2=['x','y','z'];
print data1[0] print
data1[0:2] print
data2[-3:-1] print
data1[0:] print
data2[:2]
Output:
>>>
>>>
1
[1, 2]
['x', 'y']
[1, 2, 3, 4]
['x', 'y']
>>>
a) Adding Lists:
Lists can be added by using the concatenation operator(+) to join two lists. list1=[10,20]
list2=[30,40]
list3=list1+list2
print list3
Output:
>>>
[10, 20, 30, 40]
>>>
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
b) Replicating lists:
list1=[10,20]
print list1*1
Output:
>>>
[10, 20]
>>>
c) List slicing:
A subpart of a list can be retrieved on the basis of index. This subpart isknown as list slice.
list1=[1,2,4,5,7]
print list1[0:2]
print list1[4]
list1[1]=9 print
list1
Output:
>>>
[1, 2]
7
[1, 9, 4, 5, 7]
>>>
data1=[5,10,15,20,25]
print "Values of list are: "print
data1
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
Output:
>>>
Values of list are:
[5, 10, 15, 20, 25]
Values of list are:
[5, 10, 'Multiple of 5', 20, 25]
>>>
list1=[10,"rahul",'z']
print "Elements of List are: "print
list1 list1.append(10.45)
print "List after appending: "print
list1
Output:
>>>
Elements of List are:
[10, 'rahul', 'z']
List after appending:
[10, 'rahul', 'z', 10.45]
>>>
Output:
>>>
[10, 'rahul', 50.8, 'a', 20, 30]
['rahul', 50.8, 'a', 20, 30]
[20, 30]
>>>
1) min(list):
Eg:
list1=[101,981,'abcd','xyz','m']
list2=['aman','shekhar',100.45,98.2]
print "Minimum value in List1: ",min(list1) print
"Minimum value in List2: ",min(list2)
Output:
>>>
Minimum value in List1: 101
Minimum value in List2: 98.2
>>>
2) max(list):
Eg:
list1=[101,981,'abcd','xyz','m']
list2=['aman','shekhar',100.45,98.2]
print "Maximum value in List : ",max(list1) print
"Maximum value in List : ",max(list2)
Output:
>>>
Maximum value in List : xyz
Maximum value in List : shekhar
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
>>>
3) len(list):
Eg:
list1=[101,981,'abcd','xyz','m']
list2=['aman','shekhar',100.45,98.2]
print "No. of elements in List1: ",len(list1) print
"No. of elements in List2: ",len(list2)
Output:
>>>
No. of elements in List1 : 5No.
of elements in List2 : 4
>>>
4) cmp(list1,list2):
Explanation: If elements are of the same type, perform the comparison and return the
result. If elements are different types, check whether they are numbers.
If we reached the end of one of the lists, the longer list is "larger." If bothlist are same it
returns 0.
Eg:
list1=[101,981,'abcd','xyz','m']
list2=['aman','shekhar',100.45,98.2]
list3=[101,981,'abcd','xyz','m'] print
cmp(list1,list2)
print cmp(list2,list1)
print cmp(list3,list1)
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
Output:
>>>
-1
1
0
>>>
5) list(sequence):
Eg:
seq=(145,"abcd",'a')
data=list(seq)
print "List formed is : ",data
Output:
>>>
List formed is : [145, 'abcd', 'a']
>>>
1) index(object):
Eg:
data = [786,'abc','a',123.5]
print "Index of 123.5:", data.index(123.5) print
"Index of a is", data.index('a')
Output:
>>>
Index of 123.5 : 3
Index of a is 2
>>>
2) count(object):
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
Eg:
data = [786,'abc','a',123.5,786,'rahul','b',786]
print "Number of times 123.5 occured is", data.count(123.5) print
"Number of times 786 occured is", data.count(786)
Output:
>>>
Number of times 123.5 occured is 1
Number of times 786 occured is 3
>>>
3) pop()/pop(int):
Eg:
data = [786,'abc','a',123.5,786]
print "Last element is", data.pop()
print "2nd position element:", data.pop(1)print data
Output:
>>>
Last element is 786
2nd position element:abc
[786, 'a', 123.5]
>>>
4) insert(index,object):
Eg:
data=['abc',123,10.5,'a']
data.insert(2,'hello') print
data
Output:
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
>>>
['abc', 123, 'hello', 10.5, 'a']
>>>
5) extend(sequence):
Eg:
data1=['abc',123,10.5,'a']
data2=['ram',541]
data1.extend(data2) print
data1
print data2
Output:
>>>
['abc', 123, 10.5, 'a', 'ram', 541]
['ram', 541]
>>>
6) remove(object):
Eg:
data1=['abc',123,10.5,'a','xyz']
data2=['ram',541]
print data1
data1.remove('xyz')
print data1
print data2
data2.remove('ram')
print data2
Output:
>>>
['abc', 123, 10.5, 'a', 'xyz']
['abc', 123, 10.5, 'a']
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
['ram', 541]
[541]
>>>
7) reverse():
Eg:
list1=[10,20,30,40,50]
list1.reverse()
print list1
Output:
>>>
[50, 40, 30, 20, 10]
>>>
8) sort():
Eg:
list1=[10,50,13,'rahul','aakash']
list1.sort()
print list1
Output:
>>>
[10, 13, 50, 'aakash', 'rahul']
>>>
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
Experiment-2.3
Program to demonstrate creation and accessing of dictionary and apply different
kinds of operations on them.
Output:
>>>
{100: 'Ravi', 101: 'Vijay', 102: 'Rahul'}
>>>
plant={} plant[1]='Ravi'
plant[2]='Manoj'
plant['name']='Hari'
plant[4]='Om'
print plant[2] print
plant['name'] print
plant[1] print plant
Output:
>>>
Manoj
Hari
Ravi
{1: 'Ravi', 2: 'Manoj', 4: 'Om', 'name': 'Hari'}
>>>
Output:
>>>
Id of 1st employer is 100
Id of 2nd employer is 101
Name of 1st employer is Suresh
Profession of 2nd employer is Trainer
>>>
Output:
>>>
{'Salary': 15000, 'Profession': 'Manager','Id': 100, 'Name': 'Suresh'}
{'Salary': 20000, 'Profession': 'Trainer', 'Id': 101, 'Name': 'Ramesh'}
>>>
1) len(dictionary):
Output:
>>>
{100: 'Ram', 101: 'Suraj', 102: 'Alok'}
3
>>>
2) cmp(dictionary1,dictionary2):
Explanation:
Eg:
Output:
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
>>>
-1
0
1
>>>
3) str(dictionary):
Eg:
Output:
>>>
{100: 'Ram', 101: 'Suraj', 102: 'Alok'}
>>>
Methods:
1) keys():
Eg:
Output:
>>>
[100, 101, 102]
>>>
values():
Eg:
data1.values()
Output:
>>>
['Ram', 'Suraj', 'Alok']
>>>
2) items():
Eg:
Output:
>>>
[(100, 'Ram'), (101, 'Suraj'), (102, 'Alok')]
>>>
3) update(dictionary2):
Eg:
Output:
>>>
{100: 'Ram', 101: 'Suraj', 102: 'Alok', 103: 'Sanjay'}
{103: 'Sanjay'}
>>>
4) clear():
Eg:
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
Output:
>>>
{100: 'Ram', 101: 'Suraj', 102: 'Alok'}
{}
>>>
5) fromkeys(sequence)/ fromkeys(seq,value):
Eg:
Output:
>>>
{'Email': None, 'Id': None, 'Number': None}
{'Email': 100, 'Id': 100, 'Number': 100}
>>>
6) copy():
Eg:
Output:
>>>
{'Age': 23, 'Id': 100, 'Name': 'Aakash'}
>>>
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
7) has_key(key):
Eg:
Output:
>>>
True
False
>>>
8) get(key):
Eg:
Output:
>>>
23
None
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
Experiment-2.4
Program to demonstrate creation and accessing of tuples and apply different kinds
of operations on them.
>>> data=(10,20,'ram',56.8)
>>> data2="a",10,20.9
>>> data
(10, 20, 'ram', 56.8)
>>> data2 ('a',
10, 20.9)
>>>
tuple1=()
For a single valued tuple, there must be a comma at the end of the value.eg:
Tuple1=(10,)
tupl1='a','mahesh',10.56
tupl2=tupl1,(10,20,30) print
tupl1
print tupl2
Output:
('a', 'mahesh', 10.56)
(('a', 'mahesh', 10.56), (10, 20, 30))
>>>
Output:
>>>
1
(1, 2)
('x', 'y')
(1, 2, 3, 4)
('x', 'y')
>>>
a) Adding Tuple:
eg:
data1=(1,2,3,4)
data2=('x','y','z')
data3=data1+data2
print data1
print data2
print data3
Output:
>>>
(1, 2, 3, 4)
('x', 'y', 'z')
(1, 2, 3, 4, 'x', 'y', 'z')
>>>
b) Replicating Tuple:
Replicating means repeating. It can be performed by using '*' operator by aspecific number
of time.
Eg:
tuple1=(10,20,30);
tuple2=(40,50,60);
print tuple1*2
print tuple2*3
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
Output:
>>>
(10, 20, 30, 10, 20, 30)
(40, 50, 60, 40, 50, 60, 40, 50, 60)
>>>
c) Tuple slicing:
A subpart of a tuple can be retrieved on the basis of index. This subpart isknown as tuple
slice.
Eg:
data1=(1,2,4,5,7)
print data1[0:2]
print data1[4]
print data1[:-1]
print data1[-5:]
print data1
Output:
>>>
(1, 2)
7
(1, 2, 4, 5)
(1, 2, 4, 5, 7)
(1, 2, 4, 5, 7)
>>>
Note: If the index provided in the Tuple slice is outside the list, then it raises an
IndexError exception.
Other Operations:
Elements of the Tuple cannot be updated. This is due to the fact that Tuplesare immutable.
Whereas the Tuple can be used to form a new Tuple.
Eg:
data=(10,20,30)
data[0]=100
print data
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
Output:
>>>
Traceback (most recent call last):
File "C:/Python27/t.py", line 2, in
data[0]=100
TypeError: 'tuple' object does not support item assignment
>>>
data1=(10,20,30)
data2=(40,50,60)
data3=data1+data2
print data3
Output:
>>>
(10, 20, 30, 40, 50, 60)
>>>
Deleting individual element from a tuple is not supported. However thewhole of the tuple
can be deleted using the del statement.
Eg:
data=(10,20,'rahul',40.6,'z') print
data
del data #will delete the tuple data
print data #will show an error since tuple data is already deleted
Output:
>>>
(10, 20, 'rahul', 40.6, 'z')
Traceback (most recent call last): File
"C:/Python27/t.py", line 4, in
print data
NameError: name 'data' is not defined
>>>
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
1) min(tuple):
Eg:
data=(10,20,'rahul',40.6,'z')
print min(data)
Output:
>>>
10
>>>
2) max(tuple):
Eg:
data=(10,20,'rahul',40.6,'z')
print max(data)
Output:
>>>
z
>>>
3) len(tuple):
Eg:
data=(10,20,'rahul',40.6,'z')
print len(data)
Output:
>>>
5
>>>
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
4) cmp(tuple1,tuple2):
Explanation:If elements are of the same type, perform the comparison andreturn the result.
If elements are different types, check whether they are numbers.
If we reached the end of one of the lists, the longer list is "larger." If bothlist are same it
returns 0.
Eg:
data1=(10,20,'rahul',40.6,'z')
data2=(20,30,'sachin',50.2)
print cmp(data1,data2)
print cmp(data2,data1)
data3=(20,30,'sachin',50.2)
print cmp(data2,data3)
Output:
>>>
-1
1
0
>>>
5) tuple(sequence):
Eg:
dat=[10,20,30,40]
data=tuple(dat)
print data
Output:
>>>
(10, 20, 30, 40)
>>>
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
Unit III
Experiment-3.1
0
found = False
print(Sequential_Search([11,23,58,31,56,77,43,12,65,19],31))
print(binary_search([1,2,3,5,8], 6))
print(binary_search([1,2,3,5,8], 5))
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
def bubbleSort(nlist):
for passnum in range(len(nlist)-1,0,-1):for i in
range(passnum):
if nlist[i]>nlist[i+1]:
temp = nlist[i] nlist[i]
= nlist[i+1] nlist[i+1]
= temp
nlist = [14,46,43,27,57,41,45,21,70]
bubbleSort(nlist)print(nlist)
def selectionSort(nlist):
for fillslot in range(len(nlist)-1,0,-1):
maxpos=0
for location in range(1,fillslot+1):
if nlist[location]>nlist[maxpos]:
maxpos = location
nlist = [14,46,43,27,57,41,45,21,70]
selectionSort(nlist)print(nlist)
def insertionSort(nlist):
for index in range(1,len(nlist)):
currentvalue = nlist[index]
position = index
while position>0 and
nlist[position-1]>currentvalue:
nlist[position]=nlist[position-
1]
position = position-1
nlist[position]=currentvalue
nlist = [14,46,43,27,57,41,45,21,70]
insertionSort(nlist)print(nlist)
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
Def quickSort(data_list):
quickSortHlp(data_list,0,len(data_list)-1)
splitpoint = partition(data_list,first,last)
quickSortHlp(data_list,first,splitpoint-1)
quickSortHlp(data_list,splitpoint+1,last)
def partition(data_list,first,last):
pivotvalue = data_list[first]
leftmark = first+1
rightmark = last
done = False
while not done:
def mergeSort(nlist):
print("Splitting ",nlist) if
len(nlist)>1:
mid = len(nlist)//2
lefthalf = nlist[:mid]
righthalf = nlist[mid:]
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
mergeSort(lefthalf)
mergeSort(righthalf)
i=j=k=0
while i < len(lefthalf) and j < len(righthalf): if
lefthalf[i] < righthalf[j]:
nlist[k]=lefthalf[i] i=i+1
else:
nlist[k]=righthalf[j] j=j+1
k=k+1
nlist = [14,46,43,27,57,41,45,21,70]
mergeSort(nlist)
print(nlist)
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
Experiment-3.2
Program to implement concepts of Object Oriented Programming such as
classes, inheritance and polymorphism.
1. Program to implement an object class.
class Student:
def init (self, rollno, name):
self.rollno = rollno
self.name = name
def displayStudent(self):
print "rollno : ", self.rollno, ", name: ", self.name emp1 =
Student(121, "Ajeet")
emp2 = Student(122, "Sonoo")
emp1.displayStudent()
emp2.displayStudent()
Output:
Output:
Eating...
Barking...
Output:
Eating...
Barking...
Weeping
class First(object):
def init (self):
super(First, self). init ()
print("first")
class Second(object):
def init (self): super(Second,
self). init ()print("second")
Third();
Output:
first
second
third
class Circle:
def getRadius(self):
return self. radius
def area(self):
return math.pi * self. radius ** 2
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
c1 = Circle(4) print(c1.getRadius())
c2 = Circle(5) print(c2.getRadius())
Expected Output:
4
5
9
class A():
class B(A):
c = B()
c.m1()
Expected Output:
m1 from B
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
Experiment-3.3
Program to demonstrate read and write data to the file in various modes.
Output:
>>>
Welcome to the world of Python
Welcome to the world
>>>
3. Program to open the file in the read mode and use of for loop to print
each line present in the file.
# a file named "geek", will be opened with the reading mode. file =
open('geek.txt', 'r')
# This will print every line one by one in the filefor each in
file:
print (each)
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
open("myfile.txt","r+")
file1.seek(0)
file1.seek(0)
file1.seek(0)
# readlines function
print "Output of Readlines function is " print
file1.readlines()
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
print
file1.close()
Output:
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]file1.close()
# Append-adds at last
file1 = open("myfile.txt","a")#append mode
file1.write("Today \n")
file1.close()
file1 = open("myfile.txt","r")
print "Output of Readlines after appending"
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)
print
file1.readlines()
print
file1.close()
# Write-Overwrites
file1 = open("myfile.txt","w")#write mode
file1.write("Tomorrow \n")
file1.close()
file1 = open("myfile.txt","r")
print "Output of Readlines after writing"
print file1.readlines()
print
file1.clo
se()
Output: