CS Practical
Submitted By: Dhruv Rohilla
Class: 12th A
Roll No: 12
School: Angels Public School
Submitted To: Neeta Mam
Certificate
This is to certify that Dhruv Rohilla of
Class 12th A, Roll No. 12, has
successfully completed the practical
titled 'CS Practical' under the guidance
of Neeta Mam during the academic
year 2023-2024.
Date: ________________
Teacher Signature:
______________________
Acknowledgment
I would like to express my special
thanks of gratitude to my teacher
Neeta Mam who gave me the golden
opportunity to work on this practical,
which has helped me learn many
things. I am also thankful to my parents
and friends for their support.
Additionally, I would like to thank the
authors of the book Sumita Arora and
the various online resources like
Google, which provided valuable
information and assistance.
Index
1. PROGRAM FOR FACTORIAL OF A NUMBER.
2. PROGRAM TO CHECK WHETHER THE GIVEN NUMBER IS PRIME OR NOT
3. PROGRAM TO FIND THE CONSONANTS AND VOWELS IN THE GIVEN STRING
4. PROGRAM TO CHECK NO. IS PERFECT OR NOT.
5. PROGRAM TO CHECK NO. IS PALINDROME AND PERFECT NUMBER.
6. PROGRAM TO CHECK NO. IS PERFECT NUMBER.
7. PROGRAM TO FIND HAPPY NUMBER
8. PROGRAM TO CHECK GIVEN STRING IS PALINDROME.
9. PROGRAM FOR SORTING THE LIST FROM BUBBLE SORT.
10. PROGRAM FOR SORTING THE LIST USING INSERTION SORT.
11. PROGRAM FOR EMP DETAIL IN A TEXT FILE.
12. PROGRAM FOR WRITING DATA IN TEXT FILE.
13. PROGRAM FOR READING DISPLAYING THE DATA FROM BINARY FILE.
14. PROGRAM TO DISPLAY THE LIST IN REVERSE ORDER
15. PROGRAM FOR STORING THE EMP DETAIL IN BINARY FILE.
16. PROGRAM FOR READ DATA FROM CSV FILE.
17. PROGRAM TO SHOW PUSH AND POP OPERATION USING STACK.
18. PROGRAM TO ESTABLISH THE CONNECTION WITH MYSQL AND SHOW DATA.
19. MENU DERIVING PROGRAM WITH SQL CONNECTION.
20. SQL PROGRAM-1
21. SQL PROGRAM-2
22. SQL PROGRAM-3
23. SQL PROGRAM-4
24. SQL PROGRAM-5
PROGRAM TO CALCULATE FACTORIAL OF A NUMBER
def fact():
  fact=1
  if numb<0:
     print("FACTORIAL DOES NOT EXIST FOR NEGATIVE NUMBERS")
  elif numb==0:
     print("FACTORIAL OF 0 IS 1")
  else:
     for x in range(1,numb+1):
         fact=fact*x
  print("THE FACTORIAL OF",numb,"IS",fact)
numb=int(input("ENTER A NUMBER:"))
fact()
PROGRAM TO CHECK WHETHER THE GIVEN NUMBER IS PRIME OR
NOT
def isprime(number):
  if number<=1:
    return False
  for i in range(2,number):
    if number%i==0:
        return False
  return True
number = int(input("enter a number"))
if isprime(number):
  print("prime number")
else:
  print("not prime number")
PROGRAM TO FIND THE CONSONANTS AND VOWELS IN THE GIVEN
STRING
def count_vowels_consonants(s):
  vowels = "AEIOUaeiou"
  vowel_count = 0
  consonant_count = 0
  for char in s:
    if char.isalpha():
      if char in vowels:
         vowel_count += 1
      else:
         consonant_count += 1
  return vowel_count, consonant_count
a = input("enter a string")
print(count_vowels_consonants(a))
PROGRAM TO CHECK THE NUMBER IS PALINDROME OR NOT
def is_palindrome(number):
  return str(number) == str(number)[::-1]
number = int(input("Enter a number: "))
if is_palindrome(number):
  print("is a palindrome.")
else:
  oprint("is not a palindrome.")
PROGRAM TO CHECK GIVEN STRING IS PALINDROME
def palindrome():
  if stri==stri[ : :-1]:
    print("STRING IS PALINDROME")
  else:
    print("STRING IS NOT PALINDROME")
