0% found this document useful (0 votes)
10 views35 pages

Aditya Kumar Shukla

The document contains a series of programming exercises and solutions primarily in Python and SQL. It includes tasks such as writing functions for array manipulation, database connectivity, file handling, and various algorithms. Each exercise is followed by code snippets and their outputs, demonstrating the expected results of the implementations.

Uploaded by

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

Aditya Kumar Shukla

The document contains a series of programming exercises and solutions primarily in Python and SQL. It includes tasks such as writing functions for array manipulation, database connectivity, file handling, and various algorithms. Each exercise is followed by code snippets and their outputs, demonstrating the expected results of the implementations.

Uploaded by

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

Aditya Kumar

Shukla
guidance, monitoring and constant
encouragement throughout the course of this
learning.
VISHAL YADAV XII-F

INDEX
S. PROGRAM T. SIGN
No
Q1) Write a python code for a
function(t,n), which repositions
all the elements of array by
shifting each of them to next
position and shifting element to
last position
Q2) write a function SWAP2BEST
(ARR, Size) in python to modify
the content of the list in such a
way that the elements , which
are multiples of 10 swap with
the value present in the very
next position in the list.

Q3) WAP a program to find the


number of lines starting with ‘F’
in firewall.txt.
Q4) write a definition for a function
economic() to read each record
of a binary file ITEMS.DAT, find
and display those items which
cost less than 2500.

Q5) Write the definition of a


member function PUSH() in
python to add a new book in a
dynamic stack of BOOKS
considering the following code
is already included in the
program: ISBN, TITLE.

Q6) Write a function in python


POP(Arr), where Arr is a stack
implemented by a list of
numbers. The function returns
the value deleted from the
stack.

Q7) Write a Mysql-Python


connectivity code display
ename, empno , designation,
sal of those employees whose
salary is more than 3000 from
the table emp. Name of the
database is”Emgt”.
Q8) WAP to show entered string is
palindrome or not.
Q9) WAP to remove all odd numbers
from the given list.

Q10) Write a program to display


frequencies of all the element of
a list.
Q11) Write a python function to
perform push operation in a
dynamically allocated stack.
Q12) Write a program to display and
delete element from a queue.
Q13) Write a program to check
whether the MySQL database is
connected to python not.
Q14) To display longest line in text
file.
Q15) create a csv file with roll no,
name, marks of students.
Q16) WAP to find the highest
common factor (HCF) of two
numbers.
Q17) Program using FETCHONE

Q18) Program using rowcount


Q19) WAP to bubble sort a particular
list in ascending order.
Q20) WAP traversing a 2D List.

Q21) Find the output of the following


code.

Q22) Write a python program to


create the tuple
(‘a’,’bb’,’ccc’,’dddd’…….) that
ends with 26 copies of the letter
Z.

#Program1: write a code in python for a function


convert(T,N),which repositions all the elements of array
by shifting each of them to next position and shifting
element to last position.

def Convert(T,N):
t=T[0]
for i in range(N-1):
T[i]=T[i+1]
T[N-1]=t
print("after conversion",T)
d=[34,38,43,51]
print("Original List",d)
r=len(d)
Convert(d,r)

#OUTPUT:
Original List [34, 38, 43, 51]
after conversion [38, 43, 51, 34]

#Program2: write a function SWAP2BEST (ARR, Size)


in python to modify the content of the list in such a way
that the elements, which are multiples of 10 swap with
the value present in the very next position in the list.

def SWAP2BEST(A,size):
i=0
while(i,size):
if(A[i]%10==0):
A[i],A[i+1]=A[i+1],A[i]
i=i+2
else:
i=i+1
return(A)
d=[90,56,45,20,34,54]
print("actual list",d)
r=len(d)
print("after swapping",SWAP2BEST(d,r))
#OUTPUT:
Actual list[90,56,45,20,34,54]
After swapping[56,90,45,34,20,54]

#Program3: WAP a program to find the number of lines


starting with ‘F’ in firewall.txt.
F=open(r”C:\Users\hp\Desktop\cs\networking\firewall.txt”)
C=0
For i in f.readline():
If(i==’F’):
C=c+1
Print(c)

