12CS em 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

14 IMPORTING C++ PROGRAMS IN PYTHON

I. Choose the best answer: (1 Mark)


1. Which of the following is not a scripting language?
(A) JavaScript (B) PHP (C) Perl (D) HTML
2. Importing C++ program in a Python program is called
(A) wrapping (B) Downloading
(C) Interconnecting (D) Parsing
3. The expansion of API is
(A) Application Programming Interpreter
(B) Application Programming Interface
(C) Application Performing Interface
(D) Application Programming Interlink
4. A framework for interfacing Python and C++ is
(A) Ctypes (B) SWIG (C) Cython (D) Boost
5. Which of the following is a software design technique to split your code into separate
parts?
(A) Object oriented Programming (B) Modular programming
(C) Low Level Programming (D) Procedure oriented Programming
6. The module which allows you to interface with the Windows operating system is
(A) OS module (B) sys module
(c) csv module (d) getopt module
7. getopt() will return an empty array if there is no error in splitting strings to
(A) argv variable (B) opt variable
(c)args variable (d) ifile variable
8. Identify the function call statement in the following snippet.
if __name__ =='__main__':
main(sys.argv[1:])
(A) main(sys.argv[1:]) (B) __name__
(C) __main__ (D) argv
9. Which of the following can be used for processing text, numbers, images, and
scientific data?
(A) HTML (B) C (C) C++ (D) PYTHON

..95..
12 – Computer Science

10. What does __name__ contains?


