0% found this document useful (0 votes)
77 views39 pages

Sample Project File (CS) (LACE FILE)

Uploaded by

ZACK & CYRUS
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views39 pages

Sample Project File (CS) (LACE FILE)

Uploaded by

ZACK & CYRUS
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

COMPUTER SCIENCE PRACTICAL FILE

SUBJECT CODE-083
CLASS-XII(COMPUTER SCIENCE)
SESSION-2022-23

Q1. Write a program in python to check a number whether it is prime or not.


Source Code
num=int(input("Enter the number: "))
for i in range(2,num):
if num%i==0:
print(num, "is not prime number")
break
else:
print(num,"is prime number")
break
output-
2. Write a program to check a number whether it is palindrome or not.

Source Code-
num=int(input("Enter a number : "))
n=num
res=0
while num>0:
rem=num%10
res=rem+res*10
num=num//10

if res==n:
print("number is palindrome")
else:
print("Number is not Palindrome")
output-
3. Write a program to calculate compound interest.

Source Code-
p=float(input("Enter the principal amount : "))
r=float(input("Enter the rate of interest : "))
t=float(input("Enter the time in years : "))
x=(1+r/100)**t
CI= p*x-p
print("Compound interest is : ", round(CI,2))

Output-
4. Write a program to display ASCII code of a character and vice versa.

