0% found this document useful (0 votes)
4 views32 pages

LN 13 14 15 16

Download as doc, pdf, or txt
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 32

LESSON: 13 PYTHON AND CSV FILES

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.

2. Mention the two ways to read a CSV file using Python.


There are two ways to read a CSV file.
1.Using reader() function
2.Using DictReader class

3. Mention the default modes of the File.


The default mode in python file is reading in text mode.
'r' - Open a file for reading. (default)
't' - Open in text mode. (default)

4. What is use of next() function?


next() function is used to skip the row heading after reading the CSV file.
Example:
import csv
rf=open(‘test.csv’)
row=csv.reader( rf )
next(row)
lt = list(row)
lt.sort( )
for i in lt:
print(i)
rf.close( )
5. How will you sort more than one column from a csv file? Give an example statement.
To sort by more than one column we can use itemgetter with multiple indices:
operator . itemgetter (0,2), The content of “test.csv” is
ItemName ItemPrice Quantity
Mouse 100 5
Keyboard 250 3
Monitor 2500 2
Example:
import csv
rf=open(‘test.csv’, ’r’)
row=csv.reader(rf)
next(row)
lt=[ ]
lt=sorted(row, key=operator.itemgetter(0,2))
for i in lt:
print(i)
rf.close( )

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. Write a Python program to modify an existing file.


The content of “test.csv” before modification:
Rollno Name Age
1 Rishi 5
2 Veeru 35
3 Param 30

Modifying the 3rd row of test.csv


import csv
dt = [’3’, ‘Bala’, ’52’]
rf = open(‘test.csv’, ’r’)
row1 = csv.reader(rf)
lt = list(row1)
lt[3] = dt
wf = open(‘test.csv’, ’w’)
row2 = csv.writer(wf)
row2.writerows(lt)
rf.close( )
wf.close( )

Content of test.csv after modification:


Rollno Name Age
1 Rishi 5
2 Veeru 35
3 Bala 52

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')

5. What is the difference between reader() and DictReader() function?


reader() DictReader()
To read a CSV file into a list can be done by To read a CSV file into a dictionary can be done
using reader() function of csv module. by using DictReader class of csv module.
csv. reader() works with list/tuple csv.DictReader() works with dictionary.
It takes additional argument ‘fieldnames’ that
It does not take additional arguments.
are used as dictionary keys.
Example: Example:
import csv import csv
rf = open(‘test.csv’, ’r’) rf = open(‘test.csv’, ’r’)
row = csv.reader(rf) row = csv.DictReader(rf)
for i in row: for i in row:
print(i) print(dict(i))
rf.close( ) rf.close( )

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)

3. Write the different methods to read a File in Python.


There are two ways to read a CSV file.
1.Using reader() function
2.Using DictReader class
Using reader() function:
We can read the contents of CSV file with the help of csv.reader() method. The reader function is designed to take each
line of the file and make a list of all columns.
Syntax:
csv.reader(fileobject,delimiter,fmtparams)
file object : passes the path and the mode of the file.
delimiter : an optional parameter containing the standard dialects 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
rf = open(‘test.csv’, ’r’)
row = csv.reader(rf)
for i in row:
print(i)
rf.close( )
Using DictReader() class
To read a CSV file into a dictionary can be done by using DictReader class of csv module. It creates an object which
maps data to a dictionary. The keys are given by the fieldnames as parameter. DictReader works by reading the first line
of the CSV and using each comma separated value in this line as a dictionary key. The columns in each subsequent row
then behave like dictionary values and can be accessed with the appropriate key (i.e. fieldname).
Example:
import csv
rf = open(‘test.csv’, ’r’)
row = csv.DictReader(rf)
for i in row:
print(dict(i))
rf.close( )

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. Write the rules to be followed to format the data in a CSV file.


