0% found this document useful (0 votes)
61 views70 pages

12 B Cs Tanush

Uploaded by

Tanush goyal
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)
61 views70 pages

12 B Cs Tanush

Uploaded by

Tanush goyal
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/ 70

Computer

Science
Practical
File
NAME – Tanush Goyal
Class – XII-B
INDEX
S.No. Question Type Remarks

1. Program to make a bank management system Nested If -Else

2. Program to obtain percentage of a student and Nested If -Else


assign him grade
3. Program to obtain the values of x and n and Looping
then display the sum of the series
4. Program to obtain a number from the user and Looping
then display all the palindrome up to this
number
5. Program to calculate all the Armstrong Looping
numbers between 0-1000
6. Program to print all prime numbers within a Looping
range
7. Program that prompts the user to input a String
decimal integer and display its binary
equivalent
8. Program to obtain a string and a letter from String
the user and check whether the letter is
present in the string or not and if present then
how much and at which position
9. Program to obtain number of students, their Dictionary
roll number, marks of each from the user and
then store it into a dictionary and print the
following
10. Program to obtain product number, cost of Dictionary
each 4 products from the user and then store it
into a dictionary and print the following:
11. Single Table program to perform the MYSQL
following function
12. Single Table program to perform the MYSQL
following function
13. Single Table program to perform the MYSQL
following function
14. Multiple Table program to perform the MYSQL
following function
15. Multiple Table program to perform the MYSQL
following function
16. Program to obtain a string in a function as an User defined
argument and then calculate total number of function
capital vowels in it and this total number of
vowels is passed to another function pattern()
and to display pattern:
S.No. Question Type Remarks
17. Program to obtain employee number and User defined
salary in dictionary as a key-value pair and function
pass this dictionary as an argument in a
function for some employees of company
depending upon user and then return the
employee number with max salary and also
how many employees are earning below
average salary.
18. Program to have a function which obtain a User defined
number as a argument and return “yes” if it is function
a palindrome number otherwise return “no”.
19. Program to have a user-defined function User defined
compare which obtain 3 integer arguments function
and return the max argument and by how
much from other two numbers
20. Python function named find_max that takes a User defined
list of numbers as a parameter and finds the function
maximum value in the list. The function
should return the maximum value
21. Program to find the second largest number in List Manipulation
a list.
22. Program to reverse the elements of a list List Manipulation
without using the built-in reverse function.
23. Program to find the common elements List Manipulation
between two lists.
24. Program to remove the nth occurrence of a List Manipulation
specified element from a list
25. Program to have a user-defined function Data File Handling
compare which obtain 3 integer arguments Text File
and return the max argument and by how
much from other two numbers and then store
this data in a file compare.txt and in the same
program display the contents of the file.
26. Program to obtain characters from the user till Data File Handling
user enter “-1” & store all capital characters Text File
to “upper.txt”, small letters to “lower.txt”,
digits to “digits.txt” and other characters to
“others.txt”.
27. Menu Driven program to have a binary file Data File Handling
which consists of emp no, emp name and (Module-Pickle)
salary and do the following operations on it- Binary
create, read, modify, search, delete.
28. Program to count no. of records in a csv file- Data File Handling
“products.csv” containing product no.name CSV
and quantity.
29. Write a program, with separate user-defined Stack
functions to perform the following operations
on stack
30 Menu Driven Program of MySQL Python + MySQL
connectivity for adding , updating, deleting connectivity
and displaying the data
Q1 Write a python program to take input of
1. account balance
2. account holder name
3. account type
4. account opening balance for a particular account holder
Now perform the following task:
1. Display a report showing all the details of a account holder in a tabular manner
2. Deposit the money
3. Withdraw the money (minimum balance should be 1000Rs)

