Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

CS Practical File

file for cs
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

CS Practical File

file for cs
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

ST.

XAVIER’S SCHOOL, SILVASSA

Academic Year: 2024-2025

PRACTICAL FILE
-----------------------------------------------------------------------------------
Roll No :

Name : Yash Karansinh Thakor

Class : XIIth

Subject : COMPUTER SCIENCE

Subject Code : 083

Project Guide : Mrs. Preetinder Kaur Bedi


(Computer Science)
ST. XAVIER’S SCHOOL, SILVASSA

CERTIFICATE

This is to certify that Cadet Yash Karansinh Thakor, Roll No: _________
has successfully completed the Practical File in the subject Computer
Science (083) laid down in the regulations of CBSE for the purpose of
Practical Examination in Class XII to be held in St. Xavier’s School,
Silvassa.

Mrs. Pree nder Kaur Bedi


MCA

Examiner: Principal:
Name: _______________ Name: ______________

Signature: Signature:
ACKNOWLEDGEMENT
Apart from the efforts of me, the success of any project depends largely on the
encouragement and guidelines of many others. I take this opportunity to express my
gratitude to the people who have been instrumental in the successful completion of this
project.

I express a deep sense of gratitude to the almighty God for giving me strength for the
successful completion of the project.

I express my heartfelt gratitude to my parents for constant encouragement while


carrying out this project.

I gratefully acknowledge the contribution of the individuals who contributed in


bringing this project up to this level, who continues to look after me despite my flaws.

I express my sincere thanks to the academician The Principal of St. Xavier’s School,
Silvassa who has been continuously motivating and extending their helping hand to us and
for constant encouragement and the guidance provided during this project.

I am overwhelmed to express my thanks to The Administrative Officer for


providing me an infrastructure and moral support while carrying out this project in the
school.

My sincere thanks to Mrs. Preetinder Kaur Bedi, Master in-charge, a guide, a


mentor, and all the above, a friend, who critically reviewed my project and helped in
solving each and every problem, occurred during implementation of the project.

The guidance and support received from all the members who contributed and who
are contributing to this project, was vital for the success of the project. I am grateful for
their constant support and help.
INDEX

No. Particulars Date Tr. Sign

1. Program to enter two numbers and print the


arithmetic operations like +, -, *, /, // and %.

2. Write a program to find whether an inputted number is


perfect or not.

3. Write a Program to check if the entered number is


Armstrong or not.

4. Write a Program to find the factorial of the entered


number.

5. Write a Program to enter the number of terms and to


print the Fibonacci Series.

6. Write a Program to enter the string and to check if


it’s palindrome or not using a loop.

7. Write a random number generator that generates


random numbers between 1 and 6 (simulates a dice)
8. Write a program that generates a series using a function
while takes first and last values of the series and then
generates four terms that are equidistant e.g., if two
number passed are 1 and 7 then function returns 1 3 5 7.

9. Write a Python program using a function to print factorial


number series from n to m numbers.

10. Write a Python program to demonstrate the concept of


variable length argument to calculate the product and
power of the first 10 numbers.

Write a Python program to accept the username


11. “Admin” as the default argument and password 123
entered by the user to allow login into the system.

12. Read a text file line by line and display each word
separated by #.

Read a text file and display the number of


13. vowels/consonants/uppercase/lowercase characters in
the file.

14. Remove all the lines that contain the character a’ in a file
and write it to another file.

Create a binary file with name and roll number. Search


15. for a given roll number and display the name, if not found
display appropriate message.
16. Create a binary file with roll number, name and marks.
Input a roll number and update the marks.

17. Create a CSV file by entering user-id and password, read


and search the password for given user-id.

18. Write a menu-driven python program to implement


stack operation.

19. Take a sample of ten phishing e-mails (or any text file)
and find most commonly occurring words.

20. Write a Python program to accept a list as a function


parameter and raise the Index Error exception.

Write a program to accept the number of days and


21. display appropriate weeks in an integer. Display an
appropriate error message through multiple exception
handling including the finally clause.

