0% found this document useful (0 votes)
11 views33 pages

Shreyapro

The document contains 14 computational questions and their solutions involving Python programming concepts like functions, lists, files handling, sorting, searching etc. The questions cover topics like creating and reading text and binary files, defining functions to perform tasks like displaying odd/even numbers from a list, checking if a number is prime, calculating factorial, sorting lists etc. Functions are also defined to search records from binary files, add/display records in csv/binary files. Overall the document demonstrates the student's understanding of various Python programming concepts through well written solutions to sample problems.

Uploaded by

aishwary0212
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views33 pages

Shreyapro

The document contains 14 computational questions and their solutions involving Python programming concepts like functions, lists, files handling, sorting, searching etc. The questions cover topics like creating and reading text and binary files, defining functions to perform tasks like displaying odd/even numbers from a list, checking if a number is prime, calculating factorial, sorting lists etc. Functions are also defined to search records from binary files, add/display records in csv/binary files. Overall the document demonstrates the student's understanding of various Python programming concepts through well written solutions to sample problems.

Uploaded by

aishwary0212
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

LAKHIMPUR –KHERI

Class –XII

Session: 2021-22
COMPUTER(083)
REPORT FILE

NAME : ANISHA DUBEY

CLASS : XII

BOARD ROLL NO. 23676941

TEACHER’S SIGNATURE : ……………………….


Q1.Write a Program to Input 10 numbers and Create a list Print allOdd
Numbers Present in the list.

def display_list(alist):
length = len(alist)
for i in range(0,length):
if alist[i]%2!=0:
print(alist[i],'\t',end='')
#_main_
alist=[]
for i in range(0,10):
value=int(input('enter the value:'))
alist.append(value)
display_list(alist)

OUTPUT

enter the value: 2