Output:
A1
''' Tanush Goyal
12B
'''
acno = int(input("Enter account number: "))
acna = input("Enter account holder name: ")
while True:
acty = input("Enter account type(s/c): ")
if acty == 's' or acty == 'c':
break
else:
print('''
Acount type caan only be --> s or c
Please enter again ''')
while True:
acbal = eval(input("Enter opening balance(min 1000): "))
if acbal >= 1000:
break
else:
print('''
Minimum opening balance is 1000
Please enter again ''')
while True:
print('''
1. Display report
2. Deposit money
3. Withdraw money
4. Exit''')
ask = int(input("Enter the number of task(1,2,3,4) : "))
if ask==1:
print("account number"," ",acno) and print("account holder name"," ",acna)
print("account type"," ",acty) and print("account balance"," ",acbal)
elif ask==2:
dep = eval(input("Enter the amount of money to be deposited: "))
acbal+=dep
print("Account balance = ",acbal)
elif ask==3:
withdraw = eval(input("Enter the amoount of money to withdraw: "))
while True:
if acbal<1000:
print('Your acount balance is less than 1000 please deposit some money')
break
elif withdraw>(acbal-1000):
print("you are withdrawing money more than you account balance - 1000")
break
else:
acbal-=withdraw
print("Successfully done a withdrawl of ",withdraw,"account balance left",acbal)
break
elif ask==4:
break
else:
print("Enter numbers only from 1,2,3,4 ")
Q2 Write a python program to obtain percentage of a student and assign him grade according to
the following criteria
Percentage Grade
80-100 A
60-80 B
40-60 C
<=40 D

Output:
A2

'''
Tanush Goyal
12B
'''
pr= eval(input("Enter your percentage: "))
if pr>80 and pr<=100:
print("A Grade")
elif pr>60 and pr<=80:
print("B Grade")
elif pr>40 and pr<=60:
print("C Grade")
elif pr<=40:
print("D Grade")
Q3 Write a python program to obtain the values of x and n and then display the sum of the
following series:

x – x2/2! + x4/4! -x6/6! ………. xn/n!

Output:
A3

'''
Tanush Goyal
12B
'''

x = eval(input("Enter the value of x: "))


n = int(input("Enter the value of n: "))

sum=0
for i in range(2,n+1,2):
f=1
for j in range(2,i+1):
f*=j
sum += (((-1)**(i-1))*(x**i))/f
print(x+sum)
Q4 Write a python program to obtain a number from the user and then display all the palindrome
up to this number?

Output:
A4

'''
Tanush Goyal
12B
'''

n=int(input("Enter number:"))
for i in range(0,n+1):
temp=i
rev=0
while(i>0):
dig=i%10
rev=rev*10+dig
i=i//10
if(temp==rev):
print(temp)
Q5 Write a python program to calculate all the Armstrong numbers between 0-1000

Output:
A5

'''
Tanush Goyal
12B
'''
print("Armstrong numbers between 0 to 1000: \n")

for num in range(0, 1001):


sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
print(num)
Q6 Write a program to print all prime numbers within a range:

Output:
A6
'''
Tanush Goyal
12B
'''
start = int(input("Enter the starting number: "))
end = int(input("Enter the ending number: "))

print("Prime numbers between", start, "and", end, "are:")

for num in range(start, end + 1):


if num > 1:
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
break
else:
print(num)
Q7 Write a program that prompts the user to input a decimal integer and display its binary
equivalent

Output:
A7

'''
Tanush Goyal
12B
'''

d = float(input("Enter a decimal number: "))


int_part = int(d)
frac_part = d - int_part

b_int = ""
b_frac = ""

while int_part > 0:


r = int_part % 2
b_int = str(r) + b_int
int_part //= 2

while frac_part > 0:


if len(b_frac) >= 10:
break
frac_part *= 2
if frac_part >= 1:
b_frac += "1"
frac_part -= 1
else:
b_frac += "0"

binary = b_int + "." + b_frac

print("Binary equivalent:", binary)


