0% found this document useful (0 votes)
28 views152 pages

Computer Science Functions Study Guide

The document provides comprehensive study material on computer science topics, specifically focusing on functions, data abstraction, and their characteristics. It explains concepts such as subroutines, pure and impure functions, and the distinction between interface and implementation. Additionally, it covers abstract data types, constructors, and selectors, along with examples and definitions relevant to programming languages.

Uploaded by

KN AISHWARYA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views152 pages

Computer Science Functions Study Guide

The document provides comprehensive study material on computer science topics, specifically focusing on functions, data abstraction, and their characteristics. It explains concepts such as subroutines, pure and impure functions, and the distinction between interface and implementation. Additionally, it covers abstract data types, constructors, and selectors, along with examples and definitions relevant to programming languages.

Uploaded by

KN AISHWARYA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Std 12

Computer Science

Chapters 1 to 16
Study Material

1
Chapter 1 - Function

2
PART-II
1. What is a subroutine?

• Subroutines are the basic building blocks of computer programs.


• Subroutines are small sections of code that are used to perform a particular task that can be used
repeatedly.
• In Programming languages these subroutines are called as Functions.
2. Define Function with respect to Programming language.

• A function is a unit of code that is often defined within a greater code structure.
• Specifically, a function contains a set of code that works on many kinds of inputs, like variants,
expressions and produces a concrete output.
3. Write the inference you get from X:=(78).

• It is a function definition.
• The value 78 bound to the name ‘X'.
4. Differentiate interface and implementation.

• In object-oriented programs classes are the interface and how the object is processed and
executed is the implementation.
5. Which of the following is a normal function definition and recursive function definition
i) let sum x y:
return x + y (i) Normal Function

ii) let disp :


print ‘welcome’ (ii) Normal Function

iii) let rec sum num:


if (num!=0) then return num + sum (num-1) (iii) Recursive Function
else
return num
3
6. Define recursive function.

• A function definition which calls itself is called recursive function.


PART - III
1. Mention the characteristics of Interface.
• The class template specifies the interfaces to enable an object to be created and operated
properly.
• An object's attributes and behaviour is controlled by sending functions to the object.
2. Why strlen is called pure function?

• Pure functions are functions which will give exact result when the same arguments are passed.
• strlen is a pure function because the function takes one variable as a parameter, and accesses it
to find its length.
• This function reads external memory but does not change it, and the value returned derives from
the external memory accessed.
3. What is the side effect of impure function. Give example.

• The variables used inside the function may cause side effects though the functions which are not
passed with any arguments. In such cases the function is called impure function.
• When a function depends on variables or functions outside of its definition block, you can never
be sure that the function will behave the same every time it’s called.
• Example: random( ) function will give different outputs for the same function call.
4. Differentiate pure and impure function.

PURE FUNCTION IMPURE FUNCTION

• The return value of the pure functions solely • The return value of the impure functions does
depends on its arguments passed. not solely depend on its arguments passed.
• Hence, if you call the pure functions with the • Hence, if you call the impure functions with the
same set of arguments, you will always get the same set of arguments, you might get the
same return values. different return values.
• For example: strlen(),sqrt(), sin( ) • For example: random (), Date ().
• They do not have any side effects. • They have side effects.
• They do not modify the arguments which are • They may modify the arguments which are
passed to them. passed to them.

4
Additional Questions: 2 or 3 marks
[Link] Definitions.

• Definitions bind values to names.


• Definitions are not expressions, at the same time expressions are also not treated as definitions.
• Definitions are distinct syntactic blocks.
• Definitions can have expressions nested inside them, and vice-versa.
[Link] the Syntax for Function Definition.

• Syntax: The syntax for function definitions:


Here the ‘fn’ is a variable indicating an identifier being used as a
function name.

• The names ‘a1’ to ‘an’ are variables indicating the identifiers used as parameters.
• The keyword ‘rec’ is required if ‘fn’ is to be a recursive function; otherwise, it may be omitted.
7. What happens if you modify a variable outside the function? Give an example.

• A function has side effects when it has observable interaction with the outside world.
• There are situations our functions can become impure though our goal is to make our functions
pure.
• side effect is not a necessary bad thing. Sometimes they are useful (especially outside functional
programming paradigm).
• One of the most popular groups of side effects is modifying the variable outside of function.
• For example

PART-IV
1. What are called Parameters and write a note on
(i) Parameter without Type (ii) Parameter with Type

• Parameters are the variables in a function definition and arguments are the values which are
passed to a function definition.
1. Parameter without Type

• Let us see an example of a function definition:

5
• The precondition (requires) and postcondition (returns) of the function is given.
• In the above function definition variable ‘b’ is the parameter and the value which is passed to the
variable ‘b’ is the argument.
• In the above function definition, since the if expression returns 1 in the then branch, according to
the typing rule, the entire if expression has type int and the function's return type is also ‘int’.
• ‘b’ is compared to 0 with the equality operator, so ‘b’ is also a type of ‘int’.
• Since ‘a’ is multiplied with another expression using the * operator, ‘a’ must be an int.
2. Parameter with Type

• Now let us write the same function definition with type mentioned :

• When we write the type annotations for ‘a’ and ‘b’ the parentheses are mandatory.
• This is useful on times when you get a type error from the compiler that doesn't make sense.
• Explicitly annotating the types can help with debugging such an error message.

• If you want to define a recursive function:


• Use “let rec” instead of “let”.
• Syntax: The syntax for function definitions:

• Here the ‘fn’ is a variable indicating an identifier being used as a function name.
• The names ‘a1’ to ‘an’ are variables indicating the identifiers used as parameters.
• The keyword ‘rec’ is required if ‘fn’ is to be a recursive function; otherwise, it may be omitted.

6
2. Identify in the following program

i) Name of the function (i) gcd


ii) Identify the statement which tells it is a recursive function (ii) let rec gcd a b
iii) Name of the argument variable (iii) a,b
iv) Statement which invoke the function recursively (iv) gcd b (a mod b)
v) Statement which terminates the recursion (v) return a
3. Explain with example Pure and impure functions.
Pure Function:-
• Pure functions are functions which will give exact result when the same arguments are passed.
• The return value of the pure functions solely depends on its arguments passed.
• Hence, if you call the pure functions with the same set of arguments, you will always get the same return
values.
• They do not modify the arguments which are passed to them.
• They do not have any side effects.
• Examples: strlen( ) , sqrt ( ), sin( )

Impure Function:-
• The variables used inside the function may cause side effects though the functions which are not passed
with any arguments. In such cases the function is called impure function.
• The return value of the impure functions does not solely depend on its arguments passed.
• Hence, if you call the impure functions with the same set of arguments, you might get the different return
values.
• They may modify the arguments which are passed to them.
• They have side effects.
• Examples: random (),Date (). let a:= random( )

4. Explain with an example interface and implementation.


Interface:-
• An interface is a set of action that an object can do.
• For example, when you press a light switch, the light goes on, you may not have cared how it splashed the
light.
7
• In Object Oriented Programming language, an Interface is a description of all functions that a class must
have in order to be a new interface.
• In our example, anything that "ACTS LIKE" a light, should have function definitions like turn_on () and a
turn_off (). The purpose of interface is to allow the computer to enforce the properties of the class.

Implementation:-
• Implementation 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.
• Example:

• The person who drives the car doesn't care about the internal working. To increase the speed of the car he
just presses the accelerator to get the desired behaviour.
• Here the accelerator is the interface between the driver (the calling / invoking object) and the engine (the
called object).
• In this case, the function call would be Speed (70): This is the interface.
• Internally, the engine of the car is doing all the things. It's where fuel, air, pressure, 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.

Hands on Practice:
1. Write algorithmic function definition to find the minimum among 3 numbers.
let min x y z :=
if x < y then
if x < z then x else z
else
if y < z then y else z
2. Write algorithmic recursive function definition to find the sum of n natural numbers.
let rec sum n:=
if (n != 0) then
return n + sum (n - 1)
else
return n

8
Chapter 2 – Data Abstraction

9
PART-II
1. What is abstract data type?

• Abstract Data type (ADT) is a type (or class) for objects whose behaviour is defined by a set of
value and a set of operations.
• The definition of ADT only mentions what operations are to be performed but not how these
operations will be implemented.
2. Differentiate constructors and selectors.
Constructors Selectors
Constructors are functions that build Selectors are functions that retrieve
the abstract data type. information from the data type.
Constructors create an object, bundling Selectors extract individual pieces of
together different pieces of information. information from the object.

3. What is a Pair? Give an example.

• Any way of bundling two values together into one can be


considered as a pair.
• Lists are a common method to do so. Therefore, List can
be called as Pairs.
4. What is a List? Give an example.

• List is constructed by placing expressions within square brackets separated by commas. Such an
expression is called a list literal.
• Example: num := [10, 20]
x, y:= num
5. What is a Tuple? Give an example.

• A tuple is a comma-separated sequence of values surrounded with parentheses.


• Tuple is similar to a list. The difference between the two is that you cannot change the elements of
a tuple once it is assigned whereas in a list, elements can be changed.
• Example colour= ('red', 'blue', 'Green')
Additional Questions:
[Link] Abstraction.

• The process of providing only the essentials and hiding the details is known as abstraction.
[Link] the different ways to implement ADT.

10
• There can be different ways to implement an ADT, the List ADT can be implemented using singly
linked list or doubly linked list.
• Similarly, stack ADT and Queue ADT can be implemented using lists.
[Link] of rational numbers.

PART - III
1. Differentiate Concrete data type and abstract datatype.
Concrete data type Abstract data type
Concrete data types or structures (CDT's) are Abstract Data Types (ADT's) offer a high-level view
direct implementations of a relatively simple (and use) of a concept independent of its
concept. implementation.

A concrete data type is a data type whose An abstract data type the representation of a data
representation is known type is unknown

2. Which strategy is used for program designing? Define that Strategy.

• A powerful strategy for designing programs: 'wishful thinking'.


• Wishful Thinking is the formation of beliefs and making decisions according to what might be
pleasing to imagine instead of by appealing to reality.
3. Identify Which of the following are constructors and selectors?
(a) N1=number( )
(b) accetnum(n1)
(c) displaynum(n1)
(d) eval(a/b)
(e) x,y= makeslope (m), makeslope(n)
(f) display()
• (a) Constructors
• (b) Selectors
• (c) Selectors
11
• (d) Selectors
• (e) Constructors
• (f) Selectors

4. What are the different ways to access the elements of a list. Give example.

• The elements of a list can be accessed in two ways.


• The first way is via our familiar method of multiple assignment, which unpacks a list into its
elements and binds each element to a different name.
• lst := [10, 20]
• x, y := lst
• In the above example x will become10 and y will become 20.
• A second method for accessing the elements in a list is by the element selection
• operator, also expressed using square brackets. Unlike a list literal, a square-brackets expression
directly following another expression does not evaluate to a list value, but instead selects an
element from the value of the preceding expression.
• lst[0]
10
lst[1]
20
5. Identify Which of the following are List, Tuple and class?
(a) arr [1, 2, 34]
(b) arr (1, 2, 34)
(c) student [rno, name, mark]
(d) day= (‘sun’, ‘mon’, ‘tue’, ‘wed’)
(e) x= [2, 5, 6.5, [5, 6], 8.2]
(f) employee [eno, ename, esal, eaddress]
• (a) List
• (b) Tuple
• (c) Class
• (d) Tuple
• (e) List
• (f) Class
PART - IV
1. How will you facilitate data abstraction. Explain it with suitable example

• To facilitate data abstraction, you will need to create two types of functions: constructors and
selectors.
12
• Constructors are functions that build the abstract data type. Selectors are functions that retrieve
information from the data type.
• For example, say you have an abstract data type called city. This city object will hold the city’s
name, and its latitude and longitude. To create a city object, you’d use a function like
city = makecity (name, lat, lon)
• To extract the information of a city object, you would use functions like
• getname(city)
• getlat(city)
• getlon(city)
• The function which creates the object of the city is the constructor.
city = makecity (name, lat, lon)
• Here makecity (name, lat, lon) is the constructor which creates the object city.

• Selectors are nothing but the functions that retrieve information from the data type. Therefore, in
the above code
• getname(city)
• getlat(city)
• getlon(city)
are the selectors because these functions extract the information of the city object

2. What is a List? Why List can be called as Pairs. Explain with suitable example

• List is constructed by placing expressions within square brackets separated by commas.


• Such an expression is called a list literal. List can store multiple values. Each value can be of any
type and can even be another list.
13
• Example for List is [10, 20].
• The elements of a list can be accessed in two ways. The first way is via our familiar
• method of multiple assignment, which unpacks a list into its elements and binds each element to
a different name.
lst := [10, 20]
x, y := lst
• In the above example x will become10 and y will become 20.
• A second method for accessing the elements in a list is by the element selection
• operator, also expressed using square brackets. Unlike a list literal, a square- brackets expression
directly following
• another expression does not evaluate to a list value, but instead selects an element from the value
of the preceding expression.
lst [0]
10
lst [1]
20
• In both the example mentioned above mathematically we can represent list similar to a set.
lst [(0, 10), (1, 20)] – where

• Any way of bundling two values together into one can be considered as a pair.
• Lists are a common method to do so. Therefore, List can be called as Pairs.

3. How will you access the multi-item. Explain with example.

• In the case of something more complex, like a person, we have a multi- item object where each
'item' is a named thing: the firstName, the lastName, the id, and the email.
• One could use a list to represent a person:
person= ['Padmashri', 'Baskar', '994-222-1234', 'compsci@[Link]']

14
• In this example Person is referred to as a class or a type, while p1 is referred to as an object or an
instance.
• Therefore, we can define a class as bundled data and the functions that work on that data.

15
Chapter 3 – Scoping

16
PART-II

1. What is a scope?

• Scope refers to the accessibility of variables, with in one part of a program to another part of the same
program.

2. Why scope should be used for variable. State the reason.

• Variables addresses to an object in memory.


• When you assign a variable with := to an instance (object), you're binding (or mapping) the variable to
that instance.
• Multiple variables can be mapped to the same instance.

3. What is Mapping?

• The process of binding a variable name with an object is called mapping.


• = (equal to sign) is used in programming languages to map the variable and object.

4. What do you mean by Namespaces?

• Namespaces are containers for mapping names of variables to objects.


• Eg: a:=5
• In the following example, a is first mapped to the integer 5. In this case, a is the variable name, while
the integer value 5 is the object.

5. How Python represents the private and protected Access specifiers?

• Python prescribes a convention of prefixing the name of the variable or method with single or double
underscore to emulate the behaviour of protected and private access specifiers.

Additional Questions:

6. Define a module.

• A module is a part of a program.


• Programs are composed of one or more independently developed modules.
• The examples of modules are procedures, subroutines, and functions.

7. Define modular programming.

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

17
PART – III
1. Define Local scope with an example.

• Local scope refers to variables defined in current function. Always, a function will first look up for
a variable name in its local scope.
• Only if it does not find it there, the outer scopes are checked.
• Example:

• On execution of the above code the variable a displays the value 7, because it is defined and
available in the local scope.
2. Define Global scope with an example.

• A variable which is declared outside of all the functions in a program is known as global variable.
• This means, global variable can be accessed inside or outside of all the functions in a program.
• Example:

• On execution of the above code the variable a which is defined inside the function displays the
value 7 for the function call Disp() and then it displays 10, because a is defined in global scope.
3. Define Enclosed scope with an example.

• All programming languages permit functions to be nested. A function (method) with in another
function is called nested function.

18
• A variable which is declared inside a function which contains another function definition with in it,
the inner function can also
access the variable of the outer
function. This scope is called
enclosed scope.

• In the above example Disp1() is defined with in Disp(). The variable ‘a’ defined in Disp() can be even
used by Disp1() because it is also a member of Disp().
4. Why access control is required?

