You are on page 1of 22

COMPUTER SCIENCE

PRACTICAL REPORT
(2022-23)

Name-NIHAL SAINI
Class-12-B
INDEX
Sr.
No
Topic Date Signatur
e
1) Write a program function using a function to print factorial 1.10.22
number series from ‘n’ to ‘m’
2) Write the program to accept the user name admin as a default 1.10.22
argument and password 123 enter by the user to allow login into
the system
3) Write a program to demonstrate the concept of variable length 2.10.22
argument to calculate the product and power of the first ‘10’
natural number
4) Read a text file line by line and display each word separated by 3.10.22
a’#’
5) Read a text file and display the number of vowels consonants 4.10.22
uppercase, lowercase characters in the file
6) Remove all the line that contain a character small ‘a’ in a file and 5.10.22
write into another file,
7) Create a binary file with name and roll name search if not found 5.10.22
display an appropriate message
8) Create a binary file with roll no, name and marks. Input roll no and 6.10.22
update mark.
9) Write a random number generator that generates random 7.10.22
number between 1 and 6
10) Create a csv file by entering user id and password read and search 7.10.22
the password for given user id
11) Write a python program to implement stack operations 7.10.22
12) SQL Queries 9.10.22
13) Menu driven usage of functions of list 9.10.22
14) SQL Connectivity 9.10.22
functions
(1.) WAP USING A FUNCTION TO PRINT FACTORIAL NUMBER SERIES FROM N TO
M NUMBERS
def facto():
n=int(input("Enter the number:"))
f=1
for i in range(1,n+1):
f*=i
print("Factorial of ",n, "is: ",f, end=" ")
facto()

OUTPUT-
(2.) WAP TO ACCEPT USERNAME ADMIN AS A DEFAULT ARGUMENT AND
PASSWORD 123 ENTERED BY THE USER TO ALLOW LOGIN INTO THE SYSTEM

def user_pass(password,username="Admin"):
if password=='123':
print("You have logged into system")
else:
print("Password is incorrect!!!!!!")
password=input("Enter the password:")
user_pass(password)

OUTPUT-
(3.) Write a python program to demonstrate the concept of variable length
argument to calculate product and power of the first 10 numbers.
def product10(*n):
pr = 1
for i in n:
pr = pr * i
print("Product of first 10 natural Numbers:",pr)
product10(1,2,3,4,5,6,7,8,9,10)
def power(x, n):
pow = 1
for i in range(n):
pow = pow * x
return pow
n=2
for i in range(1,11):
x=i
print("Powers: ",power(x,n))

OUTPUT-
Data file handling
(4.) READ A TEXT FILE LINE BY LINE AND DISPLAY EACH WORD SEPERATED BY ‘#’.

file=open("nihal.txt","r")
r=file.readlines()
for i in range(len(r)):
a=r[i].split()
print("#".join(a))
file.close()
OUTPUT-

(5.) READ A TEXT FILE AND DISPLAY THE NUMBER OF VOWELS, CONSONANT,
LOWER CASE, UPPER CASE IN THE FILE

file=open("nihal.txt","r")
v=c=u=l=0
b=file.read()
for i in b:
if i.isalpha():
if i in["a","e","i","o","u","A","E","I","O","U"]:
v+=1
else:
c+=1
if i.isupper():
u+=1
elif i.islower():
l+=1
print("no of vowels",v)
print("no of consonants",c)
print("no of upper case",u)
print("no of lower case",l)
OUTPUT-

(6.) REMOVE ALL THE LINES THAT CONTAIN THE CHARACTER ‘a’ IN A FILE AND
WRITE IN ANOTHER FILE

input_file=open(r"nihal.txt","r")
output_file=open(r"nihalresult.txt","w")
lines=input_file.readlines()
for i in lines:
if 'a' not in i:
output_file.write(i)
output_file.close()
input_file.close()
OUTPUT-

i)Input file-