Q8 write a program to obtain a string and a letter from the user and check whether the letter is
present in the string or not and if present then how much and at which position

Output:
A8
'''
Tanush Goyal
12B
'''
a = input("Enter a string: ")
b = input("Enter a letter: ")
l=len(a)
c=0
for i in range(0,l):
if a[i]==b:
print("Found at",i,"the position")
c=c+1
print("Total",c,"times")
Q9 Write a program to obtain number of students, their roll number, marks of each from the user
and then store it into a dictionary and print the following
1. The dictionary
2. Average Marks
3. Total Marks
4. Maximum Marks
Output:
A9
'''
Tanush Goyal
12B
'''

d={}
n=int(input("Enter the number of students: "))
s=mx=0
for i in range(1,n+1):
r=int(input("Enter the roll number: "))
m=int(input("Enter the Marks: "))
d[r]=m
s+=m
if m>mx:
mx=m

print("List of student:",d)
print("Average marks: ",s/n)
print("Total marks: ",s)
print("Maximum marks: ",mx)
Q10 Write a program to obtain product number, cost of each 4 products from the user and then
store it into a dictionary and print the following:
1. Dictionary
2. Average cost
3. Total cost
4. Maximum cost
5. Also ask the user f he wants to add more details of how much products, their number and
their cost and then print the final dictionary
Output:
A10
'''
Tanush Goyal
12B
'''
d={}
a=b=s=0

for i in range(1,5):
n=int(input("Enter product number: "))
c=eval(input("Enter the cost of product: "))
d[n]=c

s+=c

if c>s/4:
b=b+1
elif c<s/4:
a=a+1

print("\n\n")
print("Product details: ",d)
print("Average product cost: ",s/4)
print("Products above average: ",b)
print("Products below average: ",a)
print("\n\n")
new= input("Do you want to add more produts(Y/N): ")

while new=='Y':

n=int(input("Enter product number: "))


c=eval(input("Enter the cost of product: "))
d[n]=c
new= input("Do you want to add more produts(Y/N): ")

print("\n\n")
print("New product detail list: ",d)
Q11 MYSQL
Database name – School , Table name - Book
Bno Bname Subject Author Cost
1 Easy CS CS Vidyapeeth 190
2 MySQL CS NCERT 250
3 Python CS NCERT 500
4 Maths Part 1 Maths NCERT 350
5 Physics English NCERT 246
6 Maths Part 2 Maths 467
7 Cengage 908
8 Chemistry Part 1 Chemistry NCERT 676
9 Chemistry part 2 Chemistry NCERT 765
10 Pharmaceutical Biology 543

Using the above table answer the following questions


1. Display complete information of the books where the author is not given and subject is
Biology or Maths
2. Display Bno Bname and discount (which is 10% of the cost) for the books whose author
is NCERT
3. Insert a new column in the table where the values are (11,Boteny,Biology,456) the author
is not given
4. Display complete info of the books whose cost is between 300 to 800 and the author is
NCERT.
5. Display the bname and cost of the books where the author contains letter E
6. Display complete information of the books where the author is NCERT and is arranged
in ascending order by their cost
7. Display information of the books where the Subject is different
8. Show complete info of all books
9. Remove the column of subject
10. Write a delete the full table
A11
1. Select *
From Book
Where Subject in (“Biology”,”Maths”) and Author is null;

2. Select Bno,Bname,Cost*10/100”Discount”
From Book
Where Author = “NCERT”;

3. Insert into Book(“Bno”,”Bname”,”Subject”,”Cost”)


Values(11,”Boteny”,”Biology”,456);

4. Select *
From Book
Where Author = “NCERT and Cost between 300 and 800;

5. Select Bname , Cost


From Book
Where Author like “%E%”;

6. Select *
From Book
Where Author = “NCERT” order by Cost;

7. Select distinct Subject


From Book;

8. Select *
From Book;

9. Alter table Book


Drop Subject;

