You are on page 1of 60

CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

Department of Computer Science &


Engineering

SUBJECT: Programming in Python Lab


(21CSP-259)

B.E. II Year – IV Semester


(Branch: CSE/IT)

LAB FILE
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

Table of Contents

Sr. No. Name of the Experiments

UNIT-I

Writing python programs in various modes and printing and assigning


I. values assigned to the variables.

II. Program to demonstrate the use of if, if-else, while, for, break and continue

Program to demonstrate the use of functions and passing different types of


III.
arguments to functions.
UNIT-II

IV. Program to demonstrate the various kind of operations that can be applied
to the string.

Program to demonstrate creation and accessing of lists and apply different


V.
kinds of operations on them.
Program to demonstrate creation and accessing of dictionary and apply
VI. different kinds of operations on them.

Program to demonstrate creation and accessing of tuples and apply


VII.
different kinds of operations on them.
UNIT-III

VIII. Program to implement various kinds of searching and sorting algorithms

Program to implement concepts of Object Oriented Programming such as


IX. classes, inheritance and polymorphism.

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

1. How to execute simple commands in Python Command Prompt


Unless you use some sort of integrated development environment, you will end up typingWindows
commands into what is variously referred to as a “DOS window” or “Command prompt window”.
Usually you can create such a window from your Start menu; under Windows7 the menu selection
is Start ‣ Programs ‣ Accessories ‣ Command Prompt. You should be ableto recognize when you
have started such a window because you will see a Windows “command prompt”, which usually
looks like this:

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

You should then see something like:

Python 2.7.3 (default, Apr 10 2012, 22.71:26) [MSC v.1500 32 bit (Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.

>>>

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:

>>> print "Hello"

Hello

>>> "Hello" * 3

'HelloHelloHello'
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

How do I make Python scripts executable?

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.

2. How to execute simple commands in Python IDLE interactive shell

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.

Using the Python Shell Window

The top of IDLE's Python Shell window will look something like this:
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

Experimenting with Python Commands

Python, by design, is an interpreted language (as opposed to a compiled language). Programs


written with interpreted languages do tend to execute a little more slowly than do compiled
programs, but for most tasks the difference is insignificant. The big advantage of an interpreted
language is experimentation: A programmer can try out algorithms and play around with different
commands interactively (that is, without having to write a complete program to do either). For
people just starting to learn programming in general, or Python in particular, interactive
experimentation is very useful. This interactivity is the main purpose of the IDLE's Python Shell
window. You probably noticed already that the last line of text in the window is theset of three
'greater-than' symbols. This is the prompt symbol; when you see it on a line by itself, Python is
waiting for you to do something -- such as type in a command.

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:

print("Bear Down, Wildcats!")

3. Writing program in script mode


Script Mode

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 statement is the Python 2.6 legacy construct.

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

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.

print "PI = ", 355.0/113.0

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

print 65, "F"


print ( 65 - 32 ) * 5 / 9, "C"

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 .

from future import print_functionprint( "PI = ",


355.0/113.0 )

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

from future import print_functionprint( 65, "F" )


print( ( 65 - 32 ) * 5 / 9, "C" )

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)

We’ll look at this in detail below.

 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.

4. Program Using Variables and Assignment

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)

Listing 2.1 (variable.py) contains two statements

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)

prints 10, the value of the variable x, but the statement

print('x')

prints x, the message containing the single letter 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

Variables can be reassigned different values as needed, as Listing 2.2


(multipleassignment.py) shows.

2: multipleassignment.py

x = 10

print('x = ' + str(x))

x = 20

print('x = ' + str(x))

x = 30

print('x = ' + str(x))


CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

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:

print('x = ' + str(x))

5. Program to Assigning values to Variable

Output:

>>>

10

ravi

20000.67

>>>

6. Program to demonstrate single value to multiple variables


x=y=z=50
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

print x

print y

print z

Output:

>>>

50

50

50

>>>

7. Program to assign multiple values to multiple variables:

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

1. Program to demonstrate use of if statement in python

a=10
if a==10:
print "Hello User"

Output:
Hello User

2. Program to demonstrate use of if-else statement in python

year=2000
if year%4==0:
print "Year is Leap"else:
print "Year is not Leap"

Output:
Year is Leap

3. Program to demonstrate use of nested if-else statement in python

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.

