You are on page 1of 41

Computer science

Program File

Academic Year: 2023-2024

Roll No.:-
Name:- Ved
Class:- XII
Subject:- COMPUTER SCIENCE
Subject code:-

1
INDEX
S.N TOPIC Sign
O
1. To check whether the given number is prime or not
2. To check whether the given number is perfect or not
3. To check whether the given number is an Armstrong
no. or not
4. To check whether the given number is in Palindrome
or not
5. Write a function for the factorial of a number
6. Write a function for the Fibonacci series
7. Write a function to read a text file line by line and
display each word separated by a #
8. Read a text file and display the number of vowels/
consonants/ uppercase/ lowercase characters in a file
9. WAP to count number of words in a file.
10. WAP to remove all the lines that contains the
character 'a' in a file and write it to another file
11. Create a binary file with rollno,name, and marks.
Input a roll. no and update the marks.
12. Program to read and write employee records in a
binary file.
13. Write a program to enter the following records in a
binary file: Item No integer Item Name string Qty
integer Price float Number of records to be entered
should be accepted from the user. Read the file to
display the records in the following format: Item No:
Item Name: Quantity: Price per item: Amount: (to
be calculated as Price * Qty).
14. Program to delete a specified record from binary file.
15. Create a csv file by entering user id and password.
Search the password for the given user
16. To perform read and write operations in a csv
17. WAP to generate random numbers between to 6 and
check whether a user has won the lottery or not.
18. To implement a stack using list data structure
19. SQL Queries
20. Aggregate functions in sql
21. Connect to Python with MySQL using database
connectivity