10. Drop table Book;


Q12 MYSQL
Database name – Bank , Table name - Manager
Eno Ename Salary Post
1 Rahul Gupta 400000 Assistant Manager
2 Rajesh Kumar 150000 Assistant Clerk
3 Moksh Kumar Gupta 250000 Clerk
4 Daksh Lohchab 550000 Junior Manager
5 Dhruv Gupta 550000 Junior Manager
6 Tanush Goyal 800000 Senior Manager
7 Shubhajeet Pramanic 45000 Cashier
8 Shivam Bansal 25000 Assistant Cashier
9 Shourya Gupta 3000 Sweeper
10 Krishna Sarraf 2000 Sweeper

Using the above table answer the following questions:


1. Display all the information of the employees whose salary is 2000
2. Display all he information of employes with name starting with D and arrange them
according to their salary in ascending order
3. Display distinct information of post of employes
4. Display employee name and the increased salary(10% increase) of all the Managers
5. Insert a new row for the values(11,”Rudraksh Kumar”,”1000”,”Sweeper”)
6. Change the salary of the column with junior managers to 600000
7. Change the post of Shivam Bansal to Cashier with increased salary
8. Delete the row of Shourya Gupta
9. Display total number of employes in each post with Salary equal or above than 1500
10. Display the maximum salary where post is Manager
A12
1. Select *
From Manager
Where salaray = 2000;

2. Select *
From Manager
Where Ename like “D%” order by salary asc;

3. Select distinct Post


From Manager;

4. Select Ename , cost+cost*(1/10)”Increased Salary”


From Manager;

5. Insert into Manager values(11,”Rudraksh Kumar”,”1000”,”Sweeper”)”;

6. Update Manager
Set Salary = 600000
Where Post = “Junior Manager”;

7. Update Manager
Set Post = “Cashier” , Salary = 45000
Where Ename = “Shivam Bansal”;

8. Delete
From Manager
Where Ename = “Shourya Gupta”

9. Select Post
From Manager
Where Salary >= 5000
Group by Post;

10. Select max(Salary)


From Manager
Where Post like “%Manager%”;
Q13 MYSQL
Database Name - Shop , Table Name - Stationery
Sno P_name Price Manufacturer
01 Colours 80 Camlin

02 Pencil 40 Doms
03 Water colours 45 Camlin

04 Gel pen 20 Hauser

05 Colours 95 Faber castle

06 File 30 Lotus

07 Eraser 10 Doms

08 Drawing sheets 25 Pringle

Using the above table to answer the following questions:


1. Display all the info in t he table
2. Display the p_name & price of the all the products having manufacturer as ”camlin”.
3. write a query to increase the price by 10 of all the products.
4. Display all the rows sorted in descending order of price.
5. Remove all the products having price less than 40.
6. Display complete information of all the products having number of characters exactly 6
in their Manufacturer.
7. Add a new row for product with the details : 09,”sketch pens”,30,”doms”.
8. Add two tuples in the table Citizen.
9. Display total number of records of the Product table.
10. Display different types of Manufacturer available in the Citizen table.
A13

1. Select *
From Stationery;

2. Select P_name,Price
from Stationery
where manufacturer = “camlin”;

3. Update stationery
set price = price+10;

4. Select*
from stationery
order by price disc;

5. Delete
from stationery
where price < 40;

6. Select*
from stationery
where manufacturer like “_ _ _ _ _ _ “;

7. Insert into stationery values ( 09 , “ sketch pens “, 30 , “doms” );

8. Insert into stationery values(10,”scale”,20,”doms”);


Insert into stationery values (11,”files”,15,”lotus”);

9. Select count(*)
from stationery;

10. Select distinct manufacturer


from stationery;
Q14 MYSQL
Database Name – School , Table Name - questions
question_id question_text difficulty_level subject chapter

1 What is a database? Easy Computer Science DBMS

