0% found this document useful (0 votes)
215 views

Python Myssql Programs For Practical File Class 12 Ip

The programs demonstrate basic SQL operations like SELECT, INSERT, UPDATE and ORDER BY using Python and MySQL. One program inserts sample data into a database table. Another program fetches and prints this data using a SELECT query. A third program updates the data in the table using an UPDATE query and specifies an ORDER BY clause to sort the results.

Uploaded by

Pragyanand Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
215 views

Python Myssql Programs For Practical File Class 12 Ip

The programs demonstrate basic SQL operations like SELECT, INSERT, UPDATE and ORDER BY using Python and MySQL. One program inserts sample data into a database table. Another program fetches and prints this data using a SELECT query. A third program updates the data in the table using an UPDATE query and specifies an ORDER BY clause to sort the results.

Uploaded by

Pragyanand Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

1.

2
2. 3
3. 4
4. 5
5. 6
6. 7
7. 8
8. 9
9. 10
10. 11
11. 12
12. 13
13. 14
14. 15
15. 16
16. 17
17. 18
18. 19
19. 20
20. 21
21. 22
22. 23
23. 24
24. 25
25. 26

1
# A program to make invoice with GST calculator.
item=input(“Enter item name: “)
sp = float (input(“Enter selling price of items “+
item+ “: “))
gstRate=float(input(“Enter gst rate (%):”))
cgst=sp*((gstRate/2)/100)
sgst=cgst
amount=sp+cgst+sgst

print(“\t INVOICE”)
print(“Item:”,item)
print(“CGST (@”,(gstRate/2),”%):”,cgst)
print(“SGST (@”,(gstRate/2),”%):”,sgst)
print(“Amount Payable:”,amount)

OUTPUT

2
# A program to print Identity matrix of a no.
n=int(input(“enter a number:”))
for i in range(0,n):
for j in range(0,n):
if(i==j):
print(“1”,sep=“ “,end=“ “)
else:
print(“0”,sep=“ “,end=“ “)
print()

OUTPUT

3
# A program for a simple calculator.
num1=float(input(“Enter first number:”))
num2=float(input(“Enter second number:”))
op=input(“Enter operator[+,-,*,/,%]:”)
result=0
if op==‘+’:
result=num1+num2 OUTPUT
elif op==‘-’:
result=num1-num2
elif op==‘*’:
result=num1*num2
elif op==‘/’:
result=num1/num2
elif op==‘%’:
result=num1%num2
else:
print(“Invalid
operator!!”)print(num1,op,num2,’=‘,result)

4
# A program to find Compound interest.
def compound_interest(principle,rate,time):
result=principle*(pow((1+rate/100),time))
return result
p=float(input(“enter the priciple amount: “))
r=float(input(“enter the interest rate: “))
t=float(input(“enter the time in years: “))
amount=compound_interest(p,r,t)
interest=amount-p
print(“compound amount is %.2f” % amount)
print(“compound interest is %.3f” % interest)

OUTPUT

5
# A program to find marking grade.
sub1=int(input(“enter marks of the first subject:”))
sub2=int(input(“enter marks of the second subject:”))
sub3=int(input(“enter marks of the third subject:”))
sub4=int(input(“enter marks of the fourth subject:”))
sub5=int(input(“enter marks of the fifth subject:”))
avg=(sub1+sub2+sub3+sub4+sub5)/5
if(avg>=90):
print(“grade: A”)

elif(avg>=80 and avg<90): OUTPUT


print(“grade: B”)
elif(avg>=70 and avg<80):
print(“grade: C”)
elif(avg>=60 and avg<70):
print(“grade: D”)
else:
print(“grade: F”)

6
# A program to show basic operations on single array.
import numpy as np
a = np.array([[1, 2],[3, 4]])
b = np.array([[4, 3], [2, 1]])
# Adding 1 to every element
print (“Adding 1 to every element:”, a + 1)
# Subtracting 2 from each element
print (“\n Subtracting 2 from each element:”, b - 2)
# sum of array elements
print (“\n Sum of all array elements: “, a.sum())
# Adding two arrays
print (“\n Array sum:\n”, a + b)