enter the value: 17
enter the value: 56
enter the value: 23
enter the value: 46
enter the value: 87
enter the value: 98
enter the value: 47
enter the value: 85
enter the value: 4
17 23 87 47 85
Q2.Write a Program using User Defined Function to check and
Display Whether the Entered Number is Prime or not.
def display_prime(number):
flag=False
for i in range(2,number):
if number%i==0:
flag=True
break
if flag==False:
print(number,'is prime number')
else:
print(number,’is not a prime \
number’)
#_main_
number= int(input('enter a number \
to be checked’))
display_prime(number)

OUTPUT
enter a number to checked
13 13 is a prime number

enter a number to checked


26 26 is not a prime number
Q3.Write a Program using Function, to Input an Integer and Print its
Factorial using While Loop.
def display_factorial(number):
count=1
fact=1
while count<=number:
fact=fact*count
count=count+1
print('factorial of', number,'=',fact)
#_main_
number= int(input('enter a number '))
display_factorial(number)

OUTPUT
enter a number 5
factorial of 5 =
120

enter a number 0
factorial of 0 = 1
Q4. Write a Program Using User Defined Function to Create a text
file “Para.txt”. Write another Function to Display each Words
present in the file”Para.txt” , also print number of words present in
the file.

def create_file():
f1=open("para.txt","w")
f1.write("Take umbrella and raincoat\
when it rains\n")
f1.write("We all should enjoy
the\
monsoon")
f1.close()
def read_file():
f1=open("para.txt","r")
data=f1.read()
word=data.split()
count=0
for i in word:
print(i)
count+=1
print('No of words present in the file:',count)
f1.close()
#_main_
create_file()
read_file()
OUTPUT

Take
umbrella
and
raincoat
when
it
rains
We
all
should
enjoy
the
monsoon
No of words present in the file: 13
Q5.Write the functions for the following:
a) Create a file “alphabets.txt”,and write data into it.
b) Read the data from file and count the number of vowels
and consonants present in each word.

def create_file():
f1= open("alphabets.txt","w")
f1.write("Take umbrella and raincoats\
when it rains")
f1.close()
def count():
f1=open("alphabets.txt","r")
data=f1.read()
word=data.split()
print("WORDS\tNO.OF VOWELS\tNO.OF
CONSONANTS")
for i in word:
c_count,v_count=0,0
for j in i:
if j in"AEIOU" or j in"aeiou":
v_count+=1
else:
c_count+=1 print(i,"\
t",v_count,"\t\t",c_count)
f1.close()
#_main_
create_file()
count()
OUTPUT
WORDS NO.OF VOWELS NO.OF CONSONANTS
Take 2 2
umbrella 3 5
and 1 2
raincoats 4 5
when 1 3
it 1 1
rains 2 3
Q6.Write a user defined function to arrange the list in ascending
order by method of bubble sort.

def bubble_sorting(list):
length=len(list)
for i in range(0,length):
for j in range(0,length-i-1):
if list[j]>list[j+1]:
temp=list[j]
list[j]=list[j+1]
list[j+1]=temp
print('SORTED LIST')
print(list)
#_main_
num=[]
N=int(input('ENTER NO. OF ELEMENTS TO\
BE ENTERED IN THE LIST'))
for i in range(0,N):
value=int(input('ENTER VALUE TO
BE\
ENTERED IN THE LIST'))
num.append(value)
bubble_sorting(num)
OUTPUT
ENTER NO. OF ELEMENTS TO BE ENTERED IN THE LIST7
ENTER VALUE TO BE ENTERED IN THE LIST2
ENTER VALUE TO BE ENTERED IN THE LIST256
ENTER VALUE TO BE ENTERED IN THE LIST95
ENTER VALUE TO BE ENTERED IN THE LIST451
ENTER VALUE TO BE ENTERED IN THE LIST95
ENTER VALUE TO BE ENTERED IN THE LIST25
ENTER VALUE TO BE ENTERED IN THE LIST58
SORTED LIST
[2, 25, 58, 95, 95, 256, 451]
Q7.Write a program for insertion sorting.

def insertionsort(arr):
l=len(arr)
for i in range(1,l):
value=arr[i]
j=i-1
while j>=0 and value<arr[j]:
arr[j+1]=arr[j]
j-=1
arr[j+1]=value
#_main_
num=[10,25,75,4,94,28,5]
insertionsort(num)
print('sorted list')
for i in range(0,len(num)):
print(num[i],end=' ')

OUTPUT
sorted list
4 5 10 25 28 75 94
Q8. Write a Program using Function to Create a List of Sorted
Numbers. Enter a Number check that the Number is Present in the
list or not using method of Binary search.
def bin_search(ar,key):
low=0
high=len(ar)-1
while low<=
high:
mid=int((low+high)/2)
if key==ar[mid]:
return mid
elif key<ar[mid]:
high=mid-1
else:
low=mid+1
else:
return -1
#_main_
ar=[]

n=int(input('enter no of elements'))
for i in range (0,n):
value=int(input('enter value'))
ar.append(value)
item=int(input('enter search item:'))
res=bin_search(ar,item)
if res>=0:
print(item,'found at index',res)
else:
print(item,'not found in array')
OUTPUT

enter no of elements5
enter value13
enter value56
enter value65
enter value78
enter value87
enter search item:65
65 found at index 2

enter no of elements5
enter value12
enter value34
enter value45
enter value54
enter value67
enter search item:60
60 not found in array
Q9.Write a user defined function to create a binary file “stud.dat”,
add the records in the file depending on the user’s choice.

import pickle
def writefile():
f1=open("stud.dat","wb")
ch='y'
rec=[]
while ch=='y':
roll=int(input("enter roll no"))
name=input("enter name")
mark=int(input("enter marks"))
rec=[roll,name,mark]
pickle.dump(rec,f1)
ch=input("Do you want to add any \
more record(y/n"))
f1.close()
#_main_
writefile()
OUTPUT
enter roll no1
enter nameAYUSH
enter marks98
Do you want to add any more recordy
enter roll no2
enter nameDEEPAK
enter marks87
Do you want to add any more recordy
enter roll no3
enter nameHARSHIT
enter marks85
Do you want to add any more record (y/n) n
Q10.Write a user defined function to read the content of binary file
“stud.dat” and print the data present in the file.

import pickle
def readfile():
f1=open("stud.dat","rb")
rec=[]
try:
while True:
rec=pickle.load(f1)
print(rec)
except EOFError:
f1.close()
#_main_
readfile()

OUTPUT
[1, 'AYUSH', 98]
[2, 'DEEPAK', 87]
[3, 'HARSHIT', 85]
Q11.Write a user defined function to search and display the record
of a given roll number from binary file “stud.dat”.
import pickle
def search_file():
found=False
f1=open("stud.dat","rb")
rec=[]
sroll=int(input("enter roll no to be \
searched"))
try:
while True:
rec=pickle.load(f1)
if rec[0]==sroll:
print(rec)
found=True
except EOFError:
if found==True:
print("Record found")
else:
print("record not found")
f1.close()
#_main_
search_file()

OUTPUT

enter roll no to be searched3


[3, 'HARSHIT', 85]
Record found
enter roll no to be searched0
record not found
Q12.Write functions for the following:
a) To add record in the binary file “lib.dat”.
b) To display the record from binary file “lib.dat”.
import pickle
def write_file():
f1=open("lib.dat","wb")
book=[]
ch='y'
while ch=='y':
bno=int(input("enter book no"))
name=input("enter book name")
price=float(input("enter price"))
book=[bno,name,price]
pickle.dump(book,f1)
ch=input("do you want to add any\
more record")
f1.close()
def display_file():
f1=open("lib.dat","rb")
book=[]
try:
while True:
book=pickle.load(f1)
print(book)
except EOFError:
f1.close()
#_main_
write_file()
display_file()
OUTPUT
enter book no587
enter book nameMODERN ABC
enter price1200
do you want to add any more recordy
enter book no588
enter book nameCOMPUTER SCIENCE WITH PYTHON
enter price1000
do you want to add any more recordy
enter book no589
enter book nameSL ARORA
enter price1300
do you want to add any more recordn

[587, 'MODERN ABC', 1200.0]


[588, 'COMPUTER SCIENCE WITH PYTHON', 1000.0]
[589, 'SL ARORA', 1300.0]
Q13.Write a user defined function to search details of the book
whose book no. is entered by the user.

import pickle
def read_file():
f1=open("lib.dat","rb")
book=[]
bns=int(input("Enter book no to be\
search"))
found=False
try:
while True:
book=pickle.load(f1)
if bns==book[0]:
print(book)
found=True
except EOFError:
if found==True:
print("Record found")
else:
print("Record not found")
f1.close()
#_main_
read_file()

OUTPUT
Enter book no to be search587
[587, 'MODERN ABC', 1200.0]
Record found
Enter book no to be search290
Record not found
Q14. Write the functions for the following:
a) To add record in the csv file “exam.csv”.
b) To display the record from csv file “exam.csv” if mark
is more than 90.