4. Program to demonstrate the display table of number using for-loop


statement.
num=2
for a in range (1,6):
print num * a
Output:
2
4
6
8
10
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

5. Program to find sum of Natural numbers from 1 to 10.

sum=0
for n in range(1,11):
sum+=n
print sum

Output:
55

6. Program to demonstrate the use of nested for loop.

for i in range(1,6):
for j in range (1,i+1):
print i,
print

Output:
>>>
1
22
333
4444
55555
>>>

7. Program to add digits of a number using while loop.

n=153
sum=0
while n>0:r=n%10
sum+=rn=n/10
print sum

Output:

>>>
9
>>>
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

8. Program to demonstrate the use of the break statement.

for i in [1,2,3,4,5]: if
i==4:
print "Element found"
break
print i,

Output:

>>>
1 2 3 Element found
>>>

9. Program to demonstrate the use of the continue statement.

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.

1. Program to demonstrate the use of 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
>>>

2. Program to demonstrate the use of return statement in functions.

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
>>>

3. Program to demonstrate the passing of arguments in functions.

def addition(x,y):
print x+y
x=15
addition(x,10)
addition(x,x)
y=20
addition(x,y)

Output:

>>>
25
30
35
>>>

4. Program to demonstrate the use of Default Arguments in functions.

#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
>>>

5. Program to demonstrate the use of Keyword Arguments in functions.

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
>>>

6. Program to demonstrate the scope of variable:


Local Variable:
def msg():
a=10
print "Value of a is",a
return

msg()
print a #it will show error since variable is local
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

Value of a is 10

Traceback (most recent call last):


File "C:/Python27/lam.py", line 7, in <module> print
a #it will show error since variable is local
NameError: name 'a' is not defined
>>>
</module>

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.

1. Program to retrieve String in reverse as well as normal form


name="Rajat"
length=len(name)
i=0
for n in range(-1,(-length-1),-1):
print name[i],"\t",name[n]
i+=1

Output:

>>>
R t
a a
j j
a a
t R
>>>

2. Program to demonstrate string concatenation

>>> "ratan" + "jaiswal"

Output:

'ratanjaiswal'
>>>

NOTE: Both the operands passed for concatenation must be of same


type, else it will show an error.

3. Program to demonstrate the use of replication operator


>>> 5*"Vimal"

Output:
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

'VimalVimalVimalVimalVimal'

4. Program to demonstrate the use of membership operators.

>>> 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

5. Program to demonstrate relational operators.

>>> "RAJAT"=="RAJAT"
True
>>> "afsha">='Afsha'
True
>>> "Z"<>"z"
True

6. Program to demonstrate the use of slice notation.

>>> str="Nikhil"
>>> str[0:6]
'Nikhil'
>>> str[0:3]
'Nik'
>>> str[2:5]
'khi'
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

>>> str[:6]
'Nikhil'
>>> str[3:]
'hil'

Note: startIndex in String slice is inclusive whereas endIndex is


exclusive.

>>> str="Mahesh"
>>> str[:6]+str[6:]
'Mahesh'

7. Program to demonstrate various string functions

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)

str="Welcome to world of SSSIT";


substr1="come";
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

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()

string1="HelloPython"; # Even space is not allowedprint


string1.isalpha();
string2="This is Python2.7.4"print
string2.isalpha();
Output:
>>>
True
False
>>>
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

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)

string1="Hello Python"; print


string1.swapcase();
string2="welcome to SSSIT"print
string2.swapcase();

Output:

>>>
hELLO pYTHON
WELCOME TO sssit
>>>

17) lstrip()

string1=" Hello Python";


print string1.lstrip();
string2="@@@@@@@@welcome to SSSIT" print
string2.lstrip('@');

Output:

>>>
Hello Python
welcome to world to SSSIT
>>>

18) rstrip()

string1=" Hello Python ";


print string1.rstrip();
string2="@welcome to SSSIT!!!" print
string2.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.

1. Program to demonstrate creation and accessing of lists

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']
>>>

2. Program to demonstrate various list operations

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:

Replicating means repeating . It can be performed by using '*' operator by a specific


number of time.

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]
>>>

d) Updating elements in a List:

data1=[5,10,15,20,25]
print "Values of list are: "print
data1
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