OUTPUT

7
# A program to demonstrate indexing in numpy.
import numpy as np
arr = np.array([[-1, 2, 0, 4], [4, -0.5, 6, 0], [2.6, 0, 7, 8],
[3, -7, 4, 2.0]])
# Slicing array
temp = arr[:2, ::2]
print (“Array with first 2 rows and alternate
columns(0 and 2):\n”, temp)
# Integer array indexing example
temp = arr[[0, 1, 2, 3], [3, 2, 1, 0]]
print (“\nElements at indices (0, 3), (1, 2), (2, 1),
(3, 0):\n”, temp)

OUTPUT

8
# A program to demonstrate aggregate functions.

import numpy as np
array1 = np.array([[10, 20, 30], [40, 50, 60]])

print(“Mean: “, np.mean(array1))
print(“Std: “, np.std(array1))
print(“Var: “, np.var(array1))
print(“Sum: “, np.sum(array1))
print(“Prod: “, np.prod(array1))

OUTPUT

9
# A program to demonstrate unary operators.
import numpy as np
arr = np.array([[1, 5, 6], [4, 7, 2], [3, 1, 9]])
# maximum element of array
print (“Largest element is:”, arr.max())
print (“Row-wise maximum elements:”, arr.max(axis = 1))
# minimum element of array
print(“Column-wise minimum elements:”,arr.min(axis = 0))
# sum of array elements
print (“Sum of all array elements:”, arr.sum())
# cumulative sum along each row
print (“Cumulative sum along each row:\n”,
arr.cumsum(axis = 1))
OUTPUT

10
# A program to convert a dictionary into Dataframe.

import pandas as pd

# Define a dictionary containing employee data


data = {‘Name’:[‘Jai’, ‘Princi’, ‘Gaurav’, ‘Anuj’],
‘Age’:[27, 24, 22, 32],
‘Address’:[‘Delhi’, ‘Kanpur’, ‘Allahabad’, ‘Kannauj’],
‘Qualification’:[‘Msc’, ‘MA’, ‘MCA’, ‘Phd’]}
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
# select two columns
print(df[[‘Name’, ‘Address’]])

OUTPUT

11
# Program to find max and min values in a dataframe.

import pandas as pd
df = pd.DataFrame([[10, 20, 30, 40], [7, 14, 21, 28],
[55, 15, 8, 12],[15, 14, 1, 8], [7, 1, 1, 8], [5, 4, 9, 2]],
columns=[‘Apple’, ‘Orange’, ‘Banana’, ‘Pear’],
index=[‘Basket1’, ‘Basket2’, ‘Basket3’,
‘Basket4’, ‘Basket5’, ‘Basket6’])
print(“\n----------- Minimum -----------\n”)
print(df[[‘Apple’, ‘Orange’, ‘Banana’, ‘Pear’]].min())
print(“\n----------- Maximum -----------\n”)
print(df[[‘Apple’, ‘Orange’, ‘Banana’, ‘Pear’]].max())

OUTPUT

12
# Program to calculate Mean and mode in Dataframe.

import pandas as pd
df = pd.DataFrame([[10, 20, 30, 40], [7, 14, 21, 28], [55,
15, 8, 12], [15, 14, 1, 8], [7, 1, 1, 8], [5, 4, 9, 2]],
columns=[‘Apple’, ‘Orange’, ‘Banana’, ‘Pear’],
index=[‘Basket1’, ‘Basket2’, ‘Basket3’,
‘Basket4’, ‘Basket5’, ‘Basket6’])

print(“\n----------- Calculate Mean -----------\n”)


print(df.mean())
print(“\n----------- Calculate Mode -----------\n”)
print(df.mode())

OUTPUT

13
# A program for dataframe creation in pandas.

import pandas as pd

data = {‘Age’: [30, 20, 22, 40],


‘Height’: [165, 70, 120, 80],
‘Score’: [4.6, 8.3, 9.0, 3.3],
‘State’: [‘NY’, ‘TX’, ‘FL’, ‘AL’]
}
print(data)
df = pd.DataFrame(data)
print(df)

OUTPUT

