12CS em 3
12CS em 3
12CS em 3
..95..
12 – Computer Science
..96..
12 – Computer Science
..97..
12 – Computer Science
..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
..100..
` 15 DATA MANIPULATION THROUGH SQL
..101..
12 – Computer Science
..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
..105..
12 – Computer Science
2. Write the Python script to display all the records of the following table using
fetchmany()
Icode ItemName Rate
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
Rate :- Integer
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
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
..109..
12 – Computer Science
6. Observe the output figure. Identify the coding for obtaining this output.
..110..
12 – Computer Science
..111..
12 – Computer Science
..112..
12 – Computer Science
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
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()
➢ 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
3 Scoping 129
..118..
1. Functions
..119..
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
..124..
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
..127..
12 – Computer Science
..128..
3. Scoping
..129..
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
..132..
4. Algorithmic Strategies
..133..
12 – Computer Science
..134..
12 – Computer Science
..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
..138..
5. Python – Variables and Operators
..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
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