You are on page 1of 26

COMPUTER SCIENCE

PRACTICAL FILE

Name-Arman Jaiswal
Class-12-C
functions
#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-
# 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 sum10(*n):
total=0
for i in n:
total=total + i
print("Sum of first 10 Numbers:",total)
sum10(1,2,3,4,5,6,7,8,9,10)
def product10(*n):
pr=1
for i in n:
pr=pr * i
print("Product of first 10 Numbers:",pr)
product10(1,2,3,4,5,6,7,8,9,10)
OUTPUT-

Data file handling

#READ A TEXT FILE LINE BY LINE AND DISPLAY


EACH WORD SEPERATED BY A ‘#’.

file=open("student.txt","r")
doc=file.readlines()
for i in doc:
words=i.split()
for a in words:
print(a+"#")
file.close()

OUTPUT-
#READ A TEXT FILE AND DISPLAY THE NUMBER
OF VOWELS, CONSONANT, LOWER CASE, UPPER
CASE IN THE FILE

def cnt():
f=open("student.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)
cnt()

OUTPUT-
#REMOVE ALL THE LINES THAT CONTAIN THE
CHARACTER ‘a’ IN A FILE AND WRITE IN
ANOTHER FILE

input_file=open(r"armaninput.txt","r")
output_file=open(r"armanoutput.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-

#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("*"*133)
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("*"*133)

import pickle
stu={}
print("="*102)
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 message-
#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('class12c.txt', 'wb')
pickle.dump(db, dbfile)
dbfile.close()
def update(rno,mark):
dbfile = open('class12c.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('class12c.txt', 'wb')
pickle.dump(db, dbfile)
dbfile.close()
def display():
dbfile = open('class12c.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-
#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-
#CREATE A CSV FILE WHILE ENTERING USER ID &
PASSWORD, READ AND SEARCH THE PASSWORD
FOR GIVEN USER ID
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
#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-
Syllabus book
SQL
PG NO.614
Q10.

Ans.
i) 4
ii)34
iii) 35.33
iv) 7800
q12.

Ans.
i) SELECT employeeid, name, jobtitle from
EMPLOYEE, JOB
WHERE EMPLOYEE.jobid = JOB.JOBID ;
ii) SELECT name, sales, jobtitle from EMPLOYEE,
JOB
WHERE EMPLOYEE.jobid = JOB.JOBID and
EMPLOYEE.sales>1300000 ;
iii) SELECT name, jobtitle from EMPLOYEE, JOB
WHERE EMPLOYEE.jobid = JOB.JOBID and
EMPLOYEE.name LIKE “%SINGH%” ;
iv) JOBID
v) UPDATE EMPLOYEE
Set jobid = 104
WHERE employeeid is “E4”;
Q13.
Ans. SELECT avg(salary), departments from JOB
Where COUNT(DISTINCT departments) >3;

You might also like