cs record file

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

PRACTICAL FILE (2024-2025)

CLASS XII

SUBJECT: COMPUTER SCIENCE (083)

1. #WAP to print a string and the number of vowels present in it


st=input("Enter the string:")
print("Entered string =",st)
st=st.lower()
c=0
v=['a','e','i','o','u']
for i in st:
if i in v:
c+=1
print("Number of vowels in entered string =",c)

OUTPUT:
Enter the string: PYTHON PROGRAMMING
Entered string = PYTHON PROGRAMMING
Number of vowels in entered string = 4

2. Write a python script to take input for 2 numbers and an operator (+ , – , * , /


). Based on the operator calculate and print the result?

a=int(input("Enter 1st no "))


b=int(input("Enter 2nd no "))
op=input("Enter the operator (+,-,,/) ")
if(op=="+"):
c=a+b
print("Sum = ",c)
elif(op=="*"):
c=a*b
print("Product = ",c)
elif(op=="-"):
if(a>b):
c=a-b
else:
c=b-a
print("Difference = ",c)
elif(op=="/"):
c=a/b
print("Division = ",c)
else:
print("Invalid operator")

OUTPUT:

Enter 1st number1:64

Enter 2nd number2: 8

Enter the operator (+,-,*,/):/

Division = 8.0

3. Write a program to read a file book.txt print the contents of file along with
frequency of word “computer” in it.

f=open("book.txt","r")
L=f.readlines()
c=c1=0
print("Contents of file :")
for i in L:
print(i)
j=i.split()
for k in j:
if k.lower()=="computer":
c1=c1+1
print("*****FILE END*****")
print()
print("Number of times 'computer' in the file=",c1)
f.close()

OUTPUT:

Contents of file :
Its language constructs and object-oriented approach aim to help computer
programmers to write clear with logical code.

I choosed computer group because I love my computer subject very much.

*****FILE END*****

Number of times 'computer' in the file=3


4. Write a program to read a file Top.txt and print the contents of file along
with the number of lines starting with A.

f=open("Top.txt","r")
st=f.readlines()
c=0
print("Contents of file :")
for i in st:
print(i)
if i[0]=="A":
c+=1
print("\n*****FILE END*****")
print()
print("Number of lines starting with 'A' =",c)

OUTPUT:
A Python is an interpreted, high-level, general-purpose programming language.
Created by Guido van Rossum and first released in 1991.
A Python's design philosophy emphasizes code readability.
Its language constructs and object-oriented approach aim to help programmers
write clear, logical code.
*****FILE END*****

Number of lines starting with 'A' = 2

5. WAP to input a list of number and search for a given number using linear
search

l=eval(input("Enter the list of numbers:"))


x=int(input("Enter the number:"))
for i in l:
if i==x:
print("Element present") break
else:
print("Element not found")
break

OUTPUT:
Enter the list of numbers:[5,3,4,2,1]
Enter the number: 3
Element present
6. Write a function DigitSum() that takes a number and returns its digit sum
def DigitSum(n):
s=0
n=str(n)
for i in n:
s=s+int(i)
return s
n=int(input("Enter the number"))
print("Sum of digits =", DigitSum(n))

OUTPUT:
Enter the number69 Sum of digits = 15

7. Write a function Div3and5() that takes a 10 elements numeric tuple and return
the sum of elements which are divisible by 3 and 5.

def Div3and5(t):
s=0
for i in t:
if i%3==0 and i%5==0:
s=s+i
return s #main
l=[]
for i in range(3):
print("Enter the ",i+1,"th number of the tuple",end=" ",sep="")
e=int(input())
l.append(e)
t=tuple(l)
print("Entered tuple :",t)
print("Sum of numbers in tuple divisible by 3 and 5 =",Div3and5(t))

OUTPUT:
Enter the 1th number of the tuple
15
Enter the 2th number of the tuple
27
Enter the 3th number of the tuple
81
Entered tuple: (15, 27, 81)
Sum of numbers in tuple divisible by 3 and 5 = 15
8. Write a Program to enter the string and to check if it‟s palindrome or not using
loop.

def palin(s):
return s==s[::-1]
s=str(input("Enter the string data:"))
ans=palin(s)
if ans:
print("The given string data:",s,":is pallindrome")
else:
print("The given string data:",s,":is not a pallindrome")

OUTPUT:
Enter the string data:MALAYALAM
The given string data: MALAYALAM :is palindrome

9. Program to read the content of file and display the total number of consonants,
uppercase, vowels and lower case characters‟