Create a student table and insert data. Implement the


following SQL commands on the student table:
• ALTER table to add new attributes / modify data type
drop attribute.
• UPDATE table to modify data.
• ORDER BY to display data in ascending / descending
22. order.
• DELETE to remove tuple(s).
• GROUP BY and find the min, max, sum, count and
average.
23. Integrate SQL with Python by importing the MySQL
module

Write a program to connect Python with MySQL


24. using database connectivity and perform the
following operations on data in database: Fetch,
Update and delete the data
Program 1:
Program to enter two numbers and print the arithmetic operations like +, -, *, /, // and %.

Code:

a1 = int(input("Enter first number:"))


b2 = int(input("Enter second number:"))
add = a1+b2
dif = a1-b2
mul = a1*b2
div = a1/b2
floor_div = a1//b2
power = a1**b2
modulus = a1 % b2
print('Sum of', a1, 'and', b2, 'is:', add)
print('Difference of',a1, 'and', b2, 'is', dif)
print('Product of', a1, 'and', b2, 'is:', mul)
print('Division of',a1, 'and', b2, 'is:',div)
print('Floor Division of', a1, 'and', b2, 'is', floor_div)
print('Exponent of',a1, 'and', b2, 'is:',power)
print('Modulus of', a1, 'and', b2, 'is:', modulus)

Output:
Program 2:
Write a program to find whether an inputted number is perfect or not.

Code:

x = int(input("Enter a number: "))


sum = 0
for i in range(1, x):
if x % i == 0:
sum += i
if sum == x:
print(x, "is a perfect number.")
else:
print(x, "is not a perfect number.")

Output:
Program 3:
Write a Program to check if the entered number is Armstrong or not.

Code:

p = int(input("Enter any number: "))


q = p
sum = 0
while (p > 0):
ans = p % 10
sum = sum + (ans*ans*ans)
p = int(p/10)
if sum == q:
print("It is an Armstrong Number.")
else:
print("It is not an Armstrong Number.")

Output:
Program 4:
Write a Program to find the factorial of the entered number.

Code:

n = int(input("Enter the number to find its factorial: "))


g = 1
h = 1
while h<=n:
g = g * h
h = h + 1
print("Factorial of", n, "=",g)

Output:
Program 5:
Write a Program to enter the number of terms and to print the Fibonacci Series.

Code:

nterms = int(input("How many terms: "))


a, b = 0,1
cnt = 0
if nterms<=0:
print("Please enter a positive integer.")
elif nterms==1:
print("Fibonacci sequence upto", nterms,":")
print (a)
else:
print("Fibonacci sequence: ")
while cnt < nterms:
print(a)
nth=a+b
a=b
b=nth
cnt+=1

Output:
Program 6:
Write a Program to enter the string and to check if it’s palindrome or not using a loop.

Code:

def palindrome(str):
for j in range(0, int (len(str)/2)):
if str[j] != str[len(str)-j-1]:
return False
return True
s = input("Enter a string:")
answer = palindrome(s)
if(answer):
print("Yes, it is a palindrome.")
else:
print("No, it is not a palindrome.")

Output:
Program 7:
Write a random number generator that generates random numbers between 1 and 6 (simulates a dice)

Code:

import random
min = 1
max = 6
roll_dice_again = "y"
while roll_dice_again == "y" or roll_dice_again == "Y":
print("Rolling the dice...")
value = random.randint (min, max)
print("You got...", value)
roll_dice_again = input("Roll the dice again? (y/n): ")

Output:
Program 8:
Write a program that generates a series using a function while takes first and last values of the series
and then generates four terms that are equidistant e.g., if two number passed are 1 and 7 then
function returns 1-3-5-7.

Code:

def series(a,b):
d = int((b-a)/3)
print("Series is =",a,a+d,a+2*d,b)

first = int(input("Enter the starting term: "))


last = int(input("Enter the ending term: "))
series(first, last)

Output:
Program 9:
Write a Python program using a function to print factorial number series from n to m numbers.

Code:

def factorial(n):
return 1 if (n==1 or n==0) else n * factorial(n - 1);
num = int(input("Enter a number: "))
print("Factorial of", num, "is", factorial(num))

Output:
Program 10:
Write a Python program to demonstrate the concept of variable length argument to calculate the
product and power of the first 10 numbers.

Code:

def calculate(op, *args):


result = 1
if op == "Product":
for number in args:
result *= number
elif op == "Power":
for number in args:
result = result**number
return result
print(calculate("Product",4,6,2,7,1,2,6,9,2,3))
print(calculate("Power",4,6,2,7,1,2,6,9,2,3))

Output:
Program 11:
Write a Python program to accept the username “Admin” as the default argument and password 123
entered by the user to allow login into the system.

Code:

def user_pw(pw, username = "Admin"):


if pw == '123':
print("You have logged into the system.")
else:
print("Password is incorrect!")

pw = input("Enter the password: ")


user_pw(pw)

Output:
Program 12:
Read a text file line by line and display each word separated by #.

Code:

f = open("file1.txt")
for x in f:
words =x.split()
for w in words:
print(w + '#', end= "")
print()
f.close()

TXT File:

Output:
Program 13:
Read a text file and display the number of vowels/consonants/uppercase/lowercase characters in the
file.

Code:

f = open("file2.txt")
v = 0
c = 0
u = 0
l = 0
o = 0
d = f.read()
vowels = ['a','e', 'i', 'o', 'u']
for ch in d:
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:", c)
print("Total capital letters in file:", u)
print("Total small letters in file:", l)
print("Total other than letters in file:", o)
f.close()
TXT File:

Output:
Program 14:
Remove all the lines that contain the character ‘a’ in a file and write it to another file.

Code:

def Remove():
oldf = open("oldfile.txt","r")
newf = open("newfile.txt", "w")
L = []
lines = oldf.readlines ()
for line in lines:
if 'a' in line:
newf.write(line)
else:
L.append(line)
oldf = open("oldfile.txt", "w")
oldf.writelines(L)
oldf.close()
newf.close()
print("File copied successfully.")
Remove()

Old TXT File:


Output:

Old TXT File after running code:

New TXT File after running code:


Program 15:
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.

Code:

import pickle
def write():
D={}
f = open("studentdetails.dat", "wb")
while True:
r = int(input("Enter Roll no:"))
n = input("Enter Name:")
D['Roll No'] = r
D['Name'] = n
pickle.dump(D, f)
ch = input("Do you want to enter more records (Y/N): ")
if ch in 'Nn':
break
f.close()
def search():
found = 0
rollno = int(input("Enter Roll No whose name you want to display:"))
f = open("studentdetails.dat","rb")
try:
while True:
rec = pickle.load(f)
if rec ['Roll No'] == rollno:
print(rec["Name"])
found = 1
break
except EOFError:
f.close()
if found == 0:
print("Sorry not found...")
print("Sorry not found...")
f.close()

write()
search ()

Output:
Program 16:
Create a binary file with roll number, name and marks. Input a roll number and update the marks.

Code:

import pickle
def Write():
f=open('studentdetails.dat', 'wb')
while True:
r=int(input("Enter Roll Number: "))
n=input("Enter Name: ")
m = int(input("Enter Marks: "))
record=[r,n,m]
pickle.dump(record, f)
ch=input("Do you want to enter more records (Y/N): ")
if ch in 'Nn':
break
f.close()

def Read():
f=open('studentdetails.dat','rb')
try:
while True:
rec=pickle.load(f)
print (rec)
except EOFError:
f.close()

def Update():
f=open('studentdetails.dat','rb+')
rollno=int(input("Enter Roll no whose marks you want to update: "))
try:
while True:
pos=f.tell()
rec=pickle.load(f)
if rec[0]==rollno:
um = int(input("Enter Updated Marks: "))
rec [2]=um
f.seek(pos)
pickle.dump(rec, f)
except EOFError:
f.close()

Write ()
Read()
Update()
Read()

Output:
Program 17
Create a CSV file by entering user-id and password, read and search the password for given user-id.

