0% found this document useful (0 votes)
1K views16 pages

Namma Kalvi 12th Computer Science Unit 5 Sura Guide em

The document discusses importing C++ programs into Python. It compares scripting languages like Python to other programming languages. Python can import C++ files using various interfaces like MinGW. A Python program can execute C++ code containing elements like control statements, arrays, and functions. Python handles errors that occur in imported C++ code. While Python is interpreted, C++ must be compiled, and Python is dynamically typed versus C++'s static typing.

Uploaded by

Aakaash C.K.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views16 pages

Namma Kalvi 12th Computer Science Unit 5 Sura Guide em

The document discusses importing C++ programs into Python. It compares scripting languages like Python to other programming languages. Python can import C++ files using various interfaces like MinGW. A Python program can execute C++ code containing elements like control statements, arrays, and functions. Python handles errors that occur in imported C++ code. While Python is interpreted, C++ must be compiled, and Python is dynamically typed versus C++'s static typing.

Uploaded by

Aakaash C.K.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

www.surabooks.com This material only for sample www.surabooks.

com
Namma Kalvi


www.nammakalvi.org

 
UNIT-V INTEGRATING PYTHON WITH MYSQL AND C++
Importing C++
Chapter
Programs in Python
14
ns
io
CHAPTER SNAPSHOT
at
ic
14.1 Introduction
14.2 Scripting Language
bl

14.2.1 Difference between Scripting and Programming Languages


14.3 Applications of Scripting Languages
Pu

14.4 Features of Python over C++


14.5 Importing C++ Files in Pythona
14.5.1 MinGW Interface
ra

14.5.2 Executing C++ Program through Python


14.6 Python Program to import C++
Su

14.6.1 Module
14.7 Python program Executing C++ Program using control statement
14.8 How Python is handling the errors in C++
14.9 Python program Executing C++ Program Containing Arrays
14.10 Python program Executing C++ Program Containing Functions
14.11 Python program to Illustrate the inheritance of a Class

[201]

[email protected] Ph: 81242 01000 / 812430 1000 / 96001 75757


Unit V - Chapter 14
www.surabooks.com

Sura’s ➠ XII Std - Computer Science

Evaluation
 
This material only for sample www.surabooks.com

www.nammakalvi.org

8. Identify the function call statement in the


Part - I following snippet.
Choose the best answer  (1 mark) if __name__ =='__main__':
main(sys.argv[1:])
1. Which of the following is not a scripting
language? (a) main(sys.argv[1:])
(a) JavaScript (b) PHP (b) __name__
(c) Perl (d) HTML (c) __main__
 [Ans. (d) HTML] (d) argv [Ans. (c)__main__]
2. Importing C++ program in a Python program 9. Which of the following can be used for
is called processing text, numbers, images, and
(a) wrapping (b) Downloading scientific data?
(c) Interconnecting (d) Parsing (a) HTML (b) C

ns
[Ans. (a) wrapping] (c) C++ (d) PYTHON
3. The expansion of API is [Ans. (a) HTML]

io
(a) Application Programming Interpreter
10. What does __name__ contains ?
(b) Application Programming Interface at (a) c++ filename
(c) Application Performing Interface
(c) main() name
(d) Application Programming Interlink
ic
(c) python filename
[Ans. (b) Application Programming
Interface] (d) os module name
bl

4. A framework for interfacing Python and C++ is [Ans. (d) os module name]
Pu

(a) Ctypes (b) SWIG


(c) Cython (d) Boost Part - II
[Ans. (d) Boost] Answer the following questions
ra

5. Which of the following is a software design  (2 marks)


technique to split your code into separate
parts?
Su

1. What is the theoretical difference between


(a) Object oriented Programming Scripting language and other programming
(b) Modular programming language?
(c) Low Level Programming Ans. (i) The theoretical difference between the two
(d) Procedure oriented Programming is that scripting languages do not require the
[Ans. (b) Modular programming] compilation step and are rather interpreted.
6. The module which allows you to interface with (ii) For example, normally, a C++ program
the Windows operating system is needs to be compiled before running
whereas, a scripting language like JavaScript
(a) OS module (b) sys module
or Python need not be compiled.
(c) csv module (d) getopt module
(iii) A scripting language requires an interpreter
[Ans. (a) OS module]
while a programming language requires a
7. getopt() will return an empty array if there is compiler. A given language can be called
no error in splitting strings to as a scripting or programming language
(a) argv variable (b) opt variable depending on the environment they are put
(c) args variable (d) ifile variable to use.
[Ans. (c) args variable]

202
[email protected] Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample

2. Differentiate compiler and interpreter.


Sura’s
www.surabooks.com

➠ XII Std - Computer Science


Part - III

Importing C++ Programs in Python


Ans.
Answer the following questions
S.
No
Compiler Interpreter  (3 marks)
Scans the entire Translates program 1. Differentiate PYTHON and C++.
program and one statement at a
Ans.
(i) translates it as a time.
whole into machine S.
PYTHON C++
code. No
It takes large It takes less amount Python is typically C++ is typically a
amount of time to of time to analyze (i) an "interpreted" "compiled" language
analyze the source the source code but language
(ii) code but the overall the overall execution Python is a C++ is compiled
execution time time is slower. (ii) dynamic-typed statically typed
is comparatively language language