f = open("file1.txt")
v=0
c=0
u=0
l=0
o=0
data = f.read()
vowels=['a','e','i','o','u']
for ch in data:
if ch.isalpha():
if ch.lower() in vowels:
v+=1
else:
c+=1
if ch.isupper():
u+=1
elif ch.islower():
l+=1
elif ch!=' ' and ch!='\n':
o+=1
print("Total Vowels in file :",v)
print("Total Consonants in file n :",c)
print("Total Capital letters in file :",u)
print("Total Small letters in file :",l)
print("Total Other than letters :",o)
f.close()

CONTENT O FILE:
India is my country I love python
Python learning is fun 123@

OUTPUT:
Total Vowels in file 16
Total Consonants in file n 30
Total Capital letters in file 3
Total Small letters in file 43
Total Other than letters 4

10. Program to store student‟s information like admission number, roll no., name
and marks in a dictionary, and display information on the basis of admission
number.

SCL=dict()
i=1
flag=0
n=int(input(“\nEnter number of entries:”))
while i<=n:
Adm=input(“\nEnter admission no of student:”)
nm=input(“Enter name of the student:”)
sec=input(“Enter class and section:”)
per=float(input(“Enter percentage of a student:”))
b=(nm,sec,per)
SCL[Adm]=b
i=i+1
l=SCL.keys()
for i in l:
print(“\nAdmno- “,I,” :”)
z=SCL[i]
print(“Name\t”,”class\t”,”per\t”)
for j in z:
print(j, end=”\t”)

OUTPUT:

Enter number of entries:1

Enter admission no of student:12001

Enter name of the student:GEETHA G

Enter class and section:XII A


Enter percentage of a student:86

Admno- 12001 :
Name class per
GEETHA G XII A 86.0

11. Program to read the content of file line by line and write it to another file
except for the lines contains “a” letter in it.
#Program to read line from file and write it to another line
#Except for those line which contains letter 'a'

f1 = open("file2.txt")
f2 = open("file2copy.txt","w")

for line in f1:


if 'a' not in line:
f2.write(line)
print(“## File Copied Successfully! ##”) f1.close()
f2.close()

NOTE: Content of file2.txt


a quick brown fox one two three four five six seven
India is my country eight nine ten
bye!

OUTPUT :
## File Copied Successfully! ##
NOTE: After copy content of file2copy.txt
one two three four five six seven eight nine ten bye!

12. Program to create binary file to store Rollno and Name, Search any Rollno
and display name if Rollno found otherwise “Rollno not found”

import pickle
student=[ ]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
student.append([roll,name])
ans=input("Add More ?(Y)")
pickle.dump(student,f)
f.close()
f=open('student.dat','rb')
student=[ ]
while True:
try:
student = pickle.load(f)
except EOFError:
break
ans='y'

while ans.lower()=='y':
found=False
r = int(input("Enter Roll number to search :"))
for s in student:
if s[0]==r:
print("## Name is :",s[1], " ##")
found=True
break
if not found:
print("####Sorry! Roll number not found ####")
ans=input("Search more ?(Y) :")
f.close()

OUTPUT:

Enter Roll Number :101


Enter Name :Rose
Add More ?(Y)y
Enter Roll Number :102
Enter Name :Kumar
Add More ?(Y)n
Enter Roll number to search :102
## Name is : Kumar ##
Search more ?(Y) :y
Enter Roll number to search :101
## Name is : Rose ##
Search more ?(Y) :n

13. Program to create binary file to store Rollno, Name and Marks and update
marks of entered Rollno.

import pickle
student=[ ]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
marks = int(input("Enter Marks :"))
student.append([roll,name,marks])
ans=input("Add More ?(Y)")
pickle.dump(student,f)
f.close()
f=open('student.dat','rb+')
student=[]
while True:
try:
student = pickle.load(f)
except EOFError:
break
ans='y'
while ans.lower()=='y':
found=False
r = int(input("Enter Roll number to update :"))
for s in student:
if s[0]==r:
print("## Name is :",s[1], " ##")
print("## Current Marks is :",s[2]," ##")
m = int(input("Enter new marks :"))
s[2]=m
print("## Record Updated ##")
found=True
break
if not found:
print("####Sorry! Roll number not found ####")
ans=input("Update more ?(Y) :")
f.close()

OUTPUT:
Enter Roll Number :12001
Enter Name :Raj
Enter Marks :78

Add More ?(Y)y


Enter Roll Number :12002
Enter Name :Gokul
Enter Marks :88
Add More ?(Y)n

Enter Roll number to update :12001


## Name is : Raj ##
## Current Marks is : 78 ##

Enter new marks :80


## Record Updated ##

Update more ?(Y) :n

14. Program to create CSV file and store empno,name,salary and search any
empno and display name,salary and if not found appropriate message.

import csv
with open('myfile.csv',mode='a') as csvfile:
mywriter = csv.writer(csvfile,delimiter=',')
ans='y'
while ans.lower()=='y':
eno=int(input("Enter Employee Number "))
name=input("Enter Employee Name ")
salary=int(input("Enter Employee Salary :"))
mywriter.writerow([eno,name,salary])
print("## Data Saved... ##")
ans=input("Add More ?")
ans='y'
with open('myfile.csv',mode='r') as csvfile:
myreader = csv.reader(csvfile,delimiter=',')
while ans=='y':
found=False
e = int(input("Enter Employee Number to search :"))
for row in myreader:
if len(row)!=0:
if int(row[0])==e:
print("============================")
print("NAME :",row[1])
print("SALARY :",row[2])
found=True
break
if not found:
print("==========================")
print(" EMPNO NOT FOUND")
print("==========================")
ans = input("Search More ? (Y)")

OUTPUT:
Enter Employee Number 1001
Enter Employee Name kala
Enter Employee Salary :67000
## Data Saved... ##
Add More ?y
Enter Employee Number 1002
Enter Employee Name selva
Enter Employee Salary :70000
## Data Saved... ##
Add More ?n
Enter Employee Number to search :1001
============================
NAME : kala
SALARY : 67000
Search More ? (Y)y
Enter Employee Number to search :1002
============================
NAME : selva
SALARY : 70000
Search More ? (Y)n
15. Program to implement Stack in Python using List
def isEmpty(S):
if len(S)==0:
return True
else:
return False

def Push(S,item):
S.append(item)
top=len(S)-1

def Pop(S):
if isEmpty(S):
return "Underflow"
else:
val = S.pop()
if len(S)==0:
top=None
else:
top=len(S)-1
return val

def Peek(S):
if isEmpty(S):
return "Underflow"
else:
top=len(S)-1
return S[top]

def Show(S):
if isEmpty(S):
print("Sorry No items in Stack ")
else:
t = len(S)-1
print("(Top)",end=' ')
while(t>=0):
print(S[t],"<==",end=' ')
t-=1
print()
# main begins here
S=[] #Stack
top=None
while True:
print("**** STACK DEMONSTRATION ******")
print("1. PUSH ")
print("2. POP")
print("3. PEEK")
print("4. SHOW STACK ")
print("0. EXIT")
ch = int(input("Enter your choice :"))
if ch==1:
val = int(input("Enter Item to Push :"))
Push(S,val)
elif ch==2:
val = Pop(S)
if val=="Underflow":
print("Stack is Empty")

else:
print("Deleted item", val)
elif ch==3:

print("\nDeleted Item was :",val)

val = Peek(S)
if val=="Underflow":
print("Stack Empty")

else:
print("Top Item", val)
elif ch==4:

print("Top Item :",val)

Show(S)
elif ch==0:
print("Bye")
break

OUTPUT:

**** STACK DEMONSTRATION ******


1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT

Enter your choice :4


Top Item : 40
(Top) 40 <==
20 <==
**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT

Enter your choice :1

Enter Item to Push :20


**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT

Enter your choice :30


**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT

INTERFACE PYTHON WITH MYSQL


16. Program to connect with database and store record of employee and display
records.

import mysql.connector as mycon


con = mycon.connect(host='127.0.0.1',user='root', password="root")
cur = con.cursor()
cur.execute("create database if not exists company")
cur.execute("use company")
cur.execute("create table if not exists employee(empno int, name varchar(20), dept
varchar(20),salary int)")
con.commit()
choice=None
while choice!=0:
print("1. ADD RECORD ")
print("2. DISPLAY RECORD ")
print("0. EXIT")
choice = int(input("Enter Choice :"))
if choice == 1:
e = int(input("Enter Employee Number :"))
n = input("Enter Name :")
d = input("Enter Department :")
s = int(input("Enter Salary :"))
query="insert into employee values({},'{}','{}',{})".format(e,n,d,s)
cur.execute(query)
con.commit()
print("## Data Saved ##")
elif choice == 2:
query="select * from employee"
cur.execute(query)
result = cur.fetchall()
print("%10s"%"EMPNO","%20s"%"NAME","%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
elif choice==0:
con.close()
print("## Bye!! ##")
else:
print("## INVALID CHOICE ##")

OUTPUT:

1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :1
Enter Employee Number :1 Enter Name :AMIT
Enter Department :SALES Enter Salary :9000
## Data Saved ##
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :1
Enter Employee Number :2 Enter Name :NITIN
Enter Department :IT Enter Salary :80000 ## Data Saved ##
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :2
EMPNO NAME DEPARTMENT SALARY
1 AMIT SALES 9000
2 NITIN IT 80000

17.Program to connect with database and search employee number in table


employee and display record, if empno not found display appropriate message.

import mysql.connector as mycon


con = mycon.connect(host='127.0.0.1',user='root', password="root",
database="company")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE SEARCHING FORM")
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO SEARCH :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO", %20s"%"NAME","%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
ans=input("SEARCH MORE (Y) :")
OUTPUT:

###############EMPLOYEE SEARCHING FORM ###################

ENTER EMPNO TO SEARCH :1


EMPNO NAME DEPARTMENT SALARY
1 AMIT SALES 9000
SEARCH MORE (Y) :y
ENTER EMPNO TO SEARCH :2
EMPNO NAME DEPARTMENT SALARY
2 NITIN IT 80000
SEARCH MORE (Y) :y
ENTER EMPNO TO SEARCH :4
Sorry! Empno not found SEARCH MORE (Y) :n

18. Program to connect with database and delete the record of entered employee
number.

import mysql.connector as mycon


con = mycon.connect(host='127.0.0.1',user='root', password="root",
database="company")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE DELETION FORM")
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO DELETE :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO","%20s"%"NAME", "%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
choice=input("\n## ARE YOUR SURE TO DELETE ? (Y) :")
if choice.lower()=='y':
query="delete from employee where empno={}".format(eno)
cur.execute(query)
con.commit()
print("=== RECORD DELETED SUCCESSFULLY! ===")
ans=input("DELETE MORE ? (Y) :")
OUTPUT:

###################EMPLOYEE DELETION FORM ######################

ENTER EMPNO TO DELETE :2


EMPNO NAME DEPARTMENT SALARY
2 NITIN SALES 91000

## ARE YOUR SURE TO DELETE ? (Y) :y


=== RECORD DELETED SUCCESSFULLY! === DELETE MORE ? (Y) :y
ENTER EMPNO TO DELETE :2
Sorry! Empno not found DELETE MORE ? (Y) :n

SQL COMMANDS
19. Consider the following table STUDENT. Write SQL commands for the following
statements.

StudID StudName Class Age Addr Marks


1001 Rose XII 17 Chennai 80
1002 Jhon XII 17 Madurai 70
1003 Surya X 15 Salem 55
1004 Madhan XII 15 Chennai 63

i) Create table for student using the above fields and apply Primary Key for the suitable
field.
ii) Enter the data in the column using SQL Command.
iii) Add another column in the STUDENT table as Gender.
iv) Remove the tuples from STUDENT table that have Age is less than 17.
v) Modify the table to change the StudName as “Gokul” for the StudID=1003