ii)output file-
(7.) CREATE A BINARY FILE WITH NAME & ROLL NO. SEARCH FOR A GIVEN A ROLE
NO. AND DISPLAY THE NAME IF NOT FOUND DISPLAY APPROPRIATE MESSAGE
print("*"*100)
print("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.")
print("*"*100)
import pickle
stu={}
print("="*100)
print("Already Exsisting Data of Binary File.")
#print("*"*133)
rh1=open("Student.dat",'rb+')
try:
while True:
stu=pickle.load(rh1)
print(stu)
except EOFError:
rh1.close()
fh1=open("Student.dat",'ab+')
print("="*102)
ans=input("Want to Enter more data to file (y/n)...")
while ans=='y':
stu['Rollno']=int(input("Enter Roll Number: "))
stu['Name']=input("Enter Name: ")
pickle.dump(stu,fh1)
ans=input("Want to enter more? (y/n)...")
fh1.close()
print()
print("Searching in Binary File")
print("="*102)
key=int(input("Enter the Roll Number to be searched: "))
fh2=open("Student.dat",'rb+')
found=False
try:
while True:
stu=pickle.load(fh2)
if stu['Rollno']==key:
found=True
print("The Searched Roll No is Found:")
print()
print(stu)
except EOFError:
if found==False:
print()
print("The Searched Roll No does not exsits: ")
else:
print()
print("Searching Completed")
fh2.close()

OUTPUT-
Error output-