ns
faster. Data type is not Data type is required
Programming Programming (iii) required while while declaring

io
language like C, language like declaring variable variable
(iii)
C++ use compilers. Python, Ruby use at It can act both It is a general
interpreters. as scripting and purpose language
(iv)
3. Write the expansion of (i) SWIG (ii) MinGW general purpose
ic
language
Ans. (i) 
SWIG – Simplified Wrapper Interface
bl

Generator 2. What are the applications of scripting


(ii) MINGW – Minimalist GNU for Windows
language?
Pu

Ans. (i) To automate certain tasks in a program


4. What is the use of modules? (ii) Extracting information from a data set
Ans. (i) The use of modules to break down large (iii) Less code intensive as compared to
programs into small manageable and
ra

traditional programming language


organized files. (iv) can bring new functions to applications
Su

(ii) Modules provide reusability of code. and glue complex systems together
Define our most used functions in a 3. What is MinGW? What is its use?
module and import it, instead of copying
Ans. (i) MinGW refers to a set of runtime header
their definitions into different programs.
files, used in compiling and linking the
5. What is the use of cd command. Give an code of C, C++ and FORTRAN to be run
example. on Windows Operating System.
Ans. ‘cd’ command refers to change directory and (ii) MinGw-W64 (version of MinGW) is the
absolute path refers to the couple path. best compiler for C++ on Windows. To
(Eg) “cd c:\program files\open office 4\program” compile and execute the C++ program,

203
[email protected] Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit V - Chapter 14
www.surabooks.com

Sura’s ➠ XII Std - Computer Science


need ‘g++’ for Windows. MinGW allows
to compile and execute C++ program
 
This material only for sample www.surabooks.com

www.nammakalvi.org
(vi) In Python, a function may accept an
argument of any type, and return multiple
dynamically through Python program values without any kind of declaration
using g++. beforehand. Whereas in C++ return
(iii) Python program that contains the C++ statement can return only one value.
coding can be executed only through
minGW-w64 project’ run terminal. The run 2. Explain each word of the following command.
terminal open the command-line window Python <filename.py> -<i> <C++ filename
through which Python program should be  without cpp extension>
executed.
Ans. Python <filename.py> -i <C++ filename without
4. Identify the module ,operator, definition name
cpp extension>
for the following
welcome.display() Python Keyword to execute
the Python program
Ans. Welcome.display()
from command-line

ns
filename.py- i Name of the Python
program to executed
definition name input mode

io
dot operator C++ filename Name of C++ file
without cpp to be compiled and
module name
at extension executed
5. What is sys.argv? What does it contain?
ic
Ans. sys.argv is the list of command-line arguments 3. What is the purpose of sys, os, getopt module
passed to the Python program. argv contains in Python? Explain.
bl

all the items that come along via the command- Ans. This module provides access to some variables
Pu

line input, it's basically an array holding the used by the interpreter and to functions that
command-line arguments of the program. interact strongly with the interpreter.
Part - IV sys.argv :
Answer the following questions
ra

(i) sys.argv is the list of command-line


arguments passed to the Python program.
 (5 marks)
Su

argv contains all the items that come


1. Write any 5 features of Python. along via the command-line input, it's
Ans. (i) Python uses Automatic Garbage Collection basically an array holding the command-
whereas C++ does not. line arguments of the program.
(ii) C++ is a statically typed language, while
(ii) To use sys.argv, you will first have to
Python is a dynamically typed language.
import sys. The first argument, sys.argv[0],
(iii) Python runs through an interpreter, while is always the name of the program as it
C++ is pre-compiled. was invoked, and sys.argv[1] is the first
(iv) Python code tends to be 5 to 10 times argument you pass to the program (here it
shorter than that written in C++. is the C++ file).
(v) In Python, there is no need to declare types
explicitly where as it should be done in C++

204
[email protected] Ph: 81242 01000 / 812430 1000 / 96001 75757
OS :

www.surabooks.com This material only for sample


Sura’s
www.surabooks.com

➠ XII Std - Computer Science


Here is the detail of the parameters −

Importing C++ Programs in Python


(i) The OS module in Python provides a (i) argv : This is the argument list of values
way of using operating system dependent to be parsed (splited). In our program the
functionality. complete command will be passed as a list.
(ii) The functions that the OS module allows (ii) options : This is string of option letters that
you to interface with the Windows the Python program recognize as, for input
operating system where Python is running or for output, with options (like ‘i’ or ‘o’)
on. that followed by a colon (:). Here colon is
os.system(): used to denote the mode.
(i) Execute the C++ compiling command (a
(iii) long_options : This parameter is passed
string contains Unix, C command which
with a list of strings. Argument of Long
also supports C++ command) in the shell
options should be followed by an equal sign
(Here it is Command Window).
('='). In our program the C++ file name