• Access control is a security technique that regulates who or what can view or use
resources in a computing environment.
• It is a fundamental concept in security that minimizes risk to the object.
• In other words access control is a selective restriction of access to data. IN Object oriented
programming languages it is implemented through access modifiers.
5. Identify the scope of the variables in the following pseudo code and write its
Output

19
PART-IV
[Link] the types of scopes for variable or LEGB rule with example.

• The LEGB rule is used to decide the order in which the scopes are to be searched
for scope resolution. The scopes are listed below in terms of hierarchy (highest to lowest).

Local Scope:
• Local scope refers to variables defined in current function. Always, a function will first look up for
a variable name in its local scope.
• Only if it does not find it there, the outer scopes are checked.
• Look at this example

• On execution of the above code the variable a displays the value 7, because it is defined and
available in the local scope.

Global Scope:
• A variable which is declared outside of all the functions in a program is known as global variable.
20
• This means, global variable can be accessed inside or outside of all the functions in a program.
• Consider the following example

• On execution of the above code the variable a which is defined inside the function displays the
value 7 for the function call Disp() and then it displays 10, because a is defined in global scope.

Enclosed Scope:
• All programming languages permit functions to be nested. A function (method) with in another
function is called nested function.
• A variable which is declared inside a function which contains another function definition with in it,
the inner function can also access the variable of the outer function.
• This scope is called enclosed scope.

• In the above example Disp1() is defined with in Disp(). The variable ‘a’ defined in Disp() can be even
used by Disp1() because it is also a member of Disp().

Built-in Scope:
• The built-in scope has all the names that are pre-loaded into the program scope when we start the
compiler or interpreter.
• Any variable or function which is defined in the modules of a programming language has Built-in or
module scope.

21
• They are loaded as soon as the library files are imported to the program.

2. Write any Five Characteristics of Modules.


The following are the desirable characteristics of a module.
1. Modules contain instructions, processing logic, and data.
2. Modules can be separately compiled and stored in a library.
3. Modules can be included in a program.
4. Module segments can be used by invoking a name and some parameters.
5. Module segments can be used by other modules.

3. Write any five benefits in using modular programming.


• Less code to be written.
• A single procedure can be developed for reuse, eliminating the need to retype the code many
times.
• Programs can be designed more easily because a small team deals with only a small part of the
entire code.
• Modular programming allows many programmers to collaborate on the same application.
• The code is stored across multiple files.
• Code is short, simple and easy to understand.
• Errors can easily be identified, as they are localized to a subroutine or function.
• The same code can be used in many applications.
• The scoping of variables can easily be controlled.

22
Chapter 4 – Algorithmic Strategies

23
PART-II
1. What is an Algorithm?

• An algorithm is a finite set of instructions to accomplish a particular task.


• It is a step-by-step procedure for solving a given problem.
• An algorithm can be implemented in any suitable programming language.
2. Write the phases of performance evaluation of an algorithm.
Analysis of algorithms and performance evaluation can be divided into two different phases:

• A Priori estimates: This is a theoretical performance analysis of an algorithm. Efficiency of an


algorithm is measured by assuming the external factors. (Asymptotic notations used)
• A Posteriori testing: This is called performance measurement. In this analysis, actual statistics
like running time and required for the algorithm executions are collected. (Not preferred in the
industry)
3. What is Insertion sort?

• Insertion sort is a simple sorting algorithm.


• It works by taking elements from the list one by one and inserting then in their correct position in
to a new sorted list.
• This algorithm builds the final sorted array at the end.
4. What is Sorting?

• Sorting is a method of arranging group of items in ascending or descending order.


• Various sorting techniques in algorithm are Bubble sort, Heap sort, Selection sort and Insertion
sort.
5. What is searching? Write its types.

• A searching algorithm is the step-by-step procedure used to locate specific data among a
collection of data.
• There are 2 types of searching, they are: (i) Linear search (ii) Binary search
Additional Questions:
6. Define algorithmic solution.

• An algorithm that yields expected output for a valid input is called an algorithmic solution.
7. Define algorithmic analysis.

24
• An estimation of the time and space complexities of an algorithm for varying input sizes is called
algorithm analysis.
8. Define algorithmic strategy.

• A way of designing algorithm is called algorithmic strategy.


9. Define memoization.

• Memoization or memoisation is an optimization technique used primarily to speed up computer


programs by storing the results of previous function calls and returning the cached result when the
same inputs occur again.
10. Write the different factors in which the time efficiency of an algorithm is measured.
The execution time that you measure in this case would depend on a number of factors such as:
• Speed of the machine
• Compiler and other system Software tools
• Operating System
• Programming language used
• Volume of data required
PART - III
1. List the characteristics of an algorithm.

• Input
• Output
• Finiteness
• Definiteness
• Effectiveness
• Correctness
• Simplicity
• Unambiguous
• Feasibility
• Portable
• Independent

2. Discuss about Algorithmic complexity and its types.

• 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.
• Time Complexity:
The Time complexity of an algorithm is given by the number of steps taken by the algorithm to
complete the process.

25
• Space Complexity:
Space complexity of an algorithm is the amount of memory required to run to its completion. The
space required by an algorithm is equal to the sum of the following two components: fixed part
and variable part.
3. What are the factors that influence time and space complexity.

• Time Factor -Time is measured by counting the number of key operations like comparisons in the
sorting algorithm.
• Space Factor - Space is measured by the maximum memory space required by the algorithm.
4. Write a note on Asymptotic notation.

• Asymptotic Notations are languages that uses meaningful statements about time and space
complexity.
• The following three asymptotic notations are mostly used to represent time complexity of
algorithms:
• (i) Big O:
Big O is often used to describe the worst-case (upper bound) of an algorithm.
• (ii) Big Ω :
Big Omega is the reverse Big O, if Bi O is used to describe the upper bound (worst - case) of a
asymptotic function, Big Omega is used to describe the lower bound (best-case).
• (iii) Big Θ :
When an algorithm has a complexity with lower bound = upper bound, say that an algorithm has a
complexity O (n log n) and Ω (n log n), it’s actually has the complexity Θ (n log n), which means the
running time of that algorithm always falls in n log n in the best-case and worst-case.
5. What do you understand by Dynamic programming?

• Dynamic programming is an algorithmic design method that can be used when the solution to a
problem can be viewed as the result of a sequence of decisions.
• Dynamic programming approach is similar to divide and conquer.
• The given problem is divided into smaller and yet smaller possible sub-problems.

• Dynamic programming is used whenever problems can be divided into similar sub-problems, so
that their results can be re-used to complete the process.
• Dynamic programming approaches are used to find the solution in optimized way.
• For every inner sub problem, dynamic algorithm will try to check the results of the previously
solved sub-problems.
• The solutions of overlapped sub-problems are combined in order to get the better solution.

26
6. Design an algorithm to find the square of a given number.

• Step 1 – start the process


• Step 2 – get the input x
• Step 3 –calculate the square by multiplying the input value ie., square ← x* x
• Step 4 − display the result square
• Step 5 – stop
7. Differentiate algorithm and program.

PART - IV
1. Explain the characteristics of an algorithm.

• Input - Zero or more quantities to be supplied.


• Output - At least one quantity is produced.
• Finiteness - Algorithms must terminate after finite number of steps.
• Definiteness - All operations should be well defined. For example operations involving division by
zero or taking square root for negative number are unacceptable.
• Effectiveness - Every instruction must be carried out effectively.
27
• Correctness - The algorithms should be error free.
• Simplicity - Easy to implement
• Unambiguous - Algorithm should be clear and unambiguous. Each of its steps and their
inputs/outputs should be clear and must lead to only one meaning.
• Feasibility - Should be feasible with the available resources.
• Portable - An algorithm should be generic, independent of any programming language or an
operating system able to handle all range of inputs.
• Independent - An algorithm should have step-by-step directions, which should be independent of
any programming code.

2. Discuss about Linear search algorithm.

• Linear search also called sequential search is a sequential method for finding a particular value in
a list.
• This method checks the search element with each element in sequence until the desired element
is found or the list is exhausted.
• In this searching algorithm, list need not be ordered.
• Procedure
1. Traverse the array using for loop
2. In every iteration, compare the target search key value with the current value of the list.
• If the values match, display the current index and value of the array
• If the values do not match, move on to the next array element.
3. If no match is found, display the search element not found.
• To search the number 25 in the array given below, linear search will go step by step in a sequential
order starting from the first element in the given array if the search element is found that index is
returned otherwise the search is continued till the last index of the array.
• In this example number 25 is found at index number 3.

28
3. What is Binary search? Discuss with example.

• Binary search also called half-interval search algorithm.


• It finds the position of a search element within a sorted array.
• The binary search algorithm can be done as divide-and-conquer search algorithm and executes in
logarithmic time.

Procedure for Binary search:

1. Start with the middle element:


• If the search element is equal to the middle element of the array i.e., the middle value =
number of elements in array/2, then return the index of the middle element.
• If not, then compare the middle element with the search value,
• If the search element is greater than the number in the middle index, then select the
elements to the right side of the middle index, and go to Step-1.
• If the search element is less than the number in the middle index, then select the elements
to the left side of the middle index, and start with Step-1.
2. When a match is found, display success message with the index of the element matched.
3. If no match is found for all comparisons, then display unsuccessful message.

Example: Let us assume that the search element is 60 and we need to search the location or index of
search element 60 using binary search.

29
30
4. Explain the Bubble sort algorithm with example.

• Bubble sort is a simple sorting algorithm.


• The algorithm starts at the beginning of the list of values stored in an array. It compares each pair
of adjacent elements and swaps them if they are in the unsorted order. This comparison and
passed to be continued until no swaps are needed, which indicates that the list of values stored in
an array is sorted. The algorithm is a comparison sort, is named for the way smaller elements
"bubble" to the top of the list. Although the algorithm is simple, it is too slow and less efficient
when compared to insertion sort and other sorting methods.
• Assume list is an array of n elements. The swap function swaps the values of the given array
elements.
Procedure
1. Start with the first element i.e., index = 0, compare the current element with the next element of
the array.
2. If the current element is greater than the next element of the array, swap them.
3. If the current element is less than the next or right side of the element, move to the next
element. Go to Step 1 and repeat until end of the index is reached.
Let's consider an array with values {15, 11, 16, 12, 14, 13} Below, we have a pictorial representation of
how bubble sort will sort the given array

The above pictorial example is for iteration-1. Similarly, remaining iteration can be done. The final iteration
will give the sorted array. At the end of all the iterations we will get the sorted values in an array as given
below:

31
5. Explain the concept of Dynamic programming with suitable example.

• Dynamic programming is an algorithmic design method that can be used when the solution to a
problem can be viewed as the result of a sequence of decisions.
• Dynamic programming approach is similar to divide and conquer.
• The given problem is divided into smaller and yet smaller possible sub-problems.

• Dynamic programming is used whenever problems can be divided into similar sub-problems, so
that their results can be re-used to complete the process.
• Dynamic programming approaches are used to find the solution in optimized way.
• For every inner sub problem, dynamic algorithm will try to check the results of the previously
solved sub-problems.
• The solutions of overlapped sub-problems are combined in order to get the better solution.
Steps to do Dynamic programming :
• The given problem will be divided into smaller overlapping sub-problems.
• An optimum solution for the given problem can be achieved by using result of smaller sub-
problem.
• Dynamic algorithms uses Memoization.
Fibonacci Series – An example

• Fibonacci series generates the subsequent number by adding two previous numbers.
• The initial values of Fib 0 & Fib 1 can be taken as 0 and 1.
• Fibonacci series satisfies the following conditions: Fib n = Fibn-1 + Fibn-2
Fibonacci Series - Iterative Algorithm with Dynamic programming approach:
Initialize f0=0, f1 =1
step-1: Print the initial values of Fibonacci f0 and f1
step-2: Calculate Fibonacci fib ← f0 + f1
step-3: Assign f0← f1, f1← fib
step-4: Print the next consecutive value of Fibonacci fib.
step-5: Goto step-2 and repeat until the specified number of terms generated.
Hence, a Fibonacci series for the value n = 8 can look like this:
Fib8 = 0 1 1 2 3 5 8 13

Additional Questions:
6. Explain the selection sort algorithm with example. Refer Pg nos: 39,40
7. Explain the insertion sort with example. Refer Pg nos: 40,41

32
Chapter 5 – Python – Variables and Operators

33
PART - II
1. What are the different modes that can be used to test Python Program?
• In Python, programs can be written in two ways namely Interactive mode and Script mode.
• The Interactive mode allows us to write codes in Python command prompt (>>>) whereas in script
mode programs can be written and stored as separate file with the extension .py and executed.
• Script mode is used to create and edit python source file
2. Write short notes on Tokens.
• Python breaks each logical line into a sequence of elementary lexical components known as
Tokens.
• The normal token types are:-
1) Identifiers,
2) Keywords,
3) Operators,
4) Delimiters and
5) Literals.
Whitespace separation is necessary between tokens.
3. What are the different operators that can be used in Python ?
• In computer programming languages operators are special symbols which represent
computations, conditional matching etc.
• The value of an operator used is called operands.
• Operators are categorized as:
o Arithmetic (+, -, *, /, %, **, //)
o Relational or Comparative (< , > , <= , >=, ==, !=)
o Logical (and, or, not)
o Assignment (+=, -=, *=, /=, %=, **=, //=)
o Conditional, etc.
4. What is a literal? Explain the types of literals?
• Literal is a raw data given to a variable or constant. In Python, there are various types of literals.
1) Numeric - Numeric Literals consists of digits and are immutable (unchangeable). Numeric
literals can belong to 3 different numerical types Integer, Float and Complex
2) String - In Python a string literal is a sequence of characters surrounded by quotes. Python
supports single, double and triple quotes for a string.
3) Boolean - A Boolean literal can have any of the two values: True or False.

34
5. Write short notes on Exponent data?
• An Exponent data contains decimal digit part, decimal point, exponent part followed by one or
more digits.

Additional Questions:
6. Write a note on interactive mode programming.
• In interactive mode Python code can be directly typed and the interpreter displays the result(s)
immediately.
• The interactive mode can also be used as a simple calculator.
7. How will you invoke Python IDLE?
The following command can be used to invoke Python IDLE from Window OS.
Start → All Programs → Python 3.x → IDLE (Python 3.x)
(Or)
Click python Icon on the Desktop if available.

PART - III
1. Write short notes on Arithmetic operator with examples.
• An arithmetic operator is a mathematical operator that takes two operands and performs a
calculation on them.
• They are used for simple arithmetic.

35
2. What are the assignment operators that can be used in Python?

• In Python, = is a simple assignment operator to assign values to variable.


• Let a = 5 and b = 10 assigns the value 5 to a and 10 to b these two assignment statement can also
be given as a,b=5,10 that assigns the value 5 and 10 on the right to the variables a and b
respectively.
• There are various compound operators in Python like +=, -=, *=, /=, %=, **= and //= are also
available.
3. Explain Ternary operator with examples.

• Ternary operator is also known as conditional operator that evaluate something based on a
condition being true or false.
• It simply allows testing a condition in a single line replacing the multiline if-else making the code
compact.
• Syntax:
Variable Name = [on_true] if [Test expression] else [on_false]
• Examples : min= 49 if 49 < 50 else 49 # min = 49
min= 50 if 49 > 50 else 49 # min = 49
4. Write short notes on Escape sequences with examples.

• In Python strings, the backslash "\" is a special character, also


called the "escape" character.
• It is used in representing certain whitespace characters: "\t" is a
tab, "\n" is a newline, and "\r" is a carriage return.
• For example to print the message "It's raining", the Python
command is
>>> print ("It\'s rainning")
It's raining
5. What are string literals? Explain.

• In Python a string literal is a sequence of characters surrounded by quotes.


