You are on page 1of 29

VELAMMAL VIDHYASHRAM GUDUVANCHERY

PYTHON FILES
2022-2023
COMPUTER SCIENCE PRACTICAL (083)

Name : _________________________________

Class & Sec : _________________________________

Exam No. : _________________________________


CONTENTS
Name: Class:
Ex. Date Name of the Experiment Page Teacher’s
No Initial

P a g e 2 | 29
CONTENTS
Name: Class:
Ex. Date Name of the Experiment Page Teacher’s
No Initial

P a g e 3 | 29
1. ARITHMETIC OPERATIONS
Aim: -
To write a menu driven Python Program to perform Arithmetic
operations (+, -, *, /).
Algorithm:-
Step 1:- Get Inputs.
Step 2:- Print the menu.
Step 3:- Get input for the choice from menu.
Step 4:- Using Selective statements calculate and print the result.
Source Code:-
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
ch=int(input("Enter your choice:"))
a=int(input("Enter the First Number:"))
b=int(input("Enter the Second Number:"))
if ch==1:
print("The Addition value is:",a+b)
elif ch==2:
print("The Subtraction value is:",a-b)
elif ch==3:
print("The Multiplication value is:",a*b)
elif ch==4:
print("The Division value is:",a/b)

P a g e 4 | 29
else:
print("Invalid option")

Output:-
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice:1
Enter the First Number:5
Enter the Second Number:3
The Addition value is: 8

Result:-
Thus the above program has been successfully executed.
--------------------------------------------------------------------------------------------------

P a g e 5 | 29
2. MULTIPLICATION TABLE
Aim:-
To write a Python Program to display the multiplication table of the
given number.
Algorithm:-
Step 1:- Get Input.
Step 2:- Using Looping statements calculate and print the result.
Source Code:-
num = int(input("Display multiplication table of:"))
for i in range(1, 11):
print(num, 'x', i, '=', num*i)
Output:-
Display multiplication table of: 2
2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
Result:-
Thus the above program has been successfully executed.

P a g e 6 | 29
3. DOUBLE THE ODD VALUES AND HALF EVEN VALUES OF A LIST
Aim: - To write a python program to pass list to a function and double
the odd values and half even values of a list and display list element
after changing.
Algorithm:-
Step 1:- Create List.
Step 2:- Create Function.
Step 3:- Call the Function.
Step 4:- Using Selective statements calculate and print the result.
Source Code:-
def f(x):
new_list=[]
for i in x:
if i%2==0:
new_list.append(i//2)
else:
new_list.append(i*2)
return new_list
my_list=list(range(1,6))
print('Original List:',my_list)
my_list=f(my_list)
print('Modified List:',my_list)
Output:-
Original List: [1, 2, 3, 4, 5]
Modified List: [2, 1, 6, 2, 10]

P a g e 7 | 29
Result:-
Thus the above program has been successfully executed.
--------------------------------------------------------------------------------------------------
4. ODD AND EVEN NUMBERS COUNT IN TUPLE.
Aim:-
To write a Python program input n numbers in tuple and pass it to
function to count how many even and odd numbers are entered.
Algorithm:-
Step 1:- Create tuple.
Step 2:- Print the data.
Step 3:- Create and call the Function.
Step 4:- Using Selective statements calculate and print the result.
Source Code:-
def CountOfEO(t):
EC = OC = 0
for i in t:
if(i % 2 == 0):
EC = EC + 1
else:
OC = OC + 1
return EC,OC
t=eval(input("Enter the tuple"))
print("Tuple Items are = ", t)
eCount, oCount = CountOfEO(t)
print("The Count of Even Numbers in t = ", eCount)

P a g e 8 | 29
print("The Count of Odd Numbers in t = ", oCount)
Output:-
Enter the tuple 2, 3, 4, 5, 6, 7, 8, 9
Tuple Items are = (2, 3, 4, 5, 6, 7, 8, 9)
The Count of Even Numbers in t = 4
The Count of Odd Numbers in t = 4
Result:-
Thus the above program has been successfully executed.
--------------------------------------------------------------------------------------------------
5. UPDATE VALUE AT THAT KEY IN DICTIONARY
Aim: - To write a Python program to function with key and value, and
update value at that key in dictionary entered by user.
Algorithm:-
Step 1:- Get Inputs.
Step 2:- Create empty dictionary.
Step 3:- Update the value.
Step 4:- Print the result.
Source Code:-
key = input("Please enter the Key : ")
value = input("Please enter the Value : ")
myDict = {}
myDict[key] = value
print("\nUpdated Dictionary = ", myDict)
Output:-
Please enter the Key: 1

P a g e 9 | 29
Please enter the Value: January

Updated Dictionary = {'1': 'January'}


Result:-
Thus the above program has been successfully executed.
--------------------------------------------------------------------------------------------------
6. VOWELS COUNTING
Aim:-
To write a Python program to pass a string to a function and count how
many vowels present in the string.
Algorithm:-
Step 1:- Get Input.
Step 2:- Print the data.
Step 3:- Create and call the function.
Step 4:- Using Selective statements calculate and print the result.
Source Code:-
def vowels(s):
v=0
for i in s:
if i in "aeiouAEIOU":
v=v+1
return v
s=input("Enter String:")
print("Number of vowels is string is:", vowels(s))

P a g e 10 | 29
Output:-
Enter String: Hello India
Number of vowels is string is: 5
Result:-
Thus the above program has been successfully executed.
--------------------------------------------------------------------------------------------------
7. RANDOM NUMBER GENERATOR
Aim: - To write a Python program to generator (Random Number) that
generates random numbers between 1 and 6 (simulates a dice) using
user defined function.
Algorithm:-
Step 1:- Import module.
Step 2:- Get input for the choice.
Step 3:- Using Selective statements calculate and print the result.
Source Code:-
import random
while True:
ch=input("Enter (r) for roll dice or press any other key to quit")
if (ch != ' r ' ):
break
n=random.randint(1,6)
print(n)
Output:-
Enter (r) for roll dice or press any other key to quitr
4

P a g e 11 | 29
Enter (r) for roll dice or press any other key to quitr
1
Enter (r) for roll dice or press any other key to quitr
2
Enter (r) for roll dice or press any other key to quitd
Result:-
Thus the above program has been successfully executed.
--------------------------------------------------------------------------------------------------
8. MATHEMATICAL FUNCTIONS
Aim: - To write a python program to implement python mathematical
functions.
Algorithm:-
Step 1:- Import module.
Step 2:- Using math functions Calculate and print the result.
Source Code:-
import math as m
print("The sin value of 90 is:",m.sin(90))
print("The cos value of 45 is:",m.cos(45))
print("The tan value of 90 is:",m.tan(90))
print("The square root value of 81 is:",m.sqrt(81))
print("The power value of 2 power 3 is:",m.pow(2,3))
print("The ceil value of 1.3 is:",m.ceil(1.3))
print("The floor value of 1.5 is:",m.floor(1.5))
print("The absolute value of -5 is:",m.fabs(-5))
print("The factorial value of 4 is:",m.factorial(4))

P a g e 12 | 29
Output:-
The sin value of 90 is: 0.8939966636005579
The cos value of 45 is: 0.5253219888177297
The tan value of 90 is: -1.995200412208242
The square root value of 81 is: 9.0
The power value of 2 power 3 is: 8.0
The ceil value of 1.3 is: 2
The floor value of 1.5 is: 1
The absolute value of -5 is: 5.0
The factorial value of 4 is: 24
Result:-
Thus the above program has been successfully executed.
--------------------------------------------------------------------------------------------------
9. STRING FUNCTIONS
Aim: - To write a python program to implement python string functions.
Algorithm:-
Step 1:- Get Inputs.
Step 2:- Print the data.
Step 3:- Using String functions print the result.
Source Code:-
s1="Hello India"
s2="Welcome India"
print("The Capitalize functions is:",s1.capitalize())
print("The title function is:",s2.title())
print("The lower function is:",s1.lower())
P a g e 13 | 29
print("The Upper function is:",s2.upper())
print("The Swapcase function is:",s1.swapcase())
print("The Count function is:",s2.count('e'))
print("The find function is:",s2.find('e'))
print("The isalpha function is:",s1.isalpha())
print("The isdigit function is:",s2.isdigit())
print("The replace function is:",s2.replace("Welcome","My"))
Output:-
The Capitalize functions is: Hello india
The title function is: Welcome India
The lower function is: hello india
The Upper function is: WELCOME INDIA
The Swapcase function is: hELLO iNDIA
The Count function is: 2
The find function is: 1
The isalpha function is: False
The isdigit function is: False
The replace function is: My India
Result:-
Thus the above program has been successfully executed.
--------------------------------------------------------------------------------------------------

P a g e 14 | 29
10. DISPLAY EACH WORD SEPARATED BY #
Aim:- To write a python program to read and display file content line by
line with each word separated by #.
Algorithm:-
Step 1:- Open a file.
Step 2:- Read the data.
Step 3:- Using Looping statements calculate and print the result.
Source Code:-
sample.txt

Hello Students

Welcome to All

textfilepro.py

file=open(“sample.txt”,’r’)

for text in file.readlines():

for word in text.split():

print(word+ “#” , end=” “)

print(“ “)

file.close()

Output:-

Hello# Students#

Welcome# to# All#

Result:-

Thus the above program has been successfully executed.

P a g e 15 | 29
11. REMOVE THE LINES THAT CONTAIN ‘A’ IN A FILE.
Aim:- To write a python program to remove all the lines that contain the
character ‘a’ in a file and write it to another file.
Algorithm:-
Step 1:- Open a file.
Step 2:- Read the data.
Step 3:- Using Selective statements calculate and print the result.
Source Code:-
sample.txt
I am a python
hello world
textfilepro.py
file=open("sample.txt",'r')
lines=file.readlines()
file.close()
file=open("x.txt",'w')
file1=open("y.txt",'w')
for line in lines:
if 'a' in line:
file1.write(line)
else:
file.write(line)
print("All line that contains a character has been removed from x.txt
file")
print("All line that contains a character has been saved from y.txt file")

P a g e 16 | 29
file.close()
file1.close()
Output:-
x.txt
hello world

y.txt
I am a python
Result:-
Thus the above program has been successfully executed.
--------------------------------------------------------------------------------------------------
12. CASE COUNTING
Aim:- To write a python program to read characters from keyboard one
by one, all lower case letters gets stored inside a file “LOWER”, all
uppercase letters gets stored inside a file “UPPER”, and all other
characters get stored inside “OTHERS”.
Algorithm:-
Step 1:- Open a file.
Step 2:- Read the data.
Step 3:- Using Selective statements calculate and print the result.
Source Code:-
f1=open("e:\\lower.txt","w")
f2=open("e:\\upper.txt","w")
f3=open("e:\\others.txt","w")
c=True
while c:
P a g e 17 | 29
c=input("Enter a character to write or False to terminate the program
: ")
if c is False:
break
elif c.islower():
f1.write(c)
elif c.isupper():
f2.write(c)
else:
f3.write(c)
f1.close()
f2.close()
f3.close()
Output:-
Enter a character to write or False to terminate the program: h
Enter a character to write or False to terminate the program: H
Enter a character to write or False to terminate the program: a
Enter a character to write or False to terminate the program: A
Enter a character to write or False to terminate the program: i
Enter a character to write or False to terminate the program: I
Enter a character to write or False to terminate the program: @
Enter a character to write or False to terminate the program: 1
Enter a character to write or False to terminate the program:
lower.txt
hai

P a g e 18 | 29
upper.txt
HAI
others.txt
@1
Result:-
Thus the above program has been successfully executed.
--------------------------------------------------------------------------------------------------
13. SEARCH RECORD IN A BINARY FILE
Aim: - To write a Python program to create a binary file with name and
roll number. Search for a given roll number and display the name, if not
found display appropriate message.
Algorithm:-
Step 1:- Import module.
Step 2:- Open a file.
Step 3:- Get Inputs.
Step 4:- Read the data.
Step 5:- Get input for the choice.
Step 6:- Using Looping statements Search and print the result.
Source Code:-
binaryprofile1.py
import pickle
file=open("stud.dat","wb")
stud={}
n=int(input("Enter the number of students:"))
for i in range(n):

P a g e 19 | 29
sno=int(input("Enter the student roll number:"))
sname=input("Enter student name")
stud[sno]=sname
pickle.dump(stud,file)
file.close()
binaryprofile2.py
import pickle
file=open("stud.dat","rb")
d=pickle.load(file)
n=int(input("Enter the student Number to search"))
for i in d:
if i==n:
print("The name of the roll number ",i,"is",d[i])
else:
print("Data not found in the file.")
break
file.close()
Output:-
Enter the number of students: 2
Enter the student roll number: 101
Enter the student name: Ajay
Enter the student roll number: 102
Enter the student name: Siva
Enter the student number to search: 101
The name of the roll number 101 is Ajay
P a g e 20 | 29
Enter the student number to search: 111
Data not found in the file.
Result:-
Thus the above program has been successfully executed.
--------------------------------------------------------------------------------------------------
14. UPDATE RECORD OF A BINARY FILE.
Aim: - To write a Python program to create a binary file with roll
number, name and marks. Input a roll number and update the marks.
Algorithm:-
Step 1:- Import module.
Step 2:- Open a file.
Step 3:- Get inputs.
Step 4:- Read the data.
Step 5:- Get input for the choice.
Step 6:- Using Looping statements update and print the result.
Source Code:-
binaryprofile1.py
import pickle
file=open("stud.dat","wb")
stud={}
n=int(input("Enter the number of students:"))
for i in range(n):
sno=int(input("Enter the student roll number:"))
sname=input("Enter the student name")
mark=int(input("Enter the student mark"))

P a g e 21 | 29
stud[sno]={}
stud[sno]["Sname"]=sname
stud[sno]["Marks"]=mark
pickle.dump(stud,file)
file.close()
binaryprofile2.py
file=open("stud.dat","rb+")
d=pickle.load(file)
n=int(input("Enter the student Number to Update Marks"))
for i in d:
if i==n:
x=int(input("Enter the student new marks"))
d[i]["Marks"]=x
print(d)
else:
print("Data not found in the file.")
break
pickle.dump(d,file)
file.close()
Output:-
Enter the number of students: 2
Enter the student roll number: 111
Enter the student name: Arjun
Enter the student mark: 70
Enter the student roll number: 112
P a g e 22 | 29
Enter the student name: Ram
Enter the student mark: 90
Enter the student number to update marks: 111
Enter the student new marks: 80
{111: {'Sname': 'Arjun', 'Marks': 80}, 112: {'Sname': 'Ram', 'Marks': 90}}
Enter the student number to update marks: 110
Data not found in the file.
Result:-
Thus the above program has been successfully executed.
--------------------------------------------------------------------------------------------------
15. EMPLOYEE DETAILS IN CSV FILE.
Aim: - To write a Python program to create a CSV file to store Empno,
Name and Salary. Search and display Name and Salary of a given
Empno, if not found display appropriate message.
Algorithm:-
Step 1:- Import module.
Step 2:- Open a file.
Step 3:- Get Inputs.
Step 4:- Read the data.
Step 3:- Get input for the choice.
Step 4:- Using Selective statements search and print the result.
Source Code:-
import csv
with open("e:\\myfile.csv","a") as csvfile:
mywriter=csv.writer(csvfile,delimiter=',')

P a g e 23 | 29
ch='y'
while ch.lower()=='y':
eno=int(input("Enter Employee Number:"))
ename=input("Enter Employee Name:")
salary=int(input("Enter Employee Salary:"))
mywriter.writerow([eno,ename,salary])
print("Data Saved Successfully!")
ch=input("Add more ?")
ans='y'
with open("e:\\myfile.csv","r") as csvfile:
myreader=csv.reader(csvfile,delimiter=',')
while ans=='y':
found=False
n=int(input("Enter Employee Number to Search:"))
for i in myreader:
if len(i)!=0:
if int(i[0])==n:
print("NAME :",i[1])
print("SALARY :",i[2])
found=True
break
if not found:
print(" Data not found")
ans=input("Search More ?(Y)")

P a g e 24 | 29
Output:-
Enter Employee Number:101
Enter Employee Name:Ajay
Enter Employee Salary:50000
Data Saved Successfully!
Add more ?y
Enter Employee Number:102
Enter Employee Name:Sanjay
Enter Employee Salary:45000
Data Saved Successfully!
Add more ?n

Enter Employee Number to Search:101


NAME : ajay
SALARY : 50000
Enter Employee Number to Search:103
Data not found
Search More ?(Y)n
Result:-
Thus the above program has been successfully executed.
--------------------------------------------------------------------------------------------------

P a g e 25 | 29
16. STUDENTS DETAILS IN CSV FILE.
Aim:- To write a Python program create a CSV file to store Rollno, Name
and Marks. Also read the content from CSV file.
Algorithm:-
Step 1:- Import module.
Step 2:- Open a file.
Step 2:- Get Inputs.
Step 3:- Read the data.
Step 4:- Using Looping statements print the result.
Source Code:-
import csv
with open("e:\\myfile1.csv","w",newline="") as csvfile:
mywriter=csv.writer(csvfile,delimiter=',')
ch='y'
while ch.lower()=='y':
Rollno=int(input("Enter Student Roll Number:"))
Name=input("Enter Student Name:")
Marks=int(input("Enter Student Marks:"))
mywriter.writerow([Rollno,Name,Marks])
print("Data Saved Successfully!")
ch=input("Add more ?")
with open("e:\\myfile1.csv","r") as csvfile:
newFileReader=csv.reader(csvfile)
for i in newFileReader:
print("Student roll number is:",i[0])

P a g e 26 | 29
print("Student name is:",i[1])
print("Student mark is:",i[2])
Output:-
Enter Student Roll Number:101
Enter Student Name:Ajay
Enter Student Marks:100
Data Saved Successfully!
Add more ?y
Enter Student Roll Number:102
Enter Student Name:Siva
Enter Student Marks:98
Data Saved Successfully!
Add more? n
Student roll number is: 101
Student name is: Ajay
Student mark is: 100
Student roll number is: 102
Student name is: Siva
Student mark is: 98
Result:-
Thus the above program has been successfully executed.
--------------------------------------------------------------------------------------------------

P a g e 27 | 29
17. READ THE PASSWORD IN A CSV FILE
Aim: - To create a CSV file by entering user-id and password, read and
search the password for given userid.
Algorithm:-
Step 1:- Import module.
Step 2:- Open a file.
Step 3:- Get Inputs.
Step 4:- Read the data.
Step 5:- Get input for the choice.
Step 6:- Using Selective statements search and print the result.
Source Code:-
File1.py
import csv
f=open("e:\\s1.csv","w",newline="")
x=csv.writer(f)
x.writerow(["User","Pwd"])
while True:
uid=input("Enter User:")
pd=input("Enter Password:")
x.writerow([uid,pd])
ch=input("Enter continue or not")
if ch in 'Nn':
break
f.close()
File2.py

P a g e 28 | 29
import csv
f=open("e:\\s1.csv",'r')
n=input("Enter uid to search pwd:")
x=csv.reader(f)
for i in x:
if i[0]==n:
print("Your Password is:",i[1])
break
else:
print("Sorry data not found")
f.close()
Output:-
Enter User:admin1
Enter Password:111
Enter continue or noty
Enter User:admin2
Enter Password:222
Enter continue or not n
Enter uid to search pwd: admin1
Your Password is: 111
Enter uid to search pwd:admin3
Sorry data not found
Result:-
Thus the above program has been successfully executed.

P a g e 29 | 29

You might also like