2 What is SQL? Easy Computer Science DBMS

3 What is normalization? Medium Computer Science DBMS

4 What is a primary key? Easy Computer Science DBMS

5 What is a foreign key? High Computer Science DBMS

Table Name - answers


answer_id question_id answer_text
1 1 A database is a structured collection of data.

2 2 SQL stands for Structured Query Language.

3 3 Normalization is the process of organizing data.

4 4 A primary key is a unique identifier of a record.

5 5 A foreign key is a reference to a primary key in a table.

Using the above tables to answer the following questions:


1. Write a query to retrieve all questions from the questions table.
2. Write a query to retrieve the question with the highest difficulty level.
3. Write a query to retrieve the subject and chapter for a given question_id.
4. Write a query to retrieve the answer for a specific question.
5. Write a query to retrieve all questions with a difficulty level of "Medium".
6. Write a query to retrieve the number of questions for each difficulty level.
7. Write a query to retrieve the questions along with their answers.
8. Write a query to retrieve the number of questions for each subject.
9. Write a query to retrieve the questions for a specific subject and chapter.
10. Write a query to retrieve the questions that have answers containing letter b.
A14
1. SELECT *
FROM questions;

2. SELECT *
FROM questions
ORDER BY difficulty_level DESC LIMIT 1;

3. SELECT subject, chapter


FROM questions
WHERE question_id = 2;

4. SELECT answer_text
FROM answers
WHERE question_id = 3;

5. SELECT *
FROM questions
WHERE difficulty_level = 'Medium';

6. SELECT difficulty_level, COUNT(*) AS total_questions


FROM questions GROUP BY difficulty_level;

7. SELECT q.question_id, question_text, answer_text


FROM questions q , answers a
Where q.question_id = a.question_id;

8. SELECT subject, COUNT(*)


FROM questions
GROUP BY subject;

9. SELECT *
FROM questions
WHERE subject = ‘Computer Science’ AND chapter = ‘DBMS’;

10. SELECT q.question_id, question_text


FROM questions q , answers a
Where q.question_id = a.question_id and answer_text like “%b%”;
Q15 MYSQL
Database Name – School , Table Name – Students
student_i student_na ag clas sectio
d me e s n
1 John Smith 17 12 A
2 Emma 16 12 B
Johnson
3 Michael Lee 17 12 A
4 Sarah Brown 16 12 C
5 David Miller 16 12 A
Table Name: Grades
student_ subje gra
id ct d
e
1 Math A
2 Scien B
ce
3 Engli A
sh
4 Math C
5 Scien B+
ce

Using the above tables to answer the following questions:


1. Select all students from the Students table.
2. Select the student with student_id 3.
3. Select the students from section A.
4. Select the student names and their corresponding grades.
5. Count the number of students.
6. Get the average age of students.
7. Update the age of student with student_id 4 to 17.
8. Delete the student with student_id 5 from the Students table.
9. Select the students who have scored an A grade in Math.
10. Select the student names and their grades for students in section A.
A15
1. SELECT *
FROM Students;

2. SELECT *
FROM Students WHERE student_id = 3;

3. SELECT *
FROM Students WHERE section = 'A';

4. SELECT Students.student_name, Grades.grade


FROM Students , Grades
WHERE Students.student_id = Grades.student_id;

5. SELECT COUNT(*)
FROM Students;

6. SELECT AVG(age)
FROM Students;

7. UPDATE Students SET age = 17


WHERE student_id = 4;

8. DELETE FROM Students


WHERE student_id = 5;

9. SELECT Students.*
FROM Students,Grades
WHERE Students.student_id = Grades.student_id and Grades.grade = 'A' AND
Grades.subject = 'Math';

10. SELECT Students.student_name, Grades.grade


FROM Students,Grades
WHERE Students.student_id = Grades.student_id and Students.section = 'A';
Q16 Write a program to obtain a string in a function as an argument and then calculate total
number of capital vowels in it and this total number of vowels is passed to another function
pattern() and to display following pattern:
*
**
***……n

