You are on page 1of 34

COMPUTER

SCIENCE
JOURNAL
BY ABHIRAM KS
CLASS XII S2
ROLL NO : 03

BOARD ROLL NO:


i. To find the factorial of an entered number
ii. To print the Fibonacci Series up to N
iii. Exit

while(1):
print("\na) Factorial of number")
print("b) To print the Fibonacci Series up to N")
print("c) Exit")
ch=input("\nchoose option from above: ")
if ch=="a":
Ans="yes"
while Ans=="yes" or Ans=="YES":
n=int(input("Enter number to find its Factorial: "))
f=1
F=1
while f<=n:
F*=f
f+=1
print("Factorial of",n,"is",F)
Ans=input("\nDo you want to find more factorials? ")
elif ch=='b':
Ans="yes"
while Ans=="yes" or Ans=="YES":
n=int(input("Enter no.: "))
a,b,c=0,1,0
print(a,b,end=" ")
while c<n:
c=a+b
if c<n:
a,b=b,c
print(c,end=" ")
print('')
Ans=input("\nDo you want to find more factorials? ")
elif ch=='c':
exit()
else:
print('Invalid choice')
2.1. To find the vowels and consonants in a given string.
2. Check if a given String is Palindrome or not.
3. Exit
while(1):
print('1. To find the vowels and consonants in a given string.')
print('2. Check if a given String is Palindrome or not.')
print('3. Exit')
ch=int(input("\nchoose option from above: "))
if ch==1:
str1=input('Enter string: ')
vowel=consonant=0
lst=['a','e','i','o','u','A','E','I','O','U']
for letter in str1:
if letter.isalpha():
if letter in lst:
vowel+=1
else:
consonant+=1
print('No. of Vowel',vowel,'\nNo. of Consonant',consonant)
elif ch==2:
str2=input('Enter string: ')
if str2==str2[::-1]:
print(str2,'is palindrome')
else:
print(str2,'is not palindrome')
elif ch==3:
exit()
else:
print('Invalid choice')

OUTPUT
3. Write a function to generate a random number between 1 and 6. Ask the user to guess the
number. Give 4 choices to guess and print appropriate message

import random
ans='yes'
while ans=='yes':
n=random.randint(1,6)
c=1
while c<5:
n2=int(input('Enter your guess'))
if n2==n:
print('Guess matched')
else:
print('Wrong guess',4-c,'chance left')
c+=1
ans=input('want to continue?')

OUTPUT
4. Write a menu driven program with the following options:
1. To accept a string
2. To print the string
3. To count the total no. of words in the given string.
4. To find the longest word &amp; print its position.
5. Exit

def add():
str1=input('Enter a string')
return(str1)
def show(str1):
if str1==None:
print('Enter the string first')
else:
print(str1)
def count(str1):
l=str1.split()
words=len(l)
print('There are',words,'words in the string' )
def longest(str1):
l=str1.split()
length=0
for word in l:
if len(word)>length:
longword=word
print('Longest word is',longword,'and its position is at',str1.find(longword))
str1=None
while (1):
print('1. To accept a string')
print('2. To print the string')
print('3. To count the total no. of words in the given string.')
print('4. To find the longest word and print its position.')
print('5. Exit')
ch=int(input('Enter on choice from above'))
if ch==1:
str1=add()
elif ch==2:
show(str1)
elif ch==3:
count(str1)
elif ch==4:
longest(str1)
elif ch==5:
exit()
else:
print('Invalid choice')

OUTPUT
5 ) Write a menu driven program with the following options:
i. To accept a set of numbers &amp; store them into a list
ii. To accept a no &amp; find its position in the list using Linear Search method
iii. To accept a no &amp; delete from the list iv. Exit