stri=input("ENTER A STRING")
palindrome()
PROGRAM TO FIND HAPPY NUMBER
def sum_of_squares(n):
  total = 0
  while n > 0:
    digit = n % 10
    total += digit ** 2
    n = n // 10
  return total
def is_happy_number(n):
  seen_numbers = []
  while n != 1 and n not in seen_numbers:
    seen_numbers.append(n)
    n = sum_of_squares(n)
  if n == 1:
    return True
  else:
    return False
num = int(input("Enter a number: "))
if is_happy_number(num):
  print(f"{num} is a Happy Number.")
else:
  print(f"{num} is not a Happy Number.")
PROGRAM FOR CHECKING NO. IS PERFECT OR NOT
def is_perfect(nu8r):
  sum_of_divisors = 0
  for i in range(1, number):
    if number % i == 0:
        sum_of_divisors += i
  return sum_of_divisors == number
number = int(input("Enter a number: "))
if is_perfect(number):
  print("is a perfect number.")
else:
  print("is not a perfect number.")
PROGRAM TO SORT LIST USING BUBBLE SORT
def bubble_sort(list_1):
  for i in range(0,len(list_1)-1):
    for j in range(len(list_1)-1):
       if(list_1[j]>list_1[j+1]):
         list_1[j],list_1[j+1]=list_1[j+1],list_1[j]
  return list_1
list_1=[100, 30, 10, 12, 45, 2, 7]
print("THE UNSORTED LIST IS:",list_1)
print("THE SORTED LIST IS:",bubble_sort(list_1))
PROGRAM TO SORT LIST USING INSERTION SORT
def insertionsort(list_1):
  n=len(list_1)
  for i in range(1, n):
    val= list_1[i]
    j = i-1
    while j >= 0 and val < list_1[j]:
       list_1[j+1]=list_1[j]
       j -= 1
    list_1[j+1] = val
  return(list_1)
list_1= [93,25,42,44,345,4]
print("THE UNSORTED LIST IS:",list_1)
print("THE SORTED LIST IS:",insertionsort(list_1))
PROGRAM TO WRITE SOME DATA IN TEXT FILE
fin=open("student.txt","w")
for i in range(3):
  studentname=input("enter name of student")
  fin.write(studentname)
  fin.write("\n")
fin.close()
PROGRAM TO TAKE EMPLOYEE DETAILS AND STORES IT IN A TEXT
FILE
file1 = open("empdata.txt","w")
count = int(input("how many employee:"))
for i in range(count):
  print("enter the deatis of employee", (i+1),"below:")
  emp_id = input("enter the emp id")
  emp_name = input("enter employee name")
  designation = input("enter the designation")
  salary = int(input("enter the salary"))
  rec = emp_id+","+emp_name+","+designation+","+str(salary)+'\n'
  file1.write(rec)
file1.close()
ADDING MORE DATA TO BINARY FILE
import pickle
def add_data():
  f_1=open("student.dat","ab")
  r_no=int(input("ROLL NUMBER"))
  stu_name=input("STUDENT NAME")
  stu_add=input("STUDENT ADDRESS")
  print("DATA ADDED SUCCESSFULLY")
  rec=[r_no,stu_name,stu_add]
  pickle.dump(rec,f_1)
  f_1.close()
add_data()
PROGRAM TO DISPLAY THE LIST IN REVERSE ORDER
import pickle
Names = ['first' , 'second','third','fourth','fifth']
lst = []
for i in range (-1,-5,-1):
  lst.append(Names[i])
with open('test.dat','wb')as fout:
   pickle.dump(lst,fout)
with open('test.dat','rb')as fin:
   nlist = pickle.load(fin)
print(nlist)
CREATING CSV FILE
import csv
f=open("student.csv","w")
stuwriter=csv.writer(f)
stuwriter.writerow(["ROLL NO.","NAME","MARKS"])
n=int(input("enter no. of student record to be added"))
for i in range (n):
  print("STUDENT RECORD",(i+1))
  rollno=int(input("enter roll no.:"))
  name=input("enter name:")
  marks=float(input("enter marks:"))
  sturec=[rollno,name,marks]
  stuwriter.writerow(sturec)
