Computer Science Functions Study Guide
Computer Science Functions Study Guide
Computer Science
Chapters 1 to 16
Study Material
1
Chapter 1 - Function
2
PART-II
1. What is a subroutine?
• 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
• 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.
• 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.
• 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
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.
• 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
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( )
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.
• 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.
• 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
4. What are the different ways to access the elements of a list. Give 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
• 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.
• 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.
3. What is Mapping?
• 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.
• 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.
22
Chapter 4 – Algorithmic Strategies
23
PART-II
1. What is an Algorithm?
• 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.
• Input
• Output
• Finiteness
• Definiteness
• Effectiveness
• Correctness
• Simplicity
• Unambiguous
• Feasibility
• Portable
• Independent
• 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.
PART - IV
1. Explain the characteristics of an 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.
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.
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?
• 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.
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.
• 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.
• 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:
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.
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.
• An arithmetic operator is a
mathematical operator that takes
two operands and performs a
calculation on them.
• They are used for simple
arithmetic.
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:
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.
• 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’)
• 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
Output:
48
4. Write the syntax of while loop.
• Syntax: Example:
while <condition>:
statements block 1
[else:
statements block2]
Additional Questions:
6. Write a note on parameters used with print function.
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
• 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 ……………..
………………………………………
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.
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.
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.
• 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.
• 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:
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
• 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:
• 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:
Recursion functions:
60
• 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:
Global Scope:
62
4. Write a Python code to find the L.C.M. of two numbers.
63
Output:
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?
• Python will not allow deleting a particular character in a string, whereas we can remove entire
string variable using del command.
• Example:
5. What is slicing?
• 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( )
Output:
weol
70
• Example:
Additional Questions:
6. Write a note on replace( ) function. Give an example.
• 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 (+)
• Example:
>>> "welcome" + "Python"
'welcomePython'
(ii) Append (+ =)
• 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 [ ]
• 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?
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
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)
• 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']
[ 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]()
• 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.
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:
• 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:
• 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++.
• 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 =.
• 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]( )
• List comprehension is a simplest way of creating sequence of elements that satisfy a certain condition.
• Syntax: List = [ expression for variable in range ]
• Example:
• 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
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:
• 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:
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:
• 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.
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.
• 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?
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( )
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'
• 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?
• 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?
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.
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:
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:
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
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?
• 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.
• 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.
• 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:
• 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.
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:-
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:-
• 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.
100
101
3. Differentiate DBMS and RDBMS.
102
DIFFERENCE (−)
CARTESIAN PRODUCT (X )
SELECT (symbol : σ)
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 :∪)
Result:
• 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:
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.
4. Which component of SQL lets insert values in tables and which lets to create a table?
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.
• 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.
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;
• 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;
• 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
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.
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.
• 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
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 :
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)
);
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.
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;
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.
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.
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.
• 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:
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:
METHOD 2:
• 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.
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 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.
119
PART – IV
1. Differentiate Excel file and CSV file.
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:
• 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:
We can write the CSV file with custom quote characters, by registering new dialects using csv.register_dialect()
class of csv module.
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?
• 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.
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.
• 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.
127
PART – III
1. Differentiate PYTHON and C++.
• 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.
PART – IV
1. Write any 5 features of Python.
[Link]:
• 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:
• 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:
#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]
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.
• 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.
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]()
• 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.
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.
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
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.
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().
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:-
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”)
Output:
TABLE CREATED
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:
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:
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.
• 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
• 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
• 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”
(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.
• The master table holds the key information about the database tables and it is called sqlite_master.
144
Chapter 16 – Date Visualization Using PYPLOT:
Line Chart, Pie Chart and Bar Chart
145
146
PART – II
1. What is Data Visualization?
• There are many types of Visualizations under Matplotlib. Some of them are:
• Line plot
• Scatter plot
• Histogram
• Box plot
• Bar chart and
• Pie chart
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])
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).
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]()
• 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.
149
PART – IV
1. Explain in detail the types of pyplots using Matplotlib.
Line Chart:
Bar Chart:
Pie Chart:
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.
c. [Link] - [Link] is used to specify title to the graph or assigns the plot title.
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