• Python supports single, double and triple quotes for a string.
• A character literal is a single character surrounded by single or double quotes.
• The value with triple-quote "' '" is used to give multiline string literal.
• A Character literal is also considered as string literal in Python.

36
Additional Questions:
6. List the key features of python.

• It is a general-purpose programming language which can be used for both scientific and non-
scientific programming.
• It is a platform independent programming language.
• The programs written in Python are easily readable and understandable.
7. Write a note on comments in python.

• In Python, comments begin with hash symbol (#).


• The lines that begins with # are considered as comments and ignored by the Python interpreter.
• Comments may be single line or no multi-lines.
• The multiline comments should be enclosed within a set of ''' '''(triple quotes).
• Examples:
# It is Single line Comment
''' It is multiline comment which contains more than one line '''
8. Write a note on indentation.

• Python uses whitespace such as spaces and tabs to define program blocks whereas other
languages like C, C++, java use curly braces { } to indicate blocks of codes.
• The number of whitespaces (spaces and tabs) in the indentation is not fixed, but all statements
within the block must be indented.
• Typical amount of indentation for Python is four spaces.

37
PART – IV
1. Describe in detail the procedure Script mode programming.

• A script is a text file containing the Python statements. Python Scripts are reusable code.
• Once the script is created, it can be executed again and again without retyping.
• The Scripts are editable.

(i) Creating Scripts in Python:


1. Choose File → New File or press Ctrl + N in Python shell window.
2. An untitled blank script text editor will be displayed on screen as shown
3. Type the following code in Script editor
a =100
b = 350
c = a+b
print ("The Sum=", c)

(ii) Saving Python Script :


(1) Choose File → Save or Press Ctrl + S
(2) Now, Save As dialog box appears on the screen as shown
(3) In the Save As dialog box, select the location where you want to save your Python code, and type
the file name in File Name box. Python files are by default saved with extension .py. Thus, while
creating Python scripts using Python Script editor, no need to specify the file extension.
(4) Finally, click Save button to save your Python script.

(iii) Executing Python Script:


(1) Choose Run → Run Module or Press F5
(2) If your code has any error, it will be shown in red color in the IDLE window, and Python describes
the type of error occurred. To correct the errors, go back to Script editor, make corrections, save the
file using Ctrl + S or File → Save and execute it again.

2. Explain input() and print() functions with examples.

• A program needs to interact with the user to accomplish the desired task; this can be achieved
using Input-Output functions.
• The input() function helps to enter data at run time by the user and the output function print() is
used to display the result of the program on the screen after execution.

print( ) function:-
• In Python, the print() function is used to display result on the screen.

38
• Syntax:

• Example:

• The print ( ) evaluates the expression before printing it on the monitor.


• The print () displays an entire statement which is specified within print ( ). Comma ( , ) is used as a
separator in print ( ) to print more than one item.
input( ) function:

• In Python, input( ) function is used to accept data as input at run time.


• Syntax:
Variable = input (“prompt string”)
• where, prompt string in the syntax is a statement or message to the user, to know what input
can be given.

39
• The input ( ) accepts all data as string but not as numbers.
• If a numerical value is entered, the input values should be explicitly converted into numeric data
type.
• The int( ) function is used to convert string data as integer data explicitly.

3. Discuss in detail about Tokens in Python.


• Python breaks each logical line into a sequence of elementary lexical components known as
Tokens.
• The normal token types are:-
1) Identifiers,
2) Keywords,
3) Operators,
4) Delimiters and
5) Literals.
Whitespace separation is necessary between tokens.
Identifiers:

• An Identifier is a name used to identify a variable, function, class, module or object.


• An identifier must start with an alphabet (A..Z and a..z) or underscore ( _ ).
• Identifiers may contain digits (0 .. 9)
• Python identifiers are case sensitive i.e. uppercase and lowercase letters are distinct.
• Identifiers must not be a python keyword.
• Python does not allow punctuation character such as %,$, @ etc., within identifiers.
• Example of valid identifiers: Sum, total_marks, regno, num1
• Example of invalid identifiers: 12Name, name$, total-mark, continue.
Keywords:
• Keywords are special words used by Python interpreter to recognize the structure of program.
• As these words have specific meaning for interpreter, they cannot be used for any other purpose.
• Examples: if, elif, else, def, del, in, lambda, continue.
40
Operators:
• In computer programming languages operators are special symbols which represent
computations, conditional matching etc.
• The value of an operator used is called operands.
• Operators are categorized as:
o Arithmetic (+, -, *, /, %, **, //)
o Relational or Comparative (< , > , <= , >=, ==, !=)
o Logical (and, or, not)
o Assignment (+=, -=, *=, /=, %=, **=, //=)
o Conditional, etc.
Delimiters :
• Delimiters are sequence of one or more characters 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 in expressions, lists, dictionaries
and strings.
• Following are the delimiters:

Literals:
• Literal is a raw data given to a variable or constant.
• In Python, there are various types of literals.
1) Numeric
2) String
3) Boolean
Additional Questions:
4. Explain python datatypes.

• All data values in Python are objects and each object or value has type.
• Python has Built-in or Fundamental data types such as Number, String, Boolean, tuples, lists, sets
and dictionaries etc.
Number Data type:

• The built-in number objects in Python supports integers, floating point numbers and complex
numbers.
• Integer Data can be decimal, octal or hexadecimal.
• Octal integer use digit 0 (Zero) followed by letter 'o' to denote octal digits.

41
• Hexadecimal integer use 0X (Zero and either uppercase or lowercase X) and L (only upper case) to
denote long integer.
• Examples :
102, 4567, 567 # Decimal integers.
0o102, 0o876, 0o432 # Octal integers
0X102, 0X876, 0X432 # Hexadecimal integers
34L, 523L # Long decimal integers
• A floating-point data is represented by a sequence of decimal digits that includes a decimal point.
• An Exponent data contains decimal digit part, decimal point, exponent part followed by one or
more digits.
• Examples :
123.34, 456.23, 156.23 # Floating point data
12.E04, 24.e04 # Exponent data
• Complex number is made up of two floating point values, one each for the real and imaginary
parts.
Boolean Data type:

• A Boolean data can have any of the two values: True or False.
• Examples :
num_var1=True
num_var2=False
String Data type:

• String data can be enclosed in single quotes or double quotes or triple quotes.
• Examples:
Char_data = ‘A’
String_data= "Computer Science"
Multiline_data= ”””String data can be enclosed in single quotes or double quotes or triple
quotes.”””
5. Discuss about operators.
• In computer programming languages operators are special symbols which represent
computations, conditional matching etc.
• The value of an operator used is called operands.

• Operators are categorized as:


o Arithmetic (+, -, *, /, %, **, //)
o Relational or Comparative (< , > , <= , >=, ==, !=)
o Logical (and, or, not)
42
o Assignment (+=, -=, *=, /=, %=, **=, //=)
o Conditional, etc.
Arithmetic Operators:

• An arithmetic operator is a
mathematical operator that takes
two operands and performs a
calculation on them.
• They are used for simple
arithmetic.

Relational or Comparative operators:

• A Relational operator is also


called as Comparative operator
which checks the relationship
between two operands.
• If the relation is true, it returns
True; otherwise it returns False.

Logical operators:

• In python, Logical operators are used to perform logical operations on the given relational
expressions.
• There are three logical operators they are and, or and not.

Assignment operators:

• In Python, = is a simple assignment operator to assign values to variable.

43
• Let a = 5 and b = 10 assigns the value 5 to a and 10 to b these two assignment statement can also
be given as a,b=5,10 that assigns the value 5 and 10 on the right to the variables a and b
respectively.
• There are various compound operators in Python like +=, -=, *=, /=, %=, **= and //= are also
available.
Conditional operator:

• Ternary operator is also known as conditional operator that evaluate something based on a
condition being true or false.
• It simply allows testing a condition in a single line replacing the multiline if-else making the code
compact.
• Syntax:
Variable Name = [on_true] if [Test expression] else [on_false]
• Examples : min= 49 if 49 < 50 else 49 # min = 49
min= 50 if 49 > 50 else 49 # min = 49

44
Chapter 6 – Control Structures

1 % 3 ==0
1 ==0 → False

2 % 3 == 0
2 == 0 → False

3 % 3 == 0
0 == 0 → True

45
PART – II
1. List the control structures in Python.

• There are three important control structures:


1. Sequential
2. Alternative or Branching
3. Iterative or Looping
2. Write note on break statement.

• The break statement terminates the loop containing it.


• Control of the program flows to the statement immediately after the body of the loop.
3. Write is the syntax of if..else statement.

• Syntax:
if <condition>:
statements-block 1
else:
statements-block 2
4. Define control structure.

• A program statement that causes a jump of control from one part of the program to another is
called control structure or control statement.
5. Write note on range () in loop.

• The range( ) is a built-in function, to generate series of values between two numeric intervals.
• Syntax : range (start, stop, [step])
where,
start – refers to the initial value
stop – refers to the final value
step – refers to increment value, this is optional part.
Additional Questions:
6. Define Sequential statement.

• A sequential statement is composed of a sequence of statements which are executed one after
another.
• A code to print your name, address and phone number is an example of sequential statement

46
7. Define Alternative or Branching. List the types.

• When we need to skip a segment or set of statements and execute another segment based on the
test of a condition is called alternative or branching.
• Python provides the following types of alternative or branching statements:
• Simple if statement
• if..else statement
• if..elif statement
8. Define Iteration and its types.

• Iteration or loop are used in situation when the user need to execute a block of code several of
times or till the condition is satisfied.
• A loop statement allows to execute a statement or group of statements multiple times.
• Python provides two types of looping constructs:
• while loop
• for loop
9. Write the syntax for simple if.

• Syntax:
if <condition>:
statements-block1
10. Define jump statement and its types.

• The jump statement in Python, is used to unconditionally transfer the control from one part of the
program to another.
• There are three keywords to achieve jump statements in Python :
o break
o continue
o pass
PART – III
1. Write a program to display
A
A B
A B C
A B C D
A B C D E

47
for i in range (65, 70):
for j in range (65 , i+1):
print (chr(j), end = ‘ ‘)
print (end = ‘\n’)

2. Write note on if..else structure.

• The if .. else statement provides control to check the true block as well as the false block.
• Following is the syntax of ‘if..else’ statement.

• Syntax:
if <condition>: Example:
statements-block 1
else:
statements-block 2

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


n1 = int ( input (“Enter the first number:”) )
n2 = int ( input (“Enter the second number:”) )
n3 = int ( input (“Enter the third number:”) )
if (n1 >= n2) and (n1 >= n3):
large = n1
elif (n2 >= n2) and (n2 >= n3):
large = n2
else:
large = n3
print (“The Largest number is:”, large)

Output:

48
4. Write the syntax of while loop.

• Syntax: Example:
while <condition>:
statements block 1
[else:
statements block2]

5. List the differences between break and continue statements.


break continue
The break statement terminates the loop Continue statement unlike the break statement is
containing it. used to skip the remaining part of a loop.
Control of the program flows to the statement Control of the program flows start with next
immediately after the body of the loop. iteration.
Syntax: Syntax:
break continue

Additional Questions:
6. Write a note on parameters used with print function.

• print can have end, sep as parameters.


• end parameter can be used when we need to give any escape sequences like ‘\t’ for tab, ‘\n’ for
new line and so on.
• sep as parameter can be used to specify any special characters like, (comma) ; (semicolon) as
separator between values.
7. Write a note on conditional operator or an alternate method of if.. else with an example.

• An alternate method to rewrite the above program is also Example:


available in Python.
• The complete if..else can also written as:
• Syntax:
variable = variable1 if condition else variable 2

8. Write a note on pass statement.

• pass statement in Python programming is a null statement.


• pass statement when executed by the interpreter it is completely ignored.
49
• Nothing happens when pass is executed, it results in no operation.
• pass statement can be used in ‘if ’ clause as well as within loop construct, when you do not want
any statements or commands within that block to be executed.
• Syntax: Example:
pass

PART – IV
1. Write a detail note on for loop.

• The for loop is usually known as a definite loop, because the programmer knows exactly how
many times the loop will be executed.
• Syntax:
for counter_variable in sequence:
statements-block 1
[else: # optional block
statements-block 2]
• The for .... in statement is a looping statement used in Python to iterate over a sequence of
objects, i.e., it goes through each item in a sequence.
• Here the sequence is the collection of ordered or unordered values or even a string.
• The range( ) is a built-in function, to generate series of values between two numeric intervals.
• Syntax : range (start, stop, [step])
where,
start – refers to the initial value
stop – refers to the final value
step – refers to increment value, this is optional part.
• Example:

50
2. Write a detail note on if..elif..else statement with suitable example.
When we need to construct a chain of if statement(s) then ‘elif ’ clause
can be used instead of ‘if else’.

• Syntax:
if <condition 1>:
statements-block 1
elif <condition 2>:
statements-block 2
else:
statements-block n

• In the syntax of if..elif..else, condition-1 is tested if it is true then


statements-block1 is executed, otherwise the control checks
condition-2, if it is true statements-block2 is executed and even if it fails statements-block n
mentioned in else part is executed.
• ‘Multiple if..else statements can be combined to one if..elif…else.
• ‘elif ’ can be considered to be abbreviation of ‘else if ’.
• In an ‘if ’ statement there is no limit of ‘elif ’ clause that can be used, but an ‘else’ clause if used
should be placed at the end.

• Example:
n1 = int ( input (“Enter the first number:”) )
n2 = int ( input (“Enter the second number:”) )
n3 = int ( input (“Enter the third number:”) )
if (n1 >= n2) and (n1 >= n3):
large = n1
elif (n2 >= n2) and (n2 >= n3):
large = n2
else:
large = n3
print (“The Largest number is:”, large)

Output:

51
3. Write a program to display all 3 digit odd numbers.
for i in range (101, 1000, 2): Output:
print (i , end= ‘ ‘)
101 103 105 ……………..
………………………………………

………………… 995 997 999

4. Write a program to display multiplication table for a given number.


n = int ( input (“Enter a number:”) )
print (“Multiplication table of” , n)
for i in range (1 , 6):
print (n , ‘x’ , i, ‘=’ , n * i)

Output:

52
Chapter 7 – Python Functions

53
54
PART – II
1. What is function?

• Functions are named blocks of code that are designed to do specific job.
• Functions are nothing but a group of related statements that perform a specific task.
2. Write the different types of function.

• User-defined functions - Functions defined by the users themselves.


• Built-in functions - Functions that are inbuilt with in Python.
• Lambda functions - Functions that are anonymous un-named function.
• Recursion functions - Functions that calls itself is known as recursive.
3. What are the main advantages of function?
• It avoids repetition and makes high degree of code reusing.
• It provides better modularity for your application.
4. What is meant by scope of variable? Mention its types.
• Scope of variable refers to the part of the program, where it is accessible, i.e., area where you can
refer (use) it.
• We can say that scope holds the current set of variables and their values.
• The two types of scopes are local scope and global scope.
5. Define global scope.
• A variable, with global scope can be used anywhere in the program.
• It can be created by defining a variable outside the scope of any function.

55
6. What is base condition in recursive function.
• A recursive function calls itself.
• The condition that is applied in any recursive function is known as base condition.
• A base condition is must in every recursive function otherwise it will continue to execute like an
infinite loop.

7. How to set the limit for recursive function? Give an


example.

• Python stops calling recursive function after 1000


calls by default.
• It also allows you to change the limit using
[Link] (limit_value).

Additional Questions:
8. Define a block and a nested block.

• A block is one or more lines of code, grouped together so that they are treated as one big
sequence of statements while execution.
• In Python, statements in a block are written with indentation.
• A block within a block is called nested block.
• When the first block statement is indented by a single tab space, the second block of statement is
indented by double tab spaces.
9. Define parameters and arguments.

• Parameters are the variables used in the function definition.


• Arguments are the values we pass to the function parameters.
10. What is the use of lambda functons.

• Lambda function is mostly used for creating small and one-time anonymous function.
• Lambda functions are mainly used in combination with the functions like filter(), map() and
reduce().
11. Write the syntax of lambda functions.

• Syntax:
lambda [argument(s)] : expression
56
12. Write the syntax of user-defined function.

13. Write a note on return statement.

• Syntax:
return [expression list ]
• This statement can contain expression which gets evaluated and the value is returned.
• If there is no expression in the statement or the return statement itself is not present inside a
function, then the function will return the None object.

PART – III
1. Write the rules of local variable.
• A variable with local scope can be accessed only within the function that it is created in.
• When a variable is created inside the function the variable becomes local to it.
• A local variable only exists while the function is executing.
• The formal parameters are also local to function.
2. Write the basic rules for global keyword in python.
• When we define a variable outside a function, it’s global by default, we need not use global
keyword.
• We use global keyword to modify the value of the global variable inside a function.
• Use of global keyword outside a function has no effect
3. What happens when we modify global variable inside the function?
• Example:

• In the above program, x is defined as a global variable.


• Inside the add( ) function, global keyword is used for x and we increment the variable x by 5.
• Now, we can see the change on the global variable x outside the function i.e the value of x is 5.
57
4. Differentiate ceil() and floor() function?

ceil ( ) floor ( )
Returns the smallest integer greater than or Returns the largest integer less than or equal to
equal to x. x.
Syntax: [Link] (x) Syntax: [Link] (x)
Example: Example:
import math import math
x = 26.7 x = 26.7
print ([Link](x)) print ([Link](x))
Output: Output:
26 27

HINTS to remember:-
ceil( ) – rounds up. next highest integer. It is denoted as ⌈x⌉.
floor ( ) – rounds down. next lowest integer. It is denoted as ⌊x⌋.

5. Write a Python code to check whether a given year is leap year or not.
yr = int (input (“Enter the year:”) )
if (yr % 4 ==0):
print(“Leap Year”)
else:
print(“ Not a leap year”)

Output 1: Output 2:
Enter the year : 2012 Enter the year : 2013
Leap Year Not a leap year

6. What is composition in functions?


• The value returned by a function may be used as an argument for another function in a nested
manner. This is called composition.
• For example, if we wish to take a numeric value or an expression as a input from the user, we take
the input string from the user using the function input() and apply eval() function to evaluate its
value.
• Example:
>>> n1 = eval (input ("Enter a number: "))
Enter a number: 234
>>> n1
234
58
7. How recursive function works?

• Recursive function is called by some external code.


• If the base condition is met then the program gives meaningful output and exits.
• Otherwise, function does some required processing and then calls itself to continue recursion.
8. What are the points to be noted while defining a function?

• When defining functions there are multiple things that need to be noted;
• Function blocks begin with the keyword “def ” followed by function name and parenthesis ().
• If any input parameters are present should be placed within these parentheses when you define
a function.
• The code block always comes after a colon (:) and is indented.
• The statement “return [expression]” exits a function, optionally passing back an expression to
the caller.
A “return” with no arguments is the same as return None.
Additional Questions:
9. Write the advantages of user-defined functions.

• Functions help us to divide a program into modules. This makes the code easier to manage.
• It implements code reuse. Every time you need to execute a sequence of statements, all you need
to do is to call the function.
• Functions, allows us to change functionality easily, and different programmers can work on
different functions.
PART – IV
1. Explain the different types of function with an example.
The different types of functions are as follows:

• User-defined functions - Functions defined by the users themselves.


• Built-in functions - Functions that are inbuilt with in Python.
• Lambda functions - Functions that are anonymous un-named function.
• Recursion functions - Functions that calls itself is known as recursive.
User-defined functions:

• Syntax:

• When defining functions there are multiple things that need to be noted;
• Function blocks begin with the keyword “def ” followed by function name and parenthesis ().
59
• If any input parameters are present should be placed within these parentheses when you define
a function.
• The code block always comes after a colon (:) and is indented.
• The statement “return [expression]” exits a function, optionally passing back an expression to
the caller.
A “return” with no arguments is the same as return None.
• Example: def hello():
print (“hello - Python”)
return
Lambda or Anonymous functions:

• In Python, anonymous function is a function that is defined without a name.


• While normal functions are defined using the def keyword, in Python anonymous functions are
defined using the lambda keyword.
• Hence, anonymous functions are also called as lambda functions.
• Syntax:
lambda [argument(s)] : expression
• Example: sum = lambda arg1, arg2: arg1 + arg2
print ('The Sum is :', sum(30,40))
print ('The Sum is :', sum(-30,40))
Output:
The Sum is : 70
The Sum is : 10
Built-in functions: Example:
Functions which are using python libraries are
called Built-in functions.

Recursion functions:

• When a function calls itself is known as recursion.


• Recursive function is called by some external code.
• If the base condition is met then the program gives meaningful output and exits.
• Otherwise, function does some required processing and then calls itself to continue recursion.

60
• Example:

2. Explain the scope of variables with an example.

• Scope of variable refers to the part of the program, where it is accessible, i.e., area where you can
refer (use) it.
• There are two types of scopes - local scope and global scope.
Local Scope:

• A variable declared inside the function's body is known as local variable.


Rules of local variable:
• A variable with local scope can be accessed only within the function that it is created in.
• When a variable is created inside the function the variable becomes local to it.
• A local variable only exists while the function is executing.
• The formal parameters are also local to function.
Example:

Global Scope:

• A variable, with global scope can be used anywhere in the program.


• It can be created by defining a variable outside the scope of any function.
Rules of global Keyword:
• When we define a variable outside a function, it’s global by default. You don’t have to use global
keyword.
• We use global keyword to modify the value of the global variable inside a function.
61
• Use of global keyword outside a function has no effect.
Example:

3. Explain the following built-in functions.


(a) id() (b) chr() (c) round() (d) type() (e) pow()

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

63
Output:

5. Explain recursive function with an example.

• When a function calls itself is known as recursion.


• The condition that is applied in any recursive function is known as base condition. A base
condition is must in every recursive function otherwise it will continue to execute like an infinite
loop.
Overview of how recursive function works:

• Recursive function is called by some external code.


• If the base condition is met then the program gives meaningful output and exits.
• Otherwise, function does some required processing and then calls itself to continue recursion.
• Example:

Additional Questions:
6. Explain function arguments with relevant examples.

• Arguments are used to call a function and there are primarily 4 types of functions that one can
use:
• Required arguments,
• Keyword arguments,
• Default arguments and
• Variable-length arguments.
Required Arguments :

• “Required Arguments” are the arguments passed to a function in correct positional order.
• Here, the number of arguments in the function call should match exactly with the function
definition.
• We need atleast one parameter to prevent syntax errors to get the required output.

64
• Example:

Keyword Arguments :

• Keyword arguments will invoke the function after the parameters are recognized by their
parameter names.
• The value of the keyword argument is matched with the parameter name and so, one can also put
arguments in improper order (not in order).
• Example:

Default Arguments:

• In Python the default argument is an argument that takes a default value if no value is provided in
the function call.
• The following example uses default arguments, that prints default salary when no argument is
passed.
• Example:

65
Variable-Length Arguments:

• In some instances, we might need to pass more arguments than have already been specified.
• Going back to the function to redefine it can be a tedious process.
• Variable-Length arguments can be used instead.
• These are not specified in the function’s definition and an asterisk (*) is used to define such
arguments.
• Syntax:

• Example:

66
Chapter 8 – Strings and String Manipulation

67
PART – II
1. What is String?

• String is a data type in python, which is used to handle array of characters.


• String is a sequence of Unicode characters that may be a combination of letters, numbers, or
special symbols enclosed within single, double or even triple quotes.
• Example:
‘Welcome to learning Python’
“Welcome to learning Python”
‘‘‘ “Welcome to learning Python” ’’’
2. Do you modify a string in Python?

• Strings in python are immutable.


• That means, once you define a string, modifications or deletion is not allowed.
• However, we can replace the existing string entirely with the new string.
3. How will you delete a string in Python?

• Python will not allow deleting a particular character in a string, whereas we can remove entire
string variable using del command.
• Example:

4. What will be the output of the following python code?


str1 = “School”
print (str1 * 3)

Output: School School School

5. What is slicing?

• Slice is a substring of a main string.


• A substring can be taken from the original string by using [ ] operator and index or subscript values.
• Thus, [ ] is also known as slicing operator.
68
• Using slice operator, you have to slice one or more substrings from a main string.
• General format of slice operation:
str [start : end]
Additional Questions:
6. Define a subscript.

• index values are otherwise called as subscript which are used to access and manipulate the
strings.
• The subscript can be positive or negative integer numbers.
• The positive subscript 0 is assigned to the first character and n-1 to the last character, where n is
the number of characters in the string.
• The negative index assigned from the last character to the first character in reverse order begins
with -1
7. Define escape sequences.

• Escape sequence in python Escape sequences starts with a backslash and it can be interpreted
differently.
• Example:
>>> print ('They said, "What\'s there?"')
They said, "What's there?"
8. What are the membership operators.

• The ‘in’ and ‘not in’ operators can be used with strings to determine whether a string is present in
another string.
• Therefore, these operators are called as Membership Operators.

PART – III
1. Write a Python program to display the given pattern:-

COMPUTER
COMPUTE
COMPUT
COMPU
COMP
COM
CO
C

69
(OR) (OR)

2. Write a short about the followings with suitable example: (a) capitalize( ) (b) swapcase( )

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


str1 = "welcome"
str2 = "to school"
str3=str1[:2] +str2[len(str2)-2:]
print(str3)

Output:
weol

4. What is the use of format( )? Give an example.


• The format( ) function used with strings is very versatile and powerful function used for formatting
strings.
• The curly braces { } are used as placeholders or replacement fields which get replaced along with
format( ) function.

70
• Example:

5. Write a note about count( ) function in python.

Additional Questions:
6. Write a note on replace( ) function. Give an example.

• replace() function is used to temporarily change all occurrences of a particular character in a


string.
• The changes done through replace () does not affect the original string.
• Syntax: replace(“char1”, “char2”)
• The replace function replaces all occurrences of char1 with char2.
• Example:

7. Write a note on string formatting operator.

• The string formatting operator is one of the most exciting feature of python.
• The formatting operator % is used to construct strings, replacing parts of the strings with the data
stored in variables.
• Syntax: (“String to be display with %val1 and %val2” %(val1, val2))
71
• Example:

PART – IV
1. Explain about string operators in python with suitable example.

• Python provides the following operators for string operations. These operators are useful to
manipulate string.
i. Concatenation ( + )
ii. Append ( + = )
iii. Repeating ( * )
iv. String Slicing [ ]
v. Stride when slicing string.
(i) Concatenation (+)

• Joining of two or more strings is called as Concatenation.


• The plus (+) operator is used to concatenate strings in python.

• Example:
>>> "welcome" + "Python"
'welcomePython'
(ii) Append (+ =)

• Adding more strings at the end of an existing string is known as append.


• The operator += is used to append a new string with an existing string.
• Example:
>>> str1="Welcome to "
>>> str1+="Learn Python"
>>> print (str1)
Welcome to Learn Python
(iii) Repeating (*)

• The multiplication operator (*) is used to display a string in multiple number of times.
• Example:
72
>>> str1="Welcome "
>>> print (str1*4)
Welcome Welcome Welcome Welcome
(iv) String slicing [ ]

• Slice is a substring of a main string.


• A substring can be taken from the original string by using [ ] operator and index or subscript values.
• Thus, [ ] is also known as slicing operator.
• Using slice operator, you have to slice one or more substrings from a main string.
• Syntax:
str [start : end]
• where start is the beginning index and end is the last index value of a character in the string.
• Python takes the end value less than one from the actual index specified.

• Example 1: slice a single character from a string


>>> str1="THIRUKKURAL"
>>> print (str1[0])
T
• Example 2 : slice a substring from index 0 to 4
>>> print (str1[0 : 5])
THIRU
(v) Stride when slicing string

• When the slicing operation, you can specify a third argument as the stride, which refers to the
number of characters to move forward after the first character is retrieved from the string.
• The default value of stride is 1.
• Example:

73
Chapter 9 – Lists, Tuples, Sets and Dictionary

74
PART – II
1. What is List in Python?

• A list in Python is known as a “sequence data type” like strings.


• It is an ordered collection of values enclosed within square brackets [ ].
• Each value of a list is called as element.
• Syntax: Variable = [element-1, element-2, element-3 …… element-n]
• Example: [“Welcome” , 3.14 , 10 , [2, 4, 6]]

2. How will you access the list elements in reverse order?

• Python enables reverse or negative indexing for the list elements.


• Thus, 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.

3. What will be the value of x in following python code?


List1=[2,4,6[1,3,5]]
x=len(List1) Output: 4
print (x)

4. Differentiate del with remove() function of List.

del remove ( )
del statement is used to delete elements whose remove() function is used to delete elements of a list if its
index is known. index is unknown.
The del statement can also be used to delete remove() function can also be used to delete one or more
entire list. elements if the index value is not known
Syntax: Syntax:
del List [index of an element] List. remove(element)
del List [index from : index to]
del List

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


• Tuple with n number elements
Tuple_Name = (E1, E2, E2 ……. En)
• Elements of a tuple without parenthesis
Tuple_Name = E1, E2, E3 ….. En

6. What is set in Python?


• In python, a set is another type of collection data type.
• A Set is a mutable and an unordered collection of elements without duplicates.

75
• That means the elements within a set cannot be repeated.
• This feature used to include membership testing and eliminating duplicate elements.

PART – III
1. What are the difference between list and Tuples?

1. The elements of a list are changeable (mutable) whereas the elements of a tuple are unchangeable
(immutable), this is the key difference between tuples and list.
2. The elements of a list are enclosed within square brackets. But, the elements of a tuple are enclosed by
parentheses.
3. Iterating tuples is faster than list.
2. Write a short note about sort().
• sort ( ):
Sorts the element in list
• Syntax:
[Link](reverse=True|False, key=myFunc)

Both arguments are optional

• If reverse is set as True, list sorting is in descending order.


• Ascending is default. • Key=myFunc; “myFunc” - the name of the user defined function that specifies the
sorting criteria.
• Note: sort( ) will affect the original list.

• Example:
MyList=['Thilothamma', 'Tharani', 'Anitha', 'SaiSree', 'Lavanya']
[Link]( )
print(MyList)
[Link](reverse=True)
print(MyList)
• Output:
['Anitha', 'Lavanya', 'SaiSree', 'Tharani', 'Thilothamma']
['Thilothamma', 'Tharani', 'SaiSree', 'Lavanya', 'Anitha']

3. What will be the output of the following code?

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


print(list) (2)1 = 2
(2)2= 4
(2)3 = 8
Output: (2)4 = 16

[ 1 ,2 , 4 , 8 , 16]

76
4. Explain the difference between del and clear() in dictionary with an example.

del clear ( )
In Python dictionary, del keyword is used to The clear() function is used to delete
delete a particular element. all the elements in a dictionary.
To remove the dictionary, you can use del
keyword with dictionary name.
Syntax: Syntax:
To delete a particular element: To delete all the elements:
del dictionary_name[key] dictionary_name.clear( )

Example: Example:
del Dict['Mark1'] [Link]()

5. List out the set operations supported by python.

• Python supports the set operations such as: Union, Intersection, difference and Symmetric difference.
i. Union: It includes all elements from two or more sets.
ii. Intersection: It includes the common elements in two sets.
iii. Difference: It includes all elements that are in first set (say set A) but not in the second set (say set B).
iv. Symmetric difference: It includes all the elements that are in two sets (say sets A and B) but not the
one that are common to two sets.

6. What are the difference between List and Dictionary?

List Dictionary
List is an ordered set of elements Dictionary is a data structure that is used for
matching one element (Key) with another
(Value)
The index values can be used to access a In dictionary, key represents index. Remember
particular element. that, key may be a number of a string
Lists are used to look up a value. Dictionary is used to take one value and look up
another value

Additional Questions:

7. Define Nested List.

• Nested list is a list containing another list as an element.


• Example: Mylist = [ “Welcome”, 3.14, 10, [2, 4, 6] ]

8. Define list length.

• The len() function in Python is used to find the length of a list. (i.e., the number of elements in a list).

77
• Example:

9. Define accessing elements using for loop.

• In Python, the for loop is used to access all the elements in a list one by one.
• This is just like the for keyword in other programming language such as C++.

10. Write a note on changing list elements.

• In Python, the lists are mutable, which means they can be changed.
• A list element or range of elements can be changed or altered by using simple assignment operator =.

11. Define remove( ) , pop( ) , clear( ).

• remove() function can also be used to delete one or more elements if the index value is not known.
Syntax: [Link](element)
• pop() function deletes and returns the last element of a list if the index is not given.
Syntax: [Link](index of an element)
• clear() is used to delete all the elements in list, it deletes only the elements and retains the list.
Syntax: [Link]( )

12. Define list comprehensions. Give an example.

• List comprehension is a simplest way of creating sequence of elements that satisfy a certain condition.
• Syntax: List = [ expression for variable in range ]
• Example:

13. Define a tuple.

• Tuples consists of a number of values separated by comma and enclosed within parentheses.
• Tuple is similar to list, values in a list can be changed but not in a tuple.
78
• Syntax:
Tuple with n number elements
Tuple_Name = (E1, E2, E2 ……. En)
Elements of a tuple without parenthesis
Tuple_Name = E1, E2, E3 ….. En

14. How will you create tuples using tuple ( ) function.

• The tuple() function is used to create Tuples from a list.


• When you create a tuple, from a list, the elements should be
enclosed within square brackets.
• Syntax: Tuple_Name = tuple( [list elements] )

15. How to create single element tuple? (or) Define a singleton tuple.

• While creating a tuple with a single element, add a comma at the end of the element.
• In the absence of a comma, Python will consider the element as an ordinary data type; not a tuple.
• Creating a Tuple with one element is called “Singleton” tuple.
• Example:

16. Write a note on tuple assignment.

• Tuple assignment is a powerful feature in Python.


• It allows a tuple variable on the left of the assignment operator to be assigned to the values on the right
side of the assignment operator.
• Each value is assigned to its respective variable.

17. How will you create a set?

• A set is created by placing all the elements separated by comma within a pair of curly brackets.
• The set() function can also used to create sets in Python.
• Syntax: Set_Variable = {E1, E2, E3 …….. En}

79
• Example:

18. How to create a set using list or tuple?

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


• Firstly we have to create a list or Tuple then, substitute its variable within set() function as argument.
• Example:

19. Define a dictionary. Write its syntax.

• A dictionary is a mixed collection of elements.


• The keys in a Python dictionary is separated by a colon ( : ) while the commas work as a separator for the
elements.
• The key value pairs are enclosed with curly braces { }

20. Write a note on Dictionary comprehension. Give an example.

• Syntax: Dict = { expression for variable in sequence [if condition] }


• The if condition is optional and if specified, only those values in the sequence are evaluated using the
expression which satisfy the condition.
• Example:

80
21. Write the syntax to add more elements in a dictionary.

• Syntax:
dictionary_name [key] = value/element
• Example:
MyDict ['Class'] = 'XII - A' # Adding new value
print("Class: ", MyDict['Class']) # Printing newly added value

PART – IV
1. What the different ways to insert an element in a list. Explain with suitable example.

• In Python, append() function is used to add a single element and extend() function is used to add
more than one element to an existing list.
• Syntax:
[Link] (element to be added)
[Link] ( [elements to be added])
• Example1: Example2:

Inserting elements in a list:

• append() function in Python is used to add more elements in a list. But, it includes elements at the
end of a list.
• If we want to include an element at your desired position, we can use insert () function.
• The insert() function is used to insert an element at any position of a list.

• Example:

• In the above example, insert() function inserts a new element ‘Ramakrishnan’ at the index value 3,
ie. at the 4th position.
81
• While inserting a new element in between the existing elements, at a particular location, the
existing elements shifts one position to the right.
2. What is the purpose of range()? Explain with an example.

• The range() is a function used to generate a series of values in Python.


• Using range() function, you can create list with series of values.
• The range() function has three arguments.

where,
• start value – beginning value of series. Zero is the default beginning value.
• end value – upper limit of series. Python takes the ending value as upper limit – 1.
• step value – It is an optional argument, which is used to generate different interval of values.

Creating a list with series of values:

• Using the range() function, you can create a list with series of values.
• To convert the result of range() function into list, we need one more function called list().
• The list() function makes the result of range() as a list.
• Syntax: List_Varibale = list ( range ( ) )
• Example:

82
3. What is nested tuple? Explain with an example.

4. Explain the different set operations supported by python with suitable example.

• Python supports the set operations such as union, intersection, difference and symmetric
difference.

83
84
85
86
87
Chapter 10 – Python Classes and Objects

88
PART – I
1. What is class?

• Class is the main building block in Python.


• Object is a collection of data and function that act on those data.
• Class is a template for the object.
• According to the concept of Object-Oriented Programming, objects are also called as instances of a class.
• In Python, everything is an object.

2. What is instantiation?

• Once a class is created, next you should create an object or instance of that class.
• The process of creating object is called as “Class Instantiation”.
• Syntax:
Object_name = class_name( )

3. What is the output of the following program?

class Sample:
__num=10
def disp(self):
print(self.__num)
S=Sample()
[Link]()
print(S.__num)

Output: 10
AttributeError: 'Sample' object has no attribute '__num'

4. How will you create constructor in Python?

• Constructor is the special function that is automatically executed when an object of a class is created.
• In Python, there is a special function called “init” which act as a Constructor.
• It must begin and end with double underscore.

89
5. What is the purpose of Destructor?

• Destructor is also a special method to destroy the objects.


• In Python, __del__( ) method is used as destructor.
• It is just opposite to constructor.
• The __del__ method gets called automatically when we deleted the object reference using the del.
• Syntax:
def ___del___ (self):
<statements>

6. How will you access class members?

• Any class member ie. class variable or method (function) can be accessed by using object with a dot ( . )
operator.
• Syntax:
Object_name . class_member

PART – II
1. What are class members? How do you define it?

• In Python, a class is defined by using the keyword class.


• Every class has a unique name followed by a colon ( : ).
• Syntax:
class class_name:
statement_1
statement_2
…………..
…………..
statement_n
• where, statement in a class definition may be a variable declaration, decision control, loop or even a
function definition.
• Variables defined inside a class are called as “Class Variable” and functions are called as “Methods”.
• Class variable and methods are together known as members of the class.
• The class members should be accessed through objects or instance of class.
• A class can be defined anywhere in a Python program.
• Example: Program to define a class
class Sample:
x, y = 10, 20 # class variables

90
2. Write a class with two private class variables and print the sum using a method.

Output:

3. 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')
del [Link]
[Link]() Output:
Fruit 1 = Apple, Fruit 2 = Mango
Ans: del [Link] must be removed from line no: 8.

4. What is the output of the following program?


class Greeting:
def __init__(self, name):
self.__name = name
def display(self):
print("Good Morning ", self.__name)
obj=Greeting('Bindu Madhavan')
[Link]()

Output: Good Morning Bindhu Madhavan

5. How to define constructor and destructor in Python?

Constructor:

• Constructor is the special function that is automatically executed when an object of a class is created.
• In Python, there is a special function called “init” which act as a Constructor.
91
• It must begin and end with double underscore.

Destructor:

• Destructor is also a special method to destroy the objects.


• In Python, __del__( ) method is used as destructor.
• It is just opposite to constructor.
• The __del__ method gets called automatically when we deleted the object reference using the del.
• Syntax:
def ___del___ (self):
<statements>
PART – IV
1. Explain about constructor and destructor with suitable example.

Constructor:

• Constructor is the special function that is automatically executed when an object of a class is created.
• In Python, there is a special function called “init” which act as a Constructor.
• It must begin and end with double underscore.

Output:

Destructor:

• Destructor is also a special method to destroy the objects.


• In Python, __del__( ) method is used as destructor.
• It is just opposite to constructor.

92
• The __del__ method gets called automatically when we deleted the object reference using the del.
• Syntax:
def ___del___ (self):
<statements>

93
Chapter 11 – Database Concepts

94
PART – II
1. Mention few examples of a DBMS.
• FoxPro
• Dbase
• Windows registry
• XML

2. List some examples of RDBMS.


• MySQL
• Oracle
• SQL Server
• MariaDB
• SQLite
• MS Access

3. What is data consistency?


• Data Consistency means that data values are the same at all instances of a database.
• It refers to the accuracy, reliability and uniformity of data across a database or system.
4. What is the difference between Hierarchical and Network data model?

Hierarchical Data Model Network Data Model


In Hierarchical model, a child record In Network model, a child may have
has only one parent node. many parent nodes.
In Hierarchical model, data is It represents the data in many-to-
represented as a simple tree like many relationships.
structure form.

5. What is normalization?
• Normalization is a process of organizing the data in the database to reduce data redundancy and improve
data integrity.
• Database normalization was first proposed by Dr. Edgar F Codd as an integral part of RDBMS. These rules
are known as E F Codd Rules.

PART - III
1. What is the difference between Select and Project command?

Select Command Project Command


The SELECT operation is used for selecting a subset The projection method defines a relation that
with tuples according to a given condition contains a vertical subset of Relation.
Select filters out all tuples that do not satisfy C. The projection eliminates all attributes of the input
relation but those mentioned in the projection list.
symbol : σ symbol : Π
95
2. What is the role of DBA?

• Database Administrator or DBA is the one who manages the complete database management system.
• DBA takes care of the security of the DBMS, managing the license keys, managing user accounts and
access etc.

3. Explain Cartesian Product with a suitable example.

• Cross product is a way of combining two relations.


• The resulting relation contains, both relations being combined.
A x B means A times B, where the relation A and B have different
attributes.
• This type of operation is helpful to merge columns from two
relations.

4. Explain Object Model with example.

• Object model stores the data in the form of objects, attributes and methods, classes and Inheritance.
• This model handles more complex applications, such as Geographic information System (GIS), scientific
experiments, engineering design and manufacturing.
• It is used in file Management System. It represents real world objects, attributes and behaviours.
• It provides a clear modular structure. It is easy to maintain and modify the existing code.

An example of the Object model is Shape, Circle, Rectangle and


Triangle are all objects in this model.
➢ Circle has the attribute radius.
➢ Rectangle has the attributes length and breadth.
➢ Triangle has the attributes base and height .
The objects Circle, Rectangle and Triangle inherit from the object
Shape.
5. Write a note on different types of DBMS users.

• Database Administrators: Database Administrator or DBA is the one who manages the complete
database management system. DBA takes care of the security of the DBMS, managing the license keys,
managing user accounts and access etc.
• Application Programmers or Software Developers: This user group is involved in developing and
designing the parts of DBMS.
• End User: All modern applications, web or mobile, store user data. Applications are programmed in such a
way that they collect user data and store the data on DBMS systems running on their server. End users are
the one who store, retrieve, update and delete data.
• Database designers: are responsible for identifying the data to be stored in the database for choosing
appropriate structures to represent and store the data.

96
Additional Questions:

6. Write the advantages of RDBMS.

• Segregation of application program.


• Minimal data duplication or Data Redundancy.
• Easy retrieval of data using the Query Language.
• Reduced development time and maintenance
7. Describe the database structure.

• Table is the entire collection of related data in one table, referred to as a File or Table where the data is
organized as row and column.
• Each row in a table represents a record, which is a set of data for each database entry.
• Each table column represents a Field, which groups each piece or item of data among the records into
specific categories or types of data.
• Eg. StuNo., StuName, StuAge, StuClass, StuSec.
o A Table is known as a RELATION
o A Row is known as a TUPLE
o A column is known as an ATTRIBUTE.

8. Explain the components of DBMS.

The Database Management System can be divided into five major components as follows:

[Link]
[Link]
[Link]
[Link]/Methods
[Link] Access Languages.
1. Hardware: The computer, hard disk, I/O channels for data, and any other physical component involved in
storage of data
2. Software: The DBMS software is capable of understanding the Database Access Languages and interprets into
database commands for execution.
3. Data: It is the resource for which DBMS is designed. DBMS creation is to store and utilize data.
4. Procedures/Methods: They are general instructions to use a database management system such as installation
of DBMS, manage databases to take backups, report generation, etc.
5. DataBase Access Languages: They are the languages used to write commands to access, insert, update and
delete data stored in any database.
Examples of popular DBMS: Dbase, FoxPro

97
PART – IV
1. Explain the different types of data model.

• A data model describes how the data can be represented and accessed from a software after complete
implementation
• The main purpose of data model is to give an idea as how the final system or software will look like after
development is completed.
• Types of Data Model :-
• Hierarchical Model
• Relational Model
• Network Database Model
• Entity Relationship Model
• Object Model

Hierarchical Model:-

• Hierarchical model was developed by IBM as


Information Management System.
• In Hierarchical model, data is represented as a simple
tree like structure form.
• This model represents a one-to-many relationship i.e
parent-child relationship.
• One child can have only one parent but one parent can
have many children.
• This model is mainly used in IBM Main Frame
computers.

Relational Model:-

• The Relational Database model was first proposed by E.F. Codd in 1970 .
• Nowadays, it is the most widespread data
model used for database applications
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.
• Hence tables are also known as relations
in a relational model.
• A relation key is an attribute which
uniquely identifies a particular tuple (row
in a relation (table)).

98
Network Model:-

• Network database model is an extended form of


hierarchical data model.

The difference between hierarchical and Network data


model is :-
• In hierarchical model, a child record has only one
parent node.
• In a Network model, a child may have many parent
nodes. It represents the data in manyto-many
relationships.
• This model is easier and faster to access the data.

Entity Relationship Model. (ER model):-

• In this database model, relationship are created by dividing the object into entity and its characteristics
into attributes.
• It was developed by Chen in 1976.
• This model is useful in developing a conceptual design for the database. It is very simple and easy to
design logical view of data.
• The developer can easily understand the system by looking at ER model constructed.
• Rectangle represents the entities. E.g. Doctor and Patient.
• Ellipse represents the attributes E.g. D-id, D-name, P-id, P-name.
• Attributes describes the characteristics and each entity becomes a major part of the data stored in the
database.
• Diamond represents the relationship in ER diagrams E.g. Doctor diagnosis the Patient.

Object Model:-

• Object model stores the data in the form of objects, attributes and methods, classes and Inheritance.
• This model handles more complex applications, such as Geographic
information System (GIS), scientific experiments, engineering design
and manufacturing.
• It is used in file Management System. It represents real world
objects, attributes and behaviours.
• It provides a clear modular structure. It is easy to maintain and
modify the existing code.

99
An example of the Object model is Shape, Circle, Rectangle and Triangle are all objects in this model.

• Circle has the attribute radius.


• Rectangle has the attributes length and breadth.
• Triangle has the attributes base and height .
The objects Circle, Rectangle and Triangle inherit from the object Shape.
2. Explain the
different types of
relationship
mapping.

100
101
3. Differentiate DBMS and RDBMS.

[Link] the different operators in Relational algebra with suitable examples.

• Relational Algebra, was first created by Edgar F Codd while at IBM.


• It was used for modelling the data stored in relational databases and defining queries on it.

Relational Algebra is divided into various groups:

• Unary Relational Operations:


SELECT ( symbol : σ)
PROJECT ( symbol : ∏)
• Relational Algebra Operations from Set Theory:
UNION (∪)
INTERSECTION (∩)

102
DIFFERENCE (−)
CARTESIAN PRODUCT (X )

SELECT (symbol : σ)

• General form σ c ( R ) with a relation R and a condition C on the attributes of R.


• The SELECT operation is used for selecting a subset with tuples according to a given condition.
• Select filters out all tuples that do not satisfy C.

PROJECT (symbol : Π)

• The projection eliminates all attributes of the input relation but those mentioned in the projection list.
• The projection method defines a relation that contains a vertical subset of Relation.

103
UNION (Symbol :∪)

• It includes all tuples that are in tables A or in B.


• It also eliminates duplicates.
• Set A Union Set B would be expressed as A ∪ B.

Result:

SET DIFFERENCE ( Symbol : - )

• The result of A – B, is a relation which includes all tuples that are in A but not in B.
• The attribute name of A has to match with the attribute name in B.

Result:

INTERSECTION (symbol : ∩)

• A ∩ B Defines a relation consisting of a set of all tuple that are in both in A and B.
• However, A and B must be union-compatible.
Result:

PRODUCT OR CARTESIAN PRODUCT (Symbol : X )

• Cross product is a way of combining two relations.


• The resulting relation contains, both relations being combined.
• A x B means A times B, where the relation A and B have different attributes.
• This type of operation is helpful to merge columns from two relations.

104
5. Explain the characteristics of RDBMS.

105
Chapter 12 – Structured Query Language (SQL)

PART – II
1. Write a query that selects all students whose age is less than 18 in order wise.

SELECT * FROM student WHERE Age<=18 ORDER BY Name;

2. Differentiate Unique and Primary Key constraint.

Unique Key Constraint Primary Key Constraint


This constraint ensures that no two This constraint declares a field as a
rows have the same value in the Primary key which helps to uniquely
specified columns. identify a record.
The UNIQUE constraint can be applied The primary key does not allow NULL
only to fields that have also been values.
declared as NOT NULL.

3. Write the difference between table constraint and column constraint?

Table Constraint Column Constraint


Table constraint apply to a group of Column constraint apply only to
one or more columns. individual column.

4. Which component of SQL lets insert values in tables and which lets to create a table?

Command Description Component


INSERT Inserts data into a Data Manipulation Language
table (DML)
CREATE To create tables in Data Definition Language (DDL)
the database
106
5. What is the difference between SQL and MySQL?

SQL MySQL
SQL-Structured Query Language is a MySQL is a database management
language used for accessing system, like SQL Server, Oracle,
databases. Informix, Postgres, etc.
SQL is a query language. MySQL is a Relational Database
Management System.

PART – III
1. What is a constraint? Write short note on Primary key constraint.

Constraint: -

• Constraints are used to limit the type of data that can go into a table.
• This ensures the accuracy and reliability of the data in the database.
• Constraints could be either on a column level or a table level.
• Constraint is a condition applicable on a field or set of fields.

Primary Key Constraint: -

• This constraint declares a field as a Primary key which 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.
• The primary key does not allow NULL values.

2. Write a SQL statement to modify the student table structure by adding a new field.

• The ALTER command is used to alter the table structure like adding a column, renaming the existing
column, change the data type of any column or size of the column or delete the column from the table.
• To modify existing column of table, the ALTER TABLE command can be used with MODIFY clause.
• Syntax: ALTER TABLE <table-name> MODIFY<column-name><data type><size>;
• Example: ALTER TABLE Student MODIFY Address char (25);
The above command will modify the address column of the student table to hold 25 characters.

3. Write any three DDL commands.

1) CREATE TABLE Command:-


• CREATE TABLE command is used to create tables in the database. Each table must have at least one
column.
• Syntax: CREATE TABLE <table-name> (<column name><data type>[<size>] , (<column name><data
type>[<size>]….. );
• Example: CREATE TABLE Student (Admno Integer, Name char(50), Gender char(1), Age Integer);

2) ALTER Command:-
• The ALTER command is used to alter the table structure like adding a column, renaming the existing
column, change the data type of any column or size of the column or delete the column from the table.
107
• Syntax: ALTER TABLE <table-name> ADD <column-name><data type><size>;
• Example: ALTER TABLE Student ADD Address char;

3) DROP Command:-
• The DROP TABLE command is used to remove a table from the database.
• If you drop a table, 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, so we must be careful while using DROP TABLE command.
• Syntax: DROP TABLE table-name;
• Example: DROP TABLE Student;