(8.) CREATE A BINARY FILE WITH ROLL NO. AND MARKS INPUT ROLL NO. AND
UPDATE THE MARKS
import pickle
db = {}
n1={}
def storedata(ns):
for i in range(ns):
name=input("Enter Name of the Student")
rno=int(input("Enter Rollno"))
mark=int(input("Enter Mark"))
n1['name']=name
n1['rno']=rno
n1['mark']=mark
n=dict(n1)
db[i]=n
dbfile = open(‘class12b.txt', 'wb')
pickle.dump(db, dbfile)
dbfile.close()
def update(rno,mark):
dbfile = open(‘class12b.txt', 'rb')
db = pickle.load(dbfile)
f=1
for keys in db:
if rno == db[keys]["rno"]:
db[keys]["mark"]=mark
print("Roll No: ",db[keys]["rno"])
print("Name : ",db[keys]["name"])
print("Mark: ",db[keys]["mark"])
f=0
if f:
print(rno," is not avialable")
else:
dbfile.close()
dbfile = open(‘class12b.txt', 'wb')
pickle.dump(db, dbfile)
dbfile.close()
def display():
dbfile = open(‘class12b.txt', 'rb')
db = pickle.load(dbfile)
print(db)
ns=int(input("Enter No. of Students to be stored"))
storedata(ns)
display()
rno=int(input("Enter Roll no to Search"))
mark=int(input("Enter New Mark"))
update(rno,mark)
display()

OUTPUT-
(9.) WRITE A RANDOM NO. GENERATOR THAT GENERATES RANDOM NO.
BETWEEN 1 AND 6
import random
min = 1
max = 6
roll_again = "y"
while roll_again == "y" or roll_again == "Y":
print("Rolling the dice...")
val = random.randint (min, max)
print("You get... :", val)
roll_again = input("Roll the dice again? (y/n)...")

OUTPUT-
(10.) CREATE A CSV FILE WHILE ENTERING USER ID & PASSWORD, READ AND
SEARCH THE PASSWORD FOR GIVEN USER ID

import csv
List = [["nihal", "nihal9231"],
["utkarsh", "utkarsh2004"],
["anirudh", "anirudh2004"],
["aryan"," aryan 2004"],
["Paradox", "174899"]]
f1=open("UserInformation.csv", "w", newline="\n")
writer=csv.writer(f1)
writer.writerows(List)
f1.close()
f2=open("UserInformation.csv", "r")
rows=csv.reader(f2)
userId = input("Enter the user-id: ")
fl = True
for record in rows:
if record[0]==userId:
print("The password is: ", record[1])
fl = False
break
if fl:
print("User-id not found")
import csv
with open("user_info.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("user_info.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

OUTPUT-
Stack operations
(11.) WRITE A PYTHON PROGRAM TO IMPLEMENT STACK OPERATIONS
class Stack_struct:
def __init__(self):
self.items = []
def check_empty(self):
return self.items == []
def add_elements(self, my_data):
self.items.append(my_data)
def delete_elements(self):
return self.items.pop()
my_instance = Stack_struct()
while True:
print('Push <value>')
print('Pop')
print('Quit')
my_input = input('What operation would you like to perform ? ').split()
my_op = my_input[0].strip().lower()
if my_op == 'push':
my_instance.add_elements(int(my_input[1]))
elif my_op == 'pop':
if my_instance.check_empty():
print('The stack is empty')
else:
print('The deleted value is : ', my_instance.delete_elements())
elif my_op == 'Quit':
break

OUTPUT-
SQL
(12.) SQL QUERIES
(13.) WRITE A PROGRAM TO SHOW THE WORKING OF AL LIST FUNCTION /
METHOD
def lst_menudriven():
l=[1,2,3,4,5,6,7,8,9]
def add():
print("CHOOSE:\n1.Append an element\n2.Insert at a specific position\
n3.Append a list")
opt1=int(input("choose one:"))
if opt1==1:
val=int(input("element to be added:"))
l.append(val)
elif opt1==2:
val=int(input("element to be added:"))
p=int(input("enter the position:"))
l.insert(p-1,val)
elif opt1==3:
val=eval(input("list to be added:"))
l.extend(val)
return l
def mod():
n=int(input("new value:"))
p=int(input("enter the position:"))
l[p-1]=n
return l
def d():
print("CHOSE:\n1.Delete using index\n2.Delete using value")
opt2=int(input("choose one:"))
if opt2==1:
p=int(input("enter the position:"))
l.pop(p-1)
elif opt2==2:
val=eval(input("element to be deleted:"))
l.remove(val)
return l
def sort():
a=l.sorted()
print(a)
def menu():
print("CHOOSE:\n1.Append\n2.Modify\n3.Delete\n4.Sort\n5.Exit")
a=True
while a:
opt=int(input("choose one:"))
if opt==1:
print(add())
menu()
elif opt==2:
print(mod())
menu()
elif opt==3:
print(d())
menu()
elif opt==4:
sort()
menu()
else:
a=False
break
menu()
lst_menudriven()
(14.)SQL CONNECTIVITY PROGRAM
import pymysql as p
def create():
obj=p.connect(user="root",password="root",host="localhost")
a=obj.cursor()
n=input("enter the name of the database")
sql="create database "+n+";"
a.execute(sql)
print("database change:")
def createtable():
s=input("enter the name of the database")
obj=p.connect(user="root",password="root",host="localhost",database=s)
a=obj.cursor()
tname=input("enter the name of the table")
sql="create table" +tname+ "(sno int,namechar(10));"
a.execute(sql)
a.close()
obj.close()
def insertres():
s=input("enter the name of the databsase")
tname=input("ente rthe name of the table")
obj.pconnect(user="root",password="root",host="localhost",database=s)
a=obj.cursor()
n=int(input("enter how mny records you want"))
for i in range(n):
sno=input("enter your serialno")
name=input("enter your name")
sql="insert into" +tname+ "vaues('''+sno+''','''+name+''');"
a.execute(sql)
obj.connect()
a.close()
obj.close()
def displayrecords():
s=input("enter the name of the database")
tname=input("enter name of table")
obj=p.connect(user="root",password="root",host="localhost",database=s)
a=obj.cursor()
sql="select * from stu;" +tname
a.execute(sql)
for n in a:
for y in n:
print(y,end="\t")
print()
a.close()
obj.close()
def showtable():
s=input("enter the name of the database")
obj=p.connect(user="root",password="root",host="localhost",database=s)
a=obj.cursor()
sql="show tables;"
a.execute(sql)
for j in a:
print(j)
a.close()
obj.close()
def showdb():
obj=p.connect(user="root",password="root",host="localhost",database=s)
a=obj.cursor()
sql="show databases;"
for j in a:
print(j)
a.close()
obj.close()
while True:
print("menu")
print("1.create database")
print("2.cerate table")
print("3.insertrec")
print("4.displayrecrods")
print("5.showtables")
print("6.showdatabases")
print("7.exit")
ch=int(input("enter your choice"))
if ch==1:
create()
elif ch==2:
createtable()
elif ch==3:
insertrec()
elif ch==4:
displayrecords()
elif ch==5:
showtable()
elif ch==6:
showdb()
elif ch==7:
break
else:
continue

You might also like