f.close()
PROGRAM TO WRITE, READ AND SEARCH IN CSV FILE
import csv
def write():
  f=open("item.csv","w",newline="")
  s_writer=csv.writer(f)
  s_writer.writerow(["item no.","item name","quantity","price"])
  rec=[]
  while True:
    n=int(input("item no."))
    name=input("item name")
    quantity=int(input("quantity"))
    price=int(input("price"))
    rec.append([n,name,quantity,price])
    ch=input("do you continue Y/N")
    if ch=="n":
       break
  for i in rec:
    s_writer.writerow(i)
  print("DATA ADDED SUCCESSFUL")
  f.close()
def read():
  f= open("item.csv","r")
  print("reading csv file")
  s_reader=csv.reader(f)
  for i in s_reader:
    print(i)
  f.close()
def search():
  f=open("item.csv","r")
  print("seaching data")
  s=input("enter item no.")
  s_reader=csv.reader(f)
  found=0
  for i in s_reader:
    if i[0]==s:
         print(i[1:])
         found=1
  if found==0:
    print("no record")
  f.close()
write()
read()
search()
STACK IMPLEMENTATION
s = []
top = None
def isempty(stk):
    if(stk==[]):return True
    else:return False
def push(stk,item):
    global top
    i = stk.append(item)
    top = len(stk)-1
def pop(stk):
    global top
    if(isempty(stk)):return("underflow")
    else:a = stk.pop()
    if(len(stk)==0):top = None
    else:top = len(stk)-1
    return a
def peek(stk):
  global top
  if top ==None:print("there is no value to peek")
  if(isempty(stk)):return("underflow")
  else: top = len(stk)-1
  return stk[top]
def display(stk):
  global top
  if(isempty(stk)):print("underflow")
  else:
    top = len(stk)-1
    print(stk[top],"<---top")
    for i in range(top-1,-1,-1):
       print(stk[i])
