12 Cs Full Study Materials 2022-23
12 Cs Full Study Materials 2022-23
12 Cs Full Study Materials 2022-23
MATERIALS FOR
XII- COMPUTER SCIENCE
NAME : .....................................................................................................................................
2
Section-B
5. Which of the following is a normal function definition and which is recursive function definition
i) let sum x y :
return x + y
g
i.Or
Ans: Normal Function
la
ii) let disp :
a dasa
print „welcome‟www
.P
Ans: Normal Function
rgrg
ia.O
iii) let rec sum num: a l
a al i.O
as s
if (num!=0) then return adad+a sum (num-1)
.P.num
P
wwww
else ww
return num
Ans: Recursive Function
3
Section-C
Answer the following questions (3 Marks)
Here, the result of inc() will change every time if the value of „y‟ get changed inside the function
definition.
Hence, the side effect of inc () function is changing the data of the external variable „y‟.
4. Differentiate pure and impure function.
Pure functions will give exact result Impure functions never assure .O Ogrg
ryou
l alia i.
when the same arguments are passed. adsaasathe same
that the function willabehave
d
a
ww.P.P
every time it‟s
ww wcalled.
w
Pure function does not cause any side Impure function causes side effects to
4
effects to its output. its output.
The return value of the pure functions The return value of the impure
solely depends on its arguments functions does not solely depend on
passed. l a i.Org its arguments passed.
d asa
w .Pa
wwnot modify the arguments
They do They may modify the arguments
which are passed to them. which are passed.
Section - D
Answer the following questions: (5 Marks)
1. What are called Parameters and write a note on
(i) Parameter without Type (ii) Parameter with Type
Answer:
Parameters are the variables in a function definition
Arguments are the values which are passed to a function definition.
Two types of parameter passing are,
1. Parameter Without
. Type
2. Parameter With Type
5
1. Parameter Without Type:
Lets see an example of a function definition of Parameter Without Type:
(requires: b>=0 )
(returns: a to the power of b) .Or g
l ai
let rec pow a b:= da sa
a
w.P
if b=0 then 1 ww
else a * pow a (b-1)
l a i.Org
a
dasthe value passed to the
In the above function definition variable „ b‟ is the parameter aand
P
variable „b‟ is the argument. w.
ww
The precondition (requires) and postcondition (returns) of the function is given.
We have not mentioned any types: (data types). This is called parameter without type.
In the above function definition the expression has type „int‟, so the function's return type also be
„int‟ by implicit.
2. Parameter With Type:
Now let us write the same function definition with types,
In this example we have explicitly annotating the types of argument and return type as „int‟.
Here, when we write the type annotations for „a‟ and „b‟ the parantheses are mandatory.
This is the way passing parameter with type which helps the compiler to easily infer them.
2. Identify in the following program
let rec gcd a b :=
if b <> 0 then gcd b (a mod b) else return a
i) Name of the function
6
ii) Identify the statement which tells it is a recursive function
let rec gcd a b :=
“rec” keyword tells the compiler it is a recursive function
iii) Name of the argument variable
„a‟ and „b‟
iv) Statement which invoke the function recursively
gcd b l(ai.modrg
O b)
a a
s the recursion
ada
v) Statement whichPterminates
w.
ww return a
rg g
3. Explain with example Pure and impure
i.Or functions.
i.O
aslaala
asa
adad
.P.P
wwww
ww
Pure functions will give exact result Impure functions never assure you
when the same arguments are passed. that the function will behave the same
every time it‟s called.
Pure function does not cause any side Impure function causes side effects to
effects to its output. its output.
The return value of the pure functions The return value of the impure
solely depends on its arguments functions does not solely depend on
passed. its arguments passed.
They do not modify the arguments They may modify the arguments
which are passed to them which are passed.
If we call pure functions with same set If we call impure functions with same
of arguments, we will always get the set of arguments, we might get the
same return values. different return values.
l a i.Org
da sa
w .Pa
w w
The person who drives the car doesn't care about the internal working.
To increase the speed of the car he just presses the accelerator to get the desired behaviour.
8
Here the accelerator is the interface between the driver (the calling / invoking object) and the engine
(the called object).
In this case, the function call would be Speed (70): This is the interface.
Internally, the engine of the car is doing all the things.
It's where fuel, air, pressure,la
andi .O . rgrg
O
electricity come together i .O . rtogrcreate
O g the power to move the vehicle.
a a la i a l
a al a i
All of these actionsPare a s
da s a s s
a just wants to go faster.
adaseparated
. .P adadwho
from the driver,
.P.P
Thus we separate
w w
wwinterface from implementation.www w
ww ww
2. DATA ABSTRACTION
Section – A
Choose the best answer (1 Mark)
1. Which of the following functions that build the abstract data type ?
(A) Constructors (B) Destructors (C) recursive (D)Nested
2. Which of the following functions that retrieve information from the data type?
(A) Constructors (B) Selectors (C) recursive (D)Nested
3. The data structure which is a mutable ordered sequence of elements is called
(A) Built in (B) List (C) Tuple (D) Derived data
4. A sequence of immutable objects is called
(A) Built in (B) List (C) Tuple (D) Derived data
5. The data type whose representation is known are called
(A) Built in datatype (B) Derived datatype
(C) Concrete datatype (D) Abstract datatype
6. The data type whose representation is unknown are called
(A) Built in datatype (B) Derived datatype
(C) Concrete datatype (D) Abstract datatype
7. Which of the following is a compound structure?
(A) Pair (B) Triplet (C) single (D) quadrat
10
Section-B
Constructors are functions that build the Selectors are functions that retrieve
abstract data type. information from the data type.
4. What are the different ways to access the elements of a list. Give example.
The elements of a list can be accessed in two ways.
1. Multiple Assignment:
Which unpacks a list into its elements and binds each element to a different name.
Example:
lst := [10, 20]
x, y := lst
x will become10 and y will become 20.
12
2. Element Selection Operator:
It is expressed using square brackets.
Unlike a list literal, a square-brackets expression directly following another expression does not
evaluate to a list value, but instead selects an element from the value of the preceding
expression.
Example:
lst[0]
10
lst[1]
20
5. Identify Which of the following are List, Tuple and class ?
Section - D
Answer the following questions: (5 Marks)
1. How will you facilitate data abstraction.
i . O . rgrg
O Explain it with suitable example.
l ala i
a aadsaasa by defining an abstract data type (ADT), which is a collection of
Data abstraction is dsupported
w.P.selectors.
constructorsww
and P
ww w
To facilitate data abstraction, you will need to create two types of functions:
Constructors
Selectors
a) Constructor:
Constructors are functions that rgrbuild
g the abstract data type.
rgrg
s alaalia.O
i.O
s a l
a alia.O
i.O
s
daadahave adas
For example,ww
sayayou
.P.P an abstract data
. P. adatype
P called city.
ww ww
ww
ww ww 13
g
This city object will hold the city‟s name, and its latitude and longitude.
To create a city object, you‟d use a function like city = makecity (name, lat, lon).
Here makecity (name, lat, lon) is the constructor which creates the object city.
g
i.O rg
s a l a
a da
ww.P
w
g
i.O rg
da sala
a
ww.P
w
g
b) Selectors:
Selectors are functions that retrieve information from the data type.
g Selectors extract individual i. O. rgrg of information from the object.
pieces
O
l al a i
a d
a adsaasa of a city object, you would use functions like
To extract the information
ww .P.P
wgetname(city)
ww
w
getlat(city)
g
getlon(city)
These are the selectors because these functions extract the information of the city object.
g
2. What is a List? Why List can be called as Pairs. Explain with suitable example.
LIST:
g List is constructed by placing expressions within square brackets separated by commas.
Such an expression is called a list literal.
List can store multiple values.
g
i . O . rgrg
O i. O . rgrg
O i . Org
a i a i a
adsaEach
l a
asa value can be of any l a l
adsaastype
a and can even be aanother
sa list.
l l
a d
a a d
a a d
.P.P The elements of
ww .aP.list
ww P can be accessed inwtwo .P ways.
ww
ww ww
ww ww
1. Multiple Assignment:
Which unpacks a list into its elements and binds each element to a different name.
14
Example:
lst := [10, 20]
x, y := lst
15
The new data type Person is pictorially represented as,
i .O . rgrg
O i .Or g
l al a i l a
a d
a adsaasa ada
sa
.P.P
ww w.P
ww
ww ww
i .O . rgrg
O i . O. Orgrg i . O. Orgrg
l al a i l al a i l al a i
a daadsaasa ad aadsaasa ad aadsaasa
.P.P
ww .P.P
ww .P.P
ww
ww
ww ww
ww ww
ww
i .O . rgrg
O i .O . rgrg
O i .O . rgrg
O
l al a i l al a i l al a i
a daadsaasa a daadsaasa a daadsaasa
.P.P
ww .P.P
ww .P.P
ww
ww
ww ww
ww ww
ww
i .O . rgrg
O i .O . rgrg
O i .O . rgrg
O
aal al a i aal al a i aal al a i
P a daadsas P a daadsas P a daadsas
. .P
ww . .P
ww . .P
ww
ww
ww ww
ww ww
ww
The class (structure) construct defines the form for multi-part objects that represent a person.
Person is referred to as a class or a type, while p1 is referred to as an object or an instance.
rg g rg g
Using class you can create .Oi.Or objects of that type.
many
lalia i.Or
lalia.O
a d
a adsaasa adaadsaasa
Class defineswaw
.P
data .P.P related data items.
P abstraction by grouping
wwww . ww
ww
ww
A class as bundled data and the functions that work on that data that is using class we can access
multi-part items.
3.SCOPING
Section – A
Choose the best answer (1 Mark)
1. Which of the following refers to the visibility of variables in one part of a program to another part of
the same program.
(A) Scope (B) Memory (C) Address (D) Accessibility
2. The process of binding a variable name with an object is called
(A) Scope (B) Mapping (C) late binding (D) early binding
3. Which of the following is used in programming languages to map the variable and object?
(A) :: (B) := (C) = (D) ==
4. Containers for mapping names of variables to objects is called
(A) Scope (B) Mapping (C) Binding (D) Namespaces
5. Which scope refers to variables defined in current function? i .O . rgrg
O
l al a i
a daadsaasa
(A) Local Scope (B) Global scope (C) Module scope
ww.P.P (D) Function Scope
wwww
6. The process of subdividing a computer program into separate sub-programs is called
i .O . rgrg
O
(A) Procedural Programming (B) Modular programming aal al a i
P a daadsas
(C)Event Driven Programming . .PProgramming
(D) Object oriented
ww
wwww
7. Which of the following security technique that regulates who can use resources in a computing
environment?
(A) Password (B)Authentication (C) Access control (D) Certification
8. Which of the following members of a class can be handled only from within the class?
(A) Public members (B)Protected members (C) Secured members (D) Private members
9. Which members are accessible from outside the class?
(A) Public members (B)Protected members (C) Secured members (D) Private members
10. The members that are accessible from within the class and are also available to its sub-classes is
called
(A) Public members (B)Protected members (C) Secured members (D) Private members
17
Section-B
Answer the following questions (2 Marks)
1. What is a scope?
.O rg
laivariables,
Scope refers to the visibilityaof parameters and functions in one part of a program to
P a das
another part of w .
thewsame program.
w
2. Why scope should be used for variable. State the reason.
The scope should be used for variables because; it limits a variable's scope to a single definition.
That is the variables are visible only to that part of the code.
Example:
i .O . rgrg
O i . O . rgrg
O
l al a i l al a i
a d
aadsaasa a d
a adsaasa
.P.P
ww .P.P
ww
ww
ww ww
ww
3. What is Mapping?
Namespaces are containers for mapping names of variables to objects (name : = object).
Example: a:=5
On execution of the above code the variable a which is defined inside the function displays the
value 7 for the function call Disp() and then it displays 10, because a is defined in global scope.
Access control is a security technique that regulates who or what can view or use resources in a
computing environment.
It is a fundamental concept ini.O . rgrg that minimizesi.risk
security
O O . rgrtog the object.
O
l a a i l a a i
In other words access d saasal is a selective restriction
acontrol
d d
l
adsaasa of access to data.
a
.P.P a a
.P.P a
In OOPS Access
wwww control is implemented wwwthrough
w access modifiers.
ww ww
5. Identify the scope of the variables in the following pseudo code and write its output.
color:= Red
mycolor():
b:=Blue
myfavcolor():
g:=Green
print color, b, g
myfavcolor()
print color, b
mycolor()
print color
OUTPUT:
Red Blue Green
Red Blue
Red
Scope of Variables:
Variables lalia.O . rgrg Scope
O i .O . rgrg
O
i l al a i
a d
Color:=Red
a adsaasa Global
a d
a adsaasa
ww.P.P .P.P
ww
w w
b:=Blue
ww ww
ww Enclosed
G:=Green Local
20
Section - D
Answer the following questions: (5 Marks)
1. Explain the types of scopes for variable or LEGB rule with example.
SCOPE:
Scope refers to the visibility of variables, parameters and functions in one part of a program to
another part of the same program. g
i.O r
TYPES OF VARIABLE SCOPE:
sala a
Local Scope .Pad
ww
EnclosedwScope
Global Scope O rg
l a i.
Built-in Scope asa ad
LEGB RULE: ww.P
w
The LEGB rule is used to decide the order in which the scopes are to be searched for scope
resolution.
The scopes are listed below in terms of hierarchy (highest to lowest).
g
i.O . rgrg
O i .O . rgrg
O
l al a i lal a i
a d
a adsaasa adaadsaasa
.P.P
ww .P.P
ww
ww
ww ww
ww
g
g
i .O. rgrg
O
l
aa al a i
P adaadsas
. .P
ww
ww
ww 21
g
On execution of the above code the variable a displays the value 7, because it is defined and
available in the local scope.
ii) ENCLOSED SCOPE:
A variable which is declared inside a function which contains another function definition with in
it, the inner function can also access the variable of the outer function. This scope is called
enclosed scope.
When a compiler or interpreter searches for a variable in a program, it first search Local, and then
search Enclosing scopes.
i . O . rgrg
O
a i
d adsaaslala
a
.P.Pa
w ww
w
ww
i . O . rgrg
O
l al a i
a d
a adsaasa
ww.P.P
w w w
w within Disp(). The variable „a‟ defined in Disp() can be
In the above example Disp1() is defined
even used by Disp1() because it is also a member of Disp().
iii) GLOBAL SCOPE:
A variable which is declared outside of all the functions in a program is known as global variable.
Global variable can be accessed inside or outside of all the functions in a program.
Example:
i . O. rgrg
O i . O rg
a i a
d a
d saaslala d a sal
a
.P.Pa a
w ww
w w w.P
ww w
On execution of the above code the variable a which is defined inside the function displays the
value 7 for the function call Disp() and then it displays 10, because a is defined in global scope.
iv) BUILT-IN-SCOPE:
The built-in scope has all the names that are pre-loaded into the program scope when we start the
compiler or interpreter.
Any variable or module which is defined in the library functions of a programming language has
Built-in or module scope.
22
g
i . O . rgrg
O
l al a i
a d
a adsaasa
.P.P
ww
ww
ww
g
i .O . rgrg
O
l al a i
a d
a adsaasa
.P.P
ww
ww
ww
g
2. Write any Five Characteristics of Modules.
The following are the desirable characteristics of a module.
g 1. Modules
.OO grg instructions, processing logic, and data.
rcontain
a s
a aslaaliai.
a2.dadModules can be separately compiled and stored in a library.
.P.P
wwww
ww 3. Modules can be included in a program.
g
4. Module segments can be used by invoking a name and some parameters.
5. Module segments can be used by other modules.
23
g
g
4. ALGORITHMIC STRATEGIES
Section – A
Choose the best answer (1 Mark)
1. The word comes from the name of a Persian mathematician Abu Ja‟far Mohammed ibn-i Musa al
Khowarizmi is called?
(A) Flowchart (B) Flow (C) Algorithm (D) Syntax
2. From the following sorting algorithms which algorithm needs the minimum number of swaps?
(A) Bubble sort (B) Quick sort (C) Merge sort (D) Selection sort
3. Two main measures for the efficiency of an algorithm are
(A) Processor and memory (B) Complexity and capacity
(C) Time and space (D) Data and space
4. The algorithm that yields expected output for a valid input is called as
(A) Algorithmic solution (B) Algorithmic outcomes
(C) Algorithmic problems gg
.O r r coding
(D) Algorithmic
l alia i . O
5. Which of the following is used to describe the d adsaacase
worst
a a
sa of an algorithm?
.PP
ww.
wwww
(A) Big A (B) Big S (C) Big W (D) Big O
.O rgrg
O Org
6. Big is the reverse of l
aaalia i. l a i.
adaadsas a dasa
(A) Big O ww P
. .P (B) Big θ w.P (C) Big A (D) Big S
ww ww ww
7. Binary search is also called as
(A) Linear search (B) sequential g search (C) Random search (D) Half-internal search
O
. i. r
O r g . Org
8. The Θ notation in asymptotic
aala li
evaluation
a represents l a i
a
P adaadsas a das
(A) Base caseww
w . . P . P
(B) Average caseww(C) Worst case (D) NULL case
ww w w
9. If a problem can be broken into subproblems which are reused several times, the problem possesses
which property?
(A) Overlapping subproblems (B) Optimal substructure
(C) Memoization (D) Greedy
10. In dynamic programming, the technique of storing the previously calculated values is called ?
(A) Saving value property (B) Storing value property
(C) Memoization (D) Mapping
g
24
Section-B
3. What are the factors that influence time and space complexity.
The two main factors, which decide the efficiency of an algorithm are,
Time Factor -Time is measured by counting the number of key operations like comparisons in the
sorting algorithm.
Space Factor - Space is measured by the maximum memory space required by the algorithm.
l a i .Org
4. Write
asa a note on Asymptotic notation.
a d
w .P
ww Asymptotic Notations are languages that use meaningful statements about time and space
complexity.
g
The following three asymptotic notations are mostly used to represent time complexity of
algorithms:
(i) Big O
g
Big O is often used to describe the worst-case of an algorithm.
(ii) Big Ω
g Big Omega is the reverse Big rg
OO.
s alai.
Example: If Big a a used to describe the upper bound (worst - case) then, Big Ω is used to
Odis
w .P
wwlower bound (best-case).
describe the
g (iii) Big Θ
When an algorithm has a complexity with lower bound = upper bound, that algorithm has a
complexity O (n log n) and Ω (n log n), it‟s actually has the complexity Θ (n log n).
g
Time complexity is n log n in both best-case and worst-case.
26
g
5. What do you understand by Dynamic i . O . rgrg programming?
O
l al a i
Dynamic programming
a d
a adsaasisa used when the solution to a problem can be viewed as the result of a
w.P.P
sequence ofwdecisions.
wwww
Dynamic programming approach is similar to divide and conquer (i.e) the problem can be
i .O . Orgrg
divided into smaller sub-problems.
l al a i
dadsaasa can be re-used to complete the process.
Results of the sub-problems
a a
ww.P.P
w w
Dynamic programming approaches are used to find the solution in optimized way.
w w
Section - D
Answer the following questions: (5 Marks)
1. Explain the characteristics of an algorithm.
g
ia.O r rg
.O
a l
aal i
P adaadsas
Characteristics ..
ww P Meaning
wwww
Input Zero or more quantities to be supplied.
Output At least one quantity is produced.
Finiteness Algorithms must terminate after finite number of steps.
Definiteness All operations should be well defined.
Effectiveness Every instruction must be carried out effectively.
Correctness The algorithms should be error free.
Simplicity Easy to implement.
Algorithm should be clear and unambiguous. Each of its steps should be clear
Unambiguous
and must lead to only one meaning.
Feasibility Should be feasible grgwith the available resources.
. O. r
O
Portable a s
a aslaaliaishould
An algorithm be generic, independent and able to handle all range of
d d
inputs.
a
ww .P.Pa
wwww
An algorithm should have step-by-step directions, which should be independent
Independent
of any programming
i . O. rgrg code.
O
lal a i
adaadsaasa
2. Discuss aboutww
.P.Psearch algorithm.
ww
Linear
ww
LINEAR SEARCH:
Linear search also called sequential search is a sequential method for finding a particular value in a
list.
This method checks the search element with each element in sequence until the desired element is
found or the list is exhausted.
In this searching algorithm, list need not be ordered.
27
g
Pseudo code:
1. Traverse the array using for loop
2. In every iteration, compare the target search key value with the current value of the list.
gg
.O r r current index and value of the array
If the values match, display
lalia i. O
the
d saasa
admatch,
If the values do a
.P.Pnot
a move on to the next array element. If no match is found, display the
wwww
search element not found.
ww
3. If no match is found, display the search element not found.
Example:
To search the number 25 in the array given below, linear search will go step by step in a
sequential order starting from the first element in the given array.
if the search element is found that index is returned otherwise the search is continued till the last
index of the array.
In this example number 25 is found at index number 3.
i . O . rgrg
O
index 0 1 l al a i
a d
a adsaas2a 3 4
values 10 .P.P 20
12
ww 25 30
ww
ww
Snippet:
Input: values[]={10,12,20,25,30}
Target=25
Output:
3
28
2. When a match is found, display success message with the index of the element matched.
The array is being sorted in the given example and it is suitable to do the binary search
algorithm.
Let us assume that the search element is 60 and we need to search the location or index of
search element 60 using binary search.
Element not found because the value in index 7 is greater than search value . ( 80 > 60)
g So, the search element must be in the lower part from the current mid value location
Now we change our search range low to mid - 1 and find the new mid value as index 5
g
i.O. rgrg
O
l
aa ala i
P a daadsas
. .P
ww
ww
ww 29
g
Now we compare the value stored at location 5 with our search element.
We found that it is a match.
It compares each pair of adjacent elements and swaps them if they are in the unsorted order.
This comparison and passed to be continued until no swaps are needed, which shows the values
in an array is sorted.
It is named so becase, the smaller elements "bubble" to the top of the list.
It is too slow and less efficient when compared to other sorting methods.
Pseudo code
1. Start with the first element i.e., index = 0, compare the current element with the next element of the
array.
2. If the current element is greater than the next element of the array, swap them.
If the current element is less than the next or right side of the element, move to the next element.
Go to Step 1 and repeat until end of the index is reached.
Example:
Consider an array with values {15, 11, 16, 12, 14, 13}
Below, we have a pictorial representation of how bubble sort.
i . O .Orgrg
l al a i
a d
a adsaasa
.P.P
ww
ww
ww
i .O . Orgrg
l ala i
adaadsaasa
.P.P
ww
ww
ww
30
The above pictorial example i . Ois
. rgfor
O rg iteration-1.
l a a i
Similarly, remaining d saasal can be done.
aditeration
a a
.P.Pwill give the sorted array.
The final iteration
wwww
w w
At the end of all the iterations we will get the sorted values in an array as given below:
i .O . rgrg
O
l al a i
a d
a adsaasa
ww.P.P
wwww
5. Explain the concept of Dynamic programming with suitable example.
Dynamic programming is used when the solution to a problem can be viewed as the result of a
sequence of decisions.
Dynamic programming approach is similar to divide and conquer (i.e) the problem can be
divided into smaller sub-problems.
. O rgrg
O . O rgrg
O
Results of the sub-problems a i
aslala i .
can be re-used to i
complete .
aslala the process.
a i
a s
a a sa
Dynamic programming adad approaches are used
.P.P adatod find the solution in optimized way.
.P.P
w w
ww programming ww www w
ww
Steps to do Dynamic
The given problem will be divided into smaller overlapping sub-problems.
An optimum solution for the given problem can be achieved by using result of smaller sub-
problem.
Dynamic algorithms uses Memoization.
i .O . rgrg
O
l al a i
a d
a adsaasawith Dynamic Programming Approach
Fibonacci Iterative Algorithm
ww.P.P
wwww
The following example shows a simple Dynamic programming approach for the generation of
Fibonacci series.
Initialize f0=0, f1 =1
step-1: Print the initial values of Fibonacci f0 and f1
i.O rgrg
step-2: Calculate fibanocci i.O
salaalafib ← f0 + f1
daadas
P
.f0←a
P
step-3: Assign
ww ww . f1, f1← fib
ww
step-4: Print the next consecutive rgrgvalue of fibanocci fib
i . O
. O
laalai until the specified number of terms generated laalia.
step-5: Goto step-2dand s a
srepeat s a
s
.wP.Pa aada adaada
.wP.P
For example w ww
wwif we generate fibonacci series upto 10 digits, the algorithm will generate w
the series
ww ww
as shown below:
The Fibonacci series is : 0 1 1 2 3 5 8 13 21 34 55
31
5. PYTHON - VARIABLES AND OPERATORS
Section – A
Choose the best answer (1 Mark)
In Python, programs can be written in two ways namely Interactive mode and Script mode.
Interactive mode allows us to write codes in Python command prompt ( >>> ).
Script mode is used to create and edit python source file with the extension .py
32
2. Write short notes on Tokens.
Python breaks each logical line into a sequence of elementary lexical components known as
Tokens.
The normal token types are ,
1) Identifiers,
2) Keywords,
3) Operators,
4) Delimiters and
5) Literals.
3. What are the different operators that can be used in Python ?
l ai .Org
It simply allows testing a condition in a single
sa
da replacing the multiline if-else making the code
Paline
w.
compact. ww
Syntax:
Example :
34
It is used in representing certain whitespace characters.i.Org
da sala
Python supports the following escape sequence a
w w.P characters.
w
l a i .Org
a d asa
w.P
ww
35
Once the Python Scripts is created, they are reusable , it can be executed again and again without
retyping.
The Scripts are editable.
(i) Creating Scripts in Python
ia.O rgrg
.O ia.O rgrg
.O
1. Choose File → New File orapressl al i Ctrl + N in Pythonalshell
al i window.
a s s a a s sa
2. An untitled blank script
.P.P da editor will be displayed
adatext adada on screen.
.P.P
www w w
ww w
3. Type the codewin
w Script editor as givenwbelow,w
i .O . rgrg
O
aal al a i
P a daadsas
ww. .P
ww
ww
i. O . rgrg
O
a i
d adsaaslala
a
.P.Pa
w ww
w
ww
(ii) Saving Python Script
(1) Choose File → Save or Press Ctrl + S
(2) Now, Save As dialog box appears on the screen.
(3) In the Save As dialog box
Select the location to save your Python code.
Type the file name in File Name box.
Python files are by default saved with extension .py.
So, while creating scripts using Python Script editor, no need to specify the file extension.
(4) Finally, click Save button to save your Python script.
(iii) Executing Python Script
(1) Choose Run → Run Module or Press F5
(2) If your code has any error, it will be shown in red color in the IDLE window, and Python describes
the type of error occurred.
To correct the errors, go back to Script editor, make corrections, save the file and execute it
again.
(3) For all error free code, the output will appear in the IDLE window of Python as shown in Figure.
i .O . rgrg
O
l al a i
a d
aadsaasa
.P.P
ww
ww
ww
36
2. Explain input() and print() functions with examples.
Input and Output Functions
A program needs to interact with the user to accomplish the desired task; this can be achieved using
Input-Output functions.
The input() function helps to enter data at run time by the user
The output function print() is used to display the result of the program on the screen after
execution.
1) print() function
In Python, the print() function is used to display result on the screen.
Syntax for print():
Example:
i .O . rgrg
O
a i
dadsaaslala
a
.P.Pa the expression before printing it on the monitor.
The printw(w)w
wevaluates
w
w
The print () displays an entire statement which is specified within print ( ).
Comma ( , ) is used as a separator in print ( ) to print more than one item.
2) input() function
In Python, input( ) function is used to accept data as input at run time.
The syntax for input() function is,
“Prompt string” in the syntax is a message to the user, to know what input can be given.
37
If a prompt string is used, iti.O
is Ogrg
rdisplayed on the monitor; . O rgrthe
O g user can provide.expected
O rgrg data from
O
la ai . l a ia i . l a ia i .
the input device. da dsaasal dadsaasa
l
dadsaasa
l
a a a
.PP
.P.Ptyped data from thewkeyboard a a
.P.P a
The input(
ww
w
w) w w
takes wwwww. and storeswinwthe ww
ww given variable.
If prompt string is not given in input( ), the user will notgknow what is to be typed as input.
i .O . r rg
O
Example: l al a i
sa as
. P.Padaada
wwww
ww
In Example 1 input() using prompt string takes proper input and produce relevant output.
In Example 2 input() without using prompt string takes irrelevant input and produce unexpected
output.
So, to make your program more interactive, provide prompt string with input( ).
Input() using Numerical values:
The input ( ) accepts all O
l ali
a . data
i . rgrgas string or characters but not as numbers.
O
The int( ) function
a d
a adsaisasaused to convert string data as integer data explicitly.
Example: ww.P.P
ww
ww
i .O . rgrg
O
aal al a i
P a daadsas
ww . .P
wwww
i . O . rgrg
O
a i
d adsaaslala
a
.P.Pa
ww
3. Discuss in detail about Tokens in Python.
ww
ww
Tokens
Python breaks each logical line into a sequence of elementary lexical components known as
Tokens.
The normal token types are,
1) Identifiers,
2) Keywords,
3) Operators,
4) Delimiters and
5) Literals.
38
Whitespace separation is necessary between tokens, identifiers or keywords.
1) Identifiers
An Identifier is a name used to identify a variable, function, class, module or object.
An identifier must start with an alphabet (A..Z or a..z) or underscore ( _ ).
Identifiers may contain digits (0 .. 9)
Python identifiers are case sensitive i.e. uppercase and lowercase letters are distinct.
Identifiers must not be a python keyword.
Python does not allow punctuation g
.Orcharacter such as %,$, @ etc., within identifiers.
a l a i
Example of valid identifiers: s Sum, total_marks, regno, num1
. P ada
Example of invalid w
ww identifiers: 12Name, name$, total-mark, continue
2) Keywords
Keywords are special words used by Python interpreter to recognize the structure of program.
Keywords have specific meaning for interpreter, they cannot be used for any other purpose.
Python Keywords: false, class, If, elif, else, pass, break etc.
3) Operators i . O . rgrg
O i . O. rgrg
O i . O . rgrg
O
la
al a i l al a i l a a i
Operators are special d adsaassymbols d adsaasa computations,
which represent d saasal
adconditional matching in
. P a
P a . PPa a . PPa a
programming. wwww. wwww. wwww.
ww ww ww
Operators are categorized as Arithmetic, Relational, Logical, Assignment and Conditional.
ia.O .O rgrg
Value and variables whenaused l al iwith operator are known as operands.
d adsasa
Example: .P.Paa
wwww
ww
a=100
b=10
l a i .Org
print ("The Sum a
P a das = ",a+b)
w. a > b = ",a>b)
printw("The
w
print ("The a > b or a == b = ",a>b or a==b)
a+=10
print(“The a+=10 is =”, a)
Output:
The Sum = 110
The a>b = True
The a > b or a == b = True
The a+=10 is= 110
4) Delimiters
Python uses the symbols and symbol combinations as delimiters in expressions, lists, dictionaries
and strings.
Following are the delimiters.
39
i . O . rgrg
O
l ala i
adaadsaasa
ww.P.P
ww ww
5) Literals i .O . rgrg
O
l al a i
a d
a adsaasa
Literal is a raw data given in a variable or constant.
ww.P.P
In Python, there are various types of w ww
literals.
w They are,
1) Numeric Literals consists of digits and are immutable
2) String literal is a sequence of characters surrounded by quotes.
3) Boolean literal can have any of the two values: True or False.
6. CONTROL STRUCTURES
Section – A
Choose the best answer (1 Mark)
1. How many important control structures are there in Python?
A) 3 B) 4 C) 5 D) 6
2. elif can be considered to be abbreviation of
A) nested if B) if..else C) else if D) if..elif
3. What plays a vital role in Python programming?
A) Statements B) Control D) Indentation
4. Which statement is generally used as a placeholder?
A) continue B) break C) pass D) goto
5. The condition in the if statement should be in the form of
A) Arithmetic or Relational expression B) Arithmetic or Logical expression
C) Relational or Logical expression D) Arithmetic
6. Which of the following is known as definite loop?
A) do..while B) while C) for D) if..elif
rg
lai.O snippet?
7. What is the output of the following
a
i=1 P a das
w.
ww
while True:
if i%3 ==0:
break
print(i,end='')
i +=1
A) 1 2 B) 123 C) 1234 D) 124
8. What is the output of the following snippet?
T=1
while T:
print(True)
break
41
A) False B) True C) 0 D) no output
Syntax:
if <condition>:
statements-block 1
else:
statements-block 2
42
4. Define control structure.
A program statement that causes a jump of control from one part of the program to another is called
control structure or control statement.
5. Write note on range () in loop
range() generates a list of values starting from start till stop-1 in for loop.
The syntax of range() is as follows:
range (start,stop,[step])
Where,
The if .. else statement provides control to check the true block as well as the false block.
if..else statement thus provides two possibilities and the condition determines which BLOCK is to be
executed.
43
Syntax:
if <condition>:
statements-block 1
else:
statements-block 2
3. Using if..else..elif statement write a suitable program to display largest of 3 numbers.
CODE:
n1= int(input("Enter the first number:"))
rg g
n2= int(input("Enter the second a i.Or
number:"))
i.O
d a
d saaslala
n3= int(input("Enter the a
.P.Pthird
a number:"))
w ww
w
ww
if(n1>=n2)and(n1>=n3):
biggest=n1;
elif(n2>=n1)and(n2>=n3):
biggest=n2
else:
biggest=n3
print("The biggest number between",n1,",",n2,"and",n3,"is",biggest)
OUTPUT
Enter the first number:1
Enter the second number:3
Enter the third number:5
The biggest number between 1 , 3 and 5 is 5
4. Write the syntax of while loop.
Syntax:
while <condition>:
statements block 1
[else:
statements block2]
44
5. List the differences between breakrgrand
i.O.O rgrg
g continue statements.
i.O.O i . O . rgrg
O
l al a i l al a i l al a i
a d
break
a adsaasa a d
a adsaasa d adsaasa
continue
a a
.P.P
ww ww.P.P ww.P.P
w ww
w wwww wwww
The break statement terminates the loop The Continue statement is used to skip the
containing it. remaining part of a loop and
Control of the program flows to the statement Control of the program flows start with next
immediately after the body of the loop. iteration.
Syntax: Syntax:
break continue
Section - D
Answer the following questions: (5 Marks)
g The sequence
rg g refers to the initial, final
rg g and increment value.rg
a l
a al i.Or
ia.O alaal i.Or
ia.O a l a i.O
fors sloop uses the range() function
ss in the sequence to
s specify the initial, final and increment values.
. P. adaada
P . P. adaada
P . P ada
wwww range() generates wwwawlist of values startingwfromw start till stop-1.
ww ww w
45
The syntax of range() is as follows:
range (start,stop,[step])
Where,
ia.Orgrg
start – refers to the initial i.O
alaalvalue
ss
. P. adaada
P
stop – refers
ww w
towthe final value
ww
step – refers to increment value, this is optional part.
Example:
for i in range(2,10,2):
print (i,end=' ')
else:
print ("\nEnd of the loop")
Output:
2468
When we need to construct a chain of if statement(s) then „elif‟ clause can be used instead of „else‟.
„elif‟ clause combines if..else-if..else statements to one if..elif…else.
„elif‟ can be considered to be abbreviation of „else if‟.
In an „if‟ statement there is no limit of „elif‟ clause that can be used, but an „else‟ clause if used
should be placed at the end.
Syntax:
if <condition-1>:
statements-block 1
elif <condition-2>:
statements-block 2
else:
statements-block n
46
rg g
In the syntax of if..elif..else mentioned risgrtested
g grg
rstatements-
i.Or above, condition-1
i.O
aslaala i.O
i.O
aslaala
if it is true then
i.O
i.O
aslaala
block1 is executed.PP d a s
a d a s
a d a s
a
w . . a ad
w ww
a ad
.P.P ww
a ad
.P.P
w
www w
www w
www
Otherwise the control checks condition-2, if it is true statements-block2 is executed and even if it
fails statements-block n mentioned in else part is executed.
Example:
m1=int (input(“Enter mark in first subject : ”))
m2=int (input(“Enter mark in second subject : ”))
avg= (m1+m2)/2
if avg>=80:
print (“Grade : A”)
elif avg>=70 and avg<80:
print (“Grade : B”)
elif avg>=60 and avg<70:
print (“Grade : C”)
elif avg>=50 and avg<60:
print (“Grade : D”)
else:
print (“Grade : E”)
Output :
Enter mark in first subject : 34
Enter mark in second subject : 78
Grade : D
3. Write a program to display all 3 digit odd numbers.
CODE:
lower=int(input("Enter the lower limit for the range:"))
rgrg
.OO
iai. for the range:"))
saslaallimit
upper=int(input("Enter the upper
. P. adaada
P
for i in range(lower,upper+1):
ww ww
ww
if(i%2!=0):
print(i,end=" ")
47
Output:
49
Section-B
Answer the following questions (2 Marks)
1. What is function?
Orgrg
Functions are named blocks of code that are designed to do one specific job.salaalia. i.O laalia.
s sas
. P. adaada
P .P.P
a
adada
Types of Functions are User defined, Built-in, lambda and recursion.
wwwwww ww
ww
ww
Function blocks begin with the keyword “def ” followed by function name and parenthesis
Org ().
lai.
2. Write the different types of function. asa
w. Pad
TYPES OF FUNCTION:
ww
l a i.Org
sa
ada
ww.P
w
Scope of variable refers to the part of the program, where it is accessible, i.e., area where you can
refer (use) it.
g and their values.
Scope holds the current set of variables
alai.Or
d as
The two types of scopes
.Pa are- local scope and global scope.
w w
5. Define globalwscope.
A variable with local scope can be accessed only within the function/block that it is created in.
When a variable is created inside the function/block, the variable becomes local to it.
If we modify the global variable , We can see the change on the global variable outside the function
also.
51
Example:
x=0 # global variable
def add():
global x
x=x+5 # increment by 2
print ("Inside add() function x value is :", x)
add()
print ("In main x value is :", x)
Output:
Inside add() function x value is : 5
In main x value is : 5 #value of x changed outside the
function
Returns the smallest integer greater than or Returns the largest integer less than or equal to
equal to x x
math.ceil math.floor
(x) (x)
5. Write a Python code to check whether a given year is leap year or not.
CODE:
n=int(input("Enter the year"))
if(n%4==0):
print ("Leap Year")
else:
print ("Not a Leap Year")
Output:
52
g
i.Or
6. What is composition in functions?
d asala
The value returned a
w w.Pby a function may be used as an argument for another function in a nested
w
manner.
For example, if we wish to take a numeric value as a input from the user, we take the input string
from the user using the function input() and apply eval() function to evaluate its value.
2. If the base condition is met then the program gives meaningful output and exits.
3. Otherwise, function does some required processing and then calls itself to continue recursion.
Function blocks begin with the keyword “def” followed by function name and parenthesis ().
Any input parameters should be placed within these parentheses.
The code block always comes after a colon (:) and is indented.
The statement “return [expression]” exits a function, and it is optional.
A “return” with no arguments is the same as return None.
Section - D
Answer the following questions: (5 Marks)
53
i) BUILT-IN FUNCTION:
Built-in functions are Functions that are inbuilt with in Python.
print(), echo() are some built-in function.
ii) USER DEFINED FUNCTION:
Functions defined by the users themselves are called user defined function.
Functions must be defined, to create and use certain functionality.
Function blocks begin with the keyword “def ” followed by function name and parenthesis ().
When defining functions there are multiple things that need to be noted;
Function blocks begin with the keyword “def” followed by function name and parenthesis ().
Any input parameters should be placed within these parentheses.
The code block always comes after a colon (:) and is indented.
The statement “return [expression]” exits a function, and it is optional.
A “return” with no arguments is the same as return None.
EXAMPLE:
def area(w,h):
return w * h
print (area (3,5))
iii) LAMBDA FUNCTION:
In Python, anonymous function is a function that is defined without a name.
While normal functions are defined using the def keyword, in Python anonymous functions are
defined using the lambda keyword.
Hence, anonymous functions are also called as lambda functions.
rg g rg g
i.Or
USE OF LAMBDA OR ANONYMOUS
i.O FUNCTION:
aslaala i.Or
i.O aslaala
d a
d s
a d asa
d and one-time anonymous function.
Lambda function aisamostly
.P.P used for creating
a asmall
.P.P
w w w w w w
www www
Lambda functions are mainly used in combination with the functions like filter(), map() and
reduce().
EXAMPLE:
sum = lambda arg1, arg2: arg1 + arg2
print ('The Sum is :', sum(30,40))
54
print ('The Sum is :', sum(-30,40))
Output:
The Sum is : 70
The Sum is : 10
iv) RECURSIVE FUNCTION:
Functions that calls itself is knowni.O
asrg
.O rg
recursive.
a s
a aslaalai
adad function works
Overview of how recursive
w .P.P
w
ww is called by some external code.
1. Recursivewfunction
w
g
r g output and exits.
i.Or
ia.O
2. If the base condition is met then the program giveslameaningful
dadsaasal
a
.P.Pa
3. Otherwise, function does some required processing and then calls itself to continue recursion.
w ww
w
ww
2. Explain the scope of variables with an example.
Scope of variable refers to the part of the program, where it is accessible, i.e., area where you can
refer (use) it.
We can say that scope holds the current set of variables and their values.
There are two types of scopes - local scope and global scope.
Local Scope:
A variable declared inside the function's body or in the local scope is known as local variable.
Rules of local variable:
A variable with local scope can be accessed only within the function/block that it is created in.
When a variable is created inside the function/block, the variable becomes local to it.
A local variable only exists while the function is executing.
The formal arguments are also local to function.
Example:
def loc():
y=0 # local scope
print(y)
loc()
Output:
0
55
Global Scope
A variable, with global scope can be used anywhere in the program.
It can be created by defining a variable outside the scope of any function/block.
rg g
Rules of global Keyword lalia.O
a a i.Or
adsas
adakeyword
The basic rules for global
w . P.P in Python are:
www
ww
When we define a variable outside a function, it‟s global by default. You don‟t have to use
global keyword.
We use global keyword to read and write a global variable inside a function.
Use of global keyword outside a function has no effect
Use of global Keyword
Without using the global keyword we cannot modify the global variable inside the function but
we can only access the global variable.
Example:
x=0 # global variable
def add():
global x
x=x+5 # increment by 2
print ("Inside add() function x value is :", x)
add()
print ("In main x value is :", x)
Output:
Inside add() function x value is : 5
In main x value is : 5 #value of x changed outside the function
56
3. Explain the following built-in functions.
(a) id() (b) chr() (c) round() (d) type() (e) pow()
57
4. Write a Python code to find the L.C.M. of two numbers.
CODE:
x=int(input("Enter first number:"))
y=int(input("Enter second number:"))
if x>y:
min=x
else:
min=y
while(1):
y l==
if((min%x == 0) and (min %sa
.Org
ai 0)):
. P ada
print("LCM w
is:",min)
w
w
break
min=min+1
OUTPUT:
Enter first number:2
Enter second number:3
LCM is: 6
5. Explain recursive function with rgrgexample.
ai.Oi.an
O
d a
d saaslala
Functions that calls.P a a is known as recursive.
w wwitself
w
.P
ww
When a function calls itself is known as recursion.
Recursion works like loop but sometimes it makes more sense to use recursion than loop.
Imagine a process would iterate indefinitely if not stopped by some condition is known as infinite
iteration.
The condition that is applied in any recursive function is known as base condition.
A base condition is must in every recursive function otherwise it will continue to execute like an
infinite loop.
Python stops calling recursive function after 1000 calls by default.
So, It also allows you to change the limit using sys.setrecursionlimit (limit_value).
58
Overview of how recursive function works: i . O . rgrg
O i . O. rgrg
O
l al a i l al a i
a d
a adsaasa a d
a adsaasa
1. Recursive function is called by some external
.P.Pcode. .P.P
wwww wwww
ww ww
2. If the base condition is met then the program gives meaningful output and exits.
3. Otherwise, function does some required processing and then calls itself to continue recursion.
EXAMPLE:
def fact(n):
if n == 0:
return 1
else:
return n * fact (n-1)
print (fact (0))
print (fact (5))
Output:
1
120
59
8. STRINGS AND STRING MANIPULATION
Section – A
Choose the best answer (1 Mark)
1. Which of the following is the output of the following python code?
str1="TamilNadu"
print(str1[::-1])
(a) Tamilnadu (b) Tmlau (c) udanlimaT d) udaNlimaT
2. What will be the output of the following code?
str1 = "Chennai Schools"
str1[7] = "-"
(a) Chennai-Schools (b) Chenna-School (c) Type error (d) Chennai
3. Which of the following operator is used for concatenation?
(a) + (b) & (c) * (d) =
.OOrgrallows
4. Defining strings within triple quotes g creating:
sasalaliai.
(a) Single line Strings
adada (b) Multiline Strings
.P.Pa
wStrings
w
w
(c) Doublewline
w w (d) Multiple Strings
5. Strings in python: rgrg
l alia.O
i. O
(a) Changeable (b) Mutable a a (c) Immutable (d) flexible
P a daadsas
ww . .P
6. Which of the following is the slicing operator?
ww
ww
(a) { } (b) [ ] (c) < > (d) ( )
7. What is stride?
(a) index value of slide operation (b) first argument of slice operation
(c) second argument of slice operation (d) third argument of slice operation
8. Which of the following formatting character is used to print exponential notation in upper case?
(a) %e (b) %E (c) %g (d) %n
9. Which of the following is used as placeholders or replacement fields which get replaced along with
format( ) function?
(a) { } (b) < > (c) ++ (d) ^^
10. The subscript of a string may be:
(a) Positive (b) Negative (c) Both (a) and (b) (d) Either (a) or (b)
60
Section-B
Answer the following questions (2 Marks)
1. What is String?
String is a data type in python, usedrgrtog handle array of characters.
a
String is a sequence of characters
a l lia.O O may be a combination of letters, numbers, or special
i.that
a s
a s a
adadsingle,
symbols enclosedwwithin
.P.P double or even triple quotes.
w ww w
w
2. Do you modify a string in Python?
Yes we can modify the string by the following method,
A new string value can be assign to the existing string variable.
When defining a new string value to the existing string variable.
Python completely overwrite new string on the existing string.
3. How will you delete a string in Python?
Python will not allow deleting a particular character in a string.
Whereas you can remove entire string variable using del command.
Example:
del str1[2]
4. What will be the output of the following python code?
str1 = “School”
print(str1*3)
OUTPUT:
School School School
5. What is slicing?
Slice is a substring of a main string.
A substring can be taken from the original grg string by using [ ] slicing operator and index or subscript
. O r
O
values.
asaaslaaliai.
Using slice operator, adadhave to slice one or more substrings from a main string.
.P.you
P
wwww
ww
General format of slice operation:
str[start:end]
Section-C
Answer the following questions (3 Marks)
1. Write a Python program to display the given pattern
COMPUTER
COMPUTE
COMPUT
COMPU
COMP
COM
CO
C
61
CODE:
str="COMPUTER"
index=len(str)
for i in str:
print(str[:index])
index-=1
62
OUTPUT:
Number 1: 34
Number 2: 54
The sum of 34 and 54 is 88
65
10. Let setA={3,6,9}, setB={1,3,9}. What will be the result of the following snippet?
print(setA|setB)
(a) {3,6,9,1,3,9} (b) {3,9} (c) {1} (d) {1,3,6,9}
11. Which of the following set operation includes all the elements that are in two sets but not the one
that are common to two sets?
(a) Symmetric difference (b) Difference (c) Intersection (d) Union
12. The keys in Python, dictionary is specified by
(a) = (b) ; (c)+ (d) :
Section-B
Answer the following questions (2 Marks)
1. What is List in Python?
A list is an ordered collection of values enclosed within square brackets [ ] also known as a
“sequence data type”.
Each value of a list is called as element.
Elements can be a numbers, characters, strings and even the nested lists.
Syntax: Variable = [element-1, element-2, element-3 …… element-n]
2. How will you access the list elements in reverse order?
Python enables reverse or negative indexing for the list elements.
A negative index can be used to access an element in reverse order.
Thus, python lists index in opposite order.
The python sets -1 as the index value rgrgfor the last element in list and -2 for the preceding element and
i . O
i. O
so on.
d a
d saaslaala
This is called as Reverse
a a Indexing.
.P.P
3. What will bewthewwwvalue
w of x in following python code?
w
List1=[2,4,6,[1,3,5]]
x=len(List1)
print(x)
OUTPUT:
====== RESTART: C:/Users/SANJANASRI.SANJANASRI-PC/Desktop/Python/LI.py ======
4
>>>
4. Differentiate del with remove( ) function of List.
del remove( )
del statement is used to delete known elements remove( ) function is used to delete elements of
a list if its index is unknown.
The del statement can also be used to delete The remove is used to delete a particular element
entire list.
66
5. Write the syntax of creating a Tuple with n number of elements.
Syntax:
Tuple_Name = (E1, E2, E2 ……. En) # Tuple with n number elements
Tuple_Name = E1, E2, E3 ….. En # Elements of a tuple without parenthesis
67
3. What will be the output of the following code?
list = [2**x for x in range(5)]
print(list)
OUTPUT: [1, 2, 4, 8, 16]
4. Explain the difference between del and clear( ) in dictionary with an example.
del clear( ) rgrg
The del statement is used to delete known The function clear( ) is usedsto l alia.O
i
delete. O
all the
a aasa
elements elements in list aad d
.P.P
ww
ww
ww
The del statement can also be used to delete It deletes only the elements and retains the list.
entire list.
68
Section - D
Answer the following questions: (5 Marks)
1. What the different ways to insert an element in a list. Explain with suitable example.
Inserting elements in a list using insert():
The insert ( ) function helps you to include an element at your desired position.
The insert( ) function is used to insert an element at any position of a list.
Syntax:
List.insert (position index, element)
Example:
>>> MyList=[34,98,47,'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan' ]
. O rg
>>> MyList.insert(3,l a i 'Ramakrishnan')
d asa
>>> print(MyList)
a
P
w.47,
Output: [34,
w w98, 'Ramakrishnan', 'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan']
In the above example, insert( ) function inserts a new element „Ramakrishnan‟ at the index value 3,
th
ie. at the 4 position.
While inserting a new element, the existing elements shifts one position to the right.
Adding more elements in a list using append():
The append( ) function is used to add a single element in a list.
But, it includes elements at the end of a list.
Syntax:
List.append (element to be added)
Example:
>>> Mylist=[34, 45, 48]
>>> Mylist.append(90)
>>> print(Mylist)
Output: [34, 45, 48, 90]
Adding more elements in a list using extend():
The extend( ) function is used to add more than one element to an existing list.
In extend( ) function, multiple elements should be specified within square bracket as arguments of
the function.
Syntax:
List.extend ( [elements to be added])
Example:
>>> Mylist=[34, 45, 48]
>>> Mylist.extend([71, 32, 29])
>>> print(Mylist)
Output: [34, 45, 48, 90, 71, 32, 29]
69
2. What is the purpose of range( )? Explain with an example.
range():
The range( ) is a function used to generate a series of values in Python.
Using range( ) function, you can create list with series of values.
The range( ) function has three arguments.
Using the range( ) function, you can create a list with series of values.
To convert the result of range( ) function into list, we need one more function called list( ).
The list( ) function makes the result of range( ) as a list.
Syntax:
List_Varibale = list ( range ( ) )
Example :
g .O r rg
>>> Even_List = list(range(2,11,2))
O
lali
a i .
a d
a adsaasa
>>> print(Even_List)
ww .P.P
Output: www
[2,w4, 6, 8, 10]
In the above code, list( ) function takes the result of range( ) as Even_List elements.
Thus, Even_List list has the elements of first five even numbers.
70
3. What is nested tuple? Explain with an example.
Tuple:
Tuples consists of a number of values separated by comma and enclosed within parentheses.
Tuple is similar to list, values in a list can be changed but not in a tuple.
Nested Tuples:
In Python, a tuple can be defined inside another tuple; called Nested tuple.
In a nested tuple, each tuple is considered as an element.
The for loop will be useful to access all the elements in a nested tuple.
Example:
Toppers = (("Vinodini", "XII-F", 98.7), ("Soundarya", "XII-H", 97.5), ("Tharani", "XII-F",
95.3), ("Saisri", "XII-G", 93.8))
for i in Toppers:
print(i)
Output:
('Vinodini', 'XII-F', 98.7)
('Soundarya', 'XII-H', 97.5)
('Tharani', 'XII-F', 95.3)
('Saisri', 'XII-G', 93.8)
4. Explain the different set operations supported by python with suitable example.
A Set is a mutable and an unordered collection of elements without duplicates.
Set Operations:
The set operations such as Union, Intersection, difference and Symmetric difference.
(i) Union:
It includes all elements from two or more sets.
The operator | is used to union of two sets.
The function union( ) is also used to join two sets in python.
Example:
set_A={2,4,6,8}
set_B={'A', 'B', 'C', 'D'}
U_set=set_A|set_B
print(U_set)
Output:
{2, 4, 6, 8, 'A', 'D', 'C', 'B'}
71
(ii) Intersection:
It includes the common elements in two sets.
The operator & is used to intersect two sets in python.
The function intersection( ) is also used to intersect two sets in python.
rg
s a lai.O
ada
w.P
ww
Example:
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A & set_B)
Output:
{'A', 'D'}
(iii) Difference:
It includes all elements that are in first set (say set A) but not in the second set (say set B).
The minus (-) operator
rg g
i.Or
The function difference( ) is also used to difference operation.
laia.O
d a
d saasal
aa
.P.P
w ww
w
ww
Example:
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A - set_B)
Output:
{2, 4}
72
Example:
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A ^ set_B)
Output:
{2, 4, 'B', 'C'}
73
g
10. PYTHON CLASSES AND OBJECTS
Section – A
Choose the best answer (1 Mark)
1. Which of the following are the key features of an Object Oriented Programming language?
(a) Constructor and Classes (b) Constructor and Object
(c) Classes and Objects (d) Constructor and Destructor
2. Functions defined inside a class:
(a) Functions (b) Module (c) Methods (d) section
3. Class members are accessed through which operator?
(a) & (b) . (c) # (d) %
4. Which of the following method is automatically executed .Org
lai when an object is created?
a d asa
(a) __object__( ) (b) __del__( ) w.P (c) __func__( ) (d) __init__( )
ww
5. A private class variable is prefixed with
(a) __ (b) && (c) ## (d) **
6. Which of the following method is used as destructor?
(a) __init__( ) (b) __dest__( ) (c) __rem__( ) (d) __del__( )
7. Which of the following class declaration is correct?
(a) class class_name (b) class class_name<> (c) class class_name: (d) class class_name[
]
8. Which of the following is the output of the following program?
class Student:
def __init__(self, name):
self.name=name
S=Student(“Tamil”)
(a) Error (b) Tamil (c) name (d) self
9. Which of the following is the private class variable?
(a) __num (b) ##num (c) $$num (d) &&num
10. The process of creating an object is called as:
(a) Constructor (b) Destructor (c) Initialize (d) Instantiation
74
Section-B
Answer the following questions (2 Marks)
1. What is class?
“init” is a special function begin and end with double underscore in Python act as a Constructor.
Constructor function will automatically executed when an object of a class is created.
General format:
<statements>
75
5. What is the purpose of Destructor?
Destructor is also a special method gets executed automatically when an object exit from the scope.
In Python, __del__( ) method is used as destructor.
General format:
def __del__(self):
<statements>
Section-C
Answer the following questions rgrg (3 Marks)
a i . O
i. O
1. What are class members?
dad slala do you define it?
saaHow
a
.P.Pa
wwww
Variables defined
ww inside a class are called as “Class Variable” and functions are called as
“Methods”.
Class variable and methods are together known as members of the class.
The class members should be accessed through objects or instance of class.
A class can be defined anywhere in a Python program.
SYNTAX FOR DEFINING A CLASS:
class class_name:
statement_1
statement_2
…………..
…………..
statement_n
2. Write a class with two private class variables and print the sum using a method.
CODE:
class Sample:
def __init__(self,n1,n2):
self.__n1=n1
self.__n2=n2
g def sum(self):
print("Class Variable 1:",self.__n1)
76
print("Class Variable 2:",self.__n2)
print("Sum:",self.__n1 + self.__n2)
S=Sample(5,10)
S.sum()
OUTPUT:
>>>
Class Variable 1: 5
Class Variable 2: 10
Sum: 15
>>>
3. Find the error in the following program to get the given output?
ERROR CODE:
class Fruits:
def __init__(self, f1, f2):
self.f1=f1
self.f2=f2
def display(self):
print("Fruit 1 = %s, Fruit 2 = %s" %(self.f1, self.f2))
F = Fruits ('Apple', 'Mango')
del F.display
F.display()
OUTPUT:
ERROR:
line 8, in <module>
del F.display
AttributeError: display
77
CORRECT CODE:
class Fruits:
def __init__(self, f1, f2):
self.f1=f1
self.f2=f2
def display(self):
print("Fruit 1 = %s, Fruit 2 = %s" %(self.f1, self.f2))
F = Fruits ('Apple','Mango')
F.display()
OUTPUT:
g
Output:
>>>
g rg
Good Morning
ai.O Bindu Madhavan
sal
d a
w. Pa>>>
ww 78
g
5. How do define constructor and destructor in Python?
CONSTRUCTOR:
“init” is a special function begin and end with double underscore in Python act as a Constructor.
Constructor function will automatically executed when an object of a class is created.
General format of constructor:
<statements>
DESTRUCTOR:
Destructor is also a special method gets executed automatically when an object exit from the scope.
In Python, __del__( ) method is used as destructor.
General format of destructor:
def __del__(self):
<statements> Section - D
1. Explain about constructor and destructor with suitable example.
Constructor :
• Constructor is the special function called “init” which act as a constructor.
• This function will executes automatically when the object is created.
• It must begin and end with double underscore.
• It can be defined with (or) without arguments.
Syntax :
def ___ init ___ (self, [ args ……… ]) :
< statements >
Destructor :
79
Example :
Class sample :
def ___ init ___ (self, num) :
Print (“constructor of class sample….”)
self.num = num
print (“The value is : “, num)
def ___del___ (self) :
Print (“Destructor of class sample”)
S = sample (10)
The class “Sample” has a constructor which executed automatically, when an object S is created
with actual parameter 10. rg
s a lai.O
• da sample..”
When the constructor gets executed, it prints the “Constructor ofaClass
w .P
w
• The passing value of the constructor is assigned to self . w
nam and it prints the value passed.
OUTPUT :
80
11. DATABASE CONCEPTS
Section – A
Choose the best answer (1 Mark)
1. What is the acronym of DBMS?
a) DataBase Management Symbol b) Database Managing System
c) DataBase Management System d) DataBasic Management System
2. A table is known as
a) tuple b) attribute c) relation rg d)entity
l a i . O
3. Which database model represents parent-child relationship?
asad
a) Relational b) Network w .Pc)a Hierarchical d) Object
ww
4. Relational database model was first proposed by
a) E F Codd b) E E Codd c) E F Cadd d) E F Codder
5. What type of relationship does hierarchical model represents?
a) one-to-one b) one-to-many c) many-to-one d) many-to-many
6. Who is called Father of Relational Database from the following?
a) Chris Date b)Hugh Darween c) Edgar Frank Codd d) Edgar Frank Cadd
7. Which of the following is an RDBMS?
a) Dbase b) Foxpro c) Microsoft Access d) Microsoft Excell
8. What symbol is used for SELECT statement?
a) σ b) Π c) X d) Ω
9. A tuple is also known as
a) table b) row c) attribute d) field
10. Who developed ER model?
a) Chen b) EF Codd c) Chend d) Chand
Section-B
Answer the following questions (2 Marks)
1. Mention few examples of a database.
Foxpro
dbase.
IBM DB2.
Microsoft Access.
Microsoft Excel.
MySQL.
81
2. List some examples of RDBMS.
SQL Server
Oracle
MySQL
MariaDB
SQLite
3. What is data consistency?
Data Consistency means that data values are the same at all instances of a database.
On live data, it is being continuously updated and added, maintaining the consistency of data can
become a challenge.
But DBMS handles it by itself.
4. What is the difference between Hierarchical and Network data model?
Hierarchical data model Network data model
In hierarchical model, a child record has In a Network model, a child may have
only one parent node many parent nodes.
i .O. rgrg
O
lal a i
a d
a adsaasa
.P.P
ww
ww
ww
g gg r r on different types of DBMS users.
5. Write l a lia.O
a i O
note
.
aa
P a daadsas Administrators
Database
ww. .P
ww
ww Database Administrator or DBA is the one who manages the complete database management system.
g Application Programmers grg or Software Developers
. O Or
This
s liai. group is involved in developing and designing the parts of DBMS.
aslaauser
a a
dad User
aEnd
ww.P.P
ww
ww End users are the one who store, retrieve, update and delete data.
Database designers:
They are responsible for identifying the data to be stored in the database for choosing appropriate
structures to represent and store the data.
Section - D
Answer the following questions: (5 Marks)
1. Explain the different types of data model.
Data Model
A data model describes how the data can be represented and accessed from a software after
complete implementation
83
Types of Data Model
The different types of a Data Model are,
Hierarchical Model
Relational Model
Network Database Model
Entity Relationship Model
Object Model
i). Hierarchical Model:
In Hierarchical model, data is represented as a simple tree like structure form.
This model represents a one-to-many relationship ie parent-child relationship.
One child can have only one parent but one parent can have many children.
This model is mainly used in IBM Main Frame computers.
Example:
Example:
i .O .Orgrg
l al a i
adaadsaasa
.P.P
ww
ww
ww
84
iii.) Network Model
85
Example:
1. One-to-One Relationship
2. One-to-Many Relationship
3. Many-to-One Relationship
4. Many-to-Many Relationship
i.) One-to-One Relationship:
In One-to-One Relationship, one entity is related with only one other entity.
One row in a table is linked with only one row in another table and vice versa.
rg g
For Example: A student can have only one exam number.
i.Or
i.O
d a
d saaslaala
aa
.P.P
w ww
w
ww
i. O .Orgrg
a i
d a
d saaslala
a
.P.Pa
wwww
ww
86
iii. Many-to-One Relationship:
In Many-to-One Relationship, many entities can be related with only one in the other entity.
For Example: A number of staff members working in one Department.
Multiple rows in staff members table is related with only one row in Department table.
g
a l ai.Or
s
ada
w.P
ww
4. Many-to-Many Relationship:
.Org
a s alai occurs when multiple records in a table are associated with
A many-to-many relationship
adanother table.
.Pin
multiple records
w w
Example:wBooks and Student :Many Books in a Library are issued to many students.
g
a l ai.Or
P adas
w .
ww
87
3. Differentiate DBMS and RDBMS.
The SELECT operation is used for selecting a subset with tuples according to a given condition.
Select filters out all tuples that do not satisfy C.
Example: σ = “Big Data” (STUDENT )
course
PROJECT (symbol : Π)
The projection eliminates all attributes of the input relation but those mentioned in the projection
list.
The projection method defines a relation that contains a vertical subset of Relation.
Example: Π (STUDENT)
course
UNION (Symbol :∪) A U B
It includes all tuples that are in tables A or in B.
It also eliminates duplicates.
Set A Union Set B would be expressed as A ∪ B
SET DIFFERENCE ( Symbol : - )
The result of A – B, is a relation which includes all tuples that are in A but not in B.
The attribute name of A has to match with the attribute name in B.
INTERSECTION (symbol : ∩) A ∩ B
Defines a relation consisting of a set of all tuple that are in both in A and B.
However, A and B must be union-compatible.
PRODUCT OR CARTESIAN PRODUCT gg (Symbol : X )
ia.O rr
.O
lal i
Cross product is a waydof asa
adsacombining two relations.
P a
P a
. . contains, both relations being combined.
The resulting relation
wwww
ww
This type of operation is helpful to merge columns from two relations.
A x B means A times B, where the relation A and B have different attributes.
89
5. Explain the characteristics of DBMS.
1. Data Stored in a Tables Data is stored into tables, created inside the database.
DBMS also allows to have relationship between tables.
This constraint ensures that no two rows This constraint declares a field as a Primary
have the same value in the specified key which helps to uniquely identify a
columns. record.
The UNIQUE constraint can be applied only The primary key does not allow NULL
to fields that have also been declared as values and therefore a primary key field must
NOT NULL. have the NOT NULL constraint.
91
3. Write the difference between table constraint and column constraint?
Table Constraint Column Constraint
Table constraints apply to a group of one or Column constraints apply only to individual
more columns. column.
4. Which component of SQL lets insert values in tables and which lets to create a table?
Command Description component
Section-C
Answer the following questions (3 Marks)
1. What is a constraint? Write short
Orgrnote
g on Primary keyOconstraint.
rgrg
s a
s laalia. i.O s aslaalia. i.O
Constraint is a condition
adaadapplicable
a on a field aordaaset
da of fields.
. P. P
wwdeclares a field as a w . P. P
ww key which helps to uniquely identify a record.
Primary constraint
wwww wwPrimary
w
It is similar to unique constraint except that only one field of a table can be set as primary key.
The primary key does not allow NULL values and therefore a primary key field must have the
NOT NULL constraint.
2. Write a SQL statement to modify the student table structure by adding a new rgrg
ifield.
i.O.O
d a
d saaslaala
aa
Syntax : ALTER TABLE <table-name> ADD <column-name><datawtype><size>;
.P.P
w
ww w w
To add a new column “Address” of type „char‟ to the Student table, the command is used as
Statement: ALTER TABLE Student ADD Address char;
92
3. Write any three DDL commands.
Data Definition Language:
Create Command: To create tables in the database.
CREATE TABLE Student (Admno integer, Name char(20), Gender char(1), Age integer);
Alter Command: Alters the structure of the database.
ALTER TABLE Student ADD Address char;
Drop Command: Delete tables from database.
DROP TABLE Student;
4. Write the use of Savepoint command with an example.
The SAVEPOINT command is used to temporarily save a transaction so that you can rollback to the
point whenever required.
Syntax: SAVEPOINT savepoint_name;
Example: SAVEPOINT A;
5. Write a SQL statement using DISTINCT keyword.
The DISTINCT keyword is used along with the SELECT command to eliminate duplicate rows in
the table.
This helps to eliminate redundant data.
For Example: SELECT DISTINCT Place lai Student;.Org
saFROM
. P ada
wSection - D
ww
Answer the following questions: (5 Marks)
i .O .Orgrg
lal a i
a d
a adsaasa
.P.P
ww
ww
ww
(i)Unique Constraint: Table Constraint
This constraint ensures that no two rows have the same value in the specified columns.
93
For example UNIQUE constraint applied on Admno of student table ensures that no two students
have the same admission number and the constraint can be used as:
In the above example the check constraint is set to Age field where the value of Age must be less
than or equal to 19.
(V) Table Constraint:
When the constraint is applied to a group of fields of the table, it is known as Table constraint.
The table constraint is normally given at the end of the table definition.
Let us take a new table namely Student1 with the following fields Admno, Firstname, Lastname,
Gender, Age, Place:
Example:
CREATE TABLE Student 1
(
Admno integer NOT NULL,
Firstname char(20),
Lastname char(20),
Gender char(1),
Age integer,
Place char(10),
PRIMARY KEY (Firstname, Lastname) → Table constraint i .O . rgrg
O
l al a i
); a d
a adsaasa
ww.P.Pand Lastname are defined as Primary key which is a
In the above example, the two fields, Firstname
wwww
Table constraint.
95
2. Consider the following employee table. Write SQL commands for the qtns.(i)i.O
torg
.O rg
(v).
a s
a aslaalai
d
a ad
w .P.P
w
w
www
i .O . rgrg
O
l ala i
a d
a adsaasa
.P.P
ww
ww
ww
96
By Data Manipulation we mean,
Insertion of new information into the database
Retrieval of information stored in a database.
Deletion of information from the database.
Modification of data stored in the database.
ii) DATA DEFINITION LANGUAGE:
The Data Definition Language (DDL) consist of SQL statements used to define the database
structure or schema.
It simply deals with descriptions of the database schema and is used to create and modify the
structure of database objects in databases.
The DDL provides a set of definitions to specify the storage structure and access methods used by
the database system.
SQL commands which comes under Data Definition Language are:
Create To create tables in the database.
97
g
Commit Saves any transaction into the database permanently.
Male 5
Female 3
i .O . rgrg
O i .O . rgrg
O i .O . rgrg
O
l al a i l al a i l al a i
a d
a adsaasa adaadsaasa adaadsaasa
.P.P
ww .P.P
ww .P.P
ww
ww
ww ww
ww ww
ww
i .O . rgrg
O i .O . rgrg
O i .O . rgrg
O
l al a i l al a i l al a i
a d
a adsaasa a d
a adsaasa a d
a adsaasa
.P.P
ww .P.P
ww .P.P
ww
ww
ww ww
ww ww
ww
98
5. Write a SQL statement to create a table for employee having any five fields and create a table
constraint for the employee table.
CREATE TABLE employee
(
empno integer NOT NULL,
name char(20),
desig char(20),
pay integer,
allowance integer,
PRIMARY KEY (empno)
);
13. PYTHON AND CSV FILES
Section – A
Choose the best answer (1 Mark)
1. A CSV file is also known as a ….
(A) Flat File (B) 3D File (C) String File (D) Random File
2. The expansion of CRLF is
(A) Control Return and Line Feed (B) Carriage Return and Form Feed
(C) Control Router and Line Feed (D) Carriage Return and Line Feed
3. Which of the following module is provided by Python to do several operations on the CSV files?
(A) py (B) xls (C) csv (D) os
4. Which of the following mode is used when dealing with non-text files like image or exe files?
(A) Text mode (B) Binary mode (C) xls mode (D) csv mode
5. The command used to skip a row in a CSV file is
(A) next() (B) skip() (C) omit() (D) bounce()
6. Which of the following is a string used to terminate lines produced by writer()method of csv
module?
(A) Line Terminator (B) Enter key (C) Form feed (D) Data Terminator
7. What is the output of the following program? import csv
d=csv.reader(open('c:\PYPRG\ch13\city.csv'))
next(d)
for row in d:
print(row)
if the file called “city.csv” contain the following details
chennai,mylapore
mumbai,andheri
100
8. Which of the following creates an object which maps data to a dictionary?
(A) listreader() (B) reader() (C) tuplereader() (D) DictReader ()
9. Making some changes in the data of the existing file or adding more data is called
(A)Editing (B) Appending (C) Modification (D) Alteration
10. What will be written inside the file test.csv using the following program import csv
D = [['Exam'],['Quarterly'],['Halfyearly']]
csv.register_dialect('M',lineterminator
i .O . rgrg = '\n')
O
l
aa al a i
P a daadsas
with open('c:\pyprg\ch13\line2.csv', 'w') as f:
ww. . P
wr = csv.writer(f,dialect='M')
wwww
wr.writerows(D)
f.close()
(A) Exam Quarterly Halfyearly (B) Exam Quarterly Halfyearly
(C) E (D) Exam,
Q Quarterly,
H Halfyearly
Section-B
Answer the following questions (2 Marks)
5. How will you sort more than one column from a csv file? Give an example statement.
To sort by more than one column you can use itemgetter with multiple indices.
Syntax: operator.itemgetter(col_no)
Example: sortedlist = sorted (data, key=operator.itemgetter(1))
Section-C
1. Write a note on open() function of python. What is the difference between the two methods?
Python has a built-in function open() to open a file.
This function returns a file object, also called a handle, as it is used to read or modify the file
accordingly.
The default is reading in text mode.
In this mode, while reading from the file the data would be in the format of strings.
On the other hand, binary mode returns bytes and this is the mode to be used when dealing with
non-text files like image or exe files.
PROGRAM: student.csv
import csv
row = [„3‟, „Meena‟,‟Bangalore‟]
with open(„student.csv‟, „r‟) as readFile:
102
reader = csv.reader(readFile)
3. Write a Python program to read a CSV file with default delimiter comma (,).
#importing csv
import csv #opening the csv file which is in different location with read mode
with open('c:\\pyprg\\sample1.csv', 'r') as F:
#other way to open the file is f= ('c:\\pyprg\\sample1.csv', 'r')
reader = csv.reader(F) # printing each line of the Data row by row
print(row)
F.close()
OUTPUT:
['SNO', 'NAME', 'CITY']
['12101', 'RAM', 'CHENNAI']
['12102', 'LAVANYA', 'TIRUCHY'] i . O. rgrg
O
a
l la i
asaasa
['12103', 'LAKSHMAN', 'MADURAI']
adad
ww.P.P
ww
ww
4. What is the difference between the write mode and append mode.
Creates a new file if it does not exist or Creates a new file if it does not exist.
truncates the file if it exists.
103
5. What is the difference between reader() and DictReader() function?
Reader():
The reader function is designed to take each line of the file and make a list of all columns.
Using this method one can read data from csv files of different formats like quotes (" "), pipe (|) and
comma (,).
csv. Reader work with list/tuple.
Syntax: csv.reader(fileobject,delimiter,fmtparams)
DictReader():
DictReader works by reading the first line of the CSV and using each comma separated value in this
line as a dictionary key.
DictReader is a class of csv module is used to read a CSV file into a dictionary.
It creates an object which maps data to a dictionary.
csv.DictReader work with dictionary.
Section - D
Answer the following questions: (5 Marks)
1. Differentiate Excel file and CSV file.
Orgrg
Excel CSVsaslaalia. i.O
dada
a atext format with a series
Excel is a binary file that holds information CSV format is awplain
w.P.P
w
ww w
about all the worksheets in a file, including of values separated by commas.
both content and formatting.
XLS files can only be read by applications CSV can be opened with any text editor in
that have been especially written to read their Windows like notepad, MS Excel,
format, and can only be written in the same OpenOffice, etc.
way.
Excel is a spreadsheet that saves files into its CSV is a format for saving tabular
own proprietary format viz. xls or xlsx information into a delimited text file with
extension .csv i .O. rgrg
O
l ala i
asamuch faster, and it
Excel consumes more memory while Importing CSV filesacan daadsabe
w.P.memory
also consumeswless P
importing data wwww
104
g
2. Tabulate the different mode with its meaning.
Mode Description
'r' Open a file for reading. (default)
'w' Open a file for writing. Creates a new file if it does not exist or truncates the
file if it exists.
'x' Open a file for exclusive creation. If the file already exists, the operation fails.
'a' Open for appending at the end of the file without truncating it. Creates a new
file if it does not exist.
't' Opren in text mode. (default)
'b' Open in binary mode.
'+' Open a file for updating (reading and writing)
105
OUTPUT:
['SNO', 'NAME', 'CITY']
['12101', 'RAM', 'CHENNAI']
['12102', 'LAVANYA', 'TIRUCHY']
['12103', 'LAKSHMAN', 'MADURAI'] rgrg
l ali
a .O
i .O
asaasaat the beginning
ii) CSV files- data with Spaces
adad
w .
w P.P
Consider the following
wwww file “sample2.csv” containing the following data when opened through notepad
i .O . rgrg
O
l
aa al a i
P a daadsas
. .P
ww
wwww
The following program read the file through Python using “csv.reader()”.
import csv
csv.register_dialect('myDialect',delimiter = ',',skipinitialspace=True)
F=open('c:\\pyprg\\sample2.csv','r')
reader = csv.reader(F, dialect='myDialect')
for row in reader:
print(row)
F.close()
OUTPUT:
['Topic1', 'Topic2', 'Topic3']
['one', 'two', 'three']
i . O . rgrg
O
['Example1', i
alala 'Example2', 'Example3']
a
P a daadsas
..
ww P
ww
ww These whitespaces in the data can be removed, by registering new dialects using
g csv.register_dialect()
O rgrg class of csv module.
l a i
a . i . O
daA al
saasdialect describes the format of the csv file that is to be read.
. PPa a d
wwww. In dialects the parameter “skipinitialspace” is used for removing whitespaces after the delimiter.
ww
g iii) CSV File-Data With Quotes
You can read the csv file with quotes, by registering new dialects using csv.register_dialect() class
of csv module.
g Here, we have quotes.csv file with following data.
106
g
SNO,Quotes
1, "The secret to getting ahead is getting started."
2, "Excellence is a continuous process and not an accident."
The following Program read “quotes.csv” file, where delimiter is comma (,) but the quotes are within
quotes (“ “).
import csv
csv.register_dialect('myDialect',delimiter = ',',quoting=csv.QUOTE_ALL,
skipinitialspace=True)
f=open('c:\\pyprg\\quotes.csv','r')
reader = csv.reader(f, dialect='myDialect')
for row in reader:
print(row)
OUTPUT:
['SNO', 'Quotes']
['1', 'The secret to getting ahead is getting started.']
['2', 'Excellence is a continuous process and not an accident.']
i . O. rgrg
O
l al a i
adaadsaasa
.P.P
ww
ww
ww
In the following file called “sample4.csv”,each column is separated with | (Pipe symbol)
107
i .O . rgrg
O i .O . rgrg
O i .O . rgrg
O
l ala i l al a i l al a i
adaadsaasa a d
a adsaasa a d
a adsaasa
.P.P
ww .P.P
ww .P.P
ww
ww
ww ww
ww ww
ww
OUTPUT :
“SNO”,”Person”,”DOB” ”1”,”Madhu”,”18/12/2001” ”2”,”Sowmya”,”19/2/1998”
”3”,”Sangeetha”,”20/3/1999” ”4”,”Eshwar”,”21/4/2000”
“5”,”Anand”,”22/5/2001”
108
2. The last record in the file may or may not have an ending line break.
For example:
3.
There may be an optional header line appearing as the first line of the file with the same format as
normal record lines.
The header will contain names corresponding to the fields in the file and should contain the same
number of fields as the records in the rest of the file.
For example: field_name1,field_name2,field_name3
4.
Within the header and each record, there may be one or more fields, separated by commas.
Spaces are considered part of a field and should not be ignored.
The last field in the record must not be followed by a comma.
For example: Red , Blue
5.
Each field may or may not be enclosed in double quotes.
If fields are not enclosed with double quotes, then double quotes may not appear inside the fields.
For example:
6.
Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-
quotes.
For example:
7.
If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be
preceded with another double quote.
For example:
109
14. IMPORTING C++ PROGRAMS IN PYTHON
Section – A
Choose the best answer (1 Mark)
1. Which of the following is not a scripting language?
(A) JavaScript (B) PHP (C) Perl
rg (D) HTML
i.O
2. Importing C++ program in a Python program isdcalled
a sala
a
w.P
(A) wrapping ww
(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)rgopt variable (C)args variable (D) ifile variable
a i . O
8. Identify the function call
d sal
astatement in the following snippet.
P a
w.
ww
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?
rg g
(A) HTML (B) C (C) C++ i.Or
(D) PYTHON
ai.O
d a
d saaslala
10. What does __name__ contains ? aa
.P.P
w ww
w
(A) c++ filename (B) main() name ww
(C) python filename (D) os module name
110
g
Section-B
Answer the following questions (2 Marks)
1. What is the theoretical difference between Scripting language and other programming
language?
Scripting Language Programming Language
A scripting language requires an interpreter. A programming language requires a compiler.
A scripting language need not be compiled. A programming languages needs to be compiled
before running .
Example: Example:
JavaScript, VBScript, PHP, Perl, Python, Ruby, C, C++, Java, C# etc.
ASP and Tcl.
111
“cd” command used to change directory and absolute path refers to the complete path where
Python is installed.
Example: c:\>cd c:\ program files \ openoffice 4 \ program
Section-C
Answer the following questions (3 Marks)
l ai .Org
sa
daand
1. Differentiate PYTHON
P a C++.
w w.
w
PYTHON C++
Python is typically an "interpreted" language C++ is typically a "compiled" 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
112
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 along via the command-line input, it's basically an array
holding the command-line arguments of the program.
To use sys.argv, you will first have to import sys.
sys.argv[0] is always the name of the program as it was invoked.
sys.argv[1] is the first argument you pass to the program.
main(sys.argv[1]) :
Accepts the program file (Python program) and the input file (C++ file) as a list(array).
argv[0] contains the Python program which is need not to be passed because by default
__main__ contains source code reference
argv[1] contains the name of the C++ file which is to be processed.
Section - D
Answer the following questions: (5 Marks)
1. Write any 5 features of Python.
Python uses Automatic Garbage Collection.
Python is a dynamically typed language.
Python runs through an interpreter.
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.
g
In Python, a function may accept an argument of any type, and return multiple values without any
kind of declaration beforehand.
2. Explain each word of the following command.
COMMAND: Python <filename.py> -<i> <C++ filename without cpp extension>
Where ,
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 Name of C++ file to be compiled and executed
extension>
113
3. What is the purpose of sys,os,getopt module in Python. Explain
(i) Python‟s sys Module:
This module provides access to some variables used by the interpreter and to functions that interact
strongly with the interpreter.
sys.argv is the list of command-line arguments passed to the Python program.
argv contains all the items that come along via the command-line input, it's basically an array
holding the command-line arguments of the program.
To use sys.argv, you will first have to import sys.
sys.argv[0] is always the name of the program as it was invoked.
sys.argv[1] is the first argument you pass to the program.
main(sys.argv[1]) :
Accepts the program file (Python program) and the input file (C++ file) as a list(array).
argv[0] contains the Python program which is need not to be passed because by
default__main__ contains source code reference
r g
ai.O of the C++ file which is to be processed.
argv[1] contains the lname
a dasa
(ii) Python's OS Module:
w.P
ww
The OS module in Python provides a way of using operating system dependent functionality.
The functions that the OS module allows you to interface with the Windows operating system
where Python is running on.
os.system(): Execute the C++ compiling command in the shell.
For Example to compile C++ program g++ compiler should be invoked.
Command: os.system („g++‟ + <varaiable_name1> „-<mode>‟ + <variable_name2>
os.system function system() defined in os module
114
Example:
os.system('g++ ' + cpp_file + ' -o ' + exe_file) --
g++ compiler compiles the file cpp_file and –o (output) send to exe_file
(iii) Python getopt Module:
The getopt module of Python helps you to parse (split) command-line options and arguments.
This module provides two functions to enable command-line argument parsing.
getopt.getopt method:
This method parses command-line options and parameter list.
Syntax of getopt method:
<opts>,<args>=getopt.getopt(argv, options, [long_options])
Here is the detail of the parameters −
argv -- This is the argument list of values to be parsed (splited). In our program
the complete command will be passed as a list.
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.
g
ia.Orgrg i.Orgrg
long_options -- This parameter is passed with i.Oof strings. Argument i.O
salaaallist
s salaalaof Long options
s
should be followed .P.P adada .P.Pa
anaequal sign ('=').www
adada
wwby
wwww www
In our program the C++ file name
g will be passed as string and „i‟ also will be passed along with
g
l a i.Or
to indicate it as the inputa file.
P a das
getopt() method w.
ww returns value consisting of two elements.
Each of these values are stored separately
O rgrg in two different list (arrays) opts and args .
l alia. i. O
daadsaasastrings like mode, path and args contains any string if at all not splitted
Opts contains list of asplitted
ww.P.P
w w w
w path or mode.
because of wrong
args will be an empty array if there is no error in splitting strings by getopt().
115
g
Example:
opts, args = getopt.getopt (argv, "i:",['ifile='])
g
where opts contains -- ('-i', 'c:\\pyprg\\p4')]
-i: -- option nothing but mode should be followed by :
'c:\\pyprg\\p4' -- value nothing but the absolute path of C++ file.
In our examples since the entire command line commands are parsed and no leftover argument, the
second argument args will be empty [].
If args is displayed using print() command it displays the output as [].
Example:
>>>print(args)
[]
4. Write the syntax for getopt() and explain its arguments and return values.
Python getopt Module:
The getopt module of Python helps you to parse (split) command-line options and arguments.
This module provides two functions to enable command-line argument parsing.
getopt.getopt method:
This method parses command-line options and parameter list.
Syntax of getopt method:
<opts>,<args>=getopt.getopt(argv, options, [long_options])
Here is the detail of the parameters −
argv -- This is the argument list of values to be parsed (splited). In our program
the complete command will be passed as a list.
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 parameter is passed with a list of strings. Argument of Long options
should be followed by an equal sign ('=').
In our program the C++ file name will be passed as string and „i‟ also will be passed along with
to indicate it as the input file.
116
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, path and args contains any string if at all not splitted
because of wrong path or mode.
args will be an empty array if there is no error in splitting strings by getopt().
Example:
opts, args = getopt.getopt (argv, "i:",['ifile='])
where opts contains -- ('-i', 'c:\\pyprg\\p4')]
-i: -- option nothing but mode should be followed by :
'c:\\pyprg\\p4' -- value nothing but the absolute path of C++ file.
In our examples since the entire command line commands are parsed and no leftover argument, the
second argument args will be empty [].
If args is displayed using print() command it displays the outpu
Example:
>>>print(args)
[]
118
g
COMPUTER SCIENCE
15. DATA MANIPULATION THROUGH SQL
Section – A
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?
i . O . rgrg
O
(A) Flat file database system (B) Relational Database a i
d a
d saaslasystem
la
a
.P.PaDatabase system
(C) Hierarchical database system (D) Object oriented
w ww
w
ww
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 (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 avoide the duplicate?
(A) Distinct (B) Remove (C) Where (D) GroupBy
119
g Section-B
Answer the following questions (2 Marks)
1. Mention the users who uses the Database.
g Users of database can be human users, other programs or applications
2. Which method is used to connect a database? Give an example.
Create a connection using connect () method and pass the name of the database File.
g
Example:
import sqlite3
# connecting to the database
connection = sqlite3.connect ("Academy.db")
# cursor
cursor = connection.cursor()
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:
sql_command = """INSERT INTO Student (Rollno, Sname, Grade, gender, Average, birth_date)
VALUES (NULL, "Akshay", "B", "M","87.8", "2001-12-12");""" cursor.execute(sql_command)
5. Which method is used to fetch all rows from the database table?
The fetchall() method is used to fetch all rows from the database table.
g Example: result = cursor.fetchall()
120
g
g Section-C
Answer the following questions (3 Marks)
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 fulfill a specified condition.
EXAMPLE: To display the different grades scored by male students from “student table”
g
import sqlite3
connection = sqlite3.connect("Academy.db")
g cursor = connection.cursor()
cursor.execute("SELECT DISTINCT (Grade) FROM student where gender='M'")
result = cursor.fetchall()
g print(*result,sep="\n")
OUTPUT:
('B',)
('A',)
('C',)
('D',)
g
121
g
g
4. Read the following details.Based on that write a python script to display department wise
records.
database name :- organization.db
g Table name :- Employee
Columns in the table :- Eno, EmpName, Esal, Dept
PYTHON SCRIPT:
import sqlite3
connection = sqlite3.connect(“organization.db”)
c=conn.execute(“SELECT * FROM Employee GROUP BY Dept”)
for row in c:
print(row)
conn.close()
5. Read the following details.Based on that write a python script to display records in
desending 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(“SELECT * FROM Employee ORDER BY Eno DESC”)
result=cursor.fetchall()
print(result)
Section - D
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 MySQLor Oracle.
122
ADVANTAGES:
SQLite is fast, rigorously tested, and fl exible, making it easier to work.
Python has a native library for SQLite.
Steps To Use SQLite:
Step 1: import sqlite3
Step 2: Create a connection using connect () method and pass the name of the database File
Org
ai. of the database to be accessed.
Connecting to a database in step2 means passing the
salname
. P ada
If the database already exists the connection
w
ww 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 ()
Cursor is a control structure used to traverse and fetch the records of the database.
Cursor has a major role in working with Python.
All the commands will be executed using cursor object only.
To create a table in the database, create an object and write the SQL command in it.
Example:- sql_comm = "SQL statement"
For executing the command use the cursor method and pass the required sql command as a
parameter.
l a i .Org
Many
sa number of commands can be stored in the sql_comm and can be executed one after other.
ada
.P Any changes made in the values of the record should be saved by the commend "Commit" before
w
ww
closing the "Table connection".
2. Write the Python script to display all the records of the following table using fetchmany()
123
g
www.Padasalai.Org
PYTHON SCRIPT:
import sqlite3
connection = sqlite3.connect(“Materials.db”)
cursor=connection.cursor()
cursor.execute(“SELECT * FROM Materials”)
print(“Displaying All The Records”)
result=cursor.fetchmany(5)
print(result, Sep= “\n”)
OUTPUT:
Displaying All The Records
(1003, „Scanner‟, 10500)
(1004, „Speaker‟, 3000)
(1005, „Printer‟, 8000)
(1008, „Monitor‟, 15000)
(1010, „Mouse‟, 700)
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.
rgrg
.OO
i i.
saslaala
This is similar to WHERE condition but can be used only with group functions.
. P. adaada
P
Group functions cannot be used in WHERE Clause but can be used
wwwwin HAVING clause.
ww
Example:
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor() i . O . rgrg
O
l al a i
cursor.execute("SELECT a d
aadsaasa
GENDER,COUNT(GENDER) FROM Student GROUP BY GENDER
w.wP.P
ww
ww
HAVING COUNT(GENDER)>3")
result = cursor.fetchall()
co = [i[0] for i in cursor.description]
print(co)
print(result)
124
g
OUTPUT:
['gender', 'COUNT(GENDER)']
[('M', 5)]
PYTHON SCRIPT:
import sqlite3
connection = sqlite3.connect(“ABC.db”)
cursor=connection.cursor()
sql_command – “““ CREATE TABLE Item(
Icode INTEGER PRIMARY KEY,
ItemName VARCHAR(25),
Rate INTEGER) ; ”””
cursor.execute(sql_command)
sql_command = “““ INSERT INTO Item(Icode, ItemName, Rate) VALUES (1
”””
cursor.execute(sql_command)
connection.commit()
connection.close()
print(“TABLE CREATED”)
OUTPUT:
TABLE CREATED
125
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 100rg
l a i . O
S002 Anu Bangalore 1010 a 200
das
S003 Shahid Bangalore 1008w.Pa 175
ww
S004 Akila Hydrabad 1005 195
S005 Girish Hydrabad 1003 25
S006 Shylaja Chennai 1008 180
S007 Lavanya Mumbai 1005 325
PYTHON SCRIPT:
i) Display Name, City and Itemname of suppliers who do not reside in Delhi.
import sqlite3
connection = sqlite3.connect(“ABC.db”)
cursor.execute(“SELECT Supplier.Name, Supplier.City,Item.ItemName FROM Supplier,Item
WHERE Supplier.Icode = Item.Icode AND Supplier.City NOT In Delhi ”)
s = [i[0] for I in cursor.description]
print(s)
result = cursor.fetchall()
for r in result:
print r
OUTPUT:
[„Name‟, „City‟, „ItemName‟]
[„Anu‟, „Bangalore‟, „Scanner‟]
[„Shahid‟, „Bangalore‟, „Speaker‟]i . O. rgrg
O
la
asal a i
[„Akila‟, „Hydrabad‟,adaadsa„Printer‟]
[„Girish‟, ww .P.P „Monitor‟]
„Hydrabad‟,
wwww
[„Shylaja‟, „Chennai‟, „Mouse‟]
[„Lavanya‟, „Mumbai‟, „CPU‟]
126
ii) Increment the SuppQty of Akila by 40
import sqlite3
connection = sqlite3.connect(“ABC.db”)
cursor.execute(“UPDATE Supplier ST SuppQty = SuppQty +40 WHERE Name = „Akila‟ ”)
cursor.commit()
result = cursor.fetchall()
print (result)
connection.close()
OUTPUT:
127
g
5. Which of the following module should be importad to visualize data and information in phython?
128
g 7. Read the code:
a. import matplotlib.pyplot as plt
b. plt.plot(3,2)
g c. plt.show()
Identify the output for the above coding.
i.Org
al a
adas
w.P
ww
129
g
09. 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
Section-B
Answer the following questions (2 Marks)
130
g 5. Write the difference between the following functions:
plt.plot([1,2,3,4]), plt.plot([1,2,3,4], [1,4,9,16]).
Section-C
Answer the following questions (3 Marks)
g
1. Draw the output for the following data visualization plot.
import matplotlib.pyplot as plt
g 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')
g plt.ylabel('bar height')
plt.title('Epic Graph\nAnother Line! Whoa')
plt.show()
OUTPUT:
i . O .Orgrg
a i
d a
d saaslala
a
.P.Pa
wwww
ww
l a i .Org
a d asa
w.P
ww
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.
131
3. Write the plot for the following pie chart output.
i . O . rgrg
O
la l a i
a d
a adsaasa
.P.P
ww
ww
ww
i .O . rgrg
O
l al a i
a d
a adsaasa
.P.P
ww
ww
ww
132
A Line Chart is often used to visualize a trend in data over intervals of time – a time series – thus
the line is often drawn chronologically.
Example:
import matplotlib.pyplot as plt
years = [2014, 2015, 2016, 2017, 2018]
total_populations = [8939007, 8954518, 8960387, 8956741, 8943721]
plt.plot (years, total_populations)
plt.title ("Year vs Population in India")
plt.xlabel ("Year")
plt.ylabel ("Total Population")
plt.show()
In this program,
Plt.title() → specifies title to the graph
Plt.xlabel() → specifies label for X-axis
Plt.ylabel() → specifies label for Y-axis
Output:
i .O . rgrg
O
l al a i
a daadsaasa
ww.P.P
ww
ww
i .O . rgrg
O
aal al a i
P a daadsas
ww. .P
ww
ww
i .O . rgrg
O
a i
d adsaaslala
a
.P.Pa
w ww
w
ww
g
Bar Chart:
A BarPlot (or BarChart) is one of the most common type of plot.
It shows the relationship between a numerical variable and a categorical variable.
Bar chart represents categorical data with rectangular i .O . rgrg
bars.
O
l al a i
Each bar has a height corresponds to the value
a d itasrepresents.
adsa a
.P.P a
The bars can be plotted vertically w
orw ww
whorizontally.
w
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
133
Example:
import matplotlib.pyplot as plt
labels = ["TAMIL", "ENGLISH", "MATHS", "PHYSICS", "CHEMISTRY", "CS"]
usage = [79.8, 67.3, 77.8, 68.4, 70.2, 88.5]
l ai .Org
y_positions = range (len(labels))
plt.bar (y_positions,d sa
ausage)
.P a
ww
plt.xticksw(y_positions, labels)
plt.ylabel ("RANGE")
plt.title ("MARKS")
plt.show()
Output:
i . O . rgrg
O
l al a i
a d
a adsaasa
.P.P
ww
ww
ww
i.O . rgrg
O
l al a i
a d
a adsaasa
.P.P
ww
ww
ww
134
Example:
import matplotlib.pyplot as plt
sizes = [89, 80, 90, 100, 75]
.O Ogrg
r"Maths",
labels = ["Tamil", "English",
l alia i . "Science", "Social"]
a s a
s a
ada=dalabels, autopct = "%.2f ")
plt.pie (sizes, labels
.P.P
www w
plt.axes().set_aspect ("equal")
ww
plt.show()
i . O . rgrg
O
a i
d adsaaslala
a
.P.Pa
wwww
ww
i . O .Orgrg
l al a i
a d
a adsaasa
.P.P
ww
ww
ww
135
Save Figure:
This button will allow you to save your figure in various forms.
136