Class 12 Practical List
Class 12 Practical List
Class 12 Practical List
COMPUTER SCIENCE
PROGRAM FILE
LIST OF PROGRAMS
OUTPUT:
Enter a number: 10
The factorial of 10 is 3628800
2. Write a Program to enter the number of terms and to print the Fibonacci Series.
n = 10
num1 = 0
num2 = 1
next_number = num2
count = 1
Output
1 2 3 5 8 13 21 34 55 89
3. Write a program to accept a string and print the number of uppercase, lowercase,
vowels, consonants and spaces in the given string.
Str=input(“Enter A string”)
lower=0
upper=0
for i in Str:
if(i.islower()):
lower+=1
else:
upper+=1
print("The number of lowercase characters is:",lower)
print("The number of uppercase characters is:",upper)
Output
OUTPUT:
Enter a word to be searched Geeks
Given word Found
5. Write a Program to enter the numbers and a List to perform Binary Search using function.
if x == array[mid]:
return mid
else:
high = mid - 1
return -1
OUTPUT:
Enter a list:[2,3,4,5,6,8,10]
Enter a Number to be searched:4
Element is present at index 2
6. Write a Program to enter the elements in a List and sort these elements using bubble sort
technique.
def bubbleSort( theSeq ):
n = len( theSeq )
for i in range( n - 1 ) :
flag = 0
for j in range(n - 1) :
if flag == 0:
break
return theSeq
el = [21,6,9,33,3]
result = bubbleSort(el)
print (result)
7. Program to read and display file content line by line with each word separated by “ #”.
def process_file(file_path):
try:
with open(file_path, 'r') as file:
for line in file:
words = line.split()
formatted_line = '#'.join(words)
print(formatted_line)
except FileNotFoundError:
print(f"File '{file_path}' not found.")
except Exception as e:
print(f"An error occurred: {e}")
try:
with open(file_path, 'r') as file:
content = file.read()
for char in content:
if char.isalpha():
if char.isupper():
uppercase_count += 1
elif char.islower():
lowercase_count += 1
if char in vowels:
vowel_count += 1
elif char in consonants:
consonant_count += 1
except FileNotFoundError:
print(f"File '{file_path}' not found.")
except Exception as e:
print(f"An error occurred: {e}")
file_path = 'file.txt'
count_characters(file_path)
9. 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.
f1 = open("Mydoc.txt")
f2 = open("copyMydoc.txt","w")
for line in f1:
if 'a' not in line:
f2.write(line)
print('## File Copied Successfully! ##')
f1.close()
f2.close()
f2 = open("copyMydoc.txt","r")
print(f2.read())
10. Program to store students’ details like admission number, roll number, name and percentage in a
dictionary and display information on the basis of admission number.
import csv
with open('Student_Details.csv','w',newline='') as csvf:
writecsv=csv.writer(csvf,delimiter=',')
choice='y'
while choice.lower()=='y':
rl=int(input("Enter Roll No.: "))
n=input("Enter Name: ")
p=float(input("Enter Percentage: "))
r=input("Enter Remarks: ")
writecsv.writerow([rl,n,p,r])
print(" Data saved in Student Details file..")
choice=input("Want add more record(y/n)....")
pickle.dump(d2,b)
d3={'name':'third','roll number':3}
pickle.dump(d3,b)
roll=int(input('enter the desired roll no:'))
with open('students','rb')as b:
p=[]
while True:
try:
for i in range(1,4):
k=pickle.load(b)
p+=[k['roll number']]
if roll==k['roll number']:
print('the name of the desired student is:',k['name'])
if roll not in p:
print('the student of the desired roll no. does not exist')
except EOFError:
break
12. Program to create binary file to store Roll no, Name and Marks and update marks of entered Roll
no.
import pickle
def write_to_binary_file(filename, students):
with open(filename, 'wb') as file:
pickle.dump(students, file)
def read_from_binary_file(filename):
try:
with open(filename, 'rb') as file:
students = pickle.load(file)
return students
except FileNotFoundError:
return ()
def roll_dice():
print (random.randint(1, 6))
flag = True
while flag:
user_prompt = input(">")
if user_prompt.lower() == "quit":
flag = False
else:
print("Rolling dice...\nYour number is:")
roll_dice()
14. Create a CSV file by entering user-id and password, read and search the password for given user-
id.
import csv
with open("7.csv", "w") as obj:
fileobj = csv.writer(obj)
fileobj.writerow(["User Id", "password"])
while(True):
user_id = input("enter id: ")
password = input("enter password:
") record = [user_id, password]
fileobj.writerow(record)
x = input("press Y/y to continue and N/n to terminate the program\n")
if x in "Nn":
break
elif x in "Yy":
continue
with open("7.csv", "r") as obj2:
fileobj2 = csv.reader(obj2)
given = input("enter the user id to be searched\n")
for i in fileobj2:
next(fileobj2)
# print(i,given)
if i[0] == given:
print(i[1])
break
15. Program to implement Stack in Python using List.
def isempty(stk):
if stk==[]:
return True
else:
return False
def push(stk,item):
stk.append(item)
top=len(stk)-1
def pop(stk):
if isempty(stk):
return "underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item
def peek(stk):
if isempty(stk):
return "underflow"
else:
top=len(stk)-1
return stk[top]
def display(stk):
if isempty(stk):
print('stack is empty')
else:
top=len(stk)-1
print(stk[top],'<-top')
for i in range(top-1,-1,-1):
print(stk[i])
def main():
stk=[]
top=None
while True:
print('''stack operation
1.push
2.pop
3.peek
4.display
5.exit''')
iii. SELECT Class, DOB, city FROM Students WHERE Marks between 540 to 551;
17. To write SQL-Queries for the following Questions based on the given table.
Solution:
i. (a) Create table VEHICAL (VOCDE char(4) primary key, VECHICALTYPE varchar(20),
PERKM int(3));
(b) Create table TRAVEL(CNO int(3) primary key, CNAME varchar(20), TRAVELDATE DATE,
KM int(3), VCODE char(3), NOP int(3));
ii. (a) INSERT INTO VEHICAL VALUES(‘V01’, ‘VOLVO BUS’, 150);
(b) INSERT INTO TRAVEL values(101, ‘K.NAIWAL’, ’13-12-2015’,200,’V01’, 32);
iii. DISPLAY CNO,CNAME,TRAVELDATE from TRAVEL order by desc CNO;
iv.
18. Program to connect with database and store record of employee and display records.
def connect_db():
conn = mysql.connector.connect( host="localhost", # MySQL server address (localhost if local)
user="root",
return conn
def display_employees():
conn = connect_db()
cursor = conn.cursor() # Retrieve all records from the employee
table cursor.execute('SELECT * FROM employee')
employees = cursor.fetchall() # Check if there are any records and display
them if employees:
print(f"{'ID':<5}{'Name':<20}{'Age':<5}{'Department':<20}{'Salary':<10}")
print("-" * 60)
for emp in employees: print(f"{emp[0]:<5}{emp[1]:<20}{emp[2]:<5}{emp[3]:<20}
{emp[4]:<10}") else: print("No
employee records found.")
conn.close()
display_employees()
19. 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
def connect_db():
conn = mysql.connector.connect( host="localhost", user="root", password="your_password",
database="employee_db")
return conn
def search_employee(empno):
conn = connect_db()
cursor = conn.cursor() # Query to search for the employee by empno
cursor.execute(''' SELECT * FROM employee WHERE empno = %s; ''', (empno,))
employee = cursor.fetchone()
if employee: # Employee found, displaying the details
print(f"{'Emp No':<10}{'Name':<20}{'Age':<5}{'Department':<20}{'Salary':<10}")
print("-" * 60)
print(f"{employee[0]:<10}{employee[1]:<20}{employee[2]:<5}{employee[3]:<20}
{employee[ 4]:<10}")
else:
conn.close()
search_employee(empno)
20. Write a program to connect Python with MySQL using database connectivity and perform the
following operations on data in database: Fetch, Update and delete the data.
A. CREATE A TABLE
import mysql.connector demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("CREATE TABLE STUDENT (admn_no int primary key, sname varchar(30), gender
char(1), DOB date, stream varchar(15), marks float(4,2))")
B. INSERT THE DATA:
import mysql.connector demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("insert into student values (%s, %s, %s, %s, %s, %s)", (1245, 'Arush', 'M', '2003-
10-04', 'science', 67.34))
demodb.commit( )
C. FETCH THE DATA
import mysql.connector demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("select * from student")
for i in democursor:
print(i)
D. UPDATE THE RECORD
import mysql.connector demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("update student set marks=55.68 where admn_no=1356")
demodb.commit( )
E. DELETE THE DATA
import mysql.connector demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("delete from student where admn_no=1356")
demodb.commit( )