# #MAIN_PROGRAM_
print("stack implementation")
while True :
 print("1:Push")
 print("2:Pop")
 print("3:Peek")
 print("4:Display")
 print("5:Exit")
 ch = int(input("enter your choice for stack operation"))
 if ch==1:
   item = int(input("enter the item you want to add"))
   push(s,item)
   print("sussesfully added item to the stack")
   input("press any key to continue")
 elif ch == 2:
   a = pop(s)
   if a=="underflow":
      print("underflow!Error")
   else:
    print("pop value is:",a)
   input("press any key to continue:")
 elif ch == 3:
   a = peek(s)
   if a=="underflow":
    print("underflow!Error")
   else:
      print(a)
   input("press any key to continue")
 elif ch == 4:
   display(s)
   input("press any key to continue")
 elif ch == 5:
   print("program is going to exit now do you want to continue yes
or no")
   con = input()
   if con=="yes":break
   else:input("press any key to continue:")
 else:
   print("invalid input")
2.
Novowel = []
vowels = "AEIOUaeiou"
def PushNV(N):
     for word in N:
       voweltest = False
       for letter in word:
         if letter in vowels:
           voweltest = True
           break
     if not voweltest:
           Novowel.append(word)
All = []
for i in range(5):
  w = input("Enter a word: ")
  All.append(w)
PushNV(All)
if len(Novowel) == 0:
  print("Empty Stack")
else:
  while len(Novowel) != 0:
     print(Novowel.pop(), " ", end=' ')
  print()
1 . PROGRAM TO ESTABLISH CONNECTION WITH MYSQL AND
SHOW DATA
import mysql.connector as dh
myconnector = dh.connect(host = "localhost" , user = "root",passwd = "dhruv",database =
"dhruv")
if myconnector.is_connected():
  print("succesfully connected to mysql database")
mycursor = myconnector.cursor()
mycursor.execute("select*from product")
myrec = mycursor.fetchall()
for i in myrec:
  print (i)
2.
import mysql.connector as dh
myconnector = dh.connect(host = "localhost" , user = "root",passwd = "dhruv",database =
"product")
if myconnector.is_connected():
  print("succesfully connected to mysql database")
mycursor = myconnector.cursor()
mycursor.execute("select*from company")
myrec = mycursor.fetchall()
for i in myrec:
  print (i)
Sql Programs
Q1. In a database, there are two tables given below. Write SQL
command for the statements 1 to 4 and give the outputs also:
Table : EMPLOYEE
Table : JOB
       JOBID          JOBTITLE                SALARY
       101            President               200000
       102            Vice President          125000
       103            Administration Assistant 80000
       104            Accounting Manager      70000
       105            Accountant              65000
       106            Sales Manager           80000
       EMPLOYEEID      NAME                SALES       JOBID
       E1              Sumit sinha         1100000     102
       E2              Vijay singh tomar   1300000     101
       E3              Ajay rajpal         1400000     103
       E4              Mohit ramnani       1250000     102
       E5              Shailja singh       1450000     102
Creating the table:
Inserting values into table:
1. To display employee ids, names of employees, job ids with
   corresponding job titles.
2. To display names of employees, sales and corresponding job titles
   who have achieved sales more than 1300000.
3. To display names and corresponding job titles of those employees
   who have ‘SINGH’(anywhere) in their names.
4. Identify foreign key in the table Employee.
Job_id
5. Write SQL command to change the JOBID to 104 of the employee
   with ID as E4 in the table ‘EMPLOYEE’.
Q2. With reference to following relations PERSONAL and JOB answer
the questions that follow: Create following tables such that Empno
and Sno are not null and unique, date of birth is after “12-jan-1960”,
name is never blank, Area and Native place is valid, hobby, dept is
not empty, salary is between 4000 and 10000.
Table : PERSONAL
  Empno       Name         Dobirth        Native place Hobby
  123         Amit         23-jan-        Delhi        Music
                           1965
  127         Manoj        12-dec-        Mumbai       Writing
                           1976
  124         Abhai        11-aug-        Allahabad    Music
                           1975
  125         Vinod        04-apr-        Delhi        Sports
                           1977
  128         Abhay        10-mar-        Mumbai       Gardening
                           1974
  129         Ramesh       28-oct-        Pune         Sports
                           1981
Table : JOB
  Sno     area        App_date   salary      Retd_date dept
  123     Agra        25-jan-    5000        25-jan-    Marketing
                      2006                   2026
  127     Mathura     22-dec-    6000        22-dec-    Finance
                      2006                   2026
  124     Agra        19-aug-    5500        19-aug-    Marketing
                      2007                   2027
  125     Delhi       14-apr-    8500        14-apr-    Sales
                      2004                   2018
  128      Pune        13-mar-   7500   13-mar-   Sales
                       2008             2028
Creating the table:
Inserting values in table:
1. Show Empno, Name and Salary of those who have Sports as
   hobby.
2. Show name of the eldest employee.
3. Show number of employees area wise.
4. Show youngest employee from each native place.
5. Show Sno, Name, Hobby and salary in descending order of salary.
6. Show the hobbies of those whose name pronounces as “Abhay”.
7. Show the appointment date and native place of those whose
   name starts with ‘A’ or ends with ‘d’.
8. Show the salary expense with suitable column heading of those
   who shall retire after 20-jan-2006.
9. Show additional burden on the company in case of salary of
   employees having hobby as sports, is increased by 10%.
10. Show the hobby of which there are 2 or more employees.
11. Show how many employee shall retire today if maximum length
  of service is 20 years.
12. Show those employee name and date of birth who have served
  more than 17 years as on date.
13. Show names of those who earn more than all of the employees
  of sales dept.
14. Increase salary of the employees by 5% of their present salary
  with hobby as music or they have completed atleast 3 years of
  service.
15. Write the output of :
  (a)   Select distinct hobby from personal;
  (b)   Select avg(salary) from personal, job where empno=sno and
        area in (‘Agra’, ‘Delhi’);
  (c)   Select count(distinct native_place) from personal;
  (d)   Select name, max(salary) from personal, job where
        empno=sno;
16. Add a new tuple in the table personal essentially with hobby as
  Music.
17. Insert a new column email in job table.
18. Create a new table with values of columns empno, name and
  hobby.
19. Create a view of personal and job details of those who have
  served less than 15 years.
20. Erase the records of employee from job table whose hobby is
  not sports.
21. Remove the table personal.
Q3. Consider the following tables Employee and Salary. Write SQL
commands for the statements 1. to 4. and give outputs for sql
queries 5. to 7.
Table : EMPLOYEE
    Eid       Name          Depid        Qualification   Sec
    1         Deepali       101          MCA             F
              gupta
    2         Rajat tyagi   101          BCA             M
    3         Hari mohan    102          B.A.            M
    4         Harry         102          M.A.            M
    5         Sumit mittal 103           B.Tech.         M
    6         Jyoti         101          M.Tech.         F
Table : SALARY
        Eid      Basic       D.A.           HRA           Bonus
        1        6000        2000           2300          200
        2        2000        300            300           30
        3        1000        300            300           40
        4        1500        390            490           30
        5        8000        900            900           80
        6        10000       300            490           89
Creating the table :
Inserting the values :
  1. To display the frequency of employees department wise.
2. To list the names of those employees only whose name starts
   with ‘H’.
3. To add a new column in salary table. The column name is
   Total_sal.
4. To store the corresponding values in the Total_sal column.
5. Select max(basic) from salary where bonus>40;
6. Select count(*) from employee group by sec;
  7. Select distinct depid from employee;
Q4. Given the following tables for a database LIBRARY :
Table : BOOKS
Book_i Book_nam        Author_na      Publishe   Pric Type       Qty
d      e               me             rs         e               .
C001      Fast Cook    Lata Kapoor    EPB        355      Cooker 5
                                                          y
F001      The Tears    William        First      650      Fiction 20
                       Hopkins        publ.
T001      My first     Brain &        EPB        350      Text   10
          C++          Brooke
T002      C++          A.W.Rossain TDH           350      Text   15
          brainworks   e
F002      Thunderbol Anna             Fierst     750      Fiction 50
          ts         Roberts          publ.
Table : ISSUED
                   Book_Id              Quantity_Issued
                   T001                 4
                   C001                 5
                   F001                 2
Creating the table :
Inserting values in table :
1. To show book name, author name and price of books of first publ.
   publishers.
2. To list the names from books of text type.
3. To display the names and price from books in acsending order of
   their price.
4. To increase the price of all books of EPG publisher by 50.
5. To display the books_id, books_name and quantity_issued for all
   books which have been issued.
6. To insert a new row in the table issued having the following data:
   “F003”,1.
7. Give the outputs of the following queries:
  (a)   Select count(*) from books;
(b)   Select max(price) from books where quantity>=15;
(c)   Select book_name, author_name from books where
      publishers= “EPB”.
(d)   Select count(distinct publishers) from books where
      price>=400;
Q5. Consider the following DEPT and WORKER tables. Write SQL
queries from 1. to 4. and write outputs from 5. To 8.
Table : DEPT
    DCODE                   DEPARTMENT         CITY
    D01                     MEDIA              DELHI
    D02                     MARKETING          DELHI
    D03                     INFRASTRUCTURE     MUMBAI
    D05                     FINANCE            KOLKATA
    D04                     HUMAN RESOURCE     MUMBAI
Table : WORKER
    WNO        NAME           DOJ        DOB          GENDER   DCODE
    1001       Geoge K        2013-09-02 1991-09-01 Male       D01
    1002       Ryma Sen       2012-12-11 1990-12-15 Female     D03
    1003       Mohitesh       2013-02-03 1987-09-04 Male       D05
    1007       Anil Jha       2014-01-17 1984-10-19 Male       D04
    1004       Manila         2012-12-09 1986-11-14 Female     D01
               Sahai
    1005       R Sahay        2013-11-18 1987-03-31 Male       D02
    1006       Jaya Priya     2014-06-09 1985-06-23 Female     D05
Creating the table :
Inserting values in table :
1. To display wno, name, gender from the table worker in
   descending order of wno.
2. To display the name of all the female workers from the table
   worker .
3. To display the wno and name of those workers from the table
   worker who are born between “1987-01-01” and “1991-12-01”.
4. To count and display male workers who have joined after “1986-
   01-01”.
5. Select count(*), dcode from workers group by dcode having
   count(*)>1;
6. Select distinct department from dept;
7. Select name, department, city from worker w, dept d where
   w.dcode=d.dcode and wno<1003;
8. Select max(doj), min(dob) from worker;
Bibliography
1. Sumita Arora, Computer Science with
Python.
2. Google, www.google.com.