Output:
A16
'''
Tanush Goyal
12B
'''
def vowel(a):
l=len(a)
c=0
for i in range(0,l):
if a[i] in 'AEIOU':
c=c+1
print(c)
pattern(c)
def pattern(c):
for i in range(1,c+1):
for j in range(1,i+1):
print("*",end=" ")
print()
x=input("enter a string=")
vowel(x)
Q17 Write a program to obtain employee number and salary in dictionary as a key-value pair and
pass this dictionary as an argument in a function for some employees of company depending
upon user and then return the employee number with max salary and also how many employees
are earning below average salary.

Output:
A17
'''
Tanush Goyal
12B
'''

n=int(input("enter no. of employees="))


dict=dict()
for i in range(1,n+1):
e=int(input("enter employee no.="))
s=int(input("enter salary="))
dict[e]=s
def maxemp(d):
s=0
m=0
mx=0
for i in d:
s+=d[i]
if d[i]>mx:
mx=d[i]
emp=i
avg=s/(i+1)
c=0
for j in d:
if d[j]<avg:
c+=1
return mx,c,emp
max,ba,eno=maxemp(dict)
print("employee with max salary=",eno)
print("max salary=",dict[eno])
print("no. of employees with below average salary=",ba)
Q18 Write a program to have a function which obtain a number as a argument and return “yes” if
it is a palindrome number otherwise return “no”.

Output:
A18
'''
Tanush Goyal
12B
'''
def fun1(num):
r=0
s=0
m=num
while num!=0:
r=num%10
s=s*10+r
num//=10
if s==m:
return "yes"
else:
return "no"
n = int(input("enter a number "))
result=fun1(n)
print("the number is palindrome or not?-",result)
Q19 Write a program to have a user-defined function compare which obtain 3 integer arguments
and return the max argument and by how much from other two numbers

Output:
A19
'''
Tanush Goyal
12B
'''
def compare(a,b,c):
if a>b and a>c:
mx=a
d1=a-b
d2=a-c
elif b>a and b>c:
mx=b
d1=b-a
d2=b-c
elif c>a and c>b:
mx=c
d1=c-a
d2=c-b
return mx,d1,d2
x=int(input("enter num="))
y=int(input("enter num="))
z=int(input("enter num="))
p,q,r=compare(x,y,z)
print("max num=",p)
print("diff 1=",q)
print("diff2=",r)
Q20 Write a Python function named find_max that takes a list of numbers as a parameter and
finds the maximum value in the list. The function should return the maximum value.

Output:
A20
'''
Tanush Goyal
12B
'''
def find_max(numbers):
maximum = numbers[0]
for num in numbers:
if num > maximum:
maximum = num
return maximum

n= int(input("How many numbers: "))


numbers=[]
for i in range(0,n):
no = eval(input("Enter the no: "))
numbers.append(no)
max_value = find_max(numbers)
print("Maximum: ",max_value)
Q21 Write a Python program to find the second largest number in a list.

Output:
A21
'''
Tanush Goyal
12B
'''
my_list = [5, 2, 8, 1, 3]
sorted_list = sorted(my_list, reverse=True)
second_largest = sorted_list[1]
print("Second largest number:", second_largest)
Q22 Write a Python program to reverse the elements of a list without using the built-in reverse
function.
Output:
A22
'''
Tanush Goyal
12B
'''
my_list = [1, 2, 3, 4, 5]
reversed_list = my_list[::-1]
print("Reversed list:", reversed_list)
Q23 Write a Python program to find the common elements between two lists.

Output:
A23
'''
Tanush Goyal
12B
'''
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
common_elements = [element for element in list1 if element in list2]
print("Common elements:", common_elements)
Q24 Write a Python program to remove the nth occurrence of a specified element from a list.