import csv
def write_file():
with open('EXAM.CSV','w',) as f1:
filewriter=csv.writer(f1)
filewriter.writerow(['Roll','Name',\
'Marks
ch='y'
while ch=='y' or ch=='Y':
roll=int(input('enter roll no'))
name=input('enter name')
marks=int(input('enter marks'))
record=[roll,name,marks]
filewriter.writerow(record)
ch=input('Do you want to add \
anymore record:')
def read_file():
with open('EXAM.CSV','r',newline='\n')\
as f1:
filereader=csv.reader(f1)
next(filereader)
for row in filereader:
if int(row[2])>=90:
print(row)
f1.close()
#_main_
write_file()
read_file()

OUTPUT
enter roll no1
enter nameARPIT
enter marks95
Do you want to add anymore record:y
enter roll no2
enter nameSURAJ
enter marks90
Do you want to add anymore record:N

['1', 'ARPIT', '95']


['2', 'SURAJ', '90']
Q15.Write a user defined function to print details of the student
whose marks are greater than 90 and less than or equal to 100 from
a csv file “EXAM.CSV”.
def read_file():
with open('EXAM.CSV','r') as f1:
filereader=csv.reader()
next(filereader)
for row in filereader:
if int(row[2]>90 and row[2]<=100):
print(row)
f1.close()
#_main_
read_file()

OUTPUT
[‘1’,’ARPIT’,’95’]
Q16. Program showing,adding,deleting elements according to
user's choice in a stack?

stack=[]
top=-1
def choice_input():
print("enter your choice")
ch=int(input("enter choice"))
return ch
def push_ele(stack,top):
rollno=int(input("enter roll no"))
marks=int(input("enter marks"))
element=(rollno,marks)
stack.append(element)
top=top+1
return top
def show_ele(stack,top):
i=top
while(i>=0):
print(stack[i])
i=i-1
def pop_ele(stack,top):
element=stack.pop()
top=top-1
print("value deleted from stack",element)
return top
while True:
print("1=add a new element")
print("2=display the elements")
print("3=delete an element")
print("4=quit")
choice=choice_input()
if choice==1:
while True:
top=push_ele(stack,top)
print("do u want to add more element")
cho=input("enter choice y/n")
if cho=="n":
break
if choice==2:
show_ele(stack,top)
if choice==3:
top=pop_ele(stack,top)
if choice==4:
break
print("do u want more")
OUTPUT
1=add a new element
2=display the elements
3=delete an element
4=quit
enter your choice
enter choice1
enter roll no25
enter marks94
do u want to add more element
enter choice y/nn
1=add a new element
2=display the elements
3=delete an element
4=quit
enter your choice
enter choice4
do u want more
Q17.Create table club by using interface between python and
mysql.

import mysql.connector as abc


mydb=abc.connect(host='localhost',\
userame='root',passwd='abc@123',\
database='mydatabase')
mycursor=mydb.cursor()
if mydb.is_connected():
print('Successfully Connected to\
Database')
Query="CREATE TABLE CLUB\
(Coach_Id INT(5) NOT NULL,\
CoachName VARCHAR(50) NOT
NULL,Age INT(3),\
Sports VARCHAR(50),\
Dateofapp DATE ,\
Pay FLOAT(10,2),Gender CHAR(1))"
mycursor.execute(Query)
Query2='DESCRIBE CLUB'
mycursor.execute(Query2)
for data in mycursor:
print(data)
OUTPUT
Successfully Connected to Database
('Coach_Id', 'int(5)', 'NO', '', None, '')
('CoachName', 'varchar(50)', 'NO', '', None, '')
('Age', 'int(3)', 'YES', '', None, '')
('Sports', 'varchar(50)', 'YES', '', None, '')
('Dateofapp', 'date', 'YES', '', None, '')
('Pay', 'float(10,2)', 'YES', '', None, '')
('Gender', 'char(1)', 'YES', '', None, '')

Field Type Null Key Default Extra


Coach_id Int (5) No NULL
Coachname Varchar (50) No NULL
Age Int (3) YES NULL
Sports Varchar (50) YES NULL
Dateofapp Date YES NULL
Pay Float (10,2) YES NULL
Gender Char (1) YES NULL
Q18.Write a program to add 5 records in the table club using
python and mysql interface.

import mysql.connector as abc


mydb=abc.connect(host='localhost',username='root',\
passwd='abc@123',database='mydatabase')
mycursor=mydb.cursor()
if mydb.is_connected():
print('Successfully Connected to Database')
Record1='INSERT INTO CLUB\
VALUES(1,"KUKREJA",35,
\"KARATE",\
"1997-02-25",1000,"M")'
Record2='INSERT INTO CLUB\
VALUES(2,"RAVINA",34,\
"KARATE",\
"1996-02-20",1200,"F")'
Record3='INSERT INTO CLUB\
VALUES(3,"ROHIT",25,\
"SWIMMING",\
"2000-10-05",1500,"M")'
Record4='INSERT INTO CLUB \
VALUES(4,"VIRAT",32,\
"CRICKET",\
"1998-08-10",2000,"M")'
Record5='INSERT INTO CLUB \
VALUES(5,"SINDHU",30,\
"BADMINTON",\
"1995-12-14",1750,"F")'
mycursor.execute(Record1)
mycursor.execute(Record2)
mycursor.execute(Record3)
mycursor.execute(Record4)
mycursor.execute(Record5)
mydb.commit()
mycursor.execute(‘SELECT * FROM CLUB’)
for data in mycursor:
print(data)