14
# Program to draw two lines on same graph.
import matplotlib.pyplot as plt
x1 = [1,2,3]
y1 = [2,4,1]
# plotting the line 1 points
plt.plot(x1, y1, label = “line 1”)

x2 = [1,2,3] OUTPUT
y2 = [4,1,3]
# plotting the line 2 points
plt.plot(x2, y2, label = “line 2”)
# naming the x axis
plt.xlabel(‘x - axis’)
# naming the y axis
plt.ylabel(‘y - axis’)
plt.title(‘Two lines on same graph!’)
# show a legend on the plot
plt.legend()
plt.show()

15
# A program to draw a bar chart.
import matplotlib.pyplot as plt
# x-coordinates of left sides of bars
left = [1, 2, 3, 4, 5]
# heights of bars
height = [10, 24, 36, 40, 5]
# labels for bars
tick_label = [‘one’, ‘two’, ‘three’, ‘four’, ‘five’]
# plotting a bar chart
plt.bar(left, height, tick_label = tick_label,
width = 0.4, color = [‘red’, ‘green’,’blue’])
plt.xlabel(‘x - axis’)

plt.ylabel(‘y - axis’) OUTPUT


plt.title(‘My bar chart!’)
plt.show()

16
# A program to draw histogram.
import matplotlib.pyplot as plt
# frequencies
ages = [2,5,70,40,30,45,50,45,43,40,44,
60,7,13,57,18,90,77,32,21,20,40]
# setting the ranges and no. of intervals
range = (0, 100)
bins = 10
# plotting a histogram
plt.hist(ages, bins, range, color = ‘green’,
histtype = ‘bar’, rwidth = 0.8) OUTPUT
# x-axis label
plt.xlabel(‘age’)
# frequency label
plt.ylabel(‘No. of people’)
# plot title
plt.title(‘My histogram’)
plt.show()

17
# An SQL program to demonstrate ‘select’
command.

18
# An SQL program to demonstrate ‘update’
command.

19
# An SQL program to demonstrate ‘alter’
command to add a new column and update it.

20
# An SQL program to fetch query using
“select” command and “order by” clause.

21
# An SQL program to demonstrate aggregate
functions like “max”,” min”,” avg”
and “sum”.

22
# Program in python for inserting values in database table.
import mysql.connector
mydb=mysql.connector.connect(host=“localhost”,
user=“root”,passwd=“pnsql”, database=“pns”)
mycursor = mydb.cursor()

mycursor.execute(“insert into st_info


values(1,’Ram’,’Panjab’)”)
mycursor.execute(“insert into st_info
values(2,’Keshav’,’Gujrat’)”)
mycursor.execute(“insert into st_info values(3,’Raju’,’UP’)”)
mycursor.execute(“insert into st_info
values(4,’Rohan’,’Mumbai’)”)

mydb.commit()
print(mycursor.rowcount, “record inserted.”)

OUTPUT

23
# Program in python for fetching queries from database.
import mysql.connector

mydb = mysql.connector.connect(
host=“localhost”,
user=“root”,
passwd=“pnsql”,
database=“pns”)

mycursor = mydb.cursor()

mycursor.execute(“select * from st_info”)

myresult = mycursor.fetchall()

for x in myresult: OUTPUT


print(x)

24
# Program in python to use ‘order by clause of sql.
import mysql.connector

mydb = mysql.connector.connect(
host=“localhost”,
user=“root”,
passwd=“pnsql”,
database=“pns”)

mycursor = mydb.cursor()
sql = “select * from st_info order by name”
mycursor.execute(sql)
myresult = mycursor.fetchall()

for x in myresult: OUTPUT


print(x)

25
# Program in python to update values in database.
import mysql.connector

mydb = mysql.connector.connect( host=“localhost”,


user=“root”,passwd=“pnsql”, database=“pns”)

mycursor = mydb.cursor()

mycursor.execute(“UPDATE st_info SET


address=‘Uttarakhand’ WHERE Sr_no=3 “)

mydb.commit()

print(mycursor.rowcount, “record(s) affected”)

OUTPUT
Before Update After Update

26

You might also like