SHRI SAKTHIKAILASSH WOMENS
COLLEGE, SALEM-3
DEPARTMENT OF PG COMPUTER
SCIENCE
LAB MANNUAL
COURSE NAME : MSC COMPUTER SCIENCE
SUBJECT NAME : PYTHON PROGRAMMING LAB
SUJECT CODE :23PCSCP02
EX.NO:01
LIST , TUPLE, DICTIONARY
DATE:
AIM:
To write a program using elementary data items, list, dictionaries and tuples
in python.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Write the coding for list and give input.
STEP 3: To perform the operation like adding, deleting and inserting
an item in the list.
STEP 4: Write the coding for dictionary and follow the construction
same as in step 3.
STEP 5: Then write the coding for tuple and follow the construction
same as in step 3.
STEP 6: Save the program in the extension .py and run the program.
STEP 7: Stop the program.
CODING:
>>> #LIST
>>> thislist=["green","red","yellow","purple"]
>>> thislist
>>> thislist[1]="indigo"
>>> thislist
>>> thislist.append("voilet")
>>> thislist
>>> print(len(thislist))
>>> del thislist[2]
>>> print(thislist)
>>> # TUPLE
>>> thistuple=("one","two","three","four")
>>> thistuple
>>> print(thistuple[2])
>>> print(len(thistuple))
>>> #SET
>>> thisset=set{"apple","banana","cherry"}
>>> thisset
>>> thisset.add("papaya")
>>> thisset
>>> thisset.remove("banana")
>>> thisset
>>> print(len(thisset))
>>> #DICTIONARY
>>> thisdict={"apple":"green","banana":"yellow","cherry":"red"}
>>> thisdict
>>> thisdict["apple"]="red"
>>> thisdict
>>> print(thisdict)
>>> print(len(thisdict))
OUTPUT:
LIST
['green', 'red', 'yellow', 'purple']
['green', 'indigo', 'yellow', 'purple']
['green', 'indigo', 'yellow', 'purple', 'voilet']
5
['green', 'indigo', 'purple', 'voilet']
TUPLE
('one', 'two', 'three', 'four')
Three
SET
{'cherry', 'apple', 'banana'}
{'cherry', 'apple', 'banana', 'papaya'}
{'cherry', 'apple', 'papaya'}
DICTIONARY
{'cherry': 'red', 'apple': 'green', 'banana': 'yellow'}
{'cherry': 'red', 'apple': 'red', 'banana': 'yellow'}
{'cherry': 'red', 'apple': 'red', 'banana': 'yellow'}
3
RESULT:
Thus the above program has been executed successfully.
EX.NO:02
CONDITIONAL BRANCHES
DATE:
AIM:
To create a program to calculate total, average and grade of student using
conditional statements.
ALGORITHM:
STEP 1: Start the program.
STEP 2: promote a user to enter name and subject marks like Tamil,
English, Maths, science and social.
STEP 3:Calculate total and average marks.
STEP 4: using conditional statements calculate grade.
STEP 5: Save the file using .py and run it
STEP 6: Stop a program.
CODING:
>>>name=input(“enter student name:”)
>>>tamil=float(input(“enter tamil mark:”)
>>>english=float(input(“enter english mark:”)
>>>maths=float(input(“enter maths mark:”)
>>>science=float(input(“enter science mark:”)
>>>social=float(input(“enter social mark:”)
>>>Total=tamil+english+maths+science+social
>>>avg=total/5
>>>print(“name of the student:”,name)
>>>print(“total marks:”,avg)
>>>If avg>=90:
print(“O grade”)
elif avg>=80:
print(“D+ grade”)
elif avg>=75:
print(“D grade”)
elif avg>=70:
print(“A+ grade”)
elif avg>=60:
print(A grade”)
elif avg>=50:
print(“B+ grade”)
else:
print(“O grade”)
OUTPUT:
Enter student name: meki
Enter tamil mark:89
Enter English mark:86
Enter maths mark:96
Enter science mark:96
Enter social mark:85
Name of the student:meki
Total marks:452.0
Average:90.4
O grade
RESULT:
Thus the above program has been executed successfully.
EX.NO:03
LOOPS
DATE:
AIM:
To create a program to calculate total, average and grade of student using
conditional statements.
ALGORITHM:
STEP 1: Start the program.
STEP 2: promote a user to enter name and subject marks like Tamil,
English, Maths, science and social.
STEP 3:Calculate total and average marks.
STEP 4: using conditional statements calculate grade.
STEP 5: Save the file using .py and run it
STEP 6: Stop a program.
CODING:
(a)Factorial using for loop
>>> num=int(input("enter a number:"))
enter a number:6
>>> factorial=1
>>> if num<0:
print("factorial does not exist for nagative numbers")
elif num==0:
print("the factorial of 0 is 1")
else:
for i in range(1,num+1):
factorial=factorial*i
print("the factorial of",num,"is",factorial)
OUTPUT:
the factorial of 6 is 1
the factorial of 6 is 2
the factorial of 6 is 6
the factorial of 6 is 24
the factorial of 6 is 120
the factorial of 6 is 720
(b)Factorial using while loop
>>> num=int(input("enter a number:"))
>>> fac=1
>>> i=1
>>> while i<=num:
fac=fac*i
i=i+1
print("factorial of",num,"is",fac)
OUTPUT:
enter a number:4
factorial of 4 is 1
factorial of 4 is 2
factorial of 4 is 6
factorial of 4 is 24
RESULT:
Thus the above program has been executed successfully.
EX.NO:04
FUNCTION
DATE:
AIM :
To write a program for functions using Python IDLE Environment.
ALGORITHM :
STEP 1: To open a Python IDLE environment.
STEP 2: To create a function using def keyword with function name and
Parameters.
STEP 3: To perform an arithmetic operations using function such as
addition,subtraction,multiplication,division and modulo division.
STEP 4: To get the input value of a and b using “input” function.
STEP 5: Print the result.
STEP 6: Stop the program.
CODING:
#USER DEFINED FUNCTIONS
def add(x,y):
return x+y
def subtract(x,y):
return x-y
def multiply(x,y):
return x*y
def divide(x,y):
return x/y
print(“select operation”)
print(“1.Add”)
print(“2.Subtract”)
print(“3.Multiply”)
print(“4.Divide”)
choice=input(“enter choice (1/2/3/4):”)
num 1=int(input(“enter first number:”))
num 2=int(input(“enter second number:”))
if choice==’1’:
print(num 1,”+”,num 2,”=”,add(num 1,num 2))
elif choice ==’2’:
print(num 1,”-”,num 2,”=”,subtract(num 1,num 2))
elif choice ==’3’:
print(num 1,”*”,num 2,”=”,multiply(num 1,num 2))
elif choice ==’4’:
print(num 1,”/”,num 2,”=”,divide(num 1,num 2))
else :
print(“Invalid input”)
OUTPUT:
Select operation
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 1
Enter First number: 10
Enter Second number: 20
10+20= 30
RESULT:
Thus the above program has been executed successfully
EX.NO:05
EXCEPTION HANDLING
DATE:
AIM:
To write a program of exception handling using Python IDLE Environment.
ALGORITHM:
STEP 1: To open a Python IDLE environment.
STEP 2: To perform exception handling function using the keyword try
and finally.
STEP 3: Using try block to declare a variable num and to get the input
Using “input” Function.
STEP 4: By using if statement checks the given condition if it is true then
print the Statement.
STEP 5: If it is false print the else statement then print the finally statement
as default.
STEP 6: Stop the program.
CODING:
#EXCEPTION
try:
num = int(input("Enter the Input"))
re = 100/num
except(ValueError,ZeroDivisionError):
print("Something is wrong")
else:
print("Result",re)
#EXCEPTION HANDLING
try:
num = int(input("Enter the number"))
if(num<=0):
raise ValueError("That is not positive number")
except ValueError as error:
print(error)
OUTPUT:
Enter the Input 0
Something is wrong
Enter the number -1
Result -100.0
RESULT:
Thus the above program has been executed successfully.
EX.NO:06
INHERITANCE
DATE:
AIM:
To write a program of inheritance using Python IDLE Environment.
ALGORITHM:
STEP 1: To create a class vehicle.
STEP 2:To define a function with self accessing class variable.
. STEP 3: To create class new class car.
STEP 4: To initialize the function with self accessing variable.
STEP 5: Assign the variable and create the function name specific usage.
STEP 6: To create a Derived class motor cycle assign the variable.
STEP 7: To create the function specific usage.
STEP 8: To create a object name c and calling the function general usage
and specific usage.
STEP 9: To create the object named ‘m’ and calling the function general
usage and Specific usage.
STEP 10: Stop the program.
CODING :
#parent class
>>> class dep:
def dept(self):
print("department")
#derived class
>>> class csca(dep):
def course(Self):
print("computer science")
print("computer applicaion")
>>> class year(csca):
def classes(self):
print("Iyear,IIyear,IIIyear")
>>> d=year()
>>> d.dept()
>>> d.course()
>>> d.classes()
OUTPUT:
department
computer science
computer application
Iyear,IIyear,IIIyear
RESULT:
Thus the above program has been executed successfully.
EX.NO:07
POLYMORPHISM
DATE:
AIM:
To write a program using polymorphism in python.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Write the coding for polymorphism.
STEP 3: Create a function using def keyword.
STEP 4: Create class and objects that is necessary for polymorphism.
STEP 5: Save the program with a extension .py.
STEP 6: Run the program.
STEP 7: Stop the program.
CODING:
class Polygon:
def area(self):
pass
class triangle(Polygon):
def area(self):
width = 20
height = 10
area = (width * height) / 2
print(“calculate area of triangle and rectangle”)
print(“The area of the triangle is:”,+area)
class rectangle(Polygon):
def area(self):
width = 20
height = 10
area = (width * height)
print("The area of the rectangle is:",+area)
tr = triangle()
tr.area()
re = rectangle()
re.area()
OUTPUT:
calculate area of triangle and rectangle
The area of the triangle is: 100.0
The area of the rectangle is: 200
RESULT:
Thus the above program has been executed successfully.
EX.NO:08
FILE OPERATIONS
DATE:
AIM:
To write a program to perform file operations using Python IDLE
Environment.
ALGORITHM:
STEP 1: To open a Python IDLE environment.
STEP 2: To perform file operations such as open (), close (), read and
write.
STEP 3: To open a file “text.txt” in the write mode then add the content and
close the file.
STEP 4: To open a file “text.txt” in the append mode and add the content
then close the File.
STEP 5: To open a file “text.txt” in the read mode and print the content then
close the file.
STEP 6: To execute the program using run F5.
CODING:
text_file=open(“sample.txt”,’w’)
text_file.write(“kailash women’s college”)
text_file.close()
text_file=open(“sample.txt”,’a’)
text_file.write(“nangavalli”)
text_file.write(“MSC computer science”)
text_file.close()
text_file=open(“sample.txt”,’r’)
print(“welcome to kwc”)
text_file.close()
OUTPUT:
23
20
Welcome to kwc
RESULT:
Thus the above program has been executed successfully.
EX.NO:09
MODULES
DATE:
AIM:
To write a program using modules in python.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Create a module named mymodule and function as greeting.
STEP 3: Import mymodule into the program using dot operator
STEP 4: Display the output.
STEP 5: Create another module named support and function as print_func.
STEP 6: Import support into the program using dot operator
STEP 7: Create module name directory and window, and follow the step 6.
STEP 8: Run the program and stop the program.
CODING:
#module1
#save the file name as pro.py
def greeting(name):
print("Have a nice day, " + name)
# save the file name as program.py
import pro
pro.greeting("my dear friends")
#module2
#save the file name as mymodule.py
person1 = {
"name": "Nivetha",
"age": 22,
"country": "Erode"
#save the file name as demodule.py
import mymodule
a = mymodule.person1
print(a)
OUTPUT:
RESULT:
Thus the above program has been executed successfully.
EX.NO:10
DYNAMIC WEB PAGE
DATE:
AIM:
To write a program for creating dynamic and interactive web pages using
Forms.
ALGORITHM:
STEP 1: Install the Flask framework
C:\python37>pip install virtualenv
STEP 2: After installation, goto your working directory (C:\python37)
STEP 3: Create a web.py file and stored in your working directory
STEP 4: Create a new sub directory name as “app” under your working
Directory.
STEP 5: Create an login.html files stored under the app directory
STEP 6: Open the command Prompt and goto your working directory
(C:\python37).
STEP 7: run the web.py file (C:\python37\scripts\app\>web.py)
(Server is run on http://127.0.0.1:5000)
STEP 8: Open the web browser and type the http://127.0.0.1:5000
STEP 9: Displayed on the login.html file output and entry this form and
click submit button.
CODING: (web1.py)
from flask import Flask, redirect, url_for, request
app = Flask(__name__)
@app.route('/success/<name>')
def success(name):
return 'welcome %s' % name
@app.route('/login',methods = ['POST', 'GET'])
def login():
if request.method == 'POST':
user = request.form['nm']
return redirect(url_for('success',name = user))
else:
user = request.args.get('nm')
return redirect(url_for('success',name = user))
if __name__ == '__main__':
app.run(debug = True)
CODING: login.html
<html>
<body><center>
<h1> WELCOME TO KWC ............<h1>
<img src="e:\img1.jpg">
<form action = "http://127.0.0.1:5000/login" method = "post">
<p>Enter Name:</p>
<p><input type = "text" name = "nm" /></p>
<p><input type = "submit" value = "submit" /></p>
</form></center>
</body>
</html>
Steps to run the program:
OUTPUT:
WELCOME TO KWC…
Enter your name
priya
Welcome to computer science priya
RESULT:
Thus the above program has been executed successfully.