12th PYTHON Chapter 1 To 16
12th PYTHON Chapter 1 To 16
SUBJECT : ________________________
INDEX
1
Chapters Chapters Page No
No 2&3 5 Marks
Marks
Function
1.
2. Data Abstraction
3. Scoping
4. Algorithm strategies
6. Control structures
7. Python Function
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.
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.
let disp:
print „welcome‟ Ans : Normal function
• 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.
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.
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)
let randomnumber :=
a:= random()
if a >10 then
return: a
else
return : 10
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)
Program explanation:
Precondition (requires)
Post condition (returns) Given
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‟. (mandatorymust)
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.
Questions:
(i) Name of the function .
Ans: „gcd‟
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
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
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.
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.
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.
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
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
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)
The function which creates the object of the city is the constructor.
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.
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.
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
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).
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 := “[email protected]”
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]
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.
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
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 :
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
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:
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:
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)
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.
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
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.
30
19. Define pseudo code. *
It is a method of planning the solution, the programmer to plan without syntax.
26. Name the two factors, which decides the efficiency of an algorithm.
i) Time factor
ii) Space factor
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.
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.
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.
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
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.
Output: 3
35
3. What is Binary search? Discuss with example. * (Book Back)
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
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
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.
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
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
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.
11 12 13 14 15 16
----------------------------------------------------------------------------------------------------------------------
(OR)
50 10 30 20 40
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.
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
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
Output: 10
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‟‟‟
44
3 Types of literal:
i) Numeric
ii) String
iii) Boolean
i) Numeric:
It consists of digits.
It is immutable.
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
45
Python uses the symbols and symbol combinations as delimiters.
It is used in expressions, lists, dictionaries and strings.
Ex:
( ) { } [ ]
, : . „ = ;
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
i=1
while(i<=5):
for j in range(1,i+1):
print(i,end='')
print(end='\n')
i+=1
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
*****
****
***
**
*
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
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
51
To Execute python script :
1. Choose Run Run Module (or) press F5
2. If the program has any error, correct the errors.
[[
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:
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.
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.
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.
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
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.
+ 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.
Logical Operators :
It is used to perform logical operations on the given relational expression.
56
Assignment operator:
= simple assignment operator.
It assigns value (R.H.S) to a variable (L.H.S)
Ex:
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.
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
Program:
for i in range(65,70):
for j in range(65,i+1):
print(chr(j),end=' ')
print(end="\n")
59
5. List the difference between break and continue statements. *
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
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
Output: 10
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
Syntax: pass
62
if ..elif..else
while loop
for loop
63
break
continue :
64
Hands on Experience in book:
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")
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
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")
*****
****
***
**
*
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
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
Output: centum
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 variableAccess 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)
Syntax :
range(start,stop,[step]
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
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) *
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“.
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.
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”.
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. *
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.
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
Output: 70
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
functionname( )
( or)
functionname(arguments)
Ex:
def hello():
print(“hello python”)
hello()
78
30. Which is called as non-keyword variable arguments?
Non-keyword variable arguments are called tuples.
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.
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
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
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.
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
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
85
7. Explain mathematical function? ( Additional Question)*
86
3. Evaluate the following functions and write the output.
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?
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
COMPUTER
COMPUTE
COMPUT
COMPU
COMP
COM
CO
C
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 ()
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
str1 = “welcome”
str2 = “to school”
str 3 = str1[:2] + str2[len(str2)-2:]
print (str3)
Output : weol
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.
Output: 2
Syntax:
replace(“char1”, “char2”) It replaces all occurrences of char1 with char2.
Ex:
str1="How are you"
print (str1.replace("o", "e"))
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
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
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
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
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
Output:
Number 1: 34
Number 2: 54
The sum of 34 and 54 is 88
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 .
Output : Chennai
isalpha( ) if the string contains only letters , „python‟.isalpha( )
it will return true. Output: True
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
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
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
****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
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. *
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)
Tuple_Name=(E1,E2,E3,……..En)
Tuple_Name=E1,E2,E3,………En
Ex:
T= (10,20,30)
(or)
T= 10,20,30
Ex:
S1={ 10,'A',3.14 }
102
3 Marks: (Book Back Questions)
7. What are the difference between list and Tuples? *
o reverse
o key arguments are optional.
Ex:
x=[„A‟,‟B‟,‟C‟,‟D‟]
x.sort(reverse=True)
print(x)
Output: [„D‟,‟C‟,‟B‟,‟A‟]
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‟]
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=[ ]
Ex:
x=[10,20,30]
x.append(40)
print(x)
Output: [10,20,30,40]
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]
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:
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()
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: [ ]
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
Ex:
square = [ x ** 2 for x in range(1,5) ]
print (square)
Ex:
x= [10, 20, 30]
print(type(x))
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:
Output: 10
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:
109
26. Write a note on range() in list. Give example. *
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)
110
Ex: Output:
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”)
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‟)
tup = (10,)
type(tup)
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‟)
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
Output: 10 20 30
112
35. How to create tuples using tuple() function? Give example. *
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 *
Ex:
S={1,2,3,'A',3.14}
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. *
114
Syntax:
Dictionary Key must be unique case sensitive and valid Python type.
Ex:
d = { Regno: 101,
Name:‟Sairam‟,
Class:‟XII‟,
Mark:580}
Output: {1: 2, 2: 4, 3: 6, 4: 8}
115
Syntax:
dictionary_name [key] = value/element
Ex:
d = { 'Rno': '123', 'Name' : 'Sairam', 'Total' : 500}
d[„Class‟]=‟12‟
print(d)
Output: 10
Output: 75
116
47. What will be the output of the following python snippet?
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
118
55. What will be the output of the following python snippet?
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)
Tup1 = (2,4,6,8,10)
Tup2 = (1,3,5,7,9)
Tup3 = Tup1 + Tup2
print(Tup3)
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
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?
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?
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?
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
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
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
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)
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)
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)
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.
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)
Output: {'a': 97, 'b': 98, 'c': 99, 'd': 100, 'e': 101}
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()
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]
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))
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:
(1,2,3)
(4,5,6)
132
Additional 5 Marks Quesitons:
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)
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.
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
6) Insert() function
List.insert (position index, element)
135
9) Range() function in list
range (start value, end value, step value)
136
Unit III - Chapter 10. CLASSES AND OBJECTS
===============================================
2 Marks: (Book Back Questions)
1. What is class? *
2. What is instantiation? *
Syntax :
object_name = class_name ( )
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>
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
class Greeting:
def __init__(self, name):
self.__name = name
def display(self):
print("Good Morning ", self.__name)
obj=Greeting('BinduMadhavan')
obj.display()
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 :
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 :
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 the different between Private and Public member data in class? *
Private Public
141
15. What is the different between constructor and selector? *
3 syntax : syntax :
16. Write a note on public and private data members of python class.
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
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()
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
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
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
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
<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
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)
148
Unit IV - Chapter 11. DATABASE CONCEPTS
2 Marks: (Book Back Questions)
1. Mention few examples of a database.
Dbase
FoxPro
1. A child record has only one parent node A child record may have many parent nodes.
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)
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
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.
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.
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.
154
30. What are the 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.
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”.
156
1) Hierarchical Model:
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.
1 A 1 X
2 B 2 Y
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
student
4) ER model:
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
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.
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 : σ )
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
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
163
Ex:
Table A Table A
Studno Name Studno Name
cs1 Kannan cs1 Kannan
cs1 kannan cs3 Lenin
cs4 Padmaja cs1 Kannan
cs4 Padmaja cs3 Lenin
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.
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.
4. Which component of SQL lets insert values in tables and which lets to create a table?
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)
167
8. Write any three DDL commands.
Truncate Remove all records from a table. Also release the space occupied by
those records.
SAVEPOINT A;
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.
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
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.
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
Delete Deletes all records from a table, but not the space occupied by them.
27. What are the SQL commands which comes under the DCL?
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?
31. What are SQL commands which come under the DQL?
Ex:
USE stud;
33. Write the syntax for create a table.
172
34. Write the syntax for select statement.
Arguments They are the values given to make the clause complete.
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.
Ex:
DELETE FROM student WHERE admno=101;
Ex:
DELETE FROM student
;;
Syntax :
TRUNCATE TABLE Tablename;
Ex:
TRUNCATE 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.
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;
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᾿,);
Note : Non NULL values in a table can be listed using IS NOT NULL.
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;
Syntax : COMMIT;
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:
Ex:
UPDATE Student SET age = 20 WHERE Place = “Bangalore”;
UPDATE Student SET age=18, Place=„Chennai‟ WHERE admno=102;
Ex:
ALTER TABLE Student ADD Address char;
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;
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:
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:
2. Consider the following employee table. Write SQL commands for the qtns. (i) to (v).
(ii) To display all employees whose allowance is between 5000 and 7000.
181
(iv) To add a new row.
INSERT INTO employee (EMPCODE, NAME, DESIG, PAY, ALLOWANCE)
VALUES (C106, „Shan‟, Clerk‟, 10000,4500);
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.
Delete Deletes all records from a table, but not the space occupied by them.
183
Data Query Language:
It used to query or retrieve data from a database.
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:
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>]….
);
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:
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.
Ex:
DROP TABLE student;
185
TRUNCATE command:
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:
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;
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.
5. How will you sort more than one column from a csv file? Give an example statement. *
189
3 Marks: (Book Back Questions)
6. Write a note on open() function of python. What is the difference between the two methods?
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.
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.
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.
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.
Ex: Regno,Name,Total
101, Ram, 590
102, Sita, 595
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:
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.
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 .
1. open() function
2. with statement
26. In which application the CSV file have been used extensively.
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.
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.
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.
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.
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
list = [ ]
list.append(element)
Ex:
arrayvalue= []
arrayvalue.append(row)
sort() sorted()
195
40. Write a note on writer(). (or) Write a note on CSV.writer.
Syntax:
csv.writer(fileobject,delimiter,fmtparams)
43. What is line terminator? What are the default values for it?
196
44. What are the various CSV data formats available? (or)
What are the different ways of reading a CSV file using reader() method?
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.
CSV file having custom delimiter is read with the help of csv.register_dialect().
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).
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)
Output:
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.
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:
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.
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.
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.
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()
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()
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"
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
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()
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
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
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”.
208
CHAPTER-14 IMPORTING C++ PROGRAMS IN PYTHON
=========================================================
2 Marks: (Book Back Questions)
3. Takes large amount of time to analyze. Takes less amount of time to analyze.
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.
210
8. What is MinGW? What is its use? *
Welcome.display()
Answer:
Welcome . display()
Function name
Operator
Module name
Ex: main(sys.argv[1])
211
Explanation:
argv[1] contains c++ input file along with its path.
212
15. What are the options to importing / wrapping c++ into Python?
16. Why python is called as glue language? (or) What is „glue‟ language?
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
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.
import modulename
Syntax:
<module name> . <function name>
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
215
2. Explain each word of the following command. *
Answer:
-i input mode
C++ filename without cpp extension name of C++ file to be compiled and executed .
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:
variable_name1 Name of the C++ file without extension .cpp (string format).
variable_name2 Name of the executable file without extension .exe (string format)
„+‟ Indicates all strings are concatenated as a single string
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.
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= ‟])
#include <iostream>
using namespace std;
int main()
{
cout<<“WELCOME”;
return(0);
218
Program:
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.
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?
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
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()
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.
1. import sqlite3
2. connection=sqlite3.connect(“database name.db”)
3. cursor=connection.cursor()
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.
All the table data can be fetched in an object in the form of list of Tuples.
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)
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)
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)
DISTINCT
WHERE
GROUP BY
ORDER BY
HAVING
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)
The path of a file can be either represented as „/‟ or using „\\‟ in Python.
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")
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
Program Output
1) COUNT()
2) AVG()
3) SUM()
4) MAX()
5) MIN()
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)
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT AVG(AVERAGE) FROM student ")
result = cursor.fetchall()
print(result)
Ex:
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT SUM(AVERAGE) FROM student ")
result = cursor.fetchall()
print(result)
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)
229
5 Marks: (Book Back Questions)
1. Write in brief about SQLite and the steps used to use it.
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"
230
2. Write the Python script to display all the records of the following table using fetchmany()
PROGRAM Output
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 :
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.
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:
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:
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)
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():
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT AVG(AVERAGE) FROM student ")
result = cursor.fetchall()
print(result)
SUM():
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)]
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
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?
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] )
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.
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()
242
11. What is infographics?
infographic information graphic.
An infographic is the representation of information in a graphic format.
243
17. What is Pie chart?
244
21. What is the output of the following code?
Output :
245
plt.ylabel ("Total Population")
plt.show( )
Output :
Answer:
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
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 :
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 :
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 :
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 :
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 :
249
plt.legend( ) invoke the default legend with plt.legend( ).
Calling legend( ) with no arguments automatically fetches the legend
handle and their associated labels.
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
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
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
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
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()
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
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