PART 1 - #TO WRITE AND READ


Code:

#to write and read


import csv
def write():
f = open("details.csv", "w", newline = '')
wo = csv.writer(f)
wo.writerow(["UserId", "Password"])
while True:
u_id=input("Enter UserId: ")
pw=input("Enter Password: ")
data=[u_id,pw]
wo.writerow(data)
ch = input("Do you want to enter more records (Y/N): ")
if ch in 'Nn':
break
f.close()

def read():
f = open("details.csv", "r")
ro = csv.reader (f)
for i in ro:
print(i)
f.close()

write()
read()
Output:

Output in Excel:
PART 2 – TO SEARCH THE USER
Code:

#to search the user


import csv
def write():
f = open("details.csv","w", newline = '')
wo = csv.writer (f)
wo.writerow(["UserId", "Password"])
while True:
u_id=input("Enter UserId:")
pw = input("Enter Password:")
data = [u_id,pw]
wo.writerow(data)
ch = input("Do you want to enter more records (Y/N):")
if ch in 'Nn':
break
f.close()

def read():
f = open("details.csv","r")
ro = csv.reader (f)
for i in ro:
print(i)
f.close()

def search():
f = open("details.csv","r")
u = input("Enter UserId to search:")
ro = csv.reader(f)
for i in ro:
if i[0] == u:
print(i[1])
f.close()
write()
read()
search ()

Output:

Output in Excel:
PART 3 – TO CHECK IF USER FOUND OR NOT
Code:

#to check if user found or not


import csv
def write():
f = open ("details.csv", "w", newline = '')
wo = csv.writer(f)
wo.writerow(["UserId", "Password"])
while True:
u_id=input("Enter UserId: ")
pw = input("Enter Password: ")
data=[u_id, pw]
wo.writerow(data)
ch = input("Do you want to enter more records (Y/N): ")
if ch in 'Nn':
break
f.close()

def read():
f = open("details.csv","r")
ro = csv.reader(f)
for i in ro:
print(i)
f.close()

def search():
f = open("details.csv","r")
Found = 0
u = input("Enter UserId to search: ")
ro = csv.reader(f)
next(ro)
for i in ro:
if i[0] == u:
print(i[1])
Found = 1
if Found == 0:
print("Sorry, no record found.")
f.close()

read()
search()

Output (if found):

Output (if not found):


Program 18:
Write a menu-driven python program to implement stack operation.

Code:

def isEmpty(stk):
if stk==[]:
return True
else:
return False

def add(stk,item):
stk.append(item)
top = len(stk)-1

def remove (stk):


if (stk==[]):
print("Stack empty; Underflow")
else:
print("Deleted student is:", stk.pop())

def display (stk):


if isEmpty (stk):
print("Stack empty")
else:
top = len(stk) -1
print(stk[top], "<-top")
for a in range (top-1,-1,-1):
print(stk[a])

stack = []
top = None
while True:
print("STACK OPERATION:")
print("1.Add student")
print("2.Display stack")
print("3.Remove student")
print("4.Exit")
ch=int(input("Enter your choice (1-4): "))
if ch==1:
rno=int(input("Enter Roll no to be inserted: "))
sname=(input("Enter Student name to be inserted: "))
item=[rno, sname]
add (stack, item)
input()
elif ch==2:
display (stack)
input()
elif ch==3:
remove (stack)
input()
elif ch==4:
break
else:
print("Invalid choice")
input()

Output (inserting students):

Output Continued (P.T.O)


Output (displaying stack):

Output (removing from stack):

Output Continued (P.T.O)


Output (displaying stack after removing one student from stack):

Output (upon exiting):


Program 19:
Take a sample of ten phishing e-mails (or any text file) and find most commonly occurring words.

Code:

phishingemail = ["hellouser@snapdeal.com",
"luckywinner@lottery.com",
"jackpot@flipkart.com",
"claimtheprize@snapdeal.com",
"youwon@money.com",
"spinthewheel@mymoney.com"
"hellouser@lottery.com",
"scratchthegift@amazon.com"
"dealwinner@snapdeal.com",
"luckyjackpot@myntra.com"]