data1[2]="Multiple of 5" print


"Values of list are: " print
data1

Output:

>>>
Values of list are:
[5, 10, 15, 20, 25]
Values of list are:
[5, 10, 'Multiple of 5', 20, 25]
>>>

e) Appending elements to a List:

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]
>>>

f) Deleting Elements from a List:


list1=[10,'rahul',50.8,'a',20,30] print
list1
del list1[0]
print list1 del
list1[0:3] print
list1
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

Output:

>>>
[10, 'rahul', 50.8, 'a', 20, 30]
['rahul', 50.8, 'a', 20, 30]
[20, 30]
>>>

3. Program to demonstrate use of Functions and Methods of Lists:

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 numbers, perform comparison.


If either element is a number, then the other element is returned.Otherwise,
types are sorted alphabetically .

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']
>>>

4. Program to demonstrate use of built in Functions in lists.

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.

1. Program to enclose different items in key value pair in the form of


dictionary.

data={100:'Ravi' ,101:'Vijay' ,102:'Rahul'} print


data

Output:

>>>
{100: 'Ravi', 101: 'Vijay', 102: 'Rahul'}
>>>

2. Program to implement dictionry as an associative array

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'}
>>>

3. Program to access the value of dictionary by their keys

data1={'Id':100, 'Name':'Suresh', 'Profession':'Developer'}


data2={'Id':101, 'Name':'Ramesh', 'Profession':'Trainer'} print "Id of
1st employer is",data1['Id']
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

print "Id of 2nd employer is",data2['Id']


print "Name of 1st employer:",data1['Name']
print "Profession of 2nd employer:",data2['Profession']

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
>>>

4. Program to update the key value pair within the dictionary

data1={'Id':100, 'Name':'Suresh', 'Profession':'Developer'}


data2={'Id':101, 'Name':'Ramesh', 'Profession':'Trainer'}
data1['Profession']='Manager'
data2['Salary']=20000
data1['Salary']=15000
print data1
print data2

Output:

>>>
{'Salary': 15000, 'Profession': 'Manager','Id': 100, 'Name': 'Suresh'}
{'Salary': 20000, 'Profession': 'Trainer', 'Id': 101, 'Name': 'Ramesh'}
>>>

5. Program to delete the pair within the dictionary


data={100:'Ram', 101:'Suraj', 102:'Alok'} del
data[102]
print data
del data
print data #will show an error since dictionary is deleted.
Output:
>>>
{100: 'Ram', 101: 'Suraj'}
Traceback (most recent call last):
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

File "C:/Python27/dict.py", line 5, in


print data
NameError: name 'data' is not defined
>>>

6. Program to demonstrate the built in functions within the dictionary

1) len(dictionary):

data={100:'Ram', 101:'Suraj', 102:'Alok'} print


data
print len(data)

Output:

>>>
{100: 'Ram', 101: 'Suraj', 102: 'Alok'}
3
>>>

2) cmp(dictionary1,dictionary2):

Explanation:

The comparison is done on the basis of key and value.

If, dictionary1 == dictionary2, returns 0.


dictionary1 < dictionary2, returns -1.
dictionary1 > dictionary2, returns 1.

Eg:

data1={100:'Ram', 101:'Suraj', 102:'Alok'}


data2={103:'abc', 104:'xyz', 105:'mno'}
data3={'Id':10, 'First':'Aman','Second':'Sharma'}
data4={100:'Ram', 101:'Suraj', 102:'Alok'}
print cmp(data1,data2)
print cmp(data1,data4)
print cmp(data3,data2)

Output:
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

>>>
-1
0
1
>>>

3) str(dictionary):

Eg:

data1={100:'Ram', 101:'Suraj', 102:'Alok'} print


str(data1)

Output:

>>>
{100: 'Ram', 101: 'Suraj', 102: 'Alok'}
>>>

Methods:

1) keys():

Eg:

data1={100:'Ram', 101:'Suraj', 102:'Alok'} print


data1.keys()

Output:

>>>
[100, 101, 102]
>>>
values():

Eg:

data1={100:'Ram', 101:'Suraj', 102:'Alok'} print


CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

data1.values()

Output:

>>>
['Ram', 'Suraj', 'Alok']
>>>

2) items():

Eg:

data1={100:'Ram', 101:'Suraj', 102:'Alok'} print