OUTPUT:

i) CREATE table STUDENT(StudID integer PRIMARY KEY, StudName varchar(20),


Class varchar(4), Age integer, Addr varchar(60), Marks integer);
ii) INSERT into STUDENT values(1001,‟Rose‟,‟XII‟,17,‟Chennai‟,80);
iii) ALTER table STUDENT ADD(Gender varchar(9));
iv) DELETE from STUDENT WHERE Age <17;
v) UPDATE STUDENT SET StudName=”Gokul” WHERE StudID=1003;
20. Consider the following table GAMES. Write SQL commands for the following
statements.

GCode GameName Type Number PrizeMoney ScheduleDate


101 Carom Board Indoor 2 5000 23-Jan-2004
102 Badminton Outdoor 2 12000 12-Dec-2003
103 Table Tennis Indoor 4 8000 14-Feb-2004
105 Chess Indoor 2 9000 01-Jan-2004
106 LawnTennis Outdoor 4 25000 19-Mar-2004

i) To display the name of all GAMES with their GCodes.


ii) To display details of those GAMES which are having PrizeMoney more than 7000.
iii) To display the content of the GAMES table in ascending order of ScheduleDate.
iv) To display sum of PrizeMoney for each Type of GAMES.
v) To Count & Display the Type from GAMES tables.

OUTPUT:

i) SELECT GameName, GCode FROM GAMES;


ii) SELECT * FROM GAMES WHERE PrizeMoney > 7000;
iii) SELECT * FROM GAMES ORDER BY ScheduleDate;
iv) SELECT SUM(PrizeMoney), Type FROM GAMES GROUP BY Type;
v) SELECT TYPE, COUNT(TYPE) from GAMES;

You might also like