OUTPUT
Successfully Connected to Database
(1, 'AJAY SWAROOP', 35, 'KARATE', datetime.date(1997, 2, 25),
1000.0, 'M')
(2, 'RAVINA', 34, 'KARATE', datetime.date(1996, 2, 20), 1200.0, 'F')
(3, 'ROHIT', 25, 'SWIMMING', datetime.date(2000, 10, 5), 1500.0,
'M')
(4, 'VIRAT', 32, 'CRICKET', datetime.date(1998, 8, 10), 2000.0, 'M')
(5, 'SINDHU', 30, 'BADMINTON', datetime.date(1995, 12, 14), 1750.0,
'F')
Q19.Write a program to print all records from the table club where
pay>=1500.

import mysql.connector as abc


mydb=abc.connect(host='localhost',\
username='root',\
passwd='abc@123',\
database='mydatabase')
mycursor=mydb.cursor()
if mydb.is_connected():
print('Successfully Connected to\
Database')
Query='SELECT * FROM CLUB WHERE\
Pay>=1500'
mycursor.execute(Query)
for data in mycursor:
print(data)

OUTPUT
Successfully Connected to Database
(3, 'ROHIT', 25, 'SWIMMING', datetime.date(2000, 10, 5), 1500.0,
'M')
(4, 'VIRAT', 32, 'CRICKET', datetime.date(1998, 8, 10), 2000.0, 'M')
(5, 'SINDHU', 30, 'BADMINTON', datetime.date(1995, 12, 14), 1750.0,
'F')
Q20.Write a program using python and mysql interface to update
record in the table club.