#OUTPUT:
1

#Program4: write a definition for a function economic()


to read each record of a binary file ITEMS.DAT, find and
display those items which cost less than 2500.

def Economic():
f1=open("items.dat","ab")
while true:
try:
g=pickle.load(f1)
if(g['cost']<250):
print(g)
except:
break
Economic()

#OUTPUT:
Enter gift name flowers
Enter id 2
Enter cost 500
{‘giftname’ :’ flowers’,’id’:2,’cost’:500.0}

#Program5: Write the definition of a member function


PUSH () in python to add a new book in a dynamic stack
of BOOKS considering the following code is already
included in the program: ISBN, TITLE.

s=[]
def push():
a=int(input("enter ISBN no"))
t=input("enter title")
I=[a,t]
s.append(I)
def disp(s):
if(s==[]):
print("list is empty")
else:
top=len(s)-1
print(s[top],"---top")
for i in range(top-1,-1,-1):
print(s[i])
push()
disp(s)

#OUTPUT:
Enter ISBN no 2
Enter title Encyclopedia
[2,’Encyclopedia’] ---top

#Program 6: Write a function in python POP(Arr), where


Arr is a stack implemented by a list of numbers. The
function returns the value deleted from the stack.

def POP(Arr):
if (len(st)>0):
r=st.pop()
return r
else:
print("stack empty")

#OUTPUT:
Blank

#Program 7: Write a Mysql-Python connectivity code


display ename, empno , designation, sal of those
employees whose salary is more than 3000 from the
table emp. Name of the database is”Emgt”.
import mysql.connector as m
db=m.connect(host="localhost",user="root",passwd="1234",database="Emgt")
c=db.cursor()
c.execute("select *from emp where sal>3000")
r=c.fetchall()
for i in r:
print(i)

#Program 8: WAP to show entered string is palindrome


or not.

def ispalindrome(x):
k=str(x)
I=k[::-1]
if k==I:
print("it is a palindrome")
else:
print("not a palindrome")
x=input("enter next string")
ispalindrome(x)

#OUTPUT:
it is a palindrome
enter next stringswsss
not a palindrome
enter next stringqwer
not a palindrome
#Program 9: WAP to remove all odd numbers from the
given list.
def removeodd(x):
y=[]
for i in x:
if i%2!=0:
k=x.pop(x.index(i))
y.append(k)
else:

pass
print(x)

#OUTPUT:
Remove odd([10,45,88,98,88,100])
[45,98,100]

#Program 10: Write a program to display frequencies of


all the element of a list.
def countitem(x,y):
#x=list entered by user
#y=element whose occurences are to be counted
k=x.count(y)
print(k)

#Program 11: Write a python function to perform push


operation in a dynamically allocated stack.
stk=[]

def pushin():
a=int(input("enter x"))
b=int(input("enter y"))
I=[a,b]
st.append(I)

#OUTPUT:
Pushin()
Enter x1
Enter y2
Stk
[[1,2]]

#Program 12: Write a program to display and delete


element from a queue.
que=[]
def pop():
que.pop(0)
def display():
if len(que)==0:
print("empty queue")
else:
print(que)
#Program 13: Write a program to check whether the
MySQL database is connected to python not.