l=[]
ans="y"
while (ans=="y" or ans=="Y"):
print("1. To Enter the list \n 2. to search a Number and get its position\n 3.To aceept a number and delete it from the
list\n 4.Exit")
choice=int(input("Enter your choice")) if(choice==1):
no=int(input("Enter the number of elements to be entered in the list")) print("Start entering numbers in the list")
for i in range(0,no):
ele=int(input())
l.append(ele) if(choice==2):
num=int(input("Enter the number you want to search")) for i in range(len(l)):
if(l[i]==num):
print("The Number u have entered for searching is :", num) print("We Found The Number on the ",i," th index of the
list")
else:
print("Sorry we did not find the number in the list")
break if(choice==3):
num=int(input("Enter the number u want to remove from the string")) l.remove(num)
print("The List After Removing The Element ",l)
if(choice==4): exit()
print("Do u want to continue...y/n") ans=input()
OUTPUT
6. Write a menu driven program with the following options:
i. To accept a set of numbers and create a Tuple
ii. To find the Lowest &amp; highest Number from the Tuple (without using any in-built
function)
iii. To find sum &amp; average of all elements in the Tuple (without using any in-built
function)
iv. Exit

def create():
n=int(input('How many element you want to add in the tuple?: ')
lst=[]
for i in range(n):
a=int(input('Enter no.'))
lst.append(a)
tup=tuple(lst)
return(tup)
def minmax(tup):
if tup==None:
print('First Create Tuple')
else:
l=len(tup)
n=tup[0]
b,s=n,n
for i in range(l):
n=tup[i]
if n>b:
b=n
elif s>n:
s=n
print('Smallest no. is:',s,'\nBiggest no. is:',b)
def avgsum(tup):
if tup==None:
print('First Create Tuple')
else:
Sum=0
l=len(tup)
for i in range(l):
Sum+=tup[i]
avg=Sum/l
print('Sum is',Sum,'\nAverage is',avg)
tup=None
while(1):
print('1. To accept a set of numbers and create a Tuple')
print('2. To find the Lowest and highest Number from the Tuple')
print('3. To find sum &amp; average of all elements in the Tuple')
print('4. Exit')
ch=int(input('Enter choice'))
if ch==1:
tup=create()
elif ch==2:
minmax(tup)
elif ch==3:
avgsum(tup)
elif ch==4:
exit()
else:
print('invalid choice')

OUTPUT
7. Write a menu driven Python program with the following options:
1. To create a dictionary by accepting Name and marks of N students.
2. Display the contents of the dictionary. If it is empty, print appropriate message.
3. To check whether a given name exists in the dictionary, If present print his/her marks.
4. Exit

dic={}
while(1):
print('1. To create a dictionary by accepting Name and marks of N students.')
print('2. Display the contents of the dictionary.')
print('3. Search name in the dictionary')
print('4. Exit')
ch= int(input('Enter choice fro above'))
if ch==1:
n=int(input('How many records you want to add in the dictionry'))
for i in range(n):
nm=input('Enter name')
mk=int(input('Enter marks'))
dic[nm]=mk
print('Dictionary created')
elif ch==2:
if dic=={}:
print('Empty dictionary')
else:
print("Name\t\tMarks")
for i in dic:
print(i,'\t\t',dic[i])
elif ch==3:
nm=input('Enter name')
flag=0
for i in dic:
if i==nm:
print(nm,':',dic[nm])
flag=1
if flag==0:
print('record not found')
elif ch==4:
exit()
else:
print('Invalid input')

OUTPUT
8. Write a program to write the following lines of text into a file, named exprsn .txt. Read this text
file line by line and display each word separated by a - # symbol.

fh=open('exprsn.txt','w')
st1='life is an adventure, like a roller coaster. That explains the ups and downs in life. Often, when we think we are at
the end of something, we are actually at the beginning of something else.'
fh.write(st1) # writing in the file
fh.close()

fh=open('exprsn.txt','r')
st2=fh.read()
l=st2.split()
for i in l:
print(i,'#',end='')
fh.close

OUTPUT
9.Write a program to create a file named whorules.txt, with the following lines of text. Read this
text file and display the total number of vowels/ consonants/ uppercase/ lowercase characters
present in the file.
”Be confident in yourself. Nobody can make you feel inferior without your permission. Always
look forward. You can never plan the future by looking the past.”

fh=open('whorules.txt','w')
st1="Be confident in yourself. Nobody can make you feel inferior without your permission. Always look forward. You
can never plan the future by looking the past."
fh.write(st1) # writing in the file
fh.close()

fh=open('whorules.txt','r')
st=fh.read()
v=c=u=l=0
for word in st:
if word.isalpha():
if word in ['a','e','i','o','u','A','E','I','O','U']:
v+=1
else:
c+=1
if word.isupper():
u+=1
elif word.islower():
l+=1
fh.close()
print('no. of vowel',v)
print('no. of consonant',c)
print('no. of uppercase',u)
print('no. of lowercase',l)

OUTPUT
10. Read the text file named expressn.txt that stores the following text. Count the total number of
occurrences of the word ‘it’ and ‘is’ separately
Nothing in life is to be feared,\n as it takes you nowhere.\n Worry is
like a rocking chair\n: It gives you something to do\nbut never gets
you anywhere.

fh=open('expressn.txt','r')
st=fh.read()
it=s=0
lst=st.split()
for word in lst:
if word=='it':
it+=1
elif word=='is':
s+=1
fh.close()
print('No. of "it" in the file:',it)
print('No. of "is" in the file:',s)

OUTPUT
11. Write a menu driven program
i. To create a binary file named records.dat, with some names and roll numbers taken
from user and stored in the file.
ii. To print all the records in a formatted manner.
iii. Search for a given roll number and display the name. If the given name is not found in
the file display an appropriate message.
iv. Exit

import pickle
while(1):
print('1. CREATE NEW file')
print('2. Print all the records')
print('3. Search for a roll number')
print('4. Exit')
ch=int(input('Enter one choice'))
if ch==1:
n=int(input('how many records you want to add?'))
fh=open('record.dat','ab')
for i in range(n):
lst=[]
rolno=int(input('Enter roll no'))
nm=input('Enter name')
lst=[rolno,nm]
pickle.dump(lst,fh)
print('Records added')
fh.close()
elif ch==2:
fh=open('record.dat','rb')
print('Roll no.\t\tName')
try:
while(1):
lst=pickle.load(fh)
print(lst[0],'\t\t\t',lst[1])
except EOFError:
fh.close()
elif ch==3:
fh=open('record.dat','rb')
rl=int(input('Enter roll: '))
flag=0
try:
while(1):
lst=pickle.load(fh)
if lst[0]==rl:
print(rl,':',lst[1])
flag=1
except EOFError:
fh.close()
if flag==0:
print('record not found')
elif ch==4:
exit()
else:
print('Invalid choice')
OUTPUT
12. Create a binary file named result.dat, to stores some roll number, name and marks of 4 students.
Accept a roll number and new marks of the student from the user. Update this marks into the file.
Code
import pickle def write():
f=open("studentdetails.dat",'wb') while True:
r=int(input("enter roll no :"))
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 of 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
13.Write a menu driven program
i. To create a CSV file named Employee.csv, with some names , Employee code and Salary taken from user.
ii. To print all the records .
iii. Search for a record with a given Employee number and display the Details.
iv. Display record of the employee getting the highest salary.
v. Exit

import csv
while(1):
print("1. Add records in the file")
print("2. Print all the records ")
print("3. Search for a record with Employee number")
print("4. Display record of the employee getting the highest salary")
print("5. Exit")
ch=int(input('Enter one choice'))
if ch==1:
fh=open('Employee.csv','a',newline='')
n=int(input('How many records you want to add? '))
wr=csv.writer(fh)
for i in range(n):
emno=int(input('Enter employee number: '))
emnm=input('Enter employee name')
salary=int(input('Enter employee salary'))
l=[emno,emnm,salary]
wr.writerow(l)
print('Records updated')
fh.close()
elif ch==2:
fh=open('Employee.csv','r')
print('Emp no.\t\tName\t\tSalary')
rec=csv.reader(fh)
for row in rec:
print(row[0],'\t\t',row[1],'\t\t',row[2])
fh.close()
elif ch==3:
em=int(input('Enter emp no. '))
fh=open('Employee.csv','r')
print('Emp no.\tName\tSalary')
rec=csv.reader(fh)

for row in rec:


if str(em)==row[0]:
print(row[0],'\t',row[1],'\t',row[2])
f=1
if f==0:
print('Record not found')
fh.close()
elif ch==4:
fh=open('Employee.csv','r')
rec=csv.reader(fh)
n=0
for row in rec:
if row[2]>str(n):
em=row[0]
name=row[1]
n=row[2]
print('Emp no.:',em,'\nName:',name,'\nSalary:',n)
fh.close()
elif ch==5:
exit()
else:
print('Invalid input')
OUTPUT
14.Write a menu driven program to perform the following operations on a Stack to store records of book details
(bookNo, bookName) using function:
a. Push operation
b. Pop operation
c. Peek operation
d. Display all elements from a stack

stack=[]
while (1):
print('1. Push book detail')
print('2. Pop')
print('3. Peek ')
print('4. Display all element')
print('5. Exit')
ch=int(input('Enter one choice'))
if ch==1:
n=int(input('How many records you want to add? '))
for i in range(n):
bkno=int(input('Enter Book number'))
nm=input('Enter Book name')
lst=[bkno,nm]
stack.append(lst)
print('Records added')
elif ch==2:
if stack==[]:
print('Empty stack')
else:
print(stack.pop(),'popped out of the stack')
elif ch==3:
if stack==[]:
print('Empty stack')
else:
print('Peek-',stack[-1][0],':',stack[-1][1])
elif ch==4:
if stack==[]:
print('Empty stack')
else:
print('BOOK NUMBER\tBOOK NAME')
l=len(stack)
for i in range(1,l+1):
print(stack[-i][0],'\t\t',stack[-i][1])
elif ch==5:
exit()
else:
print('invalid input')

OUTPUT
15.BCCI has created a dictionary containing top players and their runs as key value pairs of cricket
team. Write a program, with separate user defined functions to perform the following operations:
Push the name of the players (provided as keys) of the dictionary into a stack, where the
corresponding runs (value ) is greater than 49.
Pop and display the content of the stack.

stack=[]
dic={}
def addstack(dic):
if dic=={}:
print('Create the dictionary first')
else:
l=[]
for i in dic:
if i>49:
l.append([i,dic[i]])
print('Stack created')
return(l)
def create():
dic={}
n=int(input('How many elements in dictionary'))
for i in range(n):
nm=input('Enter player name')
sc=int(input('Enter player score'))
dic[sc]=nm
print('Dictionary created\n',dic)
return(dic)
def popdis(stack):
if stack==[]:
print('Empty stack')
else:
print('NAME\tSCORE')
for i in range(len(stack)):
l=stack.pop()
print(l[1],'\t',l[0])
while(1):
print('1. Create dictionary')
print('2. Form stack from dic')
print('3. Pop and display the stack')
ch=int(input('choose one option'))
if ch==1:
dic=create()
elif ch==2:
stack=addstack(dic)
elif ch==3:
popdis(stack)
else:
print('invalid choice')

OUTPUT
16.Write a Python code to connect a MySQL database namely SHOP and use the following table Stationery and
Consumer and send SQL commands to the database and retrieve the records based on the queries given
below:
Table: Stationery
S_ID StationaryName Company Price

DP01 Dot Pen REYNOLDS 10

PL02 Pencil ITC 6

ER05 Eraser ITC 7

PL01 Pencil NATRAJ 5

GP02 Gel Pen REYNOLDS 15

Table: Consumer

C_ID ConsumerName Address S_ID

1 Good Learner Delhi PL01

6 Write Well Mumbai GP02

12 Topper Delhi DP01

15 Write & Draw Delhi PL02

16 Motivation Bangalore PL01

i. To display the details of those consumers whose Address is Delhi.


ii. To display the details of Stationery whose Price is in the range of 8 to 15. (Both Value included)
iii. To display the ConsumerName, Address from Table Consumer, and Company and Price from table
Stationery, with their corresponding matching S_ID.
iv. Display the maximum and minimum price for each company.
import mysql.connector as sqltor
con=sqltor.connect(host='localhost',user='root',password='123456',database='SHOP')
if con.is_connected():
print('successful')
print('details of those consumers whose Address is Delhi.')
cur=con.cursor()
cur.execute("select * from consumer where address='Delhi'")
data=cur.fetchall()
print('C_ID\tConsumerName\tAddress\tS_ID')
for i in data:
print(i[0],'\t',i[1],'\t',i[2],'\t',i[3])

print('\n\ndetails of Stationery whose Price is in the range of 8 to 15')


cur.execute("select * from stationary where price between 8 and 15")
data=cur.fetchall()
print('S_ID\t\tStationaryName\t\tCompany\t\tPrice')
for i in data:
print(i[0],'\t\t',i[1],'\t\t',i[2],'\t',i[3])

print('\n\nConsumerName, Address Company and Price from table')


cur.execute("select ConsumerName,Address,Company,Price from Consumer,Stationary where
consumer.S_ID=Stationary.S_ID;")
print('ConsumerName\t\tAddress\t\tCompany\t\tPrice')
data=cur.fetchall()
for i in data:
print(i[0],'\t\t',i[1],'\t\t',i[2],'\t\t',i[3])

print('\n\nmaximum and minimum price for each company.')


cur.execute("select Company,max(Price) from Stationary group by Company")
print('Company\t\tMaxPrice')
data=cur.fetchall()
for i in data:
print(i[0],'\t\t',i[1])

con.close()

OUTPUT
17 Using Python MySQL Connector, execute the following SQL commands on the above student table & display
appropriate message.

i. Add a new attributes - Sec char(3) to the table


ii. UPDATE table to add Sec as A for all class 3 students
iii. ORDER By to display data in descending order
iv. GROUP BY and find the min, max, sum, count and average mark
v. DELETE to remove tuple(s) belonging to class 4

import mysql.connector as sqltor


con=sqltor.connect(host='localhost',user='root',password='123456',database='SHOP')
if con.is_connected():
print('successful')

cur=con.cursor()
cur.execute("alter table student add sec char(3)")
cur.execute("update student set sec='{}' where Class='{}'".format('A','Four'))
# to show details in order by marks desc
cur.execute("select * from student order by mark desc")
data=cur.fetchall()
print('ID\tNAME\t\tCLASS\tMARK\tSEX\tSEC')
for i in data:
print(i[0],'\t',i[1],'\t',i[2],'\t',i[3],'\t',i[4],'\t',i[5])
# group by min,max,sum,avg marks
st="select Class,min(mark),max(mark),sum(mark),avg(mark) from student group by class"
cur.execute(st)
data=cur.fetchall()
print('\n\nClass\tmin(mark)\tmax(mark)\tsum(mark)\tavg(mark)')
for i in data:
print(i[0],'\t',i[1],'\t\t',i[2],'\t\t',i[3],'\t\t',i[4])
# removes tuples of class 4
cur.execute("delete from student where class='Four'")
con.commit()
con.close()

OUTPUT
18.Write a Python code to connect a MySQL database namely SUPERMART and use the following table Items
and Consumer and send SQL commands to the database and retrieve the records based on the queries given
below:
Table: Items
I_ID ItemName Supplier Rate

PP01 Milk AMUL 52

TL02 Bread QUALITY 47

R05 Pastry ITC 75

L03 Sugar NATRAJ 50

P04 Coffee NESCAFE 95

Table: Customers

C_ID CustomerName Address I_ID

5 Ravi Verma Bangalore PP01

9 Aman Sharma Mumbai TL02

15 Mihir Sadhu Chennai L03

17 Naren Sahu Delhi P04

18 Meher Das Mumbai R05

i. To display the details of those customers who purchased Milk.


ii. To display the details of Items supplied by Amul.
iii. To display the Name of the different cities listed in Table Customers
iv. Display details of all customers with their name stating with ‘M’
import mysql.connector as sqltor
con=sqltor.connect(host='localhost',user='root',password='123456',database='SUPERMART')
if con.is_connected():
print('successful')

cur=con.cursor()
cur.execute("SELECT C_ID,CUSTOMERNAME,ADDRESS FROM CUSTOMER,ITEM WHERE
ITEMNAME='MILK' AND ITEM.I_ID=CUSTOMER.I_ID")
data=cur.fetchall()
print('\nC_ID\tCustomerName\tAddress')
for i in data:
print(i[0],'\t',i[1],'\t',i[2])

cur.execute("Select * from item where supplier='AMUL'")


data=cur.fetchall()
print('\nI_ID\tItemName\tsupplier\tRate')
for i in data:
print(i[0],'\t',i[1],'\t\t',i[2],'\t\t',i[3])

cur.execute("select distinct address from customer")


print('\nCities')
data=cur.fetchall()
for i in data:
print(i[0])

cur.execute("select * from customer where customername like 'M%'")


print('\nC_ID\tCustomerName\tAddress\t\tI_ID')
data=cur.fetchall()
for i in data:
print(i[0],'\t',i[1],'\t',i[2],'\t',i[3])

con.close()
OUTPUT
19. Using Python MySQL Connector, create a patient table and insert the following data.
Table: Patient
P_ID P_Name P_History Bill_Amt

P01 Dilip Singh Diabetes 52000

L02 Vidya Ahuja High BP 47000

T05 Dharam Pal Hypo Thyroid 7500

F03 Ved Prakash Diabetes 25000

M04 Adiba Patel Tonsils 9000

Using Python MySQL Connector, execute the following SQL commands on the above patient table
i. Insert a new patient record with details accepted from the user
ii. Change ‘Hypo Thyroid’ to ‘Hyper Thyroid’ for Dharam Pal
iii. Display all records with descending ORDER of their Bill amount
iv. Use GROUP BY and list the patient records based on their patient history.
v. DELETE records for the patients having tonsil.

import mysql.connector as sqltor


con=sqltor.connect(host='localhost',user='root',password='123456',database='SUPERMART')
if con.is_connected():
print('successful')

cur=con.cursor()
# add record
print('Enter record')
P_id=input('Enter Patient ID')
nm=input('Enter patient Name')
his=input('Enter Patient history')
amt=int(input('Enter Bill Amount'))
st="insert into patient(P_ID,P_Name,P_History,Bill_Amt) values('{}','{}','{}',{})".format(P_id,nm,his,amt)
cur.execute(st)
con.commit()
print('rec added\n')
# change hypo thyroid
st="update patient set P_History='{}' where P_Name='{}'"
cur.execute(st.format('HYPER THYROID','DHARAM PAL'))
#records with descending ORDER of their Bill amount
cur.execute("Select * from Patient order by Bill_Amt desc")
print("P_ID\tP_Name\t\tP_History\tBill_Amt")
data=cur.fetchall()
for i in data:
print(i[0],'\t',i[1],'\t',i[2],'\t',i[3])
#patient records based on their patient history.
cur.execute("delete from patient where P_History='TONSILS'")
con.commit()
#whole table
cur.execute("select * from patient")
data=cur.fetchall()
print("P_ID\tP_Name\t\tP_History\tBill_Amt")
for i in data:
print(i[0],'\t',i[1],'\t',i[2],'\t',i[3])
con.close()
ABHIRAM KS XII S2 ROLL NO 03

You might also like