You are on page 1of 19

Practical 15

Write a program to read a binary file and print the marks of only those
students who have scored marks between 10 and 15.
import os
import pickle
def Readfile():
astu=[]
if not os.path.isfile('emp.dat'):
print("no file")
else:
fb=open('emp.dat','rb')
try:
while True:
nstu=[]
nstu=pickle.load(fb)
astu=astu+(nstu)
empno=int(nstu[0])
empname=nstu[1]
marks=int(nstu[2])
if marks>=10 and marks<=15:
print(empno,empname,marks)
except EOFError as error:
pass
fb.flush()
fb.close()
Readfile()
Practical 16

Write a program to plot a pie chart depicting the students in various


streams
import matplotlib.pyplot as plt
# Plot data
stream = ['Medical','Non-Medical','Comm with Maths','Comm with \
IP','Humanities']
no_students = [32,41,55,60,50]
colors = ['red', 'gold', 'yellowgreen', 'blue', 'lightcoral']
# explode 1st slice
explode = (0.1, 0, 0, 0,0)
# Plot
plt.pie(no_students, explode=explode, labels=stream, colors=colors)
plt.title("Grouping of Students on the basis of Allocated Streams" )
plt.show()
Practical 17

Write a program to plot a bar chart showing the choice of favorite movie
among the people

import numpy as np
import matplotlib.pyplot as plt
objects = ('Comedy', 'Action', 'Romance', 'Drama', 'SciFi')
y_pos = np.arange(len(objects))
Types = (4,5,6,1,4)
plt.bar(y_pos, Types, align='center', color='blue')
plt.xticks(y_pos, objects) #set location and label
plt.ylabel('People')
plt.title('Favourite Type of Movie')
plt.show()

Practical 18

Write a program to plot frequency of marks using Line Chart

import matplotlib.pyplot as plt

def fnplot(list1):

plt.plot(list1)

plt.title("Marks Line Chart")

plt.xlabel("Value")

plt.ylabel("Frequency")

plt.show()

list1= [50,50,50,65,65,75,75,80,80,90,90,90,90]

fnplot(list1)
Practical 19
Write a program to add, remove and display the book details using list
implementation #as a Queue

Library=[]
c='y'
while (c=='y'):
print ("1. INSERT")
print ("2. DELETE ")
print ("3. Display")
choice=int(input("Enter your choice: "))
if (choice==1):
book_id=input("Enter book_id : ")
bname = input("Enter the book name :")
lib = (book_id,bname) #tuple created for a new book
Library.append(lib) #new book added to the list/queue
elif (choice==2):
if (Library==[]):
print("Queue Empty")
else:
print("Deleted element is:",Library.pop(0))
elif (choice==3):
l=len(Library)
for i in range(0,l):
print (Library[i])
else:
print("wrong input")
c=input("Do you want to continue or not : ")
Practical 20
Write a program for implementation of List as stack
s=[]
c="y"
while (c=="y"):
print ("1. PUSH")
print ("2. POP ")
print ("3. Display")
choice=int(input("Enter your choice: "))
if (choice==1):
a=input("Enter any number :")
s.append(a)
elif (choice==2):
if (s==[]):
print ("Stack Empty")
else:
print ("Deleted element is : ",s.pop())
elif (choice==3):
l=len(s)
for i in range(l-1,-1,-1): #To display elements from last element to first
print (s[i])
print(s.reverse())
else:
print("Wrong Input")
c=input("Do you want to continue or not? ")
Practical 21

Write a program to check for all the databases, present in MySQL using
Python

import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="root",passwd="dps")
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)

Practical 22

Write a program to check whether the created table exists in MySQL using
Python Interface

import mysql.connector
mydb = mysql.connector.connect(host="localhost",\
user="root",\
passwd="dps",\
database="test")
mycursor = mydb.cursor()
mycursor.execute("SHOW TABLES")
for x in mycursor:
print(x)
Practical 23
Write a menu-driven program to demonstrate four major operations
performed on a table through MySQL-Python connectivity

def menu():
c='y'
while (c=='y'):
print ("1. add record")
print ("2. update record ")
print ("3. delete record")
print("4. display records")
print("5. Exiting")
choice=int(input("Enter your choice: "))
if choice == 1:
adddata()
elif choice== 2:
updatedata()
elif choice== 3:
deldata()
elif choice== 4:
fetchdata()
elif choice == 5:
print("Exiting")
break
else:
print("wrong input")
c=input("Do you want to continue or not: ")
def fetchdata():
import mysql.connector
try
db=mysql.connector.connect(host="localhost",user="root",password='dps', \
database='test')
cursor = db.cursor()
cursor.execute("SELECT * FROM students" )
results = cursor.fetchall()
for x in results:
print(x)
except:
print ("Error: unable to fetch data")