4. Write the use of Savepoint command with an example.

• The SAVEPOINT command is used to temporarily save a transaction so that you can rollback to the point
whenever required.
• The different states of our table can be saved at anytime using different names and the rollback to that
state can be done using the ROLLBACK command.
• Syntax: SAVEPOINT savepoint_name;
• Example:
UPDATE Student SET Name = ‘Mini’ WHERE Admno=105;
SAVEPOINT A;

5. Write a SQL statement using DISTINCT keyword.

• The DISTINCT keyword is used along with the SELECT command to eliminate duplicate rows in the table.
• This helps to eliminate redundant data.
• Example: SELECT DISTINCT Place FROM Student;
Will display the following data as follows :
Place
Chennai
Bangalore
Delhi
PART – IV

1. Write the different types of constraints and their functions.


• Constraints ensure database integrity, therefore known as database integrity constraints.
• The different types of constraints are :
1. Unique Constraint
2. Primary Key Constraint
3. Check Constraint
4. Default Constraint
5. Table Constraint
• Unique Constraint: -
o This constraint ensures that no two rows have the same value in the specified columns.

108
o Example: UNIQUE constraint applied on Admno of student table ensures that no two students
have the same admission number and the constraint can be used as:
CREATE TABLE Student
(
Admno integer NOT NULL UNIQUE, → Unique constraint
Name char (20) NOT NULL,
Gender char (1),
Age integer,
Place char (10),
);
o The UNIQUE constraint can be applied only to fields that have also been declared as NOT NULL.
o When two constraints are applied on a single field, it is known as multiple constraints.
o In the above Multiple constraints NOT NULL and UNIQUE are applied on a single field Admno, the
constraints are separated by a space and at the end of the field definition a comma(,) is added.
o By adding these two constraints the field Admno must take some value ie. will not be NULL and
should not be duplicated.
• Primary Key Constraint: -