'''import mysql.connector as con

mycon=con.connect(host="127.0.0.1",user="root",passwd="5971",database="
my school")

#connection check
if mycon.is_connected():
print("connectiion successful")
else:
print("not successful")

#OUTPUT:
Connection successful

#Program 14: To display longest line in text file.

file=open('helloworld.txt','r')
line1=file.readline()
a=len(line1)
for i in file:
line=file.readline()
x=len(line)
if x>a:
print(line)
file.close()

#OUTPUT:
This line is the longest line

#Program 15: create a csv file with roll no, name, marks
of students.

import csv
f=open("Student.csv","w",newline='')
s_writer=csv.writer(f,defaulter=';')
s_writer.writerow(['roll no','name','marks'])
rec=[]
while True:
r=int(input("enter roll no:"))
n=int(input("enter marks:"))
lst=[r,n,m]
rec.append(lst)
ch=input("do you want to enter more records?(y/n)")
if ch=='n':
break
for i in rec:
s_writer.writerow(i)
f.close()

#OUTPUT:

Roll no;name;marks
1;arnav;99
2;amit;97

#Program 16: WAP to find the highest common factor


(HCF) of two numbers.
def HCF(x,y):
if x>y:
smaller=y
else:
smaller=x
for i in range(1,smaller+1):
if((x%i==0)and(y%i==0)):
hcf=i
return hcf
num1=int(input("enter fist number"))
num2=int(input("enter second number"))
print("The HCF of of",num1,"and",num2,"is",HCF(num1,num2))

#OUTPUT:
Enter first number: 7
Enter second number: 21
The HCF of 7 and 21 is 7

#Program17: using FETCHONE

import mysql.connector
mydb=mysql.connector.connect(host='localhost',user='root',passwd='passwor
d',database='arnavai')
cursor.execute("select *from table1")
records=cursor.fetchone()
for i in records:
print(i)

#OUTPUT:
Arnav Sharan
3
A
Mysql> use arnavai;
Database changed
Mysql>select* from table1;

Name Roll no Section


Arnav Sharan 3 A
Arnav Singh 4 A
ABC 1 B
PQR 10 C
XYZ 11 Null
DEF null A

#Program18: ROWCOUNT
import mysql.connector
mydb=mysql.connector.connect(host='localhost',user='root',passwd='passwor
d',database='arnavai')
cursor=mydb.cursor()
cursor.execute(“UPDATE table1 set Roll=05 where Section=’A’ ”)
mydb.commit(0
print(cursor.rowcount,”Records updated”)

#OUTPUT:
3 Records updated

#Program 19: WAP to bubble sort a particular list in


ascending order.

d=[14,67,32,12]
n=len(d)
for i in range(n):
for j in range(n-i-1):
if(d[j]>d[j+1]):
d[j],d[j+1]=d[j+1],d[j]
print(d)

#OUTPUT:
[12,14,32,67]

#Program 20: WAP traversing a 2D List.


a=[[1,2],[3,4],[5,6]]
for i in range(3):
for j in range(2):
print(a[i][j])

OUTPUT:1 2 3 4 5 6 7 8
4.pickle.dump(ID, fin)
5.fin.close()
6.fout = open("Emp.pkl",'rb')
7.ID = pickle.load(fout)
8.print(ID[5])
Ans:-
OUTPUT
Dunzo

MY SQL
[QUESTIONS]
#OUTPUT QUESTIONS

1.Observe the given Table TEACHER and give the output


of question(i) and (ii).

TEACHER CODE TEACHER NAME DATE OF JOINING

T001 ANAND 2001-01-30


T002 AMIT 2007-09-05
T003 ANKIT 2007-09-20
T004 BALBIR 2010-02-15
T005 JASBIR 2011-01-20
T0006 KULBIR 2008-07-11
(i) SELECT TEACHER_NAME,DOJ FROM TEACHER WHERE TEACHER
_NAME LIKE %I%
(ii) SELECT * FROM TABLE WHERE DOJ LIKE %-09-%

Ans:-
(i) TEACHER_NAME DOJ

AMIT 2007-09-05
ANKIT 2007-09-20
BALBIR 2010-02-15
JASBIR 2011-01-20
KULBIR 2008-07-11
(ii)
TEACHER_CODE TEACHER_NAME DOJ

T002 AMIT 2007-09-05


T003 ANKIT 2007-09-20
2.FIND THE OUTPUT OF (i) and (ii) ,WHICH ARE BASED ON TABLE NAMED
ACCOUNT AND TRANSACT.
Table :ACCOUNT
A NO. A NAME ADDRESS
101 Niraj singh Banglore
102 Rohan gupta chennai
103 Ali raza Hyderabad
104 Rishabh jain Chennai
105 Simaran kaur Chandigarh

Table : TRANSACT
TRNO ANO AMOUNT TYPE DOT

T001 101 2500 WITHDRAW 2017-12-21


T002 102 3000 DEPOSIT 2017-06-01
T003 103 2000 WITHDRAW 2017-05-12
T004 104 1000 DEPOSIT 2017-10-22
T005 405 12000 DEPOSIT 2017-11-06
(i) SELECT DISTINCT ANO FORM TRANSACT
Ans:-
ANO ANAME

103 Ali raza


105 Simran Kaur

(ii) SLECT COUNT(*),SUM(AMOUNT) FROM TRANSACT

Ans:-
COUNT(*) SUM(AMOUNT)

2 5000
#COMMANDS QUESTION

QUES.1 Write SQL commands for the following on the


basis of given table Teacher :
Table : Teacher

No Name Age Department Salary Sex Dateofjoin

1 Jugal 34 Computer 12000 M 1997-01-10

2 Sharmila 31 History 20000 F 1998-03-24

3 Sandeep 32 Maths 30000 M 1996-12-12

4 Sangeeta 35 History 40000 F 1999-07-01

5 Rakesh 42 Maths 25000 M 1997-09-05

6 Shyam 50 History 30000 M 1998-06-27

7 Shiv Om 44 Computer 21000 M 1997-02-25

8 Shalakha 33 Maths 20000 F 1997-07-31

1. To show all information about the teacher of history


department.
2. To list the names of female teachers who are in Hindi
department.
3. To list names of all teachers with their date of joining in
ascending order.

Answer
1.
SELECT *
FROM Teacher
WHERE Department = 'History' ;

Output
+----+----------+-----+------------+--------+-----+------------+
| No | Name | Age | Department | Salary | Sex | Dateofjoin |
+----+----------+-----+------------+--------+-----+------------+
| 2 | Sharmila | 31 | History | 20000 | F | 1998-03-24 |
| 4 | Sangeeta | 35 | History | 40000 | F | 1999-07-01 |
| 6 | Shyam | 50 | History | 30000 | M | 1998-06-27 |
+----+----------+-----+------------+--------+-----+------------+
2.
SELECT Name
FROM Teacher
WHERE Sex = 'F' and Department = 'Hindi' ;

Explanation

There are no records in the Teacher table where the department


is 'Hindi'. Hence, there will be no output.
3.
SELECT Name, Dateofjoin
FROM Teacher
ORDER BY Dateofjoin ;

Output

+----------+------------+
| Name | Dateofjoin |
+----------+------------+
| Sandeep | 1996-12-12 |
| Jugal | 1997-01-10 |
| Shiv Om | 1997-02-25 |
| Shalakha | 1997-07-31 |
| Rakesh | 1997-09-05 |
| Sharmila | 1998-03-24 |
| Shyam | 1998-06-27 |
| Sangeeta | 1999-07-01 |
+----------+------------+

QUES.2 Write SQL commands for the following on the


basis of given table MOV :
Table : MOV

No Title Type Rating Stars Qty Price

1 Gone with the Wind Drama G Gable 4 39.95

2 Friday the 13th Horror R Jason 2 69.95

3 Top Gun Drama PG Cruise 7 49.95

4 Splash Comedy PG13 Hanks 3 29.95

5 Independence Day Drama R Turner 3 19.95

6 Risky Business Comedy R Cruise 2 44.95

7 Cocoon Scifi PG Ameche 2 31.95

8 Crocodile Dundee Comedy PG13 Harris 2 69.95

9 101 Dalmatians Comedy G 3 59.95

10 Tootsie Comedy PG Hoffman 1 29.95


1. Display a list of all movies with Price over 20 and sorted by
Price.
2. Display all the movies sorted by QTY in decreasing order.
3. Display a report listing a movie number, current value and
replacement value for each movie in the above table.
Calculate the replacement value for all movies as : QTY *
Price * 1.15.

Answer
1.
SELECT Title
FROM MOV
WHERE Price > 20
ORDER BY Price ;

Output

+--------------------+
| Title |
+--------------------+
| Splash |
| Tootsie |
| Cocoon |
| Gone with the Wind |
| Risky Business |
| Top Gun |
| 101 Dalmatians |
| Friday the 13th |
| Crocodile Dundee |
+--------------------+
2.
SELECT Title
FROM MOV
ORDER BY Qty DESC ;

Output

+--------------------+
| Title |
+--------------------+
| Top Gun |
| Gone with the Wind |
| Splash |
| Independence Day |
| 101 Dalmatians |
| Friday the 13th |
| Risky Business |
| Cocoon |
| Crocodile Dundee |
| Tootsie |
+--------------------+
3.
SELECT No AS Movie_Number , Price AS Current_Value, (Qty * Price *
1.15) AS Replacement_Value
FROM MOV ;

Output

+--------------+---------------+--------------------+
| Movie_Number | Current_Value | Replacement_Value |
+--------------+---------------+--------------------+
| 1 | 39.95 | 183.77000350952147 |
| 2 | 69.95 | 160.884992980957 |
| 3 | 49.95 | 402.09750614166256 |
| 4 | 29.95 | 103.3275026321411 |
| 5 | 19.95 | 68.8275026321411 |
| 6 | 44.95 | 103.38500175476074 |
| 7 | 31.95 | 73.48500175476073 |
| 8 | 69.95 | 160.884992980957 |
| 9 | 59.95 | 206.8275026321411 |
| 10 | 29.95 | 34.44250087738037 |
+--------------+---------------+--------------------+

QUES.3 Write SQL commands for the following on the


basis of given table STUDENT1 :
Table : STUDENT1

No. Name Stipend Stream AvgMark Grade Class

1 Karan 400.00 Medical 78.5 B 12B


No. Name Stipend Stream AvgMark Grade Class

2 Divakar 450.00 Commerce 89.2 A 11C

3 Divya 300.00 Commerce 68.6 C 12C

4 Arun 350.00 Humanities 73.1 B 12C

5 Sabina 500.00 Nonmedical 90.6 A 11A

6 John 400.00 Medical 75.4 B 12B

7 Robert 250.00 Humanities 64.4 C 11A

8 Rubina 450.00 Nonmedical 88.5 A 12A

9 Vikas 500.00 Nonmedical 92.0 A 12A

10 Mohan 300.00 Commerce 67.5 C 12C

1. Select all the Nonmedical stream students from


STUDENT1.
2. List the names of those students who are in class 12
sorted by Stipend.
3. List all students sorted by AvgMark in descending order.
4. Display a report, listing Name, Stipend, Stream and amount
of stipend received in a year assuming that the Stipend is
paid every month.

Answer
1.
SELECT *
FROM STUDENT1
WHERE Stream = 'Nonmedical' ;
Output

+-----+--------+---------+------------+---------+-------+-------+
| No. | Name | Stipend | Stream | AvgMark | Grade | Class |
+-----+--------+---------+------------+---------+-------+-------+
| 5 | Sabina | 500 | Nonmedical | 90.6 | A | 11A |
| 8 | Rubina | 450 | Nonmedical | 88.5 | A | 12A |
| 9 | Vikas | 500 | Nonmedical | 92.0 | A | 12A |
+-----+--------+---------+------------+---------+-------+-------+
2.
SELECT Name
FROM STUDENT1
WHERE Class LIKE '12%'
ORDER BY Stipend ;

Output

+--------+
| Name |
+--------+
| Divya |
| Mohan |
| Arun |
| Karan |
| John |
| Rubina |
| Vikas |
+--------+
3.
SELECT *
FROM STUDENT1
ORDER BY AvgMark DESC ;

Output

+-----+---------+---------+------------+---------+-------+-------+
| No. | Name | Stipend | Stream | AvgMark | Grade | Class |
+-----+---------+---------+------------+---------+-------+-------+
| 9 | Vikas | 500 | Nonmedical | 92.0 | A | 12A |
| 5 | Sabina | 500 | Nonmedical | 90.6 | A | 11A |
| 2 | Divakar | 450 | Commerce | 89.2 | A | 11C |
| 8 | Rubina | 450 | Nonmedical | 88.5 | A | 12A |
| 1 | Karan | 400 | Medical | 78.5 | B | 12B |
| 6 | John | 400 | Medical | 75.4 | B | 12B |
| 4 | Arun | 350 | Humanities | 73.1 | B | 12C |
| 3 | Divya | 300 | Commerce | 68.6 | C | 12C |
| 10 | Mohan | 300 | Commerce | 67.5 | C | 12C |
| 7 | Robert | 250 | Humanities | 64.4 | C | 11A |
+-----+---------+---------+------------+---------+-------+-------+
4.
SELECT Name, Stipend, Stream, (Stipend * 12) AS Yearly_Stipend
FROM STUDENT1 ;

Output

+---------+---------+------------+----------------+
| Name | Stipend | Stream | Yearly_Stipend |
+---------+---------+------------+----------------+
| Karan | 400 | Medical | 4800 |
| Divakar | 450 | Commerce | 5400 |
| Divya | 300 | Commerce | 3600 |
| Arun | 350 | Humanities | 4200 |
| Sabina | 500 | Nonmedical | 6000 |
| John | 400 | Medical | 4800 |
| Robert | 250 | Humanities | 3000 |
| Rubina | 450 | Nonmedical | 5400 |
| Vikas | 500 | Nonmedical | 6000 |
| Mohan | 300 | Commerce | 3600 |
+---------+---------+------------+----------------+

QUES.4Write SQL commands for the following on the


basis of given table CLUB :
Table : CLUB

COACH_ID COACHNAME AGE SPORTS PAY SEX DATOFAPP

1 KUKREJA 35 KARATE 1000 M 1996-03-27

2 RAVINA 34 KARATE 1200 F 1998-01-20

3 KARAN 34 SQUASH 2000 M 1998-02-19

4 TARUN 33 BASKETBALL 1500 M 1998-01-01

5 ZUBIN 36 SWIMMING 750 M 1998-01-12


COACH_ID COACHNAME AGE SPORTS PAY SEX DATOFAPP

6 KETAKI 36 SWIMMING 800 F 1998-02-24

7 ANKITA 39 SQUASH 2200 F 1998-02-20

8 ZAREEN 37 KARATE 1100 F 1998-02-22

9 KUSH 41 SWIMMING 900 M 1998-01-13

10 SHAILYA 37 BASKETBALL 1700 M 1998-02-19

1. To show all information about the swimming coaches in


the club.
2. To list names of all coaches with their date of appointment
(DATOFAPP) in descending order.
3. To display a report, showing coachname, pay, age and
bonus (15% of pay) for all the coaches.

Answer
1.
SELECT *
FROM CLUB
WHERE SPORTS = 'SWIMMING' ;

Output

+----------+-----------+-----+----------+-----+-----+------------+
| COACH_ID | COACHNAME | AGE | SPORTS | PAY | SEX | DATOFAPP |
+----------+-----------+-----+----------+-----+-----+------------+
| 5 | ZUBIN | 36 | SWIMMING | 750 | M | 1998-01-12 |
| 6 | KETAKI | 36 | SWIMMING | 800 | F | 1998-02-24 |
| 9 | KUSH | 41 | SWIMMING | 900 | M | 1998-01-13 |
+----------+-----------+-----+----------+-----+-----+------------+
2.
SELECT COACHNAME, DATOFAPP
FROM CLUB
ORDER BY DATOFAPP DESC ;
Output

+-----------+------------+
| COACHNAME | DATOFAPP |
+-----------+------------+
| KETAKI | 1998-02-24 |
| ZAREEN | 1998-02-22 |
| ANKITA | 1998-02-20 |
| KARAN | 1998-02-19 |
| SHAILYA | 1998-02-19 |
| RAVINA | 1998-01-20 |
| KUSH | 1998-01-13 |
| ZUBIN | 1998-01-12 |
| TARUN | 1998-01-01 |
| KUKREJA | 1996-03-27 |
+-----------+------------+
3.
SELECT COACHNAME, PAY, AGE, (PAY * 0.15) AS BONUS
FROM CLUB ;

Output

+-----------+------+-----+--------+
| COACHNAME | PAY | AGE | BONUS |
+-----------+------+-----+--------+
| KUKREJA | 1000 | 35 | 150.00 |
| RAVINA | 1200 | 34 | 180.00 |
| KARAN | 2000 | 34 | 300.00 |
| TARUN | 1500 | 33 | 225.00 |
| ZUBIN | 750 | 36 | 112.50 |
| KETAKI | 800 | 36 | 120.00 |
| ANKITA | 2200 | 39 | 330.00 |
| ZAREEN | 1100 | 37 | 165.00 |
| KUSH | 900 | 41 | 135.00 |
| SHAILYA | 1700 | 37 | 255.00 |
+-----------+------+-----+--------+
My SQL Connectivity
Based Program

Write a Menu Based Python database


connectivity script that performs the
following operations on the table named
PRODUCT in SHOP Database. Observe the
data given and set suitable primary key
for the table and appropriate datatypes
for the fields.

Table: PRODUCT
P_ ID ProductName Manufacturer Price
TP01 Talcum Powder LAK 40
FW05 Face Wash ABC 45
BS01 Bath Soap ABC 55
SH06 Shampoo XYZ 120
FW12 Face Wash XYZ
The Menu should be:-
(1)Add a record
(2)Display All Records
(3)Displayrecords of a particular
manufacturer.
(4)Modifythe Price of a given P_ID
entered by user.
(5)Delete a Record of given ProductName
(6)Exit.
Source Code:
import mysql.connector as ms

con = ms.connect(host = 'localhost', user =


'root', passwd = 'dpsbn') cur = con.cursor()

cur.execute("create database shop")


cur.execute("use shop")

cur.execute("create table product(p_id char(4)


primary key, prod_name varchar(200), mfr char(3),
price int)")

#
cur.execute("insert into product
values('TP01','Talcum Powder','LAK',40)")
con.commit()

cur.execute("insert into product


values('FW05','Face Wash','ABC',45)")
con.commit()

cur.execute("insert into product


values('BS01','Bath Soap','ABC',55)")
con.commit()

cur.execute("insert into product


values('SH06','Shampoo','XYZ',120)")
con.commit()

cur.execute("insert into product


values('FW12','Face Wash','XYZ',NULL)")
con.commit()
# while
True: m
=
int(input("\
nEnter input
[(1) - (6)]:
"))

if m == 1:
a = input("Enter p_id: ")
b = input("Enter prod_name: ") c
= input("Enter manufacturer: ") d
= int(input("Enter price: "))

cur.execute("insert into product


values('{}','{}','{}',{})".format(a,b,c,d))
con.commit()

print("\nDone!!!\n")
elif m == 2:

cur.execute("select * from product")


data1 = cur.fetchall()

print("\n",data1,"\n")
elif m == 3:

e = input("Enter mfr to display record(s):


")
cur.execute("select * from product where
mfr = '{}'".format(e))
data2 = cur.fetchall()

print("\n",data2,"\n")
elif m == 4:

f = input("Enter p_id: ") g =


int(input("Enter new price: "))

cur.execute("update product set price = {}


where p_id = '{}'".format(g,f))
con.commit()
print("\nDone!!!\n")
elif m == 5:

h = input("Enter prod_name: ")


cur.execute("delete from product where
prod_name = '{}'".format(h))
con.commit()

print("\nDone!!!\n")
elif m == 6: print("\nYou
have exited...")
break else:
print("\nInvalid Input ... Try Again\n")
con.close()

Output:

Enter input [(1) - (6)]: 2

[('BS01', 'Bath Soap', 'ABC', 55), ('FW05',


'Face Wash', 'ABC', 45), ('FW12', 'Face Wash',
'XYZ', None), ('SH06', 'Shampoo', 'XYZ', 120),
('TP01', 'Talcum Powder', 'LAK', 40)]

Enter input [(1) - (6)]: 3


Enter mfr to display record(s): ABC

[('BS01', 'Bath Soap', 'ABC', 55), ('FW05',


'Face Wash', 'ABC', 45)]
Enter input [(1) - (6)]: 5
Enter prod_name: Bath Soap

Done!!!

Enter input [(1) - (6)]: 1


Enter p_id: AK47
Enter prod_name: Assaultnikov
Enter manufacturer: AKM
Enter price: 47000

Done!!!

Enter input [(1) - (6)]: 4


Enter p_id: FW12
Enter new price: 60

Done!!!

Enter input [(1) - (6)]: 6

You have exited...

You might also like