def adddata():
import mysql.connector
db=mysql.connector.connect(host='localhost',user='root',password='dps', \
database='test')
cursor = db.cursor()

cursor.execute("INSERT INTO students \


VALUES('1011','Ritu','XI','A','10','Gurgaon','9999210223')")

cursor.execute("INSERT INTO students \


VALUES('1003','Pihu','XII','B','13','Palam Vihar','9876210223')")
cursor.execute("INSERT INTO students \
VALUES('1006','Kartik','XI','A','14','Sushant lok','9899500042')")
cursor.execute("INSERT INTO students \
VALUES('1008','Neha','XII','B','20','Sector 15','9998752221')")
db.commit()
print("Records added")
def updatedata():
import mysql.connector
try:
db=mysql.connector.connect(host="localhost",user="root",password='dps',\
database='test')
cursor = db.cursor()
sql = ("Update students set sec='B' where name='Ritu'")
cursor.execute(sql)
print("Record Updated")
db.commit()
except Exception as e:
print (e)

def deldata():
import mysql.connector
db=mysql.connector.connect(host="localhost",user="root",password='dps', \
database='test')
cursor = db.cursor()
sql = "delete from students where name='Ritu'"
cursor.execute(sql)
print("Record Deleted")
db.commit()
menu()
Practical 24
views.py

Create a django application to display a table on the webpage.


from django.http import HttpResponse
from django.template import engines
from django.template.loader import render_to_string
def home(request):
title=" US"
author="vsbhs"
about_template='''
<html><head>
<title>Home Page</title></head>
<body>
<center><h1> About'''+title+'''</h1></center>
<center><p> Welcome to the
<font color=red>First Page</font> in HTML</p></center>
<center><table border=2 bgcolor=yellow>
<tr><th>Roll</th><th> Name</th><th>Age</th></tr>
<tr><td>1</td><td>Raman</td><td>12</td></tr>
<tr><td>2</td><td>Sohan</td><td>13</td></tr>
</table>
<center><p><h1>Thank you </h1></center>
</body>
</html>'''
django_engine=engines['django']
template=django_engine.from_string(about_template)
html=template.render({'title':title,'author':author})
return HttpResponse(html)

urls.py

from django.contrib import admin


from django.urls import path
from django.conf.urls import url
from newone12 import views
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^$',views.home),
]

Practical 25
views.py
Create a django application showing the use of GET method.
from django.http import HttpResponse
from django.template import loader
from django.template import engines
from django.template.loader import render_to_string
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt

def index(request):
if request.method=='GET':
name = request.GET.get('name')
v1=request.GET.get('v1')
v2=request.GET.get('v2')
v3=int(v1)+int(v2)
about_template='''
<html>
<head> <title>Home Page</title> </head>
<body>
<center>
Name '''+(name)+'''and the sum is '''+str(v3)+'''
<center><p><h1>Thank You</h1></center>
</body>
</html>'''
django_engine=engines['django']
template=django_engine.from_string(about_template)
html=template.render()
return HttpResponse(html)
else:
template = loader.get_template ('index.html')
return HttpResponse(template.render())
urls.py

from django.contrib import admin


from django.urls import path
from django.conf.urls import url
from newone13 import views
urlpatterns = [
url(r'^getdata/',views.index),
url(r'^$',views.index),
]

index.html

<html>
<head> <title>use of post</title></head>
<body>
<center><h2>use of post method</h2>
<form method="GET" action="\getdata\">
<table>
<tr><td>Enter your name:</td><td><input type="text" name ="name"/></td> </tr>
<tr> <td>Enter your value1:</td><td><input type="text"name="v1"/></td> </tr>
<tr><td>Enter your value2:</td><td><input type="text" name="v2"/></td> </tr>
<tr><td><button>Submit From</button></td></tr>
</table></form>
</center>
</body></html>
Output – Practical 16

Output – Practical 17
Output – Practical 18
Output – Practical 19
Output – Practical 20
Output – Practical 21

Output – Practical 22
Output – Practical 23
Output – Practical 24

Output – Practical 25

You might also like