2
Program 1:
AIM- To check whether the given number is prime or not.
INPUT:
number = int(input("Please Enter any Value: "))
count = 0
for i in range(2, (number//2 + 1)):
if(number% i==0):
count = count + 1
break
if (count ==0 and number != 1):
print("%d is a Prime", number)
else:
print("%d is Not prime", number)

OUTPUT:

3
Program 2:
AIM- To check whether the given number is perfect or not.
INPUT:
num= int(input("Enter the value:"))
result = 0
for m in range(1, num ):
if(num % m == 0):
result = result + m
if (result == num ):
print("Yes it is a Perfect number!")
else:
print("No, the value is not a Perfect number!")

OUTPUT:

4
Program 3:
AIM- To check whether the given number is an Armstrong or
not.
INPUT:
num= int(input("Enter a number:"))
sum=0
temp=num
while temp>0:
digit=temp % 10
sum += digit **3
temp//=10
if num== sum:
print(num,"is an armstrong number in order 3")
else:
print(num,"is not an armstrong number in order 3")
OUTPUT:

5
Program 4:
AIM- To check whether the given number is in palindrome
or not.
INPUT:
txt= input("enter some text")
if(txt== txt[::-1]):
print("this is a palindrome string")
else:
print("this is not in palindrome")

OUTPUT:

6
Program 5:
AIM- Write a function for the factorial of a number.
INPUT:
n= int(input("enter a number:"))
factorial=1
if n<0:
print("factorial of negative numbers does not exist")
elif n==0:
print("Factorial of 0 is 1")
else:
for i in range(1,n+1):
factorial=factorial*i
print("the factorial of",n,"is",factorial)

OUTPUT:

7
Program 6:
AIM- Write a function for the Fibonacci series.
n = int(input("Enter the value of 'n': "))
a =0
b= 1
sum=0
count = 1
print ("Fibonacci Series: ", end=" ")
while (count <= n):
print (sum, end = "")
count += 1
a=b
b = sum
sum =a+b
OUTPUT:

8
Program 7:
AIM- Write a function to read a text file line by line and display
each word separated by a “#”.
INPUT:

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

OUTPUT:

9
Program 8:
AIM- Read a text file and display the number of vowels/
consonants/ uppercase/ lowercase characters in a file.
INPUT:
f=open ("C:\\Users\\Admin\\Documents\\a.txt","r")
p=f.read()
f.close()
C_V,C_C, C_U,C_S=0,0,0,0
for ch in p:
if ch in 'aeiouAEIOU' :
C_V+=1
if ch not in 'aeiouAEIOU':
C_C+=1
if ch.isupper():
C_U+=1
if ch.islower ():
C_S+=1
print ("The number of vowels in the file",C_V)
print ("The number of consonants in the file", C_C)
print ("The number of uppercase characters in the file", C_U)
print ("The number of lowercase characters in the file",C_S)
OUTPUT:

10
Program 9:
11
AIM- WAP to count number of words in a file.
INPUT:
import pickle
f=open(“C:\\ Users\\Admin\\Documents\\a.txt","r")
count=0
for line in f:
words=line.split(“ “)
count=+len(words)
f.close()
print(“number of words in a text file:”,count”)

OUTPUT:

Program 10:
12
AIM- WAP to remove all the lines that contains the character 'a'
in a file and write it to another file.
INPUT:
f1 = open("/storage/emulated/0/python/12th/text.txt",'r')
f2 = open("untitled.txt","w")
s=f1.readlines()
for j in s:
if 'a' in j:
f2.write(j)
print('## File Copied Successfully ##')
f1.close()
f2.close()
OUTPUT:

Program 11:
13
AIM- Create a binary file with rollno,name, and marks. Input a
roll. no and update the marks.
INPUT:
import pickle
s={}
f=open('stud.dat','wb')
c="y"
while c=='y' or c=='Y':
rno=int(input("enter the roll no. of the student:"))
name=input("enter the name of the student:")
marks=int(input("enter the marks of the student:"))
s["RollNo"]=rno
s["Name"]=name
s["Marks"]=marks
pickle.dump(s,f)
c=input("Do you want to add more students (y/n):")
f.close()
f=open("stud.dat","rb+")
rno=int(input("enter the roll no. of the student to be updated"))
marks=int(input("enter the updated marks of the student:"))
f.seek(0,0)
m=0
try:
while True:

14
pos=f.tell()
s=pickle.load(f)
if s['RollNo']== rno:
f.seek(pos)
elif s["Marks"]== marks:
pickle.dump(s,f)
m=m+1
except EOFError:
f.close()
OUTPUT:

Program 12:
15
AIM- Program to read and write employee records in a binary
file.
INPUT:
import pickle
f=open("empfile.dat","ab")
print ("Enter Records of Employees")
while True:
eno=int(input("Employee number : "))
ename=input("Employee Name : ")
ebasic=int(input("Basic Salary : "))
allow=int(input("Allowances : "))
totsal=ebasic+allow
print("TOTAL SALARY : ", totsal)
edata=[eno,ename,ebasic,allow,totsal]
pickle.dump(edata,f)
ans=input("Do you wish to enter more records (y/n)? ")
if ans.lower()=='n':
print("Record entry OVER ")
print()
break
print("Size of binary file (in bytes):",f.tell())
f.close()
print("Now reading the employee records from the file")
print()

16
readrec=1
try:
with open("empfile.dat","rb") as f:
while True:
edata=pickle.load(f)
print("Record Number : ",readrec)
print(edata)
readrec=readrec+1
except EOFError:
f.close()

OUTPUT:

17
18
Program 13:
AIM- Write a program to enter the following records in a binary
file: Item No integer Item Name string Qty integer Price float
Number of records to be entered should be accepted from the
user. Read the file to display the records in the following format:
Item No: Item Name: Quantity: Price per item: Amount: (to be
calculated as Price * Qty).
INPUt:
#write records
import pickle
f=open("items.dat",'wb')
record={}
wish="y"
count=1
while wish.upper()=="Y":
item_no= int(input("enter item number:"))
item_name=input("enter item name:")
quantity=int(input("enter quantity:"))
price=float(input("enter price per item:"))
record['itemno']=item_no
record['itemname']=item_name
record['quantity']=quantity
record['price']=price

19
pickle.dump(record, f)
wish=input("want to add more records (y/n):")
count=count+1
f.close()

#read records
import pickle
f=open("items.dat","rb")
record={}
count=1
try:
while True:
print("item",count,"details")
record=pickle.load(f)
print("item number:",record["itemno"])
print("item name:",record["itemname"])
print("quantity:",record["quantity"])
print("price:",record["price"])
print("amount:",record["quantity"]*record["price"])
count=count+1
except EOFError:
f.close()

20
OUTPUT:

21
Program 14:
AIM- Program to delete a specified record from binary file.
INPUt:
import pickle
fin=open('C:\\Users\\Arihant\\Desktop\\File Handli
ng\\student1.dat','wb')
for i in range(2):
rno=int(input('Enter roll number of the student:" ))
name=input('Enter student name:')
marks=int(input('Enter marks of the student :'))
rec=[rno,name,marks]
pickle.dump(rec, fin)
fin.close()

stu={}
def Del():
file=open('C:\\Users\\Arihant\\Desktop\\File Ha
ndling\\student1.dat','rb')
f=open('C:\\Users\\Arihant\\Desktop\\File Handl
ing\\student.dat','wb')
r=int(input('Enter roll number to be deleted :'))
found=False
try:

22
while True:
stu=pickle.load(file)
if stu[0]==r:
found=True
else:
pickle.dump(stu,f)
except EOFError:
file.close()
f.close()
if found==False:
print("Record not found"
file1=open('C:\\Users\\Arihant\\Desktop\\File Han
dling\\student.dat','rb')
info=pickle.load(file1)
try:
while True:
for i in info:
print(i)
continue()
break()
except EOFError:
file1.close()
Del()

23
24
Program 15:
AIM- Create a csv file by entering user id and password. Search
the password for the given user.
INPUt:
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")

25
for i in fileobj2:
next(fileobj2)
if i[0] == given:
print(i[1])
break
output:

Program 16:
26
AIM- To perform read and write operations in a csv
INPUt:
import csv
f= open("C:\\Users\\Admin\\Desktop",'w')
fieldnames = ['emp_name', 'dept', 'birth_month']
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'emp_name': 'Parker', 'dept': 'Accounting',
'birth_month': 'November'})
writer.writerow({'emp_name': 'Smith', 'dept': 'IT', 'birth_month':
'October'})
f.close()
output:

Program 17:
27
AIM- WAP to generate random numbers between 1 to 6 and
check whether a user has won the lottery or not.

INPUt:
import random
def check_lottery(selected_number):
lottery_number=5
if selected_number== lottery_number:
return "congratulations! you won the lottery"
else:
return "sorry, you lost."
selected_number=int(input('enter your selected number
(between 1 and 6):'))
print(check_lottery(selected_number))
output:

28
Program 18:
AIM- To implement a stack using list data structure.

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

def Push(stk,elt):
stk.append(elt)
print ("element inserted...")
print (stk)

def pop(stk):
if isEmpty(stk):
print("stack is empty... underflow case..")
else:
print("deleted element is:", stk.pop())

def peek(stk):

29
if isEmpty(stk):
print("stack is empty...")
else:
print("element at top of the stack:", stk[-1])

def Display(stk):
if isEmpty(stk):
print("stack is empty")
else:
for i in range(len(stk)-1,-1,-1):
print(stk[i])

Stack=[ ]
while True:
print("1.PUSH")
print("2.POP")
print("3.PEEK")
print("4.DISPLAY")
print("5.EXIT")
ch=int(input("Enter your choice:"))
if ch==1:
element=int(input("enter the element which you want to
add"))
Push(Stack,element)

30
if ch==2:
pop(Stack)
if ch==3:
peek(Stack)
if ch==4:
Display(Stack)
elif ch==5:
break
output:

31
32
Program 19:
AIM- SQL Queries
1. SELECT * FROM EMP;

A. SELECT DISTINCT DEPARTMENT FROM EMP;

33
B. SELECT NAME, SALARY FROM EMP WHERE
SALARY>35000 AND SALARY<40000;

C. SELECT NAME FROM EMP WHERE CITY IN


<”GUWAHATI”,”SURAT”,”JAIPUR”>;

D. SELECT NAME FROM EMP WHERE NAME LIKE “M%”;

34
E. SELECT NAME FROM EMP ORDER BY ID DESC;

F. SELECT AVG(SALARY) AS AVG_SALARY,


DEPARTMENT FROM EMP GROUP BY DEPARTMENT;

G. SELECT MAX(SALARY) AS MAX_SALARY,


DEPARTMENT FROM EMP GROUP BY DEPARTMENT
HAVING MAX(SALARY)>39000;

35
Program 20:
AIM- Aggregate functions in SQL
A. SELECT AVG(SALARY) AS AVG_SALARY FROM EMP;

B. SELECT MIN(SALARY) AS MIN_SALARY FROM EMP


WHERE GENDER=”FEMALE”;

C. SELECT MAX(SALARY) AS MAX_SALARY FROM EMP


WHERE GENDER=”MALE”;

D. SELECT SUM(SALARY) AS TOTAL_SALARY FROM EMP


WHERE CITY=”GUWAHATI”;

36
E. SELECT COUNT(*) “TUPLES” FROM EMP;

37
Program 21:
AIM- Connect to python with MySQL using database
connectivity.
a. Create-
import mysql.connector as c
db=c.connect(host="localhost",user= "root",
passwd="chehakvega293",
database="employeedetails2")
mc=db.cursor()
mc.execute('CREATE TABLE employeedetail(ID int
primary key, NAME varchar(40), DEPARTMENT
varchar(50), SALARY decimal(8,2),CITY varchar(30),
GENDER varchar(15));”)
db.commit()

38
b. Insert Values-
import mysql.connector as c
db=c.connect(host="localhost",user='root',
passwd='chehakvega293',
database='employeedetails2')
mc=db.cursor()
mc.execute("INSERT INTO employeedetail
VALUES(101,'puja','technology',
100000,'delhi','female');")
db.commit()

c. Fetch-
import mysql.connector as c
db=c.connect(host="localhost",user='root',passwd="c
hehakvega293",d atabase='employeedetails2')
mc=db.cursor()
mc.execute("select * from employeedetail;")
for i in mc:
print(i)

39
d. Update-
import mysql.connector as c
db=c.connect(host="localhost",user='root',passwd="c
hehakvega293",d atabase='employeedetails2')
mc=db.cursor()
mc.execute("UPDATE employeedetail SET
NAME='shreya' where ID=100;")
db.commit()

e. Delete-
import mysql.connector as c
db=c.connect(host="localhost",user='root',passwd='c
hehakvega293',da tabase='employeedetailsz')
mc=db.cursor()
mc.execute("DELETE FROM employeedetail where
ID=100;")
db.commit()

40
41

You might also like