o This constraint declares a field as a Primary key which helps to uniquely identify a record.
o It is similar to unique constraint except that only one field of a table can be set as primary key.
o The primary key does not allow NULL values.
o Example: showing Primary Key Constraint in the student table:
CREATE TABLE Student
(
Admno integer PRIMARY KEY, → Primary Key constraint
Name char(20) NOT NULL,
Gender char(1),
Age integer,
Place char(10),
);
o In the above example the Admno field has been set as primary key and therefore will help us to
uniquely identify a record, it is also set NOT NULL, therefore this field value cannot be empty.
• Default Constraint:-
o The DEFAULT constraint is used to assign a default value for the field.
o When no value is given for the specified field having DEFAULT constraint, automatically the default
value will be assigned to the field.
o Example: showing default Constraint in the student table:
CREATE TABLE Student
(
Admno integer PRIMARY KEY,
Name char(20)NOT NULL,
Gender char(1),
Age integer DEFAULT 17, → Default Constraint
Place char(10)
109
);
o In the above example the “Age” field is assigned a default value of 17, therefore when no value is
entered in age by the user, it automatically assigns 17 to Age.
• Check Constraint:-
o This constraint helps to set a limit value placed for a field.
o When we define a check constraint on a single column, it allows only the restricted values on that
field.
o Example: showing check constraint in the student table:
CREATE TABLE Student
(
Admno integer PRIMARY KEY
Name char(20)NOT NULL,
Gender char(1),
Age integer CHECK (Age <=19), → Check Constraint
Place char(10),
);
o In the above example the check constraint is set to Age field where the value of Age must be less
than or equal to 19.
• Table Constraint:-
o When the constraint is applied to a group of fields of the table, it is known as Table constraint.
o The table constraint is normally given at the end of the table definition.
o Example:
CREATE TABLE Student 1
(
Admno integer NOT NULL,
Firstname char(20),
Lastname char(20),
Gender char(1),
Age integer,
Place char(10),
PRIMARY KEY (Firstname, Lastname) → Table constraint
);
o In the above example, the two fields, Firstname and Lastname are defined as Primary key which is a
Table constraint.

2. Consider the following employee table. Write SQL commands for the qtns.(i) to (v).

110
(i) To display the details of all employees in descending order of pay.
(ii) To display all employees whose allowance is between 5000 and 7000.
(iii) To remove the employees who are mechanic.
(iv) To add a new row.
(v) To display the details of all employees who are operators.

(i) SELECT * FROM employee ORDER BY PAY DESC;


(ii) SELECT * FROM employee WHERE ALLOWANCE BETWEEN 5000 AND 7000.
(iii) DELETE FROM employee WHERE DESIG=”Mechanic”;
(iv) INSERT INTO employee (EMPCODE, NAME, DESIG, PAY, ALLOWANCE) VALUES (S1002, John, Supervisor,
29000, 12000);
(v) SELECT * FROM employee WHERE DESIG=”Operator”;

3. What are the components of SQL? Write the commands in each.

• SQL commands are divided into five categories:


o DDL - Data Definition Language
o DML - Data Manipulation Language
o DCL - Data Control Language
o TCL - Transaction Control Language
o DQL - Data Query Language

• DDL - Data Definition Language:-


o The Data Definition Language (DDL) consist of SQL statements used to define the database
structure or schema.
o It simply deals with descriptions of the database schema and is used to create and modify the
structure of database objects in databases.
o The DDL provides a set of definitions to specify the storage structure and access methods used by
the database system.
o SQL commands which comes under Data Definition Language are:

Create To create tables in the database.


Alter Alters the structure of the database.
Drop Delete tables from database.
Truncate Remove all records from a table, also release the space
occupied by those records.

• DML - Data Manipulation Language:-


o A Data Manipulation Language (DML) is a query language used for adding (inserting), removing
(deleting), and modifying (updating) data in a database.
o In SQL, the data manipulation language comprises the SQL-data change statements, which modify
stored data but not the schema of the database table.

o The DML is basically of two types:


111
Procedural DML – Requires a user to specify what data is needed and how to get it.
Non-Procedural DML - Requires a user to specify what data is needed without specifying how to get
it.
o SQL commands which comes under Data Manipulation Language are :
Insert Inserts data into a table

Update Updates the existing data within a table.

Delete Deletes all records from a table, but not the


space occupied by them.

• DCL - Data Control Language:-


o A Data Control Language (DCL) is a programming language used to control the access of data
stored in a database.
o It is used for controlling privileges in the database (Authorization).
o The privileges are required for performing all the database operations such as creating sequences,
views of tables etc.

o SQL commands which come under Data Control Language are:


Grant Grants permission to one or more users to perform specific tasks.

Revoke Withdraws the access permission given by the GRANT statement.

• TCL - Transaction Control Language:-


o Transactional control language (TCL) commands are used to manage transactions in the database.
o These are used to manage the changes made to the data in a table by DML statements.
o SQL command which come under Transfer Control Language are:

Commit Saves any transaction into the database permanently.

Roll back Restores the database to last commit state.

Save point Temporarily save a transaction so that you can rollback.

• DQL - Data Query Language:-

o The Data Query Language consist of commands used to query or retrieve data from a database.
o One such SQL command in Data Query Language is SELECT.
Select It displays the records from the table.

4. Construct the following SQL statements in the student table-


(i) SELECT statement using GROUP BY clause.
(ii) SELECT statement using ORDER BY clause.
112
GROUP BY clause:-

• The GROUP BY clause is used with the SELECT statement to group the students on rows or columns having
identical values or divide the table in to groups.
• For example to know the number of male students or female students of a class, the GROUP BY clause
may be used.
• It is mostly used in conjunction with aggregate functions to produce summary reports from the database.
• Syntax: SELECT <column-names> FROM <table-name> GROUP BY <column-name>HAVING condition];
Gender
• Eg 1: SELECT Gender FROM Student GROUP BY Gender; M
F

• Eg 2: SELECT Gender, count(*) FROM Student GROUP BY Gender;

Gender Count(*)
M 5
F 3
ORDER BY clause:-

• The ORDER BY clause in SQL is used to sort the data in either ascending or
descending based on one or more columns.
1. By default ORDER BY sorts the data in ascending order.
2. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in
ascending order.
• Syntax: SELECT <column-name>[,<column-name>,….] FROM <table-name> ORDER BY
<column1>,<column2>,…ASC| DESC ;
• For example : To display the students in alphabetical order of their names, the command is used as
SELECT * FROM Student ORDER BY Name;
• The above student table is arranged as follows :

Admno Name Gender Age Place

104 Abinandh M 18 Chennai

101 Adarsh M 18 Delhi

102 Akshith M 17 Bangalore

5. Write a SQL statement to create a table for employee having any five fields and create a table constraint
for the employee table.
CREATE TABLE employee
(
Empcode Integer NOT NULL;
Empname CHAR (30),
113
Designation CHAR (20),
Pay Integer,
Allowance Integer,
PRIMARY KEY (Empcode)
);

ADDITIONAL QUESTIONS: 2, 3 or 5 marks


1. List the functions of DDL.
o It should identify the type of data division such as data item, segment, record and database file.
o It gives a unique name to each data item type, record type, file type and data base.
o It should specify the proper data type. It should define the size of the data item.
o It may define the range of values that a data item may use.
o It may specify privacy locks for preventing unauthorized data entry.

2. Compare DELETE, TRUNCATE, DROP in SQL.

DELETE The DELETE command deletes only the rows from the table based on the condition given in the
where clause or deletes all the rows from the table if no condition is specified. But it does not free
the space containing the table.

TRUNCATE The TRUNCATE command is used to delete all the rows, the structure remains in the table and free
the space containing the table.

DROP The DROP command is used to remove an object from the database. If you drop a table, 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.

3. Write a note on COMMIT Command.


o The COMMIT command is used to permanently save any transaction to the database.
o When any DML commands like INSERT, UPDATE, DELETE commands are used, the changes made
by these commands are not permanent.
o It is marked permanent only after the COMMIT command is given from the SQL prompt.
o Once the COMMIT command is given, the changes made cannot be rolled back.
o Syntax: COMMIT;

4. Define ROLLBACK and SAVEPOINT.


o The ROLLBACK command restores the database to the last commited state.
o It is used with SAVEPOINT command to jump to a particular savepoint location.
o Syntax: ROLL BACK TO save point name;

o The SAVEPOINT command is used to temporarily save a transaction so that you can rollback to the
point whenever required.

114
o The different states of our table can be saved at anytime using different names and the rollback to
that state can be done using the ROLLBACK command.
o Syntax: SAVEPOINT savepoint_name;

5. Write a note on DQL command – SELECT.


o One of the most important tasks when working with SQL is to generate Queries and retrieve data.
o A Query is a command given to get a desired result from the database table.
o The SELECT command is used to query or retrieve data from a table in the database.
o It is used to retrieve a subset of records from one or more tables.
o Syntax: SELECT <column-list>FROM<table-name>;
Table-name is the name of the table from which the information is retrieved.
Column-list includes one or more columns from which data is retrieved.
o Example: To view all the fields and rows of the table the SELECT command can be given as
SELECT * FROM STUDENT;

Hands on Experience :-

1. Create a query of the student table in the following order of fields name, age, place and admno.

CREATE TABLE Student (name char(30), age integer, place char(3), admno integer));

2. Create a query to display the student table with students of age more than 18 with unique city.

SELECT DISTINCT city FROM Student WHERE age >=18;

3. Create a employee table with the following fields employee number, employee name, designation, date of
joining and basic pay.