ns
(ii) For Example to compile C++ program g++
will be passed as string and ‘i’ also will be
compiler should be invoked. To do so the
passed along with to indicate it as the input
following command is used.

io
file.
os.system (‘g++’ + <varaiable_name1> at
 ‘-<mode>’ + <variable_name2> getopt() method returns value consisting of

getopt module : two elements. Each of these values are stored
ic
(i) The getopt module of Python helps you to separately in two different list (arrays) opts and
parse (split) command-line options and args. Opts contains list of splitted strings like
bl

arguments. mode, path and args contains any string if at


Pu

(ii) This module provides two functions to


all not splitted because of wrong path or mode.
enable command-line argument parsing. args will be an empty array if there is no error in
splitting strings by getopt().
getopt.getopt method :
ra

(i) This method parses command-line options For example, The Python code which is going
and parameter list. Following is the syntax to execute the C++ file p4 in command line will
Su

for this method − have the getopt() method like the following one.
(ii) <opts>,<args>=getopt.getopt(argv, options,
opts, args = getopt.getopt (argv, "i:",['ifile='])
[long_options])
4. Write the syntax for getopt() and explain its where opts [('-i', 'c:\\pyprg\\p4')]
arguments and return values. contains
Ans. getopt.getopt method : This method parses -i :- option nothing but
command-line options and parameter list. mode should be
followed by :
Following is the syntax for this method −
<opts>,<args>=getopt.getopt(argv, options, 'c:\\pyprg\\p4' value nothing but the
absolute path of C++
[long_options])
file.

205
[email protected] Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit V - Chapter 14
www.surabooks.com

Sura’s ➠ XII Std - Computer Science


In our examples since the entire command line
commands are parsed and no leftover argument,
 
This material only for sample www.surabooks.com

www.nammakalvi.org
import sys, os, getopt
def main(argv):
the second argument args will be empty []. If
cpp_file = ''
args is displayed using print() command it dis-
exe_file = ''
plays the output as [].
opts, args = etopt.getopt(argv,  "i:",['ifile='])
5. Write a Python program to execute the for o, a in opts:
following c++ coding if o in ("-i", "--ifile"):
#include <iostream> cpp_file = a + '.cpp'
exe_file = a + '.exe'
using namespace std;
run(cpp_file, exe_file)
int main() def run(cpp_file, exe_file):
{ cout<<“WELCOME”; print("Compiling " + cpp_file)
return(0); os.system('g++ ' + cpp_file + ' -o ' + exe_ file)

ns
} print("Running " + exe_file)
print("-------------------------")
The above C++ program is saved in a file
print

io
welcome.cpp
os.system(exe_file)
Ans. #Now select File→New in Notepad and type the
print
Python program as main.py
at
if __name__ =='__main__':
# Program that compiles and executes a .cpp file
ic
main(sys.argv[1:])
# Python main.py -i welcome
bl
Pu

additional questions and Answers

Choose the Correct Answer 1 MARK 4. In which language datatype or not required
ra

while declare variable?


1. Which of the following are general purpose (a) C++ (b) C
Su

programming language? (c) Java (d) Python


(a) Python (b) C++  [Ans. (d) Python]
(c) Java (d) All of these
5. Which of the following can act both as
 [Ans. (d) All of these]
scripting and general purpose language?
2. Which of the following is not general purpose (a) Python (b) C
language? (c) C++ (d) Html
(a) Python (b) Perl  [Ans. (a) Python]
(c) Java (d) C++
6. Which programming language is useful
 [Ans. (b) Perl]
when the logic can be written in C++ and
3. Which of the following is not a compiled manipulated through python program?
statically typed language? (a) C++ (b) Python
(a) C++ (b) Java
(c) Perl (d) Html
(c) Python (d) All of these
 [Ans. (b) Python]
[Ans. (c) Python]

206
[email protected] Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit V - Chapter 14
www.surabooks.com

Very Short Answers 2 MARKS 7.


 
This material only for sample

Sura’s ➠ XII Std - Computer Science


www.surabooks.com

www.nammakalvi.org
Write a note on
(i) CD command
1. Differentiate static typed language and (ii) Cls command
dynamic typed language. Ans. (i) C
 D command : The "cd" command refers to
Ans. (i) A static typed language like C++ requires changes directory and absolute path refers to
the programmer to explicitly tell the the complete path where Python is installed.
computer what “data type” each data value (ii) Cls command : To clear the screen in
is going to use. command window use cls command
(ii) A dynamic typed language like Python, 8. What is meant by module?
doesn’t require the data type to be given Ans. (i) Modular programming is a software design
technique to split your code into separate
explicitly for the data. Python manipulate parts.
the variable based on the type of value. (ii) These parts are called modules. The focus
for this separation should have modules
2. List some scripting language.
with no or just few dependencies upon
Ans. The most widely used scripting languages are

ns
other modules.
JavaScript, VBScript, PHP, Perl, Python, Ruby,
9. Write a note on main (sys.argv [1]).
ASP and Tcl.
Ans. main(sys.argv[1]) : Accepts the program file

io
3. What is garbage collection in python? at (Python program) and the input file (C++ file)
Ans. (i) Python deletes unwanted objects (built-in as a list(array). argv[0] contains the Python
program which is need not to be passed because
types or class instances) automatically to
by default __main__ contains source code
ic
free the memory space. reference and argv[1] contains the name of the
bl

(ii) The process by which Python periodically C++ file which is to be processed.
frees and reclaims blocks of memory that 10. Write the syntax and example of
Pu

no longer are in use is called Garbage (i) os.system () (ii) getopt ()


Collection. Ans. (i) os.system (‘g++’ + <varaiable_name1>
4. What is the use of GNU C complier?  ‘-<mode>’ + <variable_name2>
ra

(ii) <opts>,<args>=getopt.getopt(argv, options,


Ans. g++ is a program that calls GCC (GNU C
[long_options])
Compiler) and automatically links the required
Su

11. Write a command for wrapping C++ code.


C++ library files to the object code.
Ans. if __name__=='__main__':
5. How will you execute C++ program through main(sys.argv[1:])
python using MinGW interface? Give example. Short Answers 3 MARKS
Ans. Executing C++ Program through Python
(i) Double click the run terminal of MinGW 1. Write a note on (i) sys module (ii) OS module
(iii) getopt module
(ii) Go to the folder where the Python software
Ans. (i)  sys module provides access to some
is located (Python.exe) is located.
variables used by the interpreter and to
For example here “Python” is located in functions that interact with the interpreter
6. What does cd command refers? (ii) OS module in Python provides a way
Ans. The "cd" command refers to changes directory and of using operating system dependent
absolute path refers to the complete path where functionality
Python is installed. (iii) The getopt module of Python helps you to
parse (split) command-line options and
arguments.

210
[email protected] Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample www.surabooks.com


Chapter DATA MANIPULATION
15 THROUGH SQL

CHAPTER SNAPSHOT
www.nammakalvi.org

15.1 Introduction
15.2 SQLite
15.3 Creating a Database using SQLite

ns
15.4 SQL Query Using Python
15.5 The SQL AND, OR and NOT Operators
15.6 Querying A Date Column

io
15.7 Aggregate Functions
at
15.8 Updating A Record
15.9 Deletion Operation
ic
15.10 Data input by User
15.11 Using Multiple Table for Querying
bl

15.12 Integrating Query With Csv File


Pu

15.13 Table List

Evaluation
ra

3. Which of the following is a control structure used


Part - I to traverse and fetch the records of the database?
Su

Choose the best answer  (1 mark) (a) Pointer (b) Key


(c) Cursor (d) Insertion point
1. Which of the following is an organized
 [Ans. (c) Cursor]
collection of data?
(a) Database (b) DBMS 4. Any changes made in the values of the record
(c) Information (d) Records should be saved by the command
 [Ans. (a) Database] (a) Save (b) Save As
(c) Commit (d) Oblige
2. SQLite falls under which database system?
 [Ans. (c) Commit]
(a) Flat file database system
(b) Relational Database system 5. Which of the following executes the SQL
(c) Hierarchical database system command to perform some action?
(d) Object oriented Database system (a) execute() (b) key()
 [Ans. (b) Relational Database system] (c) cursor() (d) run()
 [Ans. (a) execute()]

[215]

[email protected] Ph: 81242 01000 / 812430 1000 / 96001 75757


Unit V - Chapter 15
www.surabooks.com

Sura’s ➠ XII Std - Computer Science


6. Which of the following function retrieves the
average of a selected column of rows in a table?
 
This material only for sample www.surabooks.com

www.nammakalvi.org
4. Write the command to populate record in a
table. Give an example.
(a) Add() (b) SUM() Ans. To populate (add record) the table "INSERT"
(c) AVG() (d) AVERAGE() command.
 [Ans. (c) AVG()] Example :
7. The function that returns the largest value of connection = sqlite3.connect ("Academy.db")
the selected column is cursor = connection.cursor()
(a) MAX() (b) LARGE() 5. Which method is used to fetch all rows from
(c) HIGH() (d) MAXIMUM()
the database table?
 [Ans. (a) MAX()]
Ans. cursor.fetchall() - fetchall () method is to fetch
8. Which of the following is called the master all rows from the database table.
table?
(a) sqlite_master (b) sql_master
Part - III
(c) main_master (d) master_main Answer the following questions
 [Ans. (b) sql_master]  (3 marks)

ns
9. The most commonly used statement in SQL is 1. What is SQLite? What is it advantage?
(a) cursor (b) select Ans. (i) SQLite is a simple relational database

io
(c) execute (d) commit system, which saves its data in regular data
 [Ans. (b) select] at files or even in the internal memory of the
10. Which of the following clause avoid the computer.
duplicate? (ii) It is designed to be embedded in
ic
(a) Distinct (b) Remove applications, instead of using a separate
database server program such as MySQLor
bl

(c) Where (d) GroupBy


 [Ans. (a) Distinct Oracle.
(iii) SQLite is fast, rigorously tested, and flexible,
Pu

Part - II making it easier to work.


Answer the following questions 2. Mention the difference between fetchone()
 (2 marks) and fetchmany().
ra

1. Mention the users who use the Database. Ans. (ii) cursor.fetchone() - The fetchone () method
Ans. Users of database can be human users, other
returns the next row of a query result set or
Su

programs or applications. None in case there is no row left.


(ii) cursor.fetchmany() method returns the
2. Which method is used to connect a database? next number of rows (n) of the result set.
Give an example. 3. What is the use of Where Clause?. Give a
Ans. cursor() method is used to connect a database. python statement using the where clause.
sql_command = """INSERT INTO Student Ans. (i) The WHERE clause is used to extract
(Rollno, Sname, Grade, gender, Average, only those records that fulfill a specified
birth_date) condition.
3. What is the advantage of declaring a column (ii) cursor.execute("SELECT DISTINCT
(Grade) FROM student where gender='M'")
as "INTEGER PRIMARY KEY"?
Ans. If a column of a table is declared to be an 4. Read the following details.Based on that write
INTEGER PRIMARY KEY, then whenever a a python script to display departmentwise
NULL is used as an input for this column, the records
database name : organization.db
NULL will be automatically converted into an Table name : Employee
integer which will be one larger than the highest
Columns in the table : Eno, EmpName,
value so far used in that column.
Esal, Dept
216
[email protected] Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com

Ans. import sqlite3


This material only for sample

connection = sqlite3. connect ("organization.db")


Sura’s
(iv) 
www.surabooks.com

➠ XII Std - Computer Science


Connecting to a database in step2 means
passing the name of the database to be

Data manipulation through SQL


cursor = connection . cursor () accessed. If the database already exists the
cursor. execute ("SELECT * FROM Employee connection will open the same. Otherwise,
 GROUPBY Dept") Python will open a new database file with
result = cursor . fetchall () the specified name.
print (* result, sep = "\n") (v)  Cursor in step 3 is a control structure used
to traverse and fetch the records of the
5. Read the following details. Based on that write
a python script to display records in desending database.
order of (vi)  Cursor has a major role in working with
Eno Python. All the commands will be executed
database name : organization.db using cursor object only.
Table name : Employee (vii) To create a table in the database, create an
Columns in the table : Eno, EmpName, object and write the SQL command in it.
Esal, Dept Example : sql_comm = "SQL statement"

ns
Ans. import sqlite3 (viii) For executing the command use the
connection = sqlite3 . connect ("organization.db") cursor method and pass the required sql

io
cursor = connection . cursor () command as a parameter. Many number of
cursor. execute ("SELECT * FROM Employee commands can be stored in the sql_comm
 ORDER BY Eno DESC")
at and can be executed one after other.
result = cursor . fetchall () (ix) Any changes made in the values of the
ic
print (*result, sep = "\n") record should be saved by the commend
bl

Part - IV "Commit" before closing the "Table


connection".
Answer the following questions
Pu

2. Write the Python script to display all the records


 (5 marks) of the following table using fetchmany()

1. Write in brief about SQLite and the steps used Icode Item Name Rate
ra

to use it. 1003 Scanner 10500


Ans. (i) SQLite is a simple relational database
Su

1004 Speaker 3000


system, which saves its data in regular data
files or even in the internal memory of the 1005 Printer 8000
computer.
1008 Monitor 15000
(ii) It is designed to be embedded in
applications, instead of using a separate 1010 Mouse 700
database server program such as MySQLor
Oracle. Ans. A
 ssume database name, is shop.db and table
(iii) SQLite is fast, rigorously tested, and name is electronics for the given table.
flexible, making it easier to work. Python Python Script :
has a native library for SQLite. import sqlite3
To use SQLite, connection = sqlite3.connect ("shop.db")
Step 1 : import sqlite3 cursor = connection . cursor ()
Step 2 : create a connection using connect cusrsor . execute ("SELECT * FROM
() method and pass the name of electronics")
the database file
result = cursor . fetchall ()
Step 3 : Set the cursor object cursor =
connection. cursor () print (* result, sep = "\n")

217
[email protected] Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample

additional questions and Answers


Sura’s
www.surabooks.com

➠ XII Std - Computer Science

Data manipulation through SQL


Choose the Correct Answer 1 MARK 8. The command to populate the table is
(a) ADD (b) APPEND
1. Which of following is fast, flexible and easy to (c) INSERT (d) ADDROW
work?  [Ans. (c) INSERT]
9. Which of the following statement in SQL is
(a) CSV (b) SQlite
used to retrieve or fetch data from a table in
(c) Perl (d) Ruby
a database?
 [Ans. (b) SQlite] (a) select (b) inset
2. Which method is SQlite is used create a (c) create (d) fetch
connection with a database file created?  [Ans. (a) select]
(a) cursor () (b) lite () 10. Which sqlite method is used to fetch all rows
(c) connect () (d) connection () from the database table?
 [Ans. (c) connect ()] (a) fetch () (b) fetchrowsAll ()

ns
3. Which method has a major role in working (c) fectchmany () (d) fetchall ()
with python?  [Ans. (d) fetchall ()]
(a) cursor ()

io
11. Which SQlite method is used to fetch the
(b) connect ()
required number of rows in the database table?
(c) execute ()
(d) close
at (a) fetch () (b) fetchamany ()
 [Ans. (a) cursor ()] (c) fetchrows () (d) tablerows ()
ic
 [Ans. (b) fetchamany ()]
4. The SQlite command opens the already created
bl

database is 12. Which of the following clause will not work in


(a) Cursor (b) Sql-comm SQlite?
Pu

(c) Connect (d) Connection (a) DISTINCT (b) HAVING


 [Ans. (c) Connect] (c) FETCHALL (d) WHERE
5. Which of the following is a command to  [Ans. (c) FETCHALL]
ra

open the already created database from 13. Which SQlite keyword is used to fetch only the
the statement connection = sqlite3.connect unique values from the database table?
("ABC.db")
Su

(a) UNIQUE (b) DISTINCT


(a) ABC.db (b) connect
(c) SQlite3 (d) connection (c) GROUPBY (d) HAVING
 [Ans. (b) connect]  [Ans. (b) DISTINCT]
6. Which of the following is used define a SQL
14. Which SQlite keyword is used to extract only
command in SQlite3?
those records that fulfill a specified condition?
(a) " " (b) " " " "
(a) WHERE (b) EXTRACT
(c) ' ' (d) " " " " " "
(c) CONNECT (d) CURSOR
 [Ans. (d) " " " " " "]
 [Ans. (a) WHERE]
7. A table column will be automatically auto
incremented in SQlite3 by giving 15. Which of the following clause is often used
with aggregate functions to group the result?
(a) KEY
(b) PRIMARY KEY (a) ORDER BY
(c) PRIMARY COLUMN (b) WHERE
(d) KEY PRIMARY (c) GROUP BY
 [Ans. (c) PRIMARY COLUMN] (d) DISTINCT
 [Ans. (c) GROUP BY]
219
[email protected] Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample www.surabooks.com

 
Chapter DATA VISUALIZATION USING PYPLOT:
16 LINE CHART, PIE CHART AND BAR CHART

CHAPTER SNAPSHOT
www.nammakalvi.org

16.1 Data Visualization Definition
16.2 Getting Started
16.3 Special Plot Types

ns
Evaluation
io
Part - I
at
Choose the best answer (1 mark) 4. Read the following code: Identify the purpose of
ic
this code and choose the right option from the
1. Which is a python package used for 2D
bl

following.
graphics?
(a) matplotlib.pyplot (b) matplotlib.pip C:\Users\Your Name\AppData\Local Programs\
Pu

(c) matplotlib.numpy (d) matplotlib.plt Python\ Python36-32\Scripts>pip list


[Ans. (a) matplotlib.pyplot] (a) List installed packages
2. Identify the package manager for Python (b) list command
ra

packages, or modules.
(c) Install PIP
(a) Matplotlib (b) PIP
Su

(c) plt.show() (d) python package (d) packages installed


[Ans. (b) PIP] [Ans. (a) List installed packages]

3. Read the following code: Identify the purpose 5. To install matplotlib, the following function will
of this code and choose the right option from be typed in your command prompt. What does
the following. “-U”represents?
C : \ Us e r s \ Yo u r N a m e \ A p p D a t a \ L o c a l Python –m pip install –U pip
Programs\Python\Python36-32\Scripts>pip
–version (a) downloading pip to the latest version
(a) Check if PIP is Installed (b) upgrading pip to the latest version
(b) Install PIP (c) removing pip
(c) Download a Package (d) upgrading matplotlib to the latest version
(d) Check PIP version [Ans. (b) upgrading pip to the latest version]
[Ans. (a) Check if PIP is Installed]

[223]

[email protected] Ph: 81242 01000 / 812430 1000 / 96001 75757



www.surabooks.com

Part - II
This material only for sample

Sura’s
www.surabooks.com

➠ XII Std - Computer Science


5. Write the difference between the following

Data Visualization Using Pyplot: Line Chart, Pie Chart and Bar Chart
Answer the following questions functions: plt.plot([1,2,3,4]), plt.plot([1,2,3,4],
[1,4,9,16]).
 (2 marks) Ans.
plt.plot([1,2,3,4]) plt.plot([1,2,3,4],
1. Define: Data Visualization.
[1,4,9,16])
Ans. Data Visualization is the graphical representation After installing A single list or array
of information and data. The objective of Data Matplotlib, we will provided to the plot ()
Visualization is to communicate information begin coding by command, matplotlib
visually to users. For this, data visualization assumes it is a sequence of
importing Matplotlib
uses statistical graphics. Numerical data may y values, and automatically
using the command: generates the x values for
be encoded using dots, lines, or bars, to visually import matplotlib. you. Since python ranges
communicate a quantitative message. pyplot as plt start with 0, the default x
vector has the same length
2. List the general types of data visualization. Now you have
as y but starts with 0.

ns
Ans. (i) Charts imported Matplotlib Hence the x data are
(ii) Tables in your workspace. [0, 1, 2, 3].

io
You need to display plot() is a versatile
(iii) Graphs
the plots. Using command, and will take
(iv) Maps
at
Matplotlib from an arbitrary number of
(v) Infographics within a Python arguments.
ic
(vi) Dashboards script, you have This .plot takes many
to add plt.show() parameters, but the first
bl

3. List the types of Visualizations in Matplotlib. two here are 'x' and 'y'
method inside the file
Ans. There are many types of Visualizations under coordinates. This means,
Pu

to display your plot. you have 4 co-ordinates


Matplotlib. Some of them are :
according to these lists:
(i) Line plot
(1,1), (2,4), (3,9) and
(ii) Scatter plot (4,16).
ra

(iii) Histogram Part - III


(iv) Box plot Answer the following questions
Su

(v) Bar chart and


 (3 marks)
(vi) Pie chart

4. How will you install Matplotlib? 1. Draw the output for the following data
visualization plot.
Ans. You can install the latest version of pip from
import matplotlib.pyplot as plt
your command prompt using the following plt.bar([1,3,5,7,9],[5,2,7,8,2], label="Example
command. one")
Python–m pip install –U pip plt.bar([2,4,6,8,10],[8,6,2,5,6],
label="Example two", color='g')
plt.legend()

225
[email protected] Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit V - Chapter 16
www.surabooks.com

Sura’s ➠ XII Std - Computer Science


plt.xlabel('bar number')
plt.ylabel('bar height')
 
This material only for sample www.surabooks.com

www.nammakalvi.org
Ans. import matplotlib.pyplot as plt
val = [29.2, 54.2, 6.3, 8.35]
plt.title('Epic Graph\nAnother Line! Whoa') label = ["sleeping", "playing", "working", eating"]
plt.show() plt.pie (val, label = label)
Ans. plt.axes (). set_aspect ("equal")
9
plt.title ("Interesting Graph Check it out")
8 plt.show()
7
6
Part - IV
5 Answer the following questions
4
3
 (5 marks)
2 1. Explain in detail the types of pyplots using
1 Matplotlib.

ns
2 4 6 8 9 10 Ans. Matplotlib allows you to create different kinds of
The above code represents the following: plots ranging from histograms and scatter plots
to bar graphs and bar charts.

io
Lables → specifics labels for the bars. Line Chart :
Usage → Assign values to the labels specified. at (i) A Line Chart or Line Graph is a type of
Range → create sequence of numbers. chart which displays information as a series
2. Write any three uses of data visualization. of data points called ‘markers’ connected
ic
Ans. (i)  Data Visualization help users to analyze by straight line segments.
bl

and interpret the data easily. (ii) A Line Chart is often used to visualize
(ii) It makes complex data understandable and a trend in data over intervals of time – a
usable.
Pu

time series – thus the line is often drawn


(iii) Various Charts in Data Visualization helps chronologically.
to show relationship in the data for one or (iii) Program for Line plot :
more variables. import matplotlib.pyplot as plt
ra

years = [2014, 2015, 2016, 2017, 2018]


3. Write the coding for the following:
total_populations = [8939007, 8954518,
Su

a. To check if PIP is Installed in your PC.  8960387, 8956741, 8943721]


b.  To Check the version of PIP installed in plt.plot (years, total_populations)
your PC.
plt.title ("Year vs Population in India")
c. To list the packages in matplotlib.
plt.xlabel ("Year")
Ans. a. pip
plt.ylabel ("Total Population")
b. pip--version
plt.show()
c. pip list In this program,
4. Write the plot for the following pie chart Plt.title() → specifies title to the graph
output. Plt.xlabel() → specifies label for X-axis
Plt.ylabel() → specifies label for Y-axis
Bar Chart :
29.2% (i) A BarPlot (or BarChart) is one of the
54.2% most common type of plot. It shows the
8.3%
8.3% relationship between a numerical variable
and a categorical variable.

226
[email protected] Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample

(ii) Bar chart represents categorical data with


Sura’s
www.surabooks.com

➠ XII Std - Computer Science


2. Explain the various buttons in a matplotlib

Data Visualization Using Pyplot: Line Chart, Pie Chart and Bar Chart
rectangular bars. Each bar has a height window.
corresponds to the value it represents. The Ans. Buttons in the output : In the output figure,
bars can be plotted vertically or horizontally.
you can see few buttons at the bottom left corner.
(iii) It’s useful when we want to compare a given
numeric value on different categories. To Let us see the use of these buttons.
make a bar chart with Matplotlib, we can Subplots
Home Button Pan Axis Button Button
use the plt.bar() function.
(iv) Program :
import matplotlib.pyplot as plt
# Our data Forward / Back Buttons Zoom
Button
Save the
Figure Button

labels = ["TAMIL", "ENGLISH", "MATHS", (i) Home Button → The Home Button will
 "PHYSICS", "CHEMISTRY", "CS"] help one to begun navigating the chart. If
usage = [79.8, 67.3, 77.8, 68.4, 70.2, 88.5] you ever want to return back to the original
# Generating the y positions. Later, we'll view, you can click on this.
 use them to replace them with labels.

ns
(ii) Forward/Back buttons → These buttons
y_positions = range (len(labels)) can be used like the Forward and Back
# Creating our bar plot buttons in browser. Click these to move

io
plt.bar (y_positions, usage) back to the previous point you were at, or
plt.xticks (y_positions, labels) at forward again.
plt.ylabel ("RANGE") (iii) Pan Axis → This cross-looking button
allows you to click it, and then click and
plt.title ("MARKS")
ic
drag graph around.
plt.show() (iv) Zoom → The Zoom button lets you click on
bl

Pie Chart : it, then click and drag a square would like
to zoom into specifically. Zooming in will
Pu

(i) Pie Chart is probably one of the most


common type of chart. It is a circular require a left click and drag. Zoom out with
a right click and drag.
graphic which is divided into slices to
(v) Configure Subplots → This button allows
illustrate numerical proportion.
ra

you to configure various spacing options


(ii) The point of a pie chart is to show the with figure and plot.
relationship of parts out of a whole. To
Su

(vi) Save Figure → This button will allow you to


make a Pie Chart with Matplotlib, we can save figure in various forms.
use the plt.pie() function.
3. Explain the purpose of the following functions:
(iii) The autopct parameter allows us to display
a. plt.xlabel
the percentage value using the Python
b. plt.ylabel
string formatting.
c. plt.title
(iv) Program :
d. plt.legend()
import matplotlib.pyplot as plt
e. plt.show()
sizes = [89, 80, 90, 100, 75]
Ans. a. Specifies label for x-axis
labels = ["Tamil", "English", "Maths",
b. Specifies label for y-axis
 "Science", "Social"]
c.  Specifies title to the graph or assigns the
plt.pie (sizes, labels = labels, autopct =
plot title.
"%.2f ")
d. Invoke the default legend with plt
plt.axes().set_aspect ("equal")
e. Display the plot
plt.show()

227
[email protected] Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit V - Chapter 16
www.surabooks.com

Sura’s
This material only for sample

➠ XII Std - Computer Science

additional questions and Answers


  www.surabooks.com

www.nammakalvi.org

Choose the Correct Answer 1 MARK 8. In Python matplotlib is a


(a) control structure (b) dictionary
1. Which kind of data encoded visually
(c) library (d) list
communicate a quantitative message?
(a) String (b) Numbers  [Ans. (c) library]
(c) Images (d) None of these 9. Matplotlib allows you to create a
 [Ans. (b) Numbers] (a) Table (b) Charts
2. The numerical data is encoded using (c) Maps (d) Info graphics
(a) dots (b) lines  [Ans. (b) Charts]
(c) bars (d) all of these 10. How many types of visualizations are there
 [Ans. (d) all of these] under matplotlib?
(a) 6 (b) 4
3. Which of the following is not a type of Data (c) 5 (d) Many

ns
Visualization?  [Ans. (d) Many]
(a) Graphs (b) Picture
11. Which of following is not a visualization under

io
(c) Maps (d) Infographics matplotlib?
 [Ans. (b) Picture] at (a) Scatter plot (b) Table plot
4. Which of the following is the representation of (c) Histogram (d) Box plot
information in a graphic format?  [Ans. (b) Table plot]
ic
(a) Info graphics (b) Graphics 12. Which of the following is a type of plot that
bl

(c) Dashboard (d) Charts shows the data as a collection of points?


 [Ans. (a) Info graphics] (a) Box plot (b) Chart plot
Pu

5. Which of the following is a collection of (c) Line plot (d) Scatter plot
resources assembled to create a single unified  [Ans. (d) Scatter plot]
visual display? 13. Which plot displays the distribution of data
ra

(a) Info graphics (b) Dashboard based on the five number summary?
(c) Graphics (d) Chats
(a) Scatter plot (b) Line plot
Su

 [Ans. (b) Dashboard]


(c) Box plot (d) Chart plot
6. Which of the following translate complex ideas  [Ans. (c) Box plot]
and concepts into a simple visual format?
(i) Data visualization (ii) Dashboards 14. Which of the following is not a five number
(iii) Tables (iv) Maps summary in box plot visualization?
(a) i, iii (b) iii, ii (a) First Quartile (b) Second Quartile
(c) i, iv (d) i, ii (c) Third Quartile (d) Minimum
 [Ans. (b) Second Quartile]
 [Ans. (d) i, ii]
15. Which of the following is a management
7. The most popular data visualization library in
Python is software for installing python package?
(a) matplotlib (b) pip (a) pip (b) plot
(c) matinfolib (d) matpiplib (c) mat plot lib (d) plot lib
 [Ans. (a) mat plot lib]  [Ans. (c) matplotlib]

www.nammakalvi.org
228
[email protected] Ph: 81242 01000 / 812430 1000 / 96001 75757

You might also like