What Happens If You Modify A Variable Outside The Function? Give An Example
What Happens If You Modify A Variable Outside The Function? Give An Example
in
The return value of the pure functions The return value of the impure
solely depends on its arguments functions does not solely depend on
passed. its arguments passed.
They do not modify the arguments They may modify the arguments
which are passed to them. which are passed.
5. What happens if you modify a variable outside the function? Give an example.
Modifying the variable outside of function causes side effect.
Example:
Here, the result of inc() will change every time if the value of „y‟ get changed inside the function
definition.
Hence, the side effect of inc () function is changing the data of the external variable „y‟.
Section - D
Answer the following questions: (5 Marks)
1. What are called Parameters and write a note on
(i) Parameter without Type (ii) Parameter with Type
Answer:
Parameters are the variables in a function definition
Arguments are the values which are passed to a function definition.
Two types of parameter passing are,
1. Parameter Without Type
2. Parameter With Type
5
1. Parameter Without Type:
Lets see an example of a function definition of Parameter Without Type:
(requires: b>=0 )
(returns: a to the power of b)
let rec pow a b:=
if b=0 then 1
else a * pow a (b-1)
In the above function definition variable „ b‟ is the parameter and the value passed to the
variable „b‟ is the argument.
We have not mentioned any types: (data types). This is called parameter without type.
In the above function definition the expression has type „int‟, so the function's return type also be
„int‟ by implicit.
2. Parameter With Type:
Now let us write the same function definition with types,
In this example we have explicitly annotating the types of argument and return type as „int‟.
Here, when we write the type annotations for „a‟ and „b‟ the parantheses are mandatory.
This is the way passing parameter with type which helps the compiler to easily infer them.
2. Identify in the following program
let rec gcd a b :=
if b <> 0 then gcd b (a mod b) else return a
i) Name of the function
6
ii) Identify the statement which tells it is a recursive function
let rec gcd a b :=
“rec” keyword tells the compiler it is a recursive function
iii) Name of the argument variable
„a‟ and „b‟
iv) Statement which invoke the function recursively
gcd b (a mod b)
v) Statement which terminates the recursion
return a
3. Explain with example Pure and impure functions.
Pure functions will give exact result Impure functions never assure you
when the same arguments are passed. that the function will behave the same
every time it‟s called.
Pure function does not cause any side Impure function causes side effects to
effects to its output. its output.
The return value of the pure functions The return value of the impure
solely depends on its arguments functions does not solely depend on
passed. its arguments passed.
They do not modify the arguments They may modify the arguments
which are passed to them which are passed.
If we call pure functions with same set If we call impure functions with same
of arguments, we will always get the set of arguments, we might get the
same return values. different return values.
The person who drives the car doesn't care about the internal working.
To increase the speed of the car he just presses the accelerator to get the desired behaviour.
8
Here the accelerator is the interface between the driver (the calling / invoking object) and the engine
(the called object).
In this case, the function call would be Speed (70): This is the interface.
Internally, the engine of the car is doing all the things.
It's where fuel, air, pressure, 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.
PREPARED BY
9
www.nammakalvi.in
Section - D
Answer the following questions: (5 Marks)
1. How will you facilitate data abstraction. Explain it with suitable example.
Data abstraction is supported by defining an abstract data type (ADT), which is a collection of
constructors and selectors.
To facilitate data abstraction, you will need to create two types of functions:
Constructors
Selectors
a) Constructor:
Constructors are functions that build the abstract data type.
Constructors create an object, bundling together different pieces of information.
For example, say you have an abstract data type called city.
13
This city object will hold the city‟s name, and its latitude and longitude.
To create a city object, you‟d use a function like city = makecity (name, lat, lon).
Here makecity (name, lat, lon) is the constructor which creates the object city.
b) Selectors:
Selectors are functions that retrieve information from the data type.
Selectors extract individual pieces of information from the object.
To extract the information of a city object, you would use functions like
getname(city)
getlat(city)
getlon(city)
These 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:
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.
The elements of a list can be accessed in two ways.
1. Multiple Assignment:
Which unpacks a list into its elements and binds each element to a different name.
14
Example:
lst := [10, 20]
x, y := lst
15
www.nammakalvi.in
The class (structure) construct defines the form for multi-part objects that represent a person.
Person is referred to as a class or a type, while p1 is referred to as an object or an instance.
Using class you can create many objects of that type.
Class defines a data abstraction by grouping related data items.
A class as bundled data and the functions that work on that data that is using class we can access
multi-part items.
PREPARED BY
J. BASKARAN M.Sc., B.Ed. (C.S) J. ILAKKIA M.Sc., M.Phil., B.Ed. (C.S)
[email protected] [email protected]
Puducherry. Puducherry.
16
Section - D
Answer the following questions: (5 Marks)
1. Explain the types of scopes for variable or LEGB rule with example.
SCOPE:
Scope refers to the visibility of variables, parameters and functions in one part of a program to
another part of the same program.
TYPES OF VARIABLE SCOPE:
Local Scope
Enclosed Scope
Global Scope
Built-in Scope
LEGB RULE:
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).
i) LOCAL SCOPE:
Local scope refers to variables defined in current function.
A function will always look up for a variable name in its local scope.
Only if it does not find it there, the outer scopes are checked.
Example:
21
www.nammakalvi.in
On execution of the above code the variable a displays the value 7, because it is defined and
available in the local scope.
ii) ENCLOSED SCOPE:
A variable which is declared inside a function which contains another function definition with in
it, the inner function can also access the variable of the outer function. This scope is called
enclosed scope.
When a compiler or interpreter searches for a variable in a program, it first search Local, and then
search Enclosing scopes.
In the above example Disp1() is defined within Disp(). The variable „a‟ defined in Disp() can be
even used by Disp1() because it is also a member of Disp().
iii) GLOBAL SCOPE:
A variable which is declared outside of all the functions in a program is known as global variable.
Global variable can be accessed inside or outside of all the functions in a program.
Example:
On execution of the above code the variable a which is defined inside the function displays the
value 7 for the function call Disp() and then it displays 10, because a is defined in global scope.
iv) BUILT-IN-SCOPE:
The built-in scope has all the names that are pre-loaded into the program scope when we start the
compiler or interpreter.
Any variable or module which is defined in the library functions of a programming language has
Built-in or module scope.
22
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.
PREPARED BY
Section - D
Answer the following questions: (5 Marks)
1. Explain the characteristics of an algorithm.
Characteristics Meaning
Input Zero or more quantities to be supplied.
Output At least one quantity is produced.
Finiteness Algorithms must terminate after finite number of steps.
Definiteness All operations should be well defined.
Effectiveness Every instruction must be carried out effectively.
Correctness The algorithms should be error free.
Simplicity Easy to implement.
Algorithm should be clear and unambiguous. Each of its steps should be clear
Unambiguous
and must lead to only one meaning.
Feasibility Should be feasible with the available resources.
An algorithm should be generic, independent and able to handle all range of
Portable
inputs.
An algorithm should have step-by-step directions, which should be independent
Independent
of any programming code.
Pseudo code:
1. Traverse the array using for loop
2. In every iteration, compare the target search key value with the current value of the list.
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. If no match is found, display the
search element not found.
3. If no match is found, display the search element not found.
Example:
To search the number 25 in the array given below, linear search will go step by step in a
sequential order starting from the first element in the given array.
if the search element is found that index is returned otherwise the search is continued till the last
index of the array.
In this example number 25 is found at index number 3.
index 0 1 2 3 4
values 10 12 20 25 30
Snippet:
Input: values[]={10,12,20,25,30}
Target=25
Output:
3
28
2. When a match is found, display success message with the index of the element matched.
The array is being sorted in the given example and it is suitable to do the binary search
algorithm.
Let us assume that the search element is 60 and we need to search the location or index of
search element 60 using binary search.
First, we find index of middle element of the array by using this formula :
Compare the value stored at index 4 with target value, which is not match with search element.
As the search value 60 > 50.
Now we change our search range low to mid + 1 and find the new mid value as index 7.
Element not found because the value in index 7 is greater than search value . ( 80 > 60)
So, the search element must be in the lower part from the current mid value location
Now we change our search range low to mid - 1 and find the new mid value as index 5
29
Now we compare the value stored at location 5 with our search element.
We found that it is a match.
It compares each pair of adjacent elements and swaps them if they are in the unsorted order.
This comparison and passed to be continued until no swaps are needed, which shows the values
in an array is sorted.
It is named so becase, the smaller elements "bubble" to the top of the list.
It is too slow and less efficient when compared to other sorting methods.
Pseudo code
1. Start with the first element i.e., index = 0, compare the current element with the next element of the
array.
2. If the current element is greater than the next element of the array, swap them.
If the current element is less than the next or right side of the element, move to the next element.
Go to Step 1 and repeat until end of the index is reached.
Example:
Consider an array with values {15, 11, 16, 12, 14, 13}
Below, we have a pictorial representation of how bubble sort.
30
www.nammakalvi.in
PREPARED BY
35
Once the Python Scripts is created, they are reusable , it can be executed again and again without
retyping.
The Scripts are editable.
(i) Creating Scripts in Python
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.
3. Type the code in Script editor as given below,
To correct the errors, go back to Script editor, make corrections, save the file and execute it
again.
(3) For all error free code, the output will appear in the IDLE window of Python as shown in Figure.
36
www.nammakalvi.in
The input() function helps to enter data at run time by the user
The output function print() is used to display the result of the program on the screen after
execution.
1) print() function
In Python, the print() function is used to display result on the screen.
Syntax for print():
Example:
2) input() function
In Python, input( ) function is used to accept data as input at run time.
The syntax for input() function is,
“Prompt string” in the syntax is a message to the user, to know what input can be given.
37
If a prompt string is used, it is displayed on the monitor; the user can provide expected data from
the input device.
The input( ) takes typed data from the keyboard and stores in the given variable.
If prompt string is not given in input( ), the user will not know what is to be typed as input.
Example:
In Example 1 input() using prompt string takes proper input and produce relevant output.
In Example 2 input() without using prompt string takes irrelevant input and produce unexpected
output.
So, to make your program more interactive, provide prompt string with input( ).
Input() using Numerical values:
The input ( ) accepts all data as string or characters but not as numbers.
The int( ) function is used to convert string data as integer data explicitly.
Example:
1) Identifiers,
2) Keywords,
3) Operators,
4) Delimiters and
5) Literals.
38
Whitespace separation is necessary between tokens, identifiers or keywords.
1) Identifiers
An Identifier is a name used to identify a variable, function, class, module or object.
An identifier must start with an alphabet (A..Z or a..z) or underscore ( _ ).
Identifiers may contain digits (0 .. 9)
Python identifiers are case sensitive i.e. uppercase and lowercase letters are distinct.
Identifiers must not be a python keyword.
Python does not allow punctuation character such as %,$, @ etc., within identifiers.
Example of valid identifiers: Sum, total_marks, regno, num1
Example of invalid identifiers: 12Name, name$, total-mark, continue
2) Keywords
Keywords are special words used by Python interpreter to recognize the structure of program.
Keywords have specific meaning for interpreter, they cannot be used for any other purpose.
Python Keywords: false, class, If, elif, else, pass, break etc.
3) Operators
Operators are special symbols which represent computations, conditional matching in
programming.
Operators are categorized as Arithmetic, Relational, Logical, Assignment and Conditional.
Value and variables when used with operator are known as operands.
Example:
a=100
b=10
print ("The Sum = ",a+b)
print ("The a > b = ",a>b)
print ("The a > b or a == b = ",a>b or a==b)
a+=10
print(“The a+=10 is =”, a)
Output:
The Sum = 110
The a>b = True
The a > b or a == b = True
The a+=10 is= 110
4) Delimiters
Python uses the symbols and symbol combinations as delimiters in expressions, lists, dictionaries
and strings.
Following are the delimiters.
39
www.nammakalvi.in
5) Literals
Literal is a raw data given in a variable or constant.
In Python, there are various types of literals. They are,
1) Numeric Literals consists of digits and are immutable
2) String literal is a sequence of characters surrounded by quotes.
3) Boolean literal can have any of the two values: True or False.
PREPARED BY
40
5. List the differences between break and continue statements.
break continue
The break statement terminates the loop The Continue statement is used to skip the
containing it. remaining part of a loop and
Control of the program flows to the statement Control of the program flows start with next
immediately after the body of the loop. iteration.
Syntax: Syntax:
break continue
Section - D
Answer the following questions: (5 Marks)
45
www.nammakalvi.in
Example:
for i in range(2,10,2):
print (i,end=' ')
else:
print ("\nEnd of the loop")
Output:
2468
End of the loop
2. Write a detail note on if..else..elif statement with suitable example.
When we need to construct a chain of if statement(s) then „elif‟ clause can be used instead of „else‟.
„elif‟ clause combines if..else-if..else statements to one if..elif…else.
„elif‟ can be considered to be abbreviation of „else if‟.
In an „if‟ statement there is no limit of „elif‟ clause that can be used, but an „else‟ clause if used
should be placed at the end.
Syntax:
if <condition-1>:
statements-block 1
elif <condition-2>:
statements-block 2
else:
statements-block n
46
In the syntax of if..elif..else mentioned above, 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.
Example:
m1=int (input(“Enter mark in first subject : ”))
m2=int (input(“Enter mark in second subject : ”))
avg= (m1+m2)/2
if avg>=80:
print (“Grade : A”)
elif avg>=70 and avg<80:
print (“Grade : B”)
elif avg>=60 and avg<70:
print (“Grade : C”)
elif avg>=50 and avg<60:
print (“Grade : D”)
else:
print (“Grade : E”)
Output :
Enter mark in first subject : 34
Enter mark in second subject : 78
Grade : D
3. Write a program to display all 3 digit odd numbers.
CODE:
lower=int(input("Enter the lower limit for the range:"))
upper=int(input("Enter the upper limit for the range:"))
for i in range(lower,upper+1):
if(i%2!=0):
print(i,end=" ")
47
Output:
PREPARED BY
48
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.
For example, if we wish to take a numeric value as a input from the user, we take the input string
from the user using the function input() and apply eval() function to evaluate its value.
2. If the base condition is met then the program gives meaningful output and exits.
3. Otherwise, function does some required processing and then calls itself to continue recursion.
Function blocks begin with the keyword “def” followed by function name and parenthesis ().
Any input parameters should be placed within these parentheses.
The code block always comes after a colon (:) and is indented.
The statement “return [expression]” exits a function, and it is optional.
A “return” with no arguments is the same as return None.
Section - D
Answer the following questions: (5 Marks)
53
i) BUILT-IN FUNCTION:
Built-in functions are Functions that are inbuilt with in Python.
print(), echo() are some built-in function.
ii) USER DEFINED FUNCTION:
Functions defined by the users themselves are called user defined function.
Functions must be defined, to create and use certain functionality.
Function blocks begin with the keyword “def ” followed by function name and parenthesis ().
When defining functions there are multiple things that need to be noted;
Function blocks begin with the keyword “def” followed by function name and parenthesis ().
Any input parameters should be placed within these parentheses.
The code block always comes after a colon (:) and is indented.
The statement “return [expression]” exits a function, and it is optional.
A “return” with no arguments is the same as return None.
EXAMPLE:
def area(w,h):
return w * h
print (area (3,5))
iii) LAMBDA FUNCTION:
In Python, anonymous function is a function that is defined without a name.
While normal functions are defined using the def keyword, in Python anonymous functions are
defined using the lambda keyword.
Hence, anonymous functions are also called as lambda functions.
USE OF LAMBDA OR ANONYMOUS FUNCTION:
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().
EXAMPLE:
sum = lambda arg1, arg2: arg1 + arg2
print ('The Sum is :', sum(30,40))
54
www.nammakalvi.in
Output:
The Sum is : 70
The Sum is : 10
iv) RECURSIVE FUNCTION:
Functions that calls itself is known as recursive.
Overview of how recursive function works
1. Recursive function is called by some external code.
2. If the base condition is met then the program gives meaningful output and exits.
3. Otherwise, function does some required processing and then calls itself to continue recursion.
2. Explain the scope of variables with an example.
Scope of variable refers to the part of the program, where it is accessible, i.e., area where you can
refer (use) it.
We can say that scope holds the current set of variables and their values.
There are two types of scopes - local scope and global scope.
Local Scope:
A variable declared inside the function's body or in the local scope is known as local variable.
Rules of local variable:
A variable with local scope can be accessed only within the function/block that it is created in.
When a variable is created inside the function/block, the variable becomes local to it.
A local variable only exists while the function is executing.
The formal arguments are also local to function.
Example:
def loc():
y=0 # local scope
print(y)
loc()
Output:
0
55
Global Scope
A variable, with global scope can be used anywhere in the program.
It can be created by defining a variable outside the scope of any function/block.
Rules of global Keyword
The basic rules for global keyword in Python are:
When we define a variable outside a function, it‟s global by default. You don‟t have to use
global keyword.
We use global keyword to read and write a global variable inside a function.
Use of global keyword outside a function has no effect
Use of global Keyword
Without using the global keyword we cannot modify the global variable inside the function but
we can only access the global variable.
Example:
x=0 # global variable
def add():
global x
x=x+5 # increment by 2
print ("Inside add() function x value is :", x)
add()
print ("In main x value is :", x)
Output:
Inside add() function x value is : 5
In main x value is : 5 #value of x changed outside the function
56
3. Explain the following built-in functions.
(a) id() (b) chr() (c) round() (d) type() (e) pow()
57
4. Write a Python code to find the L.C.M. of two numbers.
CODE:
x=int(input("Enter first number:"))
y=int(input("Enter second number:"))
if x>y:
min=x
else:
min=y
while(1):
if((min%x == 0) and (min % y == 0)):
print("LCM is:",min)
break
min=min+1
OUTPUT:
Enter first number:2
Enter second number:3
LCM is: 6
5. Explain recursive function with an example.
Functions that calls itself is known as recursive.
When a function calls itself is known as recursion.
Recursion works like loop but sometimes it makes more sense to use recursion than loop.
Imagine a process would iterate indefinitely if not stopped by some condition is known as infinite
iteration.
The condition that is applied in any recursive function is known as base condition.
A base condition is must in every recursive function otherwise it will continue to execute like an
infinite loop.
Python stops calling recursive function after 1000 calls by default.
So, It also allows you to change the limit using sys.setrecursionlimit (limit_value).
58
www.nammakalvi.in
2. If the base condition is met then the program gives meaningful output and exits.
3. Otherwise, function does some required processing and then calls itself to continue recursion.
EXAMPLE:
def fact(n):
if n == 0:
return 1
else:
return n * fact (n-1)
print (fact (0))
print (fact (5))
Output:
1
120
PREPARED BY
59
OUTPUT:
Number 1: 34
Number 2: 54
The sum of 34 and 54 is 88
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 :
>>> Even_List = list(range(2,11,2))
>>> print(Even_List)
Output: [2, 4, 6, 8, 10]
In the above code, list( ) function takes the result of range( ) as Even_List elements.
Thus, Even_List list has the elements of first five even numbers.
70
www.nammakalvi.in
Output:
('Vinodini', 'XII-F', 98.7)
('Soundarya', 'XII-H', 97.5)
('Tharani', 'XII-F', 95.3)
('Saisri', 'XII-G', 93.8)
4. Explain the different set operations supported by python with suitable example.
A Set is a mutable and an unordered collection of elements without duplicates.
Set Operations:
The set operations such as Union, Intersection, difference and Symmetric difference.
(i) Union:
It includes all elements from two or more sets.
The operator | is used to union of two sets.
The function union( ) is also used to join two sets in python.
Example:
set_A={2,4,6,8}
set_B={'A', 'B', 'C', 'D'}
U_set=set_A|set_B
print(U_set)
Output:
{2, 4, 6, 8, 'A', 'D', 'C', 'B'}
71
(ii) Intersection:
It includes the common elements in two sets.
The operator & is used to intersect two sets in python.
The function intersection( ) is also used to intersect two sets in python.
Example:
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A & set_B)
Output:
{'A', 'D'}
(iii) Difference:
It includes all elements that are in first set (say set A) but not in the second set (say set B).
The minus (-) operator is used to difference set operation in python.
The function difference( ) is also used to difference operation.
Example:
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A - set_B)
Output:
{2, 4}
72
Example:
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A ^ set_B)
Output:
{2, 4, 'B', 'C'}
PREPARED BY
73
5. How do define constructor and destructor in Python?
CONSTRUCTOR:
“init” is a special function begin and end with double underscore in Python act as a Constructor.
Constructor function will automatically executed when an object of a class is created.
General format of constructor:
<statements>
DESTRUCTOR:
Destructor is also a special method gets executed automatically when an object exit from the scope.
In Python, __del__( ) method is used as destructor.
General format of destructor:
def __del__(self):
<statements>
Section - D
Answer the following questions: (5 Marks)
1. Write a menu driven program to add or delete stationary items. You should use dictionary to
store items and the brand.
CODE:
stationary={}
print("\n1. Add Item \n2.Delete item \n3.Exit")
ch=int(input("\nEnter your choice: "))
while(ch==1)or(ch==2):
if(ch==1):
n=int(input("\nEnter the Number of Items to be added in the Dictionary: "))
for i in range(n):
item=input("\nEnter an Item Name: ")
brand=input("\nEnter the Brand Name: ")
stationary[item]=brand
print(stationary)
79
elif(ch==2):
ritem=input("\nEnter the item to be removed from the Dictionary: ")
stationary.pop(ritem)
print(stationary)
ch=int(input("\nEnter your choice: "))
OUTPUT:
PREPARED BY
80
www.nammakalvi.in
Example:
84
iii.) Network Model
85
Example:
1. One-to-One Relationship
2. One-to-Many Relationship
3. Many-to-One Relationship
4. Many-to-Many Relationship
i.) One-to-One Relationship:
In One-to-One Relationship, one entity is related with only one other entity.
One row in a table is linked with only one row in another table and vice versa.
For Example: A student can have only one exam number.
One row in a table A is linked to many rows in a table B, but one row in a table B is linked to
only one row in table A.
For Example: One Department has many staff members.
86
www.nammakalvi.in
4. Many-to-Many Relationship:
A many-to-many relationship occurs when multiple records in a table are associated with
multiple records in another table.
Example: Books and Student :Many Books in a Library are issued to many students.
87
3. Differentiate DBMS and RDBMS.
The SELECT operation is used for selecting a subset with tuples according to a given condition.
Select filters out all tuples that do not satisfy C.
Example: σ = “Big Data” (STUDENT )
course
PROJECT (symbol : Π)
The projection eliminates all attributes of the input relation but those mentioned in the projection
list.
The projection method defines a relation that contains a vertical subset of Relation.
Example: Π (STUDENT)
course
UNION (Symbol :∪) A U B
It includes all tuples that are in tables A or in B.
It also eliminates duplicates.
Set A Union Set B would be expressed as A ∪ B
SET DIFFERENCE ( Symbol : - )
The result of A – B, is a relation which includes all tuples that are in A but not in B.
The attribute name of A has to match with the attribute name in B.
INTERSECTION (symbol : ∩) A ∩ B
Defines a relation consisting of a set of all tuple that are in both in A and B.
However, A and B must be union-compatible.
PRODUCT OR CARTESIAN PRODUCT (Symbol : X )
Cross product is a way of combining two relations.
The resulting relation contains, both relations being combined.
This type of operation is helpful to merge columns from two relations.
A x B means A times B, where the relation A and B have different attributes.
89
www.nammakalvi.in
PREPARED BY
90
www.nammakalvi.in
The SAVEPOINT command is used to temporarily save a transaction so that you can rollback to the
point whenever required.
Syntax: SAVEPOINT savepoint_name;
Example: SAVEPOINT A;
5. Write a SQL statement using DISTINCT keyword.
The DISTINCT keyword is used along with the SELECT command to eliminate duplicate rows in
the table.
This helps to eliminate redundant data.
For Example: SELECT DISTINCT Place FROM Student;
Section - D
Answer the following questions: (5 Marks)
93
For example UNIQUE constraint applied on Admno of student table ensures that no two students
have the same admission number and the constraint can be used as:
In the above example the check constraint is set to Age field where the value of Age must be less
than or equal to 19.
(V) Table Constraint:
When the constraint is applied to a group of fields of the table, it is known as Table constraint.
The table constraint is normally given at the end of the table definition.
Let us take a new table namely Student1 with the following fields Admno, Firstname, Lastname,
Gender, Age, Place:
Example:
CREATE TABLE Student 1
(
Admno integer NOT NULL,
Firstname char(20),
Lastname char(20),
Gender char(1),
Age integer,
Place char(10),
PRIMARY KEY (Firstname, Lastname) → Table constraint
);
In the above example, the two fields, Firstname and Lastname are defined as Primary key which is a
Table constraint.
95
2. Consider the following employee table. Write SQL commands for the qtns.(i) to (v).
96
www.nammakalvi.in
Truncate Remove all records from a table, also release the space occupied by those records.
97
Commit Saves any transaction into the database permanently.
Male 5
Female 3
98
5. Write a SQL statement to create a table for employee having any five fields and create a table
constraint for the employee table.
CREATE TABLE employee
(
empno integer NOT NULL,
name char(20),
desig char(20),
pay integer,
allowance integer,
PRIMARY KEY (empno)
);
PREPARED BY
99
5. What is the difference between reader() and DictReader() function?
Reader():
The reader function is designed to take each line of the file and make a list of all columns.
Using this method one can read data from csv files of different formats like quotes (" "), pipe (|) and
comma (,).
csv. Reader work with list/tuple.
Syntax: csv.reader(fileobject,delimiter,fmtparams)
DictReader():
DictReader works by reading the first line of the CSV and using each comma separated value in this
line as a dictionary key.
DictReader is a class of csv module is used to read a CSV file into a dictionary.
It creates an object which maps data to a dictionary.
csv.DictReader work with dictionary.
Section - D
Answer the following questions: (5 Marks)
1. Differentiate Excel file and CSV file.
Excel CSV
Excel is a binary file that holds information CSV format is a plain text format with a series
about all the worksheets in a file, including of values separated by commas.
both content and formatting.
XLS files can only be read by applications CSV can be opened with any text editor in
that have been especially written to read their Windows like notepad, MS Excel,
format, and can only be written in the same OpenOffice, etc.
way.
Excel is a spreadsheet that saves files into its CSV is a format for saving tabular
own proprietary format viz. xls or xlsx information into a delimited text file with
extension .csv
Excel consumes more memory while Importing CSV files can be much faster, and it
importing data also consumes less memory
104
2. Tabulate the different mode with its meaning.
Mode Description
'r' Open a file for reading. (default)
'w' Open a file for writing. Creates a new file if it does not exist or truncates the
file if it exists.
'x' Open a file for exclusive creation. If the file already exists, the operation fails.
'a' Open for appending at the end of the file without truncating it. Creates a new
file if it does not exist.
't' Opren in text mode. (default)
'b' Open in binary mode.
'+' Open a file for updating (reading and writing)
105
www.nammakalvi.in
OUTPUT:
['SNO', 'NAME', 'CITY']
['12101', 'RAM', 'CHENNAI']
['12102', 'LAVANYA', 'TIRUCHY']
['12103', 'LAKSHMAN', 'MADURAI']
ii) CSV files- data with Spaces at the beginning
Consider the following file “sample2.csv” containing the following data when opened through notepad
The following program read the file through Python using “csv.reader()”.
import csv
csv.register_dialect('myDialect',delimiter = ',',skipinitialspace=True)
F=open('c:\\pyprg\\sample2.csv','r')
reader = csv.reader(F, dialect='myDialect')
for row in reader:
print(row)
F.close()
OUTPUT:
['Topic1', 'Topic2', 'Topic3']
['one', 'two', 'three']
['Example1', 'Example2', 'Example3']
These whitespaces in the data can be removed, by registering new dialects using
csv.register_dialect() class of csv module.
A dialect describes the format of the csv file that is to be read.
In dialects the parameter “skipinitialspace” is used for removing whitespaces after the delimiter.
106
SNO,Quotes
1, "The secret to getting ahead is getting started."
2, "Excellence is a continuous process and not an accident."
The following Program read “quotes.csv” file, where delimiter is comma (,) but the quotes are within
quotes (“ “).
import csv
csv.register_dialect('myDialect',delimiter = ',',quoting=csv.QUOTE_ALL,
skipinitialspace=True)
f=open('c:\\pyprg\\quotes.csv','r')
reader = csv.reader(f, dialect='myDialect')
for row in reader:
print(row)
OUTPUT:
['SNO', 'Quotes']
['1', 'The secret to getting ahead is getting started.']
['2', 'Excellence is a continuous process and not an accident.']
In the following file called “sample4.csv”,each column is separated with | (Pipe symbol)
107
4. Write a Python program to write a CSV File with custom quotes.
import csv
info = [[„SNO‟, „Person‟, „DOB‟],
[„1‟, „Madhu‟, „18/12/2001‟],
[„2‟, „Sowmya‟,‟19/2/1998‟],
[„3‟, „Sangeetha‟,‟20/3/1999‟],
[„4‟, „Eshwar‟, „21/4/2000‟],
[„5‟, „Anand‟, „22/5/2001‟]]
csv.register_dialect(„myDialect‟,quoting=csv.QUOTE_ALL)
with open(„c:\\pyprg\\ch13\\person.csv‟, „w‟) as f:
writer = csv.writer(f, dialect=‟myDialect‟)
for row in info:
writer.writerow(row)
f.close()
OUTPUT :
“SNO”,”Person”,”DOB” ”1”,”Madhu”,”18/12/2001” ”2”,”Sowmya”,”19/2/1998”
”3”,”Sangeetha”,”20/3/1999” ”4”,”Eshwar”,”21/4/2000”
“5”,”Anand”,”22/5/2001”
108
www.nammakalvi.in
2. The last record in the file may or may not have an ending line break.
For example:
3.
There may be an optional header line appearing as the first line of the file with the same format as
normal record lines.
The header will contain names corresponding to the fields in the file and should contain the same
number of fields as the records in the rest of the file.
For example: field_name1,field_name2,field_name3
4.
Within the header and each record, there may be one or more fields, separated by commas.
Spaces are considered part of a field and should not be ignored.
The last field in the record must not be followed by a comma.
For example: Red , Blue
5.
Each field may or may not be enclosed in double quotes.
If fields are not enclosed with double quotes, then double quotes may not appear inside the fields.
For example:
6.
Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-
quotes.
For example:
7.
If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be
preceded with another double quote.
For example:
109
5. What is sys.argv? What does it contain?
sys.argv is the list of command-line arguments passed to the Python program.
argv contains all the items that come along via the command-line input, it's basically an array
holding the command-line arguments of the program.
To use sys.argv, you will first have to import sys.
sys.argv[0] is always the name of the program as it was invoked.
sys.argv[1] is the first argument you pass to the program.
main(sys.argv[1]) :
Accepts the program file (Python program) and the input file (C++ file) as a list(array).
argv[0] contains the Python program which is need not to be passed because by default
__main__ contains source code reference
argv[1] contains the name of the C++ file which is to be processed.
Section - D
Answer the following questions: (5 Marks)
1. Write any 5 features of Python.
Python uses Automatic Garbage Collection.
Python is a dynamically typed language.
Python runs through an interpreter.
Python code tends to be 5 to 10 times shorter than that written in C++.
In Python, there is no need to declare types explicitly.
In Python, a function may accept an argument of any type, and return multiple values without any
kind of declaration beforehand.
2. Explain each word of the following command.
COMMAND: Python <filename.py> -<i> <C++ filename without cpp extension>
Where ,
Python Keyword to execute the Python program from command-line
<filename.py > Name of the Python program to executed
-< i > Input mode
<C++ filename without cpp Name of C++ file to be compiled and executed
extension>
113
3. What is the purpose of sys,os,getopt module in Python. Explain
(i) Python‟s sys Module:
This module provides access to some variables used by the interpreter and to functions that interact
strongly with the interpreter.
sys.argv is the list of command-line arguments passed to the Python program.
argv contains all the items that come along via the command-line input, it's basically an array
holding the command-line arguments of the program.
To use sys.argv, you will first have to import sys.
sys.argv[0] is always the name of the program as it was invoked.
sys.argv[1] is the first argument you pass to the program.
main(sys.argv[1]) :
Accepts the program file (Python program) and the input file (C++ file) as a list(array).
argv[0] contains the Python program which is need not to be passed because by
default__main__ contains source code reference
argv[1] contains the name of the C++ file which is to be processed.
(ii) 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.
os.system(): Execute the C++ compiling command in the shell.
For Example to compile C++ program g++ compiler should be invoked.
Command: os.system („g++‟ + <varaiable_name1> „-<mode>‟ + <variable_name2>
os.system function system() defined in os module
114
www.nammakalvi.in
Example:
os.system('g++ ' + cpp_file + ' -o ' + exe_file) --
g++ compiler compiles the file cpp_file and –o (output) send to exe_file
(iii) Python getopt Module:
The getopt module of Python helps you to parse (split) command-line options and arguments.
This module provides two functions to enable command-line argument parsing.
getopt.getopt method:
This method parses command-line options and parameter list.
Syntax of getopt method:
<opts>,<args>=getopt.getopt(argv, options, [long_options])
Here is the detail of the parameters −
argv -- This is the argument list of values to be parsed (splited). In our program
the complete command will be passed as a list.
options -- This is string of option letters that the Python program recognize as, for
input or for output, with options (like „i‟ or „o‟) that followed by a colon
(:).
Here colon is used to denote the mode.
long_options -- This parameter is passed with a list of strings. Argument of Long options
should be followed by an equal sign ('=').
In our program the C++ file name will be passed as string and „i‟ also will be passed along with
to indicate it as the input file.
getopt() method returns value consisting of two elements.
Each of these values are stored separately in two different list (arrays) opts and args .
Opts contains list of splitted strings like mode, path and args contains any string if at all not splitted
because of wrong path or mode.
args will be an empty array if there is no error in splitting strings by getopt().
115
Example:
opts, args = getopt.getopt (argv, "i:",['ifile='])
where opts contains -- ('-i', 'c:\\pyprg\\p4')]
-i: -- option nothing but mode should be followed by :
'c:\\pyprg\\p4' -- value nothing but the absolute path of C++ file.
In our examples since the entire command line commands are parsed and no leftover argument, the
second argument args will be empty [].
If args is displayed using print() command it displays the output as [].
Example:
>>>print(args)
[]
4. Write the syntax for getopt() and explain its arguments and return values.
Python getopt Module:
The getopt module of Python helps you to parse (split) command-line options and arguments.
This module provides two functions to enable command-line argument parsing.
getopt.getopt method:
This method parses command-line options and parameter list.
Syntax of getopt method:
<opts>,<args>=getopt.getopt(argv, options, [long_options])
Here is the detail of the parameters −
argv -- This is the argument list of values to be parsed (splited). In our program
the complete command will be passed as a list.
options -- This is string of option letters that the Python program recognize as, for
input or for output, with options (like „i‟ or „o‟) that followed by a colon
(:). Here colon is used to denote the mode.
long_options -- This parameter is passed with a list of strings. Argument of Long options
should be followed by an equal sign ('=').
In our program the C++ file name will be passed as string and „i‟ also will be passed along with
to indicate it as the input file.
116
getopt() method returns value consisting of two elements.
Each of these values are stored separately in two different list (arrays) opts and args .
Opts contains list of splitted strings like mode, path and args contains any string if at all not splitted
because of wrong path or mode.
args will be an empty array if there is no error in splitting strings by getopt().
Example:
opts, args = getopt.getopt (argv, "i:",['ifile='])
where opts contains -- ('-i', 'c:\\pyprg\\p4')]
-i: -- option nothing but mode should be followed by :
'c:\\pyprg\\p4' -- value nothing but the absolute path of C++ file.
In our examples since the entire command line commands are parsed and no leftover argument, the
second argument args will be empty [].
If args is displayed using print() command it displays the output as [].
Example:
>>>print(args)
[]
cpp_file = a + '.cpp'
exe_file = a + '.exe'
run(cpp_file, exe_file)
def run(cpp_file, exe_file):
print("Compiling " + cpp_file)
os.system('g++ ' + cpp_file + ' -o ' + exe_file)
print("Running " + exe_file)
print("-----------------------")
print
os.system(exe_file)
print
if __name__ =='__main__': #program starts executing from here
main(sys.argv[1:])
STEPS TO IMPORT CPP CODE INTO PYTHON CODE:
Select File→New in Notepad and type the above Python program.
Save the File as welcome.py.
Click the Run Terminal and open the command window
Go to the folder of Python using cd command.
Type the command: Python c:\pyprg\welcome.py -i c:\pyprg\welcome_cpp
OUTPUT:
------------------------------------------
WELCOME
------------------------------------------
PREPARED BY
J. BASKARAN M.Sc., B.Ed. (C.S) J. ILAKKIA M.Sc., M.Phil., B.Ed. (C.S)
[email protected] [email protected]
118
4. Read the following details.Based on that write a python script to display department wise
records.
database name :- organization.db
Table name :- Employee
Columns in the table :- Eno, EmpName, Esal, Dept
PYTHON SCRIPT:
import sqlite3
connection = sqlite3.connect(“organization.db”)
c=conn.execute(“SELECT * FROM Employee GROUP BY Dept”)
for row in c:
print(row)
conn.close()
5. Read the following details.Based on that write a python script to display records in
desending order of Eno.
database name :- organization.db
Table name :- Employee
Columns in the table :- Eno, EmpName, Esal, Dept
PYTHON SCRIPT:
import sqlite3
connection = sqlite3.connect(“organization.db”)
cursor=connection.cursor()
cursor.execute(“SELECT * FROM Employee ORDER BY Eno DESC”)
result=cursor.fetchall()
print(result)
Section - D
Answer the following questions: (5 Marks)
1. Write in brief about SQLite and the steps used to use it.
SQLite is a simple relational database system, which saves its data in regular data files or even in the
internal memory of the computer.
It is designed to be embedded in applications, instead of using a separate database server program
such as MySQLor Oracle.
122
ADVANTAGES:
SQLite is fast, rigorously tested, and fl exible, making it easier to work.
Python has a native library for SQLite.
Steps To Use SQLite:
Step 1: import sqlite3
Step 2: Create a connection using connect () method and pass the name of the database File
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.
Step 3: Set the cursor object cursor = connection. cursor ()
Cursor is a control structure used to traverse and fetch the records of the database.
Cursor has a major role in working with Python.
All the commands will be executed using cursor object only.
To create a table in the database, create an object and write the SQL command in it.
Example:- sql_comm = "SQL statement"
For executing the command use the cursor method and pass the required sql command as a
parameter.
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".
2. Write the Python script to display all the records of the following table using fetchmany()
123
www.nammakalvi.in
PYTHON SCRIPT:
import sqlite3
connection = sqlite3.connect(“Materials.db”)
cursor=connection.cursor()
cursor.execute(“SELECT * FROM Materials”)
print(“Displaying All The Records”)
result=cursor.fetchmany(5)
print(result, Sep= “\n”)
OUTPUT:
Displaying All The Records
(1003, „Scanner‟, 10500)
(1004, „Speaker‟, 3000)
(1005, „Printer‟, 8000)
(1008, „Monitor‟, 15000)
(1010, „Mouse‟, 700)
3. What is the use of HAVING clause. Give an example python script
Having clause is used to filter data based on the group functions.
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:
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT GENDER,COUNT(GENDER) FROM Student GROUP BY GENDER
HAVING COUNT(GENDER)>3")
result = cursor.fetchall()
co = [i[0] for i in cursor.description]
print(co)
print(result)
124
OUTPUT:
['gender', 'COUNT(GENDER)']
[('M', 5)]
4. Write a Python script to create a table called ITEM with following specification.
Add one record to the table.
Name of the database :- ABC
Name of the table :- Item
Column name and specification :-
Icode :- integer and act as primary key
Item Name :- Item Name :-
Rate :- Integer
Record to be added :- 1008, Monitor,15000
PYTHON SCRIPT:
import sqlite3
connection = sqlite3.connect(“ABC.db”)
cursor=connection.cursor()
sql_command – “““ CREATE TABLE Item(
Icode INTEGER PRIMARY KEY,
ItemName VARCHAR(25),
Rate INTEGER) ; ”””
cursor.execute(sql_command)
sql_command = “““ INSERT INTO Item(Icode, ItemName, Rate) VALUES (1008, „Monitor‟, 15000);
”””
cursor.execute(sql_command)
connection.commit()
connection.close()
print(“TABLE CREATED”)
OUTPUT:
TABLE CREATED
125
5. Consider the following table Supplier and item .Write a python script for (i) to (ii)
SUPPLIER
Suppno Name City Icode SuppQty
S001 Prasad Delhi 1008 100
S002 Anu Bangalore 1010 200
S003 Shahid Bangalore 1008 175
S004 Akila Hydrabad 1005 195
S005 Girish Hydrabad 1003 25
S006 Shylaja Chennai 1008 180
S007 Lavanya Mumbai 1005 325
PYTHON SCRIPT:
i) Display Name, City and Itemname of suppliers who do not reside in Delhi.
import sqlite3
connection = sqlite3.connect(“ABC.db”)
cursor.execute(“SELECT Supplier.Name, Supplier.City,Item.ItemName FROM Supplier,Item
WHERE Supplier.Icode = Item.Icode AND Supplier.City NOT In Delhi ”)
s = [i[0] for I in cursor.description]
print(s)
result = cursor.fetchall()
for r in result:
print r
OUTPUT:
[„Name‟, „City‟, „ItemName‟]
[„Anu‟, „Bangalore‟, „Scanner‟]
[„Shahid‟, „Bangalore‟, „Speaker‟]
[„Akila‟, „Hydrabad‟, „Printer‟]
[„Girish‟, „Hydrabad‟, „Monitor‟]
[„Shylaja‟, „Chennai‟, „Mouse‟]
[„Lavanya‟, „Mumbai‟, „CPU‟]
126
www.nammakalvi.in
import sqlite3
connection = sqlite3.connect(“ABC.db”)
cursor.execute(“UPDATE Supplier ST SuppQty = SuppQty +40 WHERE Name = „Akila‟ ”)
cursor.commit()
result = cursor.fetchall()
print (result)
connection.close()
OUTPUT:
PREPARED BY
127
3. Write the coding for the following:
a. To check if PIP is Installed in your PC.
In command prompt type pip – version.
If it is installed already, you will get version.
Command: Python - m pip install - U pip
132
www.nammakalvi.in
A Line Chart is often used to visualize a trend in data over intervals of time – a time series – thus
the line is often drawn chronologically.
Example:
import matplotlib.pyplot as plt
years = [2014, 2015, 2016, 2017, 2018]
total_populations = [8939007, 8954518, 8960387, 8956741, 8943721]
plt.plot (years, total_populations)
plt.title ("Year vs Population in India")
plt.xlabel ("Year")
plt.ylabel ("Total Population")
plt.show()
In this program,
Plt.title() → specifies title to the graph
Plt.xlabel() → specifies label for X-axis
Plt.ylabel() → specifies label for Y-axis
Output:
Bar Chart:
A BarPlot (or BarChart) is one of the most common type of plot.
It shows the relationship between a numerical variable and a categorical variable.
Bar chart represents categorical data with rectangular 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 plt.bar() function
133
Example:
import matplotlib.pyplot as plt
labels = ["TAMIL", "ENGLISH", "MATHS", "PHYSICS", "CHEMISTRY", "CS"]
usage = [79.8, 67.3, 77.8, 68.4, 70.2, 88.5]
y_positions = range (len(labels))
plt.bar (y_positions, usage)
plt.xticks (y_positions, labels)
plt.ylabel ("RANGE")
plt.title ("MARKS")
plt.show()
Output:
134
Example:
import matplotlib.pyplot as plt
sizes = [89, 80, 90, 100, 75]
labels = ["Tamil", "English", "Maths", "Science", "Social"]
plt.pie (sizes, labels = labels, autopct = "%.2f ")
plt.axes().set_aspect ("equal")
plt.show()
135
Save Figure:
This button will allow you to save your figure in various forms.
www.nammakalvi.in
PREPARED BY
136