0% found this document useful (0 votes)
206 views36 pages

Pract File - Part3 - Final Computer Practical Helpful Notes Download It

It's the incomplete pyhton computer project file hoho yes according to new cbse circular kindly make a note of it

Uploaded by

Kavitha Kavitha
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)
206 views36 pages

Pract File - Part3 - Final Computer Practical Helpful Notes Download It

It's the incomplete pyhton computer project file hoho yes according to new cbse circular kindly make a note of it

Uploaded by

Kavitha Kavitha
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/ 36

PRACTICAL RECORD FILE

CLASS-XII SUBJECT – COMPUTER SCIENCE (083)


UNIT – I: PROGRAMMING & COMPUTATIONAL THINKING (Python)

Practical OBJECTIVES & SOLUTIONS


Number
No. (1)
AIM: Write a program in python to check a number whether it is prime or not.
SOURCE num=int(input("Enter the number: "))
CODE: for i in range(2,num):
if num % i == 0:
print(num, "is not prime number")
break;
else:
print(num,"is prime number")
EXPECTED
OUTPUT:

No.(2)
AIM: Write a program to check a number whether it is palindrome or not.

SOURCE num=int(input("Enter a number : "))


CODE: n=num
res=0
while num>0:
rem=num%10
res=rem+res*10
num=num//10
if res==n:
print("Number is Palindrome")
else:
print("Number is not Palindrome")
EXPECTED
OUTPUT:

No.(3)
AIM: Write a program to calculate compound interest.
SOURCE p=float(input("Enter the principal amount : "))
CODE: r=float(input("Enter the rate of interest : "))
t=float(input("Enter the time in years : "))
x=(1+r/100)**t
CI= p*x-p
print("Compound interest is : ", round(CI,2))
EXPECTED
OUTPUT:

No.(4)
AIM: Write a program to display ASCII code of a character and vice versa.

SOURCE CODE: var=True


while var:
choice=int(input("Press-1 to find the ordinal value of a character \nPress-2\
to find a character of a value\n"))
if choice==1:
ch=input("Enter a character : ")
print(ord(ch))
elif choice==2:
val=int(input("Enter an integer value: "))
print(chr(val))
else:
print("You entered wrong choice")
print("Do you want to continue? Y/N")
option=input()
if option=='y' or option=='Y':
var=True
else:
var=False
EXPECTED
OUTPUT:

No.(5)
AIM: Write a program to input a character and to print whether a given character is an
alphabet, digit or any other character.
SOURCE ch=input("Enter a character: ")
CODE: if ch.isalpha():
print(ch, "is an alphabet")
elif ch.isdigit():
print(ch, "is a digit")
elif ch.isalnum():
print(ch, "is alphabet and numeric")
else:
print(ch, "is a special symbol")

EXPECTED
OUTPUT:

No.(6)
AIM: Write a program to calculate the factorial of an integer using recursion.

SOURCE CODE: def factorial(n):


if n == 1:
return n
else:
return n*factorial(n-1)
num=int(input("enter the number: "))
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of ",num," is ", factorial(num))
EXPECTED
OUTPUT:

No.(7)
AIM: Write a program to print fibonacci series using recursion.

SOURCE CODE: def fibonacci(n):


if n<=1:
return n
else:
return(fibonacci(n-1)+fibonacci(n-2))
num=int(input("How many terms you want to display: "))
for i in range(num):
print(fibonacci(i)," ", end=" ")
EXPECTED
OUTPUT:

No.(8)
AIM: Write a program for binary search.

SOURCE CODE: def Binary_Search(sequence, item, LB, UB):


if LB>UB:
return -5 # return any negative value
mid=int((LB+UB)/2)
if item==sequence[mid]:
return mid
elif item<sequence[mid]:
UB=mid-1
return Binary_Search(sequence, item, LB, UB)
else:
LB=mid+1
return Binary_Search(sequence, item, LB, UB)
L=eval(input("Enter the elements in sorted order: "))
n=len(L)
element=int(input("Enter the element that you want to search :"))
found=Binary_Search(L,element,0,n-1)
if found>=0:
print(element, "Found at the index : ",found)
else:
print("Element not present in the list")
EXPECTED
OUTPUT:

No.(9)
AIM: Write a recursive python program to test if a string is palindrome or not.

SOURCE CODE: def isStringPalindrome(str):


if len(str)<=1:
return True
else:
if str[0]==str[-1]:
return isStringPalindrome(str[1:-1])
else:
return False
#__main__

s=input("Enter the string : ")


y=isStringPalindrome(s)
if y==True:
print("String is Palindrome")
else:
print("String is Not Palindrome")
EXPECTED
OUTPUT:

No.(10)
AIM: Write a program to count the number of vowels present in a text file.
SOURCE CODE: fin=open("D:\\b.txt",'r')
str=fin.read( )
count=0
for i in str:
if i=='a' or i=='e' or i=='i' or i=='o' or i=='u':
count=count+1
print(count)
EXPECTED
OUTPUT:

No.(11)
AIM: Write a program to write those lines which have the character 'p' from one text file to
another text file.
SOURCE CODE: fin=open("D:\\b.txt","r")
fout=open("D:\\a.txt","a")
s=fin.readlines( )
for j in s:
if 'p' in j:
fout.write(j)
fin.close()
fout.close()
EXPECTED
OUTPUT:

No.(12)

AIM: Write a program to count number of words in a file.


SOURCE CODE: fin=open("D:\\b.txt",'r')
str=fin.read( )
L=str.split()
count_words=0
for i in L:
count_words=count_words+1
print(count_words)
EXPECTEDOUT
PUT:

No.(13)
AIM:

SOURCE CODE: import math


def fact(k):
if k<=1:
return 1
else:
return k*fact(k-1)

step=int(input("How many terms : "))


x=int(input("Enter the value of x :"))
sum=0
for i in range(step):
sum+=(math.pow(-1,i)*math.pow(x,2*i+1))/fact(2*i+1)
print("The result of sin",'(', x, ')', "is :", sum)
EXPECTED
OUTPUT:

No.(14)
AIM: Write a program to generate random numbers between 1 to 6 and check whether a user
won a lottery or not.
SOURCE CODE: import random
n=random.randint(1,6)
guess=int(input("Enter a number between 1 to 6 :"))
if n==guess:
print("Congratulations, You won the lottery ")
else:
print("Sorry, Try again, The lucky number was : ", n)
EXPECTED
OUTPUT:

No.(15)
AIM: Write a program to plot a bar chart in python to display the result of a school for five
consecutive years.

SOURCE CODE: import matplotlib.pyplot as pl


year=['2015','2016','2017','2018','2019']# list of years
p=[98.50,70.25,55.20,90.5,61.50] #list of pass percentage
j=['b','g','r','m','c'] # color code of bar charts
pl.bar(year, p, width=0.2, color=j) # bar( ) function to create the bar chart
pl.xlabel("year") # label for x-axis
pl.ylabel("Pass%") # label for y-axis
pl.show( ) # function to display bar chart
EXPECTED
OUPUT:

No.(16)
AIM: Write a program in python to plot a graph for the function y = x2.

SOURCE CODE: import matplotlib.pyplot as pl


import numpy as np
x= np.linspace(-50,50);
y= x**2
pl.plot(x,y,linestyle='-')
pl.show( )
EXPECTED
OUTPUT:

No.(17)
AIM: Write a program in python to plot a pie chart on consumption of water in daily life.
SOURCE CODE: import matplotlib.pyplot as pl
consumption=[5,30,50,3]
pl.pie(consumption, labels=['drink','bath','washing_clothes','Cooking'], autopct= '
%1.1f%% ' )
pl.show( )
EXPECTED
OUTPUT:

No.(18)
AIM: Write a program for linear search.
SOURCE CODE: L=eval(input("Enter the elements: "))
n=len(L)
item=eval(input("Enter the element that you want to search : "))
for i in range(n):
if L[i]==item:
print("Element found at the position :", i+1)
break
else:
print("Element not Found")
EXPECTED
OUTPUT:

No.(19)
AIM: Write a program for bubble sort.

SOURCE CODE: L=eval(input("Enter the elements:"))


n=len(L)
for p in range(0,n-1):
for i in range(0,n-1):
if L[i]>L[i+1]:
t=L[i]
L[i]=L[i+1]
L[i+1]=t
print("The sorted list is : ", L)
EXPECTED
OUTPUT:

No.(20)
AIM: Write a program to count number of consonants in the given string.

SOURCE CODE: def isconsonant(ch):


ch=ch.upper()
return not(ch=="A" or ch=="E" or ch=="I" or ch=="O" or ch=="U") and
ord(ch)>=65 and ord(ch)<=90
def totalconsonant(string,n):
if n==1:
return isconsonant(string[0])
return totalconsonant(string,n-1) + isconsonant(string[n-1])

#____main___-
string="abcde"
length=len(string)
print(totalconsonant(string,length))
EXPECTED
OUTPUT:

No.(21)

AIM: Write a program to get the multiplication table of any number.

SOURCE CODE: def table(a,b):


if b<=10:
c=a*b
print(a,"*",b,"=",c)
table(a,b+1)

table_num=int(input("enter the table number:"))


table(table_num,0)
EXPECTED
OUTPUT:

No.(21)
AIM: Write a program to calculate a**b using iterative code.

SOURCE CODE: def power(a,b):


res=1
if b==0:
return 1
else:
for i in range(b):
res=res*a
return res
print("enter only the positive numbers below")
num=int(input("enter base number:"))
p=int(input("raised to power of:"))
result=power(num,p)
print(num,"raised to power of",p,"is",result)
EXPECTED
OUTPUT:

No.(22)
AIM: Write a program to diplay the contents of file"a.txt".

SOURCE CODE: fileinp=open("D:\\a.txt",'r')


Str=' '
while Str:
Str=fileinp.readline()
print(Str)
fileinp.close()
EXPECTED
OUTPUT:

No.(23)
AIM: Write a program in python to plot a pie chart on volunteering week collection.

SOURCE CODE: import matplotlib.pyplot as plt


col=[8000,9800,12000,11200,15500,7300]
x1=['mon','tue','wed','thu','fri','sat']
x2=['A','B','C','D','E','F']
plt.title("volunteering week collection")
plt.bar(x1,col,color='r',width=0.25)
plt.xlabel("days")
plt.ylabel("collection")
plt.show()
EXPECTED
OUTPUT:

No.(24)
AIM: Write a program for inserting an element in sorted array using traditional algorithm.
SOURCE CODE: def findpos(ar,item):
size=len(ar)
if item < ar[0]:
return 0
else:
pos=-1
for i in range(size-1):
if (ar[i]<=item and item<ar[i+1]):
pos=-1
break
if (pos==-1 and i<=size-1):
pos=size
return pos
def shift(ar,pos):
ar.append(None)
size=len(ar)
i=size-1
while i >= pos:
ar[i]=ar[i-1]
i=i-1

mylist=[10,20,30,40,50,60,70]
print("the list in sorted order is",mylist)
item=int(input("enter new element to be inserted :"))
position=findpos(mylist,item)
shift(mylist,position)
mylist[position]=item
print("the list after inserting",item,"is",mylist)
EXPECTED
OUTPUT:

No.(25)

AIM: Write a program in python insertion in sorted array using bisect module.

SOURCE CODE: import bisect


mylist=[10,20,30,40,50,60,70]
print("the list in sorted order is:",mylist)
item=int(input("enter new element to be inserted:"))
ind=bisect.bisect(mylist,item)
bisect.insort(mylist,item)
print(item,"inserted at index",ind)
print("the list after inserting new element is",mylist)
EXPECTED
OUTPUT:

No.(26)

AIM: Write a program for mathematical operations of two numbers.


SOURCE CODE: value1=eval(input("enter value 1:"))
value2=eval(input("enter value 2:"))
opp=input("enter operator(+,-,*,/):")
result=0
while value2 > 0 or value2 < 0:
if opp=="+":
result=value1+value2
elif opp=="-":
if value1 > value2:
result=value1-value2
else:
result=value2-value1
elif opp=="*":
result=value1*value2
elif opp=="/":
result=value1/value2
else:
print("choose any correct operation to do:")
print("The Result:",value1,opp,value2,"is",result)
break
else:
print("enter a NON ZERO value for value2")
EXPECTED
OUTPUT:

No.(27)
AIM: Write a program in python to calculate total amount to be paid including GST.

SOURCE CODE: choice="y"


total=0.0
while choice=="y" or choice=="Y":
item_price=int(input("enter the item price:"))
gst=int(input("enter the GST on the item:"))
total+=(item_price+((item_price*gst)/100))
choice=input("press y to continue else press any other key:")
print("total amount to be paid:",total)
EXPECTED
OUTPUT:

No.(28)
AIM: Write a proram in python for implementation of queue as a list.

SOURCE CODE: 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=int(input("enter book_id:"))
bname=input("enter the book name:")
lib=(book_id,bname)
library.append(lib)
elif choice==2:
if library==[]:
print("queue empty")
else:
book_id,bname=library.pop()
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(y/n):")
EXPECTED
OUTPUT:

No.(29)
AIM: Write a program in python for implementation of stack using list.

SOURCE CODE: employee=[]


c="y"
while (c=="y"):
print("1.push")
print("2.pop")
print("3.display")
choice=int(input("enter your choice:"))
if choice==1:
e_id=int(input("enter employee no.:"))
ename=input("enter the employee name:")
emp=(e_id,ename)
employee.append(emp)
elif choice==2:
if employee==[]:
print("stack empty")
else:
e_id,ename=employee.pop()
print("deleted element is:",e_id,ename)
elif choice==3:
i=len(employee)
while i>0:
print(employee[i-1])
i=i-1
else:
print("wrong input")
c=input("do you want to continue or not(y/n):")
EXPECTED
OUTPUT:

No.(30)
AIM: Write a program in python to implement queue operations.

SOURCE CODE: """


queue:implemented as a list
front:integer having position of first(frontmost) element in queue
rear :integer having position of last element in queue
"""
def cls():
print("\n"*100)

def isempty(qu):
if qu==[]:
return True
else:
return False

def enqueue(qu,item):
qu.append(item)
if len(qu)==1:
front=rear=0
else:
rear=len(qu)-1

def dequeue(qu):
if isempty(qu):
return "underflow"
else:
item=qu.pop(0)
return item

def peek(qu):
if isempty(qu):
return "underflow"
else:
front=0
return qu[front]

def display(qu):
if isempty(qu):
print("queue empty!")
elif len(qu)==1:
print(qu[0],"<==front,rear")
else:
front=0
rear=len(qu)-1
for a in range(1,rear):
print(qu[a])
print(qu[rear],"<-rear")

## main ##
queue=[]
front=None
while True:
cls()
print("QUEUE OPERATIONS")
print("1.Enqueue")
print("2.Dequeue")
print("3.peek")
print("4.display")
print("5.exit")
ch=int(input("enter your choice(1...5):"))
if ch==1:
item=int(input("enter item:"))
enqueue(queue,item)
# input("press enter to continue")
elif ch==2:
item=dequeue(queue)
if item=="underflow":
print("underflow queue is empty")
else:
print("dequeue-ed item is empty!")
# input("press enter to continue...")
elif ch==3:
item=peek(queue)
if item=="underflow":
print("queue is empty")
else:
print("frontmost item is ",item)
# input("press enter to continue..")
elif ch==4:
display(queue)
# input("press enter to continue...")
elif ch==5:
break
else:
print("invalid choice")

EXPECTED
OUTPUT:

No.(31)
AIM: Write a program to find the most common phising email from a list of 10 emails saved
in a text file named email.txt .
SOURCE CODE: import collections
fin = open('D:\\email.txt','r')
a= fin.read()
d={ }
L=a.lower().split()
for word in L:
word = word.replace(".","")
word = word.replace(",","")
word = word.replace(":","")
word = word.replace("\"","")
word = word.replace("!","")
word = word.replace("&","")
word = word.replace("*","")
for k in L:
key=k
if key not in d:
count=L.count(key)
d[key]=count
n_print = int(input("How many most common words to print: "))
print("\nOK. The {} most common email are as follows\n".format(n_print))
word_counter = collections.Counter(d)
for word, count in word_counter.most_common(n_print):
print(word, ": ", count)
fin.close()
EXPECTED
OUTPUT:

No.(32)
AIM: Write a program to create a graphical calculator using tkinter library.
SOURCE CODE: from tkinter import *
def btnClick(number):
global operator
operator=operator+str(number)
strvar.set(operator)
def btnClear():
global operator
operator=''
strvar.set(operator)
def result():
global operator
res=str(eval(operator))
strvar.set(res)
root=Tk()
root.title("Calculator")
operator=''
strvar=StringVar()
ent=Entry(root,width=50,bd=5,font=('arial',10,"bold"),bg="powder
blue",textvariable=strvar,justify="right").grid(columnspan=4)
btn7=Button(root,text="7",padx=10,pady=10,font=('arial',10,"bold"),bg="powder
blue",command=lambda:btnClick(7)).grid(row=1,column=0)
btn8=Button(root,text="8",padx=10,pady=10,font=('arial',10,"bold"),bg="powder
blue",command=lambda:btnClick(8)).grid(row=1,column=1)
btn9=Button(root,text="9",padx=10,pady=10,font=('arial',10,"bold"),bg="powder
blue",command=lambda:btnClick(9)).grid(row=1,column=2)
btnPlus=Button(root,text="+",padx=10,pady=10,font=('arial',10,"bold"),bg="powder
blue",command=lambda:btnClick('+')).grid(row=1,column=3)
btn4=Button(root,text="4",padx=10,pady=10,font=('arial',10,"bold"),bg="powder
blue",command=lambda:btnClick(4)).grid(row=2,column=0)
btn5=Button(root,text="5",padx=10,pady=10,font=('arial',10,"bold"),bg="powder
blue",command=lambda:btnClick(5)).grid(row=2,column=1)
btn6=Button(root,text="6",padx=10,pady=10,font=('arial',10,"bold"),bg="powder
blue",command=lambda:btnClick(6)).grid(row=2,column=2)
btnMinus=Button(root,text="-",padx=10,pady=10,font=('arial',10,"bold"),bg="powder
blue",command=lambda:btnClick('-')).grid(row=2,column=3)
btn1=Button(root,text="1",padx=10,pady=10,font=('arial',10,"bold"),bg="powder
blue",command=lambda:btnClick(1)).grid(row=3,column=0)
btn2=Button(root,text="2",padx=10,pady=10,font=('arial',10,"bold"),bg="powder
blue",command=lambda:btnClick(2)).grid(row=3,column=1)
btn3=Button(root,text="3",padx=10,pady=10,font=('arial',10,"bold"),bg="powder
blue",command=lambda:btnClick(3)).grid(row=3,column=2)
btnMulti=Button(root,text="x",padx=10,pady=10,font=('arial',10,"bold"),bg="powder
blue",command=lambda:btnClick('*')).grid(row=3,column=3)
btn0=Button(root,text="0",padx=10,pady=10,font=('arial',10,"bold"),bg="powder
blue",command=lambda:btnClick(0)).grid(row=4,column=0)
btnClear=Button(root,text="C",padx=10,pady=10,font=('arial',10,"bold"),bg="powder
blue",command=btnClear).grid(row=4,column=1)
btnEqual=Button(root,text="=",command=result,padx=10,pady=10,font=('arial',10,"bol
d"),bg="powder blue").grid(row=4,column=2)
btnDivide=Button(root,text="/",padx=10,pady=10,font=('arial',10,"bold"),bg="powder
blue",command=lambda:btnClick('/')).grid(row=4,column=3)
Label(root,text="By:
ARUN.K.S",font=('COOPBAL',10,'italic'),fg='white',bg='black').grid(row=5,columnsp
an=4)
root.mainloop( )
EXPECTED
OUTPUT:

No.(33)
AIM: Write a program to open a webpage using urllib library.
SOURCE CODE: import urllib.request
data = urllib.request.urlopen('https://pythonschoolkvs.wordpress.com/')
print(data.read())
EXPECTED
OUTPUT:

No.(34)
AIM: Write a program to calculate EMI for a loan using numpy.
SOURCE CODE: import numpy as np
interest_rate= float(input("Enter the interest rate : "))
monthly_rate = (interest_rate)/ (12*100)
years= float(input("Enter the total years : "))
number_month = years * 12
loan_amount= float(input("Enter the loan amount : "))
emi = abs(np.pmt(monthly_rate, number_month, loan_amount))
print("Your EMI will be Rs. ", round(emi, 2))
EXPECTED
OUTPUT:

UNIT – II: COMPUTER NETWORKS


Topic: Usage of Network TOOLS
(1) traceroute: A traceroute (tracert) is a command which traces the path from one network to
another. This command is given from Command prompt using Administrator privilege.
Syntax: tracert hostname (where hostname is name of the server connection we are testing.)
Example: tracert msn.com will give following output:

(2) ping: The ping command to test the availability of a networking device on a network.
If we receive a reply then the device is working OK, if we don’t then the device is faulty,
disconnected, switched off, incorrectly configured.
Syntax: ping IP address
Example: ping 162.215.252.78 (the website: http://www.cbseacademic.nic.in/)

(3) ipconfig : Displays all current TCP/IP network configuration values and refresh Dynamic Host
Configuration Protocol and Domain Name System settings.
Syntax: ipconfig
Example: ipconfig cbseacademic.nic.in

(4) nslookup : The nslookup (which stands for name server lookup) command is a network utility
program used to obtain information about internet servers. It finds name server information for
domains by querying the Domain Name System.
Syntax: nslookup domainname
Example: nslookup
(5) whois : The ‘whois’ command is a simple command-line utility that allows we to easily get
information about a registered domain. It automatically connect to the right WHOIS server,
according to the top-level domain name, and retrieve the WHOIS record of the domain. It supports
both generic domains and country code domains. Note: We need to use this command along with
‘nslookup’ command.

Syntax: nslookup
>whois domainname
Example: nslookup
>whois amazon.in

(6) speed-test: To test the internet speed using command prompt, firstly we need to install the
following using pip command.
C:\>pip install speedtest-cli
After successfully installation of above, run the following command.
speedtest-cli
UNIT – III: DATA MANAGEMENT
Topic: Usage of MySQL, Python MySQL Connectivity and Django based Web application
No.(35)
AIM: To find a min, max, sum and average of the marks in a student marks table.

TABLE USED:

MYSQL select min(marks) from student;


QUERY:
OUTPUT:

MYSQL select max(marks) from student;


QUERY:
OUTPUT:

MYSQL select sum(marks) from student;


QUERY:
OUTPUT:

MYSQL select avg(marks) from student;


QUERY:
OUTPUT:

No.(36)
AIM: To find the total number of customers from each country in the table using group by.

TABLE USED:

MYSQL select country,count(*) from customer group by country;


QUERY:
OUTPUT:

No.(37)
AIM: To write a SQL query to display (student ID,marks) from student table in descending
order of the marks.

TABLE USED:
MYSQL select student_id,marks from student group by marks desc;
QUERY:
OUTPUT:

No.(38)

AIM: To integrate SQL with python by importing the MySQL module.

A. Write a program in python to create a database.

SOLUTION: import mysql.connector as sqltor


mydb=sqltor.connect(host="localhost",user="root",passwd="mysql")
mycursor=mydb.cursor()
mycursor.execute("create database if not exists school")
mycursor.execute("show databases")
for x in mycursor:
print(x)
mydb.close()
OUTPUT:

B. Write a program in python to create a table and describe.

SOLUTION: import mysql.connector as sqltor


mydb=sqltor.connect(host="localhost",user="root",passwd="mysql",database="school"
)
mycursor=mydb.cursor()
mycursor.execute("create table student(rollno int(3) primary key,name varchar(20),\
age int(2))")
mycursor.execute("show tables")
for x in mycursor:
print(x)
mycursor.execute("desc student")
for x in mycursor:
print(x)
mydb.close()
OUTPUT:

C. Write a program in python to insert into tables(getting input from the user).

SOLUTION: import mysql.connector as sqltor


mydb=sqltor.connect(host="localhost",\
user="root",\
passwd="mysql",database="schools")
mycursor=mydb.cursor()
name1=input("enter name:")
mycursor.execute("insert into student values(%s,'%s',%s,'%s',%s)"
%(45,name1,24,'tn',541))
mydb.commit()
mycursor.execute("select * from student")
for x in mycursor:
print(x)
mydb.close()
OUTPUT:

D. Write a program in python to select.

SOLUTION: import mysql.connector as sqltor


mydb=sqltor.connect(host="localhost",user="root",passwd="mysql",database="schools
")
mycursor=mydb.cursor()
mycursor.execute("select * from student")
myrecords=mycursor.fetchall()
n=mycursor.rowcount
print("total number of rows:",n)
for x in myrecords:
print(x)
mydb.close()
OUTPUT:

E. Write a program in python to update the record from the table.

SOLUTION: import mysql.connector as sqltor


mydb=sqltor.connect(host="localhost",\
user="root",\
passwd="mysql",database="schools")
mycursor=mydb.cursor()
mycursor.execute("update student set marks=100 where rollno=2")
mydb.commit()
mycursor.execute("select * from student")
for x in mycursor:
print(x)
mydb.close()
OUTPUT:

F. Write a program in python to delete the record from the table.

SOLUTION: import mysql.connector as sqltor


mydb=sqltor.connect(host="localhost",\
user="root",\
passwd="mysql",database="schools")
mycursor=mydb.cursor()
mycursor.execute("delete from student where rollno=1")
mydb.commit()
mycursor.execute("select * from student")
for x in mycursor:
print(x)
mydb.close()
OUTPUT:
Django

No.(39)
AIM: To write a Django based web server to parse a user request (POST), and write it to a CSV
file.
PROGRAM
:
STEP1: First a ‘demo’ folder is created with path- ‘C:\Demo’. Then the following commands
given in Windows command prompt.

STEP2: Following is the directory structure of our Django application.


STEP3: The following commands given in command line going inside the base project
directory, i.e. ‘myproject’ folder for creating the project app, i.e. ‘webapp’ folder is created
now.

STEP4: Following is the directory structure of our Django application ‘webapp’.

STEP5: we need to import our application manually inside project ‘settings.py’by manually
typing ‘webapp’ inside Application Definitions.
STEP6: Now we open webapp/views.py and put below code init
STEP7: Now we need to map this view to a URL. So, we create a new python file “urls.py”
inside our ‘webapp’. In webapp/urls.py include the following code:

STEP8: Open ‘myproject/urls.py’ file and write the below code to point the root URL conf at
the webapp.urls module

STEP9: Replace the existing code with following code in ‘webapp/views.pyfile’.


STEP10: Finally we need to move to folder of manage.py file, run the server with command:
python manage.pyrunserver. After running the server, go to the browser and type in
address bar: http://localhost:8000/webapp/

The output is displayed from the application as shown below:


OUTPUT:

****** THANK YOU ******

You might also like