import mysql.connector as abc


mydb=abc.connect(host='localhost',\
username='root', passwd='abc@123',\
database='mydatabase')
mycursor=mydb.cu
rsor()if
mydb.is_connecte
d():
print('Successfully Connected to Database')
Query='UPDATE CLUB SET
CoachName=\"AJAY
SWAROOP" WHERE\
CoachName="KUK
REJA"'
mycursor.execute(Query)
mydb.commit()

Coach_Id CoachName Age Sports Dateofapp Pay Gend


er
1 AJAY 35 KARATE 1997-2-25 1000.00 M
SWAROOP
2 RAVINA 34 KARATE 1996-2-20 1200.00 F
3 ROHIT 25 SWIMMING 2000-10-5 1500.00 M
4 VIRAT 32 CRICKET 1998-8-10 2000.00 M
5 SINDHU 30 BADMINTON 1995-12-14 1750.00 F
Q21.Write a program uing python and mysql interface to print all
records from the table club order by name.

import mysql.connector as abc


mydb=abc.connect(host='localhost',username='root',passwd='abc@
123',\
database='mydatabase')
mycursor=mydb.cursor()
if mydb.is_connected():
print('Successfully Connected to Database')
Query='SELECT * FROM CLUB ORDER BY CoachName'
mycursor.execute(Query)
for data in mycursor:
print(data)

OUTPUT
Successfully Connected to Database
(1, 'AJAY SWAROOP', 35, 'KARATE', datetime.date(1997, 2, 25),
1000.0, 'M')
(2, 'RAVINA', 34, 'KARATE', datetime.date(1996, 2, 20), 1200.0, 'F')
(3, 'ROHIT', 25, 'SWIMMING', datetime.date(2000, 10, 5), 1500.0,
'M')
(5, 'SINDHU', 30, 'BADMINTON', datetime.date(1995, 12, 14), 1750.0,
'F')
(4, 'VIRAT', 32, 'CRICKET', datetime.date(1998, 8, 10), 2000.0, 'M')

You might also like