Ip Lab Manual (Python) 2019-20
Ip Lab Manual (Python) 2019-20
Practical Syllabus
Business use-case diagrams for an airline ticket booking system, train reservation system, stock
exchange
Collaboratively write a program and manage the code with a version control system (GIT)
PRACTICAL FILE –INFORMATICS PRACTICES (065)
LIST OF PRACTICALS (2019-20) CLASS-XII
Programming Language: Python
Find the min, max, sum, and average of the marks in a student marks table.
Aggregate functions:
These functions are used to do operations from the values of the column and a single value is returned.
1. AVG()
2. COUNT()
3. FIRST()
4. LAST()
5. MAX()
6. MIN()
7. SUM()
Students-Table
Aggregate Functions
MAX(): The MAX() function returns the maximum value of the selected column.
Syntax:
SELECT MAX(column_name) FROM table_name;
Queries:
MaxMarks
95
Fetching max age among students from the Students table.
SELECT MAX(AGE) AS MaxAge FROM Students;
Output:
MaxAge
21
MIN(): The MIN() function returns the minimum value of the selected column.
Syntax:
SELECT MIN(column_name) FROM table_name;
Queries:
Fetching minimum marks among students from the Students table.
SELECT MIN(MARKS) AS MinMarks FROM Students;
Output:
MinMarks
50
Fetching minimum age among students from the Students table.
SELECT MIN(AGE) AS MinAge FROM Students;
Output:
MinAge
18
SUM (): The SUM () function returns the sum of all the values of the selected column.
Syntax:
SELECT SUM (column_name) FROM table_name;
Queries:
Fetching summation of total marks among students from the Students table.
SELECT SUM(MARKS) AS TotalMarks FROM Students;
Output:
TotalMarks
400
Fetching summation of total age among students from the Students table.
SELECT SUM(AGE) AS TotalAge FROM Students;
Output:
TotalAge
97
Find the total number of customers from each country in the table (customer ID,
customer Name, country) using group by.
4 Around the Horn Thomas 120 Hanover Sq. London WA1 1DP UK
Hardy
COUNT(CustomerID) Country
2 Germany
2 France
1 Canada
1 UK
1 Spain
2 Mexico
1 Sweden
Write a SQL query to order the (student ID, marks) table in descending order of the
marks.
3 Arnold Three 55
import mysql.connector
db_connection = mysql.connector.connect
(
host="hostname",
user="username",
passwd="password"
)
Example,
import mysql.connector
db_connection = mysql.connector.connect(
host="localhost",
user="root",
passwd="root"
)
print(db_connection)
Output:
Write a Django based web server to parse a user request (POST), and write it to a
CSV file.
Here’s an example:
import csv
from django.http import HttpResponse
def some_view(request):
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
writer = csv.writer(response)
writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])
return response
The code and comments should be self-explanatory, but a few things deserve a mention:
The response gets a special MIME type, text/csv. This tells browsers that the document is a CSV file, rather
than an HTML file. If you leave this off, browsers will probably interpret the output as HTML, which will
result in ugly, scary gobbledygook in the browser window.The response gets an additional Content-
Disposition header, which contains the name of the CSV file. This filename is arbitrary; call it whatever you
want. It’ll be used by browsers in the “Save as…” dialog, etc.You can hook into the CSV-generation API by
passing response as the first argument to csv.writer. The csv.writer function expects a file-like object, and
HttpResponse objects fit the bill. For each row in your CSV file, call writer.writerow, passing it an iterable.
The CSV module takes care of quoting for you, so you don’t have to worry about escaping strings with
quotes or commas in them. Pass writerow() your raw strings, and it’ll do the right thing.
Use map functions to convert all negative numbers in a Data Frame to the mean of
all the numbers.
In [3]: df
Out[3]:
a b
0 0 -3
1 -1 2
2 2 1
In [5]: df
Out[5]:
a b
0 0 0
1 0 2
2 2 1
Consider a Data Frame, where each row contains the item category, item name, and
expenditure. Group the rows by the category, and print the total expenditure per
category.
Pandas GroupBy
Groupby is a pretty simple concept. We can create a grouping of categories and apply a function to the
categories. It’s a simple concept but it’s an extremely valuable technique that’s widely used in data science.
In real data science projects, you’ll be dealing with large amounts of data and trying things over and over,
so for efficiency, we use Groupby concept. Groupby concept is really important because it’s ability to
aggregate data efficiently, both in performance and the amount code is magnificent.
print(df)
numpy.percentile() in python
numpy.percentile()function used to compute the nth precentile of the given data (array elements) along
the specified axis.
Return :nth Percentile of the array (a scalar value if axis is none)or array with percentile values along
specified axis.
Code #1 : Working
import numpy as np
# 1D array
arr = [20, 2, 7, 1, 34]
print("arr : ", arr)
print("50th percentile of arr : ", np.percentile(arr, 50))
print("25th percentile of arr : ", np.percentile(arr, 25))
print("75th percentile of arr : ", np.percentile(arr, 75))
Output :
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web
style.use('ggplot')
start = dt.datetime(2015, 1, 1)
end = dt.datetime.now()
df = web.DataReader("TSLA", 'morningstar', start, end)
df.reset_index(inplace=True)
df.set_index("Date", inplace=True)
df = df.drop("Symbol", axis=1)
print(df.head())
Simple linear regression is an approach for predicting a response using a single feature.
It is assumed that the two variables are linearly related. Hence, we try to find a linear function that
predicts the response value(y) as accurately as possible as a function of the feature or independent
variable(x).
Let us consider a dataset where we have a value of response y for every feature x:
For generality, we define:
x as feature vector, i.e x = [x_1, x_2, …., x_n],
y as response vector, i.e y = [y_1, y_2, …., y_n]
for n observations (in above example, n=10).
A scatter plot of above dataset looks like:-
import numpy as np
import matplotlib.pyplot as plt
return(b_0, b_1)
# putting labels
plt.xlabel('x')
plt.ylabel('y')
def main():
# observations
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
y = np.array([1, 3, 2, 5, 7, 8, 8, 9, 10, 12])
# estimating coefficients
b = estimate_coef(x, y)
print("Estimated coefficients:\nb_0 = {} \
\nb_1 = {}".format(b[0], b[1]))
if __name__ == "__main__":
main()
Business use-case diagrams for an airline ticket booking system, train reservation
system, stock exchange
Collaboratively write a program and manage the code with a version control system
(GIT)
What is Git?
By far, the most widely used modern version control system in the world today is Git. Git is a mature,
actively maintained open source project originally developed in 2005 by Linus Torvalds, the famous
creator of the Linux operating system kernel. A staggering number of software projects rely on Git for
version control, including commercial projects as well as open source. Developers who have worked with
Git are well represented in the pool of available software development talent and it works well on a wide
range of operating systems and IDEs (Integrated Development Environments).
Having a distributed architecture, Git is an example of a DVCS (hence Distributed Version Control System).
Rather than have only one single place for the full version history of the software as is common in once-
popular version control systems like CVS or Subversion (also known as SVN), in Git, every developer's
working copy of the code is also a repository that can contain the full history of all changes.In addition to
being distributed, Git has been designed with performance, security and flexibility in mind.