1. Each record is to be located on a separate line, delimited by a line break by pressing enter key.
2. The last record in the file may or may not have an ending line break.
3. There may be an optional header line appearing as the first line of the file with the same format as normal
record lines. It should contain the same number of fields as the records in the rest of the file.
4. Within the header and each record, there may be one or more fields, separated by commas. Spaces are
considered part of a field and should not be ignored. The last field in the record must not be followed be a comma.
5. Each field may or may not be enclosed in double quotes.
6. Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes.
7. If double-quotes are used to enclosed fields, then a double-quote appearing inside a field must be
preceded with another double quote.
_____________________________________________________________________________________
Write notes on Purpose Of CSV File:
CSV is a simple file format used to store tabular data, such as a spreadsheet or database. Since they are plain text, it is
easier to import into a spreadsheet or another storage database, regardless of the specific software we are using. we
can open CSV files in a spreadsheet program like Microsoft Excel or in a text editor or through a database which make
us easier to read. CSV File cannot store charts or graphs. It stores data but does not contain formatting, formulas,
macros, etc.
_______________________________________________________________________________________
Python file operation:
It takes place in the following order:
Step 1: Open a file.
Step 2: Perform Read or write operation.
Step 3: Close the file.
______________________________________________________________________________________
Dialects:
 A dialect describes the format of the csv file that is to be read.
 A dialect is a class of csv module which helps to define parameters for reading and writing CSV.
 It allows us to create, store, and re-use various formatting parameters for our data.
 New dialects can be registered using csv.register_dialect().