d={}
for x in phishingemail:
i=x.split('@')
for a in i:
if a not in d:
d[a]=1
else:
d[a]+=1

maxw = max(d,key=d.get)
print("Most Common Occuring Word is:", maxw)

Output:
Program 20:
Write a Python program to accept a list as a function parameter and raise the Index Error exception.

Code:

list1 = ["Yash", "Sujal", "Lokesh"]


x = list1[3]
print(x)

Output:
Program 21:
Write a program to accept the number of days and display appropriate weeks in an integer. Display an
appropriate error message through multiple exception handling including the finally clause.

Code:
print("Handling exception using try, except, else & finally.")
try:
day= int(input("Enter a number 1-7: "))
if (day==1):
print(day," is Sunday")
elif (day==2):
print (day," is Monday")
elif (day==3):
print(day," is Tuesday")
elif (day==4):
print(day," is Wednesday")
elif (day==5):
print(day," is Thursday")
elif (day==6):
print(day," is Friday")
elif (day==7):
print(day," is Saturday")
else:
print("Wrong input.")
except:
print("Only numbers are to be entered.")
finally:
print("End of program.")

Output:

&
Program 22:

Create a student table and insert data. Implement the following SQL commands on the student table:

• ALTER table to add new attributes / modify data type / drop attribute.

• UPDATE table to modify data.

•ORDER By to display data in ascending / descending order.

• DELETE to remove tuple(s).

• GROUP BY and find the min, max, sum, count and average.

Code:

Output Continued P.T.O.


ALTER table to add new attribute:
ALTER table to modify data type:

ALTER table to drop attribute:

UPDATE table to modify data:


ORDER BY to display data in ascending order:

ORDER BY to display data in descending order:

DELETE to remove tuple/row:


TABLE 2: “stud_marks”
GROUP BY min:

GROUP BY max:

GROUP BY average:

GROUP BY sum:

GROUP BY count:
Program 23:
Integrate SQL with Python by importing the MySQL module.

Code for Command Prompt:

pip install mysql-connector-python

Code for establishing connection in Python:

import mysql.connector as msc


mydb = msc.connect(host = 'localhost', password = 'yash2007', user =
'root')

if mydb.is_connected():
print("Connection is established.")

Output:
Program 24:
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

Code in MySQL:

Code:

import mysql.connector as msc


mydb = msc.connect(host = 'localhost', password = 'yash2007', user =
'root')
cursor = mydb.cursor()
cursor.execute('show databases')

for i in cursor:
print(i)

Output:
> Table already existing in MySQL:

Code for Python to do fetchone() function:


import mysql.connector as msc
mydb = msc.connect(host = 'localhost', password = 'yash2007', user =
'root', database = 'cs_pr_file')
cursor = mydb.cursor()
cursor.execute('select * from stud_marks')
records = cursor.fetchone()
no_rec = cursor.rowcount
print("Total no. of records found in DB are:", no_rec)
print(records)
print('-------------------------------')
records = cursor.fetchone()
no_rec = cursor.rowcount
print("Total no. of records found in DB are:", no_rec)
print(records)

Output:
Code for Python to do fetchmany(size) function:
import mysql.connector as msc
mydb = msc.connect(host = 'localhost', password = 'yash2007',
user = 'root', database = 'cs_pr_file')
cursor = mydb.cursor()
cursor.execute('select * from stud_marks')
records = cursor.fetchmany(5)
no_rec = cursor.rowcount
print("Total no. of records found in DB are:", no_rec)

for i in records:
print(i)

Output:
Code for Python to do fetchall() function:
import mysql.connector as msc
mydb = msc.connect(host = 'localhost', password = 'yash2007',
user = 'root', database = 'cs_pr_file')
cursor = mydb.cursor()
cursor.execute('select * from stud_marks')
records = cursor.fetchall()
no_rec = cursor.rowcount
print("Total no. of records found in DB are:", no_rec)

for i in records:
print(i)

Output:

You might also like