Program Ms
Program Ms
OUTPUT:
Enter any stringabhishake
@bhish@ke
[PROG-2] Write a program to accept a word from
the user and display it in the following pattern.
if the word is “river” then it should display as
shown below
r
ri
riv
rive
river
OUTPUT:
Pooja
Poonam
[PROG-4] Write a function disp(name) in python to
display all the names from a list of names whose
length is of four characters.
name = ['Amit' , 'Sumit', 'Pooja' , 'Mini' ,
'Ronit' , 'Abdul', 'Poonam']
def disp(name):
for i in name:
if len(i)==4:
print(i)
disp(name)
OUTPUT:
Amit
Mini
[PROG-5] Write a function previous(List, name)
which is accepting list of names and a name and
display the index value of the first occurence of the
name passed in the list.
name = ['Amit' , 'Sumit', 'Pooja','Mini' ,
'Ronit' , 'Abdul', 'Poonam']
def previous(L,n):
c=-1
for i in L:
c = c + 1
if i.lower()==n.lower():
print("Index Value is ",c)
break
previous(name, 'sumit')
OUTPUT:
Index Value is 1
[PROG-6]Write a function double(L) in python
which take a list as an argument and if an element
is numeric then multiply it by 3 and if it is a string
then concatenate that element with itself.
L = [1, 2, 'amit', 5, 'list']
def double(L):
for i in range(len(L)):
if str(L[i]).isdigit():
L[i]=L[i]*3
else:
L[i]=L[i]*2
print(L)
double(L)
OUTPUT:
[3, 6, 'amitamit', 15, 'listlist']
[PROG-7] Write a program that arrange all odd
numbers on left side of the list and even numbers
on the right side of the list
L = [23, 44, 65, 78, 34, 21, 9]
def rightleft():
for i in L:
c=0
k=0
if i%2!=0:
k=L.index(i)
L.insert(c, L.pop(k))
c=c+1
else:
c=c+1
print(L)
rightleft()
OUTPUT:
[9, 21, 65, 23, 44, 78, 34]
[PROG-8] Write a python programs to
join/merge/concatenate the following two
dictionaries and create the new dictionary.
d1 = {1: “Amit”, 2 : “Suman”}
d2 = {4 : “Ravi”, 5 : “Kamal”}
def merge():
d1 = {1 :'Amit',2 : 'Suman'}
d2 = {4:"Ravi", 5 : 'Kamal'}
d3={ }
for i in (d1,d2):
d3.update(i)
print(d3)
merge()
OUTPUT:
{1: 'Amit', 2: 'Suman', 4: 'Ravi', 5: 'Kamal'}
[PROG-9] Write a program to accept the employee
id from the user and check Salary. If salary is less
than 25000 then increase the salary by Rs1000.
Data is stored in the dictionary in the following
format
{Empid : (Empname, EmpSalary}
emp={1:('Amit',25000),2:('Suman',30000),3:('Ravi
',36000)}
pid=int(input('Enter the product id'))
l=[ ]
if pid in emp:
l=emp[pid]
if l[1]>25000:
emp[pid]=(l[0],l[1]+500)
print(emp)
OUTPUT:
Enter the product id2
{1: ('Amit', 25000), 2: ('Suman', 30500), 3:
('Ravi', 36000)}
[PROG-10] Write a program to accept roll number,
names and marks of five students and store the
detail in dictionary using roll number as key. Also
display the sum of marks of all the five students.
d={ }
s=0
for i in range(5):
rn = int(input('Enter roll number'))
nm = input('Enter name')
mrk = input('Enter marks')
temp=(nm, mrk)
d[rn]=temp
for i in d:
L=d[i]
s=s+int(L[1])
print('Sum of marks;', s)
OUTPUT:
Enter roll number34
Enter nameAbhishek
Enter marks56
Enter roll number22
Enter namearav
Enter marks33
Enter roll number12
Enter namerishabh
Enter marks69
Enter roll number22
Enter nameishan
Enter marks56
Enter roll number32
Enter nameaditya
Enter marks44
Sum of marks; 56
Sum of marks; 112
Sum of marks; 181
Sum of marks; 225
[PROG-11]Create a text file “intro.txt” in python
and ask the user to write a single line of text by
user input.
def program1():
f = open("intro.txt","w")
text=input("Enter the text:")
f.write(text)
f.close()
program1()
OUTPUT:
Enter the text:aa b
aa b
[PROG-12] Create a text file “MyFile.txt” in python
and ask the user to write separate 3 lines with
three input statements from the user.
def program2():
f = open("MyFile.txt","w")
line1=input("Enter the text:")
line2=input("Enter the text:")
line3=input("Enter the text:")
new_line="\n"
f.write(line1)
f.write(new_line)
f.write(line2)
f.write(new_line)
f.write(line3)
f.write(new_line)
f.close()
program2()
OUTPUT:
Enter the text:abhi
Enter the text:abhi
Enter the text:qq
abhi
abhi
qq
[PROG-13] Write a program to read the contents of
both the files created in the above programs and
merge the contents into “merge.txt”. Avoid using
the close() function to close the files.
def program3():
with open("MyFile.txt","r") as f1:
data=f1.read()
with open("intro.txt","r") as f2:
data1=f2.read()
with open("merge.txt","w") as f3:
f3.write(data)
f3.write(data1)
program3()
OUTPUT:
abhi
abhi
qq
aa b
[PROG-14] Count the total number of upper case,
lower case, and digits used in the text file
“merge.txt”.
def program4():
with open("merge.txt","r") as f1:
data=f1.read()
cnt_ucase =0
cnt_lcase=0
cnt_digits=0
for ch in data:
if ch.islower():
cnt_lcase+=1
if ch.isupper():
cnt_ucase+=1
if ch.isdigit():
cnt_digits+=1
print("Total Number of Upper Case letters
are:",cnt_ucase)
print("Total Number of Lower Case letters
are:",cnt_lcase)
print("Total Number of digits
are:",cnt_digits)
program4()
OUTPUT:
Total Number of Upper Case letters are: 0
Total Number of Lower Case letters are: 13
Total Number of digits are: 0
[PROG-15] Write a program to count a total
number of lines and count the total number of
lines starting with ‘a’, ‘b’, and ‘c’. (Consider the
merge.txt file)
def program5():
with open("merge.txt","r") as f1:
data=f1.readlines()
cnt_lines=0
cnt_a=0
cnt_b=0
cnt_c=0
for lines in data:
cnt_lines+=1
if lines[0]=='A':
cnt_a+=1
if lines[0]=='B':
cnt_b+=1
if lines[0]=='C':
cnt_c+=1
print("Total Number of lines
are:",cnt_lines)
print("Total Number of lines starting with a
are:",cnt_a)
print("Total Number of lines starting with b
are:",cnt_b)
print("Total Number of lines starting with c
are:",cnt_c)
program5()
OUTPUT:
Total Number of lines are: 4
Total Number of lines strating with a are: 3
Total Number of lines strating with b are: 0
Total Number of lines strating with c are: 0
[PROG-16] Find the total occurrences of a specific
word from a text file:
def program6():
cnt = 0
word_search = input("Enter the words to
search:")
with open("merge.txt","r") as f1:
for data in f1:
words = data.split()
for word in words:
if (word == word_search):
cnt+=1
print(word_search, "found ", cnt, " times
from the file")
program6()
OUTPUT:
Enter the words to search:abhi
abhi found 2 times from the file
[PROG-17] Read first n no. letters from a text file,
read the first line, read a specific line from a text
file.
def program7():
cnt = 0
n = int(input("Enter no. characters to
read:"))
with open("merge.txt","r") as f1:
line1=f1.readline()
print("The first line of file:",line1)
nchar=f1.read(n)
print("First n no. of characters:",
nchar)
nline=f1.readlines()
print("Line n:",nline[n])
program7()
OUTPUT:
Enter no. characters to read:2
The first line of file: abhi
OUTPUT:
Enter Student No:12
Enter Student Name:Abhishek
Enter Address:rohini
************************************************
******************************
Data stored in File....
12
Abhishek
Rohini
[PROG-19] Write a program to read and write
programming languages stored in the tuple to
binary file PL.dat.
import pickle
def bin2tup():
f = open("PL.dat","wb")
t = ('C','C++','Java','Python')
pickle.dump(t,f)
f.close()
f = open("PL.dat","rb")
d = pickle.load(f)
print("PL1:",d[0])
print("PL2:",d[1])
print("PL3:",d[2])
print("PL4:",d[3])
f.close()
bin2tup()
OUTPUT:
PL1: C
PL2: C++
PL3: Java
PL4: Python
[PROG-20] Write a program to store customer data
into a binary file cust.dat using a dictionary and
print them on screen after reading them. The
customer data contains ID as key, and name, city
as values.
import pickle
def bin2dict():
f = open("cust.dat","wb")
d = {'C0001':['Subham','Ahmedabad'],
'C0002':['Bhavin','Anand'],
'C0003':['Chintu','Baroda']}
pickle.dump(d,f)
f.close()
f = open("cust.dat","rb")
d = pickle.load(f)
print(d)
f.close()
bin2dict()
OUTPUT:
{'C0001': ['Subham', 'Ahmedabad'], 'C0002':
['Bhavin', 'Anand'], 'C0003': ['Chintu',
'Baroda']}
[PROG-21] Write a function to write data into
binary file marks.dat and display the records of
students who scored more than 95 marks.
import pickle
def search_95plus():
f = open("marks.dat","ab")
while True:
rn=int(input("Enter the rollno:"))
sname=input("Enter the name:")
marks=int(input("Enter the marks:"))
rec=[]
data=[rn,sname,marks]
rec.append(data)
pickle.dump(rec,f)
ch=input("Wnat more records?Yes:")
if ch.lower() not in 'yes':
break
f.close()
f = open("marks.dat","rb")
cnt=0
try:
while True:
data = pickle.load(f)
for s in data:
if s[2]>95:
cnt+=1
print("Record:",cnt)
print("RollNO:",s[0])
print("Name:",s[1])
print("Marks:",s[2])
except Exception:
f.close()
search_95plus()
OUTPUT:
Enter the rollno:3
Enter the name:abhi
Enter the marks:97
Wnat more records?Yes:yes
Enter the rollno:4
Enter the name:aa
Enter the marks:89
Wnat more records?Yes:no
Record: 1
RollNO: 3
Name: abhi
Marks: 97
[PROG-22]Write a program the writes data (as
shown below) to file “books.dat” in List format till
the user desires and then reads data from the
same file. Display and count number of books with
name ‘Python’
import pickle
book = open("books.dat","wb")
ans='y'
while ans.upper() == 'Y' :
code = input("Enter Book Code : ")
name = input("Enter Book Name : ")
author = input("Enter Book Author Name : ")
price = float(input("Enter Book price : "))
List = [ code , name , author , price ]
pickle.dump(List,book)
ans= input("Want to add more Book details in
file ( Y/ N ) :")
book.close()
book = open("books.dat","rb")
count=0
try:
while True:
List = pickle.load(book)
if List[1].upper() == 'PYTHON' :
print(List)
count += 1
except EOFError:
book.close()
if count>0:
print("Number of books with name
'Python' : ", count)
else:
print("no books with name Python")
OUTPUT:
Enter Book Code : 112
Enter Book Name : python
Enter Book Author Name : david
Enter Book price : 400.0
Want to add more Book details in file ( Y/ N )
:Y
Enter Book Code : 102
Enter Book Name : mysql
Enter Book Author Name : arthur
Enter Book price : 222.0
Want to add more Book details in file ( Y/ N )
:N
['112', 'python', 'david', 400.0]
Number of books with name 'Python' : 1
[PROG-23]Write a menu driven program which
shows all operations on Binary File
1. Add Record
2. Display All Record
3. Display Specific Record
4. Modify Record
5. Delete Record
Use “data.dat” file which stores the record of
“Hotel” in the form of list containing Room_no,
Price, Room_type.
import pickle
import os
def main_menu():
print("6. Exit")
if ch==1:
addrec()
elif ch==2:
disp()
elif ch==3:
specific_rec()
elif ch==4:
mod()
elif ch==5:
del()
elif ch==6:
print("Bye")
else:
print("Invalid Choice.")
def addrec():
L=[ ]
f=open("data.dat","ab")
pickle.dump(L, f)
f.close()
def disp():
try:
f=open("data.dat","rb")
while True:
d=pickle.load(f)
print(d)
except:
f.close()
def specific_rec():
try:
f1=open("data.dat","rb")
while True:
d=pickle.load(f1)
if rno==d[0]:
print(d)
except:
f1.close()
def mod():
try:
file = open("data.dat","rb+")
f=open("temp1.dat","wb")
while True:
d = pickle.load(file)
if roll == d[0]:
d[1]=int(input("Enter modified
price"))
d[2]=input("Enter modified
room type")
pickle.dump(d,f)
except:
print("Record Updated")
file.close()
f.close()
os.remove("data.dat")
os.rename("temp1.dat","data.dat")
def delete():
try:
file = open("data.dat","rb+")
f=open("temp1.dat","wb")
while True:
d = pickle.load(file)
if roll != d[0]:
pickle.dump(d,f)
except:
print("Record Deleted")
file.close()
f.close()
os.remove("data.dat")
os.rename("temp1.dat","data.dat")
main_menu()
addrec()
disp()
specific_rec()
mod()
delete()
OUTPUT:
1. Add a new record
4. Modify a record
5. Delete a record
6. Exit
Record Updated
Record Deleted
[PROG-24] Write a menu driven program in Python
that asks the user to add, display, and search
records of employee stored in a binary file. The
employee record contains employee code, name
and salary. It should be stored in a list object. Your
program should pickle the object and save it to a
binary file.
import pickle
def set_data():
print()
employee = [empcode,name,salary]
return employee
def display_data(employee):
print('Salary:', employee[2])
print()
def write_record():
outfile = open('emp.dat', 'ab')
pickle.dump(set_data(), outfile)
outfile.close()
def read_records():
while True:
try:
employee = pickle.load(infile)
display_data(employee)
except EOFError:
break
infile.close()
def search_record():
flag = False
while True:
try:
employee = pickle.load(infile)
if employee[0] == empcode:
display_data(employee)
flag = True
break
except EOFError:
break
if flag == False:
print()
infile.close()
def show_choices():
print('Menu')
print('4. Exit')
def main():
while(True):
show_choices()
print()
if choice == '1':
write_record()
read_records()
search_record()
break
else:
print('Invalid input')
main()
OUTPUT:
Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 1
Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 1
Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 2
Employee code: 33
Salary: 4453
Employee code: 21
Employee name: aa
Salary: 5553
Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 3
Employee code: 21
Employee name: aa
Salary: 5553
Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 4
[PROG-25] Write a program to search the record
from “data.csv” according to the admission
number input from the user. Structure of record
saved in “data.csv” is Adm_no, Name, Class, Section,
Marks.
import csv
f = open("data.csv",'r')
d=csv.reader(f)
next(f)
k = 0
for row in d:
if int(row[0])==adm:
break
else:
f = open("data.csv" , 'w')
d=csv.writer(f)
d.writerow(field)
ch='y'
rec=[rn,nm,cls]
d.writerow(rec)
f.close()
OUTPUT:
Enter Roll number: 33
Roll Number = 1
Name = Amit
Marks = 81
--------------------------
Roll Number = 2
Name = Suman
Marks = 85
-------------------------
Roll Number = 4
Name = Deepika
Marks = 89
-------------------------
[PROG-28] Write a program to display all the
records from product.csv whose price is more than
300. Format of record stored in product.csv is
product id, product name, price.
import csv
f=open("product.csv" , "r")
d=csv.reader(f)
next(f)
print()
for i in d:
if int(i[2])>300:
print("--------------------")
f.close( )
OUTPUT:
product whose price more than 300
Product id = 2
Product Name = Mouse
Product Price = 850
---------------------------------
Product id = 3
Product Name = RAM
Product Price = 1560
--------------------------------
[PROG-29] Menu driven program for data of cars
using csv files.
import csv
fileName = 'cars.csv'
def menu():
print('='*30)
print('='*30)
print('0. Exit')
return ch
def addNew():
rec=[carName,brand,year,price]
fobj = open(fileName,'a')
dataWriter = csv.writer(fobj)
dataWriter.writerow(rec)
fobj.close()
def heading():
print('='*50)
print('%-15s%-15s%-10s%-10s'%("Car
Mode","Car Company","Mfg. Yr","Price"))
print('='*50)
def readAll(n=None):
flag=0
with open(fileName,'r',newline='\r\n') as
fobj:
dataReader = csv.reader(fobj)
heading()
if n==None:
print('%-15s%-15s%-10s%-
10s'%(myData[0],myData[1],myData[2],myData[3]))
elif n!=None:
for myData in dataReader:
if myData[1]==n:
print('%-15s%-15s%-10s%-
10s'%(myData[0],myData[1],myData[2],myData[3]))
flag+=1
if flag==0:
fobj.close()
while True:
ch=menu()
if ch==0:
break
elif ch==1:
addNew()
elif ch==2:
readAll()
elif ch==3:
readAll(company)
print(host[i][0],"\t\t",host[i][1],"\t\t",host[i
][2])
while(ch=='y' or ch=='Y'):
print("1. Add Record\n")
print("2. Delete Record\n")
print("3. Display Record\n")
print("4. Exit")
op=int(input("Enter the Choice"))
if(op==1):
push(host)
elif(op==2):
pop(host)
elif(op==3):
display(host)
elif(op==4):
break
ch=input("Do you want to enter more(Y/N)")
OUTPUT:
1. Add Record
2. Delete Record
3. Display Record
4. Exit
Enter the Choice1
Enter hostel number55
Enter Total students88
Enter total rooms90
Do you want to enter more(Y/N)Y
1. Add Record
2. Delete Record
3. Display Record
4. Exit
Enter the Choice1
Enter hostel number34
Enter Total students88
Enter total rooms90
Do you want to enter more(Y/N)Y
1. Add Record
2. Delete Record
3. Display Record
4. Exit
Enter the Choice3
Hostel Number Total Students Total Rooms
34 88 90
55 88 90
Do you want to enter more(Y/N)Y
1. Add Record
2. Delete Record
3. Display Record
4. Exit
Enter the Choice2
Deleted Record is : [34, 88, 90]
Do you want to enter more(Y/N)n
[PROG-31] Write a program to display record
flight which contains flightno, flightname and
number of travellers and display it in the form of
stack data structure.
def push(flight):
flno=int(input("enter the flight number"))
flname=input("enter the name of the flight")
flt=int(input("enter theb no. of
travellers"))
flight.append([flno,flname,flt])
def pop(flight):
if flight==[]:
print("under flow")
else:
print("flight record deleted",
flight.pop())
def display(flight):
if flight==[]:
print("under flow")
else:
print("flight record in stack")
l=len(flight)
for i in range(l-1,-1,-1):
print(flight[i])
flight=[]
while True:
print("\n1.push.\n2.pop.\n3.
display.\n4.exit")
ch=int(input("enter the choice"))
if ch==1:
push(flight)
elif ch==2:
pop(flight)
elif ch==3:
display(flight)
else:
break
OUTPUT:
1.push.
2.pop.
3. display.
4.exit
enter the choice1
enter the flight number22
enter the name of the flightindigo
enter theb no. of travellers66
1.push.
2.pop.
3. display.
4.exit
enter the choice1
enter the flight number33
enter the name of the flightkingfisher
enter theb no. of travellers44
1.push.
2.pop.
3. display.
4.exit
enter the choice3
flight record in stack
[33, 'kingfisher', 44]
[22, 'indigo', 66]
1.push.
2.pop.
3. display.
4.exit
enter the choice2
flight record deleted [33, 'kingfisher', 44]
[PROG-32] To maintain employee details like
empno, name and salary using a stack
Operations:
Addition of elements (PUSH)
Deleteion of elements (POP)
Traversal of elements (DISPLAY)
employee=[]
def push():
emp=(empno,name,sal)
employee.append(emp)
def pop():
if(employee==[]):
print("Underflow / Employee
Stack in empty")
else:
empno,name,sal=employee.pop()
def traverse():
if not (employee==[]):
n=len(employee)
for i in range(n-1,-1,-1):
print(employee[i])
else:
print("Empty , No employee to
display")
while True:
print("1. Push")
print("2. Pop")
print("3. Traversal")
print("4. Exit")
if(ch==1):
push()
elif(ch==2):
pop()
elif(ch==3):
traverse()
elif(ch==4):
print("End")
break
else:
print("Invalid choice")
OUTPUT:
1. Push
2. Pop
3. Traversal
4. Exit
Enter your choice 1
Enter empno 22
Enter name ABHI
Enter sal 1200
1. Push
2. Pop
3. Traversal
4. Exit
Enter your choice 1
Enter empno 12
Enter name arav
Enter sal 3444
1. Push
2. Pop
3. Traversal
4. Exit
Enter your choice 3
('12', 'arav', '3444')
('22', 'ABHI', '1200')
1. Push
2. Pop
3. Traversal
4. Exit
Enter your choice 2
poped element is
empno 12 name arav salary 3444
[PROG-33] Write functions AddPlayer(player) and
DeletePlayer(player) in python to add and remove
a player by considering them as push and pop
operations in a stack.
def AddPlayer(player):
pn=input("enter player name:")
player.append(pn)
def DeletePlayer(player):
if player==[]:
print("No player found")
else:
return player.pop()
player=[]
AddPlayer(player)
DeletePlayer(player)
OUTPUT:
enter player name:abhishek
[PROG-34]Write a python program to read a line of
text and Print it in reverse (Reverse word by
word).
line=input("Enter any line of text ")
stack=[]
for word in line.split():
print(word)
stack.append(word)
print("stack ",stack)
print("total words are ",len(stack))
n=len(stack)
for i in range(n-1,-1,-1):
print(stack[i],end=' ')
OUTPUT:
Enter any line of text hello how are you
hello
how
are
you
stack ['hello', 'how', 'are', 'you']
total words are 4
you are how hello
[PROG-35] Write a python program to read a line
of text and Print it in reverse.
line=input("Enter any line of text ")
stack=[]
for word in line:
print(word)
for ch in word:
stack.append(ch)
print("stack ",stack)
print("total words are ",len(stack))
n=len(stack)
for i in range(n-1,-1,-1):
print(stack[i],end='')
OUTPUT:
Enter any line of text hello how are you
h
e
l
l
o
h
o
w
a
r
e
y
o
u
stack ['h', 'e', 'l', 'l', 'o', ' ', 'h', 'o',
'w', ' ', 'a', 'r', 'e', ' ', 'y', 'o', 'u']
total words are 17
uoy era woh olleh
[PROG-36] To test connection with MYSQL using
mysql.connector
import mysql.connector
from mysql.connector import Error
con=None
try:
con =
mysql.connector.connect(host='localhost',user='r
oot',password='ct')
if(con.is_connected()==True):
print("connected to MYSQL Database")
except Error as e:
print(e)
finally:
if con is not None and
con.is_connected():
con.close()
print("Connection closed")
OUTPUT:
connected to MYSQL Database
[PROG-37] * To test connection with MYSQL using
mysql.connector
* To create a database
import mysql.connector
from mysql.connector import Error
con=None
try:
con =
mysql.connector.connect(host='localhost',user='r
oot',password='ct')
if(con.is_connected()==True):
print("connected to MYSQL Database")
db=con.cursor()
q1="create database student1;"
db.execute(q1)
print("student1 database created")
con.close()
except Error as e:
print(e)
finally:
if con is not None and
con.is_connected():
con.close()
OUTPUT:
connected to MYSQL Database
student1 database created
[PROG-38] * To create a table in an existing
database.
import mysql.connector
from mysql.connector import Error
con=None
try:
con =
mysql.connector.connect(host='localhost',user='r
oot',
password='admin123',database='student1')
if(con.is_connected()==True):
print("connected")
mycursor=con.cursor()
q1="create table stud ( rollno int, name
char(15), M1 float, M2 float, M3 float,M4 float,
M5 float, total float, per float);"
mycursor.execute(q1)
print("stud table created")
except Error as e:
print(e)
finally:
if con is not None and
con.is_connected():
con.close()
OUTPUT:
connected
stud table created
[PROG-39] * To insert a record in an existing table.
import mysql.connector
from mysql.connector import Error
con=None
try:
con =
mysql.connector.connect(host='localhost',user='r
oot',
password='admin123',database='student1')
if(con.is_connected()==True):
print("connected")
db=con.cursor()
r='1'
n='Aman Sharma'
m11='80'
m12='70'
m13='75'
m14='66'
m15='88'
db.execute("insert into stud
(rollno,name,M1,M2,M3,M4,M5) values
(%s,%s,%s,%s,%s,%s,%s)",(r,n,m11,m12,m13,m14,m15
))
con.commit()
print("Record Saved: 1 Record Inserted")
except Error as e:
print(e)
finally:
if con is not None and
con.is_connected():
con.close()
print("Connection closed")
OUTPUT:
connected
Record Saved: 1 Record Inserted
Connection closed
[PROG-40] * To fetch data from a table
* To fetch only one record using fetchone()
import mysql.connector
from mysql.connector import Error
con=None
try:
con =
mysql.connector.connect(host='localhost',user='r
oot',
password='admin123',database='student1')
if(con.is_connected()==True):
print("connected")
db=con.cursor()
sql="select * from stud;"
db.execute(sql)
res = db.fetchone()
for x in res:
print(x)
except Error as e:
print(e)
finally:
if con is not None and
con.is_connected():
con.close()
print("Connection closed")
OUTPUT:
connected
1
Aman Sharma
80.0
70.0
75.0
66.0
88.0
None
None
Connection closed
[PROG-41]WRITE THE OUTPUT OF THE QUERIES
(I) TO (IV) BASED ON THE TABLES,ACCOUNT AND
TRANSACT GIVEN BELOW:
1)SELECT ANO,ANAME FROM ACCOUNT WHERE
ADDRESS NOT IN(“CHENNAI”,”BANGALORE”)
2)SELECT DISTINCT ANO FROM TRANSACT
3)SELECT ANO,COUNT(*),MIN(AMOUNT) FROM
TRANSACT GROUP BY ANO HAVING COUNT(*)>1
4)SELECT COUNT(*),SUM(AMOUNT) FROM
TRANSACT WHERE DOT<=”2017-06-01”
OUTPUT-
mysql> insert into account
->values(“101,”Nirja Singh”,”Bangalore”),
->(102,”Rohan Gupta”,”Chennai”),
->(103,”Ali Reza”,”Hyderabad”)
->(104,”Rishabh Jain”,”Chennai”),
->(105,”Simran Kaur,”Chandigarh”);
Query OK, 5 rows affected(0.02 sec)
Records: 5 Duplicates: 0 Warning: 0
mysql> insert into transact
->values(1,101,2500,”withdraw”,”2017-12-21”),
->(2,”103,3000,”deposit”,”2017-06-01”),
->(3,102,2000,”withdraw”,2017-05-12),
->(4,103,1000,”deposit”,”2017-10-22”);
Query OK, 4 rows affected(0.02 sec)
Records: 5 Duplicates: 0 Warning: 0
[PROG-42]WRITE THE OUTPUTS OF THE SQL
QUERIES (I) TO (IV) BASED ON THE RELATIONS
TRAINS AND PASSENGERS GIVEN BELOW:
1)SELECT DISTINCT TRAVEL DATE FROM
PASSENGERS
2)SELECT MIN(TRAVELDATE),MAX(TRAVELDATE)
FROM PASSENGERS WHERE GENDER=”MALE”
3)SELECT START,COUNT(*) FROM TRAINS GROUP
BY START HAVIING COUNT(*)>1
4)SELECT TNAME,PNAME FROM TRAINS
T,PASSENGERS P WHERE T.TNO=P.TNO AND AGE
BETWEEN 40 AND 50
OUTPUT-
mysql> insert into TRAINS
->values(96,”A”,”B”,”WW”),
->(12,”C”,”D”,”UU”),
->(51,”E”,”F”,”VV”),
->(5,”G”,”H”,”XX”),
->(2,”I”,”J”,”YY”),
->(17,”K,”L”,ZZ”);
Query OK, 6 rows affected(0.02 sec)
Records: 6 Duplicates: 0 Warning: 0
mysql> insert into PASSENGERS
->values(1,1305,”L”,”M”,45,”2018-12-25”)
->(2,1215,”A”,”M”,28,”2018-11-10”),
->(3,1215,”B”,”F”,22,”2018-11-10”),
->(4,1230,”C”,”M”,42,2018-10-12”),
->(5,1230,”D”,”F”,35,”2018-10-12”),
->(6,1230,”E”,”F”,12,”2018-10-12”)
Query OK, 6 rows affected(0.02 sec)
Records: 6 Duplicates: 0 Warning: 0
[PROG-43]AMRITA IS A DATA ADMINISTRATOR
FOR A COMPANY AND HAS TO CREATE DATABASE-
‘MOVIE’AND TABLE-‘MOVIEDETAILS’.HELP HER TO
DO SO.
-TABLE SHOULD CONTAIN FOLLOWING COLUMNS[
MOVIEID-PRIMARY KEY,TITLE,LANGUAGE,RATING
AND PLATFORM WITH MAXIMUM 6 RECORDS.]
PERFORM-
(a) DISTINCT BY LANGUAGES.
(b) PLATFORMS IN DESCENDING ORDER.
(c) INCREASE RATINGS BY 1 WHERE
LANGUAGE IS HINDI.
(d) DO ADD A COLUMN CALLED AS
RECOMMENDED WITH VALUE YES FOR ALL
MOVIES.
OUTPUT-
mysql> create database movie;
Query OK, 1 row affected (0.02 sec)
mysql> use movie;
Database changed
mysql> create table moviedetails(
-> movieid int(10) primary key,
-> title varchar(20),
-> language varchar(10),
-> rating int(10),
-> platform varchar(20));
Query OK, 0 rows affected, 2 warnings (0.06 sec)