CREATE TABLE Employee (EmpNo integer, Ename char(30) NOT NULL, Desig char(30), DOJ datetime, Basicpay
integer);

4. In the above table set the employee number as primary key and check for NULL values in any field.

ALTER TABLE Employee ADD NOT NULL PRIMARY KEY (EmpNo);

ALTER TABLE Employee MODIFY Ename char (30) NOT NULL;


ALTER TABLE Employee MODIFY Desig char (30) NOT NULL;
ALTER TABLE Employee MODIFY DOJ datetime NOT NULL;
ALTER TABLE Employee MODIFY Basicpay integer NOT NULL;

5. Prepare a list of all employees who are Managers.

SELECT * FROM Employee WHERE Desig=’Manager’;

115
Chapter 13 – Python and CSV Files

116
PART – II
1. What is CSV File?

• A CSV file is a human readable text file where each line has a number of fields, separated by commas or
some other delimiter.
• A CSV file is also known as a Flat File. Files in the CSV format can be imported to and exported from
programs that store data in tables, such as Microsoft Excel or OpenOffice Calc.

2. Mention the two ways to read a CSV file using Python.

There are two ways to read a CSV file.


1. Use the csv module’s reader function
2. Use the DictReader class.

3. Mention the default modes of the File.

• The default is reading in text mode.


'r' - To open a file for reading. (default).
‘t' - To open in text mode. (default).
• In this mode, while reading from the file the data would be in the format of strings.

4. What is use of next() function?

• next( ) function is used to return the next item from the iterator.
• It is used to skip a row of the csv file.
• Example: While sorting the row heading will also get sorted, to avoid that, the first row is skipped using
next().

5. How will you sort more than one column from a csv file? Give an example statement.

• To sort by more than one column, we can use itemgetter with multiple indices:- operator. itemgetter (1,2).
• Syntax: sortedlist = sorted (data, key=operator. Itemgetter (Col_number), reverse=True)
• Example: sortedlist = sorted (data, key=[Link](1))

PART – III
1. Write a note on open() function of python. What is the difference between the two methods?

open( ) function:

• Python has a built-in function open() to open a file.


• This function returns a file object, also called a handle, as it is used to read or modify the file accordingly.
• For Example:
>>> f = open(“[Link]”) # open file in current directory and f is file object
>>> f = open(‘c:\ \pyprg\ \[Link]’) #specifying full path.

117
• We can specify the mode whether we want to read ‘r’, write ‘w’ or append ‘a’ to the file in “text or binary” in
which the file is to be opened.
The default is reading in text (“rt”) mode. In this mode, while reading from the file the data would be in the
format of strings.

METHOD 1:

f = open(“[Link]”) # since no mode is specified the default mode it is used.


#perform file operations
[Link]( )

• This method is not entirely safe.


• If an exception occurs when we are performing some operation with the file, the code exits without closing
the file.

METHOD 2:

with open("[Link]" , ’r’) as f:


# f is file object to perform file operations.

• This method ensures that the file is closed when the block inside with is exited.
• We need not to explicitly call the close() function because it is done internally.

2. Write a Python program to modify an existing file.

When we open the [Link] file with text editor, then it will show:

118
3. Write a Python program to read a CSV file with default delimiter comma (,).

4. What is the difference between the write mode and append mode.

• The ‘w’ write mode creates a new file.


• If the file is already existing, ‘w’ mode overwrites it.
• The ‘a’ append mode adds the data at the end of the file if the file already exists otherwise creates a new
one.

5. What is the difference between reader()method and DictReader() class?

reader( ) function Dictreader( ) class

The reader function is designed to take each line of DictReader works by reading the first line of the CSV
the file and make a list of all columns. and using each comma separated value in this line
as a dictionary key.

Using this function one can read data from csv files It creates an object which maps data to a dictionary
of different formats like quotes (" "), pipe ( | ) and and takes additional argument fieldnames that are
comma ( , ). used as dictionary keys.

[Link]( ) works with list / tuple. [Link] works with dictionary.


Syntax: [Link] (fileobject ,delimiter, fmtparams)

119
PART – IV
1. Differentiate Excel file and CSV file.

2. Tabulate the different mode with its meaning.

3. Write the different methods to read a File in Python.

• There are two ways to read a CSV file.

1. Use the csv module’s reader function


2. Use the DictReader class.

120
CSV Module’s Reader Function:

• We can read the contents of CSV file with the help of [Link]() function.
• The reader function is designed to take each line of the file and make a list of all columns.
• Using this function one can read data from csv files of different formats like quotes (" "), pipe ( | ) and
comma ( , ).
• Syntax: [Link] (fileobject,delimiter,fmtparams)
where,
i. file object :- passes the path and the mode of the file
ii. delimiter :- an optional parameter containing the standard dilects like , | etc can be omitted
iii. fmtparams: optional parameter which help to override the default values of the dialects like
skipinitialspace, quoting etc. Can be omitted.
• Example:

Reading CSV File Into A Dictionary:-

• To read a CSV file into a dictionary can be done by using DictReader method of csv module which 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
and using each comma separated value in this line as a dictionary key.
• The columns in each subsequent row then behave like dictionary values and can be accessed with the
appropriate key (i.e. fieldname).
• If the first row of your CSV does not contain your column names, you can pass a fieldnames parameter into
the DictReader’s constructor to assign the dictionary keys manually.
• The main difference between the [Link]() and DictReader() is in simple terms csv. reader and [Link]
work with list/tuple, while [Link] and [Link] work with dictionary.
• [Link] and [Link] take additional argument fieldnames that are used as dictionary keys.

121
• Example:

4. Write a Python program to write a CSV File with custom quotes.

We can write the CSV file with custom quote characters, by registering new dialects using csv.register_dialect()
class of csv module.

When we open the “[Link]” file in notepad, we get following output:

5. Write the rules to be followed to format the data in a CSV file.


Rules to be followed to format data in a CSV file:-

122
ADDITIONAL QUESTIONS:
1. Define Excel and CSV.

• Excel is a binary file that holds information about all the worksheets in a file, including both content and
formatting.

123
• CSV format is a plain text format with a series of values separated by commas.

2. How the CSV file operation takes place in python? (OR) What are the steps involved in file operation of
Python?

• Step 1 – Open a file


• Step 2 – Perform read or write operation
• Step 3 – Close the file.

3. How [Link]() function is used to create a normal CSV file in Python?

• The [Link]() function returns a writer object which converts the user’s data into delimited strings on the
given file-like object.
• The writerow() function writes a row of data into the specified file.
• Syntax: [Link](fileobject, delimiter, fmtparams)
where,
• fileobject :- passes the path and the mode of the file
• delimiter :- an optional parameter containing the standard dilects like , | etc can be omitted
• fmtparams : optional parameter which help to override the default values of the dialects like
skipinitialspace,quoting etc. can be omitted.

4. Define writerow( ) and writerows( ) functions.

• The writerow() function writes one row at a time.


• To write all the data at once, we can use writerows() method.

5. Define Modification.

• Making some changes in the data of the existing file or adding more data is called modification.

6. Define OrderedDict.

• An OrderedDict is a dictionary subclass which saves the order in which its contents are added.

7. Write the difference between sorted( ) and sort( ) method.

• The sorted() method sorts the elements of a given item in a specific order – Ascending or Descending.
• Sort() method which performs the same way as sorted().
• Only difference is, sort() method doesn’t return any value and changes the original list itself.

124
Hands on Experience :-

OUTPUT:-

2. Write a Python program to accept the name and five subjects mark of 5 students. Find the total
and store all the details of the students in a CSV file.

OUTPUT:-

125
Chapter 14 – Importing C++ Programs in Python

126
PART – II
1. What is the theoretical difference between Scripting language and other programming language?
• The theoretical difference between the two is that scripting languages do not require the compilation step
and are rather interpreted.
• For example, normally, a C++ program needs to be compiled before running whereas, a scripting language
like JavaScript or Python need not be compiled.
• A scripting language requires an interpreter while a programming language requires a compiler.
• A given language can be called as a scripting or programming language depending on the environment they
are put to use.

2. Differentiate compiler and interpreter.


Feature Compiler Interpreter
Translation Translates entire program at once. Translates and executes line by line.
Speed Faster execution. Slower execution.
Error Detection Errors are found after compiling. Errors are found during execution.
Examples C, C++, FORTRAN Python, Ruby, PHP

3. Write the expansion of (i) SWIG (ii) MinGW


• SWIG - Simplified Wrapper Interface Generator- Both C and C++
• MinGW - Minimalist GNU for Windows.

4. What is the use of modules?


• Modules are used to break down large programs into small manageable and organized program.
• Modules provide reusability of code.
• We can define our most used functions in a module and import it, instead of copying their definitions into
different programs.

5. What is the use of cd command. Give an example.


• To change a directory 'cd' command is used.
• Syntax: cd <absolute path>
where “cd” command refers to change directory and absolute path refers to the complete path where
Python is installed.
• Example: “C:\> cd C:\Program Files\OpenOffiice 4\Program”.

127
PART – III
1. Differentiate PYTHON and C++.

2. What are the applications of scripting language?

1. To automate certain tasks in a program


2. Extracting information from a data set
3. Less code intensive as compared to traditional programming language
4. can bring new functions to applications and glue complex systems together.

3. What is MinGW? What is its use?

• MinGW (Minimalist GNU for Windows) refers to a set of runtime header files, used in compiling and linking
the code of C, C++ and FORTRAN to be run on Windows Operating System.
• MinGw-W64 (version of MinGW) is the best compiler for C++ on Windows.
• To compile and execute the C++ program, we need ‘g++’ for Windows. MinGW allows to compile and
execute C++ program dynamically through Python program using g++.
• Python program that contains the C++ coding can be executed through either by using command prompt or
by using run terminal.

4. Identify the module ,operator, definition name for the following


welcome. display( )
welcome → module name
. → dot operator
display( ) → function name

5. What is [Link]? What does it contain?

• [Link] is the list of command-line arguments passed to the Python program.


• argv contains all the items that come via the command-line input, it's basically a list holding the command-
line arguments of the program.
• To use [Link], import sys should be used.
• The first argument, [Link][0] contains the name of the python program and [Link] [1]is the next
argument passed to the program (here it is the C++ file), which will be the argument passed through main().
128
• For Example: main([Link][1])
• Accepts the program file (Python program) and the input file (C++ file) as a list(array).
• argv[0] contains the Python program which is need not to be passed because by default __main__ contains
source code reference and argv[l] contains the name of the C++ file which is to be processed.

PART – IV
1. Write any 5 features of Python.

• Python uses Automatic Garbage Collection whereas C++ does not.


• C++ is a statically typed language, while Python is a dynamically typed language.
• Python runs through an interpreter, while C++ is pre-compiled.
• Python code tends to be 5 to 10 times shorter than that written in C++.
• In Python, there is no need to declare types explicitly where as it should be done in C++
• In Python, a function may accept an argument of any type, and return multiple values without any kind of
declaration beforehand. Whereas in C++ return statement can return only one value.
2. Explain each word of the following command.
Python <[Link]> -<i> <C++ filename without cpp extension>

Python <[Link]> -<i> <C++ filename without cpp extension>

3. What is the purpose of sys, os, getopt module in Python. Explain.

Python’s sys module:-

• This module provides access to built-in variables used by the interpreter.


• One among the variable in sys module is argv.

[Link]:

• [Link] is the list of command-line arguments passed to the Python program.


• argv contains all the items that come via the command-line input, it's basically a list holding the command-
line arguments of the program.
129
• To use [Link], import sys should be used.
• The first argument, [Link][0] contains the name of the python program and [Link] [1]is the next
argument passed to the program (here it is the C++ file), which will be the argument passed through main().

For Example: main([Link][1])

• Accepts the program file (Python program) and the input file (C++ file) as a list(array).
• argv[0] contains the Python program which is need not to be passed because by default __main__ contains
source code reference and argv[l] contains the name of the C++ file which is to be processed.

Python's OS Module:

• The OS module in Python provides a way of using operating system dependent functionality.
• The functions that the OS module allows you to interface with the Windows operating system where Python
is running on.
• [Link](): Execute the C++ compiling command (a string contains Unix, C command which also
supports C++ command) in the shell (Here it is Command Window).
• For Example to compile C++ program g++ compiler should be invoked.
• To do so the following command is used:

Python getopt module:-

• The getopt module of Python helps you to parse (split) command-line options and arguments.
• This module provides getopt() method to enable command-line argument parsing.
• [Link] function This function parses command-line options and parameter list.

130
Syntax:

4. Write the syntax for getopt() and explain its arguments and return values.

• The getopt module of Python helps you to parse (split) command-line options and arguments.
• This module provides getopt() method to enable command-line argument parsing.
• [Link] function This function parses command-line options and parameter list.

131
• Syntax:

5. Write a Python program to execute the following c++ coding.

#include <iostream>
using namespace std;
int main( )
{ cout«“WELCOME”;
return (0);
}
The above C++ program is saved in a file [Link]

132
• Type in notepad and save as [Link]

• Open Notepad and type python program and save as [Link]

Output:
——————-
WELCOME
——————-
ADDITIONAL QUESTIONS:
1. Define a Scripting Language.

• A scripting language is a programming language designed for integrating and communicating with other
programming languages.
• Some of the most widely used scripting languages are JavaScript, VBScript, PHP, Perl, Python, Ruby, ASP
and Tcl.

2. Define Garbage Collection.

• Python deletes unwanted objects (built-in types or class instances) automatically to free the memory
space.
• The process by which Python periodically frees and reclaims blocks of memory that no longer are in use is
called Garbage Collection.

133
3. Define Wrapping.
• Importing C++ program in a Python program is called wrapping up of C++ in Python.

4. Name the commonly used intefaces for importing C++ files in Python.
• Python-C-API (API-Application Programming Interface for interfacing with C programs)
• Ctypes (for interfacing with c programs)
• SWIG (Simplified Wrapper Interface Generator- Both C and C++)
• Cython (Cython is both a Python-like language for writing C-extensions)
• Boost. Python (a framework for interfacing Python and C++)
• MinGW (Minimalist GNU for Windows)

5. What is g++?
• g++ is a program that calls GCC (GNU C Compiler) and automatically links the required C++ library files to
the object code.
6. Write a note on __name__ variable in Python.
• Since there is no main() function in Python, when the command to run a Python program is given to the
interpreter, the code that is at level 0 indentation (top must line of the program) is to be executed.
• However, before doing that, interpreter will define a few special variables. __name__ is one such special
variable which by default stores the name of the Python file.
• If the source file is executed as the main program, the interpreter sets the __name__ variable to have a
value “__main__”.
• __name__ is a built-in variable which evaluates to the name of the current module.
• Thus it can be used to check whether the current script is being run on its own.

7. Write about the steps of Python program executing C++ Program using control statement.

134
Chapter 15 – Data Manipulation through SQL

PART – II
1. Mention the users who uses the Database.

• Users of database can be human users, other programs or applications.

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

• Connecting to a database in step2 means passing the name of the database to be accessed.
• If the database already exists the connection will open the same. Otherwise, Python will open a new
database file with the specified name.
• Cursor in step 3: is a control structure used to traverse and fetch the records of the database.
• Example:-
import sqlite3
connection = [Link] ("[Link]")
cursor = [Link]()

3. What is the advantage of declaring a column as “INTEGER PRIMARY KEY” .

• If a column of a table is declared to be an INTEGER PRIMARY KEY, then whenever a NULL will be used as
an input for this column, the NULL will be automatically converted into an integer which will be one larger
than the highest value so far used in that column.
• If the table is empty, the value 1 will be used.

4. Write the command to populate record in a table. Give an example.

• To populate (add record) the table "INSERT" command is passed to SQLite.


