Professional Documents
Culture Documents
Abhiram KS Xii S2 Roll No 03
Abhiram KS Xii S2 Roll No 03
SCIENCE
JOURNAL
BY ABHIRAM KS
CLASS XII S2
ROLL NO : 03
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 & 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 & store them into a list
ii. To accept a no & find its position in the list using Linear Search method
iii. To accept a no & 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 & highest Number from the Tuple (without using any in-built
function)
iii. To find sum & 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 & 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)
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
Table: Consumer
con.close()
OUTPUT
17 Using Python MySQL Connector, execute the following SQL commands on the above student table & display
appropriate message.
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
Table: Customers
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])
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
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.
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