Source Code-
var=True
while var:
choice=int(input("Press-1 to find the ordinal value of a character \nPress-2 to find a
character of a value\n"))
if choice==1:
ch=input("Enter a character : ")
print(ord(ch))
elif choice==2:
val=int(input("Enter an integer value: "))
print(chr(val))
else:
print("You entered wrong choice")
print("Do you want to continue? Y/N")
option=input()
if option=='y' or option=='Y':
var=True
else:
var=False

Output-
5. Write a program to input a character and to print whether a given character is an
alphabet, digit or any other character.
Source Code-

ch=input("Enter a character: ")


if ch.isalpha():
print(ch, "is an alphabet")
elif ch.isdigit():
print(ch, "is a digit")
elif ch.isalnum():
print(ch, "is alphabet and numeric")
else:
print(ch, "is a special symbol")
Output-

6. write a python program to create a binary file with roll no, name, marks. Display the binary file.

Source code-

import pickle
def new1():
f=open("stu.dat",'wb+')
n=int(input("how many records you want to enter"))
while n:
rec=[]
roll=input("Enter roll")
rec.append(roll)
name=input("Enter name")
rec.append(name)
marks=int(input("enter marks"))
rec.append(marks)
pickle.dump(rec,f)
n=n-1
f.close()

def read1():
f=open("stu.dat",'rb')
try:
while True:
rec=pickle.load(f)
print(rec)
except EOFError:
pass
f.close()

new1()
print("the reacords are")
read1()

The view of binary file-


Output-

7. Write a program to generate random numbers between 1 to 6 and check whether


a user won a lottery or not.

Source code-

import random
n=random.randint(1,6)
guess=int(input("Enter a number between 1 to 6 :"))
if n==guess:
print("Congratulations, You won the lottery ")
else:
print("Sorry, Try again, The lucky number was : ", n)

Output-
Q8. Write a program to import data between csv file and pandas with practical
example.
Source code-
import pandas as pd

data = pd.read_csv ('Cars_Data.csv')


df = pd.DataFrame(data, columns= ['brand','body-style','wheel-base','length','engine-type','num-of-
cylinders','horsepower','mileage','price'])
print (df)

The view of Car_Data csv file


Output-

Q9. Write a program to export data between dataframe and csv with practical example.
Source code-

import pandas as pd
import numpy as np
marks = { "English" :[67,89,90,55],
"Maths": [55,67,45,56],
"IP": [66,78,89,90],
"Chemistry”: [45,56,67,65],
"Biology": [54,65,76,87]}
result = pd.DataFrame(marks,index=["Athang","Sujata","Sushil","Sumedh"])
print("******************Marksheet****************")
print(result)
result.to_csv("result.csv")

The view of result csv file.

Output-
Q10.Write a python program to remove all the lines that contain the character a in a file and write it into another file
Source code-
fo=open("hp.txt","w")
fo.write("Harry Potter")
fo.write("There is a difference in all harry potter books\nWe can see it as harry grows\nthe books were written by J.K rowling ")
fo.close()

fo=open('hp.txt','r')
fi=open('writehp.txt','w')
l=fo.readlines()
for i in l:
if 'a' in i:
i=i.replace('a','')
fi.write(i)
fi.close()
fo.close()

Output-
The view of hp text file-

The view of writehp text file


Q11.Write a python program to Read a text file and display the number of vowels/consonants/uppercase/
lowercase characters in the text file.

Source code-
def cnt():
f=open("D:\\test2.txt","r")
cont=f.read()
print(cnt)
v=0
cons=0
l_c_l=0
u_c_l=0
for ch in cont:
if (ch.islower()):
l_c_l+=1
elif(ch.isupper()):
u_c_l+=1
ch=ch.lower()
if( ch in ['a','e','i','o','u']):
v+=1
elif (ch in ['b','c','d','f','g',
'h','j','k','l','m',
'n','p','q','r','s',
't','v','w','x','y','z']):
cons+=1
f.close()
print("Vowels are : ",v)
print("consonants are : ",cons)
print("Lower case letters are : ",l_c_l)
print("Upper case letters are : ",u_c_l)
#main program
cnt()

The view of test2 text file-


Output-

Q12. Write a menu based program to perform the operation on stack in python.

Source code-
def isEmpty(stk): # checks whether the stack is empty or not
if stk==[]:
return True
else:
return False

def Push(stk,item): # Allow additions to the stack


stk.append(item)
top=len(stk)-1

def Pop(stk):
if isEmpty(stk): # verifies whether the stack is empty or not
print("Underflow")
else: # Allow deletions from the stack
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)
print("Popped item is "+str(item))
def Display(stk):
if isEmpty(stk):
print("Stack is empty")
else:
top=len(stk)-1
print("Elements in the stack are: ")
for i in range(top,-1,-1):
print (str(stk[i]))

# executable code
if __name == " main__":
stk=[]
top=None
n=int(input("Enter the number of times you want to push"))
for i in range(n):
item=int(input("enter the value:"))
Push(stk,item)
c=input("Enter Y if you want to delete")
if c=='Y':
Pop(stk)
print("The elements of stack are:")
Display(stk)

Output-
Q13.write a python program for linear search.
Source code-
L=eval(input("Enter the elements: "))
n=len(L)
item=eval(input("Enter the element that you want to search : "))
for i in range(n):
if L[i]==item:
print("Element found at the position :", i+1)
break
else:
print("Element not Found",i+1,"th position")

output-

Q14. write a python program to create a csv file by entering user-id and password,read and search the password for given user-id.
Source code-
import csv
# User-id and password list
List = [["user1", "password1"],
["user2", "password2"],
["user3", "password3"],
["user4", "password4"],
["user5", "password5"]]
# opening the file to write the records
f1=open("UserInformation.csv", "w", newline="\n")
writer=csv.writer(f1)
writer.writerows(List)
f1.close()

# opening the file to read the records


f2=open("UserInformation.csv", "r")
rows=csv.reader(f2)
userId = input("Enter the user-id: ")
flag = True
for record in rows:
if record[0]==userId:
print("The password is: ", record[1])
flag = False
break
if flag:
print("User-id not found")

The view of csv file-

Output-
Q15. Read a text file line by line and display each word separated by a #
Source code-
file=open("book.txt","r")
lines=file.readlines()
for line in lines:
words=line.split()
for word in words:
print(word+"#",end="")
print(" ")

The view of book text file.


Output-
Q16. Write a python program to perform write and read operation of a csv file.
import csv
def create():
with open ("csv_f2.csv",'w+',newline='')as obj:
rec=[]
fobj=csv.writer(obj,delimiter=',')
fobj.writerow(['Roll','Name','Marks'])
while True:
record=[]
roll=int(input("Enter Roll"))
name=input("Enter name")
total=int(input("Enter marks"))
record=[roll,name,total]
rec.append(record)
fobj.writerow(record)
choice=int(input("1.Enter more\n2.exit\n Enter your choice"))
if choice==2:
break

def display():
with open ("csv_f2.csv",'r')as obj:
fobj=csv.reader(obj)
for i in fobj:
print(i)
create()
display()
The view of Csv File

Output-
Q17.Create the following table persons and write the SQL query command based on the same table.
(Note- Draw the table on ruled side of file sheet)
(Note-Write each question(from screen short) along with the answer (from the solution) together.)
Solutions-
i. select SurName, FirstName, City from persons where City ='Udhamwara';
Ii.select Pid, City, Pincode from persons order by Pincode desc;
Iii.select FirstName, City from persons where Gender='F' and BasicSalary>40000;Iv.
select FirstName, BasicSalary from persons where FirstName like "G%";
V. select FirstName, Surname, BasicSalary from persons where City in ('Bhawani', 'Udhamwara', 'Ahmednagar');
Vi. select FirstName, Surname, Pincode, BasicSalary from persons where City like "%Nagar%" order by BasicSalary desc;Vii.
alter table persons add column Increment float;
Viii.update persons set Increment = (0.1 * BasicSalary);
Ix. update persons set Gender = 'F' where FirstName = 'Garima';
X.select Pid, FirstName, Surname, Gender, City, Pincode, BasicSalary, Increment from Persons;Xi.
select sum(BasicSalary) as 'Total Salary', avg(BasicSalary) as 'Average Salary' from persons;
Xii.select max(BasicSalary) as ‘Maximum’, min(BasicSalary) as 'Minimum' from persons;
Xiii. Select * from persons group by city having count(*)>1;
Xiv. select avg(BasicSalary) as 'Salary for a' from Persons where FirstName like "%a";Xv.
alter table Persons change Pid Person_id int primary key;
Q18. Write a program to connect Python with MySQL using database connectivity and perform the following
operations on data in database :Insert,Fetch, Update and Delete

A. Create a table

Solution-

import mysql.connector
demodb=mysql.connector.connect(host="localhost",user="root",passwd="1234",database="school1")
democursor=demodb.cursor()
democursor.execute("Create table student(admin_no int primary key,sname varchar(30),gender char(1),DOB date,stream
varchar(15),marks float(4,2))")

Output-

B. Insert the data

Solution-

import mysql.connector
demodb=mysql.connector.connect(host="localhost",user="root",passwd="1234",database="school1")
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()

Output-

C. Fetch the data


Solution-
import mysql.connector
demodb=mysql.connector.connect(host="localhost",user="root",passwd="1234",database="school1")
democursor=demodb.cursor()
democursor.execute("select * from student")
for i in democursor:
print(i)

Output-

D. Update the Record

Solution-
import mysql.connector
demodb=mysql.connector.connect(host="localhost",user="root",passwd="1234",database="school1")
democursor=demodb.cursor()
democursor.execute("update student set marks=55.68 where admin_no=1245")
demodb.commit()

Output-

E. Delete the data


Solution-
import mysql.connector
demodb=mysql.connector.connect(host="localhost",user="root",passwd="1234",database="school1")
democursor=demodb.cursor()
democursor.execute("delete from student where admin_no=1245")
demodb.commit()

Output-

You might also like