Output:
A24
'''
Tanush Goyal
12B
'''
my_list = [1, 2, 3, 2, 4, 1, 5]
element = 2
occurrence = 2
count = 0
new_list = []
for item in my_list:
if item == element:
count += 1
if count != occurrence:
new_list.append(item)
else:
new_list.append(item)
print("List after removing nth occurrence:", new_list)
Q25-Write a program to have a user-defined function compare which obtain 3 integer arguments
and return the max argument and by how much from other two numbers and then store this data
in a file compare.txt and in the same program display the contents of the file.

Output:
A25
'''
Tanush Goyal
12B
'''
def compare(a,b,c):

if a>b and a>c:

mx=a

d1=a-b

d2=a-c

elif b>a and b>c:

mx=b

d1=b-a

d2=b-c

elif c>a and c>b:

mx=c

d1=c-a

d2=c-b

return mx,d1,d2

x=int(input("enter num="))

y=int(input("enter num="))

z=int(input("enter num="))

p,q,r=compare(x,y,z)

print("max num=",p)

print("diff 1=",q)

print("diff2=",r)

l=[x,y,z]

file=open("compare.txt","w")

for i in range(0,3):

file.write(str(l[i]))

file.write(" \n")

file.write("output:-\n")

file.write("max num:"+str(p)+"\n")

file.write("diff1:"+str(q)+"\n")

file.write("diff2:"+str(r)+"\n")

file.close()

g=open("compare.txt")

print("contents of file")

pr=g.read()
print(pr)
Q26-Write a program to obtain characters from the user till user enter “-1” & store all capital
characters to “upper.txt”,small letters to “lower.txt”, digits to “digits.txt” and other characters to
“others.txt”.

Output-
A26
'''
Tanush Goyal
12B
'''
up=open("upper.txt","w")
low=open("lower.txt","w")
dig=open("digits,txt","w")
ot=open("others.txt","w")
while True:
n=input("enter character=")
if n=="-1":
break
elif n>="A" and n<="Z":
up.write(n)
elif n>="a" and n<="z":
low.write(n)
elif n.isdigit():
dig.write(n)
else:
ot.write(n)
up.close()
low.close()
dig.close()
ot.close()
print("values entered in files")
Q27-Write a menudriven program to have a binary file which consists of emp no, emp name and
salary and do the following operations on it- create,read,modify,search,delete.

Output-
A27

import pickle

'''
Tanush Goyal
12B
'''

def add(f):

n=int(input("Enter the number of employees to add : "))

file=open(f,"wb+")

s=[]

for i in range(1,n+1):

empno=int(input("Enter employee number : "))

name=input("Enter employee Name : ")

sal=int(input("Enter your salary : "))

s.append([empno,name,sal])

pickle.dump(s,file)

file.close()

print("Records added successfully")

def read(f):

file=open(f,"rb+")

data=pickle.load(file)

print(data)

file.close()

def modify(f):

file=open(f,"rb+")

name=input("Enter the name of the employee : ")

data=pickle.load(file)

for i in data:

if i[1]==name:

i[0]=int(input("Enter the new employee number : "))

i[2]=int(input("Enter the new salary : "))

file.seek(0)

pickle.dump(data,file)

file.close()

print("Data updation successful")

def search(f):

file=open(f,"rb+")

data=pickle.load(file)

a=int(input("Enter the lower salary :"))

b=int(input("Enter the Higher salary :"))


for i in data:

if i[2]>=a and i[2]<=b:

print(i[1])

file.close()

def delete(f):

file=open(f,"rb+")

data=pickle.load(file)

empno=int(input("Enter a employee number to delete : "))

s=[]

print(data)

for i in data:

if i[0]!=empno:

s.append(i)

print(s)

file.seek(0)

pickle.dump(s,file)

file.close()

print("Deletion successful")

ch='y'

while ch=='y' or ch=='Y':