data1.items()

Output:

>>>
[(100, 'Ram'), (101, 'Suraj'), (102, 'Alok')]
>>>

3) update(dictionary2):

Eg:

data1={100:'Ram', 101:'Suraj', 102:'Alok'}data2={103:'Sanjay'}


data1.update(data2) print
data1
print data2

Output:

>>>
{100: 'Ram', 101: 'Suraj', 102: 'Alok', 103: 'Sanjay'}
{103: 'Sanjay'}
>>>

4) clear():
Eg:
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

data1={100:'Ram', 101:'Suraj', 102:'Alok'}print data1


data1.clear()
print data1

Output:
>>>
{100: 'Ram', 101: 'Suraj', 102: 'Alok'}
{}
>>>

5) fromkeys(sequence)/ fromkeys(seq,value):
Eg:

sequence=('Id' , 'Number' , 'Email')


data={}
data1={}
data=data.fromkeys(sequence) print
data
data1=data1.fromkeys(sequence,100) print
data1

Output:

>>>
{'Email': None, 'Id': None, 'Number': None}
{'Email': 100, 'Id': 100, 'Number': 100}
>>>

6) copy():
Eg:

data={'Id':100 , 'Name':'Aakash' , 'Age':23}


data1=data.copy()
print data1

Output:

>>>
{'Age': 23, 'Id': 100, 'Name': 'Aakash'}
>>>
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

7) has_key(key):

Eg:

data={'Id':100 , 'Name':'Aakash' , 'Age':23} print


data.has_key('Age')
print data.has_key('Email')

Output:

>>>
True
False
>>>

8) get(key):
Eg:

data={'Id':100 , 'Name':'Aakash' , 'Age':23} print


data.get('Age')
print data.get('Email')

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.

1. Program to implement the tuple.

>>> data=(10,20,'ram',56.8)
>>> data2="a",10,20.9
>>> data
(10, 20, 'ram', 56.8)
>>> data2 ('a',
10, 20.9)
>>>

NOTE: If Parenthesis is not given with a sequence, it is by default treated as Tuple.

There can be an empty Tuple also which contains no object.eg:

tuple1=()

For a single valued tuple, there must be a comma at the end of the value.eg:

Tuple1=(10,)

Tuples can also be nested.eg:

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))
>>>

2. Program to access the tuples.


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]
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

Output:

>>>
1
(1, 2)
('x', 'y')
(1, 2, 3, 4)
('x', 'y')
>>>

3. Program to perform various tuple operations

a) Adding Tuple:

Tuple can be added by using the concatenation operator(+) to join twotuples.

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')
>>>

Note: The new sequence formed is a new Tuple.

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:

a) Updating elements in a List:

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
>>>

Creating a new Tuple from existing:


Eg:

data1=(10,20,30)
data2=(40,50,60)
data3=data1+data2
print data3

Output:

>>>
(10, 20, 30, 40, 50, 60)
>>>

b) Deleting elements from Tuple:

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)

4. Program to demonstrate the functions of the tuple.

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 numbers, perform comparison.


If either element is a number, then the other element is returned.Otherwise,
types are sorted alphabetically .

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

Program to implement various kinds of searching and sorting algorithms

1. Program to implement sequential search

def Sequential_Search(dlist, item):pos =

0
found = False

while pos < len(dlist) and not found: if


dlist[pos] == item:
found = True
else:
pos = pos + 1

return found, pos

print(Sequential_Search([11,23,58,31,56,77,43,12,65,19],31))

2. Program to implement binary search

def binary_search(item_list,item): first =


0
last = len(item_list)-1
found = False
while( first<=last and not found):mid =
(first + last)//2
if item_list[mid] == item :
found = True
else:
if item < item_list[mid]: last
= mid - 1
else:
first = mid + 1
return found

print(binary_search([1,2,3,5,8], 6))
print(binary_search([1,2,3,5,8], 5))
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

3. Program to implement bubble sort.

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)

4. Program to implement selection sort.

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

temp = nlist[fillslot] nlist[fillslot]


= nlist[maxpos] nlist[maxpos] =
temp

nlist = [14,46,43,27,57,41,45,21,70]
selectionSort(nlist)print(nlist)

5. Program to implement insertion sort.

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)