Example:
import csv
csv.register_dialect('mydialect', delimiter = '|', quoting=csv.QUOTE_ALL, skipinitialspace=True)
rf=open(‘test.csv','r')
row = csv.reader(rf, dialect='mydialect')
for i in row:
print(i)
rf.close( )
writer() method:

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()

1. To write a CSV files - data With Quotes:


import csv
csv.register_dialect('mydialect', delimiter = ',' , 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( )
______________________________________________________________________________________
2. To write a CSV files - data With Custom delimiter:
import csv
csv.register_dialect('mydialect', delimiter = '|')
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( )
______________________________________________________________________________________

3. To write a CSV files - data With Custom Quote:

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( )
______________________________________________________________________________________

4. To write a CSV files - data With lineterminator:


import csv
csv.register_dialect('mydialect', delimiter = ',' , lineterminator=”\n\n”)
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( )

LESSON 14 IMPORTING C++ PROGRAMS IN PYTHON


8
Part - II
1. What is the theoretical difference between Scripting language and other programming language?
The theoretical difference between the two is that:
 Scripting languages do not require the compilation step and are rather interpreted.
 Whereas programming language needs to be compiled before running.
 A scripting language requires an interpreter while a programming language requires a compiler.

2. Differentiate compiler and interpreter.


compiler interpreter
Scans the entire program and translates it as a whole Translates program one statement at a time.
into machine code. It continues translating the program until the first
It generates the error message only after scanning error is met, in which case it stops. Hence debugging
the whole program. Hence debugging is is easy
comparatively hard.

3. Write the expansion of (i) SWIG (ii) MinGW


(i)SWIG (Simplified Wrapper Interface Generator- Both C and C++)
(ii)MinGW (Minimalist GNU for Windows)

4. What is the use of modules?


 We use modules to break down large programs into small manageable and organized files.
 Modules provide reusability of code.
 We can define our most used functions in a module and import it, instead of copying their definitions into different
programs.

5. What is the use of cd command. Give an example.


cd command is used to change the directory.
Syntax:
cd <absolute path>
where,
cd refers to change directory
absolute path refers to complete path where python is installed
Example:
cd c:\program files\Python

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

2. What are the applications of scripting 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

3. What is MinGW? What is its use?


 MinGW refers to a set of runtime header files, used in compiling and linking the code of C, C++ and FORTRAN to be run
on Windows Operating System.
 MinGw-W64 is the best compiler for C++ on Windows. 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++.

4. Identify the module ,operator, definition name for the following


welcome.display()
definition name (function call)
dot operator
module name

5. What is sys.argv? What does it contain?


 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.

Part - IV

1. Write any 5 features of Python.


 Python uses Automatic Garbage Collection whereas C++ does not.
 Python is a dynamically typed language, while C++ is a statically typed language.
 Python runs through an interpreter, while C++ is pre-compiled.
 Python code tends to be 5 to 10 times shorter than that written in C++.
In Python, Data type is not required while declaring variable, where as Data type is required while declaring variable in C++
 In Python, a function may accept an argument of any type, and return multiple values without any declaration
beforehand, whereas in C++ return statement can return only one value.

2. Explain each word of the following command.


Python <filename.py> -i <C++ filename without cpp extension>
Python keyword to execute the Python program from
command line.
filename.py Name of the Python program to be executed.
-i input mode
C++ filename without cpp extension name of C++ file to be compiled and executed

3. What is the purpose of sys, os, getopt module in Python. Explain


SYS MODULE:

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.

5. Write a Python program to execute the following c++ coding


#include <iostream>
using namespace std;
int main()
{ cout<<“WELCOME”;
return(0);
}
The above C++ program is saved in a file welcome.cpp
Save the following python File as welcomei.py . Program that compiles and executes a .cpp file
import sys, os, getopt
def main(argv):
opts, args = getopt.getopt(argv, "i:")
for o, a in opts:
if o in "-i":
run(a)
def run(a):
inp_file=a+'.cpp'
exe_file=a+'.exe'
os.system('g++ ' + inp_file + ' -o ' + exe_file)
os.system(exe_file)

if __name__ == '__main__': #program starts executing from


here
main(sys.argv[1:])

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.

Importing C++ Files in Python:

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.

How to import modules in Python?


Modular programming:
Modular programming is a software design technique to split your code into separate parts. These parts are called
modules. Minimization of dependencies is the goal.
Module:
Modules refer to a file containing Python statements and definitions.
Use of module:
 We use modules to break down large programs into small manageable and organized files.
 Modules provide reusability of code.
 We can define our most used functions in a module and import it, instead of copying their definitions into
different programs.
Example: factorial.py
def fact(n):
f=1
if n == 0:
return 1
else:
for i in range(1, n+1):
f= f*i
print (f)
Importing module in python:
We use import keyword to import our previously defined module.
Accessing function defined inside module:
Using the module name we can access the functions defined inside the module. The dot (.) operator is used to access
the functions.
Example:
>>>import factorial
>>>factorial.fact(5)
definition name (function call)
dot operator
module name

Output: 120

13
Python program Executing C++ Program

Steps to execute C++ program in Python:


Step 1: Type the C++ program in notepad and save it as “pali.cpp”.
Step 2: Type the Python program and save it as “pali.py “
Step 3: Click the Run Terminal and open the command window then, Go to the
folder of Python using
cd command.
Step 4: Type the command Python pali.py -i pali

Python is handling the errors in C++


Python not only execute the successful C++ program, it also helps to display even errors if any in C++
statement during compilation. For example in the following C++ program an error is there. Let us see
what happens when you compile through Python.

Step 1: Type following C++ program in notepad and save it as “hello.cpp”.


#include<iostream>
using namespace std;
int main()
{
std::cout<<"hello"
return 0;
}

Step 2: Type the Python program and save it as “hello.py “


Step 3: Click the Run Terminal to open the command window then, Go to the folder
of Python using
cd command.
Step 4: Finally, type the following command to execute C++ program from
python:
Python hello.py -i hello

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.

2. Which method is used to connect a database? Give an example.


Connect() method is used to connect to a database.
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.
Example:
Import sqlite3
con = sqlite3.connect(“student.db”)

3. What is the advantage of declaring a column as “INTEGER PRIMARY KEY”?


If a column of a table is declared to be an INTEGER PRIMARY KEY, then whenever a NULL will be used as an input for
this column, the NULL will be automatically converted into an integer which will one larger than the highest value so far
used in that column. If the table is empty, the value 1 will be used.

4. Write the command to populate record in a table. Give an example.


To populate record in the table "INSERT" command is passed to SQLite.
Example:
import sqlite3
con = sqlite3.connect ("student.db")
cursor = con.cursor()
cmd = """ CREATE TABLE student ( rollno INTEGER PRIMARY KEY,
sname VARCHAR(20),
age INTEGER,
gender CHAR(1);"""
cursor.execute(cmd)
cmd = """ INSERT INTO student ( rollno, sname, age, gender) VALUES(1001, ’Bala’, 22, ’M’);"""
cursor.execute(cmd)
cmd = """ INSERT INTO student ( rollno, sname, age, gender) VALUES(1002, ’Ganesh’, 20, ’M’);"""
cursor.execute(cmd)
con.commit()
con.close()

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.

2. Mention the difference between fetchone() and fetchmany()


fetchone() fetchmany()
The fetchmany () method returns the
The fetchone () method returns the next
specified number of records (i.e.) returns
row of a query result set or None in case
the next number of rows (n) of the result
there is no row left.
set.
Example: Example:
import sqlite3 import sqlite3
con = sqlite3.connect ("student.db") con = sqlite3.connect ("student.db")
cursor = con.cursor() cursor = con.cursor()
cmd = """ SELECT * FROM student;""" cmd = """ SELECT * FROM student;"""
cursor.execute(cmd) cursor.execute(cmd)
result = cursor.fetchone() result = cursor.fetchmany(3)
print(result) print(result)
con.close() con.close()

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.

Step 3: cursor = connection. cursor ()

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()

3. What is the use of HAVING clause? Give an example python script


Having clause is used to filter data based on the group functions. This is similar to WHERE condition
but can be used only with group functions. Group functions cannot be used in WHERE Clause but can
be used in HAVING clause.
Example:
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT GENDER,COUNT(GENDER) FROM Student GROUP BY GENDER HAVING
COUNT(GENDER)>3")
result = cursor.fetchall()
co = [i[0] for i in cursor.description]
print(co)
print(result)
con.close()
OUTPUT
['gender', 'COUNT(GENDER)']
[('M', 5)]
4. Write a Python script to create a table called ITEM with following specification.
Add one record to the table.

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()

3. Write a python script to querying a DATE column


import sqlite3
con = sqlite3.connect ("school.db")
cursor = con.cursor()
cmd = """SELECT * FROM student WHERE Birth_date>='2000-01-01';"""
cursor.execute(cmd)
result=cursor.fetchall()
for i in result:
print(i)
con.close()
4. Write a python script to querying multiple tables
import sqlite3
con = sqlite3.connect ("school.db")
cursor = con.cursor()
cmd = """SELECT student1.name, student2.total FROM student1, student2
WHERE
student1.rno =
student2.rno;"""
cursor.execute(cmd)
result=cursor.fetchall()
for i in result:
print(i)
con.close()

Data input from list


Write a python program to insert records using list and write it in the person table.
import sqlite3
con =sqlite3.connect("school.db")
cursor =con.cursor()
dt=[(123,’Sundar’,10),
(124, ‘Rishi’,12),
(125, ‘Pugazh’,17)]
for i in dt:
cursor.execute("INSERT INTO person VALUES(?,?,?),(i[0], i[1], i[2])")

22
con.commit()
con.close()

Data input by User (using qmark style)


Write a python program to create a table ‘person’ and accept data using python input () command
during runtime and write it in the person table.
import sqlite3
con =sqlite3.connect("school.db")
cur =con.cursor()
cur.execute("CREATE TABLE person (id integer NOT NULL PRIMARY KEY, name char(20),
age integer)")
print("Enter FIVE students names:")
for i in range(5):
id = int(input(“ID”))
name = input(“NAME”)
age = int(input(“AGE”))
cursor.execute("INSERT INTO person VALUES (?, ?, ?)", (id, name, age))
con.commit()
con.close()

Data input by User (using named style)


Write a python program to create a table ‘person’ and accept data using python input () command
during runtime and write it in the person table.
import sqlite3
con =sqlite3.connect("school.db")
cur =con.cursor()
cur.execute("CREATE TABLE person (id integer NOT NULL PRIMARY KEY, name char(20),
age integer)")
print("Enter FIVE students names:")
for i in range(5):

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()

Integrating Query With Csv File


Write a python program to SORT table in gender wise in descending order, then output of this query
will be written in a CSV file. Finally content of this CSV file will be read and display the result.
import sqlite3, csv
con = sqlite3.connect("school.db")
cursor = con.cursor()
cursor.execute("SELECT * FROM student ORDER BY sname DESC")
result=cursor.fetchall()
co = [i[0] for i in cursor.description]
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

1. Define: Data Visualization.


 Data Visualization is the graphical representation of information and data.
 Data Visualization uses statistical graphics to communicate information visually to users.
 Numerical data may be encoded using dots, lines, or bars, to visually communicate a quantitative
message.

2. List the general types of data visualization.


General types of Data Visualization
• Charts
• Tables
• Graphs
• Maps
• Infographics
• Dashboards

3. List the types of Visualizations in Matplotlib.


There are many types of Visualizations under Matplotlib. Some of them are:
• Line plot
• Scatter plot
• Histogram
• Box plot
• Bar chart and
• Pie chart

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

5. Write the difference between the following functions:


plt.plot([1,2,3,4]) plt. plot([1,2,3,4], [1,4,9,16])
Here, we provide a single list to the plot () Here, we provide two lists to the plot
command, matplotlib assumes it is a command, matplotlib assumes it is a
sequence of y values, and automatically sequence of x values and y values.
generates the x values for us.
Since python ranges start with 0, the default
x vector has the same length as y but starts
with 0. Hence the x data are [0, 1, 2, 3].

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()

2. Write any three uses of data visualization.


 Data Visualization helps users to analyze and interpret the data easily.
 It makes complex data understandable and usable.
 Various Charts in Data Visualization helps to show relationship in the data for one or more
variables.

3. Write the coding for the following:


 a. To check if PIP is Installed in your PC.  python -m pip --version
 b. To Check the version of PIP installed in your PC.  Pip -- version
 c. To list the packages in matplotlib.  Pip list

26
4. Write the Code for the following pie chart output.

import matplotlib.pyplot as plt


y = [29.2,8.3,8.3,54.2 ]
x = [“sleeping”, “eating”, “working”, “playing”]
e = [0 , 0.1, 0, 0]
plt.pie(y, labels=x, autopct=”%.1f”, explode=e,
startangle=90)
plt.axes().set_aspect(“equal”)
plt.show()

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.

Zoom : Zoom button helps to zoom-in and zoom-out the chart.

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.

Save: Save button helps to save our figure in various formats.

3. Explain the purpose of the following functions:


a. plt.xlabel( ) Used to assign label to X- axis.
b. plt.ylabel( ) Used to assign label to Y-axis
c. plt.title( ) Used to assign Chart title.
d. plt.legend( ) Used to display the legend.
e. plt.show( ) Used to display Chart.

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()

Infographics: An Infographics (information graphic) is the representation of information in a graphic


format.

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.

Key Differences between Histogram and Bar Graph:


Histogram Bar Graph
Histogram refers to a graphical representation of A bar graph is a pictorial representation of data
data in the form of bars to show the frequency of that uses bars to compare different categories of
numerical data. data.
A histogram represents the frequency A bar graph is a diagrammatic comparison of
distribution of continuous variables. discrete variables.
Histogram shows numerical data. Bar graph shows categorical data
In Bar graph, there is proper spacing between
In Histogram, there is no gap between the bars
bars that indicates discontinuity
In Histogram, numbers are categorized together In Bar graph, items are considered as individual
to represent ranges of data. entities.
In Histogram, bars cannot be rearranged from In Bar graph, bars can be rearranged from highest
highest to lowest as they are shown in the to lowest.

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()

2. Plot a pie chart for your marks in the recent examination.


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()

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

You might also like