print("1) Adding a record to the binary file")

print("2) Read the binary File")

print("3) Modify a record")

print("4) Search for record from a range of salary")

print("5) Delete a record")

choice=int(input("Enter you choice : "))

f=input("Enter the name of your file : ")

if choice==1:

add(f)

elif choice==2:

read(f)

elif choice==3:

modify(f)

elif choice==4:

search(f)

elif choice==5:

delete(f)

else:

print("Invalid input")
ch=input("Do you want to continue?(Y/N)")

Q28-Write a program to count no. of records in a csv file- “products.csv” containing product
no.,name and quantity.

Output-
import csv
'''
Tanush Goyal
12B
'''
file=open("products.csv","r")
data=csv.reader(file)
c=0
for i in data:
c+=1
print("the no. of records are",c)
file.close()
Q29-Vedika has created a dictionary containing names and marks as key-value pairs of 5
students. Write a program, with separate user-defined functions to perform the following
operations:
1. Push the keys (name of the student) of the dictionary into a stack, where the
corresponding value (marks) is greater than 70.
2. Pop and display the content of the stack.
Dictionary is : d={"Ramesh":58, "Umesh":78, "Vishal":90, "Khushi":60, "Ishika":95}

Output-
'''
Tanush Goyal
12B
'''
def push(stk,item):
stk.append(item)

def Pop(stk):
if stk==[]:
return None
else:
return stk.pop()
stk=[]
d={"Ramesh":58, "Umesh":78, "Vishal":90, "Khushi":60, "Ishika":95}
for i in d:
if d[i]>70:
push(stk,i)

while True:
if stk!=[]:
print(Pop(stk),end=" ")
else:
break
Q30 Write a python connectivity program to create a menu driven program performing addition ,
updating ,deletion and displaying of all the data in the table .
Host – localhost
User – root
Password – root
Database – school
Table structure – id: integer, primary key
- name character
- age integer
Output:
A30 import mysql.connector

db = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="school"
)

def insert_data():
student_id = int(input("Enter student ID: "))
name = input("Enter name: ")
age = int(input("Enter age: "))
cursor = db.cursor()
query = "INSERT INTO students VALUES (%s, %s, %s)"
values = (student_id,name, age)
cursor.execute(query, values)
db.commit()
print("Data inserted successfully!")

def update_data():
student_id = int(input("Enter student ID: "))
ask = input("Want to edit name(n) or age(a) or both(b): ")

if ask=="n" or ask=="N":
new_name = input("Enter new_name: ")
cursor = db.cursor()
query = "UPDATE students SET name = %s WHERE id = %s"
values = (new_name, student_id)
cursor.execute(query, values)
db.commit()
elif ask=="a" or ask=="A":
new_age = int(input("Enter new age: "))
cursor = db.cursor()
query = "UPDATE students SET age = %s WHERE id = %s"
values = (new_age, student_id)
cursor.execute(query, values)
db.commit()
elif ask=="b" or ask=="B":
new_age = int(input("Enter new age: "))
new_name = input("Enter new_name: ")
cursor = db.cursor()
query = "UPDATE students SET age = %s , name = %s WHERE id = %s"
values = (new_age, new_name, student_id)
cursor.execute(query, values)
db.commit()

print("Data updated successfully!")

def display_data():
cursor = db.cursor()
query = "SELECT * FROM students"
cursor.execute(query)
result = cursor.fetchall()
for row in result:
print(f"ID: {row[0]}, Name: {row[1]}, Age: {row[2]}")
while True:
print("\nMenu:")
print("1. Insert Data")
print("2. Update Data")
print("3. Display Data")
print("4. Quit")

choice = int(input("Enter your choice: "))

if choice == 1:
insert_data()
elif choice == 2:
update_data()
elif choice == 3:
display_data()
elif choice == 4:
print("Goodbye")
break
else:
print("Invalid choice. Please select a valid option.")

You might also like