6. Program to implement quick sort.

Def quickSort(data_list):
quickSortHlp(data_list,0,len(data_list)-1)

def quickSortHlp(data_list,first,last): if first


< last:

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:

while leftmark <= rightmark and data_list[leftmark] <= pivotvalue: leftmark =


leftmark + 1

while data_list[rightmark] >= pivotvalue and rightmark >= leftmark: rightmark =


rightmark -1

if rightmark < leftmark:


done = Trueelse:
temp = data_list[leftmark] data_list[leftmark] =
data_list[rightmark]data_list[rightmark] = temp
temp = data_list[first]
data_list[first] = data_list[rightmark]
data_list[rightmark] = temp
return rightmark
data_list = [54,26,93,17,77,31,44,55,20]
quickSort(data_list)print(data_list)

7. Program to implement merge sort.

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

while i < len(lefthalf):


nlist[k]=lefthalf[i] i=i+1
k=k+1

while j < len(righthalf):


nlist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",nlist)

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:

rollno : 121 , name: Ajeet


rollno : 122 , name: Sonoo

2. Program to demonstrate the concept of constructors


CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

3. Program to demonstrate inheritance in Python

class Animal: def


eat(self):
print 'Eating...'
class Dog(Animal):
def bark(self): print
'Barking...'
d=Dog()
d.eat()
d.bark()

Output:

Eating...
Barking...

4. Program to demonstrate multilevel inheritance in Python

class Animal: def


eat(self):
print 'Eating...'
class Dog(Animal):
def bark(self): print
'Barking...'
class BabyDog(Dog):
def weep(self): print 'Weeping...'
d=BabyDog()
d.eat()
d.bark()
d.weep()
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

Output:

Eating...
Barking...
Weeping

5. Program to demonstrate multiple inheritance in Python / use of super


keyword

class First(object):
def init (self):
super(First, self). init ()
print("first")

class Second(object):
def init (self): super(Second,
self). init ()print("second")

class Third(Second, First):


def init (self):
super(Third, self). init ()
print("third")

Third();

Output:

first
second
third

6. Program to demonstrate operator overloading


import math

class Circle:

def init (self, radius): self.


radius = radius

def setRadius(self, radius):self.


radius = radius

def getRadius(self):
return self. radius

def area(self):
return math.pi * self. radius ** 2
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

def add (self, another_circle):


return Circle( self. radius + another_circle. radius )

c1 = Circle(4) print(c1.getRadius())

c2 = Circle(5) print(c2.getRadius())

c3 = c1 + c2 # This became possible because we have overloaded + operatorby adding a


method named add
print(c3.getRadius())

Expected Output:
4
5
9

7. Program to demonstrate method overriding

class A():

def init (self):


self. x = 1

def m1(self): print("m1


from A")

class B(A):

def init (self): self.


y=1

def m1(self): print("m1


from B")

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.

1. Program to read and write data from a file.


obj=open("abcd.txt","w") obj.write("Welcome to the
world of Python")obj.close()
obj1=open("abcd.txt","r")
s=obj1.read()
print s
obj1.close()
obj2=open("abcd.txt","r")
s1=obj2.read(20)
print s1
obj2.close()

Output:

>>>
Welcome to the world of Python
Welcome to the world
>>>

2. Program to illustrate append() mode

file = open('geek.txt','a') file.write("This will


add this line")file.close()

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)

4. 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 modesfile1 =

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

print "Output of Read function is "print


file1.read()
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.readline()
print

file1.seek(0)

# To show difference between read and readline print


"Output of Read(9) function is "
print file1.read(9)
print

file1.seek(0)

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


file1.readline(9)

file1.seek(0)
# readlines function
print "Output of Readlines function is " print
file1.readlines()
CHANDIGARH UNIVERSITY, GHARUAN (MOHALI)

print
file1.close()

Output:

Output of Read function is


Hello
This is Delhi
This is Paris
This is London

Output of Readline function is


Hello

Output of Read(9) function is


Hello
Th

Output of Readline(9) function is


Hello

Output of Readlines function is


['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']

5. Python program to illustrate Append vs write mode

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:

Output of Readlines after appending


['This is Delhi \n', 'This is Paris \n', 'This is London \n', 'Today \n']

Output of Readlines after


writing['Tomorrow \n']

You might also like