(A) c++ filename (B) main() name
(C) python filename (D) os module name
II. Answer the following questions: (2 Marks)
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.
➢ 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 Translates program one statement at a
it as a whole into machine code. time.
It generates the error message only after It continues translating the program
scanning the whole program. until the first error is met, in which case
it stops.
Debugging is comparatively hard. Debugging is easy.
3. Write the expansion of (i) SWIG (ii)MinGW
(i) SWIG - Simplified Wrapper Interface Generator
(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 directory.
➢ In this Example, the prompt shows the "C:\>”. To goto the directory “pyprg”, type
the command 'cd pyprg' in the command prompt.
➢ It changes to “c:\pyprg>”

..96..
12 – Computer Science

III. Answer the following questions: (3 Marks)


1. Differentiate PYTHON and C++
PYTHON C++
Python is typically an "interpreted" C++ is typically a "compiled" language.
language.
Python is a dynamic-typed language. C++ is compiled statically typed
language.
Data type is not required while declaring Data type is required while declaring
variable. variable.
It can act both as scripting and general It is a general purpose language
purpose language.
2. What are the applications of scripting language?
1. To automate certain tasks in a program
2. Extracting information from a data set
3. Less code intensive as compared to traditional programming language
4. 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 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()
welcome - Module Name
. - Dot operator
display() - Function call
5. What is sys.argv? What does it contain?
➢ sys.argv is the list of command-line arguments passed to the Python program.
➢ argv contains all the items that come via the command-line input, it's basically a
list holding the command-line arguments of the program.
➢ The first argument, sys.argv[0] contains the name of the python program.
➢ sys.argv[1] is the next argument passed to the program.

..97..
12 – Computer Science

IV. Answer the following questions: (5 Marks)


1. Write any 5 features of Python.
❖ Python uses Automatic Garbage Collection whereas C++ does not.
❖ C++ is a statically typed language, while Python is a dynamically 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, there is no need to declare types explicitly where as it should be done
in C++.
❖ In Python, a function may accept an argument of any type, and return multiple
values without any kind of 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 executed
✓ -i - input mode
✓ C++ filename without cpp extension - name of C++ file to be compiled and
executed.
For example,
>>>python pycpp.py –i pali
3. What is the purpose of sys, os, getopt module in Python. Explain.
Python’s sys module:
This module provides access to 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.
➢ argv contains all the items that come via the command-line input, it's basically a
list holding the command-line arguments of the program.
➢ The first argument, sys.argv[0] contains the name of the python program.
➢ sys.argv[1] is the next argument passed to the program.
Python's OS Module:
➢ The OS module in Python provides a way of using operating system dependent
functionality.

..98..
12 – Computer Science

➢ The functions that the OS module allows you to interface with the Windows
operating system where Python is running on.
➢ Execute the C++ compiling command in the shell. For Example to compile C++
program g++ compiler should be invoked through the following command
os.system (‘g++ ’ + <variable_name1> ‘ -<mode> ’ + <variable_name2>
Python getopt module:
➢ This method parses command-line options and parameter list.
➢ Following is the syntax for this method
<opts>,<args>=getopt.getopt(argv, options, [long_options])
4. Write the syntax for getopt() and explain its arguments and return values.
The getopt module of Python helps you to parse (split) command-line options and
arguments.
Syntax:
<opts>,<args>=getopt.getopt(argv, options, [long_options])
Here,
✓ argv − This is the argument list of values to be parsed (splited)
✓ options − This is string of option letters that the Python program recognize as,
for input or for output, with options (like ‘i’ or ‘o’) that followed by a colon (:).
Here colon is used to denote the mode.
✓ long_options −This contains a list of strings. Argument of Long options should
be followed by an equal sign ('=').
✓ In our program the C++ file name along with its path will be passed as string
and ‘i’ i will be also passed to indicate it as the input file.
✓ getopt() method returns value consisting of two elements. Each of these
values are stored separately in two different list (arrays) opts and args.
✓ opts contains list of splitted strings like mode and path.
✓ args contains error string, if at all the comment is given with wrong path or
mode.
✓ args will be an empty list if there is no error.

..99..
12 – Computer Science

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”
Python Program:
# Save the following python programs as “myprg.py”
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__':
main(sys.argv[1:])

..100..
` 15 DATA MANIPULATION THROUGH SQL

I. Choose the best answer: (1 Mark)


1. Which of the following is an organized collection of data?
(A) Database (B) DBMS (C) Information (D) Records
2. SQLite falls under which database system?
(A) Flat file database system (B) Relational Database system
(C) Hierarchical database system (D) Object oriented Database system
3. Which of the following is a control structure used to traverse and fetch the records of
the database?
(A) Pointer (B) Key
(C) Cursor (D) Insertion point
4. Any changes made in the values of the record should be saved by the command
(A) Save (B) Save As (C) Commit (D) Oblige
5. Which of the following executes the SQL command to perform some action?
(A) execute() (B) key() (C) cursor() (D) run()
6. Which of the following function retrieves the average of a selected column of rows in
a table?
(A) Add() (B) SUM() (C) AVG() (D) AVERAGE()
7. The function that returns the largest value of the selected column is
(A) MAX() (B) LARGE()
(C) HIGH() (D) MAXIMUM()
8. Which of the following is called the master table?
(A) sqlite_master (B) sql_master
(C) main_master (D) master_main
9. The most commonly used statement in SQL is
(A) cursor (B) select (C) execute (D) commit
10. Which of the following clause avoid the duplicate?
(A) Distinct (B) Remove (C) Where (D) GroupBy
II. Answer the following questions: (2 Marks)
1. Mention the users who uses the Database.
Users of database can be human users, other programs or applications.

..101..
12 – Computer Science

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


connect() is used to connect/open the existing databases.
Example:
connection = sqlite3.connect ("Academy.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 (add record) the table "INSERT" command is passed to SQLite.
“execute” method executes the SQL command to perform some action.
Example:
cursor.execute(“””INSERT INTO Student (Rollno, Sname)
VALUES (1561, "Aravind")”””)
5. Which method is used to fetch all rows from the database table?
➢ cursor.fetchall() -fetchall () method is to fetch all rows from the database table.
Example:
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM student")
print("fetchall:")
result = cursor.fetchall()
print(result)
III. Answer the following questions: (3 Marks)
1. What is SQLite? What is it advantage?
➢ SQLite is a simple relational database 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.
..102..
12 – Computer Science

➢ 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()
This method returns the next row of a This method returns the next number of
query result set or None in case there is rows (n) of the result set. (Displaying
no row left. specified number of records)
It takes no argument. It takes one argument.
Example: Example:
res = cursor.fetchone() res = cursor.fetchmany(3)
3. What is the use of Where Clause. Give a python statement Using the where clause.
➢ The WHERE clause is used to extract only those records that fulfil a specified
condition.
For example, to display the different grades scored by male students from “student
table” the following code can be used.
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT DISTINCT (Grade) FROM student where gender='M'")
result = cursor.fetchall()
print(*result, sep="\n")
OUTPUT
('B',)
('A',)
('C',)
('D',)
4. Read the following details. Based on that write a python script to display
department wise records
database name :- organization.db
Table name :- Employee
Columns in the table :- Eno, EmpName, Esal, Dept

..103..
12 – Computer Science

Python script:
import sqlite3
connection=sqlite3.connect("organization.db")
cursor=connection.cursor()
cursor.execute("""create table employee(eno integer primary key, empname
varchar(20), esal integer, dept varchar(20));""")
cursor.execute("""insert into employee values ("1001", "Raja", "10500",
"Sales");""")
cursor.execute("""insert into employee values ("1002", "Surya", "9000",
"Purchase");""")
cursor.execute("""insert into employee values ("1003", "Peter", "8000",
"Production");""")
connection.commit()
print("Employee Details Department-wise :")
cursor.execute("""Select * from employee order by dept;""")
result=cursor.fetchall()
print(*result, sep="\n")
connection.close()
5. Read the following details. Based on that write a python script to display records in
descending order of Eno
database name :- organization.db
Table name :- Employee
Columns in the table :- Eno, EmpName, Esal, Dept
Python script:
import sqlite3
connection=sqlite3.connect("organization.db")
cursor=connection.cursor()
cursor.execute("""create table employee(eno integer primary key, empname
varchar(20), esal integer, dept varchar(20));""")
cursor.execute("""insert into employee values ("1001", "Raja", "10500",
"Sales");""")
cursor.execute("""insert into employee values ("1002", "Surya", "9000",
"Purchase");""")
..104..
12 – Computer Science

cursor.execute("""insert into employee values ("1003", "Peter", "8000",


"Production");""")
connection.commit()
print("Records in descending order of employee number:")
cursor.execute("""Select * from employee order by eno desc""")
result=cursor.fetchall()
print(*result,sep="\n")
connection.close()
IV. Answer the following questions: (5 Marks)
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.
To use SQLite,
✓ Step 1 - import sqlite3
✓ Step 2 - create a connection using connect() method and pass the name of
the database file. 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 - Set the cursor object cursor = connection.cursor(). It is a control
structure used to traverse and fetch the records of the database.
o Cursor has a major role in working with Python. All the commands will
be executed using cursor object only.
Example:
import sqlite3
connection=sqlite3.connect("organization.db")
cursor=connection.cursor( )

..105..
12 – Computer Science

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

Python script:
import sqlite3
connection=sqlite3.connect("inventory.db")
cursor=connection.cursor()
cursor.execute("""select * from product;""")
print("Displaying all records in the table")
result=cursor.fetchmany(5)
print(*result, sep="\n")
connection.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]

..106..
12 – Computer Science

print(co)
print(result)
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.
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

Python script:
import sqlite3
connection=sqlite3.connect("ABC.db")
cursor=connection.cursor()
cursor.execute("""drop table item;""")
cursor.execute("""create table item(icode integer primary key, itemname
varchar(25), rate integer);""")
cursor.execute("""insert into item values("1005","Printer","8000");""")
connection.commit()
connection.close()
print("Item table is created and a record is added Successfully")

..107..
12 – Computer Science

5. Consider the following table Supplier and item .Write a python script for (i) to (ii)
SUPPLIER

Suppno Name City Icode SuppQty

S001 Prasad Delhi 1008 100

S002 Anu Bangalore 1010 200

S003 Shahid Bangalore 1008 175

S004 Akila Hydrabad 1005 195

S005 Girish Hydrabad 1003 25

S006 Shylaja Chennai 1008 180

S007 Lavanya Mumbai 1005 325

i) Display Name, City and Itemname of suppliers who do not reside in Delhi.
ii) Increment the SuppQty of Akila by 40
Python script:
import sqlite3
connection=sqlite3.connect("item.db")
cursor=connection.cursor()
# i) Display Name, City and Itemname of suppliers who do not reside in Delhi.
cursor.execute ("SELECT supplier.name, supplier.city, item.itemname FROM
supplier, item WHERE supplier.city <> ’Delhi’ ")
ans=cursor.fetchall ( )
for i in ans:
print()
# ii) Increment the SuppQty of Akila by 40
cursor.execute ("UPDATE supplier SET supplier.SuppQty =S uppQty + 40
WHERE name=’Akila’ ")
connection.commit()
connection.close()

..108..
DATA VISUALIZATION USING PYTHON:
16
LINE CHART, PIE CHART AND BAR CHART

I. Choose the best answer: (1 Mark)


1. Which is a python package used for 2D graphics?
(A) matplotlib.pyplot (B) matplotlib.pip
(C) matplotlib.numpy (D) matplotlib.plt
2. Identify the package manager for Python packages, or modules.
(A) Matplotlib (B) PIP
(C) plt.show() (D) python package
3. Read the following code: Identify the purpose of this code and choose the right option
from the following.
C:\Users\YourName\AppData\Local\Programs\Python\Python36-32\Scripts>pip –
version
(A) Check if PIP is Installed (B) Install PIP
(C) Download a Package (D) Check PIP version
4. Read the following code: Identify the purpose of this code and choose the right option
from the following.
C:\Users\YourName\AppData\Local\Programs\Python\Python36-32\Scripts>pip
list
(A) List installed packages
(B) list command
(C) Install PIP
(D) packages installed
5. To install matplotlib, the following function will be typed in your command prompt.
What does “-U” represents?
Python –m pip install –U pip
(A) downloading pip to the latest version
(B) upgrading pip to the latest version
(C) removing pip
(D) upgrading matplotlib to the latest version

..109..
12 – Computer Science

6. Observe the output figure. Identify the coding for obtaining this output.

(A) import matplotlib.pyplot as plt


plt.plot([1,2,3],[4,5,1])
plt.show()
(B) import matplotlib.pyplot as plt
plt.plot([1,2],[4,5])
plt.show()
(C) import matplotlib.pyplot as plt
plt.plot([2,3],[5,1])
plt.show()
(D) import matplotlib.pyplot as plt
plt.plot([1,3],[4,1])
plt.show()
7. Read the code:
(A) import matplotlib.pyplot as plt
(B) plt.plot(3,2)
(C) plt.show()
Identify the output for the above coding.

..110..
12 – Computer Science

8. Which key is used to run the module?


(A) F6 (B) F4 (C) F3 (D) F5
9. Identify the right type of chart using the following hints.
Hint 1: This chart is often used to visualize a trend in data over intervals of time.
Hint 2: The line in this type of chart is often drawn chronologically.
(A) Line chart (B) Bar chart
(C) Pie chart (D) Scatter plot
10. Read the statements given below. Identify the right option from the following for pie
chart.
Statement A: To make a pie chart with Matplotlib, we can use the plt.pie() function.
Statement B: The autopct parameter allows us to display the percentage value using
the Python string formatting.
(A) Statement A is correct (B) Statement B is correct
(C) Both the statements are correct (D) Both the statements are wrong
II. Answer the following questions: (2 Marks)
1. Define: Data Visualization.
Data Visualization is the graphical representation of information and data. The
objective of Data Visualization is to communicate information visually to users.
2. List the general types of data visualization.
➢ Charts
➢ Tables
➢ Graphs
➢ Maps
➢ Infographics
➢ Dashboards
3. List the types of Visualizations in Matplotlib.
➢ Line plot
➢ Scatter plot
➢ Histogram
➢ Box plot
➢ Bar chart and
➢ Pie chart

..111..
12 – Computer Science

4. How will you install Matplotlib?


✓ To install matplotlib, type the following in your command prompt:
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]).
Case 1: plt.plot([1,2,3,4])
matplotlib assumes it is a sequence of y values, and automatically generates the x
values for you. 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].
Case 2: plt.plot([1,2,3,4], [1,4,9,16])
This plot takes many parameters, but the first two here are 'x' and 'y' coordinates.
This means, you have 4 co-ordinates according to these lists: (1,1), (2,4), (3,9) and
(4,16).
III. Answer the following questions: (3 Marks)
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()
Output:

..112..
12 – Computer Science

2. Write any three uses of data visualization.


❖ Data Visualization help 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 install –U pip
b. To Check the version of PIP installed in your PC.
pip --version
c. To list the packages in matplotlib.
pip list
4. Write the plot for the following pie chart output.

Code:
import matplotlib.pyplot as plt
sizes=[29.2,8.3,8.3,54.2]
labels=["Sleeping","Eating","Working","Playing"]
cols=['c','m’,’r’,'b’]
plt.pie(sizes, labels=labels, colors=cols, autopct="%.2f")
plt.axes().set_aspect("equal")
plt.title("Interesting Graph \n Check it Out!!!!")
plt.show()

..113..
12 – Computer Science

IV. Answer the following questions: (5 Marks)


1. Explain in detail the types of pyplots using Matplotlib.
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.
➢ It 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=[1,4,9]
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:
➢ It is one of the most common types of plot. It shows the relationship between a
numerical variable and a categorical variable.
➢ Bar chart represents categorical data with rectangular bars.
➢ The bars can be plotted vertically or horizontally.
➢ It’s useful when we want to compare a given numeric value on different
categories.
➢ To make a bar chart with Matplotlib, we can use the plt.bar() function.
Example:
import matplotlib.pyplot as plt
sub=["TAM","ENG","Mat","Phy”,"Che","CS"]
mark=[78,67,99,70,80,88]
plt.bar(sub,mark)
plt.xlabel(’'Subject’)
plt.ylabel(‘Marks’)
plt.title(“Student Marks”)
plt.show( )
..114..
12 – Computer Science

Pie Chart:
➢ Pie Chart is probably 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.
Example
import matplotlib.pyplot as plt
sizes = [89, 80, 90, 100, 75]
labels = ["Tamil", "English", "Maths", "Science", "Social"]
plt.pie (sizes, labels = labels, autopct = "%.2f ")
plt.axes().set_aspect ("equal")
plt.show()

2. Explain the various buttons in a matplotlib window.

➢ Home Button → The Home Button will help to return back to the original view.
➢ Forward/Back buttons → These buttons can be used to move back to the previous
point you were at, or forward again.
➢ Pan Axis → This cross-looking button allows you to click it, and then click and drag
your graph around.

..115..
12 – Computer Science

➢ Zoom → The Zoom button lets you click on it, then click and drag a square that
you would like to zoom into specifically. Zooming in will require a left click and
drag. You can alternatively zoom out with a right click and drag.
➢ Configure Subplots → This button allows you to configure various spacing options
with your figure and plot.
➢ Save Figure → This button will allow you to save your figure in various forms.
3. Explain the purpose of the following functions:
a. plt.xlabel
It is used to assign label for X-axis.
b. plt.ylabel
It is used to assign label for Y-axis.
c. plt.title
It is used to assign title for the chart.
d. plt.legend()
It is used to add legend for the data plotted. It is needed when more data
are plotted in the chart.
e. plt.show()
It is used to display our plot.

..116..
12 – Computer Science

Annexure – 1
Additional Question & Answers

..117..
Additional Q & A - Contents
Chapter Title Page

1 Functions 119

2 Data Abstraction 124

3 Scoping 129

4 Algorithmic Strategies 133

5 Python – Variables and Operators 139

6 Control Structures 149

7 Python Functions 157

8 Strings and String manipulations 168

9 List, Tuples, Set and Dictionary 174

10 Python Classes and objects 180

11 Database Concepts 185

12 Structured Query Language (SQL) 193

13 Python and CSV files 204

14 Importing C++ Programs in Python 210

15 Data Manipulation through SQL 216

16 Data Visualization using pyplot: Line chart, Pie chart 220


and Bar charts

..118..
1. Functions

I. Additional One Marks:


1. The most important criteria in writing and evaluating algorithm is
a) Number of lines b) Number of blocks
c) Time to complete a task d) Storage capacity
2. Which of the following are the building blocks of computer programs?
a) Function b) Definitions c) Parameters d) Subroutines
3. Which of the following are small section of code that are used to perform particular
task repeatedly?
a) Function b) Definitions c) Subroutines d) Programs
4. 4. In programming languages, subroutines are also called as
a) Functions b) Definitions c) Parameters d) Subroutines
5. Which of the following is a unit of code that is often defined within a greater code
structure?
a) Function b) Definitions c) Parameters d) Subroutines
6. a:=(24) is a
a) Initialization b) Declaration
c) Function definition d) Assignment
7. Which of the following is a distinct syntactic block?
a) Function b) Definitions c) Parameters d) Subroutines
8. The variables used in function definition is called
a) Arguments b) Parameters
c) Both a and b d) None of the above
9. The values which are passed to a function definition is
a) Arguments b) Parameters
c) Both a and b d) None of the above
10. The syntax to define function begins with
a) fun b) func c) let d) rec
11. The syntax for function definition is
a) fun rec fn a1,a2..an:=k b) func rec fn a1,a2..an:=k
c) rec fn a1,a2..an:=k d) let rec fn a1,a2..an:=k
12. Which of the following key indicate that the function is a recursive function?
a) rec b) recursive c) recur d) recu

..119..
12 – Computer Science

13. A function definition which call itself is called


a) main function b) self-function
c) function definition d) recursive function
14. Which of the following syntax represents the type of a function that gets an input of
type ‘x’ and returns an output of type ‘y’?
a) x=y b) x=>y c) x*y d) x->y
15. Which of the following is a set of action that an object can do?
a) Function b) Implementation c) Interface d) Object
16. When you press a light switch, the light goes on, you not have cared how it splashed
the light. It is an example for,
a) Function b) Implementation c) Object d) Interface
17. Which of the following is a description of all functions that a class must have in OOP
language?
a) Function b) Implementation c) Interface d) Object
18. An instance created for the class is
a) Function b) Variables
c) Objects d) Constructors
19. Which of the following defines an object’s visibility to the outside world?
a) Interface b) Implementation c) Both a and b d) Function
20. In OOP’s classes are
a) Interface b) Implementation c) Both a and b d) Function
21. In OOP’s, how the object is processed and executed is
a) Interface b) Implementation c) Both a and b d) Function
22. The functions which will give exact result when the same arguments are passed is
called
a) User defined functions b) Pure functions
c) Impure functions d) Assigned functions
23. sin(0) is a function, which is example for
a) User defined functions b) Pure functions
c) Impure functions d) Assigned functions
24. Which of the following statement(s) is/are true?
i) Evaluation of pure functions does not cause any side effects to its output.
ii) Pure function can be called several times with same arguments.
..120..
12 – Computer Science

iii) sin(0) is an example for impure function.


iv) strlen() is an example for pure function.
a) i, ii b) i, ii, iv c) iii only d) ii, iii, iv
25. The variables used inside the function may cause side effects through the functions
which are not passed with any arguments are called
a) User defined functions b) Pure functions
c) Impure functions d) Assigned functions
26. Which of the following do not have any side effects?
a) User defined functions b) Pure functions
c) Impure functions d) Assigned functions
27. Which of the following are expressed using statements of a programming language?
a) Specifications b) Pseudo Code c) Algorithms d) Flowchart
28. Which of the following carries out the instructions defined in the interface?
a) Function b) Implementation c) Interface d) Object
29. The following function is an example for
let rec sum x y:
Return x + y
a) User defined function b) Recursive function
c) Normal function d) Assigned function
30. The algorithm can be depicted as
a) Specifications b) Pseudo Code c) Algorithm d) Flowchart
II. Additional Two and Three Marks:
1. What are parameters?
Parameters are the variables in a function definition.
2. What are arguments?
Arguments are the values which are passed to a function definition through the
function definition.
3. What is recursive function?
A function definition which call itself is called recursive function.
4. What is an object?
An object is an instance created from the class.
5. What is an interface?
Interface just defines what an object can do, but won’t actually do it.
..121..
12 – Computer Science

6. What is implementation?
Implementation carries out the instructions defined in the interface
7. What is pure function?
Pure functions are functions which will give exact result when the same arguments
are passed.
8. What is impure function?
The variables used inside the function may cause side effects though the functions
which are not passed with any arguments. In such cases the function is called impure
function.
III. Additional Five Marks:
1. How will you solve the problem of chameleons in chrome land? Describe by
algorithm and flowchart?
➢ If the two types of chameleons are an equal number, then these two types
together will change to the color of the third type. In the end, all should display
the same color.
➢ Let us represent the number of chameleons of each type by variables a, b and c,
and their initial values by A, B and C, respectively.
➢ Let a = b be the input property. The input – output relation is a = b = 0 and c = A +
B + C.
➢ Let us name the algorithm monochromatize. The algorithm can be specified as
monochromatize (a, b, c)
inputs: a = A, b = B, c = C, a = b
outputs: a = b = 0, c = A+B+C
Example
A, B, C = 4, 4, 6

iteration a b c
0 4 4 6
1 3 3 8
2 2 2 10
3 1 1 12
4 0 0 14

..122..
12 – Computer Science

Algorithm:
let rec monochromatize a b c :=
if a>0 then
a,b,c := a-1, b-1, c+2
else
a:=0, b:=0, c:=a+b+c
return c

Flowchart:

..123..
2. Data Abstraction

I. Additional One Marks:


1. Which of the following is a powerful concept in computer science that allows
programmers to treat code as objects?
a) Data Encapsulation b) Inheritance
c) Data Abstraction d) Structures
2. “Programmers need not worry about how code is implemented-they have just know
what it does” is
a) Abstraction b) Inheritance c) Class d) Structures
3. Splitting a program into many modules is called
a) Control Flow b) Looping c) Abstraction d) Modularity
4. Which of the following are the representation for “Abstract Data Types”?
a) Object b) Classes c) Functions d) Inheritance
5. A type for objects whose behaviour is defined by a set of value and set of operations
is called
a) Abstract Data Types b) Class c) Functions d) Objects
6. The definition of ADT only mentions
a) what operations are to be performed but not how these operations will be
implemented
b) what operations are not to be performed but not how these operations will be
implemented
c) what operations are not to be performed but how these operations will be
implemented.
d) what operations are to be performed and how these operations will be
implemented.
7. The process of providing only the essentials and hiding the details is known as
a) Abstraction b) Encapsulation c) Both a and b d) Inheritance
8. The List ADT can be implemented using
a) Singly Linked List b) Doubly Linked list c) a or b d) both a and b
9. Stack ADT and Queue ADT can be implemented using
a) Stack b) Queue c) Both a and b d) Lists
10. Which of the following replicate how we think about the world?
a) Function b) Data abstraction c) Scoping d) Encapsulation

..124..
12 – Computer Science

11. To facilitate data abstraction, you will need to create


a) Constructors b) Destructors c) Selectors d) Both a and c
12. A function that builds the abstract data type is
a) Constructors b) Destructors c) Selectors d) Both a and c
13. A function which retrieves information from the data type is
a) Constructors b) Destructors c) Selectors d) Both a and c
14. city = makecity(name, lat, lon) is an example for
a) Constructors b) List c) Selectors d) Tuple
15. getname(city) is an example for
a) Constructors b) List c) Selectors d) Tuple
16. Data abstraction is supported by defining an abstract data type which is a collection of
a) Constructors b) Selectors c) Destructors d) Both a and b
17. The formation of beliefs and making decisions according to what might be pleasing to
imagine instead of by appealing to reality is
a) Abstraction b) Wishful thinking c) Constructors d) Selectors
18. To implement the concrete level of data abstraction, python provides a compound
structure called
a) Wishful thinking b) Pair c) List d) Tuple
19. List is constructed by placing expressions within square brackets separated by
a) Periods(.) b) Colon(:) c) Semicolon(;) d) Comma(,)
20. List can store
a) Multiple values b) Value can be of any type
c) Another list d) All the above
21. Identify the correct list usage from the following:
i. LIST[10,20] ii. LIST(10,20) iii. LIST[(0,10),(1,20)] iv. LIST{10,20}
a) i Only b) i, ii Only c) i, iii Only d) i, ii, iii, iv
22. The elements of a list can be accessed in
a) One way b) Two ways c) Three ways d) Four ways
23. One way of accessing the element in a list is by the
a) Addition operator b) Colon
c) Selection operator d) Dot operator
24. Any way of bundling two values together into one can be considered as
a) Pair b) List c) Tuple d) Set
..125..
12 – Computer Science

25. List:=[15,25]. To access the element 15 from the list, which of the following method
should be used?
a) List[15] b) List[0] c) List[1] d) List(0)
26. A tuple is a comma separated sequence of values surrounded with
a) Square brackets b) Set brackets
c) Parentheses d) Double quotes
27. The notation used to access the data stored in tuple is
a) Square brackets b) Set brackets
c) Parentheses d) Double quotes
28. The index value of list and tuple starts from
a) 1 b) -1 c) 0 d) NULL
29. tup:=(15,25). To access the element 15 from the list of values, which method should
be used?
a) List(15) b) List[0] c) List(1) d) List(0)
30. Which of the following is used to represent multi-part objects where each part is named?
a) Class b) Function c) Structure d) Object
31. Bundled data and the functions that work on that data are called
a) Class b) Function c) Structure d) Object
32. Bundling two values together into on can be considered as
a) Wishful thinking b) Pair c) List d) Tuple
33. Which of the following does not allow to name the various parts of a multi-item
objects?
a) Wishful thinking b) Pair c) List d) Tuple
34. Identify the following: N1 = number ()
a) Constructor b) Selector c) List d) Tuple
35. Identify the following: eval(a/b)
a) Constructor b) Selector c) List d) Tuple
36. Identify the following: arr(1, 2, 34)
a) Constructor b) Selector c) List d) Tuple
37. Identify the following: x=[2,5,6.5,[5,6],8.8]
a) Constructor b) Class c) List d) Tuple
38. Identify the following: student[rno,name,mark]
a) Constructor b) Class c) List d) Tuple
..126..
12 – Computer Science

39. Identify the following : display()


a) Constructor b) Selector
c) List d) Tuple
40. Identify the following : accetnum(n1)
a) Constructor b) Selector
c) List d) Tuple
II. Additional Two and Three Marks:
1. What is abstraction?
The process of providing only the essentials and hiding the details is known as
abstraction.
2. What are the different parts of a program?
The two parts of a program are
(i) The part that operates on abstract data
(ii) The part that defines a concrete representation
III. Additional Five Marks:
1. Explain the representation of Abstract datatype using Rational numbers.
➢ The basic idea of data abstraction is to structure programs so that they operate
on abstract data.
➢ Any program consists of two parts. The two parts of a program are, the part that
operates on abstract data and the part that defines a concrete representation, is
connected by a small set of functions that implement abstract data in terms of the
concrete representation.
Example
➢ A rational number is a ratio of integers, and rational numbers constitute an
important sub-class of real numbers. A rational number is typically written as:
<numerator>/<denominator>
✓ where both the <numerator> and <denominator> are placeholders for integer
values. Both parts are needed to exactly characterize the value of the rational
number.
➢ A rational number, you have a way of selecting its numerator and its denominator
component. Let us further assume that the constructor and selectors are also
available.

..127..
12 – Computer Science

Example: An ADT for rational numbers


- - constructor
- - constructs a rational number with numerator n, denominator d
rational(n, d)
- -selector
numer(x) → returns the numerator of rational number x
denom(y) → returns the denominator of rational number y
The pseudo code for the representation of the rational number using the above
constructor and selector is
x, y := 8, 3
rational(n,d)
numer(x) / denom(y)
- - output : 2.6666666666666665

..128..
3. Scoping

I. Additional One Marks:


1. Which of the following refers to the visibility of the variables, parameters and
functions in one part of the program to another part of the same program?
a) Scope b) Mapping c) Function d) Definitions
2. Which of the following refers, which parts of your program can see or use it?
a) Scope b) Mapping c) Function d) Definitions
3. Every variable defined in a program has
a) Local Scope b) Global Scope
c) Enclosed Scope d) Built in Scope
4. Which of the following can be accessed every part of your program?
a) Local Scope b) Global Scope
c) Enclosed Scope d) Built in Scope
5. Which of the following are the addresses to an object in memory?
a) Literals b) Variables c) Scoping d) Function
6. The process of binding a variable name with an object is called
a) Scope b) Binding c) Mapping d) Namespace
7. The symbol used in programming languages to map the variables and object is
a) = b) := c) : d) ;
8. The containers used for mapping names of variables to objects is
a) Scope b) Binding c) Mapping d) Namespace
9. What is the value of ‘b’ in the following?
a := 5
b := a
a := 3
a) 5 b) 3 c) NULL d) 0
10. The duration for which a variable is alive is called
a) Live Time b) Access Time c) Active Time d) Life Time
11. The order in which variables have to be mapped to the object in order to obtain the
value is defined by
a) Scope b) Binding c) Mapping d) Namespace
12. In terms of hierarchy, the scope with highest priority is
a) Local b) Enclosed c) Global d) Built-in

..129..
12 – Computer Science

13. In terms of hierarchy, the scope with lowest priority is


a) Local b) Enclosed c) Global d) Built-in
14. A variable which is declared inside a function which contains another function
definition within it is
a) Local b) Enclosed c) Global d) Built-in
15. Which of the following are loaded as soon as the library files are imported to the
program?
a) Local b) Enclosed c) Global d) Built-in
16. Which of the following refers to variables defined in current function?
a) Local b) Enclosed c) Global d) Built-in
17. A variable defined outside of all the functions in a program is known as
a) Local b) Enclosed c) Global d) Built-in
18. The scope names that are pre-loaded into program scope when we start the compiler
or interpreter is
a) Local b) Enclosed c) Global d) Built-in
19. A function within another function is called
a) Built-in function b) Nested function
c) Mixed function d) Co-operate function
20. Which of the following can be separately compiled and stored in a library?
a) Programs b) Scope c) Namespace d) Modules
21. Which of the following is/are true?
I) Modules can be included in a program
II) Module segments can be used by invoking a name and some parameters
III) Module segments cannot be used by other modules
a) I Only b) I & II c) II & III d) I, II, III
22. Which of the following programming allows many programmers to collaborate on the
same application?
a) Linear b) Dynamic c) Modular d) All of these
23. A security technique that regulates who or what can view or use resources in a
computing environment is
a) Modular Programming b) Access Control c) Mapping d) Password
24. A fundamental concept in security that minimizes risk to the object is
a) Modular Programming b) Access Control c) Mapping d) Password
..130..
12 – Computer Science

25. Which of the following members of a class are denied access from the outside of class?
a) private b) public c) protected d) All of these
26. The members that are accessible from outside the class is
a) private b) public c) protected d) All of these
27. The arrangement of private instance variables and public methods ensures the
principle of
a) Data Abstraction b) Inheritance
c) Polymorphism d) Data Encapsulation
28. Which of the following enables specific resources of the parent class to be inherited
by the child class?
a) private b) public c) protected d) All of these
29. The members accessible from within the class and are also available to its sub-classes is
a) private b) public c) protected d) All of these
30. The symbol prefixed with the variable to indicate protected and private access
specifiers is
a) Single underscore b) Double underscore
c) Single or Double underscore d) Backslash
31. By default, all members in a python class are
a) private b) public c) protected d) All of these
32. By default, all members in C++ and Java class are
a) private b) public c) protected d) All of these
33. The process of subdividing a computer program into separate sub-programs is called
a) Linear b) Dynamic c) Modular d) All of these
34. What is the output of the following:
a:=7
Disp():
a:=18
print a
Disp()
a) 7 b) Error c) 18 d) No Output
35. How many types of variable scopes are there?
a) 1 b) 2 c) 3 d) 4

..131..
12 – Computer Science

II. Additional Two and Three Marks:


1. What is the lifetime of a variable?
The duration for which a variable is alive is called its ‘life time’.
2. What is the use of LEGB rule?
The LEGB rule is used to decide the order in which the scopes are to be searched
for scope resolution.
3. Define module.
A module is a part of a program. Programs are composed of one or more
independently developed modules.
4. What is modular programming?
The process of subdividing a computer program into separate sub-programs is
called Modular programming.
5. What is nested function?
A function (method) with in another function is called nested function.
6. Write about the access specifiers.
➢ Public members (generally methods declared in a class) are accessible from
outside the class.
➢ Protected members of a class are accessible from within the class and are also
available to its sub-classes.
➢ Private members of a class are denied access from the outside the class. They can
be handled only from within the class.

..132..
4. Algorithmic Strategies

I. Additional One Marks:


1. A finite set of instructions to accomplish a particular task is called
a) Flow chart b) Algorithm
c) Pseudo code d) Walkthrough
2. An algorithm is
I) a finite set of instructions to accomplish a particular task
II) a step-by-step procedure for solving a given problem
III) implemented in any suitable programming language
a) I Only b) I & III Only
c) I, II, III d) None of the above
3. The way of defining an algorithm is called
a) Algorithmic procedure b) Algorithmic definition
c) Algorithmic function d) Algorithmic strategy
4. The word algorithm has come to refer to a method
a) to derive a problem b) to solve a problem
c) to define a problem d) to evaluate a problem
5. An algorithm that yields expected output for a valid input is called
a) Problem solving b) Derivations
c) Algorithmic solution d) None of the above
6. Which of the following is an expression of algorithm in a programming language?
a) Program b) Algorithm
c) Flow chart d) Pseudo code
7. Which of the following resembles a pseudo code which can be implemented in any
language?
a) Program b) Algorithm
c) Flow chart d) Pseudo code
8. The utilization of time and space complexity is defined by
a) Speed of the program b) Flow of program
c) Simplicity of an algorithm d) Efficiency of an algorithm
9. How many phases are there in analysis and performance evolution of an algorithm?
a) 2 b) 3
c) 1 d) 4

..133..
12 – Computer Science

10. A theoretical performance analysis of an algorithm is


a) Time factor b) Space factor
c) Priori estimates d) Posteriori testing
11. Performance measurement of an algorithm is
a) Time factor b) Space factor
c) Priori estimates d) Posteriori testing
12. How many factors are deciding the efficiency of an algorithm?
a) 1 b) 2
c) 3 d) 4
13. Which of the following is measured by counting the number of key operations like
comparisons in sorting algorithm?
a) Time factor b) Space factor
c) Priori estimates d) Posteriori testing
14. Which of the following is measured by the maximum memory space required by the
algorithm?
a) Time factor b) Space factor
c) Priori estimates d) Posteriori testing
15. Which of the following is given by the number of steps taken by the algorithm to
complete the process?
a) Time factor b) Space factor
c) Time complexity d) Space complexity
16. Which of the following is the amount of memory required to run to its completion?
a) Time factor b) Space factor
c) Time complexity d) Space complexity
17. The total space required to store certain data and variables for an algorithm is
defined by
a) Variable part b) Module part
c) Fixed part d) Memory part
18. The total space required by variables, which size depends on the problem and its
iteration is defined by
a) Variable part b) Module part
c) Fixed part d) Memory part

..134..
12 – Computer Science

19. The number of computational resources used by the algorithm is


a) Speed of the program b) Flow of program
c) Simplicity of an algorithm d) Efficiency of an algorithm
20. Different factors used to measure the time efficiency of an algorithm(s) is/are
a) Operating system b) Volume of data required
c) Speed of the machine d) All the above
21. The best algorithm to solve a given problem requires
a) less space, less time b) less space, more time
c) more space, less time d) more space, more time
22. The languages that use meaningful statements about time and space complexity is
a) time/space trade-off b) Asymptotic notations
c) Time complexity d) Space complexity
23. How many asymptotic notations are used to represent time complexity of an
algorithm?
a) 1 b) 2 c) 3 d) 4
24. The notation used to describe the worst-case of an algorithm is
a) Big O b) Big Ω c) Big  d) Big α
25. Which of the following is the reverse of Big O?
a) Big O b) Big Ω c) Big  d) Big α
26. Big O is used to describe
a) Lower bound b) Upper bound
c) Lower bound = Upper bound d) Centre bound
27. The complexity of an algorithm with lower bound = upper bound is
a) O(n) b) O(n2) c) O(log n) d) O(n log n)
28. Which of the following is said to be best case?
a) The first element in the list matches with the key element to be searched in a list
of elements
b) The middle element in the list matches with the key element to be searched in a
list of elements
c) The last element in the list matches with the key element to be searched in a list
of elements
d) The first element in the list matches with the key element to be sorted in a list of
elements
..135..
12 – Computer Science

29. Linear search is also called as


a) Continuous search b) Ordered search
c) Binary search d) Sequential search
30. Half – interval search algorithm is also called as
a) Linear search b) Binary search
c) Continuous search d) Ordered search
31. The algorithm finds the position of a search element within a sorted array is
a) Binary search b) Ordered search
c) Continuous search d) Linear search
32. The formula used to find index of middle element of the array in binary search is
a) mid = low + (high – low) / 2 b) mid = low - (high + low) / 2
c) mid = low + (high + low) / 2 d) mid = low - (high – low) / 2
33. The algorithm uses ‘Divide and Conquer’ technique is
a) Insertion sort b) Bubble sort
c) Linear search d) Binary search
34. The algorithm compares each pair of adjacent elements and swap them if they are in
unsorted order is
a) Insertion sort b) Bubble sort
c) Selection sort d) Merge sort
35. The algorithm which is simple, it is too slow and less efficient compared to other
sorting methods is
a) Insertion sort b) Bubble sort
c) Selection sort d) Merge sort
36. The algorithm finds the smallest elements in array and swap it with the element in
the first position of an array and so on… is called
a) Insertion sort b) Bubble sort
c) Selection sort d) Merge sort
37. The algorithm taking elements from the list one by one and inserting it in their correct
position into a new sorted list is
a) Insertion sort b) Bubble sort
c) Selection sort d) Merge sort

..136..
12 – Computer Science

38. The algorithm repeatedly selects the next-smallest element and swaps in into the
right place for every pass is called
a) Insertion sort b) Bubble sort c) Selection sort d) Merge sort
39. Which of the following is used whenever problems can be divided into similar sub-
problems?
a) Modular Programming b) Dynamic Programming
c) Memoization d) Sorting techniques
40. Dynamic algorithm uses
a) Divide and conquer b) Memoization c) Reusability d) All the these
41. An optimization technique used to speed up computer programs is
a) Divide and conquer b) Memoization c) Reusability d) All the these
42. Big  notation in asymptotic notation represents
a) Best case b) Average case c) Worst case d) NULL case
II. Additional Two and Three Marks:
1. What is an algorithmic solution?
An algorithm that yields expected output for a valid input is called an algorithmic
solution.
2. What is analysis if algorithm?
An estimation of the time and space complexities of an algorithm for varying input
sizes is called algorithm analysis.
3. What is algorithmic strategy?
A way of designing algorithm is called algorithmic strategy.
4. Explain the two different phases used for analysis of algorithms and performance
evaluation.
1. A Priori estimates:
This is a theoretical performance analysis of an algorithm. Efficiency of an
algorithm is measured by assuming the external factors.
2. A Posteriori testing:
This is called performance measurement. In this analysis, actual statistics like
running time and required for the algorithm executions are collected.
5. What is time complexity?
The Time complexity of an algorithm is given by the number of steps taken by the
algorithm to complete the process.
..137..
12 – Computer Science

6. What is space complexity?


Space complexity of an algorithm is the amount of memory required to run to its
completion.
7. What do you mean by best algorithm?
The best algorithm to solve a given problem is one that requires less space in
memory and takes less time to execute its instructions to generate output.
8. What is memoization?
Memoization is an optimization technique used primarily to speed up computer
programs by storing the results of expensive function calls and returning the cached
result when the same inputs occur again.
III. Additional Five Marks:
1. Differentiate between algorithm and program.
Algorithm Program
Algorithm helps to solve a given problem Program is an expression of algorithm in a
logically and it can be contrasted with the programming language.
program.
Algorithm can be categorized based on Algorithm can be implemented by
their implementation methods, design structured or object-oriented programming
techniques etc. approach.
There is no specific rules for algorithm Program should be written for the selected
writing but some guidelines should be language with specific syntax.
followed.
Algorithm resembles a pseudo code which Program is more specific to a programming
can be implemented in any language. language.

..138..
5. Python – Variables and Operators

I. Additional One Marks:


1. Which of the following is a general-purpose programming language?
a) C b) C++ c) Java d) Python
2. Python was created by
a) James Gosling b) Denis Ritchie
c) Bjarne Stroustrup d) Guido Van Rossum
3. National Research Institute for Mathematics and Computer Science is in
a) Philippines b) Saudi Arabia c) Netherland d) Australia
4. Python was released in the year
a) 1990 b) 1991 c) 1992 d) 1993
5. Python supports
a) Procedural Programming b) Object oriented Programming
c) Structured Programming d) Both a and b
6. Expand : IDLE
a) Integrated Device Learning Editor
b) Internal Development Loading Environment
c) Integrated Development Learning Environment
d) Internal Drive Loaded Environment
7. In how many ways python programs can be written?
a) 1 b) 2 c) 3 d) 4
8. Which of the following symbol indicates the prompt?
a) > b) >> c) >>> d) <<<
9. Which mode allows you to type Python code directly and displays the results
immediately?
a) Interactive Mode b) Script Mode
c) Alternative Mode d) Extended Mode
10. How many types of modes are there in Python editor?
a) 1 b) 2 c) 3 d) 4
11. The symbol indicates that Interpreter is ready to accept instructions is
a) # b) $ c) @ d) >>>
12. A text file containing the Python statements is
a) Script b) Notepad c) Word pad d) VI Editor

..139..
12 – Computer Science

13. Which of the following mode allows you to type Python codes and save it for later use?
a) Interactive Mode b) Script Mode
c) Alternative Mode d) Extended Mode
14. The menu used to open new script mode window is
a) File -> New b) File ->New -> File c) File -> New File d) New -> File
15. What is the output for the following code:
>>> 5 + 50 * 10
a) 550 b) 55 c) 505 d) 15
16. What is the output for the following code:
>>> x = 10
>>> y = 20
>>> z = x + y
>>> print(“The Sum is : “,z)
a) 30 b) the sum is 30
c) The Sum is 30 d) The Sum is : 30
17. The mode which allows you to execute the code again and again without typing is
a) Interactive Mode b) Alternative Mode
c) Script Mode d) Extended Mode
18. The shortcut key used to save Python code in Script mode is
a) Ctrl + Y b) Ctrl + S c) Ctrl + A d) Ctrl + Save
19. Python files are by default saved with extension
a) .pyth b) .python c) .pyt d) .py
20. To run the code in Python editor,
a) Run -> Run b) Run -> Module
c) Run -> Code d) Run -> Run Module
21. To run the code in Python editor press
a) F2 b) F5 c) F7 d) F10
22. If Python code has any error, it will be shown in
a) Blue Color b) Green Color c) Red Color d) Black Color
23. The function helps to enter data at run time by the user is
a) get() b) cin() c) getin() d) input()
24. The function used to display result on the screen is
a) display() b) print() c) cout() d) printf()
..140..
12 – Computer Science

25. Which of the following is the correct syntax for print statement?
a) print(“String to be displayed as output”)
b) print(variable)
c) print(“String to be displayed as output”,variable)
d) All the above
26. Which of the following symbol is used as a separator in print() to print more than one
item?
a) “ b) % c) , d) –
27. Which of the following takes data from the keyboard and stores the entered data in
the variable?
a) get() b) input() c) accept() d) store()
28. What is the use of the following statement? City = input()
a) Waits for the prompt b) Get input from the user
c) Assigns default value d) Error
29. The input() accepts all data as
a) Numbers b) Floating Point
c) Strings or Characters d) None of these
30. The function used to convert string data as integer explicitly is
a) init() b) integer() c) char() d) int()
31. Which of the following code is used to get input for the integer variables x and y?
a) x = int(“Enter X : “)
y = int(“Enter Y : “)
b) x = input(“Enter X : “)
y = input(“Enter Y : “)
c) x, y = int(input(“Enter X : “)), int(input(“Enter Y :”))
d) All the above
32. In Python, comments begin with
a) # b) // c) / d) ?
33. Which of the following statements are ignored by the Python interpreter?
a) input b) print c) executable d) comments
34. In Python which of the following is used to indicate blocks of codes for class, function
or body of the loops and block of selection command?
a) Spaces b) Tabs c) Both a and b d) Empty Line
..141..
12 – Computer Science

35. The number of whitespaces in the indentation is


a) Fixed b) Not fixed c) 10 d) 15
36. Python breaks each logical line into a sequence of elementary lexical components
known as
a) Comments b) Indentation
c) Tokens d) Escape Sequences
37. How many types of tokens are there?
a) 4 b) 5 c) 6 d) 7
38. A name used to identify a variable, function, class, module or object is
a) Identifiers b) Keywords c) Operators d) Literals
39. Which of the following is incorrect?
I) An identifier must start with an alphabet, underscore or digits.
II) Identifiers must be a Python keyword.
III) Python allow punctuation characters.
a) I Only b) II Only
c) III Only d) All are wrong
40. Select the valid identifiers from the following.
a) Sum b) 12Name c) name$ d) total-marks
41. Select the invalid identifiers from the following.
a) Sum b) total_marks c) num1 d) continue
42. The special words used by Python interpreter to recognize the structure of program is?
a) Identifiers b) Keywords c) Operators d) Literals
43. Why keywords cannot be used for any other purpose?
a) These words have specific meaning for interpreter.
b) These words are used for special purpose.
c) These words are reserved words.
d) All the above.
44. Which of the following is not a Python keyword?
a) pass b) del c) yield d) passed
45. The value of an operator used is called
a) Operators b) Operands c) Symbols d) Literal
46. Value and variables when used with operator are known as
a) Operators b) Operands c) Symbols d) Literal
..142..
12 – Computer Science

47. Which of the following are the special symbols which represent computations,
conditional matching etc.?
a) Operators b) Operands c) Symbols d) Literal
48. Which of the following operator is used to find the power of value?
a) ^ b) @ c) * d) **
49. What is the output of the following code?
a =100
b=10
c =a/b
print(c)
a) 10 b) 10.0 c) 10.5 d) 3
50. What is the output of the following code?
a=100
b=30
c=a//b
print(c)
a) 10 b) 10.0 c) 10.5 d) 3
51. Relational operator is also called as
a) Conditional operator b) Comparative operator
c) Assignment operator d) Logical operator
52. Which of the following operator checks the relationship between two operands?
a) Conditional operator b) Comparative operator
c) Assignment operator d) Logical operator
53. Which of the following operator is used to perform operations on the relational
operations?
a) Arithmetic operator b) Comparative operator
c) Assignment operator d) Logical operator
54. How many types of logical operators are there?
a) 1 b) 2 c) 3 d) 4
55. In Python, a simple assignment operator to assign values to variable is
a) == b) = c) != d) equal to
56. The operator used to perform floor division on operators is
a) == b) ** c) // d) /
..143..
12 – Computer Science

57. What is the output for the following code?


>>> a=97
>>> b=35
>>> a>b or a==b
a) True b) False c) 0 d) 1
58. What is the output for the following code?
>>> a=97
>>> b=35
>>> not (a>b and a==b)
a) True b) False c) 0 d) 1
59. Ternary operator is also called as
a) Conditional operator b) Comparative operator
c) Assignment operator d) Logical operator
60. What is the output for the following code?
a, b = 30, 20
min = a if a < b else b
print(min)
a) 20 b) 30 c) True d) False
61. Python uses the symbols and symbol combinations as
a) Literals b) Identifiers c) Delimiters d) Punctuators
62. Which of the following is used as symbols and symbol combinations in expressions,
lists, dictionaries and strings?
a) Delimiters b) Identifiers c) Literals d) Punctuators
63. A raw data given in a variable or constant is
a) Delimiters b) Identifiers c) Literals d) Punctuators
64. Which of the following is not a type of literals?
a) Numeric b) Strings c) Character d) Boolean
65. Octal literals are preceded with
a) 0x b) 0o c) 0h d) 0i
66. What is the output for the following code?
x = 1 + 3.14j
print(x.imag)
a) 1+3.14j b) 1 c) 3.14 d) 3.14j
..144..

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy