LN 13 14 15 16
LN 13 14 15 16
LN 13 14 15 16
Part - II
1. What is CSV File?
A CSV file is a human readable text file where each line has a number of fields, separated by commas or some other
delimiter. We can assume each line as a row and each field as a column.
1
Part - III
1. Write a note on open() function of python. What is the difference between the two methods?
Python has a built-in function to open a file. This function returns a file object, also called a handle, as it is used to read
or modify the file accordingly.
open ():
Example:
f = open(‘test.csv’)
with statement:
Example:
with open(‘test.csv’) as f:
The main difference between open( ) method and with statement is, open( ) method is not entirely safe. If an exception
occurs when we are performing some operation with the file, the code exits without closing the file. Whereas with
statement ensures that the file is closed when the block inside with is exited. We need not to explicitly call the close()
method. It is done internally.
f is file object to perform file operations.
Closing a file will free up the resources that were tied with the file and is done using Python close( ) method.
2
3. Write a Python program to read a CSV file with default delimiter comma (,).
import csv
csv.register_dialect('mydialect',delimiter = ',')
rf=open(‘test.csv’, ’r’)
row=csv.reader(rf, dialect=’mydialect’)
for i in row:
print(i)
rf.close( )
4. What is the difference between the write mode and append mode.
write mode append mode
Open a file for writing. Creates a new file if it does Open for appending at the end of the file without
not exist or truncates the file if it exists. truncating it. Creates a new file if it does not exist.
EX: f = open(‘test.csv’,'w') EX: f = open(‘test.csv’,'a')
Part – IV
1. Differentiate Excel file and CSV file.
Excel CSV
Excel is a binary file that holds information about all CSV format is a plain text format with a series of
the worksheets in a file, including both content and values separated by commas.
formatting.
Excel files can only be read by applications that have CSV can be opened with any text editor in Windows
been especially written to read their format, and can like notepad, MS Excel, Open Office, etc.
only be written in the same way.
Excel is a spreadsheet that saves files into its own CSV is a format for saving tabular information into a
proprietary format viz. .xls or .xlsx delimited text file with extension .csv
Excel consumes more memory while importing data Importing CSV files can be much faster, and it also
consumes less memory
3
2. Tabulate the different mode with its meaning.
Python File Modes
Mode Description
‘r’ Open a file for reading. (default)
‘w’ Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
‘x’ Open a file for exclusive creation. If the file already exists, the operation fails.
‘a’ Open for appending at the end of the file without truncating it. Creates a new file if it does not
exist.
‘t’ Open in text mode. (default)
‘b’ Open in binary mode.
‘+’ Open a file for updating (reading and writing)
4
4. To read CSV files-With custom Quotes:
import csv
csv.register_dialect('mydialect', delimiter = ',' , quoting=csv.QUOTE_ALL)
rf=open(‘test.csv','r')
row = csv.reader(rf, dialect='mydialect')
for i in row:
print(i)
rf.close()
5
The csv.writer() method returns a writer object which converts the user’s data into delimited strings on the given file-
like object.
The writerow() method writes one row at a time. If we need to write all the data at once we can use writerows()
method.
Syntax: csv.writer(fileobject,delimiter,fmtparams)
fileobject : passes the path and the mode of the file.
delimiter : an optional parameter containing the standard dilects like , | etc can be omitted.
fmtparams : optional parameter which help to override the default values of the dialects like
skipinitialspace,quoting etc. can be omitted.
Example:
import csv
dt = [[‘Student’, ‘Age’], [‘Bala’, ‘20’], [‘Veeru’, ‘18’], [‘Param’, ‘15’]]
wf=csv.open(‘test.csv’, ’w’)
row = csv.writer(wf)
row.writerows(dt)
wf.close( )_____________________________________________________________________________________
PROGRAMS:
1. To read CSV files- data with Spaces at the beginning:
import csv
csv.register_dialect('mydialect',delimiter = ',' ,skipinitialspace=True)
rf=open(‘test.csv','r')
row = csv.reader(rf, dialect='mydialect')
for i in row:
print(i)
rf.close()
_________________________________________________________________________________________
2. To read CSV files- data With Quotes:
import csv
csv.register_dialect('mydialect', delimiter = ',' , quoting=csv.QUOTE_ALL)
rf=open(‘test.csv','r')
row = csv.reader(rf, dialect='mydialect')
for i in row:
print(i)
rf.close()
____________________________________________________________________________________________
3. To read CSV files- data with Custom Delimiters:
import csv
csv.register_dialect('mydialect', delimiter = '|')
rf=open(‘test.csv','r')
row = csv.reader(rf, dialect='mydialect')
for i in row:
print(i)
rf.close()
4. Read A CSV File And Store It In A List
6
To read a CSV file and the contents of the file will be stored as a list.
import csv
rf=open(‘test.csv','r')
row = csv.reader(rf)
lt =list(row)
for i in lt:
print(lt)
rf.close()
____________________________________________________________________________________________
5. Read a specific column of File and store it in a list:
The content of “sample.csv”:
Rollno Name Age
1 Param 5
2 Veeru 35
3 Bala 30
To get the specific columns like only Name and Age of the student from “test.csv” file:
import csv
rf=open(‘test.csv’, ’r’)
row=csv.reader(rf)
lt=list(row)
for i in lt :
print (i[1],i[2])
rf.close()
7
import csv
csv.register_dialect('mydialect', delimiter = ',' , quotechar=’”’, quoting=csv.QUOTE_ALL)
dt = [[‘Student’, ‘Age’], [‘Bala’, ‘20’], [‘Veeru’, ‘18’], [‘Param’, ‘15’]]
wf=csv.open(‘test.csv’, ’w’)
row = csv.writer(wf, dialect=’mydialect’)
row.writerows(dt)
wf.close( )
______________________________________________________________________________________
Part - III
1. Differentiate PYTHON and C++
PYTHON C++
Python is typically an "interpreted" language C++ is typically a "compiled" language
Python is a dynamic-typed language C++ is compiled statically typed language
Data type is not required while declaring variable Data type is required while declaring
variable
It can act both as scripting and general purpose It is a general purpose language
language
9
To automate certain tasks in a program
Extracting information from a data set
Less code intensive as compared to traditional programming language
can bring new functions to applications and glue complex systems together
Part - IV
10
sys module helps to interact strongly with interpreter by accessing some built-in variables used by the interpreter. One
among the variable in sys module is argv.
sys.argv is the list of command-line arguments passed to the Python program.
The first argument - sys.argv[0] contains the name of the python program.
The second argument - sys.argv[1] contains the name of the C++ file without extension.
Example:
main(sys.argv[1])
The input C++ file is send along with its path as a list using argv[1].
argv[0] contains the Python file which is need not to be passed because by default __main__ contains source code
reference.
OS MODULE:
The OS module helps to use operating system dependent functionality. It allows us to interface with the Windows
operating system where Python is running on.
os.system() It helps to invoke g++ compiler to compile and execute C++ program on windows environment.
Syntax:
os.system (‘g++ ’ + <variable_name1> ‘-<mode>’ + <variable_name2>)
os.system Defined in os module to interact with the operating system.
g++ General compiler to compile C++ program under Windows Operating system.
variablename1 Name of the C++ file along with its path and without extension (.cpp)
mode To specify input or output mode.
Variablename2 Name of the executable file without extension( .exe)
Example:
os.system(‘g++’ + cpp_file + ‘-o’ + exe_file) g++ compiler compiles the cpp_file and output send to exe_file.
getopt MODULE:
getopt module helps to parse (split) command-line options and arguments.
getopt() method returns value consisting of two elements. Each of these values are stored separately in two different
list opts and args.
Opts contains list of splitted strings like mode and path.
args contains error string, if the command is given with wrong path or mode otherwise args will be an empty list.
Syntax:
<opts>,<args>=getopt.getopt(argv, options, [long_options])
argv This is the argument list of values to be parsed (splitted).
In our program the complete command will be passed as a list.
For example c:\pyprg\pali.py -i c:\pyprg\pali_cpp
options Python program recognize as input or output, with options (like ‘i’ or ‘o’)
that followed by a colon (:). Here colon is used to denote the mode.
long_options In our program the C++ file name along with its path will be passed as string
and ‘i’ will be also passed to indicate it as the input file.
Example:
opts, args = getopt.getopt (argv, "i:")
4. Write the syntax for getopt() and explain its arguments and return values
<opts>,<args>=getopt.getopt(argv, options, [long_options])
11
argv This is the argument list of values to be parsed (splitted). In our program the
complete command will be passed as a list.
For example c:\pyprg\pali.py -i c:\pyprg\pali_cpp
options Python program recognize as input or output, with options (like ‘i’ or ‘o’)
that followed by a colon (:). Here colon is used to denote the mode.
long_options In our program the C++ file name along with its path will be passed as string
and ‘i’ will be also passed to indicate it as the input file.
Scripting language:
A scripting language is a programming language designed for integrating and communicating with other programming
languages. Some of the most widely used scripting languages are JavaScript, VBScript, PHP, Perl, Python, Ruby, ASP and
Tcl.
Garbage Collection:
Python deletes unwanted objects automatically to free the memory space. The process by which Python periodically
frees and reclaims blocks of memory that no longer are in use is called Garbage Collection.
12
Importing C++ program in a Python program is called wrapping up of C++ in Python. Wrapping or creating Python
interfaces for C++ programs are done in many ways.
The commonly used interfaces are:
• Python-C-API (API-Application Programming Interface for interfacing with C programs)
• Ctypes (for interfacing with c programs)
• SWIG (Simplified Wrapper Interface Generator- Both C and C++)
• Cython (Cython is both a Python-like language for writing C-extensions)
• Boost. Python (a framework for interfacing Python and C++)
• MinGW (Minimalist GNU for Windows)
g++
To compile and execute the C++ program, we need ‘g++’ for Windows.
MinGW allows to compile and execute C++ program dynamically through Python program using g++.
g++ is a program that calls GCC (GNU C Compiler) and automatically links the required C++ library files to the object
code.
Output: 120
13
Python program Executing C++ Program
Output:
Compiling c:\hello.cpp
c:\hello.cpp: In function 'int main()':
c:\hello.cpp:6:21: error: expected ';' before 'return'
std::cout<<"hello"
^
14
;
return 0;
~~~~~~
LESSON 15 DATA MANIPULATION THROUGH SQL
Part - II
1. Mention the users who use the Database.
Users of database can be human users, other programs or applications.
5. Which method is used to fetch all rows from the database table?
The fetchall () method is used to fetch all rows from the database table.
Example:
import sqlite3
con = sqlite3.connect ("student.db")
cursor = con.cursor()
cmd = """ SELECT * FROM student;"""
cursor.execute(cmd)
15
result = cursor.fetchall()
for i in result:
print(i)
con.close()
Part - III
1. What is SQLite? What is it advantage?
SQLite is a simple relational database management system, which saves its data in regular data files or even in the
internal memory of the computer.
Advantages:
It is designed to be embedded in applications, instead of using a separate database server program such as
Mysql or Oracle.
SQLite is fast, rigorously tested, and flexible, making it easier to work.
Python has a native library for SQLite.
Output:
Output: [(1001, ’Bala’, 22, ‘M’)]
[(1001,’Bala’, 22, ‘M’)] [(1002, ’Param’, 20, ‘M’)]
[(1003, ’Veeru’, 18, ‘M’)]
3. What is the use of Where Clause. Give a python statement Using the where clause.
SQL WHERE CLAUSE
The WHERE clause is used to extract only those records that fulfill a specified condition.
Example:
import sqlite3
con = sqlite3.connect ("student.db")
cursor = con.cursor()
cmd = """ SELECT * FROM student WHERE place=’tvl’;"""
cursor.execute(cmd)
result = cursor.fetchall()
print(result)
con.close()
16
4. Read the following details. Based on that write a python script to display department wise records
db name :- organization.db Table name :- Employee Columns of table :- Eno, EmpName, Esal, Dept
Example:
import sqlite3
con = sqlite3.connect ("organization.db ")
cursor = con.cursor()
cmd = """ SELECT * FROM employee ORDER BY Dept ASC;"""
cursor.execute(cmd)
result = cursor.fetchall()
for i in result:
print(i)
5. Read the following details. Based on that write a python script to display records in descending
order of Eno db name :- organization.db Table name :- Employee Columns in the table :- Eno,
EmpName, Esal, Dept
Example:
import sqlite3
con = sqlite3.connect ("organization.db ")
cursor = con.cursor()
cmd = """ SELECT * FROM Employee ORDER BY Eno DESC;"""
cursor.execute(cmd)
result = cursor.fetchall()
for i in result:
print(i)
con.close()
Part - IV
1. Write in brief about SQLite and the steps used to use it.
SQLite is a simple relational database system, which saves its data in regular data files or even in the
internal memory of the computer. It is designed to be embedded in applications, instead of using a
separate database server program such as Mysql or Oracle. SQLite is fast, rigorously tested, and
flexible, making it easier to work. Python has a native library for SQLite.
Step 1: import sqlite3
It is used to importing sqlite3 inside python.
Step 2: connection=sqlite3.connect(‘database_name’)
It is used to create a connection and pass the name of the database File.
connecting to a database means passing the name of the database to be accessed. If the
database already exists the connection will open the same. Otherwise, Python will open a
new database file with the specified name.
17
It is used to set the cursor object, cursor is a control structure used to traverse and fetch
the records of the database. Cursor has a major role in working with Python. All the
commands will be executed using cursor object only.
2. Write the Python script to display all the records of the following table using fetchmany ()
Icode ItemName Rate
1003 Scanner 10500
1004 Speaker 3000
1005 Printer 8000
1008 Monitor 15000
1010 Mouse 700
import sqlite3
con = sqlite3.connect ("organization.db")
cursor = con.cursor()
cmd = """ SELECT * FROM item;"""
cursor.execute(cmd)
result = cursor.fetchmany(5)
print(result)
con.close()
18
Name of the database :- ABC
Name of the table :- Item
Column name and specification :
Icode integer and act as primary
key
Item Name Character with length 25
Rate Integer
Record to be added 1008, Monitor,15000
import sqlite3
con = sqlite3.connect ("ABC.db")
cursor = con.cursor()
cmd = """CREATE TABLE item( Icode INTEGER PRIMARY KEY,
Item_Name CHAR(25),
Rate INTEGER);"""
cursor.execute(cmd)
cmd = """ INSERT INTO item (Icode,Item_Name, Rate) VALUES(1008, ‘Monitor’, 15000);"""
cursor.execute(cmd)
print(“item Table Created and record inserted Successfully”)
con.commit()
con.close()
5. Consider the following table Supplier and item .Write a python script for (i) to (ii)
SUPPLIER
Suppno Name City Icode SuppQty
S001 veeru Delhi 1008 100
S002 Rishi Bangalore 1010 200
S003 Param Bangalore 1008 175
S004 Bala Hydrabad 1005 195
S005 Ganesh Hydrabad 1003 25
S006 Pugazh Chennai 1008 180
S007 Mithran Mumbai 1005 325
i) Display Name, City and Itemname of suppliers who do not reside in Delhi.
import sqlite3
con = sqlite3.connect ("item.db")
cursor = con.cursor()
cmd = """ SELECT Name,City Icode FROM Supplier WHERE City<>’Delhi’’;"""
cursor.execute(cmd)
result = cursor.fetchall()
for i in result:
print(i)
con.close()
19
ii) Increment the SuppQty of Bala by 40
import sqlite3
con = sqlite3.connect ("item.db")
cursor = con.cursor()
cmd = """ UPDATE Supplier SET SuppQty=’235’ WHERE Name=’Bala’ ;"""
cursor.execute(cmd)
print(“Supplier Quantity of Bala is incremented by 40, Successfully”)
con.commit()
con.close()
Aggregate Functions:
These functions are used to do operations from the values of the column and a single value is returned.
Aggregate functions:
COUNT()
AVG()
SUM()
MAX()
MIN()
COUNT():
The COUNT( ) function returns the number of rows in a table satisfying the criteria specified in the
WHERE clause. COUNT( ) returns 0 if there were no matching rows.
Example:
import sqlite3
con = sqlite3.connect("Academy.db")
cursor = con.cursor()
cursor.execute("SELECT COUNT(*) FROM student ")
result = cursor.fetchall()
print(result)
con.close()
AVG():
The AVG( ) function returns the average of a selected column.
Example:
import sqlite3
con = sqlite3.connect("Academy.db")
cursor = con.cursor()
cursor.execute("SELECT AVG(tamil) FROM student ")
result = cursor.fetchall()
print(result)
con.close()
SUM()
The SUM( ) function returns the sum of all the values in selected column.
Example:
20
import sqlite3
con = sqlite3.connect("Academy.db")
cursor = con.cursor()
cursor.execute("SELECT SUM(marks) FROM student ")
result = cursor.fetchall()
print(result)
con.close()
MAX()
The MAX() function returns the largest value of the selected column.
Example:
import sqlite3
con = sqlite3.connect("Academy.db")
cursor = con.cursor()
cursor.execute("SELECT MAX(marks) FROM student ")
result = cursor.fetchall()
print(result)
con.close()
MIN()
The MIN() function returns the smallest value of the selected column.
Example:
import sqlite3
con = sqlite3.connect("Academy.db")
cursor = con.cursor()
cursor.execute("SELECT MIN(marks) FROM student ")
result = cursor.fetchall()
print(result)
con.close()
***********************************************************************************
1. Write a python script to updating a record
import sqlite3
con = sqlite3.connect ("school.db")
cursor = con.cursor()
cmd = """UPDATE student SET name ='sundar' WHERE rollno='8' ;"""
cursor.execute(cmd)
print(“Record updated Successfully”)
con.commit()
con.close()
2. Write a python script for deletion operation
import sqlite3
con = sqlite3.connect ("school.db")
cursor = con.cursor()
cmd = """DELETE FROM student WHERE rollno='2';"""
21
cursor.execute(cmd)
print(“Record Deleted Successfully”)
con.commit()
con.close()
22
con.commit()
con.close()
23
id = int(input(“ID”))
name = input(“NAME”)
age = int(input(“AGE”))
cursor.execute("INSERT INTO person VALUES
("{sid}","{sname}","{sage}")".format(sid=id,
sna
me=name, sage=age))
con.commit()
con.close()
wf=open('query.csv','w', newline='')
row=csv.writer(wf)
row.writerow(co)
row.writerows(result)
wf.close()
rf=open('query.csv','r')
row=csv.reader(rf)
for i in row:
print(i)
rf.close()
24
LESSON 16 DATA VISUALIZATION USING PYPLOT: LINE CHART, PIE CHART AND BAR CHART
Part - II
25
4. How will you install Matplotlib?
We can install matplotlib using pip.
Pip is management software for installing python packages.
Python –m pip install –U matplotlib
Part - III
1. Draw the output for the following data visualization plot.
import matplotlib.pyplot as plt
plt.bar([1,3,5,7,9],[5,2,7,8,2],
label="Example one")
plt.bar([2,4,6,8,10],[8,6,2,5,6],
label="Example two", color='g')
plt.legend()
plt.xlabel('bar number')
plt.ylabel('bar height')
plt.title('Epic Graph\nAnother Line! Whoa')
plt.show()
26
4. Write the Code for the following pie chart output.
Part – IV
1. Explain in detail the types of pyplots using Matplotlib.
Matplotlib allows you to create different kinds of plots they are as follows:
Line Chart
Bar Chart
Pie Chart
Line Chart:
A Line Chart or Line Graph is a type of chart which displays information as a series of data points
called ‘markers’ connected by straight line segments.
A Line Chart is often used to visualize a trend in data over intervals of time – a time series – thus
the line is often drawn chronologically
Example:
import matplotlib.pyplot as plt
x = [1,2,3]
y = [5,7,4]
plt.plot(x, y, label='Line 1')
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.title('LINE GRAPH')
plt.legend()
plt.show()
Bar Chart
A Bar Plot shows the relationship between a numerical variable and a categorical variable.
Bar chart represents categorical data with rectangular bars.
Each bar has a height corresponds to the value it represents.
The bars can be plotted vertically or horizontally.
27
To make a bar chart with Matplotlib, we can use the plt.bar () function.
Example:
import matplotlib.pyplot as plt
plt.bar([1,3,5,7,9],[5,2,7,8,2], label="Example one")
plt.xlabel('bar number')
plt.ylabel('bar height')
plt.title(‘Bar Graph’)
plt.legend()
plt.show()
Pie Chart:
Pie Chart is one of the most common types of chart.
It is a circular graphic which is divided into slices to illustrate numerical proportion.
The point of a pie chart is to show the relationship of parts out of a whole.
To make a Pie Chart with Matplotlib, we can use the plt.pie ( ) function.
The autopct parameter allows us to display the percentage value using the string formatting.
Example:
import matplotlib.pyplot as plt
marks = [89, 80, 90, 100, 75]
subjects = ["Tamil", "English", "Maths", "Science", "Social"]
plt.pie (marks, labels = subjects, autopct = "%.2f ")
plt.axes().set_aspect ("equal")
plt.show()
2. Explain the various buttons in a matplotlib window.
In the matplotlib output window, we can see few buttons at the bottom left corner. Let us see the
use of these buttons.
Home Button : The Home Button will help us to navigating our chart. If we want to
return back to the original view, we can click on Home button.
Forward/Back buttons : Forward and Backward buttons help to move forward and
backward in the workspace.
Pan Axis Pan Axis button helps to drag our graph around the workspace.
Z
o
o
28
m
-
i
n
w
ill
r
e
q
u
ir
e
a
l
e
ft
cl
ic
k
a
n
d
d
r
a
g
.
Zoom-out will require a right click and drag.
Configure Subplots: Configure Subplots button helps to configure various spacing options
with our figure and plot.
29
Example:
import matplotlib.pyplot as plt
x = [1,2,3]
y = [5,7,4]
plt.plot(x, y, label='Line 1')
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.title('LINE GRAPH')
plt.legend()
plt.show()
Dashboard: A dashboard is a collection of resources assembled to create a single unified visual display.
Data visualizations and dashboards translate complex ideas and concepts into a simple visual format.
Patterns and relationships that are undetectable in text are detectable at a glance using dashboard.
Scatter plot: A scatter plot is a type of plot that shows the data as a collection of points. The position of
a point depends on its two-dimensional value, where each value is a position on either the horizontal or
vertical dimension.
Box plot: The box plot is a standardized way of displaying the distribution of data based on the five
number summaries: minimum, first quartile, median, third quartile, and maximum.
30
sequence of classes.
In Histogram, the width of rectangular blocks may In Bar graph, the width of the bars is always
or may not be same same.
1. Create a plot. Set the title, the x and y labels for both axes.
import matplotlib.pyplot as plt
x = [1,2,3]
y = [5,7,4]
plt.plot(x, y)
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.title('LINE GRAPH')
plt.show()
3. Plot a line chart on academic performance of Class 12 students in Computer Science for past 10 years.
31
import matplotlib.pyplot as plt
years =
[2011,2012,2013,2014,2015,2016,2017,2018,2019,2020]
marks = [99, 96, 95, 100, 100, 92, 100, 90, 100, 98]
plt.plot(years, marks, label='LINE GRAPH')
plt.xlabel('YEARS')
plt.ylabel('MARKS')
plt.title('Computer Science Marks')
plt.show()
4. Plot a bar chart for the number of computer science periods in a week.
import matplotlib.pyplot as plt
days = [Mon, Tue, Wed, Thur, Fri, Sat]
periods = [2,1,1,1,1,2]
plt.bar(days, periods, label='BAR GRAPH')
plt.xlabel('DAYS')
plt.ylabel('NO. OF. PERIODS')
plt.title('Computer Science Periods in a
week')
plt.show()
32