12th PYTHON Chapter 1 to 16

You might also like

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

NAME : ________________________

CLASS & SEC : ________________________

SUBJECT : ________________________

INDEX
1
Chapters Chapters Page No

No 2&3 5 Marks
Marks
Function
1.
2. Data Abstraction

3. Scoping

4. Algorithm strategies

5. python variables and operators

6. Control structures

7. Python Function

8. String and String Manipulation

9. List,Tuples ,Sets, Dictionary

10. Classes and Objects

5 Marks Questions only

One Marks (Book Back questions)

One Marks (Interior questions)

2
Unit I - CHAPTER 1. Function
========================================================
2 Mark: (Book Back Questions)

1. What is a subroutines? *
 Subroutines are the basic building blocks of computer programs.
 It is a small section of code.
 It is used to perform a particular task.
 It can be used repeatedly.

2. Define function with respect to programming language. *


 A function is a unit of code.
 It contains a set of code.
 It works on many kinds of inputs, like variants, expressions and produces concrete output.

3. Write the inference you get from X : = (78) *


 X: = (78) has an expression in it.
 But (78) is not an expression.
 It is a function definition.
 In this case the value 78 being bound to the name X.

4. Differentiate interface and implementation. *

Interface Implementations
It just defines what an object can do. It carries out the instructions defined in
But won‟t actually do it the interface.

5. Which of the following is a normal function definition and which is recursive


function definition?
 let rec sum xy:
return x+y Ans : Recursive function

 let disp:
print „welcome‟ Ans : Normal function

 let rec sum num:


f (num ! =0) then return num+sum (num-1) Ans : Recursive function
else:
return num
3
3 Marks: (Book Back Questions)
6. Mention the characteristics of interface. *
 Class template specifies interfaces to enable an object to be created and operate properly.
 An object‟s attributes and behaviour is controlled by sending functions to the object.

7. Why strlen is called pure function? *


 strlen is a pure function.
 Because the function takes one variable as parameter.
 It access the variable and find its length.
 It does not change it, and the value returned derived from the external memory accessed.

8. What is the side effect of impure function. (or)


What happen if you modify a variable outside the function? Give example. *

• The most popular side effect is “modifying the variable outside of function”.
Ex :
y:=0
let inc (x:int): int:=
y:= y+x
return (y)

 The value of y get changed inside the function definition due to which the result will
change each time.
 Impure function doesn‟t take any arguments and it doesn‟t return any value.

9. Differentiate pure and impure function . *

Pure function Impure function


1. Return value -- solely depends on its Return value --does not solely depend on its
arguments passed. arguments passed.

2. Do not modify the arguments which Modify the arguments which are passed to
are passed to them. them.
3. Do not have side effects. Have side effects.
4. Give exact result when the same Never assure that the function will behave the
arguments are passed. same every time its called.
5. Ex: strlen(), sqrt() Ex: random(), date()

4
Additional 2 Marks & 3 Marks questions:
11. What is definition? *
 It binds values to names.
 It is a distinct syntactic blocks.
 It can have expressions nested inside them and vice – versa.

12. Define parameters.


 Parameters are the variables in a function definition.
13. Define Arguments.
 Arguments are the values which are passed to a function definition.

14. What are the two types of function specification? *


1. Parameter without type
2. Parameter with type

15. What is the syntax for function definition? *


 It is introduced by the keyword “let”
 Followed by the name of the function and its arguments.
Syntax :
let fn a1…an : = K

Ex: let odd x :=

16. How the recursive function is defined? *


 It is defined by the keyword “let rec”
 Followed by the name of the function and its arguments.
Syntax:
let rec fn a1…an : = K

17. Define Object. *


 An object is an instance.
 It is created from the class.
 Interface defines an object‟s visibility to the outside world.
18. What is algorithm? *
 It is a finite set of instruction to accomplish a particular task.
 It is a step by step instruction to solve a particular task.
 It is expressed using statement of programming language.
 It helps the programmer to develop the program.

5
19. Write an algorithm to find the factorial of a number.

(requires : n>=0)
let rec fact n:=
if n=0 then 1
else
n*fact(n-1)

20. What are various syntax for function types?


1. x → y (x is input and y is output)
2. x1 → x2 → y (x1 and x2 are input and y are output)
3. x1→ …→ xn → y (x1 ... xn are input and y are output)

21. Give the advantage of pure functions?


 If a function is pure, then if it is called several times with the same arguments ,
the compiler only needs to actually call the function once.

22. Explain about random () function.


• random () is a mathematical function.
• It will give different outputs for the same function call.
Ex:

let randomnumber :=
a:= random()
if a >10 then
return: a
else
return : 10

• Here the random() function is impure .


• It is not sure what will be the result when we call the function.

23. Write the function that finds the minimum of its three arguments.
let min x y z :=
if x < y then
if x < z then x else z
else
if y < z then y else z

6
24. What happen if you modify a variable outside the function? Give example. *
 The most popular side effects is modifying the variable outside of function.
Ex:
y:=0
let inc (x:int):int :=
y:= y+x
return (y)

Here, result of inc() will change every time,


if the value of “y‟ get changed inside the function definition.
 Hence, side effect of inc () function is changing the data of the external variable “y‟.

5 Marks: (Book Back Questions)


1. What are called parameters and write a note on i) parameter without type *
ii) parameter with type.
(OR)
Explain about the function specification. *
Parameters  Variable in a function definition .
Arguments  Values which are passed to a function definition.
i) parameter without type:
 The Datatype of variable is not mentioned explicitly .
Ex:
(requires : b>=0)
(returns: a to the power of b)
let rec pow a b:=
if b=0 then 1
else
a * pow a(b-1)

Program explanation:
 Precondition (requires)
 Post condition (returns) Given

 In the function definition,


 variable b is the parameter .
 The value which is passed to the variable b is the argument.
 some language compiler solves this type data type inference problem algorithmically.

7
ii) Parameter with type :
 The Datatype of variable is mentioned explicitly.

Ex:
(requires : b>=0)
(returns: a to the power of b)
let rec pow (a: int) (b: int) : int:=
if b=0 then 1
else
a * pow a(b-1)

Program explanation:
 parentheses ( ) are mandatory for „a‟ and „b‟. (mandatorymust)
 We want to explicitly write down data types.
 Explicitly annotating the data types can help with debugging such an error message.
 This is useful on times when we get a type error from the compiler.

2. Identify in the following program: * (Book Back)

let rec gcd a b :=


if b <> 0 then gcd b (a mod b) else return a

Questions:
(i) Name of the function .
Ans: „gcd‟

(ii) Identify the statement which tells it is a recursive function


Ans: rec

(iii) Name of the argument variable.


Ans: a, b

(iv) Statement which invoke the function recursively.


Ans: (a mod b)

(v) Statement which terminates the recursion.


Ans: return a

8
3. Explain with example pure and impure functions. *
Pure functions :
 Pure functions are functions.
 A function can be pure function provided it should not have any external variable.
 It will alter the behaviour of that variable.
 It will give exact result when the same arguments are passed.
 Do not have side effects.
 Do not modify the arguments which are passed to them.
 Return value –solely depends on its arguments passed.
Ex:
let square x:=
return : x*x

 square is a pure function.


 Because it will not give different results for same input.

Advantage:
 It is called several times with the same arguments, the compiler only needs to actually
call the function once.

Impure functions:
 Variables used inside the function may cause side effects though the functions which
are not passed with any arguments.
 In such cases the function is called impure function.
 Have side effects.
 Modify the arguments which are passed to them.
 Return value – does not solely depends on its arguments passed.
 When a function depends on variables or functions outside of its definition block
 We can never be sure that the function will behave the same function call.
Ex:

let randomnumber :=
a: = random()
if a >10 then
return: a
else
return:10
 random() is impure function, the result is not same when we call.

9
4. Explain with an example interface and implementation. *
Interface :
 It is a set of action that an object can do, but won‟t actually do it.
 In OOPs, an interface is a description of all functions.
Purpose: Allow the computer to enforce the properties of the class.

Characteristics of interface:
i) Class template specifies to enable an object to be created and operated properly.
ii) An object‟s attributes and behaviour is controlled by sending functions to the object.

For example:
o when you press a light switch, the light goes on,
o We may not have cared, how it splashed the light

 In our example, Anything that "ACTS LIKE" a light, should have function definitions
like
(i) turn_on ()
(ii) turn_off ()
Implementation :
 It carries out the instructions defined in the interface.
 In object oriented programs,
 classes are the interface and
 how the object is processed and executed is the implementation

For example: Let‟s take the example of increasing a car‟s speed.

 The person who drives the car doesn‟t care about the internal working.
 To increase the car speed, he just presses the accelerator to get the desired behaviour.
 Here Accelerator is the interface between the driver and the engine.
10
 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, and
electricity come together to create the power to move the vehicle. All of these actions are
separated from the driver, who just wants to go faster.
 Thus we separate interface from implementation.

Additional 5 Mark Questions:


5. Explain in detail about chameleons of chromeland problem using function.
 There are two types of chameleons are equal in number.
 Construct an algorithm that arranges meetings between these two types.
 so that they change their colour to the third type.
 In the end, all should display the same colour.
 Let us represent the number of chameleons of each type by variables a, b and c.
 Their initial values by A, B and C respectively.
 Let a=b be the input properly.
 The input-output relation is a=b=0 and c=A+B+C.
 Let us name the algorithm monochromatize.
 The algorithm can be specified as monochromatize (a,b,c)

 In each iterative step,


 Two chameleons of the two types (equal in number) meet and
change their colors to the third one .
Ex: If A, B, C = 4, 4, 6 then the series of meeting will result in.

 In each meeting, a and b each decreases by 1 and c increased by 2.


 The solution can be expressed as an iterative algorithm.

11
UNIT I - CHAPTER 2. Data Abstraction
========================================================
2 Marks: (Book Back Questions)
1. What is abstract data type? *
ADT  Abstract Data Type.
 ADT is type for objects .
 Its behaviour is defined by a set of value and a set of operations.
 Classes are the representation for abstract Data Type.

2. Differentiate constructors and selectors. *


s.no Constructors Selectors
1 To Build the abstract data type To Retrieve information from the data type.
2 Create an object and bundling together Extract individual pieces of information
different pieces of information from the object.

3. What is a pair? Give an example. *


 Any way of bundling two values together into one, can be considered as pair.
 List can be called as pairs.
Ex:
list [(0,0) , (1,20)]

4. What is a List? Give an example. *


 A List is a sequence of values separated by comma surrounded with square brackets[].
(or)
 List is constructed by placing expressions separated by commas with square brackets[]
 List can store multiple values.
Ex:
list:=[10, 20]
x,y :=1ist

5. What is a Tuple? Give an example. *


 A tuple is a sequence of values separated by comma surrounded with parentheses( ).
Ex:
colour = („red‟, „blue‟, „green‟)

12
3 Marks: (Book Back Questions)
6. Differentiate concrete data type and abstract datatype. *
Concrete data type Abstract data type
1 It is a data type whose representation is It is a data type whose representation is
known. unknown.
2 Direct implementations of a relatively A high level view of a concept independent of
simple its implementation.

7. Which strategy is used for program designing? Define that strategy. *


 Wishful thinking is a powerful strategy.
 It is used for designing programs.
 It is the formation of beliefs and making decisions according to what might be pleasing to
imagine instead of by appealing to reality.

8. Identify which of the following are constructors and selectors? *


a) N1 := number() Ans : constructor
b) accetnum (n1) Ans : selector
c) displaynum(n1) Ans : selector
d) eval(a/b) Ans : selector
e) x,y = makelopse(m), makeslope(n) Ans : constructor
f) display() Ans : selector

9. What are the different ways to access the elements of a list .Give example.
• List elements can be accessed in two ways.

1. Multiple Assignment:
 It unpacks a list into its elements and binds each element to a different name.
Ex:
list :=[10,20]
x,y := list

 x will become10 and y will become 20.

2. Element Selection Operator:


 It is expressed using square brackets.

13
 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.
Ex:
list [0]
10
list[1]
20

10. Identify which of the following are List, Tuple and Class?
a) arr[1,2,3,4]  List
b) arr(1,2,3,4)  Tuple
c) student [rno, name, mark]  Class
d) day = („sun‟,‟mon‟, „tue‟, „wed‟)  Tuple
e) x=[2,5,6.5,[5,6],8.2]  List
f) employee [eno, ename, esal, eaddress]  Class

Additional 2 Marks & 3 Marks Questions :


11. What is data abstraction? *
 Data abstraction is a powerful concept.
 It allows programmers to treat code as objects.

12. Define modularity. What will provides it? *


 Modularity means splitting a program into many modules.
 It provides modularity.

13. What is abstraction? *


 It is the process of providing only the essentials and hiding the details.

14. How will you implement ADT?


 There can be different ways to implement an ADT.
o List ADT can be implemented using singly linked list or doubly linked list.
o Stack ADT and queue ADT can be implemented using list.

15. How will you facilitate data abstraction? *


 To facilitate data abstraction by two types of functions:
1. Constructors
2. Selectors.

14
16. What is selector? Give an example. *
 Selectors are functions .
 It retrieves information from the data type.
 Extract individual pieces of information from the object.
Ex:
Get name (city)
Get lat (city)
Get lon(city)

17. What is the function of constructor? *


 Constructors are functions
 It builds the abstract data type.
 Create an object and bundling together different pieces of information
Ex:
city = makecity(name, lat, lon)

 The function which creates the object of the city is the constructor.

18. What is the basic idea of data abstraction?


 To structure programs so that they operate on abstract data.

19. How many parts are there in a program? What are they?
They are two parts in a program.
i) Operates on abstract data.
ii) Defines a concrete representations.

20. What is meant by list literal? *


List is constructed by placing an expressions within square brackets separated by commas
is called a list literal.

21. Identify which is the constructor and selector from the following statement.
i) The function that retrieve information from the datatype - Selector
ii) The function which creates an object. - Constructor

15
5 Marks : (Book Back Questions)
1. How will you facilitate the data abstraction explain? * (Book Back)
Data abstraction:
 It is a powerful concept.
 It allows programmers to treat code as object.
Abstraction:
 It is the process of providing only the essentials and hiding the details.
 Abstraction provides modularity.
Modularity:
 It means splitting a program into many modules.
 classes (structures) are the representation for abstract data type.

ADT:
ADT Abstraction data type
 It is a type for object whose behaviour is defined by set of value and operations.
 To facilitate the data abstraction,
 we will need to create two types of function,
i) Constructor
ii) Selector

Constructor:
 Constructors are functions
 It builds the abstract data type.
 Create an object and bundling together different pieces of information
Ex:
city = makecity (name, lat, lon)
makecity  constructor
city  object

16
Selectors:
 Selectors are function.
 It retrieve the information from data type.
 It extract individual pieces of information from the object.

 get name(city)
 get lat(city) selectors
 get lon(city)

2. What is list? why list called as pairs? Explain with suitable example . *(Book Back)
 List is constructed by placing expression within square brackets [ ] separated by commas.
 An expression is called a list literal.
 List can store multiple values.
 Each value can be of any type and can even be another list.

Pair:
 Bundling two values together into one can be considered as pair.
 List can be called as pairs.

Ex: list [ (0,10), (1,20) ]


where
( 0 , 10 ) ( 1 , 20 )

Index position value Index position value

 Elements of list can be accessed in two ways.


 Multiple assignment (:=)
 Using element selection operator( [ ] ).

17
Multiple assignment :
 It is familar method.
 It unpacks a list into its elements and binds each element to a different name.
Ex:
list : = [10, 20]
x,y := list
(i.e) x:= 10, y:= 20

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.
Ex: list : = [10, 20]

list [0] (i.e) 10


list [1] (i.e) 20

3. How will you access the multi item. Explain. * (Book Back)
 The structure construct (In OOP languages it's called class construct) to represent multi-
part objects where each part is named (given a name).

pseudo code New data type Person is pictorially represented as


class Person:
creation( )
firstName := " "
lastName := " "
id := " "
email := " "

Explanation:
Person → Class name (multipart item)
Creation → Function
First name
Last name variable of new datatype.
Id
e-mail
P1:= person() → creating the object
18
First name := “xxx”
Last name :=”yyy” setting the value
Id := “92-31”
email id := “abc@gmail.com”

 Person is referred to as a class or a type


 p1 is referred to as an object or an instance.

 In the case of something more complex, like a person,


we have a multi- item object where each 'item' is a named thing:
firstName, lastName, id, and email.
One could use a list to represent a person:
person=['Padmashri', 'Baskar', '994- 222-1234', 'compsci@gmail.com']

 Multi item can be accessed using structure.


 The class construct the form for multipart objects.
 The class (structure) construct defines the form for multi-part objects .
 It represents a person.
 Its definition adds a new data type.
 In this case, a type named Person.
 Once defined, we can create new variables (instances) of the type.
 A class has bundled data and functions.
 Class defines a data abstraction by grouping related data items.
 A class is not just data, it has functions defined within it.
 We say such functions are subordinate to the class

19
Additional 5 Marks Questions:
4. What is tuple? Explain it.
 Tuple is a sequence of values separted by comma enclosed with parenthesis ( ).
 Tuple is similar to list.
 The elements cannot be changed in tuple.
 But we change the elements in list.
 Square bracket [ ] is used to access the data stored in pair.
 Note: square bracket notation is used to access the data you stored in the pair.
 The data is zero indexed, meaning we access the
o first element with nums[0]
o second element with nums[1]

Ex : colour :=('Red‟, „Green‟, „Blue‟)

Representation Tuple as a Pair


Ex:
nums:=(1,2)

num[0]→1
num[1] →2
• data index 0 represents first value .
• data index 1 represent second values

20
Unit I - CHAPTER 3. Scoping
=================================================
2 Marks: (Book Back Questions)

1. What is scope? *
 It refers to visibility of variable, parameter and function in one part of the program to
another part of same program.

2. Why scope should be used for variable state reason?


 Scope should be used for a variable because every part of the program can access the
variable.
 Scope defines the order,” in which variable have to be mapped to the object “,in order to
obtain a value.

3. What is mapping? *
 The process of binding variable name with object is called mapping.
 = (equal to) is used in programming languages to map the variable and object

4. What do you mean by namespace? *


 Name spaces are container for mapping name of variable to object.

5. How python represent private and protected access specifies? *


 Python prescribes a convention.
 Prefixing name of variable / method with single (or) double underscore to emulate (follow)
the behaviour of private & protected access specifier.

3 Marks: (Book Back Questions)


6. Define local scope with example.
 A variable which is defined in current function is called as local scope.
Ex:

21
7. Define global scope with example.
 A variable is declared outside of all function is called as global variable .
 Global variable is accessed inside or outside of all the functions in a program.
Ex :

8. What is enclosed scope with example?

 A variable is declared inside a function which contains another function definition


is called as enclosed scope.
 The inner function can also access the variable of the outer function.
Ex:

9. Why access control is required? *


 It is a security technique.
 It regulates who or what can view or use resource in a computing environment.

10. Identify the scope of the variables in the following pseudo code and write its output.
color:= Red
mycolor():
b:=Blue
myfavcolor():
g:=Green Output:
printcolor b, g Red Blue Green
myfavcolor() Red Blue
printcolor b Red
mycolor()
print color

22
Scope of variables:

Variables Scope
Color:=Red Global
B:=Blue Enclosed
G:=Green Local

Additional 2 Marks & 3 Marks questions:


11. List out the types of scope. *
1. Local scope
2. Global scope
3. Enclosed scope
4. Built in scope

12. What is built in scope with example?


 It is a widest scope.
 It has all names are preloaded into program scope.
 Any variable or function which is defined in the modules of a programming language has
Built-in or module scope.
 They are loaded as soon as the library files are imported to the program
Ex:

13. What is LEGB Rule? *


 It is used to decide the order in which the scopes are to be searched for scope resolution.

14. What is module? *


 A module is a part of program.
 Programs are composed of one or more independently developed modules.

15. What is Access control? *


 It is a security technique.
 It regulates who or what can view or use resources in a computing environment.
 It is a fundamental concept in security.
 It minimizes the risk to the object.
23
16. What are the access control available? Explain.
Private → Accessed only within the class.
Protected → Accessed only within class and sub class.
Public → Accessed outside the class also.

17. What is nested function?


 A function (method) with in another function is called nested function.

18. Define modular programming.


 The process of subdividing a computer program into separate sub-programs is called Modular
programming.

19. Write the advantages of modules.


 Modular programming enables programmers to divide up the work and debug pieces of the
program independently.

20. How the variables are prioritized?

21. What is the principle of data encapsulation?


 Arrangement of private instance variables and public methods ensures the principle of
data encapsulation.

24
5 Marks: (Book Back Questions)
1. Explain the types of scopes for variable (or) explain LEGB rule with explain?

LEGB Rule:
 It is used to decide the order in which the scopes are to be searched for scope resolution.
Scope:
 It refers to visibility of variable, parameter and function in one part of the program to
another part of same program.
Types of scope:

1. Local scope Defined inside function/class


2. Global scope Defined inside enclosing functions (Nested function concept)
3. Enclosed scope Defined at the uppermost level
4. Built in scope Reserved names in built-in functions (modules)

Local scope
 It is a variable defined in current function.
Ex:

Global scope:
 It is a variable is declared outside of all function in a program.
 Global variable is accessed inside or outside of all the functions in a program.
Ex:

25
Enclosed scope:
 It is 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.
Ex:

Built in scope:
 It is a widest scope.
 It has all names are preloaded into program scope.
 Any variable or function which is defined in the modules of a programming language has
Built-in or module scope.
 They are loaded as soon as the library files are imported to the program
Ex:

2. Write any Five characteristics of Modules.

1. Modules contain instructions, processing logic and data.


2. Module is separately compiled and stored in a library.
3. Module is included in a program.
4. Module segments can be used by invoking a name and some parameters.
5. Module segments can be used by other modules.

26
3. Write any five benefits in modular programming.
1. Less code to be written.
2. The code is stored across multiple files.
3. Code is short, simple and easy to understand.
4. The same code can be used in many applications.
5. The scoping of variables can easily be controlled.
6. Programs can be designed more easily .
Because a small team deals with only a small part of the entire code.
7. A single procedure can be developed for reuse, eliminating the need to retype the
code many times.
8. Errors can easily be identified, as they are localized to a subroutine or function.
9. It allows many programmers to collaborate on the same application.
(OR)

1. Less code to be written.


2. Single procedure can be reuse many times.
3. Programs designed easily.
4. Many programmers for same application.
5. Stored multiple files.
6. Errors easily identify.
7. Used by many application
8. Scope easily controlled

27
UNIT – I - CHAPTER 4. Algorithmic Strategies
===================================================
2 Marks : (Book Back Questions)

1. What is an algorithm? *
 It is a finite set of instruction to accomplish a particular task.
 It is a step by step instruction to solve a particular task.
 It is expressed using statement of programming language.
 It helps the programmer to develop the program.

2. Write the phases of performance evaluation of an algorithm.


 It can be divided into two different phases:
1) A Priori estimates:
 This is a theoretical performance analysis of an algorithm.
 Efficiency of an algorithm is measured by assuming the external factors.
2) A Posteriori testing:
 This is called performance measurement.
 Here, actual statistics like running time and required for the algorithm executions
are collected.
3. What is Insertion sort?
 It is a simple sorting algorithm.
 It works by taking elements from the list one by one.
 Then, inserting to correct position into a new sorted list.
 This algorithm uses n-1 number of passes to get the final sorted list.
4. What is sorting?*
 It is the process of arranging all the elements in the list.
Two Types:
1) Bubble sort
2) Insertion sort
3) Selection sort
5. What is searching? Write its types. *
 It is the process of find the elements in the list.
Two Types:
1) Linear search
2) Binary search

28
3 Marks: (Book Back Questions)
6. List the characteristics of an algorithm. *
1. Input 7. Simplicity
2. Output 8. Unambiguous
3. Finiteness 9. Feasibility
4. Definiteness 10. Portability
5. Effectiveness 11. Independent
6. Correctness

7. Discuss about algorithm complexity and its types. *


 Algorithm complexity depends on size of data, time and space.
Two types:
1) Time complexity
2) Space complexity

8. What are the factors that influence time and space complexity? *
1) Time complexity: Number of steps taken by the algorithm to complete the process.
2) Space complexity: Amount of memory required to run to its completion.
9. Write a note on Asymptotic notation. *
 It is languages.
 It uses meaningful statements about time and space complexity.
 Asymptotic notations are used to represent time complexity of algorithms.
 They are 3 types:

i) Big O:
 Big O used to describe the worst-case of an algorithm.
 It is used to describe the upper bound (worst - case) of a asymptotic function,
ii) Big Ω:
 Big Omega is the reverse Big O.
 It is used to describe the lower bound (best-case) of a asymptotic function.

iii) Big Θ:
 When an algorithm has a complexity with lower bound = upper bound,
 Algorithm complexity: O (n log n) and Ω (n log n)
 Actual Algorithm complexity: Θ (n log n)
 (i.e) Running time of that algorithm: n log n in the best-case and worst-case

29
10. What do you understand by Dynamic programming? *
 It is an algorithmic design method.
 It can be used when the solution to a problem can be viewed as the result of a sequence of
decisions.

Additional 2 Marks & 3 Marks Questions:


11. Who is an algorist? *
 The person who develops and write programs is called algorist.

12. How the data are maintained?


 Data are maintained and manipulated effectively through data structures.
13. Why algorithms are developed?
 Algorithms can be developed to store, manipulate and retrieve data from such data
structures.
14. Give some examples for data structures.
 Arrays
 Structures
 List
 Tuples
 Dictionary

15. Where does the word algorithm comes from?

 The word Algorithm comes from the name of a Persian author,


- Abu Jafar Mohammed ibn Musa al Khowarizmi(c. 825 AD(CE)),
 He wrote a textbook on mathematics.
 The word “Algorithm” has come to refer to a method to solve a problem.

16. Define algorithmic strategy.


 The way of defining an algorithm is called algorithmic strategy.

17. What is an algorithmic solution?


 An algorithm that yields expected output for a valid input is called an algorithmic solution.

18. Draw the pictorial representation of typical algorithm.

30
19. Define pseudo code. *
 It is a method of planning the solution, the programmer to plan without syntax.

20. Write the difference between Algorithm and Program.


s.no Algorithm Program
1. It helps to solve a given problem logically. It expression in a programming language
2. It based on their implementation methods, It is implemented by structured or object
design techniques, etc oriented programming approach.
3. No specific rules are followed specific rules(syntax) are followed
4. Resembles a pseudo code. Specific to a programming language.

21. Define efficiency of an algorithm.


 Efficiency of an algorithm is defined by the utilization of time and space complexity.

22. How the efficiency of an algorithm measured?


 It can be measured based on the usage of different resources.

23. How the efficiency of an algorithm maximized?


 For maximum efficiency of algorithm we wish to minimize resource usage.

24. What is meant by running time?


 The running time of an operation is calculated as how many programming instructions
executed per operation.

25. What is called algorithm analysis?


 An estimation of the time and space complexities of an algorithm for varying input sizes
is called algorithm analysis.

26. Name the two factors, which decides the efficiency of an algorithm.
i) Time factor
ii) Space factor

27. How time factor is measured?


 It is measured by counting the number of key operations like comparisons in the sorting
algorithm.
28. How space factor is measured?
 It is measured by the maximum memory space required by the algorithm.

31
29. What is complexity?
 The complexity of an algorithm f(n) gives the running time and/or the storage space required
by the algorithm in terms of n as the size of input data.

30. How the space complexity is divided?


 It is divided into 2 parts.
1) Fixed part
2) Variable part

31. Define fixed part in space complexity.


 It is defined as the total space required to store certain data and variables for an algorithm.
Ex: simple variables and constants used in an algorithm.

32. Define variable part in space complexity.


 It is defined as the total space required by variables
 The sizes depends on the problem and its iteration.
Ex: recursion used to calculate factorial of a given value n.

33. What are the important resources that cannot be compared directly?

o Time complexity
cannot be compared directly
o space complexity

34. What are the factors that measure the execution time of the algorithm.
 Speed of the machine
 Compiler and other system Software tools
 Operating System
 Programming language used
 Volume of data required

35. What is space-Time trade off? (or) what is Time-memory trade off?
 It is a way of solving in less time by using more storage space or
by solving a given algorithm in very little space by using spending more time.

36. Which is the best algorithm?


 The best algorithm requires less space in memory and takes less time to execute its
instructions to generate output to solving he given problem.

32
37. Define Big O.
 Big O used to describe the worst-case of an algorithm.
 It is used to describe the upper bound (worst - case) of an asymptotic function.

38. Define Big Ω.

 Big Omega is the reverse Big O.


 It is used to describe the lower bound (best-case) of an asymptotic function.

39. Define Big Θ.


 When an algorithm has a complexity with lower bound = upper bound,
 Algorithm complexity: O (n log n) and Ω (n log n)
 Actual Algorithm complexity: Θ (n log n)
 (i.e) Running time of that algorithm: n log n in the best-case and worst-case.

40. What is linear search algorithm?


 It called as sequential search.
 It finds a particular value in a list.
 It search the element in sequence until the desired element is found or the list is
exhausted.
 Here, list need not be ordered.

41. What is binary search algorithm?


 It is called as Half – interval search algorithm
(or)
Mid way search
(or)
Divide and conquer search algorithm
 It finds the position of a search element within a sorted array.
 It executes in logarithmic time.
Find Mid value : Formula:

Mid= low + ( high – low)/2

42. What is bubble sort algorithm?


 It is a simple sorting algorithm.
 It starts at the beginning of the list of values stored in an array.
 It is a comparison sort.

33
 It compares each pair of adjacent elements.
 If the list elements are in unsorted order “ Swaps them “ .
 If the list elements are in sorted order, ” No swaps are needed“.
 So, smaller elements “bubble” to the top of the list.
Disadvantage:
 Too slow
 Less efficient

43. What is selection sort algorithm?


 It is a simple sorting algorithm.
 It improves the performance of the bubble sort,
by making one exchange for every pass through the list.
 It first finds the smallest element in array.
 Then swap it with the element in the first position of an array.
 Repeat until the array is sorted.
 It repeatedly selects the next smallest element.
 Then swaps it into the right place for every pass. It is called as selection.

44. Define memorization/ memoization.


 It is an optimization technique.
 It used primarily to speed up computer programs by storing the results of previous
function calls and returning the cached result when the same inputs occur again

45. Define Dynamic programming.


 It is an algorithmic design method.
 It can be used when the solution to a problem can be viewed as the result of a sequence of
decisions.
 It is similar to divide and conquer.
 It used to find the solution in optimized way.

46. Write the steps to do Dynamic programming.


1. The given problem will be divided into smaller overlapping sub-problems
2. An optimum solution for the given problem can be achieved by using result of smaller
sub-problem.
3. Dynamic algorithms uses Memoization

34
5 Marks: (Book Back Questions)
1. Explain the characteristics of an algorithm? * (Book Back)
Input : Zero or more quantities to be supplied.
Output: At least one quantity is produced.
Finiteness : It must terminate after finite number of steps.
Definiteness : All operations should be well defined. (Operation involving division by
zero or taking square root for negative number are unacceptable).
Effectiveness : Every instruction must be carried out effectively.
Correctness: It should be error free.
Simplicity: Easy to implement.
Unambiguous: It should be clear and unambiguous. (Each of its steps and their
input /output should be clear and must lead to only one meaning).
Feasibility : It Should be feasible with the available resources.
Independent : It should have step-by-step directions.
It should be independent of any programming code.
Portable : It should be genetic, independent of any Programming language or
an OS able to handle all range of inputs.

2. Discuss about linear search algorithm. * (Book Back)


 It called as sequential search.
 It finds a particular value in a list.
 It search the element in sequence until the desired element is found or the list is
exhausted.
 Here, list need not be ordered.
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.
3. If the values match, display the current index and its array value.
4. If the values are not match, move on to the next array element.
5. If no match is found, display the “search element is not found”
Ex: Input: values[ ] = { 20, 50, 30, 40, 10}
Target=40
Index value 0 1 2 3 4
Value 20 50 30 40 10

Output: 3

35
3. What is Binary search? Discuss with example. * (Book Back)

 It is called as half – interval search algorithm


(or)
Mid way search algorithm
(or)
Divide and conquer search algorithm

 It finds the position of a search element within a sorted array.


 It executes in logarithmic time.
Pseudo code :
1. Start with the middle element.
 If the “search element is” equal to ”middle element of the array“
return the index of the “middle element“.

 If not, then compare the middle element with search value.

 If the search element is “greater than” the number in the middle index,
then select the elements to the “right side“ and goto step -1

 If the search element is “less than” the number in the middle index,
then select the elements to the “left side“ and goto step -1

2. If match is found, display “success message with the index”.


3. If match is not found, display “unsuccessful message”.
Example :
Index value 0 1 2 3 4
Value 10 20 30 40 50

Assume, search element is 30.

Find Mid value : formula:

Mid= low + ( high – low)/2

Here, Mid = low + ( high – low)/2


= 0 + ( 4 - 0) / 2
= 0 + 4/2
=4/2
Mid = 2

36
 So, 2 is the mid value of the array.
 Now, we compare the value stored at location 2 with search element(30).
 We found that it is a match.
 We can conclude that,
Search element is 30
Location/index is 2

-------------------------------------------------------------------------------------------------------

 Working principles:
1. List of elements in an array must be sorted.
2. Consider the following array elements.
Index value 0 1 2 3 4
Value 10 20 30 40 50

Let us assume that the search element is 40.

3. First, we find index of middle element of the array.

Find Mid value - Formula:

Mid= low + ( high – low)/2

Mid = low + ( high – low)/2


= 0 + ( 4 - 0) / 2
= 0 + 4/2
= 4/2
Mid value = 2

4. Now, we compare the value stored at index-2 with our search value-40
 The value stored at index-2 is 30
 Search value is 40
 So, it is not match with search element.
 The search value 40 is greater than 30.

5. So, Select the elements to the Right side


Now we change our low to mid + 1 and find the new mid value again.

low = mid + 1
37
mid = low + (high - low) / 2
= 3 + (4-3)/2
= 3 + 1/2
= 3 + 0.5
= 3.5 (fraction ignored)
Mid value = 3

6. Our New mid is 3 now.


We compare the value stored at index-3 with our search value -40

Index value 0 1 2 3 4
Value 10 20 30 40 50
7. We found that, it is a match.
8. We conclude that ,
Search element is 40
Location / Index is 3

4. Explain the bubble sort algorithm with example. * (Book Back)

 It is a simple sorting algorithm.


 It starts at the beginning of the list of values stored in an array.
 It is a comparison sort.
 It compares each pair of adjacent elements.
 If the list elements are in unsorted order “ Swaps them ”.
 If the list elements are in sorted order, “ No swaps are needed”.
 So, smaller elements “bubble” to the top of the list.
Disadvantage:
 Too slow
 Less efficient
Pseudo code :
1. Start with first element (i.e., index =0)
2. compare the “current element” with the “next element” of array.
3. If the current element is “greater than” the next element, “Swap them”.
4. If the current element is “Less than” then next or right side of the element,
Move to the next element.
5. Go to step-1 and Repeat until the array is sorted.

38
Example:
 Let's consider an array with values {15, 11, 16, 12, 14, 13}.
 The pictorial representation of how bubble sort will sort the given array.

 This above example is for iteration1.


 Similarly remaining iteration can be done.
 The final iteration will give the sorted array.

11 12 13 14 15 16

----------------------------------------------------------------------------------------------------------------------
(OR)

50 10 30 20 40

50 > 10 First element - 50


So, interchange Next element - 10

10 50 30 20 40

39
5. Explain the concept of Dynamic programming with suitable example. (Book Back)
 It is an algorithmic design method.
 It can be used when the solution to a problem can be viewed as the result of a sequence of
decisions.
 It is similar to divide and conquer.
 It is used problems can be divided into similar sub-problems.
 So that their results can be re-used to complete the process.
 It used to found the solution in optimized way.
 The solutions of overlapped sub-problems are combined in order to get the better solution.

STEPS:
1. The Given problem will be divided into smaller overlapping sub-problems.
2. An optimum solution for the given problem can be achieved by using result of smaller sub-
problem.
3. Dynamic algorithms uses memorization.

Additional 5 Marks question:


6. Discuss about Selection sort algorithm.

 It is a simple sorting algorithm.


 It improves the performance of the bubble sort,
by making one exchange for every pass through the list.
 It finds the first smallest element in array.
 Swap it with the element in the first position of an array.
 Then, find the second smallest element in array.
 Swap it with the element in the second position of an array.
 Repeat until the array is sorted.
 It repeatedly selects the next smallest element.
 Then swaps it into the right place for every pass . It is called as selection.
Pseudo code :
1. Start with first element. ( Index=0) .
Find the smallest element in array.
And swap the smallest element in the first position.
2. Then, we move on to the second element position.
Then look for smallest element present in the sub-array
( from starting to last index)
3. Replace the second smallest in the original array.
( also called first position in the sub array)
4. Repeat until the array is sorted.

40
Ex:
Initial array 1st pass 2nd pass 3rd pass 4th pass
13 11 11 11 11

16 16 13 13 13

11 13 16 14 14
11

14 14 16 15
14
15 15 4 15 16
15
6
6
7. Discuss about Insertion sort algorithm.
 It is a simple sorting algorithm.
 It works by taking elements from the list one by one.
 Then, inserting to correct position into a new sorted list.
 This algorithm uses n-1 number of passes to get the final sorted list.

Pseudo code :
1. If it is the first element, it is already sorted.
2. Pick next element.
3. Compare with all elements in the sorted sub-list.
4. Shift all the elements in the second sub-list that is greater than the value.
5. Insert the value.
6. Repeat until list is sorted.
Ex:
40 10 30 20 Insert 40 (Already sorted list)
10 40 30 20 Insert 40
10 30 40 20 Insert 30
10 20 30 40 Insert 20

41
UNIT – II - CHAPTER 5. Python – Variables And Operators
================================================
2 Marks: (Book Back Questions)
1. What are the different modes that can be used to test python program? *
1. Interactive mode
2. Script mode
2. Write short notes on tokens. *
 Python breaks each logical line into a sequence of elementary lexical component known
as tokens.
1. Identifiers
2. Keywords
3. Operators
4. Delimiters
5. Literals
3. What are the different operators that can be used in python? *
1. Arithmetic operator
2. Relational operator
3. Logical operators
4. Assignment operator
5. Conditional operator
4. What is literal? Explain the types of literals. *
 Literal is a raw data given to a variable or constant.
Types of literals:
1. Numeric (consists digits)
Ex: a=10
2. String ( consists 2 or more characters)
Ex: name= “ sachin “
3. Boolean (consists 2 values. True ,False)
Ex: x=True y=False

5. Write short notes on exponent data. *


 An exponent data contains
1. decimal digit part
2. decimal point
3. exponent part
4. followed by one or more digits.
Ex : 12.e4
12.E4

42
3 Marks: (Book Back Questions)
6. Write short notes on arithmetic operator with examples? *
 It is a mathematical operator .
 It takes two operands and performs a calculation on them.
 It is used for simple arithmetic operation.
Operators : + , - , * , / , % , // ,**
Ex: a+b

7. What are the assignment operators that can be used in python? *


=  Simple assignment operator.
 It is used to assign values(R.H.S) to a variable(L.H.S)
Operators: =, +=, -=, *=, /=, %=, **=, //=
Ex: a=10

8. Explain Ternary operator with example. *


 It is also known as conditional operator.
 It evaluate something based on a condition being True or False
 It replacing the multiline if-else statement.
 It making the code compact.
Syntax :
variable Name = [on_true] if [Test expression] else [on_false]

Ex: min= 10 if 10<20 else 20

Output: 10

9. Write short notes on escape sequences with examples. *


 backslash “ \” is a special character .
 It is also called as “escape character” .
 It is used to represent certain whitespace characters.
“\t”  tab
“\n”  new line
“r”  carriage return

Ex: print (“It\‟s raining”)


Output: It‟s raining

43
10. What are string literals? Explain.
 It is a sequence of characters surrounded by quotes.
 Python supports single or double or Triple quotes for a string.
 A character literal is a single characters surrounded by single or double quotes.
 Multiline string literal values within triple quote „„„ ‟‟‟
Ex: „Apple‟
“Apple”
„„„Apple‟‟‟

Additional 2 Marks & 3 Marks Questions:


11. What are the key features of python? *
 It is a general purpose programming.
 It is used for both scientific and non-scientific programming.
 It is a platform independent programming language.
 Easily readable and understandable.
12. What is identifier? Write down the rules for naming the identifier. *
 An identifier is a name.
 It is used to identify a variable, function, class, module or object.
Ex: num1
_sum

13. Write down the rules for naming the identifier. *


• Must start with an alphabet or underscore.
• May contain digits (0...9)
• case sensitive (uppercase and lowercase letter are distinct)
• Must not be a python keyword.
• Does not allow punctuation character .( %, $, @ etc., Within identifiers)
14. What is keyword? *
 Keywords are special words.
 It is used by python interpreter.
 It gives special meaning to an interpreter.
 It recognizes the structure of program.
 It cannot be used for other purpose.
Ex: if, def, for , break

15. What is literal? Explain the types of literal? *


 Literal is a raw data.
 It is given in a variable or constant.

44
3 Types of literal:
i) Numeric
ii) String
iii) Boolean

i) Numeric:
 It consists of digits.
 It is immutable.

Types of numeric literal:


1. Integer (a=10)
2. Float (b=10.5)
3. Complex (x=1 + 3.14j)
ii) String:
 It is a sequence of characters .
 Strings are surrounded by single / double / triple quotes. ( „ ‟ , “ ” , “„ ‟‟‟)
Ex: „Apple‟
“Apple”
“„Apple”‟

character literal:
 It is a single characters.
 It is surrounded by single or double quotes.
Multiline string literal:
 The values with triple quotes “„ ‟‟‟ are multiline string literal.
Ex:
“„Apple”‟

iii) Boolean:
 It has two values.
 They are True or False.
Ex:
a=true
b=false

16. What is delimiters? *


 It is a sequence of one or more characters.
 It is used to specify the boundary between separate, independent regions in plain text or
other data streams.

45
 Python uses the symbols and symbol combinations as delimiters.
 It is used in expressions, lists, dictionaries and strings.
Ex:
( ) { } [ ]
, : . „ = ;

17. What is operator? *


 Operators are special symbol.
 It performs computations, conditional matching etc..
 The value of an operator is called as operands.
Ex: a + b
Types of operator :
1. Arithmetic operator
2. Relational operator
3. Logical operator
4. Assignment operator
5. Conditional operator
18. What is operand?
 The Value of an operator is called as operands.
 Value and variables used with operator are known as operands.
Ex: a+b (a, b  operands)

19. What is logical operator? *


 It is used to perform logical operations on the given relational expression.
 There are 3 logical operators.
Operators : and , or , not.
Ex: (a < b) and (c == d)

20. What is relational operator? *


 It is also called as comparative operator.
 It checks the relationship between two operands.
 It returns either “True” or “False”
 Otherwise it return false.
Operators: <, <= , >, >= , ==, !=
Ex: a<b
21. How many data types in python? What are they? *
 Python has Built-in or Fundamental data types.
 They are Number, String, Boolean, tuples, lists and dictionaries.

46
22. Write short note on Number datatype. *
 It supports integer , floating point numbers, complex number.
1. a) Integer data :
 Integer data can be decimal, octal or hexa decimal.
b) Octal integer:
 It uses digit 0 (zero)
 Digit 0 is followed by letter o.
 o  denote the Octal digits.
Ex: 0o432
c) Hexadecimal integer :
 It uses 0x or 0X
 0 is followed by uppercase and lowercase X.
Ex: 0x456 , 0X789

d) Long decimal integer :


 It uses L to denote long integer.
Ex: 34L, 456L

2. Floating point data:


 It contains sequence of decimal digits.
 It includes decimal point.
Ex: 123.34
Exponent data:
 It contains
 Decimal digit part
 Decimal point
 Exponent part
 Followed by one or more digits.
Ex: 12.E04
3. Complex number:
 It is made up of two floating point values.
1) Real part
2) Imaginary part 1  Real part
Ex: x= 1+3.14j 3.14j  Imaginary
part
23. Write short note on Boolean datatype.
 It can have two values - True (or) False
Ex: a=True
b= False
47
24. Write short note on string datatype. *
 It is enclosed within single / double quotes / triple quotes.
Ex:
Gender = „M‟ (character data)
Name = “sachin” (string data)
Subject = “„computer science‟‟‟ (multiline data )

25. What is interactive mode programming?


 It can be directly typed and the interpreter displays the result(s) immediately.
 It used as a simple calculator.

26. What is script mode programming?


 A script is a text file.
 It contains the Python statements.
 Python scripts are reusable code.
 Once the script is created, it can be executed again and again without retyping.
 Scripts are editable.

27. How to invoke python?


To invoke Python IDLE from Window OS.
 Start → All Programs → Python 3.x → IDLE (Python 3.x)
(Or)
 Click python Icon on the Desktop if available.

28. How to create scripts in python?


1. Choose File → New File or Ctrl + N
2. An untitled blank script text editor will be displayed on screen.
3. Type the code
29. Write the python program to display the following pattern:
1
12
123
Program: 1234
12345
i=1
while(i<=6):
for j in range(1,i):
print(j,end='')
print(end='\n')
i+=1
48
30. Write the python program to display the following pattern:
12345
1234
123
12
1
Program:
i=6
while(i>1):
for j in range(1,i):
print(j,end='')
print(end='\n')
i-=1

31. Write the python program to display the following pattern:


1
22
333
4444
55555
Program:

i=1
while(i<=5):
for j in range(1,i+1):
print(i,end='')
print(end='\n')
i+=1

32. Write the python program to display the following pattern:


*
**
***
****
*****

49
Program:
s='*' i=1
i=1 while(i<=6):
while(i<=5): (or) for j in range(1,i):
print(s*i) print("*",end='')
i+=1 print(end='\n')
i+=1

33. Write the python program to display the following pattern:

*****
****
***
**
*
Program:

s='*' i=6
i=5 while(i>=1):
while(i>=1): (or) for j in range(1,i):
print(s*i) print("*",end='')
i - =1 print(end='\n')
i- =1

32. Write the python program to display the following pattern:


C
CO
COM
COMP
COMPU
COMPUT
COMPUTE
COMPUTER
Program:
s="COMPUTER"
index=0
for i in s:
print(s[:index+1])
index+=1

50
33. Write the python program to display the following pattern:
COMPUTER
COMPUTE
COMPUT
COMPU
COMP
COM
CO
C
Program:

s="COMPUTER"
index=9
for i in s:
print(s[:index-1])
index-=1

5 Marks: (Book Back Questions)


1. Describe in detail the procedure for script mode programming. *
 A script is a text file.
 It contains the Python statements.
 Python scripts are reusable code.
 Once the script is created, it can be executed again and again without retyping.

To Create scripts in python :

1. Choose File  New File (or ) Ctrl+N


2. Type the code.
To Save python script :
1. Choose File  Save (or ) Ctrl+S
2. Save As dialog box appears
3. Select the location
4. Type the file name in Filename box (extenstion .py )
5. Click Save button.

51
To Execute python script :
1. Choose Run  Run Module (or) press F5
2. If the program has any error, correct the errors.
[[

3. Then, save the file using File  Save (or) Ctrl+S


4. Execute again.
5. The output will appear on the screen ( IDLE window).

2. Explain input() and print() function with example. *

Input() function :
 It is used to accept data as input at run time.
 It accept all data as string or characters .But not as numbers.
 int( ) function is used to convert string data as numbers.
Syntax:

variable = input (“prompt string”)


variable = int (input (“prompt string”))

Ex: city = input (“Enter your city:”)


age = int (input (“Enter your age:”))

Output: Enter your city: chennai


Enter your age: 16

Prompt string:
 It is a statement or message to the users.
 From this message the user can know, “what input has been given”.
 If prompt string is not given, ”No message will be displayed on the screen”.

Print() function :
 It used to display result on the screen.

Syntax: print (“string to be displayed as output”)


print (variable)
print (“string” , variable)
print (“string1” , variable1, “string2” , variable2…..…)

52
Ex: print (“welcome”)

Output: welcome

Note:
 print() evaluates the expression before printing.
 In print( ) the comma(,) is used as a separator to print more than one item.

3. Discuss in detail about tokens in python. *


 Python breaks each logical line into a sequence of elementary lexical components is
known as tokens.
Types of token:
1. Identifier
2. Keywords
3. Operators
4. Delimiters
5. Literals
Identifier:
 An Identifier is a name.
 It is used to identify a variable, function, module, class or object.
Ex: name, mark
Keywords :
 Keywords are special words used by python interpreter.
 It recognizes the structure of program.
 It have specific meaning for interpreter
 It cannot be used for any other purpose.
Ex: break, if, def

Operators :
 Operators are special symbol.
 It performs computations, conditional matching etc..
 The value of an operator is called as operands.
Types of operator:
1. Arithmetic operator
2. Relational operator
3. Logical operator
4. Assignment operator
5. Conditional operator

53
1) Arithmetic operator:
 It is a mathematical operator.
 It takes two operands and performs a calculation on them.
 It is used for simple arithmetic operation.
Operators : + , - , * , /, % , ** , //
Ex: a+b
2) Relational operator :
 It is also called as comparative operator.
 It checks the relationship between two operands.
 It returns either “True” or “False” based on condition.

Operators: <, <=, >, >= , ==, !=


Ex: a<b
3) Logical Operators :
 It is used to perform logical operations on the given relational expression.
 There are 3 logical operators.
Operators :
1) and
2) or
3) not
Ex: (a < b) and (c==d)
4) Assignment operator:
 =  simple assignment operator.
 It assigns value (R.H.S) to a variable(L.H.S).
Operators : =, +=, -= , *= , /=, %= , **= , //=
Ex: a=5
5) Conditional operator:
 It is also known as ternary operator.
 It evaluate based on a condition being true or false.
 Single line replacing the multiline if... else statements.
 It making the code compact.
Syntax: variable name=[on true] if [test expression] else [on false]

Ex: min= 10 if 10<20 else 20

Output: 10

54
Delimiters:
 It is a sequence of one or more characters.
 It is used to specify the boundary between separate, independent regions in plain
text or other data streams.
 Python uses the symbols and symbol combinations as delimiters.
 It is used in expressions, lists, dictionaries and strings.
Ex:
( ) { } [ ]
, : . „ = ;

Literals:
 It is a raw data.
 It is given in a variable or constant.

Types of literal:
1) Numeric 2) Boolean 3) String
1) Numeric: (consists digits and immutable)
Types of numeric literal:
1. Integer Ex: a = 5
2. Float Ex: b = 2.1
3. Complex Ex: x= 1+3.14j

2) String: ( consists 2 or more characters)


Ex: name= “ sachin “

3) Boolean: (consists 2 values. True ,False)


Ex: x=True y=False

4. Discuss in detail about types of operators in python. *


 Operators are special symbol.
 It performs computations, conditional matching etc.
 The value of an operator is called as operands.
Types of operator :
1. Arithmetic operator
2. Relational operator
3. Logical operator
4. Assignment operator
5. Conditional operator

55
Arithmetic Operators :
 It is a mathematical operator .
 It takes two operands and performs a calculation on them.
 It is used for simple arithmetic operations.

Operator Operation Example Output

+ Addition 5+2 7
- Subtraction 5- 2 3
* Multiplication 5*2 10
/ Division 5/2 2.5
% Modulus 5%2 1
** Exponent 5**2 25
// Floor Division (integer division) 5 // 2 2

Relational Operator:
 It is also known as comparative operator.
 It checks the relationship between two operands.
 It returns either “True” or “False” based on condition.

Operator Operation Example Output

> Greater than 5>2 True


< Less than 5<2 False
>= Greater than or equal to 5 >= 2 True
<= Less than or equal to 5 <= 2 False
== Equal to 5 == 2 False
!= Not equal to 5 != 2 True

Logical Operators :
 It is used to perform logical operations on the given relational expression.

Operator Example (a=5,b=2) Output

and (a>b) and(a<b) False


or (a > b) or (a<b) True
not not(a >b) False

56
Assignment operator:
 =  simple assignment operator.
 It assigns value (R.H.S) to a variable (L.H.S)
Ex:

Operator Example Description Output

= a=2 Assigns value(2) to variable(a) 2


+= a += 2 a=a + 2 7
-= a -=2 a=a- 2 3
*= a *=2 a=a * 2 10
/= a /=2 a=a / 2 2.5
%= a %=2 a=a% 2 1
**= a **=2 a=a**2 25
//= a //=2 a=a // 2 2
Conditional operator:
 It is also known as ternary operator.
 It evaluate based on a condition being true or false.
 Single line replacing the multiline if... else statements.
 It making the code compact.
Syntax:
variable name=[on true] if [test expression] else [on false]

Ex: min= 10 if 10<20 else 20

Output: 10

57
UNIT – II CHAPTER-6. CONTROL STRUCTURE
=====================================================================
2 Marks: (Book Back Questions)
1. 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.

2. List the control structures in python. *


1. Sequential
2. Alternative or branching
3. Looping or iterating
3. Write a note on break statement. *
 It terminates the loop containing it.
 Control of the program flows to the statement immediately after the body of the
loop.
4. Write the syntax of if...else statement. [or] Write a note on if…else statement . *
It provides control to check the true block as well as the false block.
Syntax :
if<condition>:
True block
else:
False block

5. Write a note on range() in loop. *


 range ( ) function is a built-in function
 It generates a list of values between two numeric intervals.
Syntax :
range(start,stop,[step]

start - refers to initial value


stop - refers to final value
step - refers to increment values.
Ex:
range(2,10,2)

Output: 2468

58
3 Marks: (Book Back Questions)
1. Write a note on if...else structure? *
 It provides control to check the true block as well as the false block.
Syntax:
if<condition>:
statement – block 1
else:
statements – block

2. Write a program to display the following pattern *


A
AB
ABC
ABCD
ABCDE

Program:
for i in range(65,70):
for j in range(65,i+1):
print(chr(j),end=' ')
print(end="\n")

3. Using if..else..elif statement write a suitable program to display largest of 3 numbers. *

a= int(input("Enter the first number")) Output:


b= int(input("Enter the second number")) Enter the first number: 8
c= int(input("Enter the third number")) Enter the second number: 7
if(a>b) and (a>c): Enter the third number: 6
print(a,"is larger") 8 is larger
elif (b>a) and (b>c):
print(b,"is larger")
else:
print(c,"is larger")

4. Write the syntax of while loop. *


while<condition>:
statement – block 1
[else:
statements – block 2]

59
5. List the difference between break and continue statements. *

s.no Break Continue


1 It terminates the loop It transfers the control to next of the loop.

2 Control of the program flows to the It skips the remaining part of a loop and
statement immediately after the body of start with next iteration.
the loop
3 Syntax : break Syntax: continue

Additional 2 Marks & 3 Marks Questions:

1. What is the use of indentation? *


 Indentation is used to make the code look pretty.
 It is required in python.
 It creates blocks and sub blocks.
 It indicates which block of code the statement belongs to.
 Python uses whitespace such as spaces and tabs to define program blocks.
 Default indent spacing : 4

2. What is Sequential statement?


 A sequential statement is composed of a sequence of statement .
 These are executed one after another.

3. What is alternative or branching statement?


 It allows to skip a segment or Set of statements and execute another segment based
on the test of a condition.

4. What are the types of branching statement? *


1. Simple if statement
2. if...else statement
3. if...elif statement
5. What is the use of elif? *
 It is a chain of if statement (S) then
 Here, „elif‟ cause can be used instead of „else‟
elif  else if

 Multiple if..else statements can be combined to one if..elif..else.

60
 In an „if‟ statement, there is no limit of „elif ‟ clause can be used.
 But, elif clause end with else statement.
Syntax:
if <condition-1>:
statement – block1
elif<condition2>:
statement –block2
else :
statement – block n

6. Explain the alternate method of if..else statement with example. *


 An alternate method to rewrite if..else is also available in Python.
Syntax:
variable = variable1 if condition else variable2

Ex: min= 10 if 10<20 else 20

Output: 10

7. What is iteration or looping?


 A set of statements executes multiple times called iteration or looping.

8. What is loop? What are types? *


 It executes a statement or group of statements multiple times.
Types of loop
1. While loop
2. for loop
9. What is nested loop ?
 A loop placed within another loop is called as nested loop .

Ex: Output
i=1 1
while(i<=6): 12
for j in range(1,i): 123
print(j,end='') 1234
print(end='\n') 12345
i+=1

61
10. What is jump statement and write their types? *
 It is used to unconditionally transfer the control from one part of the program to another.
Types:
1) Break
2) Continue
3) pass

11. What is pass statement?


 It is a null statement.
 Generally used as a placeholder.
 It is completely ignored by python interpreter.
 Nothing happens when pass is executed, it results in no operation.
 It can be used in „if‟ clause as well as within loop construct

Syntax: pass

12. What is the output of the following python program. *

for word in „Computer‟:


print(word, end=‟ „)
else:
print(“\nEnd of the
loop”)
Output: Compu ter
End of the loop

13. Draw the flow charts.


if ..else

62
if ..elif..else

while loop

for loop

63
break

continue :

64
Hands on Experience in book:

1. Write a program to check whether the given character is a vowel or not.

Program Output
ch=input ("Enter a character:") Enter a character: m
if ch in('a','A','e','E','i','I','o','O','u','U'): m is not a vowel
print(ch,"is a vowel")
else:
print(ch, "is not a vowel")

2. Using if..else..elif statement check smallest of three numbers.


Program Output
n1=int(input("Enter first number:")) Enter first number : 20
n2=int(input("Enter second number:")) Enter second number: 40
n3=int(input("Enter third number:")) Enter third number:10
if(n1<n2) and(n1<n3): The smallest number is 10
s=n1
elif(n2<n1) and(n2<n3):
s=n2
else:
s=n3
print("The smallest number is",s)

3. Write a program to check if a number is Positive, Negative or zero.

Program Output
n=int(input("Enter a number:")) Enter a number:-4
if(n>0): Negative number
print("Positive number")
elif(n==0):
print("Zero")
else:
print("Negative number")

65
4. Write a program to display Fibonacci series 0 1 1 2 3 4 5…… (upto n terms)
Program Output
a=int(input("How many terms?")) How many terms? 10
n1=0 Fibonacci series:
n2=1 0,1,1,2,3,5,8,13,21,34
count=2
if(a<=0):
print("Enter the positive number")
elif(a==1):
print("Fiboncci series:")
print(n1)
else:
print("Fibonacci series:")
print(n1,',',n2,end=",")
while(count<a):
nth=n1+n2
print(nth,end=',')
n1=n2
n2=nth
count+=1

5. Write a program to display sum of natural numbers, upto n.


Program Output
n=int(input("Enter any number:")) Enter any number:5
s=0 sum: 15
for i in range(1,n+1):
s=s+i
print("sum:", s)

6. Write a program to check if the year is leap year or not.

Program Output
n=int(input("Enter any year:")) Enter any year:2000
if(n%4==0): Leap year
print("Leap year")
else:
print("Not Leap year")

66
7. Write a program to check if the given number is a palindrome or not.

Program Output
n=int(input("Enter any Enter any number: 121
number:")) Palindrome
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("Palindrome")
else:
print("Not Palindrome")

8. Write a program to print the following pattern

*****
****
***
**
*

s='*' i=6
i=5 while(i>=1):
while(i>=1): (or) for j in range(1,i):
print(s*i) print("*",end='')
i - =1 print(end='\n')
i- =1

67
5 Marks: (Book Back Questions):
1. Explain if and if else statement? (Additional question) *
Simple if statement:
 It is simple decision making statement.
 It checks the condition.
 If the condition is True, “True block” will be executed.
 If the condition is False, “True block” will not be executed.
 Condition should be in the form of relational or logical expression.

Syntax:
if<condition>:
True block

Ex:
mark=70
if(mark>=35):
print (“pass”)

Output: Pass

ii) if...else statement :


 It chooses between two possibilities.
 It executes the chosen block based on the condition.
 It checks the condition.
 If the condition is True, “True block” will be executed.
 If the condition is False, “False block” will be executed.
 It check true block as well as false block
Syntax: if <condition>:
True block
else:
false block

Ex:
mark=70
if(mark>=35):
print (“pass”)
else:
print (“fail”)
Output: Pass

68
2. Write a detail note on if..else..elif statement with suitable example.(Book Back) *
 It is a chain of if statement (S) then
 Here, „elif‟ cause can be used instead of „else‟
elif  else if

 Multiple if..else statements can be combined to one if..elif..else.


 In an „if‟ statement, there is no limit of „elif ‟ clause can be used.
 But, elif clause end with else statement.
Syntax: if <condition-1>:
statement – block1
elif<condition2>:
statement –block2
else :
statement – block n
Explanation:
 First it check the Condition 1
 If the condition1 is true, statement block 1 will be executed.
 Otherwise check the condition2,
 If the condition2 is true, statement block 2 will be executed
 If both the condition is False, statement block-n (else part) will be executed.
Ex:
mark=100
if (mark= =100 ):
print (“centum”)
elif (mark<35 ):
print(“Fail”)
else :
print(“Pass”)

Output: centum

3. Write a detail note on for loop. (Book Back) *


 For loop is usually known as “Definite loop”.
 Because, the programmer knows exactly how many times the loop will be executed.
Syntax:
for counter – variable in sequence:
Statement –block1
[else :
Statement-block2]

69
Explanation:
 for…in statements is a looping statement
 It used in python to iterate over a sequence of objects.
(It goes through each item in a sequence)
 Here, the sequence is the collection of ordered/unordered values/even a string.
 Control variableAccess each item of the sequence on each iteration until it reaches the
last item in the sequence.
Ex:
for x in “Hello World”:
print (x)

Output: Hello World

 Initially, the value of x is set to the first element of the string(„H‟)


 So the print statement inside the loop is executed.
 Then the control variable x is updated with the next element of the string and the print
statement is executed again.
 The loop runs until the last element of the string is accessed.
 range ( ) function is a built-in function
 It generates a list of values between two numeric intervals.
 Starting from start till stop-1.

Syntax :

range(start,stop,[step]

start - refers to initial value


stop - refers to final value
step - refers to increment values.

Ex:

for i in range(2,10,2):
print(i)

Output: 2468

70
4. Explain the while loop with an example. (Additional question) *
 It is an entry check loop.
 Because, the condition is checked at the beginning.
Syntax:
while<condition>:
statement block 1
[else:
statement block 2]

Explanation:
 It checks the condition.
 If the condition is “true” statement block1 will be executed.
 The statement block1 is kept executed, till the condition is true
 If the condition is “false” statement block2 will be executed.
 else part is optional.
 Condition is any valid Boolean expression.
 Boolean expression returns true or false.

Ex:
i=1
while(i<=3):
print(i)
i=i+1

Output: 123

5. Write a program to display all 3 digit odd numbers. (Book Back) *

for i in range(101,1001,2):
print(i,end=‟\t‟)
Output:
101 103 105……….999

71
6. Write a program to display multiplication table for a given number. (Book Back) *

b=1 Enter the number for multiplication table: 2


a=int(input("Enter number for multiplication table:")) 1 * 2 = 2
while(b<=10): 2*2=4
c=a*b 3*2=6
print(b,"*",a,"=",c,end=' ') 4*2=8
print(end='\n') 5 * 2 = 10
b+=1 6 * 2 = 12
7 * 2 = 14
8 * 2 = 16
9 * 2 = 18
10 * 2 = 20

72
UNIT – II - CHAPTER 7. Python Function
=================================================
2 Marks: (Book Back Questions)
1. What is function? *
 Functions are named blocks of code.
 It is designed “to do one specific job“.

2. Write the different types of functions. *


1) User defined
2) Built in
3) Lambda
4) Recursion

3. What are the main advantages of function? *


1) It avoids repetition.
2) It makes high degree of code securing.
2) It provides better modularity for your application.

4. What is meant by scope of variable? Mention its types? *


 It refers to the part of the program where it is accessible.
(i.e), area where you can refer (use) it.
 Scope holds the current set of variables and their values.
Types of scope :
1. Local scope
2. global scope

5. Define global scope.


 It is a variable is declared outside of any function block
 It is used anywhere in the program.

6. What is base condition in recursive function?


 The condition is “applied in any recursive function“ is known as base condition.
7. How to set the limit for recursive function? Give example.
sys.setrecursionlimit(limit_value) is used to set the limit for recursive function.

73
3 Marks: (Book Back Questions)
8. Write the rules of local variable. *
 It is created inside the function / block.
 It becomes local to it.
 It is accessed only within the function block.
 It only exists while the function is executing.
 Formal arguments are also local to function.

9. Write the basic rules for global keyword in python. *


 A variable defined outside a function is global by default.
 We use global keyword to read & write a global variable inside a function.
 Use of global keyword outside a function has no effect.

10. What happens when we modify global variable inside the function?
 Without “global keyword “we cannot modify” the global variable inside the
function.
 But without global keyword “we can only access the global variable”.

11. Difference between ceil() & floor() function. *

s.no ceil( ) floor( )

1 Returns the smallest integer >= x Returns the largest integer <= x
2 Syntax : math.ceil(x) Syntax : math.floor(x)
3 Ex: import math Ex: import math
x=26.7 x=26.7
print(math.ceil(x)) print(math.floor(x))
Output: 27 Output: 26

12. Write a python code to check whether a given year is leap year or not. *

x= int(input(“Enter year: ”))


if x%4==0 :
print(“leap year”)
Output: Enter year: 2000
else:
leap year
print(“non-leap year”)

74
13. What is composition in function?
 The value returned by a function “may be used as any argument for another
function“ in a nested manner is called as composition.

14. How recursive function works? *


1) Recursive function is called by some external code.
2) If the base condition is met the program gives
“meaningful output & exits“.
3). Otherwise, “function does some required processing “ and “call itself “
to continue recursion.

15. What are the points to be noted while defining function? *


Syntax :
def<function name> ([parameter1, parameter2…] )>:
<Block of Statements>
return<expression / None>

 points to be noted while defining function


1. Function block begin with “def” keyword .
2. Followed by function name and parenthesis().
3. Any input parameters or arguments must be given within parentheses ( ).
4. The code block always comes after a colon (:) and it is indented.
5. The “return <expression / None>” statement exits a function.

Additional 2 Marks & 3 Marks Questions:


16. What are the advantages of user defined function? *
 It help us to divide a program into modules.
 It implements code reuse.
 Allows to change functionality easily.

17. Write the syntax for user defined function. With example. *
Syntax :
def<function_name ([parameter1, parameter2…] )>:
<Block of Statements>
return <expression / None>

75
Ex:
def hello():
print (“hello python”)
return

18. What is anonymous function? With example. *


 A function defined without name is called as anonymous function.
 lambda keyword is used to define the anonymous function.
 It is also known as lambda functions.
Syntax:

lambda [argument(s)] : expression


Ex:
sum = lambda a1, a2 : a1 + a2
print (sum(30,40))

Output: 70

19. What are the uses of anonymous/Lambda function? *


 Anonymous functions are called as lambda functions.
 It is used for creating small and one-time anonymous function.
 It is used in combination with functions filter( ), map( ) , reduce( ).

20. What is recursive function? *


 A function which calls itself is known as recursion.
 Recursion works like loop.
 We can convert any loop to recursion.

21. What are function arguments? *


 Arguments are used to call a function.
Types of function arguments :
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments.

76
22. What is return statement? Write syntax and example.
 It is used to exit the function .
 It returns a value to its caller.
 Generally function takes inputs and return something.
 Only one return statement is executed at run time,
even function contain multiple return statements.
 Any numbers of „return‟ statements are allowed in a function.
But only one will be executed at run time.
Syntax:
return [expression list ]
Ex:
def fun (n):
if n>=0:
return n
else:
return –n
print(fun(25))

Output : 25

23. What are the methods to pass the arguments in variable length arguments?
Two methods: 1. Non keyword variable arguments
2. Keyword variable arguments
24. How to pass parameters in functions With example.
Syntax:
def function_name(parameter(s) separated by comma):
Ex:
def area(r):
return r * r
print (area(5))

25. Write the syntax for variable length arguments. With example.
Syntax:
def function name(*args):
function_body
return statement

77
Ex:
def num(*nos):
for n in nos:
print(n)
return
print ('Print two values')
num(1,2)
output:
Print two values 1 2

26. How to call a function? With example.

To call the function


 Call the function using function name with or without arguments with parenthesis.
Syntax:

functionname( )
( or)
functionname(arguments)
Ex:
def hello():
print(“hello python”)
hello()

27. What is infinite iteration?


 A process would iterate indefinitely if not stopped by condition
 Such a process is known as infinite iteration.

28. What is meant by block?


 A block is one or more lines of code, grouped together so that they are treated as
one big sequence of statements while execution.

29. What is nested block?


 A block within a block is called nested block. When the first block statement is
indented by a single tab space, the second block of statement is indented by
double tab spaces.

78
30. Which is called as non-keyword variable arguments?
 Non-keyword variable arguments are called tuples.

31. How will you pass the variable length arguments?


 We can pass the arguments using two methods.
1. Non keyword variable arguments
2. Keyword variable arguments
32. What is recursion?
 When a function calls itself is known as recursion.
 Recursion works like loop but sometimes it makes more sense to use recursion
than loop.
33. Define format() in mathematical functions.
 Returns the output based on the given format
1. Binary format: Displays the number in base 2.
2. Octal format: Displays the number in base 8.
3. Fixed-point notation: Displays the number as a fixed-point number.
The default precision is 6

Syntax: format (value [, format_ spec])

Ex:
x= 14
y= 25
print ('x value in binary :',format(x,'b'))
print ('y value in octal :',format(y,'o'))
print('y value in Fixed-point no ',format(y,'f '))

Output:
x value in binary : 1110
y value in octal : 31
y value in Fixed-point no : 25.000000
34. Define round() in mathematical functions.
Returns the nearest integer to its input.
1. First argument (number) is used to specify the value to be rounded
2. Second argument (ndigits) is used to specify the number of decimal digits
desired after rounding.

79
Syntax: round (number [, ndigits])

Ex:
n1=17.89
print (round (n1,0))
print (round (n1,1))
print (round (n1,2))
Output:
18.0
17.9
17.89
35. Define pow() in mathematical functions.
 Returns the computation of ab i.e. (a**b ) a raised to the power of b.

Syntax: pow (a,b)

Ex:
a= 5
b= 2
c= 3.0
print (pow (a,b))
Output:
print (pow (a,c))
25
print (pow (a+b,3))
125.0
343

5 Marks: (Book Back Questions)


1. Explain the different types of function with an example. *
1. User defined function
2. Built in function
3. Lambda function
4. Recursion function
1. User defined function:
 Function defined by users themselves
Syntax:
def <function_name ( [parameter1, parameter2…] )>:
Block of Statements
return <expression / None>
80
Ex:
def hello():
print (“welcome”)
return
hello( )

Output: welcome

Advantages:
1. Helps to divide a program into modules.
2. It implements code reuse.
3. Allows us to change functionality easily.

2. Built in function:
 Functions that are inbuilt within python.
Ex:
 sum( )
 max( )
 min( )
3. Lambda function:
 A function defined without name is called as lambda function.
 It is also called as anonymous function.
 It is an Unnamed function.
Syntax:
lambda[ arguments(s) ] : expression

Ex: sum = lambda a1,a2 : a1 + a2

4. Recursive function:
 A function calls itself is known as recursion.
 The condition is applied in any recursive function is known as base condition.
Ex:
def fact(n):
if n==0 :
return 1
else : Output: 120
return n*fact (n-1)
print (fact(5))
81
2. What is Scope of variables? explain. (Book Back) *
 It refers to the part of the program where it is accessible.
(i.e), area where you can refer (use) it.
 Scope holds the current set of variables and their values.
Types of scope :
1. Local scope,
2. global scope
1. Local scope :
 A variable declared inside the function body or in the local scope
Rules :
 A local variable is created inside the function or block.
The variable becomes local to it.
 It can be accessed only within the function block. That it is created .
 It only exists while the function is executing.
 Formal arguments are also local to function.
Ex:
def loc():
y=0
print(y)
loc()

Output: 0

2. Global scope :
 A variable declared outside the function or block .
 It can be used anywhere in the program.
Rules :
1. We can define a variable outside a function. It is global by default.
2. Use of global keyword outside a function has “No effect“.
3. We use global keyword to read and write a global variable ”inside a function“.
Ex:
c =1
def add():
print(c)
add()

Output: 1

82
3. Explain id(), chr(), round(), type() & pow() function.

s.no Function Description Syntax Example

1 id()  It returns the address of the object in id(object) x=15


memory print(id(x))
Output:
1357486152
2 chr()  It returns the Unicode character for chr(i) c=65
the given ASCII value . print(chr(c))
 It is inverse of ord( ) function Output: A

3 round()  It returns the nearest integer to its round ( number x=17.9


input. [ n digits ] ) print(round(x)
Output: 18
4 type()  It returns the type of object type(object) x=15.2
print(type(x))
Output :
<class „float‟>
5 pow()  It returns the computation of a, b pow(a,b) a=5
(a**b) b=2
 a raised to the power of b. Print(pow(a,b))
Output: 25

4. Explain recursive function with example.*


 A function calls itself is known as recursion.
 The condition is applied in any recursive function is known as base condition.
Recursive function working:
 Recursive function is called by some external code.
 If the base condition is met then the program gives meaningful output and exit.
 Otherwise, function does some required processing and then calls itself to continue
recursion.
Ex:
def fact(n):
if n==0 :
return 1
else : Output: 120
return n*fact (n-1)
83

print (fact(5))
5. Explain the types of arguments.( Additional Question)*
 Arguments are used to call the function.
Types of arguments:
1. Required argument
2. Keyword argument
3. Default argument
4. Variable-length argument
Required argument:
 It passed to a function in correct positional order.
 The number of arguments in the ” function call “ should match exactly with the
“function definition“.
Ex:
def fun(s):
print (s)
return
fun(“welcome”)
Output: welcome

Keyword argument:
 It will invoke the function after the parameters are recognized by their names.
 The value of the keyword argument is matched with the parameter name.
 So ,one can put arguments in improper order (not in order).
Ex:
def fun(s):
print (s)
return
fun(s=‟welcome‟)
Output: welcome

Default argument:
 It takes a default value, if no value is given in function call.
Ex:
def fun(s=‟welcome‟) :
print (s)
return
fun()
Output: welcome

84
Variable-length argument:
 We need to pass more arguments than already specified.
 Redefine the function is tedious process.
 Variable-Length arguments can be used instead.
 Arguments not specified in the function‟s definition and an asterisk (*) is used to
define such arguments.

Syntax:
def function_name (*args) :
function body
return_statement

Ex:
def fun (*nos):
for n in nos:
print(n)
return
fun(1,2)

Output: 1
2

6. Write a Python code to find the L.C.M. of two numbers.

def lcm(x,y) :
if x>y :
greater=x
else:
greater=y
while(True) :
if((greater%x==0) and (greater%y==0)) :
lcm=greater
break
greater+=1
return lcm

num1=input(“Enter the first number:”)


num2=input(“Enter the second number:”)
print(“The L.C.M or”,num,”and”,num2,”is”,lcm(num1,num2))

85
7. Explain mathematical function? ( Additional Question)*

Function Description Syntax Eg :


floor () Returns the largest integer math. floor(x) x=26.7
less than or equal to x print(math.floor(x))
Output: 26

ceil() Returns the smallest integer math.ceil(x) x=26.7


greater than or equal to x print(math.ceil(x))
Output: 27

sqrt () Returns the square root of x sqrt(x) a=30


print(math.sqrt(a))
Output: 5.47722.

Hands On Experience Inbook

1. Try the following code in the above program


s.no Code Result
1 printinfo(“3500”)
2 printinfo(“3500”,”Sri”)
3 printinfo(name=”balu”)
4 printinfo(“Jose”,1234)
5 printinfo(“ ”,salary=1234)

2. Evaluate the following functions and write the output


s.no Function Output
1 eval(„25*2-5*4') 30
2 math.sqrt(abs(-81)) 9.0
3 math.ceil(3.5+4.6) 9
4 math.floor(3.5+4.6) 8

86
3. Evaluate the following functions and write the output.

Slno Function Output


1 1) abs(-25+12.0)) 13.0
2) abs(-3.2) 3.2

2 1) ord('2') 50
2) ord('$') 36
3 type('s') <class „str‟>
4 bin(16) 0b1000
5 1) chr(13) „\r‟
2) print(chr(13)) blankline
6 1) round(18.2,1) 18.2
2) round(18.2,0) 18.0
3) round(0.5100,3) 0.51
4) round(0.5120,3) 0.512
7 1) format(66, 'c') B
2) format(10, 'x') a
3) format(10, 'X') A
4) format(0b110, 'd') 6
5) format(0xa, 'd') 10
8 1) pow(2,-3) 0.125
2) pow(2,3.0) 8.0
3) pow(2,0) 1
4) pow((1+2),2) 9
5) pow(-3,2) 9
6) pow(2*2,2) 16

87
UNIT – II - CHAPTER 8. Strings And String Manipulations
==================================================
2 Marks: (Book Back Questions)
1. What is string?

 String is a data type.


 It is used to handle array of characters.
 It is a sequence of Unicode characters.
 It is a combination of letters, numbers or special symbols.
 It is enclosed within single, double or triple quotes.
Ex:
„school‟
“school”
„‟‟school‟‟‟

2. Do you modify string in python.

 No. We cannot modify the string in python.


 Strings are immutable.
 Once you define a string modification or deletion is not allowed.
 To modify the string: A New string value can be assign to the existing string
variable.
(OR)
 Yes. We can modify the string in python.
Method:
1. A new string value can be assign to the existing string variable.
2. When defining a new string value to the existing string variable.
3. 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.
 We can remove the entire string variable using del command.
Ex:
str=”hello python”
del str (str variable is fully deleted)

88
4. What will be the output of the following python code?
str1 = “School”
print (str*3)
Ans: School School School

5. What is slicing?

 [ ]  slicing operator.
 Slice is a substring of a main string.
 A substring is taken from the original string .
 It is taken by using [ ] operator and index or subscript values .
 We can slice one or more substrings from main string.
Syntax:

str[start:end]

Ex:
s=”thirukkural”
print(s[0:5])

Output: THIRU

3 Marks: (Book Back Questions)


6. Write a python program to display the given pattern.

COMPUTER
COMPUTE
COMPUT
COMPU
COMP
COM
CO
C

Answer: (OR) Answer:

str=”COMPUTER” str=”COMPUTER”
index=9 index=len(str)
for i in str: for i in str:
print(str[:index-1]) print(str[:index])
index-=1 index-=1

89
7. Write a short note on (a) capitalize() b) swapcase ()

Function Description Example

s= „chennai‟
capitalize ( ) Used to capitalize the first character of print(s.capitalize())
the string.
Output: Chennai

s= “tAmil”
swapcase( ) Used to change case of every character print(s.swapcase”)
to its opposite case vice-versa.
Output: TaMIL

8. What will be the output of the given python program?

str1 = “welcome”
str2 = “to school”
str 3 = str1[:2] + str2[len(str2)-2:]
print (str3)

Output : weol

9. What is the use of format()? with example.

 It is used for formatting the strings.


 It used with string
 It is very versatile and powerful function .
 Curly bases { } are used as placeholders or replacements fields.
 It gets replaced along with format function.

Ex:

n1=int(input(“Number1:”))
n2=int(input(“Number2:”))
print(“Sum of { } and { } is { }”.format(n1,n2,(n1+n2)))

Output:
Number1 : 3
Number2 : 5
Sum of 3 and 5 is 8

90
10. Write a note about count () function in python.

Definition:
 It returns the number of substrings occurs within the given range.
 Range arguments are optional. (beginning and end)
 If it is not given , python searched in whole string.

Syntax : count(str, beg, end)


Ex :

str = “Raja Raja Chozhan”


print (str.count(“Raja”))

Output: 2

Additional 2 Marks & 3 Marks Questions:


11. Define replace function and write its syntax.

 Python does not support any modification in its strings.

 replace( ) function to change all occurrences of a particular character in a string.

Syntax:
replace(“char1”, “char2”) It replaces all occurrences of char1 with char2.

Ex:
str1="How are you"
print (str1.replace("o", "e"))

Output: Hew are yeu

12. What are membership operators in python?

Membership Operators in operators


not in operators
 It can be used with strings to determine whether a string is present in another string.

91
Ex:
s1=input ("Enter a string: ") Output :
s2="chennai" Enter a string: Chennai GHSS Saidapet
if s2 in s1: Found
print ("Found")
else:
print ("Not Found “)
13. What will be the output of the following python program?
str=”COMPUTER SCIENCE”
a) print(str*2) b) print(str[0:7])
Output:
a) COMPUTER SCIENCE COMPUTER SCIENCE
b) COMPUTE

14. How will you accessing characters in a string?


 Python allocate an index value for its each character.
 The index values are also called as subscript
 It used to access and manipulate the strings.
 Subscript can be positive or negative integer numbers.
Positive Subscript
0 is assigned to the first character
n-1 to the last character,
where n is the number of characters in the string.
Negative Index
Assigned from the last character to the first character in reverse order begins with -1
15. What will be the output of the following python program?
Output:
str1 = input ("Enter a string: ")
Enter a string: welcome
index=0
Subscript [ 0 ] : w
for i in str1:
Subscript [ 1 ] : e
print ("Subscript[",index,"] : ", i)
Subscript [ 2 ] : l
index + = 1
Subscript [ 3 ] : c
Subscript [ 4 ] : o
Subscript [ 5 ] : m
Subscript [ 6 ] : e

92
16. What will be the output of the following python program?
str1 = input ("Enter a string: ")
index=-1
while index >= -(len(str1)):
print ("Subscript[",index,"] : " + str1[index])
index += -1

Output:
Enter a string: welcome
Subscript [ -1 ] : e
Subscript [ -2 ] : m
Subscript [ -3 ] : o
Subscript [ -4 ] : c
Subscript [ -5 ] : l
Subscript [ -6 ] : e
Subscript [ -7 ] : w

17. What are the formatting characters available in python?


Format USAGE
characters
%c Character
%d (or) %i Signed decimal integer
%s String
%u Unsigned decimal integer
%o Octal integer
%x or %X Hexadecimal integer (lower case x refers a-f; upper case X refers A-F)
%e or %E Exponential notation
%f Floating point numbers
%g or %G Short numbers in floating point or exponential notation

93
18. What are the escape sequences are supported by python?
Escape Sequence DESCRIPTION
\newline Backslash and newline ignored
\\ Backslash
\' Single quote
\" Double quote
\a ASCII Bell
\b ASCII Backspace
\f ASCII Form feed
\n ASCII Linefeed
\r ASCII Carriage Return
\t ASCII Horizontal Tab
\v ASCII Vertical Tab
\ooo Character with octal value ooo
\xHH Character with hexadecimal value HH

19. Write a program to create an Abecedarian series.


str1="ABCDEFGH"
str2="ate"
for i in str1:
print ((i+str2),end='\t')
Output: Aate Bate Cate Date Eate Fate Gate Hate
20. What will be the output of the following python snippet?
str1=”THIRUKKURAL”
a) print(str1)
b) print(str1[0])
c) print(str1[0:5])
d) print(str1[:5])
e) print(str1[6:])

Output:
a) THIRUKKURAL b) T c) THIRU d) THIRU e) KURAL

94
21. What will be the output of the following python snippet?
str1=”THOLKAPPIYAM”
a) print(str1[4:])
b) Print(str1[4::2])
c) Print(str1[::3])
d) Print(str1[::-3])

Output:
a) KAPPIYAM b) KPIA c) TLPY d) MIAO

22. What will be the output of the following python snippet?


str1=”WELCOME”
str2=”TO SCHOOL”
str3=str1[:3]+str2[len(str2)-1:]
print(str3)
Output: WELL

23. What will be the output of the following python snippet?


Output:
str1=”Welcome to python”
a) Welcome to python
a) print(str1) b) b) pyhton
b) print(str1[11:17]) c) c) pto
c) print(str1[11:17:2]) d) d) Wotyn
d) print(str1[::4]) e) e) nyto
e) print(str1[::-4])

24. What will be the output of the following python snippet?


Output:
str1=”Welcome to learn python”
a) Welcome to learn python
a) print(str1)
b) learn
b) print(str1[10:16])
c) r
c) print(str1[10:16:4])
d) er
d) print(str1[10:16:2])
e) Wceoenyo
e) print(str1[::3])
f) nhy re telW
f) print(str1[::-2])

95
25. What will be the output of the following python snippet?

name = "Rajarajan"
mark = 98
print ("Name: %s and Marks: %d" %(name,mark))

Output:
Name: Rajarajan and Marks: 98

26. What will be the output of the following python snippet?

num1=int (input("Number 1: "))


num2=int (input("Number 2: "))
print ("The sum of { } and { } is { }".format(num1, num2,(num1+num2)))

Output:
Number 1: 34
Number 2: 54
The sum of 34 and 54 is 88

5 Marks: (Book Back Questions)


1. Explain about string operators in python with suitable example.
 String operators are useful to manipulate string.
1. Concatenation: (+)
 Joining of two or more strings is called as concatenation.
Ex: ”welcome” + “python”

Output: „welcomepython‟

2. Append (+=)
 It is used to append a new string with an existing string.
Ex:
s1= “welcome to”
s2 = “cs”
s1+= s2

Output: welcome to cs
96
3. Repeating (*)
 It is used to display a string in multiple number of times.

Ex: s= “cs”
print (str*3)

Output: cscscs
4. String slicing :
 [ ]  slicing operator.
 Slice is a substring of a main string.
 A substring is taken from the original string .
 It is taken by using [ ] operator and index or subscript values .
 We can slice one or more substrings from main string.
Syntax:
str[start:end]

Ex: s = “welcome”
print (s[1])

Output: e

5. String stride :
 stride is a third argument.
 It refers to the number of characters to move forward after the first character is
retrieved from the string.
 Default stride value is 1.
Ex:
s= “welcome”
print (s[1:6:4])

Output: o

97
Additional 5 Marks Questions:
1. Explain the following Built-in String functions .

Syntax Description Example

len(str)  Returns the length of the string. s="Sairam"


print(len(s))
(no of characters)
Output: 6
capitalize( )  Used to capitalize the first character s="chennai"
of the string . print(s.capitalize())

Output : Chennai
isalpha( )  if the string contains only letters , „python‟.isalpha( )
it will return true. Output: True

 Otherwise, it will return False. ‟Click123‟.isalpha( )


Output: False

isdigit( )  if the string contains only numbers , n=50


it will return true. print(n.isdigit( ))
Output: True
 Otherwise, it will return False .
n=‟Save Earth‟
print(n.isdigit( ))

Output: False
 if the string contains only letters and ‟Save1Earth‟.isalnum()
numbers , it will return true.
isalnum( ) Output: True
 if the string contains special
characters, it will return False . str=‟Save Earth‟
str.isalnum()
Output: False

upper( )  Returns the exact copy of the string str=‟welcome‟


with all letters in uppercase. print (str.upper( ))
Output: WELCOME

lower( )  Returns the exact copy of the string str=‟WELCOME‟


with all letters in lowercase. print (str.lower( ))

Output: welcome

98
str=‟WELCOME‟
print (str.isupper( ))
isupper( )  If the string is in uppercase , it will
return True. Output: True

str=‟welcome‟
print (str.isupper( ))

Output: False

islower( )  If the string is in lowercase , it will str=‟welcome‟


return True.. print (str.islower( ))
Output: True

title( )  Returns a string in title case . str='education‟


print(str.title())
Output : Education

swapcase( )  It will change case of every character s="tAmil"


to its opposite case. print(s.swapcase())
Output: TaMIL

count(str, beg, end)  Returns the number of substrings str="Raja Raja Chozhan"
occurs within the given range. print(str.count('Raja'))
 Search is case sensitive. Output: 2

ord(chr )  Returns the ASCII code of the ch = 'A'


character. print(ord(ch))
Output: 65

chr(ASCII)  Returns the character represented by ch=97


a ASCII. print(chr(ch))
Output: a

center(width,  Returns a string with the original str="Welcome"


fillchar) string centered to a total of width print(str1.center(15,'*'))
columns and filled with fillchar in Output:
columns that do not have characters

****Welcome****

99
 Used to search the first occurrence str=‟mammals‟
of the sub string in the given string. str.find(„ma‟)
Output: 0
 It returns the starting index value.
On omitting the start
 It returns -1 substring not occur. parameters, the function
starts the search from the
find(sub[, start[, beginning.
end]])
Ex: str1.find(„ma‟,2)

Output: 3

str1.find(„ma‟,2,4) -1

Displays -1 because the


substring could not be
found between the index
2 and 4-1. Ex:
str1.find(„ma‟,2,5)

Output: 3

100
Unit-III CHAPTER: 9 Lists, Tuples, Sets And Dictionary
==============================================
2 Marks : (Book Back Questions)
1. What is list in python? Give example. *
 A list in Python is known as a “sequence data type”.
 It is an ordered collection of values .
 Values are enclosed within square brackets [ ].
 Each value of a list is called as element.
Ex:
mark=[10,20,30,40]
m=[ ]

2. How will you access the list elements in reverse order? Give example. *
 Python enables reverse or negative indexing for the list elements.
 Python lists index in opposite order.
 The python sets -1 as the index value for the last element in list and -2 for the
preceding element and so on.
 This is called as Reverse Indexing.
Ex:
Output :
Marks = [10, 20,30,40]
i = -1 40
while i >= -4: 30
print (Marks[i]) 20
i = i + -1 10
3. What will be the value of x in following python code? *
list1=[ 2,4,6,[1,3,5] ]
x=len(list1)
Answer : value of x is 4

101
4. Differentiate del and remove() function of List. *

s.no del statement remove() function


1 Used to delete elements whose index Used to delete one or more elements
value is Known. whose index value is not known.
(or)
delete entire list.

2 Syntax: Syntax:
del List [index of an element] List.remove(element)
del List [index from : index to]
del List
3 Ex: x =[10,20,30] Ex: x=[10,20,30]
del x[1] x.remove(30)

5. Write the syntax of creating Tuple with n number of elements. *


 Creating Tuple with n number of elements.
Syntax:

Tuple_Name=(E1,E2,E3,……..En)
Tuple_Name=E1,E2,E3,………En
Ex:
T= (10,20,30)
(or)
T= 10,20,30

6. What is set in python? Or How to create set in python? *


 A set is another type of collection data type.
 A Set is a mutable .
 Set is an unordered collection of elements enclosed within { } without duplicates.
 set( ) function is also used to create sets.
Syntax:
set_variable = {E1, E2, E3 …….. En}

Ex:
S1={ 10,'A',3.14 }

102
3 Marks: (Book Back Questions)
7. What are the difference between list and Tuples? *

s.no List Tuple


1 List elements are changeable (mutable) Tuple elements are unchangeable
(immutable).
2 Enclosed within square brackets [ ] Enclosed within parenthesis ( ).

3 Iterating list is slower Iterating tuple is faster than list

4 Ex: s=[1,2,3,4] Ex: s=(1,2,3,4)

8. Write a short note about sort(). *


 It sorts the list element either in ascending or descending order.
 Default order: Ascending
 sort( ) will affect the original list.
syntax: List.sort (reverse = True | False, key=myFunc)

o reverse
o key arguments are optional.

1) reverse=True (List sorting in descending order)


reverse=False (List sorting in ascending order -default)
2) key=myFunc
myFunc  ( the user defined function specifies criteria)

Ex:
x=[„A‟,‟B‟,‟C‟,‟D‟]
x.sort(reverse=True)
print(x)

Output: [„D‟,‟C‟,‟B‟,‟A‟]

9. What will be the output of the following code? *


list = [2**x for x in range(5)]
print(list)

Answer: [1,2,4,8,16]

103
10. Explain the difference between del and clear() in dictionary with an example. *
del statement clear() function
1 Used to delete a particular Used to delete all the elements in a
element in a dictionary (or) dictionary.
Remove the dictionary
2 Syntax: Syntax:
del dictionary_name[key] dictionary_name .clear( )
del dictionary_name
3 Ex: Ex:
Dict={„Rno‟:101,‟Name‟:‟Anu‟] Dict.clear()
del Dict[„Name‟]

11. List out the set operations supported by python. *


1. Union( | )
2. Intersection(&)
3. Difference( - )
4. Symmetric difference(^)
12. Write the difference between list and dictionary. *
s.no List Dictionary

1 List is an ordered set of elements.  It is a data structure.


 Mixed collection of elements.
 It stores a key along with its elements.
 Used for matching one element (Key)
with another (Value).

2 Index values can be used to access Dictionary key represents index.


a particular element. Key may be a number of string.
3 Used to look up a value. Used to take one value and look up another
value.

104
Additional 2 Marks & 3 Marks Questions:
(List)
13. How to create a list in python? Give example. *
 A list is created by elements within square bracket.
Syntax:
Variable = [element1, element2, element3 …… element-n]
Ex:
mark=[60,70,80,90]
m=[ ]

14. How to add an element in a list? Give example. *

 append( ) function is used to add a single element in a list.


syntax:
List.append (element to be added)

Ex:
x=[10,20,30]
x.append(40)
print(x)

Output: [10,20,30,40]

15. How to add many elements in a list? Give example.

 extend( ) function is used to add more than one element to an existing list.
Syntax:
List.extend ( [elements to be added])

Ex:
x=[10,20]
x.extend([30,40,50])
print(x)

Output: [10,20,30,40,50]

105
16. How to insert elements using insert() in list? Give example. *
 Used to insert an element at any position of a list.
Syntax:
List.insert (position index, element)
Ex:
x=[10,30,40]
x.insert(1,20)
print(x)

Output: [10,20,30,40]

17. How to delete elements from a list? Give example.

 del statement
 remove( ) function used to delete element from list.
del statement:
 Used to delete known elements and entire list.

Syntax:
del List [index of an element]
del List [index from : index to]
del List
Ex:

Subject= ['Tamil', 'English', 'Maths', 'CS']


print (Subject)
Output: ['Tamil', 'English', 'Maths', 'CS']
del Subject[1]
print (Subject)
Output : ['Tamil', 'Maths', 'CS']

Remove function:
 Used to delete one or more elements of list if the index value is not known.

Syntax:
List.remove(element)
Ex:
x=[10,20,30]
x.remove(20)
print(x)

Output: [10,30]
106
18. Write short note on pop() and clear() function. *

Pop()

 It is used to delete an element using the given index value.


 It deletes and returns the last element of a list if the index is not given.

Syntax: List.pop(index of an element)

Ex: x=[10,20,30,40]
x.pop(1)
print(x)

Output: [10,30,40]

clear()
 It is used to delete all the elements in list.
 It deletes only the elements and retains the list.
Syntax:
List.clear( )
Ex:
x=[10,20,30,40]
x.clear()
print(x)

Output: [ ]

19. Write a note on nested list. Give example. *


 Nested list is a list containing another list as an element.
Ex:
x = [ “cs”,10,20 , [30,40] ]

Total number of elements : 4

107
20. Write a note on len() function *
 It is used to find the length of a list.
 List contains another list as an element, that inner list as a single element.
Ex:
x= [“Tamil”, “English”, “Maths”, “Cs”, [10,20]]
len(x)

Output: 5

21. What is list comprehension? Give example. *

 It is a simplest way of creating sequence of elements based on condition.


Syntax:
List = [ expression for variable in range ]

Ex:
square = [ x ** 2 for x in range(1,5) ]
print (square)

Output: [1, 4, 9, 16]

22. What is the use of type ( ) function?


 It is used to know the data type of a python object.
Syntax:
type (object)

Ex:
x= [10, 20, 30]
print(type(x))

Output: <class „list‟>

23. How to access list elements? Give example.


 Index value is used to access an element in a list.
 The index value starts from 0.
 Positive index starts from beginning of the list. ( Left to right)
 Positive index starts from 0.
 Negative index starts from backward from end of the list (Right to left).
 Negative index starts from -1.

108
To access an element from a list
 Write the name of the list, followed by the index of the element enclosed within
square brackets[ ].
Syntax:
List_Variable = [E1, E2, E3 …… En]
print (List_Variable[index of a element])
Ex:

x = [10, 20, 30,40]


print (x[0])

Output: 10

24. How to access all elements of a list? Give example. *


 Loops are used to access all elements from a list.
 Initial value of the loop must be zero.
Ex:

x = [10, 20, 30, 40]


i=0
while i < 4:
print (x[i])
i=i+1
Output:
10
20
30
40

25. How to access elements using for loop in list? Give example. *
 for loop is used to access all the elements in a list one by one.
Syntax:

for index_var in list:


print (index_var)
Ex: Output: 10
20
x=[10,20,30,40]
for i in x : 30
print(i) 40

109
26. Write a note on range() in list. Give example. *

 range( ) function is used to create list with series of values.


 It has 3 arguments.
1. start value  beginning value(Zero is the default)
2. end value  ending value as upper limit – 1.
3. step value  optional argument
syntax:
range (start value, end value, step value)
Ex:

for x in range (2, 11, 2):


print(x)

Output: 2
4
6
8
10
27. How to create a list with a series of values? Give example.
 List( ) function convert the result of range( ) function into list .
Syntax:
List_Varibale = list ( range ( ) )

Ex:

x = list(range(2,11,2))
print(x)

Output: [2, 4, 6, 8, 10]

28. How to change list elements? Give example.


 Lists are mutable(changed).
 A list element can be changed or altered by assignment operator (=).
Syntax:
List_Variable [index of an element] = Value to be changed
List_Variable [index from : index to] = Values to changed

 index from  beginning index.


 index to  ending index(upper limit of the range)

110
Ex: Output:

mark= [60, 70, 90, 100] 60


mark[2] = 80 70
for j in mark: 80
print (j) 100

Tuples
29. What is tuple? Give example. *
 Tuples consists of number of values separated by comma, enclosed within parentheses( )
 Tuple is similar to list,
 The values in a list cannot be changed.
Ex:
t = (1,2,3,‟A‟,”Python”)

30. How to create tuples? Give example. *


 Elements defined within parenthesis or without parenthesis, separated by comma
Syntax:

Tuple_Name=()
Tuple_Name=(E1,E2,E3,……..En)
Tuple_Name=E1,E2,E3,………En
Ex:
T=(1,2,3,‟S‟)
print(T)

Output: (1,2,3,‟S‟)

31. How to create a tuple with a single element? Give example.

 Creating a Tuple with one element is called “Singleton” tuple.


To create a tuple with a single element
 Add a comma at the end of the element.
Ex:

tup = (10,)
type(tup)

Output: <class 'tuple'>

111
32. How to access values in a tuple?

 Tuple elements can be easily accessed by using index number, starts from 0
Ex:
t=(10,20,30,‟cs‟, a)
print( t [1:4] ) Output: (20,30,‟cs‟)

33. How to update and delete a tuple? Give example.

Updating a tuple:
 Tuple is immutable (cannot be changed).
 Joining two tuples or deleting the entire tuple is possible.
Ex: ( updating- joining two tuple )

t1 = (2,4,6,8,10)
t2 = (1,3,5,7,9)
t3 = t1 + t2
print(t3) Output: (2, 4, 6, 8, 10, 1, 3, 5, 7, 9)

Deleting a tuple:
 del command can be used to delete an entire tuple
Syntax:
del tuple_name
Ex:
T= (2,4,6,8,10)
del T

34. What is tuple assignment? Give example. *


 It is a powerful feature.
 It allows a tuple variable on the left to the values on the right side of the assignment
operator.
Note: ( Tuple_variable) = (value)
Ex:

(a, b, c) = (10, 20, 30)


print(a,b,c)

Output: 10 20 30

112
35. How to create tuples using tuple() function? Give example. *

 Tuple( ) function is used to create tuples from a list.


 Tuple elements should be enclosed within square brackets [ ].
Syntax:
Tuple_Name = tuple( [list elements] )

Ex:

T = tuple( [10, 20, 30] )


print(T)

Output: (10 20 30)

36. How to return multiple values in a tuple? Give example.

 Normally, a function can return only one value at a time.


 Python returns more than one value from a function.
Ex:

def MinMax(n):
a = max(n)
b = min(n)
return(a, b)
n = (10,20,30,40,50)
(a,b) = MinMax(n)
print("Maximum ", a)
print("Minimum ", b)

Output:
Maximum 50
Minimum 10

113
Sets
37. What is set in python? (OR) How to create a set in python? Give example *

 It is an unordered collection of elements enclosed within { } without duplicates.


 It is a mutable (changeable)
 It is another type of collection data type.
 set( ) function can also used to create sets.
Syntax:
Set_Variable = {E1, E2, E3 …….. En}

Ex:
S={1,2,3,'A',3.14}

38. How to create set using list or tuple? Give example.

 A list or Tuple can be converted as set by using set( ) function.


Syntax:
set (list or tuple variable)

Ex:

x=[10,20,30,40]
s=set(x)
print(s)
Output: {10,20,30,40}

Dictionary
39. What is a dictionary? (OR) How to create a dictionary? Give example. *

 It is a mixed collection of elements separated by commas (,)


 It stores a key along with its element.
 Keys in dictionary is separated by a colon ( : )
 Key value pairs are enclosed with curly braces { }.

114
Syntax:

Dictionary_Name = { Key_1 : Value_1,


Key_2 : Value_2,
……..
Key_n : Value_n }

 Dictionary Key must be unique case sensitive and valid Python type.

Ex:
d = { Regno: 101,
Name:‟Sairam‟,
Class:‟XII‟,
Mark:580}

Note : Regno, Name, Class , Mark  Keys

101, Sairam, XII, 580  values

40. What is a dictionary comprehension? Give example. *

 It is another way of creating dictionary.


Syntax: Dict = { expression for variable in sequence [if condition]
Ex: }
d= { x : 2 * x for x in range(1,5)}

Output: {1: 2, 2: 4, 3: 6, 4: 8}

41. How to access elements in a dictionary? Give example. *


 To access a particular element, square brackets can be used along with key.
Ex:
d = { 'rno': '101', 'name' : 'Sairam', 'tot' : 580}
print("Rollno: ", d['rno'])
print("Name: ", d['name'])
print("Total:" , d[tot])

Output: Rollno: 101 Name: Sairam total: 580

42. How to add elements in a dictionary? Give example.


 We can add more values by simply assigning the value along with key.

115
Syntax:
dictionary_name [key] = value/element
Ex:
d = { 'Rno': '123', 'Name' : 'Sairam', 'Total' : 500}
d[„Class‟]=‟12‟
print(d)

Output: { Rno: 123 Name: Sairam Total: 500 Class 12 }


43. How to modify elements in a dictionary?

 Assign a value to a key, it will simply overwrite the old value.

44. How to delete elements in a dictionary? Give example.


 del keyword used to delete a particular element or entire dictionary.
 clear( ) function  used to delete all the elements in a dictionary.
Syntax:
del dictionary_name[key]
dictionary_name.clear( )
del dictionary_name
Ex:
d = { 'name' : 'A', 'total' : 500}
del d[„name‟]

45. What will be the output of the following python snippet?

Marks = [10, 23, 41, 75]


print (Marks[0])

Output: 10

46. What will be the output of the following python snippet?


Marks = [10, 23, 41, 75]
print (Marks[-1])

Output: 75

116
47. What will be the output of the following python snippet?

Marks = [10, 23, 41, 75]


i=0
while i < 4:
print (Marks[i])
i=i+1
Output: 10
23
41
75
48. What will be the output of the following python snippet?
Marks = [10, 23, 41, 75]
i=0
while i >= -4:
print (Marks[i])
i=i-1
Output: 75
41
23
10

49. What will be the output of the following python snippet?


Marks = [10, 23, 41, 75]
i=0
while i >= -4:
print (Marks[i])
i=i-1

Output: 75
41
23
10
50. What will be the output of the following python snippet?

Marks=[“Tamil”,”English”,”comp.science”,”Maths”]
len(Mysubject)

Output: 4

117
51. What will be the output of the following python snippet?
Marks=[“Tamil”,”English”,”comp.science”,”maths”] Output: Tamil
i=0 English
while i < len(MySubject):
comp.science
print (MySubject[i])
i=i+1 Maths

52. What will be the output of the following python snippet?


Marks=[23,45,67,78,98] Output: 23
for x in Marks: 45
print( x ) 67
78
98
53. What will be the output of the following python snippet?
MyList = [2, 4, 5, 8, 10] Output:
print ("MyList elements before update... ") MyList elements before update...
for x in MyList: 2
print (x) 4
MyList[2] = 6 5
8
print ("MyList elements after updation... ") 10
for y in MyList: MyList elements after updation...
print (y) 2
4
6
8
10
54. What will be the output of the following python snippet?

MyList = [1, 3, 5, 7, 9] Output:


List Odd numbers...
print ("List Odd numbers... ")
1
for x in MyList: 3
print (x) 5
MyList[0:5] = 2,4,6,8,10 7
9
print ("List Even numbers... ")
List Even numbers...
for y in MyList: 2
print (y) 4
6
8

118
55. What will be the output of the following python snippet?

MyTup1 = (23, 56, 89, 'A', 'E', 'I', "Tamil")


print(MyTup1)

Output: (23, 56, 89, 'A', 'E', 'I', 'Tamil')

56. What will be the output of the following python snippet?


MyTup3 = tuple( [23, 45, 90] )
(creating using tuple() function)
print(MyTup3)

Output: (23, 45, 90)

57. What will be the output of the following python snippet?

MyTup1 = tuple( [23, 45, 90] )


MyTup2 = (10)
MyTup3 = (10.4)
MyTup4 =[10,20,30,40,50]
MyTup5 =(10,)
MyTup6=[10.5,20.6,30,4] Output:
print(type(MyTup1)) <class 'tuple'>
print(type(MyTup2)) <class 'int'>
print(type(MyTup3)) <class 'float'>
print(type(MyTup4)) <class 'list'>
print(type(MyTup5)) <class 'tuple'>
print(type(MyTup6)) <class 'list'>

58. What will be the output of the following python snippet?

Tup1 = (12, 78, 91, "Tamil", "Telugu", 3.14, 69.48)


print(Tup1)
print(Tup1[2:5])
print(Tup1[:5])
print(Tup1[4:])
print(Tup1[:])

119
Output:
(12, 78, 91, 'Tamil', 'Telugu', 3.14, 69.48)
(91, 'Tamil', 'Telugu')
(12, 78, 91, 'Tamil', 'Telugu')
('Telugu', 3.14, 69.48)
(12, 78, 91, 'Tamil', 'Telugu', 3.14, 69.48)

59. What will be the output of the following python snippet?

Tup1 = (2,4,6,8,10)
Tup2 = (1,3,5,7,9)
Tup3 = Tup1 + Tup2
print(Tup3)

Output: (2, 4, 6, 8, 10, 1, 3, 5, 7, 9)

60. What will be the output of the following python snippet?

Tup1 = (2,4,6,8,10)
print("The elements of Tup1 is ",
Tup1)
del Tup1
print (Tup1)

Output: Error
Traceback (most recent call last):
File "C:/Users1/ Local/Programs/Python/Python310/nn.py",line 4,in <module>
print (Tup1)
NameError: name 'Tup1' is not defined

61. What will be the output of the following python snippet?

(a, b, c) = (34, 90, 76) Output:


34 90 76
print(a,b,c)
4 5.666666666666667 1 False
(x, y, z, p) = (2**2, 5/3+4, 15%2, 34>65)
print(x,y,z,p)

120
62. What will be the output of the following python snippet?

def min_max(n):
a = max(n)
b = min(n)
return(a, b)
num = (12, 65, 84, 1, 18, 85, 99) Output:
(max_num, min_num) = min_max(num) Maximum value = 99
print("Maximum value = ", max_num) Minimum value = 1
print("Minimum value = ", min_num)
63. What will be the output of the following python snippet?

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)
64. What will be the output of the following python snippet?

a = int(input("Enter value of A: "))


b = int(input("Enter value of B: "))
print("Value of A = ", a, "\n Value of B = ", b)
(a, b) = (b, a)
print("Value of A = ", a, "\n Value of B = ", b)

Output:
Enter value of A: 54
Enter value of B: 38
Value of A = 54
Value of B = 38
Value of A = 38
Value of B = 54

121
65. What will be the output of the following python snippet?

Dict = { x : 2 * x for x in range(1,10)}

Output: {1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}

66. What will be the output of the following python snippet?

MyDict = { 'Reg_No': '1221',


'Name' : 'Tamilselvi',
'School' : 'CGHSS',
'Address' : 'Rotler St., Chennai 112' }
print(MyDict)
print("Register Number: ", MyDict['Reg_No'])
print("Name of the Student: ", MyDict['Name'])
print("School: ", MyDict['School'])
print("Address: ", MyDict['Address'])

Output:

{'Reg_No': '1221', 'Name': 'Tamilselvi', 'School': 'CGHSS', 'Address': 'Rotler St., Chennai 112'}
Register Number: 1221
Name of the Student: Tamilselvi
School: CGHSS
Address: Rotler St., Chennai 112

67. What will be the output of the following python snippet?

MyDict = { 'Reg_No': '1221',


'Name' : 'Tamilselvi',
'School' : 'CGHSS',
'Address' : 'Rotler St., Chennai 112' }
print(MyDict)
print("Register Number: ", MyDict['Reg_No'])
print("Name of the Student: ", MyDict['Name'])
MyDict['Class'] = 'XII - A'
print("Class: ", MyDict['Class'])
print("School: ", MyDict['School'])
print("Address: ", MyDict['Address'])
122
Output:
{'Reg_No': '1221', 'Name': 'Tamilselvi', 'School': 'CGHSS', 'Address': 'Rotler St., Chennai 112'}
Register Number: 1221
Name of the Student: Tamilselvi
Class: XII - A
School: CGHSS
Address: Rotler St., Chennai 112
68. What will be the output of the following python snippet?

Dict = {'Roll No' : 12001, 'SName' : 'Meena', 'Mark1' : 98, 'Marl2' : 86}
print("Dictionary elements before deletion: \n", Dict)
del Dict['Mark1'] # Deleting a particular element
print("Dictionary elements after deletion of a element: \n", Dict)
Dict.clear() # Deleting all elements
print("Dictionary after deletion of all elements: \n", Dict)
del Dict
print(Dict) # Deleting entire dictionary

Output: Dictionary elements before deletion:


{'Roll No': 12001, 'SName': 'Meena', 'Mark1': 98, 'Marl2': 86}
Dictionary elements after deletion of a element:
{'Roll No': 12001, 'SName': 'Meena', 'Marl2': 86}
Dictionary after deletion of all elements:
{}
Line:8 NameError: name 'Dict' is not defined. Did you mean: 'dict'?

69. Write a program to generate whole numbers upto 10

for x in range (1, 11):


print(x)
Output: 1
2
3
4
5
6
7
8
9
10

123
70. Write a program to generate first 10 even numbers.
for x in range (2, 11, 2):
print(x)
Output: 2
4
6
8
10

71. Write a program to generate of first 10 natural numbers.


squares = [ ]
for x in range(1,11):
s = x ** 2
squares.append(s)
print (squares)
Output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

72. Write a program to generate of first 10 natural numbers using the concept of List
comprehension.
squares = [ x ** 2 for x in range(1,11) ]
print (squares)

Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

73. Write a program that creates a list of numbers from 1 to 20 that are divisible by 4.

divBy4=[ ]
for i in range(21):
if (i%4==0):
divBy4.append(i)
print(divBy4)

Output: [0, 4, 8, 12, 16, 20]

124
74. Write a program to create a list of numbers in the range 1 to 10. Then delete all the even
numbers from the list and print the final list.

Num = []
for x in range(1,11):
Num.append(x)
print("The list of numbers from 1 to 10 = ", Num)
for index, i in enumerate(Num):
if(i%2==0):
del Num[index]
prinprint("The list after deleting even numbers = ", Num)

Output:
The list of numbers from 1 to 10 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The list after deleting even numbers = [1, 3, 5, 7, 9]

75. Write a program to generate in the Fibonacci series and store it in a list. Then find the sum
of all values.

a=-1
b=1
n=int(input("Enter no. of terms: "))
i=0
sum=0
Fibo=[]
while i<n:
s=a+b
Fibo.append(s)
sum+=s
a=b
b=s
i+=1
print("Fibonacci series upto "+ str(n) +" terms is : " + str(Fibo))
print("The sum of Fibonacci series: ",sum)

Output: Enter no. of terms: 10


Fibonacci series upto 10 terms is : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
The sum of Fibonacci series: 88

125
76. Write a program to swap two values using tuple assignment
Output:
a = int(input("Enter value of A: "))
Enter value of A: 54
b = int(input("Enter value of B: "))
Enter value of B: 38
print("Value of A = ", a, "\n Value of B = ", b) Value of A = 54
(a, b) = (b, a) Value of B = 38
print("Value of A = ", a, "\n Value of B = ", b) Value of A = 38
Value of B = 54

77. Write a program using a function that returns the area and circumference of a circle whose
radius is passed as an argument.two values using tuple assignment
pi = 3.14
def Circle(r):
return (pi*r*r, 2*pi*r)
radius = float(input("Enter the Radius: "))
(area, circum) = Circle(radius)
print ("Area of the circle = ", area)
print ("Circumference of the circle = ", circum)

Output:
Enter the Radius: 5
Area of the circle = 78.5
Circumference of the circle = 31.400000000000002

78. Write a program that has a list of positive and negative numbers. Create a new tuple
that has only positive numbers from the list.

Numbers = (5, -8, 6, 8, -4, 3, 1)


Positive = ( )
for i in Numbers:
if i > 0:
Positive += (i, )
print("Positive Numbers: ", Positive)

Output: Positive Numbers: (5, 6, 8, 3, 1)

126
79. What will be the output of the following python snippet?

Output:
A={x*3 for x in range(1,6) Output:
{3, 6, 9, 12, 15}
B={y**2 for y in range(1,10,2)}
{1, 9, 81, 49, 25}
print(A)
{1, 3, 6, 9, 12, 15, 81, 49, 25}
print(B)
{3, 12, 6, 15}
print(A|B) {9}
print(A-B) {1, 3, 6, 12, 15, 81, 25, 49}
print(A&B)
print(A^B)

80. What will be the output of the following python snippet?

mydict={chr(x):x for x in range(97,102)}


print(mydict)

Output: {'a': 97, 'b': 98, 'c': 99, 'd': 100, 'e': 101}

80. What will be the output of the following python snippet?

setA={„A‟,2, 4,‟D‟} Output: {2, 4, 'C', 'B', 'D', 'A'}


setB={„A‟,‟B‟,‟C‟,‟D‟} {'A', 'D'}
print(setA | setB) {2, 4}
print(setA & setB) {2, 4, 'C', 'B'}
print(setA - setB)
print(setA ^ setB)

80. What will be the output of the following python snippet?

alpha=list(range(65,70))
for x in alpha:
print(chr(x),end='\t')

Output: A B C D E

127
81. Explain the difference between del and clear() in dictionary with an example. *
s.no del statement clear() function
1 Used to delete a particular element in Used to delete all the elements in a
a dictionary.(or) dictionary.
Remove the dictionary
2 Syntax: Syntax:
del List [index of an element] List.clear( )
del List [index from : index to]
del List
3 Ex: x =[10,20,30] Ex: x=[10,20,30]
del x[1] x.clear()

5 Marks: (Book Back Questions)


1. What are the different ways to insert an element in a list.
Explain with suitable example. (Book Back) *
Different ways to insert an element in a list :
1) append( ) function
2) extend( ) function
3) insert( ) function
append() function:
 It is used to add a single element in a list.

syntax: List.append (element to be added)

Ex:
x=[10,20,30]
x.append(40)
print(x)

Output : [10,20,30,40]

extend() function:
 It is used to add more than one element to an existing list.
 Multiple elements given within square bracket as arguments of the function.
Syntax:
List.extend ( [elements to be added ])

128
Ex:
y=[10,20]
y.extend([30,40])
print(y)
Output : [10,20,30,40]

insert() function:
 It is used to insert an element at any position of a list.
 While inserting a new element at a particular location, the existing elements
shifts one position to the right.
Syntax:
List.insert (position index, element)

Ex:
x=[10,30,40]
x.insert(1,20)
print(x)

Output : [10,20,30,40]

2. What is the purpose of range()? Explain with an example. (Book back) *


range() function:
 It is used to create list with series of values.
 It has 3 arguments.
1) start value
2) end value
3) step value
syntax:
range (start value, end value, step value)

 start value – beginning value of series( Zero is the default value)


 end value – ending value of series (upper limit-1)
 step value – optional argument (Different interval of values)
Ex:
for x in range (2, 11, 2):
print(x)
Output:
2
4
6
8
10 129
Creating a list with series of values using list() function:
 It convert the result of range( ) function into list .
Syntax:

List_Varibale = list ( range ( ) )

Ex:

x= list(range(2,11,2))
print(x)
Output: [2, 4, 6, 8, 10]

3. Explain the different set operations supported by python with suitable example.() *
 python supports the set operations .
 set operations are
1. Union ( | )
2. Intersection (&)
3. difference (-)
4. Symmetric difference(^)
Union :
 It includes all elements from two or more sets.
 Here, | operator (or) union( ) function is used.

Ex:
setA={10,20,30} setA={10,20,30}
setB={30,40,50} (or) setB={30,40,50}
print(setA | setB) print(setA.union(setB))

Output: {50, 20, 40, 10, 30}

130
Intersection:
 It includes the common elements in two sets.
 Here, &operator (or) intersection( ) function is used.

Ex:
setA={10,20,30} setA={10,20,30}
setB={30,40,50} (or) setB={30,40,50}
print(setA & setB) print(setA.intersection(setB))

Output: {30}
Difference:
 It includes all elements that are in first set (say set A)
but not in the second set. (say set B)
 Here, minus(-)operator (or) difference( ) function is used.

Ex:
setA={10,20,30} setA={10,20,30}
setB={30,40,50} (or) setB={30,40,50}
print(setA - setB) print(setA.difference(setB))

Output: {10,20}

Symmetric difference:
 It includes all the elements that are in two sets (sets A and B),
that are not common to two sets.

131
 Here, caret (-)operator (or) symmetric_difference( ) function is used.

Ex:
setA={10,20,30} setA={10,20,30}
setB={30,40,50} (or) setB={30,40,50}
print(setA ^ setB) print(setA.symmetric_difference(setB))

Output: {40, 10, 50, 20}

4. What is nested tuple? Give example. (Book Back) *


 A tuple can be defined inside another tuple is called Nested tuple.
 In a nested tuple, each tuple is considered as an element.
 The for loop is used to access all the elements in a nested tuple.
Ex:

tup = ((1,2,3), (4,5,6))


for i in tup:
print(i)

Output:
(1,2,3)
(4,5,6)

132
Additional 5 Marks Quesitons:

1. Explain the other important functions of list.


Function Description Syntax Example
copy ( ) Returns a copy of the list x=[12, 12, 36]
List.copy( ) y = x.copy()
print(y)

Output: [12, 12, 36]


count ( ) Returns the number of List.count(value) x=[36 ,12 ,12]
similar elements in the list. y = x.count(12)
print(y)

Output: 2
index ( ) Returns the index value
of the first recurring element x=[36 ,12 ,12]
List.index(element)
y = x.index(12)
print(y)

Output: 1
reverse ( ) Reverse the order of the
element in the list. List.reverse( ) x=[36 ,23 ,12]
x.reverse()
print(x)

Output: [12 ,23 ,36]

133
sort ( )  1.Sorts the element in
list . List.sort(reverse=True|False,
x=[1,2,3]
2. 2.Both arguments are key=myFunc) x.sort(reverse=True)
optional. print(x)
3. Default order
Ascending Output: [3,2,1]

4.Reverse=True
(Descending order)
5.Reverse=False
(Ascending order)
6. Key=myFunc;
7. myFunc
 User defined
function.
 specifies the criteria.

max( ) Returns the maximum


value in a list. max(list) x=[21,76,98,23]
print(max(x))

Output: 98
min( ) Returns the minimum x=[21,76,98,23]
value in a list. min(list) print(min(x))

Output: 21
sum( ) Returns the sum of x=[1,2,3]
values in a list. print(sum(x))
sum(list)
Output: 6

134
SYNTAX
1) creating list
Variable=[element-1,element-2,element-3......element-n

2) Accessing list elements.


List_Variable = [E1, E2, E3 …… En]
print (List_Variable[index of a element])

3) Accessing list elements using for loop.


for index_var in list:
print (index_var)

4) Changing list elements.


List_Variable [index of an element] = Value to be changed
List_Variable [index from : index to] = Values to changed

5) Append() and extend() function


List.append (element to be added)
List.extend ( [elements to be added])

6) Insert() function
List.insert (position index, element)

7) Delete elements from a list using del statement


del List [index of an element]
del List [index from : index to]
del List

8) Delete elements from a list using remove() function.


List.remove(element)
List.pop(index of an element)
List.clear( )

135
9) Range() function in list
range (start value, end value, step value)

10) Creating a list with series of values.


List_Varibale = list ( range ( ) )

11) List comprehensions


List = [ expression for variable in range ]

12) Creating tuple


Tuple_Name=()
Tuple_Name=(E1,E2,E3,……..En)
Tuple_Name=E1,E2,E3,………En

13) Creating tuples using tuple() function.


Tuple_Name = tuple( [list elements] )

14) Deleting tuple


del tuple_name

15) Creating set


Set_Variable = { E1, E2, E3 …….. En }

16) Creating dictionary


Dictionary_Name = { Key_1: Value_1,
Key_2:Value_2,
……..
Key_n:Value_n }
17) Dictionary comprehension.
Dict = { expression for variable in sequence [if condition] }

18) Deleting dictionary


del dictionary_name[key]
dictionary_name.clear( )
del dictionary_name

136
Unit III - Chapter 10. CLASSES AND OBJECTS
===============================================
2 Marks: (Book Back Questions)
1. What is class? *

 Class is the main building block in python.


 Object is a collection of data and function.
 Class is template for the object.
Syntax: Example:

class class – name : class student :


statement -1 mark1=80
statement -2 mark2=90
…..….
………
Statement n

2. What is instantiation? *

 The process of creating object is called as “Class instantiation”.


 Once a class is created, next step is, create an object or instance of that class.

Syntax :
object_name = class_name ( )

Ex: s=student( ) s is a object

3. What is the output of the following program? *

class sample : Output :


_ _num = 10
def disp (self): 10
print(self._ _num) Error at line no 7
s = sample() print (s._ _num)
s.disp()
Here _ _ num is private class variable.
print (s._ _num)
So it cannot access from outside of the class.

137
4. How will you create constructor in python? *
 Constructor is the special function .
 It is automatically executed“ when an object of a class is created “.
 In python, there is a special function called “init”.
 _ _init_ _( ) function is used as a constructor.
 init function must begin and end with double (_ _) underscore.
Syntax :
def _ _init_ _ (self, [args…]):
<statements>

5. What is the purpose of destructor? *


 Destructor is also a special function.
 It is opposite to constructor.
 It is executed automatically “when an object exit from the scope “.
 _ _del_ _ ( ) method is used as destructor.
 It removes memory space.
Syntax :
def _ _del_ _ (self):
<statements>

3 Marks: (Book Back Questions):


6. What are class members? How do you define it? *
 Variables “defined inside a class “ are called as class variable.
 Functions are called as method.
 Class variable and methods are together known as members of the class.
(or)

Class Members

Variables Function
(Class variables) (Methods)
Ex:
class student:
mark1=80  Class variables
mark2=90
def total(): method
sum=mar1+mark2
print(sum)

138
7. Write a class with two private class variables and print the sum using a method. *
class calculation:
_ _ a=0
_ _ b =0
def add(a,b) :
sum=a+b
print(sum)
return
x=calculation()
x.add (10,20)

8. Find the error in the following program to get the given output? *

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')
delF.display
F.display()

Output :
Fruit 1 = Apple, Fruit 2 = Mango
Error :
delF.display

9. What is the output of the following program? *

class Greeting:
def __init__(self, name):
self.__name = name
def display(self):
print("Good Morning ", self.__name)
obj=Greeting('BinduMadhavan')
obj.display()

Output: Good Morning BindhuMadhavan

139
10. How do you define constructor and destructor in python?

Constructor:
 Constructor is the special function .
 It is automatically executed“ when an object of a class is created “.
 In python, there is a special function called “init”.
 _ _init_ _( ) function is used as a constructor.
 init function must begin and end with double ( _ _ ) underscore.
Syntax :

def _ _init_ _ (self, [args…]):


<statements>

Destructor:
 Destructor is also a special function.
 It is opposite to constructor.
 It is executed automatically “when an object exit from the scope “.
 _ _del_ _ ( ) method is used as destructor.
 It removes memory space.
Syntax :

def _ _del_ _ (self):


<statements>

Additional 2 Marks & 3 Marks Questions :


11. Write a note on class methods? *

 The first argument of class method is must be „self‟ argument.


 No need to pass value for self argument, when we call the method.
 Python gives value automatically.
 If a method is defined to accept only one argument,
it will take it as two arguments.
(ie)
1. self argument
2. defined argument

140
12. How will you access the class members?

 Any class member /class variable /method (function) can be accessed by using
object with a dot(.) operator.
Syntax:
object_name.classmember

Ex: s.mark1
s.total( )

13. What is self arguments?

 The first argument of class method is must be „self‟ argument.


 No need to pass value for self argument, when we call the method.
 Python gives value automatically.
 If a method is defined to accept only one argument,
it will take it as two arguments.
(ie) 1. self argument
2. defined argument

13. What is the different between Private and Public member data in class? *

Private Public

1 Not default default


2 Double underscore (_ _) used with no special character used.
prefix of variable.
Ex:
Ex:
mark1=80
_ _ a=10
3 Accessed only within the class. Accessed anywhere in the program
Using dot operator

14. Name the function which acts as a constructor and destructor.


Answer:
i) constructor ( _ _init_ _ )
ii) destructor ( _ _del_ _ )

141
15. What is the different between constructor and selector? *

s.no Constructor Destructor

1 It is automatically executed It is automatically executed


“when an object of a class is created “. “when an object exit from the scope “.
2 _ _init_ _( ) function is used _ _del_ _ ( ) function is used

3 syntax : syntax :

def _ _ init_ _( self,[args….]): def _ _ del_ _( self):


<statements> <statements>

16. Write a note on public and private data members of python class.

public data members:

 The variables which are defined inside the class is public by default.
 These variables can be accessed anywhere in the program using dot operator.
Ex: mark1=80
private data members:
 A variable prefixed with double underscore( _ _) becomes private in nature.
 These variables can be accessed only within the class.
Ex: _ _ a=10

17. Write the syntax for the following


i) creating objects
ii) Accessing class members
Answer:
i) object_name=class_name()
ii) object_name=class_member

18. What will be the output of the following python snippet?

class Sample: Output:


x, y = 10, 20 #class variables Value of x = 10
S=Sample( ) # class instantiation Value of y = 20
print("Value of x = ", S.x) Value of x and y =30
print("Value of y = ", S.y)
print("Value of x and y = ", S.x+S.y)
142
19. What will be the output of the following python snippet?

class Student:
mark1, mark2, mark3 = 45, 91, 71 #class variable
def process(self): #class method
sum = Student.mark1 + Student.mark2 +
Student.mark3
avg = sum/3
print("Total Marks = ", sum)
print("Average Marks = ", avg)
return
S=Student()
S.process()

Output: Total Marks = 207


Average Marks = 69.0

20. What is the output of the following program? *

class Greeting:
def __init__(self, name):
self.__name = name
def display(self):
print("Welcome to",
self.__name)
obj=Greeting('Python programming‟)
obj.display()

Output:
Welcome to Python programming

21. What will be the output of the following python snippet?

class Odd_Even:
def check(self, num):
if num%2==0: Output:
print(num," is Even number") Enter a value: 5
else: 5 is Odd number
print(num," is Odd number")
n=Odd_Even()
x = int(input("Enter a value: "))
n.check(x)

143
22. What will be the output of the following python snippet?
class Sample:
def __init__(self, num):
print("Constructor of class Sample...")
self.num=num
print("The value is :", num)
S=Sample(10)
Output: Constructor of class Sample...
The value is : 10
23. What will be the output of the following python snippet?
class Sample:
num=0
def __init__(self, var):
Sample.num+=1
self.var=var print("The object value is = ", var)
print("The count of object created = ", Sample.num)
S1=Sample(15)
S2=Sample(35)
S3=Sample(45)
Output: The object value is = 15
The count of object created = 1
The object value is = 35
The count of object created = 2
The object value is = 45
The count of object created = 3

24. What will be the output of the following python snippet?


class Sample:
def __init__(self, n1, n2):
self.n1=n1
self.__n2=n2
def display(self):
print("Class variable 1 = ", self.n1)
print("Class variable 2 = ", self.__n2)
S=Sample(12, 14)
S.display()
print("Value 1 = ", S.n1)
print("Value 2 = ", S.__n2)
144
Output:
Class variable 1 = 12
Class variable 2 = 14
Value 1 = 12
Traceback (most recent call last):
File "C:/Users/1/AppData/Local/Programs/Python/tt.py", line 11, in <module>
print("Value 2 = ", S.__n2)
AttributeError: 'Sample' object has no attribute '__n2'

25. What will be the output of the following python snippet?

class Circle:
pi=3.14
def __init__(self,radius):
self.radius=radius
def area(self):
return Circle.pi*(self.radius**2)
def circumference(self):
return 2*Circle.pi*self.radius
r=int(input("Enter Radius: "))
C=Circle(r)
print("The Area =",C.area())
print("The Circumference =", C.circumference())

Output:
Enter Radius: 5
The Area = 78.5
The Circumference = 31.400000000000002
26. Fill up the blanks in the following program to get the output:
Value of x = 10
Value of y = 20
Value of x and y = 30
class sample:
x, __ = 10, 20 1
s=________ 2
print("Value of x = ", ______) 3
print("Value of y = ", _______) 4
print("Value of x and y = ", _________) 5
145
Answer:
1) y
2) sample()
3) s.x
4) s.y
5) s.x+s.y

27. Read the following program. Answer the following question.

class number: Questions:


a, b, c= 5, 3, 9 1. What does number denotes?
m=number() 2. What does a,b,c denotes?
print(m.a+m.b+m.c) 3. What does m denotes?

Answer:
1. number  class name
2. a,b,c  class variable of the class
3. m  object created to access the members of the class

5 Marks: (Book Back Questions)


1. Explain the constructor and destructor with an example. (Additional question)
Constructor:
 It is the special function .
 It is automatically executed “when an object of a class is created”.
 In python, there is a special function called “init” .
 _ _init_ _( ) function is used
 init function must begin and end with double (_ _) underscore.
Syntax : def _ _init_ _ (self, [args…]):

<statements>
Destructor:
 It is a special function.
 It is opposite to constructor.
 It is automatically executed “ when an object exit from the scope “.
 _ _del_ _ ( ) method is used.
 It removes memory space.
 del function must begin and end with double (_ _) underscore.

146
Syntax : def _ _del_ _ (self):

<statements>

Example program:

class sample:
def _ _init_ _(self,num) : Output:
print(“Constructor”) Constructor
self.num=num The value is:10
print(“The value is:”,num) Destructor
def _ _del_ _(self) :
print(“Destructor”)
s=sample(10)

2. What is class? How will you access the class member? Explain with example.
(Additional question)
Class:
 Class is the main building block in python.
 Object is a collection of data and function
 Class is template for the object.
Syntax: class class – name :
statement -1
statement -2
…..….
………
statement n
Instantiation:
 The process of creating an object is called as “Class instantiation”.
Syntax : Object_name = class_name ( )

Class members:
 Variables “defined inside a class” are called as class variable.
 Functions are called as method.
 Class variable and methods are together known as members of the class.

147
Method:
 „self‟ is the first argument of class method.
 No need to pass a value for self argument.
 Python provides values automatically.
 If a method is defined to accept only one argument,
it will take it as two arguments.
(i.e)
1.self argument
2. defined argument

Access the class members:

 Any class member /class variable / method (function) can be accessed by using
object with a dot(.) operator.

Syntax:
object_name.class_member

Example:
class sample:
x,y=10,20
s=sample( )
print(“The sum of x and y value is:”,s.x+s.y)

Output : The sum of x and y value is : 30

148
Unit IV - Chapter 11. DATABASE CONCEPTS
2 Marks: (Book Back Questions)
1. Mention few examples of a database.
 Dbase
 FoxPro

2. List some examples of RDBMS.


 Oracle
 MYSQL
 MS-Access
 SQL server
 SQLite
 MariaDB

3. What is data consistency?


 It means that “data values are the same“ at all instances of a database.
 Data, is continuously updated and added.
 Maintaining the consistency of data can become a challenge.

4. What is the difference between Hierarchical and Network data model?

s.no Hierarchical model Network data model

1. A child record has only one parent node A child record may have many parent nodes.

2. It represents the data in It represents the data in


one-to-many relationships. many-to-many relationships.

3. Data is represented as a simple Easier and faster to access the data.


“tree like structure form “.

5. What is normalization?
 Database Normalization was proposed by Dr.Edgar F Codd.
 DBMS follows Normalisation.
 Normalisation divides the data such a way that repetition is minimum.
 Normalization reduces data redundancy and improves data integrity .

149
3 Marks: (Book Back Questions)
6. What is the difference between select and project command?
s.no SELECT PROJECT

1. SYMBOL: σ SYMBOL: π

2. Used for selecting a subset with tuples Defines a relation that contains a
according to a given condition. vertical subset of relation.

3. Filters out all tuples that do not satisfy It eliminates all attributes of the input
condition. relation
4. Ex: σcourse=”BIG DATA”(Student) Ex: πcourse(Student)

7. What is the role of DBA?


 DBA - Database Administrator or DBA .
 DBA manages the complete database management system.
 DBA takes care of the “security of the DBMS, managing the user accounts and
access, managing license keys etc“.

8. Explain Cartesian product with a suitable Example.

 PRODUCT OR CARTESIAN PRODUCT Symbol :X


 Cross product is a way of “combining two relations “.
 The resulting relation contains, both relations being combined.
 A x B means A times B, where the relation A and B have different attributes.
 It is helpful to merge columns from two relations.

150
9. Explain Object Model with example.

 Object model stores the data in the form of “classes, objects, attributes and methods and
Inheritance”.
 It gives a clear modular structure.
 It is easy to maintain and modify the existing code.
 It is used in file Management System.
 It handles more complex applications,
Ex:
1. Geographic information System (GIS)
2. scientific experiments
3. engineering design and manufacturing.

STUDENT RESULT

LANGUAGE MATHS PHYSICS CHEMISTRY COMP.SCI.


E RY

10. Write a note on different types of DBMs users.


1. Database Administrators
 Database Administrator or DBA
 DBA manages the complete database management system.
 DBA takes care of the security of the DBMS, managing user accounts and
access, managing the license keys, etc.

2. Application Programmers or Software Developers


 It involved in developing and designing the parts of DBMS.
3. End User
 End users are the one who store, retrieve, update and delete data.
4. Database designers:

 It is responsible for identifying the data to be stored in the database for


choosing appropriate structures to represent and store the data.

151
Additional 2 Marks & 3 Marks Questions:
11. What is database?
 Database is a repository collection of related data organized in a way that data can be easily
accessed, managed and updated.

12. What is data?


 Data are raw facts stored in a computer
 Data is unprocessed data.
 It will not give any meaning.
 A data may contain any character, text, word or a number.
Eg: Name: vijay
Age: 16

13. What is information?


 Information is i) processed data
ii) organized data
iii) formatted data
 It allows to be utilized in a significant way.
 It will give meaningful message.
Eg: Vijay is 16 years old

14. What is database?


 Database is a repository collection of related data are organized.
 Data can be easily accessed, managed and updated.
 Database can be a software or hardware based, with one sole purpose of storing data.

15. Explain DBMS.


DBMS  Database Management System
 Computer based record keeping system.
 A DBMS is a software .
 It allows the user to create, define and manipulate database.
 It allows the users to store, process and analyze data easily.
 DBMS provides us an interface or a tool.
 It performs various operations(create database, store data , update data, etc.)
 It provides security and data consistency to the databases.

152
16. What are the advantages of RDBMS?
 Segregation of application program
 Data Redundancy
 Easy retrieval of data using the Query Language.
 Reduced development time and maintenance.

17. What are the types of DBMS users?


 Database Administrators
 Application programmers or software Developers
 Database designers.
 End user

18. Write a note on EF Codd Rules.


 Database normalization was first proposed by Dr. Edgar F Codd .
 It is as an integral part of RDBMS.
 In order to reduce data redundancy and improve data integrity.
 These rules are known as E F Codd Rules.

19. What are the components of DBMS?


 Hardware
 Software
 Data
 Procedures or Methods
 Database Access Languages

20. What is a procedure?


 They are general instructions to use a DBMS.
 such as installation of DBMS, manage databases to take backups, report generation, etc.

21. What is database access Language?


 It is a language.
 These languages are used to write commands.
 Commands for access, insert, update and delete data stored in any database.

22. What is table?


 Entire collection of related data in one table referred as a File or Table .
 In table, the data is organized as row and column.
 A Table is known as a RELATION.

153
23. What is row?
 Each row in a table represents a record.
 It is a set of data for each database entry.
 A Row is known as a TUPLE.

24. What is column?


 Each table column represents a Field.
 Field groups each piece or item of data among the records into specific categories or
types of data.
 A column is known as an ATTRIBUTE.

25. Explain data model?


 A data model describes “how the data can be represented “and “accessed from a
software “ after complete implementation .
Main purpose: How the final system or software will look like after development is
completed.
26. What are the types of Data model?
1. Hierarchical Model
2. Relational Model
3. Network Database Model
4. Entity Relationship Model
5. Object Model.

27. What are the types of relationship used in a database?


1. One-to-One Relationship
2. One-to-Many Relationship
3. Many-to-One Relationship
4. Many-to-Many Relationship

28. What is Relational Algebra?


 Relational Algebra was first created by Edgar F Codd while at IBM.
 Relational Algebra is a procedural query language.
 It is used to query the database tables using SQL.

29. What are the Unary Relational Operations?


1. SELECT ( symbol : σ)
2. PROJECT ( symbol : Π)

154
30. What are the Relational Algebra operations from Set Theory?
1. UNION (∪)
2. INTERSECTION (∩)
3. DIFFERENCE (−)
4. CARTESIAN PRODUCT (X)

31. What are the various groups divided by relational algebra?

Unary Relational Operations


1. SELECT ( symbol : σ)
2. PROJECT ( symbol : Π)
Relational Algebra Operations from Set Theory
1. UNION (∪)
2. INTERSECTION (∩)
3. DIFFERENCE (−)
4. CARTESIAN PRODUCT (X)

155
5 Marks: (Book Back Questions)
1. What are the characteristics of RDBMS? *

T. Ability 1. Ability to manipulate  RDBMS provides the facility to manipulate data (store,
data modify and delete) in a data base.

2. Reduced Redundancy  RDBMS follows Normalisation .


 It divides the data.
 In such a way that repetition is minimum.

3. Data Consistency  Data is continuously updated and added.


 Maintaining the consistency of data can become a
challenge.
 But DBMS handles it by itself.

4.4. Support Multiple user  RDBMS allows multiple users to work on insert, update,
and Concurrent Access delete data at the same time.
 still manages” to maintain the data consistency”.

5. Query Language  RDBMS provides users with a simple query language.


 Data can be for easily fetched, inserted, updated and
deleted data in a database.

6. Security RDBMS also takes care of,


 Security of data,
 protecting the data from unauthorized access,
from unauthorized access.
 Create user accounts with different access permissions
 Easily secure our data by restricting user access.

7 7.DBMS Supports  Allows us to better handle and manage data integrity in


Transactions real world application.
 Multithreading is extensively used.

2. Explain the different types of data model. *


1. Hierarchical Model
2. Relational Model
3. Network Database Model
4. Entity Relationship Model
5. Object Model

156
1) Hierarchical Model:

 It was developed by IBM( Information Management System)


 Here, data is represented as a simple tree like structure form.
 It represents a one-to-many relationship in parent-child relationship.
 One child can have only one parent.
 But one parent can have many children.
 It is mainly used in IBM Main Frame computers.

SCHOOL

CLASS

SUBJECT SECTION

THEORY LAB

2) Relational Database:
 It was first proposed by E.F. Codd in 1970 .
 It is the most widespread data model.
 It used for database application around the world.
 The basic structure of data in relational model is tables (relations).
 All the information‟s related to a particular type is stored in rows of that table.
 Tables are also known as relations.
 A relation key is an attribute which uniquely identifies a particular tuple/row.

STU-ID NAME SUB-ID SUB

1 A 1 X

2 B 2 Y

STU-ID SUB-ID MARKS

1 1 90

2 2 95

157
3) Network model:
 It is an extended form of hierarchical data model.
 In a Network model, a child may have many parent nodes.
 It represents the data in many-to-many relationships.
 It is easier and faster to access the data.

school

office library Staff room

student

4) ER model:

 It was developed by Chen in 1976.


 In this database model, relationship are created by
 dividing the object into entity and its
 characteristics into attributes.
 It is useful in developing a conceptual design for the database.
 It is very simple and easy to design logical view of data.

 Rectangle represents the entities.


 Ellipse represents the attributes.
 Attributes describes the characteristics.
 Diamond represents the relationship in ER diagrams

TEACHER RESULT STUDENT

T-Id T-Name S-Id S-Name

5) object model:
 It stores the data in the form of “classes, objects, attributes and methods and Inheritance”.
 It gives a clear modular structure.
 It is easy to maintain and modify the existing code.
 It is used in file Management System.

158
 It handles more complex applications,
such as
1. Geographic information System (GIS)
2. scientific experiments
3. engineering design and manufacturing.
STUDENT RESULT

LANGUAGE MATHS PHYSICS CHEMISTRY


CHEMISTRY COMP.SCI.
COMP.SCI.
E RY
RY

3. Differentiate DBMS and RDBMS? *

Basis of comparison DBMS RDBMS

Expansion Database Management Relational Database Management


System System

Data storage Navigational model Relational model (in tables)

(i.e)data by linked records (i.e) data in tables as row and column

Data redundancy Present Not Present

Normalization Not performed RDBMS uses normalization


to reduce redundancy

Data access Consumes more time Faster, compared to DBMS.

Keys and indexes Does not use. Used to establish relationship.


Keys are used in RDBMS.

Transaction Inefficient, Efficient and secure.


management Error prone and in secure

Distributed Databases Not supported Supported by RDBMS.

Example Dbase, FoxPro. Oracle, Mysql, SQL server, SQLite,


MariaDB, MS Access

159
4. Explain the types of relational mapping. *
Types of relationships:

1. One-to-One Relationship
2. One-to-Many Relationship
3. Many-to-One Relationship
4. Many-to-Many Relationship
1. One-to-One Relationship :
 Here, 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.
Ex: A student can have only one exam number.

STUDENT EXAM NO

Arun 101

Vino 102

Bala 102

2. One-to-Many Relationship :
 Here, one entity is related to many other entities.
 One row in a table A is linked to many rows in a table B.
 But one row in a table B is linked to only one row in table A.

Ex: One Department has many staff members

DEPARTMENT STAFF

Tamil Mano

English Kavi

CS Deva

160
3. Many-to-One Relationship :
 Here, many entities can be related with only one in the other entity.
 Multiple rows in staff members table is related with only one row in Department table.
Ex: A number of staff members working in one Department.

STAFF DEPARTMENT

Mano Tamil

Kavi English

Deva CS

4. Many-to-Many Relationship:
 Here, many entities can be related with many other entities.
 It occurs when multiple records in a table are associated with multiple records in another
table.
Ex: (Books and Student)
Many Books in a Library are issued to many students.

BOOK STUDENT

C++ Mano

SQL Kavi

JAVA Deva

161
5. Explain the different operators in relational algebra with suitable examples. *
 Relational Algebra is divided into various groups.
Unary Relational Operations
 SELECT ( symbol : σ)
 PROJECT ( symbol : Π)
Relational Algebra Operations from Set Theory
1. UNION (∪)
2. INTERSECTION (∩)
3. DIFFERENCE (−)
4. CARTESIAN PRODUCT (X)

SELECT ( symbol : σ )

General form: σ (R)


c with relation R and condition C on the attributes of R.
 It is used for selecting a subset with tuples according to a given condition.
 Select filters out all tuples that do not satisfy C.
STUDENT Table
Studno Name Course
cs1 Kannan Big Data
cs3 Lenin Big Data
cs4 Padmaja Python

Ex: σ = “Big Data” (STUDENT )


course

Output:
Studno Name Course
cs1 Kannan Big Data
cs3 Lenin Big Data
PROJECT: ( symbol : Π )
 It eliminates all attributes of the input relation but those mentioned in the projection list.
 It defines a relation that contains a vertical subset of Relation.

Ex: Πcourse(STUDENT)
Output:
Course
Big Data
R language
Python Programming

162
UNION (Symbol :∪)
 It includes all tuples that are in tables A or in B.
 It also eliminates duplicates.
 It would be expressed as A ∪ B

Ex: Consider the following 2 tables


Table A Table B
Studno Name Studno Name
cs1 Kannan cs1 Kannan
cs4 Padmaja cs3 Lenin
Output:
Table A ∪ B
Studno Name
cs1 Kannan
cs3 Lenin
cs4 Padmaja

SET DIFFERENCE ( Symbol : - )


 It 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.
 It would be expressed as A – B
Output:
Table A -B
cs4 Padmaja

INTERSECTION ( symbol : ∩ )
 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.
 It would be expressed as A ∩ B
Output:
Table A ∩ B
cs1 Kannan

PRODUCT OR CARTESIAN PRODUCT ( Symbol : X )


 Cross product is a way of combining two relations.
 The resulting relation contains, both relations being combined.
 A x B means A times B,
o where the relation A and B have different attributes.
 It is helpful to merge columns from two relations.

163
Ex:

 Cartesian product : Table A x Table B

Table A Table A
Studno Name Studno Name
cs1 Kannan cs1 Kannan
cs1 kannan cs3 Lenin
cs4 Padmaja cs1 Kannan
cs4 Padmaja cs3 Lenin

6. What are the components of DBMS? Explain. *

Hardware :
 The computer, hard disk, I/O channels for data, and any other physical component
involved in storage of data.

164
Software :
 It is a main component is a program.
 Software controls everything.
 DBMS software is capable of understanding the Database Access Languages and
interprets into database commands for execution.
Data :
 It is resource for which DBMS is designed.
 DBMS creation is to store and utilize data.
Procedures or Methods :
 They are general instructions to use DBMS.
such as
o installation of DBMS,
o manage databases to take backups,
o report generation, etc
Database Access Languages :
 It is a languages used to write commands.
 Such as access, insert, update and delete data stored in any database.
Ex: Dbase, FoxPro

165
Unit IV - Chapter 12. STRUCTURED QUERY LANGUAGE
2 Mark: (Book Back Questions)
1. Write a query that selects all students whose age is less than 18 in order wise.

SELECT * FROM student WHERE age < 18 ORDER BY age ASC;

2. Differentiate Unique and Primary Key constraint.

Unique Constraint Primary Key Constraint

No two rows have the same value Only one field of a table can be set as primary key

It can be applied only to fields declared It must have the NOT NULL constraint.
as NOT NULL.

3. Write the difference between table constraint and column constraint?


Table constraint Column constraint

It apply to a group of one or more columns. It apply only to individual column.

4. Which component of SQL lets insert values in tables and which lets to create a table?

Component Command Description


DDL CREATE TABLE Create tables in the database.
DML INSERT Inserts data into a table.

5. What is the difference between SQL and MySQL?


SQL MySQL
Structured Query Language is a MySQL is a database management
language. system, like SQL Server, Oracle,
Informix, Postgres, etc..
SQL is used for accessing databases. MySQL is a RDBMS

166
3 Marks: (Book Back Questions)
6. What is a constraint? Write short note on Primary key constraint.
 Constraint is a condition.
 It is applicable on a field or set of fields.
 It is used to limit the type of data that can go into a table.
 It could be either on a column level or a table level.
Primary Key Constraint
 A field is declared as primary key.
 It helps to uniquely identify a record.
 It is similar to unique constraint.
 Except that only one field of a table can be set as primary key.
 Primary key does not allow NULL values .
 A field declared as primary key must have the NOT NULL constraint.

Ex:
CREATE TABLE Student
( Admno integer NOT NULL PRIMARY KEY, → Primary Key constraint
Name char(20) NOT NULL,
Age integer
);

7. Write a SQL statement to modify the student table structure by adding a new field.
 ALTER command is used to alter the table structure.
 Altering like
o Adding a column,
o Delete the column ,
o Change the data type of any column ,
o Change the size of any column or
o Renaming the existing column from the table.
Syntax: (To add a new column in the existing table)

ALTER TABLE <table-name>ADD <column-name> <data type><size>;


Ex:
ALTER TABLE students ADD Address char (20);

167
8. Write any three DDL commands.

Create To create tables in database.

Alter Alters the structure of the database.

Drop Delete tables from database.

Truncate Remove all records from a table. Also release the space occupied by
those records.

9. Write the use of Save point command with an example.


 It is used to temporarily save a transaction.
 So, that we can roll back to the point whenever required.
Syntax:
SAVEPOINT savepoint_name;
Ex:

SAVEPOINT A;

10. Write a SQL statement using DISTINCT keyword.

 DISTINCT keyword is used along with the SELECT command.


 It “eliminate duplicate rows” in the table.
 It helps to eliminate redundant data.

Ex:
SELECT DISTINCT Place FROM Student;

 When the keyword DISTINCT is used, only one NULL value is returned,
even if more NULL values occur.

168
Additional 2 Mark & 3 Mark questions:
11. Define SQL
SQL  Structured Query Language.
 It is a standard programming language.
 It is used to access and manipulate RDBMS databases.
 It allows the user to create, retrieve, alter, and transfer information among databases.

12. What are the versions of SQL?


 The original version was developed at IBM‟s Research centre .
 It is originally called as Sequel in early 1970‟s.
 Later the language was changed to SQL.
 In 1986,ANSI (American National Standard Institute) published an SQL standard.
 It was updated again in 1992.
 The latest SQL was released in 2008 and named as SQL 2008.

13. What is the role of SQL in RDBMS?


 RDBMS  Relational DataBase Management System.
 Oracle, MySQL, MS SQL Server, IBM DB2 and Microsoft Access are RDBMS
packages.
 SQL language is used to access data in databases.

14. Define CRUD. (or) What is RDBMS?


 RDBMS is a type of DBMS .
 It is a row-based table structure.
 It connects the related data elements.
 It includes functions related to Create, Read, Update and Delete operations, collectively
known as CRUD.
15. Define table
 The data in RDBMS, is stored in database objects.
 The database object is called as Tables.
 A table is a collection of related data entries .
 A table consists of rows and columns.

16. Define field


 A field is a column in a table .
 Field is a vertical entity in table.
 Field is designed to maintain specific related information about every record in the
table.
Ex:
AdmnNo, Name, Age, Class, etc.

169
17. Define record.
 A Record is a row in a table.
 Record is a collection of related fields or columns that exist in a table.
 Record is a horizontal entity in a table.
Represents the details of a particular student in a student table.
18. What are the processing skills of SQL?
1. Data Definition Language (DDL)
2. Data Manipulation Language (DML)
3. Embedded Data Manipulation Language
4. View Definition
5. Authorization
6. Integrity
7. Transaction control

19. What are the components of SQL?


1. Data Manipulation Language
2. Data Definition Language
3. Data Control Language
4. Transaction Control Language
5. Data Query Language

20. Define DDL


 Data Definition Language.
 DDL consists of SQL statements.
 DDL is used to define the database structure or schema.
 It deals with descriptions of the database schema .
 It is used to create and modify the structure of database objects ( tables) in databases.
 It provides a set of definitions to specify the storage structure and access methods used
by the database system.

21. What are the functions performed by DDL?


1. It should identify the type of data division
such as data item, segment, record and database file.
2. It gives a unique name to
each data item type, record type, file type and data base.
3. It should specify the proper data type.
4. It should define the size of the data item.
5. It may define the range of values for data item.
6. It may specify locks for preventing unauthorized data entry.

170
22. What is meant by Data Manipulation?
 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.

23. Define DML


 DML  Data Manipulation Language.
 DML is a computer programming language.
 DML is used for adding , removing and modifying data in a database.
 It comprises the SQL-data change statements.
 It modify stored data. But not the schema of the database table.

24. What are the types of DML?

1. Procedural DML:
 It requires a user to specify what data is needed and how to get it.

2. Non-Procedural DML:
 It requires a user to specify what data is needed without specifying how to get it

25. What are SQL commands which come under the DML?
Insert Inserts data into a table

Update Updates the existing data within a table.

Delete Deletes all records from a table, but not the space occupied by them.

26. Define DCL


 DCL  Data Control Language.
 DCL is a programming language.
 DCL is used to control the access of data stored in a database.
 DCL is used for controlling privileges in the database (Authorization).

27. What are the SQL commands which comes under the DCL?

Grant Grants permission to one or more users to perform specific tasks.

Revoke Withdraws the access permission given by the GRANT statement.

171
28. Define TCL
 TCL  Transactional control language .
 It used to manage transactions in the database.
29. What are SQL commands which come under the TCL?

Commit Saves any transaction into the database permanently.

Roll back Restores the database to last commit state.

Save point Temporarily save a transaction. So, that we can rollback.

30. Define DQL.


 DQL  Data Query Language .
 It is used to query or retrieve data from a database.

31. What are SQL commands which come under the DQL?

Select It displays the records from the table.

32. How to create a database and use it?


Create Database:

Syntax: CREATE DATABASE database_name;

Ex: CREATE DATABASE stud;

To work with the database:

Syntax: USE DATABASE;

Ex:
USE stud;
33. Write the syntax for create a table.

CREATE TABLE <table-name>


( <column name> <data type> [<size>] ,
<column name> <data type> [<size>]….
);

172
34. Write the syntax for select statement.

SELECT <column-list> FROM <table-name>;

35. What are the keywords used in select statement?


1. DISTINCT keyword
2. ALL keyword
3. BETWEEN and NOT BETWEEN keyword
4. IN keyword
5. ORDER BY clause
6. WHERE clause
7. GROUP BY clause
8. HAVING clause

36. What are the pre-determined sets of commands to work on database?

Keywords It have a special meaning in SQL.


They are understood as instructions.

Commands It is instructions given by the user to the database.


Also known as statements.
Clauses They begin with a keyword and consist of keyword and argument.

Arguments They are the values given to make the clause complete.

37. What is constraint? With its types.


 Constraint is a condition.
 It is applicable on a field or set of fields.
 It is used to limit the type of data that can go into a table.
 It ensures the accuracy and reliability of the data in the database.
 It could be either on a column level or a table level.

38. What are the types of constraints?


1) Unique constraint
2) Primary key constraint
3) Default constraint
4) Check constraint
5) Table constraint

173
39. Write a short note on DELETE statement.
 It deletes only the rows from the table based on the condition given in the where clause.
(Or)
 Delete all the rows from the table if no condition is specified.
 But it does not free the space containing the table.

To delete one row


Syntax: DELETE FROM tablename WHERE condition;

Ex:
DELETE FROM student WHERE admno=101;

To delete all rows


Syntax:
DELETE FROM Tablename ;

Ex:
DELETE FROM student
;;

40. Write a short note on TRUNCATE statement.


 It is used to delete all the rows from the table.
 But structure remains in the table .
 Also space is freed from the table.

Syntax :
TRUNCATE TABLE Tablename;

Ex:
TRUNCATE TABLE student;

41. Write a short note on DROP statement.


 It is used to remove an object (table)from the database.
 All the rows in the table is deleted and the table structure is removed from the
database.
 Once a table is dropped we cannot get it back.

Syntax : DROP TABLE Tablename;

Ex: DROP TABLE student;

174
42. How to identify a data in a database is stored?
 Data is identified as the data type of the data .
(or )
 By assigning each field a data type.
 All the values in a given field must be of same type.

43. Write short note on ALL keyword.


 It retains duplicate rows.
 It will display every row of the table without considering duplicate entries.
Ex:
SELECT ALL place FROM Student;

44. Write short note on BETWEEN and NOT BETWEEN keyword.


BETWEEN :
 It defines a range of values the record must fall into make the condition true.
 Range may include an upper value and a lower value between which the criteria must
fall into.
Ex:

SELECT admno,name,age FROM student WHERE age BETWEEN 18 AND 19;

NOT BETWEEN:
 It is reverse of the BETWEEN operator
where the records not satisfying the condition are displayed.
Ex:

SELECT admno,name,age FROM student WHERE age NOT BETWEEN 18 AND 19;

45. Write short note on IN keyword and Not IN keyword.


IN keyword:
 It is used to specify a list of values which must be matched with the record values.
 It is used to compare a column with more than one value.
 It is similar to an OR condition.

Ex: SELECT admno,name,place FROM STUDENT WHERE place IN(„Chennai‟);

175
NOT IN keyword:
 It displays only those records that do not match in the list.
Ex:

SELECT Admno, Name, Place FROM Student WHERE Place NOT IN (῾Chennai᾿,);

46. Write short note on NULL value.


 The null value in a field can be searched in a table using ISNULL in the WHERE clause.

Ex: SELECT * FROM student WHERE age IS NULL;

Note : Non NULL values in a table can be listed using IS NOT NULL.

47. Write short note on WHERE clause in SQL statement.


 WHERE clause is used to filter the records.
 It helps to extract only those records which satisfy a given the condition.
 WHERE clause is used in SELECT, DELETE,UPDATE command.
Ex:

SELECT * FROM student WHERE age>=18;


DELETE FROM student WHERE admno=104;
UPDATE student age=20 WHERE place=”Chennai”;

48. Write short note on ORDER BY clause in SQL statement.


 It is used to sort the data in either ascending or descending order based on one or more
columns.
 Default order: ascending order.
ASC  To sort the data in ascending order.
DESC  To sort the data in descending order.
Ex:
SELECT * FROM student ORDER BY name; (By default- ASC)
SELECT * FROM student WHERE age>=18 ORDER BY name DESC;

176
49. Write short note on GROUP BY clause in SQL statement.
 It is used with SELECT statement to group on rows or columns having identical values
or divide the table into groups.
 It is mostly used in conjunction with aggregate functions to produce summary reports
 It applies the aggregate function independently to a series of groups that are defined by
having a field value in common.

Ex:
SELECT gender FROM student GROUP BY gender;
SELECT gender count(*) FROM student GROUP BY gender;

count  aggregate function

50. Write short note on HAVING clause in SQL statement.


 It can be used along with GROUP BY clause in the SELECT statement to place condition
on groups and can include aggregate functions on them.
Ex:
SELECT gender FROM student GROUP BY gender HAVING count(*)>=18;

51. Write a note on COMMIT command.


 COMMIT is used to permanently save any transaction to the database.
 Once the COMMIT command is given, the changes made cannot be rolled back.

Syntax : COMMIT;

52. Write a note on ROLLBACK command.


 ROLLBACK restores the database to the last commited state.
 It is used with SAVEPOINT command to jump to a particular savepoint location.
Syntax:
ROLLBACK TO save point;
;name;

Ex: ROLLBACK TO A;

177
53. Write short note on UPDATE command.
 It updates some or all data values in a database.
 It can update one or more records in a table.
 It specifies the rows to be changed using the WHERE clause and the new data using SET
keyword.
 To update multiple fields, multiple field assignment can be specified with the SET clause
separated by comma

Syntax:

UPDATE <table-name> SET column-name = value, column-name = value,…WHERE condition;

Ex:
UPDATE Student SET age = 20 WHERE Place = “Bangalore”;
UPDATE Student SET age=18, Place=„Chennai‟ WHERE admno=102;

54. Write short note on ALTER command.


 It is used to alter the table structure.
 Altering like adding a column, delete a column, renaming the existing column, change
the data type of any column or size of the column from the table.

To add a new column:


Syntax ALTER TABLE <table-name> ADD <column-name><data type><size>;

Ex:
ALTER TABLE Student ADD Address char;

To remove a particular field


Syntax:
ALTER TABLE <table-name> DROP COLUMN <column-name>;

Ex: ALTER TABLE Student DROP COLUMN City;

To modify existing column of table:


Syntax:
ALTER TABLE <table-name> MODIFY<column-name><data type><size>;
Ex: ALTER TABLE Student MODIFY Address char (25);

178
To rename an existing column:
Syntax: ALTER TABLE <table-name> RENAME old-column-name TO new-column-name;

Ex:
ALTER TABLE Student RENAME Address TO City;

55. Write short note on SELECT command with an example.


 It is used to query or retrieve data from a table in the database.
 It is used to retrieve a subset of records from one or more tables.

Syntax : SELECT * FROM tablename;


SELECT < column-list > FROM <table name>;

Ex: SELECT * FROM student;


SELECT admno, name FROM student;

5 Marks: (Book Back Questions)


1. Write the different types of constraints and their functions. *(Book Back).
1. UNIQUE constraint
2. PRIMARY KEY constraint
3. DEFAULT constraint
4. CHECK constraint
5. TABLE constraint

UNIQUE constraint:

 It ensures that no two rows have the same value in the specified columns.
 It is applied only to fields that have also been declared as NOT NULL.
 Two constraints are applied on a single field, it is known as multiple constraints.
Ex:
CREATE TABLE Student
(
Admno integer NOT NULL UNIQUE, → Unique constraint
Name char (20) NOT NULL,
Gender char(1),
Age integer
);

179
PRIMARY KEY constraint:

 A field is declared as primary key.


 It helps to uniquely identify a record.
 It is similar to unique constraint.
 Except that only one field of a table can be set as primary key.
 It does not allow NULL values .
 A field declared as primary key must have the NOT NULL constraint.
Ex:

CREATE TABLE Student


(
Admno integer PRIMARY KEY, → Primary Key constraint
Name char(20) NOT NULL
Gender char(1),
Age integer
);
DEFAULT constraint:
 It is used to assign a default value for the field.
 If no value is given for the specified field having DEFAULT constraint, automatically
the default value will be assigned to the field.
Ex:
CREATE TABLE Student
(
Admno integer PRIMARY KEY,
Name char(20) NOT NULL,
Gender char(1),
Age integer DEFAULT = “17” → Default Constraint
);
CHECK constraint:
 It helps to set a limit value placed for a field.
 If we define a check constraint on a single column, it allows only the restricted values on
that field.
Ex:
CREATE TABLE Student
(
Admno integer PRIMARY KEY,
Name char(20)NOT NULL,
Gender char(1),
Age integer (CHECK<=19) → Check Constraint
);

180
TABLE constraint:
 It is applied to a group of fields of the table,
 It is known as Table constraint.
 It is given at the end of the table definition.
Ex:

CREATE TABLE Student


(
Admno integer NOT NULL,
Firstname char(20),
Lastname char(20),
Gender char(1),
Age integer,
PRIMARY KEY (Firstname, Lastname) → Table constraint
);

2. Consider the following employee table. Write SQL commands for the qtns. (i) to (v).

EMPCODE NAME DESIG PAY ALLOWANCE


1001 Hariharan Supervisor 29000 12000
P1002 Shaji Operator 10000 5500
P1003 Prasad Operator 12000 6500
C1004 Manjima Clerk 8000 4500
M1005 Ratheesh Mechanic 20000 7000

(i) To display the details of all employees in descending order of pay.

SELECT * FROM employee ORDER BY PAY DESC;

(ii) To display all employees whose allowance is between 5000 and 7000.

SELECT * FROM employee WHERE ALLOWANCE BETWEEN 5000 AND 7000;

(iii) To remove the employees who are mechanic.

DELETE FROM employee WHERE DESIG = „Mechanic‟;

181
(iv) To add a new row.
INSERT INTO employee (EMPCODE, NAME, DESIG, PAY, ALLOWANCE)
VALUES (C106, „Shan‟, Clerk‟, 10000,4500);

(v) To display the details of all employees who are operators.

SELECT * FROM employee WHERE DESIG = „Operator‟;

3. What are the components of SQL? Write the commands in each.


1) DDL  Data Definition Language
2) DML  Data Manipulation Language
3) DCL  Data Control Language
4) TCL  Transaction Control Language
5) DQL  Data Query Language

Data Definition Language:

 It consists of SQL statements.


 It used to define the database structure or schema.
 It provides a set of definitions to specify the
 storage structure and
 access methods used by the database system`
Functions of DDL:
1. It should identify the type of data division
such as data item, segment, record and database file.
2. It gives a unique name to
each data item type, record type, file type and data base.
3. It should specify the proper data type.
4. It should define the size of the data item.
5. It may define the range of values for data item.
6. It may specify locks for preventing unauthorized data entry`

Create To create tables in the database.

Alter Alters the structure of the database.

Drop Delete tables from database.

Truncate Remove all records from a table, also release the space occupied by
those records.

182
Data Manipulation Language:
 It is a query language.
 It is used for adding, removing and modifying data in a database.
 It modifies stored data. But not the schema of the database table.
DML

Procedural Non-Procedural
DML DML

Procedural DML:
 It requires a user to specify what data is needed and how to get it.

Non-Procedural DML:
 It requires a user to specify what data is needed without specifying how to get it.

Insert Inserts data into a table

Update Updates the existing data within a table.

Delete Deletes all records from a table, but not the space occupied by them.

Data Control Language:


 DCL is a programming language.
 It is used to control the access of data stored in a database.
 It is used for controlling privileges in the database (Authorization).

Grant Grants permission to one or more users to perform specific tasks.

Revoke Withdraws the access permission given by the GRANT statement.

Transaction Control Language:


 It used to manage transactions in the database.

Commit Saves any transaction into the database permanently.

Roll back Restores the database to last commit state.

Save point Temporarily save a transaction .so, that we can rollback.

183
Data Query Language:
 It used to query or retrieve data from a database.

Select It displays the records from the table.

4. Construct the following SQL statements in the student table-


(i) SELECT statement using GROUP BY clause.
(ii) SELECT statement using ORDER BY clause.

(i) SELECT statement using GROUP BY clause:


Answer:
SELECT * FROM student WHERE gender = “MALE” GROUPBY gender;

(ii) SELECT statement using ORDER BY clause:


Answer:

SELECT * FROM student WHERE Age > = 18 ORDER BY DESC;

5. Write a SQL statement to create a table for employee having any five fields and
create a table constraint for the employee table.

Answer:

CREATE TABLE employee


(
Empno integer NOT NULL PRIMARY KEY,
Name char(20),
Place char(7) DEFAULT “ CHENNAI”,
Gender char(1),
Age integer CHECK age<=18,
PRIMARY KEY (Firstname, address) → Table constraint
);

184
6. Write any three DDL commands.
1) CREATE TABLE Command:
 It is used to create table.
 A table is created with specified column name, data types, sizes.

Syntax:
CREATE TABLE <table-name>
( <column name> <data type> [<size>] ,
<column name> <data type> [<size>]….
);

Ex: CREATE TABLE Student


(
Admno integer,
Name char(20)
);

2) ALTER COMMAND:
 It is used to alter the table structure.
 Altering like
o Adding a column,
o Delete the column ,
o Change the data type of any column ,
o Change the size of any column or
o Renaming the existing column from the table.
Syntax:

ALTER TABLE <table-name>ADD <column-name> <data type> <size>;

Ex: ALTER TABLE students ADD Address char (20);

2) DROP COMMAND:
 It is used to remove an object (table)from the database.
 All the rows in the table is deleted and the table structure is removed from the
database.
 Once a table is dropped we cannot get it back.

Syntax : DROP TABLE tablename;

Ex:
DROP TABLE student;

185
TRUNCATE command:

 It is used to delete all the rows from the table.


 The structure remains and the space is freed from the table.

Syntax: TRUNCATE TABLE table-name;

Ex: TRUNCATE TABLE Student;

56. Write short note on SELECT command with an example.


 It is used to query or retrieve data from a table in the database.
 It is used to retrieve a subset of records from one or more tables.

Syntax : SELECT * FROM tablename;


SELECT < column-list > FROM <table name>;

Ex: SELECT * FROM student;


SELECT admno, name FROM student;

1) DISTINCT keyword:
 SELECT command is used along with DISTINCT keyword.
 DISTINCT eliminate duplicate rows from the table.

Ex:
SELECT DISTINCT place FROM student;
2) ALL keyword:
 It retains duplicate rows.
 It will display every row of the table without considering duplicate entries.
Ex:
SELECT ALL place FROM Student;

3) BETWEEN :

 It defines a range of values the record must fall into make the condition true.
 Range may include an upper value and a lower value between which the criteria must
fall into.
Ex:
SELECT admno,name,age FROM student WHERE age BETWEEN 18 AND 19;

186
NOT BETWEEN:
 It is reverse of the BETWEEN operator
where the records not satisfying the condition are displayed.
Ex:

SELECT admno,name,age FROM student WHERE age NOT BETWEEN 18 AND 19;

4) IN keyword:
 It is used to specify a list of values which must be matched with the record values.
 It is used to compare a column with more than one value.
 It is similar to an OR condition.
Ex:
SELECT admno,name,place FROM STUDENT WHERE place IN(„Chennai‟);

NOT IN keyword:
 It displays only those records that do not match in the list.

Ex: SELECT Admno, Name, Place FROM Student WHERE Place NOT IN (῾Chennai᾿,);

5. ORDER BY clause:
 It is used to sort the data in either ascending or descending order based on one or more
columns.
 By default ORDER BY sorts the data in ascending order.
ASC  To sort the data in ascending order.
DESC  To sort the data in descending order.
Ex:
SELECT * FROM student ORDER BY name; (By default- ASC)
SELECT * FROM student WHERE age>=18 ORDER BY name DESC;

6. WHERE clause:
 WHERE clause is used to filter the records.
 It helps to extract only those records which satisfy a given the condition.
 It is used in SELECT, DELETE, UPDATE command.
Ex:

SELECT * FROM student WHERE age>=18;


DELETE FROM student WHERE admno=104;
UPDATE student age=20 WHERE place=”Chennai”;

187
7. GROUP BY clause:
 It is used with SELECT statement to group on rows or columns having identical values
or divide the table into groups.
 It is mostly used in conjunction with aggregate functions to produce summary reports.
 It applies the aggregate function independently to a series of groups that are defined by
having a field value in common.

Ex:
SELECT gender FROM student GROUP BY gender;
SELECT gender count(*) FROM student GROUP BY gender;

count  aggregate function

8. HAVING clause:
 It can be used along with GROUP BY clause in the SELECT statement to place condition
on groups
 It can include aggregate functions on them.
Ex:
SELECT gender FROM student GROUP BY gender HAVING count(*)>=18;

188
Unit V - Chapter 13. PYTHON AND CSV FILES
===================================================
2 Marks: (Book Back Questions)
1. What is CSV File?
 A CSV file is a human readable text file .
 In CSV file, each line has a number of fields.
 Number of fields are separated by commas or some other delimiter.

Ex: Regno, name, total


101, ram, 590
102, sita, 595
2. Mention the two ways to read a CSV file using Python.
1. Reader() function
2. Dict Reader class

3. Mention the default modes of the File.


 The default is reading in text mode.
 While reading from the file, the data would be in the format of strings.

4. What is use of next() function?


 We can skip the first row of the csv file .
 First row of CSV file is skipped by using the command “next( )”.

5. How will you sort more than one column from a csv file? Give an example statement. *

To sort more than one column :

 We can use itemgetter with multiple indices: operator.itemgetter(1,2)

Ex: sortedlist = sorted (data, key=operator.itemgetter(1))

189
3 Marks: (Book Back Questions)
6. Write a note on open() function of python. What is the difference between the two methods?

 open( ) is a python built-in function.


 open( ) is used to open a file.
 open( ) function returns a file object.
 File object is also called as handle.
 File object is used to read or modify the file accordingly.

Ex: (To open a file)

f=open(“sample.txt”)
f=open(„c:\\python\\sample.csv‟)
f  File object (or) handle
Two methods of csv file reading
1. Text mode (default): Reading from the file, the data would be in the format of strings.

2. Binary mode: Returns bytes and it is used when dealing with non-text files.

7. Write a Python program to modify an existing file.


import csv
row = [„3‟, „Santhosh‟,‟Karur‟]
with open(„student.csv‟, „r‟) as s:
reader = csv.reader(s)
lines = list(reader)
lines[3] = row
with open(„student.csv‟, „w‟) as m:
writer = csv.writer(m)
writer.writerows(lines)
s.close()
m.close()

8. Write a Python program to read a CSV file with default delimiter comma (,).
import csv
with open('c:\python\sample.csv', 'r') as F:
reader = csv.reader(F)
for row in reader:
print(row)
F.close()

190
9. What is the difference between the write mode and append mode.

s.no write mode append mode

1. „w‟ „a‟
2. Open a file for writing. Open for appending at the end of the file
without truncating it.
3. 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.

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


(or)
What is the difference between csv.reader() and csv.DictReader() function?*

s.no reader() DictReader()


1. It works with list / tuple It works with dictionary
2. It does use any keys It takes additional argument field
names that are used as dictionary keys.

Additional 2 Mark & 3 Mark Questions:


11. Why CSV file is known as a flat file? (or) How CSV file imported and exported?

 A CSV file is also known as a Flat File.


 Files in the CSV format can be imported to and exported from programs.
 That store data in tables, such as Microsoft Excel or OpenOfficeCalc

12. What is the purpose of CSV file?

 CSV is a simple file format.


 It is used to store tabular data, such as a spreadsheet or database.
 CSV files are plain text.
 So they are easier to import into a spreadsheet or any other storage database.

13. Expand i) CSV, ii) CRLF


CSV  Comma Separated Values
CRLF  Carriage Return Line Feed

191
14. How will you protect commas in your field? (or)
How will perfect the CSV file data contain common by itself?
 If the fields of data in your CSV file contain commas, you can protect them by enclosing
those data fields in double-quotes (“ “).
 The commas that are part of your data will then be kept separate from the commas which
delimit the fields themselves.

15. How the CSV filename represented in open command ?


File name or the complete path name can be represented either with in “ “ or in „ „ in the open
command.
16. What are the modes in which CSV file can be opened?
1. Read mode „r
2. Write mode „w‟
3. Append mode „a‟
4. Text mode „t‟
5. Binary mode „b‟

17. How to create a CSV file? With Example.

To create a CSV file in Notepad


1. First open a new file using File → New (or) Ctrl+N
2. Enter the data
3. Separating each value with a comma( , )
4. Each row with a new line.
5. Save the data in a file with .csv

Ex: Regno,Name,Total
101, Ram, 590
102, Sita, 595

18. What is the role of comma in CSV file?


 The commas that are part of our data will then be kept separate from the commas
which delimit the fields themselves.

19. Define CSV library.


 CSV library contains objects and other code to read, write, and process data from and to
CSV files.

20. What we do when newline as a part of its data?


 Any fields containing a newline as part of its data need to be enclosed in
double-quotes ( “ “).

192
21. How to create CSV file that contains double quotes with data?

 If our fields contain double-quotes as part of their data, the internal quotation marks
need to be doubled .
 So, that they can be interpreted correctly.
Ex:

RollNo, Name, FavoriteSports, Address


12101, Nivetha, ””” Cricket ””, ”” Football ”””, Mylapore chennai

22. Is it possible to open or edit by text editors that the file saved in excel?

 No. It is not possible to open or edit by text editors that the file saved in excel.

23. How to create a CSV file using MS excel?

1) First open the Excel file.


2) Enter the data.
3) Select File → Save As
4) Select CSV or type the filename with extension .csv.

24. In which application the CSV file open when the file is double clicked by default?

 By default CSV files should open automatically in Excel when the file is double clicked .

25. What are the methods to open a CSV file in MS excel?

1. open() function
2. with statement

26. In which application the CSV file have been used extensively.

 CSV files have been used extensively in e-commerce applications.

27. What are the ways to read a CSV file?


1. reader() function
2. DictReader class.

28. What are the ways to write a CSV file?


1. writer() function
2. DictWriter class

193
29. How to represent file name and path name?
 File name or the complete path name can be represented with in “ “ or
in „ „ in the open command.

30. What are the steps to read a file?(or) Write the steps involved in file operation.

Step 1 : Open a file


Step 2 : Perform read or write operation
Step 3 : Close the file

31. How will you close a file in python? (or) Write a note on close( ) method.
 Closing a file will free up the resources.
 It tied with the file and is done using Python close() method.

32. Write a note on with statement.

 This ensures that the file is closed when the block inside with is exited.
 We need not to explicitly call the close() method.
 It is done internally.
Ex:
with open("test.txt",‟r‟) as f:

33. Which deals non-text files? Or write short note on binary mode.

 Binary mode returns bytes.


 This mode to be used when dealing with non-text files like image or exe files.

34. What is the use of garbage collector?

 Python has a garbage collector.


 It is used to clean up unreferenced objects .
 But, one must not rely on it to close the file.

35. Why the file is necessary to close when open a CSV file?

 If we did not close a csv file, then the data will be erased.

36. Write a note on reader()

 reader() function is designed to take each line of the file and make a list of all columns.
 Using reader() function one can read data from csv files of different formats
like quotes (" "), pipe (|) and comma (,).

194
Syntax:
csv.reader (fileobject, delimiter, fmtparams)

file object: passes the path and the mode of the file

delimiter: an optional parameter .


containing the standard dilects like , | etc can be omitted

fmtparams: optional parameter.


It helps to override the default values of the dialects
like skipinitialspace, quoting etc. Can be omitted.

37. How to store the data in CSV file as a list?


 To read a CSV file and the contents of the file will be stored as a list .
syntax:

list = [ ]
list.append(element)
Ex:
arrayvalue= []
arrayvalue.append(row)

38. What is the difference between sort() and sorted()?

sort() sorted()

Doesn‟t return value and Returns value and


Changes the original list itself. Changes the original list.

list_name.sort()  Sorts the element of a given item in a


arranges a list value in ascending order. specific order-Ascending or Descending
list_name. sort(reverse=True) 
arrange a list in descending order.
Ex: Ex:
arrayvalue.sort(reverse=True) sortedlist=sorted(data,key=operator.itemgetter(1))

39. Which is used for dictionary keys in DictReader()?


 Using each comma separated value in this line as a dictionary key.

195
40. Write a note on writer(). (or) Write a note on CSV.writer.

 csv.writer() method returns a writer object.


 It converts the user‟s data into delimited strings on the given file-like object.
 writerow() method writes a row of data into the specified file.

Syntax:
csv.writer(fileobject,delimiter,fmtparams)

fileobject: passes the path and the mode of the file.


delimiter: an optional parameter.
containing the standard dilects like , | etc can be omitted.

fmtparams : optional parameter .


It helps to override the default values of the dialects. like
skipinitialspace,quoting etc. can be omitted.

41. What is the use of write mode?

 The „w‟ write mode creates a new file.


 If the file is already existing „w‟ mode overwrites it.

42. What is the difference between writerow() and writerows()?

s.no writerow() writerows()

1. It writes one row at a time It write all the data at atime

2. It takes 1-dimensional data (one row) It takes 2-dimensional data (multiple


rows) to write in a file.

43. What is line terminator? What are the default values for it?

 A Line Terminator is a string.


 It is used to terminate lines produced by writer.
 The default value is \r or \n.
 We can write csv file with a line terminator by registering new dialects using
csv.register_dialect() class of csv module.

196
44. What are the various CSV data formats available? (or)

What are the different ways of reading a CSV file using reader() method?

1) CSV file - data with default delimiter comma (,)


2) CSV file - data with Space at the beginning
3) CSV file - data with quotes
4) CSV file - data with custom Delimiters
45. What are the different types of writing data in CSV files?
1) Creating A New Normal CSV File
2) Modifying An Existing File
3) Writing On A CSV File with Quotes
4) Writing On A CSV File with Custom Delimiters
5) Writing On A CSV File with Lineterminator
6) Writing On A CSV File with Quotechars
7) Writing CSV File Into A Dictionary
8) Getting Data At Runtime And Writing In a File

46. What is dialect?


 A dialect describes the format of the csv file that is to be read.
 Here, the parameter “skipinitialspace” is used for removing whitespaces after the delimiter.
 By default “skipinitialspace” value is false.
 A dialect is a class of csv module.
 It helps to define parameters for reading and writing CSV.
 It allows you to create, store, and re-use various formatting parameters for your data.
47. What is the role of “skipinitialspace”?
 “skipinitialspace” is used for removing whitespaces after the delimiter.

48. How do you write CSV files with quotes?


 We can write the csv file with quotes, by registering new dialects using
csv.register_dialect() class of csv module.
49. Write a note on CSV Files With Custom Delimiters. (or) What is delimiter?
 A delimiter is a string used to separate fields.
 The default value is comma(,).
 We can have custom delimiter in CSV files by registering a new dialect using
csv.register_dialect() class of csv module.
50. How do you write a CSV file into a dictionary?
 We can write a csv file into a dictionary, using DictWriter() class of csv module.
 It creates an object which maps data into a dictionary.
 The keys are given by the fieldnames parameter.

197
51. What is a line terminator?
 A Line Terminator is a string used to terminate lines produced by writer.
 Default value: \r or \n
 We can write csv file with a line terminator by registering new dialects using
csv.register_dialect() class of csv module.

52. What is called modification?


 Making some changes in the data or adding more data of the existing file is called
modification.
53. How to read a custom delimiter?

 CSV file having custom delimiter is read with the help of csv.register_dialect().

54. Write a note on DictReader.

 To read a CSV file into a dictionary by using DictReader method of csv module.
 It works similar to the reader() class.
 But creates an object which maps data to a dictionary.
 The keys are given by the fieldnames as parameter.
 DictReader works by reading the first line of the CSV
 It using each comma separated value in this line as a dictionary key.
 The columns in each subsequent row then behave like dictionary values
 It can be accessed with the appropriate key (i.e. fieldname).

55. Write a note on OrderedDict.

 DictReader() gives OrderedDict by default in its output.


 An OrderedDict is a dictionary subclass
 It saves the order in which its contents are added.
 To remove the OrderedDict use dict( )

56. What is the use of dict()?

 Dict() is used to print the data in dictionary format without order.

57. What are the additional argument fieldnames that are used as dictionary keys?

1. csv.DictReader
2. csv.DictWriter

198
Programs:
1. Write a program to read a file with default delimiter comma.

Output:

2. Write a program to read the CSV file through python using reader () method.

Output:

3. Write a program to read the CSV file with Custom delimiter (user defined delimiter).
(or)
How do you read CSV files with custom delimiters?
 We can read CSV file with custom delimiter, by registering a new dialect using
csv.register_dialect() class of csv module.

199
4. Write a program to create a normal CSV file using writer( ) function. (or)

Write a program to create a new normal CSV file to store data.

Output:

5. Write a program to add new rows in the existing CSV file.

6. Write a program to read a specific column in a CSV file.

7. Write a program to read the CSV file and store a column value in a list for sorting.

200
8. How will you sort more than one column in a CSV file? Explain with an example.

9. Write a program to read CSV file with user defined Delimiter into a Dictionary.

10. Write a program to read a CSV file with a line terminator.

OUTPUT:

201
11. How will you write the CSV file with custom denote characters? Explain with an example.

 We can write the CSV file with custom quote characters, by registering new dialects using
csv.register_dialect() class of csv module.

OUTPUT:

12. How will you writing CSV file into a Dictionary?

Output:

13. How will you write Dictionary into CSV file with custom dialects?

Output:

202
13. Write a program to set data at runtime and writing it in a CSV file.

5 Marks: (Book Back Questions)


1. Differentiate Excel file and CSV file.
s.no Excel CSV
1. Excel is a binary file. CSV is a plain text format

2. It holds information about all the Series of values are separated by commas
worksheets in a file, including both
content and formatting
3. It can only be read by applications. It can be opened with any text editor in
That have been especially written to Windows.
read their format .
Text editors like notepad, MS Excel,
It can only be written in the same OpenOffice, etc.
format.

4. Excel is a spreadsheet. It is a format for saving tabular information


It saves files into its own proprietary into a delimited text file with extension .csv
format viz. xls or xlsx
5. It consumes more memory. It consumes less memory.
Importing CSV files can be much faster

203
2. Tabulate the different mode with its meaning.
Mode Description
„t‟ Open in text mode. (default)
„b‟ Open in binary mode.
„r‟ Open a file for reading. (default)
„w‟ Open a file for writing.
Create a new file . if it does not exist
(or)
Truncates the file if it exists.
„+‟ Open a file for updating (reading and writing)

„a‟ Open a file for appending at the end of the file ” without truncating it”.
Creates a new file , if it does not exist.
„x‟ Open a file for exclusive creation.
If the file already exists, the operation fails.

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


Different methods to read a File in Python
1. CSV file-data with default delimiter comma(,)
2. CSV file-data with space at the beginning
3. CSV file-data with quotes
4. CSV file-data with custom delimiters

1. CSV file-data with default delimiter comma (,):

 Read CSV file-data with default delimiter comma(,) and print row by row.

Program Output
import csv [„SNO‟,‟NAME‟,‟CITY‟]
F = open('c:\pyprg\sample1.csv', 'r') [„101‟, „Ram‟, „Karur‟]
x = csv.reader(F) [„102‟, „Sita‟, „Salem‟]
for row in x: [„103‟, „Balu‟,‟Trichy‟]
print(row)
F.close()

2. CSV file-data with space at the beginning:


 The output is also displayed with spaces.

204
 The whitespaces can be removed, by registering new dialects using csv.register_dialect()
class of csv module.
 A dialect describes the format of the csv file that is to be read.
 In dialects the parameter “skipinitialspace” is used for removing whitespaces after the
delimiter.
 By default “skipinitialspace” has a value false.

Program Output
import csv Topic1,Topic2,Topic3
csv.register_dialect('myDialect',delimiter = ','
one, two, three
,skipinitialspace=True)
F = open('c:\pyprg\sample2.csv', 'r') Exam1,Exam2, Exam3
x= csv.reader(F, dialect='myDialect')
for row in x:
print(row)
F.close()

3. CSV file-data with quotes:


 We can read the csv file with quotes, by registering new dialects using
csv.register_dialect() class of csv module.

Program Output
import csv SNO, Quotes
csv.register_dialect('s',delimiter=',' , quoting=csv.QUOTE_ALL,
skipinitialspace=True) 1, "Santhosh"
F = open('c:\pyprg\sample3.csv', 'r') 2, "Mohan"
reader=csv.reader(F, dialect='s')
for x in reader: 3, "Kumar"
print(x)
f.close() 4, "Raj"

4. CSV file-data with custom delimiters.


 We can read the csv file having custom delimiter by registering a new dialect with the
help of csv.register_dialect().

205
Program Output
import csv ROLL NO | NAME | GENDER |AGE
csv.register_dialect('s',delimiter='|')
F = open('c:\pyprog\sample3.csv', 'r') 100 | SANTHOSH | M |16
reader=csv.reader(F,dialect='s') 101 | MOHAN | M |17
for x in reader:
print(x) 102 | KUMAR | M | 18
f.close()
103 | RAJ | M | 18

4. Write a Python program to write a CSV File with custom quotes.


 We can write the csv file with quotes, by registering new dialects using
csv.register_dialect() class of csv module.

Program Output
import csv “SNO”, “Person”,”DOB”
s=[[„SNO‟, „Person‟, „DOB‟], “1”, “Sam”, “07/01/2003”
[„1‟, „Sam‟, „07/01/2003‟], “2”, “Mohan”,”13/04/2003”
[„2‟, „Mohan‟,‟13/04/2003‟], “3”, “Kumar”,”25/09/2001”
[„3‟, „Kumar‟,‟25/09/2001‟], “4”, “Raj”, “21/4/2000”
[„4‟, „Raj‟, „21/4/2000‟], “5”, “Mani”, “07/06/2003”
[„5‟, „Mani‟, „07/06/2003‟]]
csv.register_dialect(„m‟,quoting=csv.QUOTE_ALL)
F = open('c:\pyprog\person.csv', 'w')
writer = csv.writer(F, dialect=‟m‟)
for row in writer:
writer.writerow(row)
F.close()

3. Write the rules to be followed to format the data in a CSV file.


1. Each record (row of data) is to be located on a separate line.
It is delimited by a line break by pressing Enter key
Ex:
101, Ram, 590

206
2. The last record in the file may or may not have an ending line break.

Ex:
101, Ram, 590
102, Sita , 595  last record

3. There may be an optional header line.


 It may be 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.
 It should contain the same number of fields as the records in the rest of the file.
Ex:
Rollno, Name, Total
101, Ram, 590
102, Sita, 595 CRLF (Carriage Return and Line Feed)

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.
Ex:
102, Sita, 595

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.

Ex: “101”,” Ram”,”590”  Field data with double quotes

102, Sita , 595  Field data without double quotes

6. Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in
double-quotes ( “ “).
Ex:

Red, “,”, Blue  comma itself a field value. So, it is enclosed with
Red, Blue , Green double quotes

207
7. If double-quotes are used to enclose fields, then a double-quote appearing inside a field
must be preceded with “another double quote”.

Ex: ““Red””, ““Blue””, ““Green””  Since double quotes is a field value it is


enclosed with another double quotes.
, , white  Begins with two commas because the first
two fields of that were
empty.

208
CHAPTER-14 IMPORTING C++ PROGRAMS IN PYTHON
=========================================================
2 Marks: (Book Back Questions)

1. What is the theoretical difference between scripting and programming language? *

s.no Scripting language Programming language

1. Do not require the compilation step Require the compilation step


and rather interpreted.
2. Scripting language like JavaScript or C++ program needs to be compiled before
Python need not be compiled. running

3. Requires an interpreter Requires a compiler

2. Differentiate compiler and interpreter *

s.no Compiler Interpreter

1. It reads entire program at a time. It reads single statement at a time

2. Generates intermediate code. Generates machine code.

3. Takes large amount of time to analyze. Takes less amount of time to analyze.

4. Debugging is hard. Debugging is easy

5. Execution time is faster. Execution time is slower.

6. Intermediate object code is generated. No intermediate object code is generated

7. Ex: C, C++ Ex: Python

3. Write the expansion of 1.SWIG 2.MinGW

SWIG  Simplified Wrapper Interface Generator (Both C and C++)


MinGW  Minimalist GNU for Windows

209
4. What is the use of module ? *

 Modular programming is a software design technique to split your code (large program )
into separate parts.
 These parts are called modules.
Uses of module:
1. Minimization of dependencies is the goal.
2. We use modules to break down large programs into small manageable and organized
files
3. Modules provides reusability of code.
4. Define our most used functions in a module and import it., instead of copying their
definitions into different programs.
5. Modules refer to a file containing Python statements and definitions.

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


 „cd‟ command refers to change directory.
 It is used to change the directory.
Ex:
To go to the directory pyprg cd pyprg

3 Marks: (Book Back Questions)


6. Differentiate PYTHON and C++?

s.no PYTHON C++

1. Interpreted language Compiled language


2. Dynamic-typed language Statically typed language
3. Data type is not required while Data type is required while declaring
declaring variable. variable.
4. It can act both scripting and general It is a general purpose language.
purpose language.

7. What are the applications of scripting language? *

 To automate certain tasks in a program


 Extracting information from a data set
 Less code intensive as compared to traditional programming language
 can bring new functions to applications and glue complex systems together.

210
8. What is MinGW? What is its use? *

 MinGW refers to a set of runtime header files.


 It is used in compiling and linking the code of C, C++ and FORTRAN to be run on
Windows OS.
 MinGW allows to compile and execute C++ program dynamically through Python
program using g++.
 MinGw-W64 (version of MinGW)  Best compiler for C++ on Windows.
 To compile and execute the C++ program, you need „g++‟ for Windows.

9. Identify the module ,operator, definition name for the following *

Welcome.display()

Answer:

Welcome . display()

Function name

Operator

Module name

10. What is sys.argv? What does it contain? *

sys.argv  list of command-line arguments passed to the Python program.


vv

argv  one of the variable of sys module.


 contains all the items that come via command-line input
 basically a list.
 holding the command line argument of the program.

To use sys.argv: First import sys should be used.

sys.argv[0] : It is the first argument. (Name of the python program)


sys.argv[1] : It is the next argument.(Name of the C++ program)

Ex: main(sys.argv[1])

211
Explanation:
argv[1]  contains c++ input file along with its path.

argv[0]  contains the python program which need not to be passed .


 Because by default __main__ contains source code reference.

Additional 2 Marks & 3 Marks Questions:


11. What is scripting language?
 A scripting language is a programming language.
 It is designed for integrating and communicating with other programming languages.
 Ex: JavaScript, VBScript, PHP, Perl, Python, Ruby, ASP and Tcl.

12. What is the difference between scripting and programming language? *

s.no Scripting language Programming language

1. Do not require the compilation step Need to be compiled


rather interpreted.

2. Scripting language like JavaScript or C++ program needs to be compiled


Python need not be compiled. before running

3. Requires an interpreter Requires a compiler

13. What is Garbage collection?

 Python deletes unwanted objects automatically to free the memory space.


 The process by which Python periodically frees and reclaims blocks of memory that no
longer are in use is called “Garbage Collection”.
14. What is the use of GNU C compiler?
 g++ is a program that calls GCC (GNU C Compiler) and automatically links the required C++
library files to the object code.

15. What is wrapping?

 Importing C++ program in a Python program is called wrapping up of C++ in Python.

212
15. What are the options to importing / wrapping c++ into Python?

 Python-C-API (API-Application Programming Interface for interfacing with C programs)


 Ctypes (for interfacing with c programs)
 SWIG (Simplified Wrapper Interface Generator- Both C and C++)
 Cython (Cython is both a Python-like language for writing C-extensions)
 Boost. Python (a framework for interfacing Python and C++)
 MinGW (Minimalist GNU for Windows)

16. Why python is called as glue language? (or) What is „glue‟ language?

 Python is mostly used as a “scripting” or "glue" language.


 (i.e), Top level program mostly calls routines written in C or C++.
 This is useful when the logic can be written in terms of existing code but can be called
and manipulated through Python program

17. What is module ? *

 Modules refer to a file containing Python statements and definitions.


 Modular programming is a software design technique to split your code (large program )
into separate parts.
 These parts are called modules.

18. Which is the special variable in wrapping in python?

 __name__ is the special variable in wrapping in python.

19. Write a note on __name__ variable.

 special variable which by default stores the name of the file.


__name__
 built-in variable
 evaluates to the name of the current module
 If the source file is executed as the main program,
the interpreter sets the __name__ variable to have a value as “__main__”
20. Write the command for wrapping C++ code.

if _ _name_ _==‟_ _ main_ _‟:


main(sys.argv[1:])

213
21. What is the use of “CD” and “Cls” command?
 CD  To Change the directory in command window
 Cls To clear the screen in command window

22. How to execute C++program through python?

 Double click the run terminal of MinGW


 Go to the folder where the Python software is located (Python.exe) is located.
Ex: C:\Program Files\OpenOffiice 4\Python.

Syntax: To change from c:\> to the folder

cd<absolute path>
 “cd” command → change directory
 absolute path → complete path where Python is installed.
 To execute our program double click the run terminal change the path to the Python
folder location.

23. How to import modules in Python?

 We can import the definitions inside a module to another module.


 We use the import keyword is used.

import modulename

24. How to access the function using module?


 Using the module name we can access the functions defined inside the module.

 The dot (.) operator is used to access the functions.

Syntax:
<module name> . <function name>

25. Write the syntax to execute C++ program through python?

Python <filename.py> -i <C++ filename without cpp extension>

214
Python keyword to execute the Python program from
command-line
filename.py Name of the Python program to executed
-i input mode

C++ filename without cpp extension name of C++ file to be compiled and executed

26. What are the elements that contain getopt() module? (or)
What are the values that return by getopt() module?
 getopt() method returns value consisting of two elements.
1. Opts contains list of splitted strings like mode, path.
2. 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().

27. What are the modules available for import and run c++ in Python?
1) Sys module
2) OS module
3) getopt() module

28. Python program Executing C++ Program using control statement


 Type the C++ program in notepad and save it as “.cpp”
 Type the Python program and save it “ .py”
 Click the Run Terminal and open the command window
 Go to the folder of Python using cd command.

5 Marks : (Book Back Questions)


1. Write any 5 features of Python? *

1. Python uses Automatic Garbage Collection.


2. Python is a dynamically typed language.
3. Python runs through an interpreter.
4. Python code tends to be 5 to 10 times shorter than that written in C++.
5. In Python, there is no need to declare data types explicitly.
6. In Python, a function may accept an argument of any type, and return multiple values.
7. Python deletes unwanted objects automatically to free the memory space.

215
2. Explain each word of the following command. *

Python <filename.py> -i <C++ filename without cpp extension>

Answer:

Python keyword to execute the Python program from


command-line.

filename.py Name of the Python program to executed

-i input mode

C++ filename without cpp extension name of C++ file to be compiled and executed .

3. Explain about python sys module.

 sys module provides access to built in variables.


 It is used by the interpreter.

sys.argv  list of command-line arguments passed to the Python program.


vv

argv  one of the variable of sys module.


 Contains all the items that come via command-line input
 Basically a list.
 Holding the command line argument of the program.
To use sys.argv: First import sys should be used.

sys.argv[0] : It is the first argument. (Name of the python program)


sys.argv[1] : It is the next argument.(Name of the C++ program)

Ex: main(sys.argv[1])

Explanation:
argv[1]  contains c++ input file along with its path.
argv[0]  contains the python program which need not to be passed .
 Because by default __main__ contains source code reference.

216
4. Explain about OS module.
 OS module provides operating system dependent functionality.
 OS module allows to interface with the Windows OS where Python is running on.
os.system():
 system() defined in os module.
 Execute the C++ compiling command in the shell.
Syntax:
os.system („g++‟ + <varaiable_name1> +„-<mode>‟ + <variable_name2>)

Ex:
s.system („g++‟ + cpp_file +„-o‟ + exe_file)

Syntax explanation:

os.system  system() defined in OS module.


 General compiler.
g++
 It compiles C++ program under Windows OS.

variable_name1  Name of the C++ file without extension .cpp (string format).

mode  specify input or output mode.


 „o‟ prefixed with hyphen(-).

variable_name2  Name of the executable file without extension .exe (string format)
„+‟  Indicates all strings are concatenated as a single string

5. Explain about getopt() module.


Python getopt module :
 getopt module parse command-line options and arguments. (parse split )
 getopt module provides getopt() method.
 getopt() method to enable command-line argument parsing.

getopt.getopt() function :
 getopt() function parses command-line options and parameter list.
Syntax:
<opts>,<args>=getopt.getopt(argv, options, [long_options])

217
Syntax Explanation :
argv  Argument list of values to be parsed (splited).
options  This is string of option letters for input or for output.
 options letters ( „i‟ or „o‟)
 options letters followed by colon (:)
 colon denotes the mode.

Long_options  contains list of strings.


 Long options argument should be followed by an equal sign („=‟).
getopt() method :
 The return value consists of two elements.
1) opts
2) args
 Each of these values are stored separately in two different list (arrays).

opts  contains list of splitted strings like mode and path.

args  contains error string. (if all comment is given with wrong path or wrong mode)
 args will be empty list. (if there is no error).

Ex :
opts, args = getopt . getopt(argv, “i:” , [„ ifile= ‟])

Where opts contains [('-i', 'c:\\pyprg\\p4')]


-i: Option - mode should be followed by :
'c:\\pyprg\\p4' Value – absolute path of c++ file.

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

#include <iostream>
using namespace std;
int main()
{
cout<<“WELCOME”;
return(0);

218
Program:

import sys, os, getopt


def main(argv):
cpp_file = ''
exe_file = ''
opts, args = getopt.getopt(argv, "i:",['ifile='])
for o, a in opts:
if o in ("-i", "--ifile"):
cpp_file = a + '.cpp'
exe_file = a + '.exe'
run(cpp_file, exe_file)
def run(cpp_file, exe_file):
print("Compiling " + cpp_file)
os.system('g++ ' + cpp_file + ' -o ' + exe_file)
print("Running " + exe_file)
print("-----------------------")
print
os.system(exe_file)
print
if __name__ =='__main__':
main(sys.argv[1:])

Output: WELCOME

219
UNIT-V Chapter-15 (DATA MANIPULATION THROUGH SQL)
=========================================================
2 Marks: (Book Back Questions)
1. Mention the users who use the Database.
 Human users, other programs or applications.

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


 Connection is created by using “ connect ( )” method .
 Also pass the name of the database File.
Ex:
connection = sqlite3.connect ("Academy.db")
cursor = connection.cursor()

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


 If a column of a table is declared as INTEGER PRIMARY KEY,
then whenever a NULL is used as an input for the column,
the NULL will be automatically converted into an integer
which will be 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) the record in the table "INSERT" command is passed to SQLite.


Execute( ) method: Executes the SQL command to perform some action.

Ex:
sql_command = """INSERT INTO Student (Rollno, Sname, gender, DOB)
VALUES (NULL, "Santhosh", "M","07-01-2003");"""
cursor.execute(sql_ command)

5. Which method is used to fetch all rows from the database table?

 fetchall( ) method is to fetch all rows from the database table.


Ex:
ans= cursor.fetchall( )

220
3 Marks: (Book Back Questions)
6. What is SQLite? What is it advantage?
 SQLite is a simple relational database system.
 It saves its data in regular data files or in the internal memory of the computer.
 It is designed to be embedded in applications.
Avantage:
 SQLite is i) fast,
ii) rigorously tested,
iii) flexible,
iv) making it easier to work.
 Python has native library for SQLite

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


s.no fetchone() fetchmany()
1. Returns the next row of a query result set Returns the next number of rows (n) of the
or None in case there is no row left. result set.
2. Using while loop and fetchone( ) method using fetchmany( ) method
we can display all the records from a Displaying specified number of records
table.

8. What is the use of Where Clause. Give a python statement Using the where clause.

 WHERE clause is used to extract only those records that fulfill a specified condition.

Ex:
To display the different grades scored by male students from student table.

import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT DISTINCT (Grade) FROM student WHERE gender='M'")
result = cursor.fetchall()
print(*result,sep="\n")

9. Read the following details. Based on that write a python script to display
department wise records
Database name : organization.db
Table name : Employee
Columns in the table : Eno, EmpName, Esal, Dept

221
Answer :
import sqlite3
connection=sqlite3.connect(“organization.db”)
cursor=connection.cursor()
cursor.execute(“SELECT * FROM Employee GROUP BY Dept”)
result=cursor.fetchall()
for row in result:
print(row)
connection.close()

10. Read the following details. Based on that write a python script to display records in
descending order of Eno
Database name :organization.db
Table name : Employee
Columns in the table :Eno, EmpName, Esal, Dept
Answer:

import sqlite3
connection=sqlite3.connect(“organization.db”)
cursor=connection.cursor()
cursor.execute(“SELECT*FROM Employee ORDER BY Eno DESC”)
result=cursor.fetchall()
print(result)
connection.close()

Additional 2 Marks And 3 Marks Questions:


11. What are the advantages of sqlite?

 SQLite is fast, rigorously tested, and flexible, making it easier to work.

12. How to use sqlite?

Step 1: import sqlite3


Step 2 : create a connection.
a) using connect () method
b) pass the name of the database File

Step 3: Set the cursor object.


cursor = connection. cursor ()

222
13. What do you meant by cursor?
 A cursor is a control structure.
 cursor is used to traverse and fetch the records of the database.
 In Python, all the commands will be executed using cursor object only.

14. How to create a database using sqlite?

1. import sqlite3
2. connection=sqlite3.connect(“database name.db”)
3. cursor=connection.cursor()

15. How to create a table in a database using sqlite?


 After created database, add one or more tables to this database.
Ex:
CREATE TABLE Student
( Rollno INTEGER,
Sname VARCHAR(20),
Grade CHAR(1),
gender CHAR(1),
Average float(5.2),
birth_date DATE, PRIMARY KEY (Rollno)
);

16. How to define a sql command?


 We can define a SQL command with a triple quoted ( “”” “””) string in Python.

17. What is symbol?


 symbol is used to print the list of all elements in a single line with space.
 To print all elements in new lines or separated by space use sep= "\n" or sep= ","
respectively.

18. Write the placeholders which supported by SQlite3 module execute.


Execute (sql [, parameters])
Executes a single SQL statement.

 The SQL statement may be parametrized (i. e. Use placeholders instead of SQL literals).
 The sqlite3 module supports two kinds of placeholders:
 question marks ? (“qmark style”)
 named placeholders : name (“named style”).

223
19. Write a short note on select query.

 “Select” is the most commonly used statement in SQL.


 SELECT Statement is used to retrieve or fetch data from a table in a database.
Syntax:
“Select * from table_name”

 All the table data can be fetched in an object in the form of list of Tuples.

20. Write a note on fetchall() method

 fetchall() method is used to fetch all rows from the database table.
Ex:

import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM student")
result = cursor.fetchall()
for r in result:
print(r)

21. Write a note on fetchone() method

 fetchone() method returns the next row of a query result set (or)
None in case there is no row left.
 We can display all the records from a table using while loop and fetchone() method.
Ex:

import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM student")
result = cursor.fetchone()
print(result)

22. Write a note on fetchmany() method

 fetchmany() method returns the next number of rows (n) of the result set.
 Displaying specified number of records is done by using fetchmany().

224
Ex:

import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM student")
result = cursor.fetchmany(3)
print(result)

23. What are the frequently used clauses in sqlite?

 DISTINCT
 WHERE
 GROUP BY
 ORDER BY
 HAVING

24. Write a note on distinct clause

 It is helpful for avoiding the duplicate values present in any specific columns/table.
 When we use distinct keyword only the unique values are fetched.
Ex:

import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT DISTINCT (Grade) FROM student")
result = cursor.fetchall()
print(result)

25. How to represent the path?

 The path of a file can be either represented as „/‟ or using „\\‟ in Python.

Ex: 'c:/pyprg/sql.csv' (or) c:\\pyprg\\sql.csv‟


26. Write a note on group by clause.

 SELECT statement can be used along with GROUP BY clause.


 GROUP BY clause groups records into summary rows.
 It returns one records for each group.

225
 It is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group
the result-set by one or more columns.
Ex:
cursor.execute("SELECT gender,count(gender) FROM student Group BY gender")

27. Write a note on order by clause.

 ORDER BY Clause can be used along with the SELECT statement.


 It is used to sort the data of specific fields in an ordered way(ascending/descending order)

Ex: cursor.execute("SELECT Rollno,sname FROM student Order BY sname")

28. Write a note on having clause.

 Having clause is used to filter data based on the group functions.


 Group functions can be used in HAVING clause.
Ex:

cursor.execute("SELECT GENDER,COUNT(GENDER) FROM Student


GROUP BY GENDER HAVING COUNT(GENDER) >3")

29. Write a program using AND operator.

Ex: To display the name, Rollno and Average of students who have scored an average
between 80 to 90%
Program Output

import sqlite3
connection = sqlite3.connect("Academy.db") (1, 'Akshay', 87.8)
cursor = connection.cursor() (5, 'VARUN', 80.6)
cursor.execute("SELECT Rollno,Same,Average FROM student
WHERE (Average>=80 AND Average<=90)")
result = cursor.fetchall()
print(*result,sep="\n")

226
30. Write a program using OR operator

Ex: To display the name and Rollno of students who have not scored an average
between 60 to 70%
Program Output

import sqlite3 (1, 'Akshay', 87.8)


connection = sqlite3.connect("Academy.db") (5, 'VARUN', 80.6)
cursor = connection.cursor()
cursor.execute("SELECT Rollno,sname FROM student
WHERE (Average<60 OR Average>70)")
result = cursor.fetchall()
print(*result,sep="\n")

31. Write a program using NOT operator.


Ex: To display the details of students who have scored other than „A‟ or „B‟ from the “student table.

Program Output

import sqlite3 (3, 'BASKAR', 'C', 'M', 75.2)


connection = sqlite3.connect("Academy.db") (7, 'TARUN', 'D', 'M', 62.3)
cursor = connection.cursor()
cursor.execute("SELECT * FROM student
WHERE NOT Grade='A' and NOT Grade='B'")
result = cursor.fetchall()
print(*result,sep="\n")

32. What are aggregate functions?

1) COUNT()
2) AVG()
3) SUM()
4) MAX()
5) MIN()

33. Write a note on COUNT()

 COUNT() function returns the number of rows in a table satisfying the criteria specified in
the WHERE clause.
 It returns 0 if there were no matching rows.

227
Ex:
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT COUNT(*) FROM student ")
result = cursor.fetchall()
print(result)

34. Write a note on AVG().

 Used to finds the average mark of all students.


Ex:

import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT AVG(AVERAGE) FROM student ")
result = cursor.fetchall()
print(result)

35. Write a note on SUM().

 Used to finds the sum of all average in “Student table”.

Ex:

import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT SUM(AVERAGE) FROM student ")
result = cursor.fetchall()
print(result)

36. Differentiate MAX() and MIN()

MAX() MIN()

Returns the largest value of the selected Returns the smallest value of the selected
column. column.

228
37. Write a program with Max() and Min()

Program:

import sqlite3
connection = sqlite3.connect("Organization.db")
cursor = connection.cursor()
cursor.execute("SELECT sname, max(AVERAGE) FROM student ")
result = cursor.fetchall()
print(result)
cursor.execute("SELECT sname,min(AVERAGE) FROM student ")
result = cursor.fetchall()
print(result)

OUTPUT: Displaying the name of the Highest Average


[('PRIYA', 98.6)]
Displaying the name of the Least Average
[('TARUN', 62.3)]

38. What is sqlite_master?

 SQlite_master is the master table.


 It holds the key information about our database tables and it is called sqlite_master

39. How to display the list of tables in database?

 To show (display) the list of tables created in a database by sqlite_master

cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")

40. Write a note on cursor.description.

 cursor. description contain the details of each column headings .


 It will be stored as a tuple
 First one is 0(zero) index refers to the column name.
 From index 1 onwards the values of the column(Records) are referred.
 Using this command we can display the table‟s Field names.

229
5 Marks: (Book Back Questions)
1. Write in brief about SQLite and the steps used to use it.

 SQLite is a simple relational database system


 It saves its data in regular data files or in the internal memory of the computer.
 It is designed to be embedded in applications, instead of using a separate database server.
Advantages :
 SQLite is i) fast,
ii) rigorously tested
iii) flexible,
iv) making it easier to work.
 Python has a native library for SQLite.
To use SQLite:
Step1: import sqlite3
Step 2 : create a connection.
1. using connect () method
2. pass the name of the database File.
Step 3: Set the cursor object.
cursor = connection. cursor ()

Explanation:
1. In step 2, Connecting to a database means passing the name of the database to be
accessed.
2. If the database already exists, Python will open an existing database file.
]If the database not exists, Python will open a new database file.
3. In step 3, cursor is a control structure.
a) cursor is used to traverse and fetch the records of the database.
b) In python, all the commands will be executed using cursor object only.
Ex: sql_comm = "SQL statement"

 For executing the command use the cursor method .


 Then, pass the required sql command as a parameter.
 Many number of commands can be stored in the sql_comm.
 They can be executed one after other.
 Any changes made in the values of the record should be saved by the command "Commit"
before closing the "Table connection".

230
2. Write the Python script to display all the records of the following table using fetchmany()

Icode ItemName Rate


1003 Scanner 10500
1004 Speaker 3000
1005 Printer 8000
1008 Monitor 15000
1010 Mouse 700

PROGRAM Output

import sqlite3 Displaying all the records


connection=sqlite3.connect(“Material.db”)
(1003 , “ Scanner”, 10500)
cursor=connection.cursor()
cursor.execute(“SELECT*FROM hardware”) (1004 , “Speaker”, 3000)
print(“Displaying all the records:”) (1005 , “Printer”, 8000)
result=cursor.fetchall() (1008 , “Monitor”, 15000)
print(* result,sep=”\n”) (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.


 It is similar to WHERE condition.
 But Having clause can be used only with group functions.
 Group functions can be used in HAVING clause.

Ex:
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT GENDER,COUNT(GENDER) FROM Student
GROUP BY GENDER HAVING COUNT(GENDER)>3")
result = cursor.fetchall()
co = [i[0] for i in cursor.description]
print(co)
print(result)

Output: [„gender‟,‟COUNT(gender)‟]
[(„M‟,5)]

231
4. Write a Python script to create a table called ITEM with following specification.
Add one record to the table.
Name of the database : ABC
Name of the table : Item
Column name and specification :

Icode : integer and act as primary key


Item Name : Character with length 25
Rate : Integer
Record to be : 1008, Monitor,15000
added
Program:
import sqlite3
connection=sqlite3.connect(“ABC.db”)
cursor=conncection.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(1008,‟Monitor‟,15000);”””
cursor.execute(sql_command)
connection.commit()
connection.close()

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

SUPPLIER
Suppno Name City Icode SuppQty
S001 Prasad Delhi 1008 100
S002 Anu Bangalore 1010 200
S003 Shahid Bangalore 1008 175
S004 Akila Hydrabad 1005 195
S005 Girish Hydrabad 1003 25
S006 Shylaja Chennai 1008 180
S007 Lavanya Mumbai 1005 325

i) Display Name, City and Itemname of suppliers who do not reside in Delhi.
ii) Increment the SuppQty of Akila by 40

232
PROGRAM: i)

import sqlite3
connection=sqlite3.connect(“ABC.db”)
cursor=connection.cursor()
cursor.execute (“SELECT name, 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)
connection.commit()
connection.close()

OUTPUT:
[ „Name‟ „city‟ „Item name‟]
[ „Anu‟ „Bangalore‟ „Scanner‟]
[ „Shahid‟ „Bangalore‟ „Speaker]
[ „Akila‟ „Hydrabad‟ „Printer‟]
[ „Girish‟ „Hydrabad‟ „Monitor‟]
[ „Shylaja‟ „Chennai‟ „Mouse‟]
[ „Lavanya‟ „Mumbai‟ „CPU‟]

PROGRAM: ii)

import sqlite3
connection=sqlite3.connect(“ABC.db”)
cursor=connection.cursor()
cursor.execute (“UPDATE supplier SET suppqty=suppqty+40 WHERE name=‟Akila‟ ”)
cursor.commit()
result=cursor.fetchall()
print(result)
connection.close()

OUTPUT:
(s004,‟Akila‟, „Hydrabad‟, 1005, 235)

233
Additional 5 Marks Questions:
1. Explain in detail about various clauses in SQL.

 Clauses can be used in the SELECT statements.


1) DISTINCT
2) WHERE
3) GROUP BY
4) ORDER BY
5) HAVING

DISTINCT clause:
 It is helpful for avoiding the duplicate values present in any specific columns/table.
 When we use distinct keyword, only the unique values are fetched.
Ex:

Program : Output:
import sqlite3
connection = sqlite3.connect("Academy.db") [(„B‟),(„A‟),(„C‟),(„D‟)]
cursor = connection.cursor()
cursor.execute("SELECT DISTINCT (Grade) FROM student")
result = cursor.fetchall()
print(result)

WHERE clause:
 It is used to extract only those records that fulfill a specified condition.

Ex:
To display the different grades scored by male students from student table.

Program Output:
import sqlite3 („B‟)
connection = sqlite3.connect("Academy.db") („A‟)
cursor = connection.cursor() („C‟)
cursor.execute("SELECT DISTINCT (Grade) FROM student („D‟)
WHERE gender='M'")
result = cursor.fetchall()
print(*result,sep="\n")

234
GROUP BY clause:

 The SELECT statement can be used along with GROUP BY clause.


 The GROUP BY clause groups records into summary rows.
 It returns one records for each group.
 It is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the
result-set by one or more columns.
Ex:

Ex:
To count the number of male and female student from student table.

Program Output:
import sqlite3
connection = sqlite3.connect("Academy.db") („F‟, 2)
cursor = connection.cursor() („M‟, 5)
cursor.execute("SELECT gender,count(gender) FROM student
Group BY gender")
result = cursor.fetchall()
print(*result,sep="\n")

ORDER BY Clause:
 It can be used along with the SELECT statement
 It is used to sort the data of specific fields in an ordered way(ascending/descending order).
Ex:
Name and rollno of the students are displayed in alphabetical order from student table.

Program Output:
import sqlite3
connection = sqlite3.connect("Academy.db") („1‟, „Arun‟)
cursor = connection.cursor() („2‟, „Bala ‟)
cursor.execute("SELECT Rollno, sname FROM student („3‟, „Hari‟)
ORDER BY sname") („4‟, „Kavi‟)
result = cursor.fetchall() („5‟, „Mano‟)
print(*result,sep="\n")

235
HAVING clause:

 Having clause is used to filter data based on the group functions.


 It is similar to WHERE condition.
 But Having clause can be used only with group functions.
 Group functions can be used in HAVING clause.
Ex:
Name and rollno of the students are displayed in alphabetical order from student table.

Program Output:
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor() [„gender‟,‟COUNT(gender)‟]
cursor.execute("SELECT GENDER,COUNT(GENDER) [(„M‟,5)]
FROM Student GROUP BY GENDER
HAVING COUNT(GENDER)>3")
result = cursor.fetchall()
co = [i[0] for i in cursor.description]
print(co)
print(result)

2. Explain in detail about aggregate functions?

1) COUNT()
2) AVG()
3) SUM()
4) MAX()
5) MIN()

COUNT():

 COUNT() function returns the number of rows in a table satisfying the criteria specified in
the WHERE clause.
 It returns 0 if there were no matching rows.
Ex:

import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT COUNT(*) FROM student ")
result = cursor.fetchall()
print(result)

236
AVG():

 Used to finds the average mark of all students.


Ex:

import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT AVG(AVERAGE) FROM student ")
result = cursor.fetchall()
print(result)

SUM():

 Used to finds the sum of all average in “Student table”.

Ex:

import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT SUM(AVERAGE) FROM student ")
result = cursor.fetchall()
print(result)

MAX():
 Returns the largest value of the selected column.

MIN():
 Returns the smallest value of the selected column.

Ex:

import sqlite3
connection = sqlite3.connect("Organization.db")
cursor = connection.cursor()
cursor.execute("SELECT sname, max(AVERAGE) FROM student ")
result = cursor.fetchall()
print(result)
cursor.execute("SELECT sname,min(AVERAGE) FROM student ")
result = cursor.fetchall()
print(result)

237
OUTPUT: Displaying the name of the Highest Average
[('PRIYA', 98.6)]
Displaying the name of the Least Average
[('TARUN', 62.3)]

3. Explain SQL operators with clauses in detail.


 SQL operators are
1) AND
2) OR
3) NOT

 The AND and OR operators are used to filter records based on more than one condition.

AND operator:
Ex: To display the name, Rollno and Average of students who have scored an average
between 80 to 90%
Program Output

import sqlite3
connection = sqlite3.connect("Academy.db") (1, 'Akshay', 87.8)
cursor = connection.cursor() (5, 'VARUN', 80.6)
cursor.execute("SELECT Rollno,Same,Average FROM student
WHERE (Average>=80 AND Average<=90)")
result = cursor.fetchall()
print(*result,sep="\n")

OR operator:

Ex: To display the name and Rollno of students who have not scored an average
between 60 to 70%
Program Output
import sqlite3 (1, 'Akshay', 87.8)
connection = sqlite3.connect("Academy.db") (5, 'VARUN', 80.6)
cursor = connection.cursor()
cursor.execute("SELECT Rollno,sname FROM student
WHERE (Average<60 OR Average>70)")
result = cursor.fetchall()
print(*result,sep="\n")

238
NOT operator:

Ex: To display the details of students who have scored other than „A‟ or „B‟
from the “student table
Program Output

import sqlite3 (3, 'BASKAR', 'C', 'M', 75.2)


connection = sqlite3.connect("Academy.db") (7, 'TARUN', 'D', 'M', 62.3)
cursor = connection.cursor()
cursor.execute("SELECT * FROM student where NOT
Grade='A' and NOT Grade='B'")
result = cursor.fetchall()
print(*result,sep="\n")

239
UNIT – V – Chapter 16. DATA VISUALIZATION USING PYPLOT:
LINE CHART, PIE CHART AND BAR CHART
=======================================================
2 Marks: (Book Back Questions)
1. What is data Visualization?

 Data Visualization is the graphical representation of information and data.


Objective: communicate information visually to users.

2. List the General types of Data Visualization •


1. Tables
2. Graphs
3. Charts
4. Maps
5. Infographics
6. Dashboards

3. List the Types of Visualizations in Matplotlib.


1. Bar chart
2. Pie chart
3. Line plot
4. Box plot
5. Scatter plot
6. Histogram
4. How will you install Matplotlib?
 We can install matplotlib using pip.
 Pip is management software for installing python packages.
Importing Matplotlib using the command:

import matplotlib.pyplot as plt

 Matplotlib can be imported in the workspace.

240
5. Write the difference between the following functions:
plt.plot( [1,2,3,4] ), plt.plot( [1,2,3,4], [1,4,9,16] )

s.no plt.plot( [1,2,3,4] ) plt.plot( [1,2,3,4], [1,4,9,16] )


1. It refers y value as [1,2,3,4] This plot takes many parameters.
It refers x and y value as( [1,2,3,4],[1,4,9,16] )

2. Indirectly it refers x value as [0,1,2,3] Directly x and y values are given as


(0,1), (1,1), (2,3), (3,4) (1,1), (2,4), (3,9), (4,16)

3. Ex: import matplotlib.pyplot as plt Ex: import matplotlib.pyplot as plt


plt.plot([1,2,3,4]) plt.plot([1,2,3,4], [1,4,9,16])
plt.show() plt.show()

3 Marks: (Book Back Questions)


6. Draw the output for the following data visualization plot.
import matplotlib.pyplot as plt
plt.bar([1,3,5,7,9],[5,2,7,8,2], label="Example one")
plt.bar([2,4,6,8,10],[8,6,2,5,6], label="Example two", color='g')
plt.legend()
plt.xlabel('bar number')
plt.ylabel('bar height')
plt.title('Epic Graph\nAnother Line! Whoa')
plt.show()

Answer :

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

8. Write the plot for the following pie chart output.

Answer :
import matplotlib.pyplot as plt
slices = [29.2,8.3,8.3,54.2]
labels = ["sleeping", "eating", "working",”playing”]
plt.pie (slices, labels = labels, autopct= "%.2f")
plt.axes( ). Set_aspect(“equal”)
plt.title(“Interesting Graph \n Check it out”)
plt.show()

Additional 2 Marks & 3 marks Questions:


9. What is Matplotlib? Write its use.

 Matplotlib is the most popular data visualization library in Python.


 It allows you to create charts in few lines of code.

10. What is pip?


 Pip is a management software for installing python packages.

242
11. What is infographics?
 infographic  information graphic.
 An infographic is the representation of information in a graphic format.

12. What is dashboard?


 A dashboard is a collection of resources assembled to create a single unified visual display.
 Data visualizations and dashboards translate complex ideas and concepts into a simple
visual format.
 Patterns and relationships that are undetectable in text are detectable at a glance using
dashboard.

13. What is scatter plot?


 A scatter plot is a type of plot.
 It shows the data as a collection of points.
 The position of a point depends on its two-dimensional value.
 Each value is a position on either the horizontal or vertical dimension.

14. What is Box plot?


 Box plot is a standardized way of displaying the distribution of data
based on the five number summary:
1. minimum,
2. first quartile
3. median
4. third quartile
5. maximum.

15. What is Line Plot / chart?

 A Line Chart or Line Graph is a type of chart.


 It displays information as a series of data points.
 Data points are called as „markers‟ .
 Markers are connected by straight line segments.
 Visualize a trend in data over intervals of time – a time series .

16. What is Bar Plot / chart?

 Bar chart represents categorical data with rectangular bars.


 Each bar has a height corresponds to the value it represents.
 The bars can be plotted vertically or horizontally.

243
17. What is Pie chart?

 Pie Chart is probably one of the most common type of chart.


 It is a circular graphic .
 It is divided into slices to illustrate numerical proportion.
 The point of a pie chart is to show the relationship of parts out of a whole.

18. What is the use of autopct parameter?


 It allows us to display the percentage value using python string formatting.

19. Write the python code to plot two lines.

Python coding : Output:

import matplotlib.pyplot as plt


x = [1,2,3]
y = [5,7,4]
x2 = [1,2,3]
y2 = [10,14,12]
plt.plot(x, y, label='Line 1')
plt.plot(x2, y2, label='Line 2')
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.title('LINE GRAPH')
plt.legend()
plt.show()

20. What is the output of the following code?

Python coding : Output:

import matplotlib.pyplot as plt


plt.plot([1,2,3,4])
plt.show()

244
21. What is the output of the following code?

Python coding : Output:

import matplotlib.pyplot as plt


plt.plot([1,2,3,4], [1,4,9,16])
plt.show()

22. What is the output of the following code?


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]
y_positions = range (len(labels))
plt.bar (y_positions, usage)
plt.xticks (y_positions, labels)
plt.ylabel ("RANGE")
plt.title ("MARKS")
plt.show()

Output :

23. What is the output of the following code?


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

245
plt.ylabel ("Total Population")
plt.show( )

Output :

24. Draw the chart for the given python snippet.


import matplotlib.pyplot as plt
plt.plot ([1,2,3,4],[1,4,9,16])
plt.show( )

Answer:

25. Write the coding for the following:


a. To check if PIP is Installed in your PC.
b. To Check the version of PIP installed in your PC.
c. To list the packages in matplotlib.

246
Answer:
a) To check if PIP is Installed in your PC :
1. In command prompt type pip-version
2. If it is installed already,you will get version.
3. Command : python – m pip install –U pip.
b) To Check the version of PIP installed in your PC:
C:\Users\YourName\AppData\Local\Programs\Python
\Python36-32\Scripts>pip-version.
c) To list the packages in matplotlib :
C:\Users\YourName\AppData\Local\Programs\Python
\Python36-32\Scripts>pip list

5 Marks: (Book Back Questions)


1. Explain in detail the types of pyplots/Charts using Matplotlib.

Types of pyplots
1. Line chart
2. Bar chart
3. Pie chart
Line Chart :
 A Line Chart or Line Graph is a type of chart.
 It displays information as a series of data points.
 Data points are called as „markers‟ .
 Markers are connected by straight line segments.
 Visualize a trend in data over intervals of time – a time series .

Ex:
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.show()

247
BarChart :

 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 bars.
 Each bar has a height corresponds to the value it represents.
 The bars can be plotted vertically or horizontally.
 To make a bar chart with Matplotlib, we can use the plt.bar() function.

Ex:
import matplotlib.pyplot as plt
label = ["TAMIL", "ENGLISH", "CS"]
use = [6, 8, 10]
y = range(3)
plt.bar (y, use)
plt.xticks (y, label)
plt.ylabel ("RANGE")
plt.title ("MARKS")
plt.show()

Pie Chart :

 Pie Chart is probably one of the most common type of chart.


 It is a circular graphic .
 It is divided into slices to illustrate numerical proportion.
 The point of a pie chart is to show the relationship of parts out of a whole.
 To make a Pie Chart with Matplotlib, we can use the plt.pie() function.
 autopct parameter allows to display the percentage value using the Python string
formatting.

Ex:
import matplotlib.pyplot as plt
sizes = [80, 90, 100]
labels = ["Tamil", "English", "CS"]
plt.pie (size, labels = labels, autopct= "%.2f")
plt.show()

248
2. Explain the Buttons in the output of plot / chart.

1. Home Button :

 It will help once we have begun navigating the chart.


 It allows to return back to the original view.

2. Forward/Back buttons :
 It can be used like the Forward and Back buttons in the browser.
 It allows to move back or forward again.

3. Pan Axis :

 This is cross-looking button


 It allows to click it, and then click and drag our graph around.

4. Zoom :
 It allows to click and drag a square that would like to zoom into specifically.
 Zooming in will require a left click and drag.
 Zoom out will require a right click and drag.
5. Configure Subplots :
 It allows to configure various spacing options with your figure and plot.

6. Save Figure :

 It allows to save your figure in various forms.

3. Explain the purpose of the following functions.


a) plt.xlabel( )
b) plt.ylabel( )
c) plt.title( )
d) plt.legend( )
e) plt.show( )

plt.xlabel( )  specifies the label for the x-axis.


plt.ylabel( )  specifies the label for the y-axis.
plt.title( )  specifies the title to the graph.

249
plt.legend( )  invoke the default legend with plt.legend( ).
 Calling legend( ) with no arguments automatically fetches the legend
handle and their associated labels.

plt.show( )  Display the plot/figure.

Additional 5 Marks Questions:


1. What are the Key Differences between Histogram and Bar Graph?

s.no Histogram Bar Graph


1. It is a graphical representation of It is a pictorial representation of different
numerical data. categories of data.
2. It represents the frequency distribution of It is a diagrammatic comparison of
continuous variables. discrete variables.
3. It presents numerical data. It shows categorical data.
4. It drawn in no gap between the bars. It indicates discontinuity.
5. Items of the histogram are numbers, Items on Bar graph are considered as
Which are categorised together, to individual entities.
represent ranges of data.
6. It shows in the sequence of classes. It shows blocks from highest to lowest.
7. The width of rectangular blocks in a The width of the bars is always same.
histogram may or may not be same.

250
Chapter 1 to 16
================================================
5 Mark Questions:
Chapter-1
1. What are called parameters and write a note on
i) parameter without type *
ii) parameter with type.
(OR)
Explain about the function specification. *
2. Explain with example pure and impure functions. *
3. Explain with an example interface and implementation. *
4. Explain in detail about chameleons of chromeland problem using function.

Chapter -2
5. How will you facilitate the data abstraction explain? * (Book Back)
6. What is list? why list called as pairs? Explain with suitable example . *(Book Back)
7. How will you access the multi item. Explain. * (Book Back)
8. What is tuple? Explain. (Additional question)

Chapter-3
9. Explain the types of scopes for variable.or explain LEGB rule with explain? (BookBack)*
10. Write any Five characteristics of Modules. (Book Back) *
11. Write any five benefits in modular programming. (Book Back) *

Chapter-4
12. Explain the characteristics of an algorithm? (Book Back) *
13. Discuss about linear search algorithm. (Book Back) *
14. What is Binary search? Discuss with example. (Book Back) *
15. Explain the bubble sort algorithm with example. (Book Back) *
16. Discuss about Selection sort algorithm. (Additional question) *
17. Discuss about Insertion sort algorithm. (Additional question) *
18. Explain the concept of Dynamic programming with suitable example. (Book Back)

Chapter-5
19. Describe in detail the procedure for script mode programming. *(Book Back)
20. Explain input() and print() function with example. *(Book Back)
21. Discuss in detail about tokens in python. *

251
Chapter-6
22. Explain if and if else statement? (Additional question) *
23. Write a detail note on if..else..elif statement with suitable example.(Book Back) *
24. Write a detail note on for loop. (Book Back) *
25. Explain the while loop with an example. (Additional question) *
26. Write a program to display all 3 digit odd numbers. (Book Back) *
27. Write a program to display multiplication table for a given number. (Book Back) *
28. Explain about the jump statement with an example. (Additional question)

Chapter-7
29. What is Scope of variables? explain. (Book Back) *
30. Explain the different types of function with an example.(Book Back)*
31. Explain id( ), chr( ), round( ), type( ) & pow( ) function? (Book Back) *
32. Explain recursive function with example. (Book Back) *
33. Explain the types of arguments. (additional question)
34. Write a Python code to find the L.C.M. of two numbers. (Book Back)
35. Explain mathematical function? (Additional question)

Chapter-8
36. Explain about string operators in python with suitable example. (Book Back) *
37. Explain the following Built-in String functions .(Additional question)

Chapter-9
38. What are the different ways to insert an element in list. Explain with example. (Book Back) *
39. What is the purpose of range()? Explain with an example. (Book back) *
40. Explain the different set operations supported by python with suitable example.(BB)
41. What is nested tuple? Give example. (Book Back) *
Chapter-10

42. Explain the constructor and destructor with an example. (Additional question)
43. What is class? How will you access class member? Explain with example(Additional question)
Chapter-11
44. What are the characteristics of DBMS? *
45. Explain the different types of data model. *
46. Differentiate DBMS and RDBMS? *
47. Explain the types of relational mapping. *
48. Explain the different operators in relational algebra with suitable examples. *
49. What are the components of DBMS? Explain. *

252
Chapter-12
50. Write the different types of constraints and their functions. *
51. Table with queries.
52. What are the components of SQL? Write the commands in each. *
53. Construct the following SQL statements in the student table-
54. Write any three DDL commands. *
55. Explain the SELECT statement with example.

Chapter-13

56. Differentiate Excel file and CSV file. *


57. Tabulate the different mode with its meaning. *
58. Write the rules to be followed to format the data in a CSV file.*
59. Write the different methods to read a File in Python. *
60. Write a Python program to write a CSV File with custom quotes.

Chapter-14
61. Write any 5 features of Python? *
62. Explain each word of the following command. *
63. Explain about python sys module. *
64. Explain about OS module.*
65. Explain about getopt() module.*
66. What is the purpose of sys, os, getopt module in python.Explain

Chapter-15
67. Write in brief about SQLite and the steps used to use it. *
68. Write Python script to display all the records of the following table using fetchmany()
69. What is the use of HAVING clause. Give an example python script

Chapter-16
70. What are the Key Differences Between Histogram and Bar Graph? *
71. What is Line Plot / chart? *
73. What is Bar chart? *
74. What is Pie chart? *
75. Explain the Buttons in the output of plot / chart.
76. Explain the purpose of the following functions.
77. Explain in detail the types of pyplots using Matplotlib.

253
BOOK BACK ONE MARKS
CHAPTER- 1. FUNCTION
==========================================================================
Choose the best answer:
1. The small sections of code that are used to perform a particular task is called
(A) Subroutines (B) Files (C) Pseudo code (D) Modules
2. Which of the following is a unit of code that is often defined within a greater code structure?
(A) Subroutines (B) Function (C) Files (D) Modules
3. Which of the following is a distinct syntactic block?
(A) Subroutines (B) Function (C) Definition (D) Modules
4. The variables in a function definition are called as
(A) Subroutines (B) Function (C) Definition (D) Parameters
5. The values which are passed to a function definition are called
(A) Arguments (B) Subroutines (C) Function (D) Definition
6. Which of the following are mandatory to write the type annotations in the function definition?
(A) {} (B) ( ) (C) [ ] (D) < >
7. Which of the following defines what an object can do?
(A) Operating System (B) Compiler (C) Interface (D) Interpreter
8. Which of the following carries out the instructions defined in the interface?
(A) Operating System (B) Compiler (C) Implementation (D) Interpreter
9. The functions which will give exact result when same arguments are passed are called
(A) Impure functions (B) Partial Functions
(C) Dynamic Functions (D) Pure functions
10. The functions which cause side effects to the arguments passed are called
(A) impure function (B) Partial Functions
(C) Dynamic Functions (D) Pure functions

254
CHAPTER- 2. DATA ABSTRACTION

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

8. Bundling two values together into one can be considered as


(A) Pair (B) Triplet (C) single (D) quadrat
9. Which of the following allow to name the various parts of a multi-item object?
(A) Tuples (B) Lists (C) Classes (D) quadrats
10. Which of the following is constructed by placing expressions within square brackets?
(A) Tuples (B) Lists (C) Classes (D) quadrats

255
CHAPTER-3 . SCOPING

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?
(A) Local Scope (B) Global scope (C) Module scope (D) Function Scope
6. The process of subdividing a computer program into separate sub-programs is called
(A) Procedural Programming (B) Modular programming
(C)Event Driven Programming (D) Object oriented Programming
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

256
CHAPTER – 4. ALGORITHMIC STRATEGIES

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) Insertion sort (C) Selection sort (D) All the above
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. An algorithm that yields expected output for a valid input is called an ________.
(A) algorithmic solution (B) algorithmic outcomes
(C) algorithmic problem (D) algorithmic coding
5. Which of the following is used to describe the worst case of an algorithm?
(A) Big A (B) Big S (C) Big W (D) Big O
6. Big Ω is the reverse of ______.
(A) Big O (B) Big θ (C) Big A (D) Big S
7. Binary search is also called as
(A) Linear search (B) Sequential search (C) Random search (D) Half-interval search

8. The Θ notation in asymptotic evaluation represents


(A) Base case (B) Average case (C) Worst case (D) NULL case

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

257
CHAPTER 5
PYTHON – VARIABLES AND OPERATORS
====================================================
1. Who developed Python ?
A) Ritche B) Guido Van Rossum
C) Bill Gates D) Sunder Pitchai
2. The Python prompt indicates that Interpreter is ready to accept instruction.
A) >>> B) <<< C) # D) <<
3. Which of the following shortcut is used to create new Python Program ?
A) Ctrl + C B) Ctrl + F C) Ctrl + B D) Ctrl + N
4. Which of the following character is used to give comments in Python Program ?
A) # B) & C) @ D) $
5. This symbol is used to print more than one item on a single line.
A) Semicolon(;) B) Dollor($) C) comma(,) D) Colon(:)
6. Which of the following is not a token ?
A) Interpreter B) Identifiers C) Keyword D) Operators
7. Which of the following is not a Keyword in Python ?
A) break B) while C) continue D) operators
8. Which operator is also called as Comparative operator?
A) Arithmetic B) Relational C) Logical D) Assignment
9. Which of the following is not Logical operator?
A) and B) or C) not D) Assignment
10. Which operator is also called as Conditional operator?
A) Ternary B) Relational C) Logical D) Assignment

258
CHAPTER – 6. CONTROL STRUCTURES
=====================================================
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 C) Structure 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 is the following is known as definite loop?
A) do..while B) while C) for D) if..elif
7. What is the output of the following snippet?
i=1
while True:
if i%3 ==0:
break
print(i,end='')
i +=1 A) 12 B) 123 C) 1234 D) 124

8. What is the output of the following snippet?


T=1
while T:
print(True)
break A) False B) True C) 0 D) 1

9. Which amongst this is not a jump statement ?


A) for B) pass C) continue D) break

10. Which punctuation should be used in the blank?


if <condition>_
statements-block 1
else:
statements-block 2

A) ; B) : C) :: D) !

259
CHAPTER 7 - PYTHON FUNCTIONS

=====================================================
1. A named blocks of code that are designed to do one specific job is called as
(a) Loop (b) Branching (c) Function (d) Block
2. A Function which calls itself is called as
(a) Built-in (b) Recursion (c) Lambda (d) return
3. Which function is called anonymous un-named function
(a) Lambda (b) Recursion (c) Function (d) define
4. Which of the following keyword is used to begin the function block?
(a) define (b) for (c) finally (d) def
5. Which of the following keyword is used to exit a function block?
(a) define (b) return (c) finally (d) def
6. While defining a function which of the following symbol is used.
(a) ; (semicolon) (b) . (dot) (c) : (colon) (d) $ (dollar)
7. In which arguments the correct positional order is passed to a function?
(a) Required (b) Keyword (c) Default (d) Variable-
length
8. Read the following statement and choose the correct statement(s).
(I) In Python, you don‟t have to mention the specific data types while defining function.
(II) Python keywords can be used as function name.
(a) I is correct and II is wrong (b) Both are correct
(c) I is wrong and II is correct (d) Both are wrong
9. Pick the correct one to execute the given statement successfully.
if ____ : print(x, " is a leap year")
(a) x%2=0 (b) x%4==0 (c) x/4=0 (d) x%4=0
10. Which of the following keyword is used to define the function testpython(): ?
(a) define (b) pass (c) def (d) while

260
CHAPTER 8 - STRINGS AND STRING MANIPULATION
=====================================================
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) =
4. Defining strings within triple quotes allows creating:
(a) Single line Strings (b) Multiline Strings
(c) Double line Strings (d) Multiple Strings
5. Strings in python:
(a) Changeable (b) Mutable (c) Immutable (d) flexible
6. Which of the following is the slicing operator?
(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)

261
CHAPTER 9 - LISTS, TUPLES, SETS AND DICTIONARY
=============================================================================
1. Pick odd one in connection with collection data type
(a) List (b) Tuple (c) Dictionary (d) Loop
2. Let list1=[2,4,6,8,10], then print(List1[-2]) will result in
(a) 10 (b) 8 (c) 4 (d) 6
3. Which of the following function is used to count the number of elements in a list?
(a) count() (b) find() (c)len() (d) index()

4. If List=[10,20,30,40,50] then List[2]=35 will result


(a) [35,10,20,30,40,50] (b) [10,20,30,40,50,35]
(c) [10,20,35,40,50] (d) [10,35,30,40,50]

5. If List=[17,23,41,10] then List.append(32) will result


(a) [32,17,23,41,10] (b) [17,23,41,10,32]
(c) [10,17,23,32,41] (d) [41,32,23,17,10]

6. Which of the following Python function can be used to add more than one element within an
existing list?
(a) append() (b) append_more() (c)extend() (d) more()
7. What will be the result of the following Python code?
S=[x**2 for x in range(5)]
print(S)
(a) [0,1,2,4,5] (b) [0,1,4,9,16] (c) [0,1,4,9,16,25] (d) [1,4,9,16,25]
8. What is the use of type() function in python?
(a) To create a Tuple (b) To know the type of an element in tuple.
(c) To know the data type of python object (d) To create a list.
9. Which of the following statement is not correct?
(a) A list is mutable (b) A tuple is immutable.
(c) The append() function is used to add an element.
(d) The extend() function is used in tuple to add elements in a list.

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

262
CHAPTER 10 - PYTHON CLASSES AND OBJECTS
=====================================================
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 when an object is created?
(a) __object__( ) (b) __del__( ) (c) __func__( ) (d) __init__( )
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
print (self.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

263
CHAPTER 11 - DATABASE CONCEPTS
=====================================================
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 d)entity
3 Which database model represents parent-child relationship?
a) Relational b) Network c) Hierarchical d) Object
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 Excel
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

264
CHAPTER 12 - STRUCTURED QUERY LANGUAGE (SQL)
=====================================================
1. Which commands provide definitions for creating table structure, deleting relations, and
modifying relation schemas.
a. DDL b. DML c. DCL d. DQL
2. Which command lets to change the structure of the table?
a. SELECT b. ORDER BY c. MODIFY d. ALTER
3. The command to delete a table including the structure is
a. DROP b. DELETE c. DELETE ALL d. ALTER TABLE
4. Queries can be generated using
a. SELECT b. ORDER BY c. MODIFY d. ALTER
5. The clause used to sort data in a database
a. SORT BY b. ORDER BY c. GROUP BY d. SELECT

265
CHAPTER 13 - PYTHON AND CSV FILES
=====================================================
1. A CSV file is also known as _______.
(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

A) chennai,mylapore (B) mumbai,andheri


(C) chennai (D) chennai,mylapore
mumbai,andheri

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

266
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 = '\n')
with open('c:\pyprg\ch13\line2.csv', 'w') as f:
wr = csv.writer(f,dialect='M')
wr.writerows(D)
f.close()
(A) Exam Quarterly Halfyearly (B) Exam Quarterly Halfyearly
(C) E (D) Exam,
Q Quarterly,
H Halfyearly

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

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

269
CHAPTER.16- DATA VISUALIZATION USING PYPLOT:
LINE CHART, PIE CHART AND BAR CHART
=========================================================
1. Which is a python package used for 2D graphics?
a. matplotlib.pyplot b. matplotlib.pip
c. matplotlib.numpy d. matplotlib.plt
2. Identify the package manager for Python packages, or modules.
a. Matplotlib b. PIP c. plt.show() d. python package
3. Which of the following feature is used to represent data and information graphically?
a. Data List b. Data Tuple
c. Classes and Object d. Data Visualization
4. ______ is the collection of resources assembled to create a single unified visual display.
a. Interface b. Dashboard c. Objects d. Graphics
5. Which of the following module should be imported to visualize data and information in python?
a. csv b. getopt c. mysql d. matplotlib
6. _____is the type of chart which displays information as a series of data points connected by
straight line segments. a. csv b. Pie chart c. barchart d. Line chart
7. Read the code:
import matplotlib.pyplot as plt
plt.plot(3,2)
plt.show()
Identify the output for the above coding.

270
9. Identify the right type of chart using the following hints.
Hint 1: This chart is often used to visualize a trend in data over intervals of time.
Hint 2: The line in this type of chart is often drawn chronologically.
a. Line chart b. Bar chart c. Pie chart d. Scatter plot

10. Read the statements given below. Identify the right option from the following for pie chart.
Statement A: To make a pie chart with Matplotlib, we can use the plt.pie() function.
Statement B: The autopct parameter allows us to display the percentage value using the Python
string formatting.
a. Statement A is correct b. Statement B is correct
c. Both the statements are correct d. Both the statements are wrong

271

You might also like