• “execute” method executes the SQL command to perform some action.
• In most cases, we will not literally insert data into a SQL table. We will rather have a lot of data inside of
some Python data type e.g. a dictionary or a list, which has to be used as the input of the insert statement.
• Example:
sql_command = """INSERT INTO Student (Rollno, Sname, Grade, gender, Average, birth_date) VALUES
(NULL, "Akshay", "B", "M","87.8", "2001-12-12");"""
cursor. execute(sql_command)

5. Which method is used to fetch all rows from the database table?

• The fetchall() method is used to fetch all rows from the database table.
• Example:
cursor. execute("SELECT * FROM student")
result = cursor. fetchall( )
for r in result:
print(r)

136
PART – III
1. What is SQLite? What is it advantage?

• SQLite is a simple relational database system, which saves its data in regular data files within internal
memory of the computer.
• It is designed to be embedded in applications, instead of using a separate database server program such
as MySQLor Oracle.
• SQLite is fast, rigorously tested, and flexible, making it easier to work. Python has a native library for SQLite.

2. Mention the difference between fetchone() and fetchmany().

fetchone() fetchmany()
fetchone() method retrieves one fetchmany() method retrieves
row from the result set. multiple rows form a query
result set.
It returns the next row of a query It returns the next number of
result set or if there are no more rows (n) of the result set.
rows to fetch it returns None.
Example: Example:
result = [Link]() result = [Link](3)

3. What is the use of Where Clause. Give a python statement Using the where clause.

• The WHERE clause is used to extract only those records that fulfill a specified condition.

• Example: To display the different grades scored by male students from “student table”.
import sqlite3
connection = [Link]("[Link]")
cursor = connection. cursor()
cursor. execute("SELECT DISTINCT (Grade) FROM student WHERE gender='M'")
result = cursor. fetchall()
print(*result, sep="\n")

OUTPUT
('B',)
('A',)
('C',)
('D',)

4. Read the following details. Based on that write a python script to display department wise records

database name :- [Link]


Table name :- Employee
Columns in the table :- Eno, EmpName, Esal, Dept

137
import sqlite3
connection = [Link](“[Link]”)
cursor = connection. execute (“SELECT * FROM Employee GROUP BY Dept”)
result = cursor. fetchall( )
print(result)

Output:
(1006, ‘John’, 5000, ’CS’)
(1008, ‘Sam’, 6500, ‘CS’)
(1127, ’Vijay’, 10,000, ’IT’ )

5. Read the following details. Based on that write a python script to display records in descending order of
Eno.

database name :- [Link]


Table name :- Employee
Columns in the table :- Eno, EmpName, Esal, Dept

import sqlite3
connection = [Link](“[Link]”)
cursor = connection. cursor( )
cursor. execute(“SELECT * FROM Employee ORDER BY Eno DESC”)
result = cursor. fetchall( )
print(result)

Output:
(1127, ‘Vijay’, 10,000, ‘IT’)
(1008, ‘Sam’, 6500, ‘CS’)
(1006, ‘John’, 5000, ‘CS’)
PART – IV
1. Write in brief about SQLite and the steps used to use it.

• SQLite is a simple relational database system, which saves its data in regular data files within internal
memory of the computer.
• It is designed to be embedded in applications, instead of using a separate database server program such
as MySQLor Oracle.
• SQLite is fast, rigorously tested, and flexible, making it easier to work. Python has a native library for SQLite.

138
• Connecting to a database in step2 means passing the name of the database to be accessed.
• If the database already exists the connection will open the same. Otherwise, Python will open a new
database file with the specified name.
• Cursor in step 3: is a control structure used to traverse and fetch the records of the database.
• To create a table in the database, create an object and write the SQL command in it.
Example:- sql_comm = "SQL statement".
• For executing the command use the cursor method and pass the required sql command as a parameter.
• Many number of commands can be stored in the sql_comm and can be executed one after other.
• Any changes made in the values of the record should be saved by the commend "Commit" before closing
the "Table connection".

• Example:-
import sqlite3
connection = [Link] ("[Link]")
cursor = [Link]()
2. Write the Python script to display all the records of the following table using fetchmany().

Assume the database name as “[Link]” and table name as “electronics”.

CODING:-

import sqlite3
connection = [Link] (” shop. db”)
cursor = connection. cursor()
cursor. execute (“SELECT * FROM electronics “)
print (“Fetching all 5 records :”)
result = cursor. fetchmany(5)
print(*result, sep= ” \n”)

139
OUTPUT:-

Fetching all 5 records :


(1003, ’Scanner’ ,10500)
(1004, ’Speaker’ ,3000)
(1005, ’Printer’ ,8000)
(1008, ’Monitor’ ,15000)
(1010, ’Mouse’ ,700)

3. What is the use of HAVING clause. Give an example python script.

• Having clause is used to filter data based on the group functions.


• This is similar to WHERE condition but can be used only with group functions.
• Group functions cannot be used in WHERE Clause but can be used in HAVING clause.
Example:

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 :-

CODING:
import sqlite3
connection = sqlite3 . connect (“[Link]”)
cursor = connection. cursor ()
sql_command = ” ” ” CREATE TABLE Item (Icode INTEGER, Item_Name VARCHAR (25), Rate Integer); ” ‘” ”
cursor. execute (sql_command)
sql_command = ” ” “INSERT INTO Item (Icode, Item_name, Rate) VALUES (1008, “Monitor”, “15000”);” ” ”
cursor. execute (sql_command)

140
connection. commit ()
print (“TABLE CREATED”)

cursor. execute (“SELECT * FROM Item”)


result=cursor. fetchall()
print(“Displaying the table content:-”)
print(*result, sep=”\n”)

Output:
TABLE CREATED

Displaying the table content: -


(1008, ‘Monitor’, 15000)

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

i) Display Name, City and Itemname of suppliers who do not reside in Delhi.
ii) Increment the SuppQty of Akila by 40

i) Display Name, City and Itemname of suppliers who do not reside in Delhi:

Coding:

import sqlite3
connection = sqlite3. connect (“[Link]”)
cursor = connection. cursor ()
cursor. execute (“SELECT SUPPLIER. Name, [Link], Item. ItemName FROM Supplier, Item WHERE
Supplier. Icode = Item. Icode AND Supplier. City NOT IN “Delhi”)
result = cursor. fetchall( )
print(” Suppliers who do not reside in Delhi:”)
for r in result:
print(r)

141
Output:

Suppliers who do not reside in Delhi:


(‘Anu’, ‘Bangalore’ , ‘Mouse’)
(‘Shahid’, ’Bangalore, ’Monitor’)
(‘Akila’, ‘Hydrabad’, ’Printer’)
(‘Girish’, ‘Hydrabad’, ‘Scanner’)
(‘Shylaja’, ‘Chennai’, ‘Monitor’)
(‘Lavanya’, ‘Mumbai’, ‘Printer’)

ii) Increment the SuppQty of Akila by 40

Coding:

import sqlite3
connection = sqlite3. Connection(“[Link]”)
cursor = connection. cursor ()
cursor. execute (“UPDATE Supplier SET SuppQty = SuppQty + 40 WHERE Name= ”Akila” ”)
result = cursor. fetchall()
print (“Records after SuppQty increment:”)
for r in result:
print(r)

Output:

Records after SuppQty increment:


(‘S001′, ‘Prasad’, ‘Delhi’, 1008,100)
(‘S002′, ’Anu’, ‘Bangalore’, 1010, 200)
(‘S003′, ‘Shahid’, ‘Bangalore’, 1008,175)
(‘S004’, ‘Akila’, ‘Hydrabad’, 1005, 235)
(‘S005′, ‘Girish’, ‘Hydrabad’, 1003, 25)
(‘S006′, ‘Shylaja’, ‘Chennai’, 1008, 180)
(‘S007′, ’Lavanya’, ’Mumbai’, 1005, 325)

ADDITIONAL QUESTIONS:
1. What is a cursor in SQL and databases?

• A cursor in SQL and databases is a control structure to traverse over the records in a database.
• So, it's used for the fetching of the results.
• The cursor object is created by calling the cursor() method of connection.

2. What is the reason behind defining a SQL command with triple quotes?

• The reason behind the triple quotes is sometime the values in the table might contain single or double
quotes.

142
3. Compare fetchall(), fetchone() and fetchmany() method.

[Link]() method is used to fetch all rows from the database table.

[Link]() method returns the next row of a query result set or None in case there is no row left.

[Link]() method returns the next number of rows (n) of the result set.

4. What is the meaning of * symbol and sep?

• symbol is used to print the list of all elements in a single line with space.
• To print all elements in new lines or separated by space use sep= "\n" or sep= "," respectively

5. List the clauses used in SQL.

• SQL provides various clauses that can be used in the SELECT statements.
• The clauses can be called through python script.
• DISTINCT
• WHERE
• GROUP BY
• ORDER BY
• HAVING

6. Write a note on ORDER BY clause.

• The ORDER BY Clause can be used along with the SELECT statement to sort the data of specific fields in an
ordered way.
• It is used to sort the result-set in ascending or descending order.
• For example, Name and Rollno of the students can be displayed in alphabetical order of names.

7. What is the use of AND, OR and NOT operators combined with WHERE clause?

• The WHERE clause can be combined with AND, OR, and NOT operators.
• The AND and OR operators are used to filter records based on more than one condition.
• For example, we can display the details of students who have scored other than ‘A’ or ‘B’ from the “student
table”

8. What are Aggregate functions and define them.

(Refer TB and learn the detailed explanations along with suitable examples for 5 marks)

• Aggregate functions are used to do operations from the values of the column and a single value is returned.

• The COUNT() function returns the number of rows in a table satisfying the criteria specified in the WHERE
clause. COUNT() returns 0 if there were no matching rows.
• The AVG() function retrieves the average of a selected column of rows in a table.
• The SUM() function retrieves the sum of a selected column of rows in a table.

143
• The MAX() function returns the largest value of the selected column.
• The MIN() function returns the smallest value of the selected column.

9. Define a master table.

• The master table holds the key information about the database tables and it is called sqlite_master.

10. What is the purpose of using cursor. description?

• cursor. description contain the details of each column headings.


• It will be stored as a tuple and the first one that is 0(zero) index refers to the column name.
• From index 1 onwards the values of the column (Records) are referred.
• Using this command we can display the table’s Field names.

144
Chapter 16 – Date Visualization Using PYPLOT:
Line Chart, Pie Chart and Bar Chart

145
146
PART – II
1. What is Data Visualization?

• Data Visualization is the graphical representation of information and data.


• The objective of Data Visualization is to communicate information visually to users. For this, data
visualization uses statistical graphics.
• Numerical data may be encoded using dots, lines, or bars, to visually communicate a quantitative message

2. List the general types of data visualization.

• General types of Data Visualization are:-


• Charts
• Tables
• Graphs
• Maps
• Infographics
• Dashboards

3. List the types of Visualizations in Matplotlib.

• There are many types of Visualizations under Matplotlib. Some of them are:
• Line plot
• Scatter plot
• Histogram
• Box plot
• Bar chart and
• Pie chart

4. How will you install Matplotlib?

• Matplotlib can be installed using Pip.


• Pip is a Package manager software for installing python packages.
• We can install the latest version of pip from our command prompt using the following command:
Python -m pip install -U pip
• After installing Matplotlib, we will begin coding by importing Matplotlib using the command:
import matplotlib. pyplot as plt

5. Write the difference between the following functions: [Link]([1,2,3,4]), plt. plot([1,2,3,4], [1,4,9,16]).

[Link]([I,2,3,4]) [Link]([I,2,3,4],[1,4,9,16])

1 In [Link]([1,2,3,4]) a single list or array is In [Link]([1,2,3,4],[l,4,9,16]) the first


provided to the plot() command. two parameters are ‘x’ and ‘y’
coordinates.

147
2 matplotlib assumes it is a sequence of y This means, we have 4 co-ordinates
values, and automatically generates the x according to these list as (1,1), (2,4),
values. (3,9) and (4,16).

3 Since python ranges start with 0, the


default x vector has the same length as y
but starts with 0. Hence the x data are
[0,1,2,3].

PART – III
1. Draw the output for the following data visualization plot.
import [Link] as plt
[Link]([1,3,5,7,9],[5,2,7,8,2], label="Example one")
[Link]([2,4,6,8,10],[8,6,2,5,6], label="Example two", color='g')
[Link]()
[Link]('bar number')
[Link]('bar height')
[Link]('Epic Graph\nAnother Line! Whoa')
[Link]()

2. Write any three uses of data visualization.

• Data Visualization help users to analyze and interpret the data easily.
• It makes complex data understandable and usable.

148
• Various Charts in Data Visualization helps to show relationship in the data for one or more variables.

3. Write the plot for the following pie chart output.

149
PART – IV
1. Explain in detail the types of pyplots using Matplotlib.

Line Chart:

• A Line Chart or Line Graph is a type of chart which displays


information as a series of data points called ‘markers’
connected by straight line segments.
• A Line Chart is often used to visualize a trend in data over
intervals of time – a time series – thus the line is often
drawn chronologically.

Bar Chart:

• A BarPlot (or BarChart) is one of the most common types of plots.


• It shows the relationship between a numerical data and a categorical value.
• Bar chart represents categorical data with rectangular bars.
• Each bar has a height corresponds to the value it represents.
• The bars can be plotted vertically or horizontally.
• It’s useful when we want to compare a given numeric value on
different categories.
• To make a bar chart with Matplotlib, we can use the [Link]()
function.

Pie Chart:

• Pie Chart is probably one of the most common type of chart.


• It is a circular graphic which is divided into slices to illustrate numerical proportion.
• The point of a pie chart is to show the relationship of parts out of a whole.
• To make a Pie Chart with Matplotlib, we can use the [Link]() function.
• The autopct parameter allows us to display the percentage value using the Python string formatting.

Example:

150
2. Explain the various buttons in a matplotlib window.

• Home Button → The Home Button will help once you have begun navigating your chart. If you ever want to
return back to the original view, you can click on this.
• Forward/Back buttons → These buttons can be used like the Forward and Back buttons in your browser.
You can click these to move back to the previous point you were at, or forward again.
• Pan Axis → This cross-looking button allows you to click it, and then click and drag your graph around.
• Zoom → The Zoom button lets you click on it, then click and drag a square that you would like to zoom into
specifically. Zooming in will require a left click and drag. You can alternatively zoom out with a right click
and drag.
• Configure Subplots → This button allows you to configure various spacing options with your figure and
plot.
• Save Figure → This button will allow you to save your figure in various forms.

3. Explain the purpose of the following functions:

a. [Link] - [Link] Specifies label for X -axis

b. [Link] - [Link] is used to specify label for y-axis

c. [Link] - [Link] is used to specify title to the graph or assigns the plot title.

d. [Link]() - [Link]() is used to invoke the default legend with plt.

e. [Link]() – [Link]() is used to display the plot.

4. Write the key Differences Between Histogram and Bar Graph.

1. Histogram refers to a graphical representation; that displays data by way of bars to show the frequency of
numerical data. A bar graph is a pictorial representation of data that uses bars to compare different categories of
data.

2. A histogram represents the frequency distribution of continuous variables. Conversely, a bar graph is a
diagrammatic comparison of discrete variables.

3. Histogram presents numerical data whereas bar graph shows categorical data.
151
4. The histogram is drawn in such a way that there is no gap between the bars. On the ot her hand, there is proper
spacing between bars in a bar graph that indicates discontinuity.

5. Items of the histogram are numbers, which are categorised together, to represent ranges of data. As opposed to
the bar graph, items are considered as individual entities.

6. In the case of a bar graph, it is quite common to rearrange the blocks, from highest to lowest. But with histogram,
this cannot be done, as they are shown in the sequence of classes.

7. The width of rectangular blocks in a histogram may or may not be same while the width of the bars in a bar graph
is always same.

152

You might also like