Class XII CS Notes All Chapters
Class XII CS Notes All Chapters
Features of Python
• Python is a general purpose, dynamic, high-level, and interpreted programming language.
It supports Object Oriented programming approach to develop applications. It is simple
and easy to learn and provides lots of high-level data structures.
• Python is easy to learn yet powerful and versatile scripting language, which makes it
attractive for Application Development.
• Python's syntax and dynamic typing with its interpreted nature make it an ideal language
for scripting and rapid application development.
• Python supports multiple programming pattern, including object-oriented, imperative, and
functional or procedural programming styles.
• Python is not intended to work in a particular area, such as web programming. That is why
it is known as multipurpose programming language because it can be used with web,
enterprise, 3D CAD, etc.
• We don't need to use data types to declare variable because it is dynamically typed so we
can write a=10 to assign an integer value in an integer variable.
• Python makes the development and debugging fast because there is no compilation step
included in Python development, and edit-test-debug cycle is very fast.
23
• Computer Vision or Image Processing Applications.
• Speech Recognitions
24
Keywords
Python keywords are unique words reserved with defined meanings and functions that we can only
apply for those functions.Python contains thirty-five keywords in the version, Python 3.9.
Identifiers
In programming languages, identifiers are names used to identify a variable, function, or other
entities in a program. The rules for naming an identifier in Python are as follows:
• The name should begin with an uppercase or lowercase alphabet or an underscore sign (_).
• This may be followed by any combination of characters a-z, A-Z, 0-9 or underscore (_).
Thus, an identifier cannot start with a digit.
• It can be of any length. (However, it is preferred to keep it short and meaningful).
• It should not be a keyword or reserved word.
• We cannot use special symbols like !, @, #, $, %, etc. in identifiers.
Legal Identifier Names Example:
Myvar my_var _my_var myVar myvar2
Illegal Identifier Names Example:-
2myvar my-var my var= 9salary
Literals or Values:
Literals are the fixed values or data items used in a source code. Python supports different types
of literals such as:
a. String literals - “Rishaan”
b. Numeric literals – 10, 13.5, 3+5i
c. Boolean literals – True or False
d. Special Literal None
e. Literal collections
Literal collections
Literals collections in python includes list, tuple, dictionary, and sets.
• List: It is a list of elements represented in square brackets with commas in between. These
variables can be of any data type and can be changed as well.
• Tuple: It is also a list of comma-separated elements or values in round brackets. The values
can be of any data type but can’t be changed.
• Dictionary: It is the unordered set of key-value pairs.
• Set: It is the unordered collection of elements in curly braces ‘{}’.
Operators
An operator is used to perform specific mathematical or logical operation on values. The values
that the operator works on are called operands.
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
25
• Identity operators
• Membership operators
• Bitwise operators
Arithmetic operators: used with numeric values to perform common mathematical operations.
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Identity Operators: used to compare the objects, not if they are equal, but if they are actually the
26
same object, with the same memory location.
is Returns True if both variables are the same object x is y
is not Returns True if both variables are not the same object x is not y
Punctuators
Punctuators are symbols that are used in programming languages to organize sentence
structure, and indicate the rhythm and emphasis of expressions, statements, and program
structure. Common punctuators are: „ “ # $ @ []{}=:;(),
Python Variables
Variables are nothing but reserved memory locations to store values. This means that when
you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be
stored in the reserved memory. Therefore, by assigning different data types to variables, you
can store integers, decimals or characters in these variables.
• Variables are containers for storing data values.
• Unlike other programming languages, Python has no command for declaring a variable.
• A variable is created the moment you first assign a value to it.
Example:
x=5
y = "John"
print(x)
print(y)
• Variables do not need to be declared with any particular type and can even change type
after they have been set.
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
• String variables can be declared either by using single or double quotes:
x = "John"
# is the same as
x = 'John'
Output Variable:
The Python print statement is often used to output variables. To combine both text and a variable,
Python uses the, character:
x = "awesome"
27
print("Python is " , x)
Display Multiple variable:-
x = "awesome“
y=56
print(“Value of x and y is=" , x, y)
print (counter)
print (miles)
print (name)
a=b=c=1
a,b,c = 1,2,"john"
Data Types
The data stored in memory can be of many types, i.e., Every value belongs to a specific data type
in Python. Data type identifies the type of data which a variable can hold and the operations that
can be performed on those data.Python has various standard data types that are used to define the
operations possible on them and the storage method for each of them.
28
• String
• List
• Tuple
• Dictionary
• Boolean
• Set
Numbers
Number data types store numeric values. Number objects are created when you assign a value to
them. For example −
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The syntax of
the del statement is −
del var1[,var2[,var3[....,varN]]]]
e.g. del var
del var_a, var_b
Strings
Strings in Python are identified as a contiguous set of characters represented in the quotation
marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken
using the slice operator ([ ] and [:] ).
str = 'Hello World!'
29
print str[2:5] # Prints characters starting from 3rd to 5th llo
print str[2:] # Prints string starting from 3rd character llo World!
print str * 2 # Prints string two times Hello World!Hello World!
print str + "TEST" # Prints concatenated string Hello World!TEST
Lists
Lists are the most versatile of Python's compound data types. A list contains items separated by
commas and enclosed within square brackets ([]).
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at
0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list
concatenation operator, and the asterisk (*) is the repetition operator.
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list # Prints complete list ['abcd', 786, 2.23, 'john', 70.2]
print list[0] # Prints first element of the list- abcd
print list[1:3] # Prints elements starting from 2nd till 3rd - [786, 2.23]
print list[2:] # Prints elements starting from 3rd element -[2.23, 'john', 70.2]
print tinylist * 2 # Prints list two times-[123, 'john', 123, 'john']
print list + tinylist # Prints concatenated lists-['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas. Lists are enclosed in brackets ( [ ] ) and their elements and size can
be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated.
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print tuple # Prints the complete tuple--('abcd', 786, 2.23, 'john', 70.2)
print tuple[0] # Prints first element of the tuple-- abcd
print tuple[1:3] # Prints elements of the tuple starting from 2nd till 3rd--(786, 2.23)
print tuple[2:] # Prints elements of the tuple starting from 3rd element--(2.23, 'john', 70.2)
print tinytuple * 2 # Prints the contents of the tuple twice--(123, 'john', 123, 'john')
print tuple + tinytuple # Prints concatenated tuples-- ('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
Dictionary
Python's dictionaries are kind of hash table type. They consist of key-value pairs. A dictionary key
can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can
be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square
braces ([]). For example −
dict = {}
30
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # Prints value for 'one' key This is one
print dict[2] # Prints value for 2 key This is two
print tinydict # Prints complete dictionary {'dept': 'sales', 'code': 6734, 'name': 'john'}
print tinydict.keys() # Prints all the keys ['dept', 'code', 'name']
print tinydict.values() # Prints all the values ['sales', 6734, 'john']
Boolean
Boolean represent one of two values: True or False. When you compare two values, the expression
is evaluated and Python returns the Boolean answer.Also, almost any value is evaluated to True if
it has some sort of content.
print(10 > 9) True bool(None) False
print(10 == 9) False bool(0) False
print(10 < 9) False bool("") False
bool("abc") True bool(()) False
bool(123) True bool([]) False
bool(["apple", "cherry"]) True bool({}) False
bool(False) False
Mutable objects
Mutability means the ability to modify or edit a value. Mutable objects in Python enable the
programmers to have objects that can change their values. They generally are utilized to store
a collection of data. It can be regarded as something that has mutated, and the internal state applicable
within an object has changed.
31
In mutable data types, we can modify the already existing values of the data types (such as lists,
dictionaries, etc.). Or, we may add new values or remove the existing values from our data types.
Basically, we may perform any operation with our data without having to create a new copy of our
data type. Hence, the value assigned to any variable can be changed.
e.g. color = ["red", "blue", "green"]
print(color) Output:
color[0] = "pink" ['red', 'blue', 'green']
color[-1] = "orange" ['pink', 'blue', 'orange']
print(color)
Immutable Objects
Immutable objects in Python are objects wherein the instances do not change over the period.
Immutable instances of a specific type, once created, do not change, and this can be verified using
the id method of Python
e.g. message = "Welcome to GeeksforGeeks"
message[0] = 'p'
print(message)
Output
Traceback (most recent call last):
File "/home/ff856d3c5411909530c4d328eeca165b.py", line 3, in
message[0] = 'p'
TypeError: 'str' object does not support item assignment
32
Consider a tuple
tup = ([3, 4, 5], 'myname')
The tuple consists of a string and a list. Strings are immutable so we can’t change its value. But the
contents of the list can change. The tuple itself isn’t mutable but contain items that are mutable.
Expression in python:
A combination of constants, operands and operators is called an expression. The expression in
Python produces some value or result after being interpreted by the Python interpreter. The
expression in Python can be considered as a logical line of code that is evaluated to obtain some
result. If there are various operators in an expression then the operators are resolved based on their
precedence.
E.g. Expression 6-3*2+7-1 evaluated as 6
33
# Python automatically converts
# a to int
a=7
print(type(a))
# Python automatically converts
# b to float
b = 3.0
print(type(b))
# Python automatically converts
# c to float as it is a float addition
c=a+b
print(c)
print(type(c))
# Python automatically converts
# d to float as it is a float multiplication
d=a*b
print(d)
print(type(d))
int() : int() function take float or string as an argument and return int type object.
float() : float() function take int or string as an argument and return float type object.
str() : str() function take float or int as an argument and return string type object.
34
Operator Associativity: If an expression contains two or more operators with the same precedence then
Operator Associativity is used to determine. It can either be Left to Right or from Right to Left.
Comments in python:
Comments are non-executable statements of python. It increases the readability and understandability
of code.
Types of comment:
i. Single line comment (#) – comments only single line.
e.g. a=7 # 7 is assigned to variable ‘a’
print(a) # displaying the value stored in ‘a’
35
Using split() method
Using List comprehension
split() method :
This function helps in getting multiple inputs from users. It breaks the given input by the specified
separator. If a separator is not provided then any white space is a separator. Generally, users use a
split() method to split a Python string but one can use it in taking multiple inputs.
input().split(separator, maxsplit)
List comprehension is an elegant way to define and create list in Python. We can create lists just like
mathematical statements in one line only. It is also used in getting multiple inputs from a user.
x, y, z = [int(x) for x in input("Enter three values: ").split()]
value(s) : Any value, and as many as you like. Will be converted to string before printed
sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than
one.Default :’ ‘
end=’end’: (Optional) Specify what to print at the end.Default : ‘\n’
file : (Optional) An object with a write method. Default :sys.stdout
flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False).
Default: False
Debugging:-
Debugging is a process of locating and removing errors from program.
Errors in a program
An error or exception refers to an interruption in the execution of code due to which we cannot attain
the expected outcome to the end-users. These errors are classified on the basis of the event when the
program generate the error. The two types of errors are Compile Time Errors and Runtime Errors
and Logical errors
Selection Statements
Decision making is valuable when something we want to do depends on some user input or some
other value that is not known when we write our program. This is quite often the case and Python,
along with all interesting programming languages, has the ability to compare values and then take
one action or another depending on that outcome.
Python have following types of selection statements
1. if statement
2. if else statement
3. Ladder if else statement (if-elif-else)
4. Nested if statement
if statements
This construct of python program consist of one if condition with one block of statements. When
condition becomes true then executes the block.
Syntax:
37
if ( condition):
Statement(s)
Example:
age=int(input(“Enter Age: “))
if ( age>=18):
print(“You are eligible for vote”)
if(age<0):
print(“You entered Negative Number”)
if - else statements
This construct of python program consist of one if condition with two blocks. When condition
becomes true then executes the block given below
Syntax:
if ( condition):
Statement(s)
else:
Statement(s)
Example
x = int(input("Please enter an integer: "))
y = int(input("Please enter another integer: "))
i f x > y:
print(x,"is greater than",y)
else:
print(y,"is greater than or equal to",x)
i = 20
if (i == 10):
38
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")
Nested-if
Nested if statements mean an if statement inside another if statement.
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Example
The iteration (Looping) constructs mean to execute the block of statements again and again
depending upon the result of condition. This repetition of statements continues till condition meets
True result. As soon as condition meets false result, the iteration stops.
Python supports following types of iteration statements
1. while
2. for
Four Essential parts of Looping:
i. Initialization of control variable
ii. Condition testing with control variable
iii. Body of loop Construct
iv. Increment / decrement in control variable
39
for loop
For loops are useful when you need to do something for every element of a sequence
<statements before for loop>
for <variable> in <sequence>:
<body of for loop>
<statements after for loop>
Example
s = input("Please type some characters and press enter:")
for c in s:
print(c)
print("Done")
while Loop
Python's while statement is its most general iteration construct. In simple terms, it repeatedly
executes a block of indented statements, as long as a test at the top keeps evaluating to a true value.
When the test becomes false, control continues after all the statements in the while, and the body
never runs if the test is false to begin with.
while <test>: # loop test
<statements1> # loop body
else: # optional else
<statements2> # run if didn't exit loop with b
Example
count = 0
while (count < 9):
print ('The count is:', count )
count = count + 1
print ("Good bye!" )
Python supports to have an else statement associated with a loop statement. If the else statement is
used with a for loop, the else statement is executed when the loop has exhausted iterating the list. If
the else statement is used with a while loop, the else statement is executed when the condition
becomes false
Example:
count = 0
while count < 5:
print (count, " is less than 5" )
count = count + 1
else:
print( count, " is not less than 5”)
Single Statement Suites: If there is only one executable statement in while loop, then we can use this
40
format.
Example:
flag = 1
while (flag): print ('Given flag is really true!' )
print( "Good bye!" )
Jump Statements
Now that we‘ve seen a few Python loops in action, it‘s time to take a look at two simple statements that
have a purpose only when nested inside loops—the break and continue statements.
In Python:
pass
Does nothing at all: it‘s an empty statement placeholder
break
Jumps out of the closest enclosing loop (past the entire loop statement)
continue
Jumps to the top of the closest enclosing loop (to the loop‘s header line)
---------------------------------------------------------------------------------------------------------------------
Example
range(5) => sequence of 0,1,2,3,4
range(2,5) => sequence of 2,3,4
range(1,10,2) => sequence of 1,3,5,7,9
range(5,0,-1) => sequence of 5,4,3,2,1
range(0,-5) => sequence of [ ] blank list
(default Step is +1)
range(0,-5,-1) => sequence of 0, -1, -2, -3, -4
range(-5,0,1) => sequence of -5, -4, -3, -2, -1
41
range(-5,1,1) => sequence of -5, -4, -3, -2, -1, 0
42
WORK SHEET
LEVEL-1
Questions
Q.No Marks
43
LEVEL-2
1 D={“AMIT”:90,”RESHMA”:96,”SUMAN”:92} (1)
Print(“SUMAN” in D, 90 in D, sep=”#”)
(a) True#False (b) True#True (c) False#True (d) False#False
Ans : (a) True#False
2 Find and write the output of the following python code: (1)
x = "Welcome"
i = "e"
while i in x:
print(i, end = "$")
Ans :e$e$e$e$e$......
3. What is the output of the following Python statement : print(5+3**2/2) (1)
Ans : 9.5
4. The return type of the input() function is Ans:String (1)
44
else:
print("done")
Ans : n=1 ------ done
n=4 ------- no output
8. What is the output of the following code snippet?
def ChangeVal(M,N):
for i in range(N):
if M[i]%5 == 0:
M[i]//=5
if M[i]%3 == 0:
M[i]//=3
L = [25,8,75,12] (4)
ChangeVal(L,4)
for i in L:
print(i,end="#")
Ans : 5#8#5#4#
LEVEL-3
a) 8 // 4 + 18 * 6 / 3– 3
45
b) 35/5 or 5.0 + 30/10
Ans: a) 35.0
b)7.0
4 Concatenation operator in list is :
(a) * (b) , (c) + (d) = (1)
Ans : +
Find error in the following code(if any) and correct code by rewriting code and underline
the correction;‐
5
x= int(input(“Enter value of x:”) )
for I in range [0,10]:
(2)
if x=y:
print( x + y)
else:
print( x‐y)
Advantages of Functions
• Reducing duplication of code
• Decomposing complex problems into simpler pieces
• Improving clarity of the code
• Reuse of code
• Information hiding
46
• Function defined in modules
• User defined functions.
Built-in functions
The functions whose functionality is predefined in Python are referred to as built-in functions.
The python interpreter has several such functions that are always available for use.
E.g. len(), type(), int(), input()
Function defined in modules
These functions are pre-defined in particular modules and can only be used after the specific
module is imported.
E.g. All mathematical functions are defined in the module math.
User-defined functions
Python User Defined Functions allow users to write unique logic that the user defines. It is
the most important feature in Python that consists of custom-defined logics with a set of rules and
regulations that can be passed over the data frame and used for specific purposes.
Internally Python names the segment with top-level statements (no indentation) as
_main_ Python begins execution of a program from top-level statements.
Defining a Function
A function in Python is defined as given below:
def< function name >(parameters):
[“ ” ”<function’s docstring>” “ “]
<statements>
[<statements>]
……………………..
47
• Keyword def that marks the start of the function header.
• A function name to uniquely identify the function. Function naming follows the same rules
of writing identifiers in Python.
• Parameters (arguments) through which we pass values to a function. They are optional.
• A colon (:) to mark the end of the function header.
• Optional documentation string (docstring) to describe what the function does.
• One or more valid python statements that make up the function body. Statements must have
the same indentation level (usually 4 spaces).
• An optional return statement to return a value from the function.
Function header:
The Header of a function specifies the name of the function and the name of each
of its parameters. It begins with the keyword def.
Parameters:
Variables that are listed within the parenthesis of a function header.
Function Body:
The block of statements to be carried out, ie the action performed by the function.
Indentation:
The blank space needed for the python statements. (four spaces convention)
Whenever a function call statement is encountered, an execution frame for the function is created
and the control is transferred to it. The statements are then executed and if there is return
statement in the program, it will be executed and returns to the function call statement block.
def message():
print('Hello I am learning how to create function in python.')
def sum(a,b):
c=a+b
print('Sum of %d and %d is %d' %(a,b,c))
# main program
# calling the function message()
message()
# calling the function sum()
sum(10,20)
In the above program, two functions message() and sum() is declared. The message() function
does not accept any argument but displays a text on the screen whenever we call it. On the other
hand, the sum() function accept two arguments and display their sum on the screen. when the main
program calls the function message(), the program flow goes to the body of the function message()
and execute its codes. After that, it returns to the main program and then calls the second function
sum() by sending it two arguments (10,20), the program flow goes to the body of the function sum(),
and execute its code and again returns to the main program. At last, the main programs end.
The function calling another function is called the caller and the functions being called
is the called function or callee.
49
Passing parameters:-
Python support three types of formal arguments/parameters:
1. Positional argument (required arguments):-
When the functions call statement must match the number and order of arguments as define
in the functions definition this is called the positional arguments.
Example:-
def check(a,b,c):
:
Then possible functions call for this can be:-
check(x,y,z)#3values(allvariables)passed
check(2,x,y)#3values(literal+variables)passed
check ( 2 , 3 , 4 ) # 3 values ( all literal ) passed.
Thus through such function calls-
• The argument must be provided for all parameters (required)
• The values of argument are matched with parameters, position(order)wise(positional)
2. Default arguments:-
A parameter having defined value in the function header is known as a default parameter.
Example:-
def interest(principal,time,rate=10):
si=interest(5400,2) #third argument missing
So the parameter principal get value 5400,time get 2 and since the third argument rate is missing, so
default value 0.10 is used for rate.
• Default argument are useful in situations where some parameters always have same
value.
Some advantages of the default parameters are listed below:-
50
• They can be used to add new parameters to the existing functions.
• They can be used to combine similar function in to one.
3. Keyword(or named)arguments:-
Keyword arguments are the named arguments with assigned values being passed in the function
call statement.
Example:-
def interest(prin,time,rate):
return prin * time * rate
print (interest ( prin = 2000 , time = 2 , rate 0.10 ))
print (interest ( time = 4 , prin = 2600 , rate = 0.09 ))
print(interest(time=2,rate=0.12,prin=2000))
All the above functions call are valid now, even if the order of arguments does not match.
4. Using multiple argument type together:-
Python allows you to combine multiple argument types in a function call.
Rules for combining all three types of arguments:-
• And argument list must first contain positional(required) arguments followed by any
keyword argument.
• Keyword arguments should be taken from the required arguments preferably.
• You cannot specify a value for an argument more than once.
Example:-
def interest(prin,cc,time=2,rate=0.09):
return prin * time * rate
Types of user defined function
1. No Argument No return
2. With Argument No return
3. No Argument with return
4. With Argument with return
1. No Argument No return
def Add():
a= int (input(“Enter First Number”))
b= int (input(“Enter Second Number”))
c=a+b
print (“The Sum of inputted Numbers is:”, c)
Add()
print(“ Executed”)
Remember: The variable in main program are differ from the variable in function definition i.e. a
and b should be x and y. In this scenario the variable passed (num1,num2)will be called argument,
and when it replace with the variable defined in the function will be called as parameter.
3. No Argument with return
def Add():
a=int (input(“Enter First Number”))
b= int (input(“Enter Second Number”))
c=a+b
return c
x= add()
print (“The Sum of inputted Numbers is:”, x)
Note: { As return does not show the result we have to store the returned value on another
variable x}
4. With Argument with return
def Add (a,b):
c=a+b
return c
a=int (input(“Enter First Number”))
b= int (input(“Enter Second Number”))
x= add(a,b)
print (“The Sum of inputted Numbers is:”, x)
In the example below, the variable name is the input parameter, where as the value, “Arnav”, passed
in the function call is the argument.
def welcome(name):
print("Hello! " + name + " Good Morning!!")
welcome("Arnav")
Output:
Hello! Arnav Good Morning!!
Returning a Function
If you wish to return some values from the function to the rest of the program, you can use
the return statement. As the name suggests, it returns a value without printing it. Executing this
statement will cause the Python function to end immediately and store the value being returned into
a variable.
Scope of variables
Scope means in which part(s) of the program, a particular piece of code or data is accessible
or known.
In python there are broadly 2 kinds of Scopes:
• Global Scope
• Local Scope
Global Scope:
• A name declared in top level segment(_main_) of a program is said to have global scope
and can be used in entire program.
• Variable defined outside of the all functions are global variables.
Local Scope :
• A name declared in a function body is said to have local scope i.e. it can be used only
within this function and the other block inside the function.
• The formal parameters are also having local scope.
When dealing with Python functions, you should also consider the scope of the variables. The
code in a function is in its own little world, separate from the rest of the program. Any variable
declared in the function is ignored by the rest of the function. This means that two variables with the
same name can exist, one inside the function and the other outside the function. However, this is not
a good practice. All variable names must be unique regardless of their scope.
53
Local variable: A variable that is defined within a function and can only be used within that
particular function. With respect to the local variable, the area in a function is called “local area”.
Global variable: A variable that is defined in the main part of the programming and, unlike local
variables, can be accessed via local and global areas.
Example:
Lifetime of Variables:
Lifetime is the time for which a variable lives in memory. For global variables the lifetime is
entire program run i.e. as long as program is executing. For local variable, lifetime is their function’s
run i.e. as long as function is executing.
WORKSHEET
LEVEL I
I. Questions (1 mark)
54
1. Which of the following is the use of function in python?
a) Functions are reusable pieces of programs
b) Functions don’t provide better modularity for your application
c) you can’t also create your own functions
d) All of the mentioned
2. What is the output of the below program?
def printMax(a, b):
if a > b:
print(a, ‘is maximum’)
elif a == b:
print(a, ‘is equal to’, b)
else:
print(b, ‘is maximum’)
printMax(3, 4)
a) 3 b) 4 c) 4 is maximum d) None of the mentioned
3. What is the output of the below program?
x = 50
def func():
global x
print('x is', x)
x=2
print('Changed global x to', x)
func()
print('Value of x is', x)
a) x is 50
Changed global x to 2
Value of x is 50
b) x is 50
Changed global x to 2
Value of x is 2
c) x is 50
Changed global x to 50
Value of x is 50
d) None of the mentioned
def C2F(c):
return c * 9/5 + 32
print (C2F(100))
print (C2F(0))
a) 212.0
32.0
55
b) 314.0
24.0
c) 567.0
98.0
d) None of the mentioned
print(absolute_value(-4))
III. Questions (3 marks)
1. Differentiate ceil() and floor() function?
IV.Questions (5 marks)
57
1. What are the arguments supported by python? Explain each of them with a suitable example.
2. What is the difference between the formal parameters and actual parameters? What are their
alternative names? Also, give a suitable Python code to illustrate both.
ANSWERS
I Answer the following 1 mark
1 A
2 C
3 B
4 A
5 Header
6 _main_
7 False
8 B
9 B
10 B
11 C
12 Random
13 The first function will result in an error because the function sum() is used to
find the sum of iterablenumbers. Hence the outcomes will be Error and
6respectively.
14 The function max() is being used to find themaximum value from among -3,
-4 and false. Since falseamounts to the value zero, hence we are left with
min(0, 2, 7)Hence the output is 0 (false)
15 B
16 A
17 A
18 B
II Answer the following 2 marks
1 2
58
4
59
2 Actual Parameter is a parameter, which is used in function call statement to
send the value from calling function to the called function. It is also known
as Argument.
In the above code, actual parameters are 6, 16 and 26; and formal parameters
are x, y and z.
LEVEL II
IV. Questions (1 mark)
1. Name the Python Library modules which need to be imported to invoke the following
functions :
load ()
pow ()
2. What is the output of the below program ?
x = 50
def func(x):
#print(‘x is’, x)
x=2
#print(‘Changed local x to’, x)
func(x)
print(‘x is now’, x)
a) x is now 50
b) x is now 2
c) x is now 100
d) None of the mentioned
61
14. Predict the output of the following code
def fun3(num1,num2):
for x in range(num1,num2):
if x%4==0:
print(x,end=’ ‘)
fun3(10,20)
A. 10 12 16 20
B. 12 16
C. 12 16 20
2. From the program code given below, identify the parts mentioned below:
def processNumber(x):
x = 72
return x + 3
y = 54
res processNumber(y)
Identify these parts: function header, function call, arguments, parameters
Questions (3 marks)
1. What is a function? Why is it needful?
2. Compute the code. Write the output of the pseudocode.
r=30
t=15
62
def swap(f,g):
f = r+t
g= f - g
g=f-g
print("f=", f,"g=", g)
swap(r,t)
swap(11,3)
swap(t,10)
swap(r,t)
(b)
1.def power (b, p):
2 .r = b ** p
3. return r
4
5. def calcSquare(a):
6. a = power (a, 2)
7. return a
9.n = 5
10. result = calcSquare(n)
11. print (result)
(c)
1. def increment(X):
2. X=X+1
3.
4. # main program
5. X = 3
6. print(x)
7. increment(x)
8. print(x)
63
Questions (5 marks)
1. Differentiate between parameters and arguments.
2. Differentiate between actual parameter(s) and a formal parameter(s) with a suitable example
for each.
ANSWERS
I Answer the following 1 mark
1 pickle
math
2 A
3 C
4 B
5 True
6 Fruitful functions
7 None
8 D
9 C
10 True
11 5.0
12 The function all() returns ‘True’ if any one
or more of the elements of the iterable are non zero. In theabove case, the
values are not iterable, hence an error isthrown.
13 A
14 B
15. C
16 A
2 f= {45} g= {15}
f= {45} g= {3}
f= {45} g= {10}
f= {45} g= {15}
3 (a)1→5→9→10→5→6→1→2→36→7→10→1→2→3→10→11
(b) 1-59→10→56→1→2→36→710→11
(c) 1-5-6-7→1→2→8
65
IV Answer the following 5 marks
1 Parameters Arguments
These are specified during the Values passed during the function
function definition. call.
They are also known as formal They are also known as actual
parameters. parameters.
The values passed as parameters are Every argument is assigned to a
local variables and are assigned parameter when the function is
values of the arguments during the defined.
function call.
These variables help in the These variables are passed to the
complete execution of the function. function for execution.
The values contained by these The arguments are accessible
parameters can only be accessed throughout the program depending
from function return statements or upon the scope of the variable
if the scope of these parameters is assigned.
made global.
2 Actual Parameter is a parameter, which is used in function call statement to
send the value from calling function to the called function. It is also known as
Argument.
In the above code, actual parameters are 6, 16 and 26; and formal parameters
are x, y and z.
LEVEL III
I Questions (1 mark)
66
1. Which keyword is used for function?
a) fun
b) define
c) def
d) function
2. What are the two main types of functions?
a) Custom function & User defined function
b) Built-in function & User defined function
c) User defined function & System function
d) System function & Built-in functions
3. What is the output of below program?
def cube(x):
return x * x * x
x = cube(3)
print( x)
a) 9
b) 3
c) 27
d) 30
4. Which of the following functions is a built-in function in python?
a) seed() b) sqrt() c) factorial() d) print()
5. What is the output of the expression?round(4.5676,2)?
a) 4.5 b) 4.6 c) 4.57 d) 4.56
6. What is the output of the following function?complex(1+2j)
a) Error b) 1 c) 2j d) 1+2j
7. The function divmod(a,b), where both ‘a’ and ‘b’ are integers is evaluated as:
a) (a%b, a//b) b) (a//b, a%b) c) (a//b, a*b) d) (a/b, a%b)
8. What is the output of the function shown below?
list(enumerate([2, 3]))
9. What is the result of the code?
def p(x):
print(2**x)
p(3)
a)8 b)64 c)6 d)x
10. The default value of the parameter is defined in the ………….
11. Choose correct answer for the following code
def abc(X,Y):
print(X,Y)
abc(10,20)
A. X and Y are called actual parameter
B. X and Y are default argument
C. 10 and 20 are formal parameter
D. None of above
12. Predict the output of the following code
def fun2(list1):
for x in list1:
print(x.upper(),end=”#”)
67
fun2([‘Rajesh’,’Kumar’)
13. What will be the result of thefollowing code:
def func1(a):
a= a + '1'
a=a*2
func1("good")
A. good
B. good2good
C. goodgood
D. indentation error
14. Which of the following functions acceptsinteger as argument:
A. chr()
B. ord()
C. sum()
D. mul()
15. The function header contains:
A. Function name only
B. Parameter list only
C. Both function name & Parameter list
D. Return valu
16. A variable defined outside of all functions is known as :
A. Local variable
B. Global variable
C. Static variable
D. Unknown variable
res()
68
print("Value outside function:",x)
4. What are default arguments? What are the advantages of keyword arguments?
ANSWERS
I Answer the following 1 mark
1 C
2 B
3 C
4 D
5 C
6 D
7 B
8 The built-in function enumerate() accepts an iterable as an argument. The
function shown in the above case returns containing pairs of the numbers
given, starting from 0.Hence the output will be: [(0, 2), (1,3)].
9 A
10 Header
11 D
12 B
13 D
14 A
15 C
16 B
69
II Answer the following 2 marks
1 Global Variable: A variable that is declared in top-level statements is called
a global variable. To access the value of a global variable user need to write
a global keyword in front of the variable in a function.
It is easier to use since we need not remember the order of the arguments.
We can specify the values for only those parameters which we want, and
others have default values.
IV Answer the following 5 marks
70
a)id():
Return the “identity” of an object. This is an integer which is guaranteed to
be unique and constant for this object during its lifetime. Two objects with
non-overlapping lifetimes may have the same id() value. This is the address
of the object in memory.
(c) round ()
Return number rounded to ndigits precision after the decimal point. If ndigits is
omitted or is None, it returns the nearest integer to its input.
For the built-in types supporting round(), values are rounded to the closest
multiple of 10 to the power minus ndigits; if two multiples are equally close,
rounding is done toward the even choice (so, for example, both round(0.5) and
round(-0.5) are 0, and round(1.5) is 2). Any integer value is valid for ndigits
(positive, zero, or negative). The return value is an integer if ndigits is omitted
or None. Otherwise, the return value has the same type as number
(d) type ()
With one argument, return the type of an object. The return value is a type object
and generally the same object as returned by object.__class__.
(e) pow ()
Return base to the power exp; if mod is present, return base to the power
exp, modulo mod (computed more efficiently than pow(base, exp) % mod).
The two-argument form pow(base, exp) is equivalent to using the power
operator: base**exp.
The arguments must have numeric types. With mixed operand types, the
coercion rules for binary arithmetic operators apply. For int operands, the
result has the same type as the operands (after coercion) unless the second
argument is negative; in that case, all arguments are converted to float and a
float result is delivered. For example, pow(10, 2) returns 100, but pow(10, -
2) returns 0.01. For a negative base of type int or float and a non-integral
71
exponent, a complex result is delivered. For example, pow(-9, 0.5) returns a
value close to 3j.
FILE HANDLING
Files are of bytes stored on storage devices such as hard-disks. Files help in storing
information permanently on a computer.
Data Files:
Data files are files that store data pertaining to a specific application. The data files
can be stored in following ways:
• Text files: These files store information in the form of a stream of ASCII or UNICODE
characters. Each line is terminated by an EOL character. Python programs, contents written
in text editors are some of the example of text files.
• Binary files: These files store information in the form of a stream of bytes. No EOL character
is used and binary files hold information in the same format in which it is held in the memory.
The .exe files, mp3 file, image files, word documents are some of the examples of binary
files.We can’t read a binary file using a text editor.
Difference Between Text File And Binary File
Text File Binary File
Stores information in ASCII characters. Stores information in the same format which
the information is held in memory.
Less prone to get corrupt as change reflects as Can easily get corrupted, corrupt on even single
soon as made and can be undone. bit change.
Store only plain text in a file. Can store different types of data.
Widely used file format and can be opened in Developed for an application and can be
any text editor. opened in that only.
Slower than binary files. Binary files are faster and easier for a
program to read and write the text files.
Opened in any text editor. Mostly .txt and .rtf Can have any application defined extensions.
are used as extensions of text files.
• Please note that when you open a file in read mode,the given file must exist in folder,
otherwise Python will raise error.
File Object/File Handle:-A file object is a reference to a file on disk.It opens and makes it
available for a number of different tasks.
FileAccessModes:-
Text Binary
Description
file File
mode Mode
‘r’ ‘rb’ Read-Default value. Opens a file for reading, error if the file
does not exist.
‘w’ ‘wb’ Write- Opens a file for writing, creates the file if it does not
exist
‘a’ ‘ab’ Append- Opens a file for appending, creates the file if it does
not exist
‘r+’ ‘rb+’ Read and Write- File must exist, otherwise error is raised.
73
‘w+’ ‘wb+’ Read and Write-File is created if does not exist.
A file-mode governs the type of operations(e.g.,read/write/append) possible in the opened file i.e., it
refers to how the file will be used once it's opened.
Closing Files :
One must always close a file when the file is no longer required for any more
operations.The file can be closed by using the close( ) function which can be used w ith the
file pointer as follows:
<file_handle>.close()
Working with Text Files:
1. Read the data from a file
2. Write the data to a file
3. Append the data to a file
OUTPUT:
Example-1:Programusingread()function:
fin=open("D:\\pythonprograms\\Boo Python is interactive language. It is case sensitive
k.txt",'r') language.
str=fin.read( ) It makes the difference between uppercase and
74
print(str) lowercase letters. It is official language of google.
fin.close()
Example-2:Programusingread()function: OUTPUT:
fin=open("D:\\python programs\\Book.txt",'r')
Python is
str=fin.read(10)
print(str)
fin.close()
Example-3:usingreadline()function: OUTPUT:
Myfile
I am Peter.
How are you?
OUTPUT:
Example-1:Program using write()function:
My name is Aarav.
f=open(r’MyFile.txt’,’w’)
data = ‘My name is Aarav.’
f.write(data)
f.close( )
f=open(r’MyFile.txt’,’r’)
data = f.read( )
75
print(data)
f.close( )
flush( ) function:
• When we write any data to file, python hold everything in buffer (temporary memory) and
pushes it onto actual file later. If you want to force Python to write the content of buffer onto
storage, you can use flush() function.
• Python automatically flushes the files when closing them i.e. it will be implicitly called by the
close(), but if you want to flush before closing any file you can use flush()
seek( ) function:
The seek( ) function allows us to change the position of the file pointer in the opened
file as follows:
f.seek(offset,mode)
where
offset - is a number specifying number of bytes.
mode - specifies the reference point from where the offset will be calculated to place
the file pointer. The mode argument is optional and has three possible values namely 0, 1
and 2. The default value of mode is 0.
0 - beginning of file
1 - current position in file
2 - end of file
tell( ) function:
The tell() method returns the current position of the file pointer in the opened file. It is used as
follows:
f.tell()
76
OUTPUT:
Example-1: tell()function:
Example: fout=open("story.txt","w") 14
fout.write("Welcome Python")
print(fout.tell( ))
fout.close( )
WORKSHEET
LEVEL-I
7 Write a python program to accept a line from the user and store that in a file
2
“story.txt”.
8 Write a function to copy all the upper case words to another file. 2
9 Write the function to read the content from the file display the word which are having
3
the length of exactly 4 characters.
10 Krishna is confused in Python code given below. Please help him to answer the
5
following questions.
77
(a) Which line in the above code check for capital letter?
(b) Which line in the above code read the file “story. txt”?
(c) Which line in the above code does not affect the execution of program?
(d) Which line is the above code coverts capital letter to small letter?
(e) Which line is the above code opens the file in write mode?
(f) Which line is the above code saves the data?
(g) Which line(s) is/are the part of selection statement.
(h) Which line(s) is/are used to close story1.txt?
ANSWERS
1 (b) file_read = open("c:marks.txt", "r")
2 (a) returns the current position of record pointer within the file
3 (a) File.read(n)
4 (b) File object = open(file_name [, access_mode][,buffering])
6 22
7
78
8
(a) Line 6 (b) Line 4 (c) Line 10 (d) Line 7 (e) Line 2 (f) Line 13 (g) Line 6, Line 8
10
and Line 11 (h) Line 15
LEVEL-2
1 To read two characters from a file object "file_read"
(a) file_read.read(2)
(b) file_read(2) 1
(c) file_read(read,2)
(d) file_read.readlines(2)
2 seek() method in files used for 1
3 What does the <readlines()> method returns? (a) Str (b) A list of lines(c) List of single
1
characters(d) List of integers
4 Differentiate the following:
(a) f = open('diary.txt', 'r') 1
(b) f = open('diary.txt', 'w')
79
5 Assume that file “tear.txt”, already contain “I love my India” in the file. What will be
ANSWERS
1 (a) file_read.read(2)
2 Sets the file's current position at the offset
3 (b) A list of lines
(a) It opens the file in reading mode only in text format.
4 (b) It opens the file in writing mode only in text format. If the file exists, then it erases
the previous data.
80
5 13
5 Write a method in Python to read lines from a text file INDIA.TXT, to find and
6
Write a function to read the content from the file “India.txt”, and store the frequency
of each word in dictionary and display the dictionary in the screen.
Content of the file is:
‘‘India is the fastest growing economy.
India is looking for more investments around the globe.
The whole world is looking at India as a great market.
4
Most of the Indians can foresee the heights that India is capable of reaching.’’
Output of the file:
{‘India’: 4, ‘is’: 4, ‘the’: 4, ‘fastest’: 1, ‘growing’: 1, ‘economy.’: 1, ‘looking’: 2,
‘for’: 1, ‘more’: 1, ‘investments’: 1, ‘around’: 1, ‘globe.’: 1, ‘The’: 1, ‘whole’: 1,
‘world’: 1, ‘at’: 1, ‘as’: 1, ‘a’: 1, ‘great’: 1, ‘market.’: 1, ‘Most’: 1, ‘of’: 2, ‘Indians’:
1, ‘can’: 1, ‘foresee’: 1, ‘heights’: 1, ‘that’: 1, ‘capable’: 1, ‘reaching.’: 1}
82
(a) What will be the output?
(i) It will display first 20 characters. (ii) It will display 20th character and
onwards.
(iii) It will display first 20 bytes. (iv) It will display content at 20th
byte.
(b) Meenu, Mohan's friend has written the following Python code.
ANSWERS
1 (b) f.read()
2 (c) all lines from the file
(i) Text File (default mode)
3
(ii) File.write(“ABC”)
4 ife y
5
83
6
84
BINARY FILES
Topics Covered :
o Binary file: basic operations on a binary file:
o Open using file open modes (rb, rb+,wb,wb+, ab, ab+),
o Close a binary file,
o import pickle module, dump() and load() method,
o read, write/create, search, append and update operations in a binary file.
Binary files store data in the binary format (0’s and 1’s) which is understandable by the
machine. So when we open the binary file in our machine, it decodes the data and displays
in a human-readable format.
There are three basic modes of a binary file:
The plus symbol followed by file mode is used to perform multiple operations together. For
example, rb+ is used for reading the opening file for reading and writing. The cursor position is
at the beginning when + symbol is written with file mode.
Binary File Modes: File mode governs the type of operations read/write/append possible in the
opened file. It refers to how the file will be used once its opened.
File Description
Mode
rb Read Only: Opens existing file for read operation
wb Write Only: Opens file for write operation. If file does not exist, file is created. If
file exists, it overwrites data.
ab Append: Opens file in write mode. If file exist, data will be appended at the end.
rb+ Read and Write: File should exist, Both read and write operations can be
performed.
wb+ Write and Read: File created if not exist, If file exist, file is truncated.
ab+ Write and Read: File created if does not exist, If file exist data is truncated.
85
Pickle Module: Python pickle is used to serialize and deserialize a python object structure.
Any object on python can be pickled so that it can be saved on disk.
Pickling: Pickling is the process whereby a Python object hierarchy is converted into
a byte stream. It is also known as serialization
Example:
import pickle
In this module,we shall discuss two functions of pickle module, which are:
i) dump():To store/write the object data to the file.
ii) load():To read the object data from a file and returns the object data.
Syntax:
Write the object to the file:
pickle.dump(objname, file-object )
pickle.load(file-object)
OUTPUT:
Enter student Roll No: 1201
Enter student Name: Anil
Want to add more record(y/n): y
86
Enter student Roll No: 1202
Enter student Name: Sunil
Want to add more record(y/n): n
Read data from a Binary File:
To read the data from a binary file, we have to use load() function
Example:
import pickle
file = open("student.dat", "rb")
list =pickle.load(file)
print(list)
file.close()
OUTPUT:
[{'roll':'1201','name':'Anil'},{'roll':'1202','name':'Sunil'}]
OUTPUT:
Enter the name to be updated Sunil
Enter the updated Roll number 1204
Record updated
87
Delete a record from binary file:
import pickle
def deletestudent():
OUTPUT:
Enter roll number whose record you want to delete:1201
Record Deleted
WORKSHEET
LEVEL – 1
I Answer the following questions Marks
4 Raman open a file in readmode, but the file doesn’t exist in the folder. 1
Python raised an error for the code. What type of error will be shown?
88
6 Pickling is otherwise known as ________________ 1
2 The code given below reads from a file “sales.dat” which has following 3
information [itemcode, amount] Read from the file and find the sum of
the amount.
import pickle
F1 = open ("sales.dat", "rb")
sum = 0
while True:
try:
________________
89
________________
except EOFError:
break
print (sum)
F1.close()
91
4.writer.writerow(row): Write the row parameter to the writer’s file
object, formatted according to delimiter defined in writer function.
writerows(rows): Writes multiple rows (sequence) to the writer’s file
object
III 1.Binary files store the information in the form of a stream of bytes
similar to the format a computer memory holds data. Also there is no
delimiter for a line and no translations occur in binary files. Thus binary
files are faster and easier for a program to read and write. So the best
method for a data or program information is to store it as binary files.
1. Program
L = pickle.load(F1)
1. sum = sum + L[1]
IV
1. Mode & Description
a) r - reading only. Sets file pointer at beginning of the file. This is
the default
a. mode.
b) rb – same as r mode but with binary file.
c) r+ - both reading and writing. The file pointer placed at the
a. beginning of the file.
d) rb+ - same as r+ mode but with binary file.
e) w - writing only. Overwrites the file if the file exists. If not,
a. creates a new file for writing.
f) wb – same as w mode but with binary file.
g) w+ - both writing and reading. Overwrites. If no file exists,
a. creates a new file for R & W.
h) wb+ - same as w+ mode but with binary file.
i) a -for appending. Move file pointer at end of the file.Creates
a. new file for writing,if not exist.
j) ab – same as a but with binary file
92
It returns read bytes in the form of a string ending with line character or
returns a blank string if no more bytes are left for reading in the file.
e.g. f1=open(“E:\\mydata\\info.txt”)
info=f1.readlines()
output:
The Dowry system is evil in society
c) readlines() – Read all lines and returns them in a list
output:
[“The Dowry system is evil in society.\n”” It has reduced the sacred affair
of marriage to a business deal.\n”“Brides are treated as a marketable
commodity. \n””The parents of the brides are often put under inhuman
pressure for a handsome dowry.\n“]
3.c,c,c,d,c
LEVEL – 2
Answer the following questions Marks
3 The _________ files are used to store large data such as images, video 1
files, audio files etc
4 ______ module is used to store data into a python objects with their 1
structure.
5 ______ function of pickle module is used to write data into binary 1
6 _______ function of pickle module is used to read data from binary file. 1
7 Ms. Suman is working on a binary file and wants to write data from a 1
list to a binary file. Consider list object as L1, binary file suman_list.dat,
and file object as f. Which of the following can be the correct statement
for her?
a) f = open(‘sum_list’,’wb’); pickle. dump(L1,f)
b) f = open(‘sum_list’,’rb’); L1=pickle.dump(f)
c) f = open(‘sum_list’,’wb’); pickle.load(L1,f)
93
d) f = open(‘sum_list’,’rb’); L1=pickle.load(f)
8 Ranjani is working on the sports.dat file but she is confused about how 1
to read data from the binary file. Suggest a suitable line for her to fulfil
her wish.
import pickle
def sports_read():
f1 = open("sports.dat","rb")
_________________
print(data)
f1.close()
sports_read()
4 The code given below writes Name and Roll Nos into a binary file. Fill 2
in the blanks to complete the code.
import pickle
with open ("file.dat", "wb") as F1:
while True:
op = int (input ("Enter 1 to add data, 0 to quit"))
if (op == 1):
__________________________
__________________________
pickle.dump([name,rollno],F1)
elif op == 0:
break
import pickle
#open file in binary mode for writing.
95
with open('emp.dat', '____') as outfile: #Line 1
#Store data in list
employee = [101,'Simran',20000]
_________________ #Line 2
a) Fill in the blank in line 1 to open file in binary mode for append
data to the file
b) Fill in the blank in line 2 to pickle the list and write to file
96
4 A file sports.dat contains information in following format [event, 3
participant].
Write a program that would read the contents from file and copy only
those records from sports.dat where the event name is “Athletics” in
new file named Athletics.dat
5 A binary file “STUDENT.DAT” has structure [admission_number, 3
Name, Percentage]. Write a function countrec() in Python that would
read contents of the file “STUDENT.DAT” and display the details of
those students whose percentage is above 75. Also display number of
students scoring above 75%
6 What is pickle.dump()?What is pickle.load()? 3
7 Write a function in to search and display details of all trains, whose 3
destination is "Delhi" from a binary file "'TRAIN .DAT'" Assuming the
binary file is containing the objects of the following dictionary type:
Train = {'Tho' :_______ , 'From': _____, " To': ________}
ANSWERS
I 1.Files
2. Newline (\n)
3. Binary
4. PICKLE
5.dump()
6.load()
7.option d
8.data = f1.load(f).
9. c
10. with open('record.bin','wb') as myfile:
pickle.dump(L,myfile)
97
E.g.: CSV files – Comma Separated Files
TSV files – Tab separated files
2. Python file object provides methods and attributes to access and
manipulate files. Using file objects, we can read or write any files.
Whenever we open a file to perform any operations on it, Python returns
a file object.
3.The difference between Write() and WriteLine() method is based on
new line character.
Write() method displays the output but do not provide a new line
character.
WriteLine() method displays the output and also provides a new line
character it the end of the string, This would set a new line for the next
output.
4.rollno=int(input("Enter the Roll Number: "))
name=input("Enter the name: ")
5.
import pickle
def writefile():
f=open("datafile.dat", "wb")
list=["Apple","Mango", "Banana"]
pickle.dump(list,f)
f.close
writefile()
print("Writing done")
6. a) ab
b)pickle.dump(employee, outfile)
7. ['Fifth', 'fourth', 'third', 'second"]
III 1. Pickle module provides us the ability to serialise and deserialize objects
that is, it helps to convertobjects into bitstreams that can be stored in
files and later utilised to recreate the original objects.
98
For us, writing different kinds of objects into the binary file and later,
reading the file's content is really challenging.The fact that some of the
objects may have changing lengths makes this a tedious task. So we use
the pickle module to solve this issue since it can handle dictionaries,
sets, lists, tuples, classes, and more.It can store lists, Tuples,
dictionaries, sets, classes etc.
2.
import pickle
F1 = open ("file.dat", "wb")
Icode = input ("Enter code : ")
quantity = int (input ("Quantity : "))
d = {Icode:quantity},
pickle.dump(d, F1)
F1.close()
3.
def countrec():
num=0
fobj=open("data.dat","rb")
try:
print("Emp id\tEmp Name\tEmp Sal")
while True:
rec=pickle.load(fobj)
if rec[2]>20000:
print(rec[0],"\t\t",rec[1],"\t\t",rec[2])
except:
fobj.close()
countrec()
4.
import pickle
99
F1 = open ("sports.dat", "rb")
F2 = open ("athletics.dat", "wb")
sum = 0
while True:
try:
l = pickle.load(F1)
if (l[0].lower() == "athletics"):
print (l)
pickle.dump(l,F2)
except EOFError:
break
F1.close()
F2.close()
5.
import pickle
def countrec():
fobj=open("student.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[2]>75:
num = num + 1
print(rec[0],rec[1],rec[2])
except:
fobj.close()
return num
100
6. dump() function is used to store the object data to the file.
dump( object, filehandle )
It takes 3 arguments.
First argument is the object that we want to store.
The second argument is the file object we get by opening the desired
file in write-binary (wb) mode.
the third defines the protocol.
101
print("Not found !!!")
file.close()
search()
LEVEL – 3
Answer the following questions Marks
1. Write Python statements to open a binary file "student.dat" in both read & 1
write mode.
2. Which of the following statement is true? 1
a. pickling creates an object from a sequence of bytes
b. pickling is used for object serialization
c. pickling is used for object deserialization
d. pickling is used to manage all types of files in Python
3. Read the following Python code carefully and answers the question given after 1
the code
1
import pickle
#open file in binary mode for writing.
with open('emp.dat', '____') as outfile: #Line 1
#Store data in list
employee = [101,'Simran',20000]
_________________ #Line 2
Fill in the blank in line 1 to open file in binary mode for append data to the
file.
Fill in the blank in line 2 to pickle the list and write to file
102
myfile = open("test.bin",'wb')
pickle._________ #Statement 1
myfile.close()
103
15. How can you delete a file? Write a pseudocode to delete a file 2
16. Write a function to read name and roll no from a binary file. 3
104
F.close()
def GetStudents():
Total=0
Countrec=0
Countabove75=0
with open("STUDENT.DAT","rb") as F:
while True:
try:
____________ #3 statement to readfrom the file
Countrec+=1
Total+=R[2]
if R[2] > 75:
print(R[1], " has percent =",R[2])
Countabove75+=1
except:
break
if Countabove75==0:
print("There is no student who has percentage more than 75")
average=Total/Countrec print("average percent of class = ",average)
AddStudents()
GetStudents()
105
II. Which of the following commands is used to write the list L into the
binary file,
STUDENT.DAT? (marked as #2 in the Python code)
a. pickle.write(L,f)
b. pickle.write(f, L)
c. pickle.dump(L,F)
d. f=pickle.dump(L)
III. Which of the following commands is used to read each record from the
binary
file STUDENT.DAT? (marked as #3 in the Python code)
a. R = pickle.load(F)
b. pickle.read(r,f)
c. r= pickle.read(f)
d. pickle.load(r,f)
IV. Which of the following statement(s) are correct regarding the file
access modes?
a. ‘r+’ opens a file for both reading and writing. File object points to its
beginning.
b. ‘w+’ opens a file for both writing and reading. Adds at the end of the existing
file if it exists and creates a new one if it does not exist.
c. ‘wb’ opens a file for reading and writing in binary format. Overwrites the
file if it exists and creates a new one if it does not exist.
d. ‘a’ opens a file for appending. The file pointer is at the start of the file if the
file exists
106
d. moves the current file position to a given specified position
107
14.
A binary file is a file whose content is in a binary format consisting of a series
of sequential bytes, each of which is eight bits in length.Binary Files contain
raw data so are not in human readable format. It can be read by using some
special tool or program.
Document files: .pdf, .doc, .xls etc.
Image files: .png, .jpg, .gif, .bmp etc.
Video files: .mp4, .3gp, .mkv, .avi etc.
Audio files: .mp3, .wav, .mka, .aac etc.
Database files: .mdb, .accde, .frm, .sqlite etc.
Archive files: .zip, .rar, .iso, .7z etc.
Executable files: .exe, .dll, .class etc
15.
To delete a file, import the OS module, and run its os.remove() function.
import os
os.remove("demofile.txt")
16.
def Readrecord():
with open ('StudentRecord1.dat','rb') as Myfile:
print("\n-------DISPALY STUDENTS DETAILS--------")
print("\nRoll No.",' ','Name','\t',end='')
print()
while True:
try:
rec=pickle.load(Myfile)
print(' ',rec['SROLL'],'\t ' ,rec['SNAME'])
except EOFError:
break
108
III 1.
I. a)
II. c)
III. a)
IV. a)
V. d)
2.
Text Files Binary Files CSV Files
1 It is capable to It is capable to It is very common
handle textual data. handle large file. format and
platform
independent.
2 It consists of series It consists of data It consists of plain
of lines of a set of with a specific text with a list of
letters, numbers or pattern without data with a
symbols (String) any delimiter. delimiter.
3 Any text editors No specific It can be read
like notepad can be programs can be using text editors
used to read them. used to read them, like notepads and
python provides spreadsheet
functions to read software.
data.
4 Every line ends There is no It terminates a line
with EOL. specific EOL automatically
character. when the delimiter
is not used after
data.
CSV Files
The CSV (Comma Separated Values) is a special text file format in which rows of data are present
and the individual data elements are separated by commas. The CSV format is the most common
import and export format for spreadsheets and databases. The csv files have the extension .csv
Example for data contained in csv file
Raghu,23,100
109
Tisha,45,230
Yatin,67,90
1. Each record is located on a separate line, delimited by a line break (CRLF). For example:
One,two,three CRLF
four,five,six CRLF
2. The last record in the file may or may not have an ending line break. For example:
One,two,three CRLF
four,five,six
3. There maybe an optional header line appearing as the first line of the file with the same
format as normal record lines. For example:
Name,Rollno,Marks CRLF Header line
Raghu,1011,56 CRLF
Swara,1012,78 CRLF
4. 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:
"one","two","three" CRLF
Eight,nine,ten
[Note:
1. CR stands for the character 'Carriage Return' with Integer ASCII code - 13 and
C++/Python notation \r or '\r'.
2. LF stands for the character 'Line Feed' with Integer ASCII code - 10 and C++/Python
notation \n or '\n'.
110
3. In Windows platform the Enter Key / End of Line(EOL) / newline character is represented
by the character combination CRLF i.e. '\r\n' in python.
4. In Unix/Linux platforms the Enter Key /End of Line (EOL) / newline character is
represented by the character LF only i.e. '\n' in python.
5. In Macintosh platforms the Enter Key / End of Line (EOL) / newline character is
represented by the character CR only i.e. '\r' in python.
6. When opening a file for reading CSV file add the parameter, newline='EOL_character' to
process the End of Line correctly.
While opening a CSV file for reading on Windows platform, add the parameter, newline='\r\n' in
the open() method to avoid adding an extra blank line while processing/displaying output on the
screen ]
In CSV files there can be delimiters other than comma(,)
Tab separated values
Raghu 23 100
Tisha 45 230
Yatin 67 90
Raghu ;23;100
Tisha;45;230
Yatin;67;90
import csv as c
or
import csv
writerow() Vs writerows()
writerow() is used to write a single row to a csv file.
112
writerows() is used to write multiple rows/lines to csv file
To demonstrate writerow() and writerows()
import csv
f=open("one.csv","w",newline='')
csvwriter=csv.writer(f,delimiter=',')
csvwriter.writerow(['one','two','three'])
l=[(23,45,67),(34,56,78),(45,67,78)]
csvwriter.writerows(l)
f.close()
OUTPUT:
one,two,three
23,45,67
34,56,78
45,67,78
WORKSHEET
LEVEL – 1
I Questions (1 mark)
1 CSV files are opened with __________argument to supress EOL translation.
2 The _________ parameter of csv.reader() function is used to set a specific delimiter like a single
quote or double quote or space or any other character.
3 When you read csv file using csv.reader() function it returns the values in _______ object.
4 If you want to change a default delimiter of csv file, you can specify ________ parameter.
5 Which of the following is not a function of csv module?
a. readline()
b. writerow()
c. reader()
d. writer()
6 Anshuman wants to separate the values by a $ sign. Suggest to him a pair of function and
parameter to use it.
A open,quotechar
B writer,quotechar
C open,delimiter
D writer, delimiter
7 Which of the following is tasks cannot be done or difficult with CSV module?
A Data in tabular form
B Uniqueness of data
C Saving data permanently
D All of these
8 Observe the following code and fill the blank in statement1
import csv
with _________ as f: #statement1
r = csv.______(f) #statement2
for row in ______: #statement3
113
print(_____) #statement4
a) open(“data.csv”)
b) f=open(“data.csv”)
c) Both A & B are Correct
d) Both A & B are incorrect
9 A CSV file is also known as a ….
A. Flat File
B. 3D File
C. String File
D. Random File
10 The command used to skip a row in a CSV file is
A. next()
B. skip()
C. omit()
D. bounce()
11 Which of the following is a string used to terminate lines produced by writer()method of csv
module?
A. Line Terminator
B. Enter key
C. Form feed
D. Data Terminator
12 Making some changes in the data of the existing file or adding more data is called
A. Editing
B. Appending
C. Modification
D. Alteration
13 Observe the following code and fill the blank in statement4
import csv
with _________ as f: #statement1
r = csv.______(f) #statement2
for row in ______: #statement3
print(_____) #statement4
a) r
b) row
c) f
d) csv
14 One row of CSV file can be considered as _______ in terms of database
15 What is the output of the following program?
import csv
d=csv.reader(open('c:\PYPRG\ch13\city.csv'))
next(d)
for row in d: print(row)
if the file called “city.csv” contain the following details
chennai,mylapore
114
mumbai,andheri
A. chennai,mylapore
B. mumbai,andheri
C. Chennai, mumbai
D. chennai,mylapore
mumbai, andheri
II Questions (2 marks)
1 What is the difference between writer object’s writerow() and writerows() function?
2 How will you sort more than one column from a csv file?Give an example statement.
3 What Is CSV File”
4 Syntax for opening Student.csv file in write mode is
myfile = open("Student.csv","w",newline='').
What is the importance of newline=''?
5 What is the output of the following program if the student.csv file contains following data?
Student.csv
Ronit, 200
Akshaj, 400
import csv
d = csv.reader(“student.csv”)
next (d)
for row in d:
print (row)
III Questions (3 marks)
1 Write a note on open() function of python. What is the difference between the two methods?
2 Write a Python program to modify an existing file
3 Write a Python program to read a CSV file with default delimiter comma (,).
4 What is the difference between reader() and DictReader() function?
5 Observe the following code and fill in the given blanks:
import csv
with _________ as f: #1
r = csv.______(f) #2
for row in ______: #3
print(_____) #4
IV Questions (5 marks)
1 Vijay Kumar of class 12 is writing a program to create a CSV file "user.csv" which will contain
user name and password for some entries. He has written the following code. As a
programmer, help him to successfully execute the given task.
115
#csv file reading code
def readRecord(): # to read data from CSV file
f=open('users.csv','r')
creader = csv._________(f) # Line 3
for row in creader:
print (row[0],row[1])
__________ # Line 4
addRecord("Neil", "123@456")
addRecord("Swati","sw@tee")
addRecord("Farida","myname@FRD")
readRecord() #Line 5
1a Name the module he should import in Line 1.
1b In which mode, Vijay should open the file to append data into the file.
1c Fill in the blank in Line 3 to read the data from a csv file.
1d Fill in the blank in Line 4 to close the file
1e Write the output he will obtain while executing Line 5.
def writeFile(Gift_code,Gift_name):
F=open(“gift.csv”,‟___‟) #Line 2
FW=csv.________(F) #Line 3
FW.writerow([Gift_code,Gift_name)
F.close()
writeFile(101,”Photoframe”)
writeFile(102,”Soft Toys”)
writeFile(103,”Flower Pot”)
readFile() #Line 5
3a Name the module she should import in line 1.
3b In which mode Puneeta should open the file to add data in it?
3c Fill in the blanks in Line 3 to write data to csv file gift.csv
3d Fill in the blank in Line 4 to open the csv file from the disk
3e Which user defined function is used here for reading data?
4 Rohit, a student of class 12th, is learning CSV File Module in Python. During examination, he
116
has been assigned an incomplete python code (shown below) to create a CSV File
'Student.csv' (content shown below). Help him in completing the code which creates the
desired CSV File.
CSV File
1,AKSHAY,XII,A
2,ABHISHEK,XII,A
3,ARVIND,XII,A
4RAVI,XII,A
5,ASHISH,XII,A
Incomplete Code
import_____ #Statement-1
fh = open(_____, _____, newline='') #Statement-2
stuwriter = csv._____ #Statement-3
data = []
header = ['ROLL_NO', 'NAME', 'CLASS', 'SECTION']
data.append(header)
for i in range(5):
roll_no = int(input("Enter Roll Number : "))
name = input("Enter Name : ")
Class = input("Enter Class : ")
section = input("Enter Section : ")
rec = [_____] #Statement-4
data.append(rec)
stuwriter. _____ (data) #Statement-5
fh.close()
I.Identify the suitable code for blank space in line marked as Statement-1.
a) csv file
b) CSV
c) csv
d) Csv
II.Identify the missing code for blank space in line marked as Statement-2?
a) "School.csv","w"
b) "Student.csv","w"
c) "Student.csv","r"
d) "School.csv","r"
III.Choose the function name (with argument) that should be used in the blankspace of line
marked as Statement-3
a) reader(fh)
b) reader(MyFile)
c) writer(fh)
d) writer(MyFile)
IV.Identify the suitable code for blank space in line marked as Statement-4.
a) 'ROLL_NO', 'NAME', 'CLASS', 'SECTION'
b) ROLL_NO, NAME, CLASS, SECTION
c) 'roll_no','name','Class','section'
d) roll_no,name,Class,sectionc) co.connect()
117
V.Choose the function name that should be used in the blank space of line markedas Statement-
5 to create the desired CSV File?
a) dump()
b) load()
c) writerows()
d) writerow()
LEVEL – 2
I Answer the following Marks
1 The expansion of CRLF is 1
(A) Control Return and Line Feed
(B) Carriage Return and Form Feed
(C) Control Router and Line Feed
(D) Carriage Return and Line Feed
ans (D) Carriage Return and Line Feed
2 Importing CSV files can be much faster, and it also consumes less memory 1
while comparing with .xls files(True/False)
an True
3 A ________ parameter is used to quote all fields of csv files.
ans Quoting
4 Read following statement about features of CSV file and select which
statement is TRUE?
118
5 Which of the following file types can be opened with notepad as well as
ms excel?
a. Text Files
b. Binary Files
c. CSV Files
d. None of thes
ans CSV Files
6 What is the output of the following program if the student.csv file contains 1
following data?
Student.csv
Ronit, 200
Akshaj, 400
import csv
d = csv.reader(“student.csv”)
next (d)
for row in d:
print (row);
ans Akshaj, 400
II Answer the following Marks
1 Write a program to copy the data from “data.csv” to “temp.csv” 2
ans import csv
f=open("data.csv","r")
f1=open("temp.csv",'w')
d=csv.reader(f)
d1=csv.writer(f1)
for i in d:
d1.writerow(i)
f.close( )
f1.close( )
119
2 When is a CSV file ? When do we use CSV? 2
A CSV (Comma Separated Values) file is a form of plain text document
which uses a particular format to organize tabular information. CSV file
format is a bounded text document that uses a comma to distinguish the
values. Every row in the document is a data log. Each log is composed of
one or more fields, divided by commas. It is the most popular file format
for importing and exporting spreadsheets and databases.
3 Write a Python program to modify an existing file.
ans import csv
row = [‘3’, ‘Meena’,’Bangalore’]
with open(‘student.csv’, r’) as readFile:
reader = csv.reader(readFile)
lines = list(reader) # list()- to store each row of data as a list
lines [3] = row
with open( student.csv’, ‘w’) as writeFile:
# returns the writer object which converts the user data with delimiter
120
90,Executive,100,1700
b
It tells you the current position of cursor within the file
Syntax: file_object.tell()
2 What is difference between tell() and seek() methods? 3
ans tell() seek()
It returns the current position of Change the cursor position by
cursor in file. bytes as specified by the offset
Example: Example:
fout=open(“story.txt”,”w”) fout=open(“story.txt”,”w”)
fout.write(“Welcome Python”) fout.write(“Welcome Python”)
print(fout.tell( )) fout.seek(5)
fout.close( ) print(fout.tell( ))
fout.close( )
Output : 4 Output : 5
IV Answer the following Marks
1 Ranjan Kumar of class 12 is writing a program to create a CSV file “user.csv” 5
which will contain user name and password for some entries. He has
written the following code. As a programmer, help him to successfully
execute the given task.
import _____________ # Line 1
def addCsvFile(UserName,PassWord): # to write / add data into the CSV
file
f=open(' user.csv','________') # Line 2
121
newFileWriter = csv.writer(f)
newFileWriter.writerow([UserName,PassWord])
f.close()
#csv file reading code
def readCsvFile(): # to read data from CSV file
with open(' user.csv','r') as newFile:
newFileReader = csv._________(newFile) # Line 3
for row in newFileReader:
print (row[0],row[1])
newFile.______________ # Line 4
addCsvFile(“Arjun”,”123@456”)
addCsvFile(“Arunima”,”aru@nima”)
addCsvFile(“Frieda”,”myname@FRD”)
readCsvFile() #Line 5
122
name and class to another CSV file “class.csv”. He has written the
following code. As a programmer, help him to successfully execute the
given task.
import csv
file = open('class.csv', ---------a--------- , newline="");
writer = csv.writer(file)
file.close()
a. In which mode should Ronit open the file to make a new file?
b. Which Python keyword should be used to manage the file stream?
c. Fill in the blank in Line 3 to read the data from a csv file.
d. Fill in the blank to write name into marks.csv
e. Fill in the blank to write class into marks.csv.
ans import csv
file = open('class.csv', 'w', newline="");
writer = csv.writer(file)
file.close()
123
CSV Module’s Reader Function:
(i) We can read the contents of CSV file with the help of csv.reader()
method. The reader function is designed to take each line of the file and
make a list of all columns.
(ii) Then, choose the column we want the variable data for. Using this
method one can read data from csv files of different formats like quotes
(""), pipe (|) and comma (,).
The syntax for csv.readerf() is
csv.reader(fileobject,delimiter,fmtparams) where
(iii) file object : passes the path and the mode of the file
(iv) delimiter:an optional parameter containing the standard dilects like , |
etc can be omitted.
(v) fmtparams : optional parameter which help to override the default
values of the dialects like skipinitialspace,quoting etc. can be omitted.
CSV file with default delimiter comma (,): The following program read a
file called “sample 1. csv” with default delimiter comma (,) and print row
by row.
Program:
124
#importing csv
import csv
#opening the csv file which is in different location with read mode
with open('c:\\pyprg\\samplel.csv', 'r') as F:
#other way to open the file is f= ('c:\\pyprg\\sample1.csv', 'r')
reader = csv.reader(F)
# printing each line of the Data row by row print(row)
F.close()
Output:
(i) To read a CSV file into a dictionary can be done by using DictReader
class of csv module which works similar to the reader() class but creates an
object which maps data to a dictionary.
(ii) 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.
(iii) The columns in each subsequent row then behave like dictionary
values and can be accessed with the appropriate key (i.e. fieldname).
125
(iv) 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.
(v) The main difference between the csv. reader() and DictReader() is in
simple terms csv.reader and csv.writer work with list/tuple, while
csv.DictReader and csv. DictWriter work with dictionary, csv. DictReader
and csv. DictWriter take additional argument fieldnames that are used as
dictionary keys.
Program:
import csv
filename = c:\\pyprg\\sample8.csv’
input_file =csv.DictReader(open(filename,’r’))
for row in input_file:
print(dict(row) ) #dict() to print data
Output:
{‘ItemName ‘: ‘Keyboard ‘, ‘Quantity’: ‘48’}
{‘ItemName ‘: ‘Monitor’ ‘Quantity’: ‘52’}
{‘ItemName ‘: ‘Mouse ‘, ‘Quantity’: ‘20’}
127
CSVOpen()
CSVRead()
You as an expert of Python have to provide the missing statements and
other related queries based on the following code of Radha.
Answer any four questions (out of five) from the below mentioned
questions.
4.1 Choose the appropriate mode in which the file is to be opened in append
mode
(Statement 1)
a. w+
b. ab
c. r+
d. a
Correct Answer: d. a
ans
4.2 Which statement will be used to create a csv writer object in Statement 2.
a. csv.writer(csvf)
b. csv.writer(csvf)
c. csvf.writer()
d. cs.writer(csvf)
128
ans Correct Answer: b. cw.writerow(['Title','Author','Price'])
4.4 Which statement will be used to read a csv file in Statement 4.
a. cs.read(csvf)
b. csv.reader(csvf)
c. csvf.read()
d. csvf.reader(cs)
(A) py
(B) xls
(C) csv
(D) os
129
Ans (C) csv
2 To open a file c:\scores.csv for reading, we use _______ command. 1
a) infile = open(“c:\scores.csv”, “r”)
b) infile = open(“c:\\scores.csv”, “r”)
c) infile = open(file = “c:\scores.csv”, “r”)
d) infile = open(file = “c:\\scores.csv”, “r”)
Ans infile = open(“c:\\scores.csv”, “r”)
3 To read the entire content of the CSV file as a nested list from a file object 1
infile, we use __________ command.
(a) infile.read()
(b) infile.reader()
(c) csv.reader(infile)
(d) infile.readlines()
Ans c) csv.reader(infile)
4 The CSV files are popular because they are 1
130
written the following code. As a programmer, help him to successfully
execute the given task.
import______ # Line 1
131
Each field is separated by comma.
You can choose a different delimiter character such as ‘ ‘:’ , ‘;’ , ‘|’.
In CSV files space-characters adjacent to commas are ignored
Disadvantages of CSV:
•There is no standard way to represent binary data
•There is no distinction between text and numeric values
•There is poor support of special characters and control characters
•CSV allows to move most basic data only. Complex configurations
cannot be imported and exported this way
•There are problems with importing CSV into SQL (no distinction
between NULL and quotes)
2 What is the difference between writer object’s writerow() and writerows() 5
function? Write a python code based on these function
writer.writerow(row): Write the row parameter to the writer’s file object,
formatted according to delimiter defined in writer function
e.g.
import csv
f1=open(‘one.csv’,’w’)
w1=csv.writer(f1,delimiter = ‘,’)
132
w1.writerow([‘S.No’, ‘Name’, ‘Marks’])
f1.close()
A data structure is a way of store, organize, or manage data in efficient and productive manner.
The python data structure stack is a linear data structure. It follows the principle of LIFO (Last In
First Out). The representation of data is something like this:
133
By observing the above image you can understand the following:
Push function
A function to push an element. To push the element append() method is used as well as the
position of the top should be changed. Observe the following code:
def push(stk,e):
stk.append(e)
Pop Function
The pop function requires validation to check whether the stack is underflow or not if it is not then
use the logic to delete the element from the top. Have a look at this code:
def pop_stack(stk):
if stk==[]:
return "UnderFlow"
else:
e = stk.pop()
return e
Display function
Write a function to check the element is inserted or not, observe this code:
def display(stk):
if stk==[]:
print("Stack Underflow")
134
else:
for i in (stk[::-1]):
print(i)
Applications of the stack:
• Infix to Postfix /Prefix conversion
• Redo-undo features at many places like editors, photoshop.
• Forward and backward features in web browsers
• Used in many algorithms like Tower of Hanoi, tree traversals, stock span problems, and
histogram problems.
• String reversal is also another application of stack. Here one by one each character gets
inserted into the stack. So the first character of the string is on the bottom of the stack and
the last element of a string is on the top of the stack. After performing the pop operations
on the stack we get a string in reverse order.
Mind Map
def pushcostly(p,s):
for i in p:
if p[i]>40:
s.append(i)
def popcostly(s):
if s==[]:
print("Stack underflow")
else:
135
print("costly vegetables")
while(s):
print(s.pop())
return
veg={‘potato’:30,’beans’:40,’carrot’:40,’cabbage’:20,’brinjal’:10,’tomato’:50,’drumstick’:60}
costly= []
while True:
print ('''Menu
1.push
2.pop and display
3.exit''')
ch=int (input ("enter your choice"))
if ch==1:
pushprod(veg,costly)
elifch==2:
popdisplay(costly)
else:
break
WORKSHEET
LEVEL – 1
Answer the following questions(1 marks)
1. A stack is one of the following types of data structure?
a) Linear b) Dynamic c) Circular d) All of these
2. A condition raise due to the stack is full is known as ___________.
a) Underflow b) Overflow c) List is full d) Completely Filled
3. While popping the element from the stack, a condition will be raised, this condition is known
as ____________.
a) Underflow b) Overflow c) List is Empty d) Blank List
4. Which of the following is not a compound data structure?
a) Stack
b) Queue
c) Array
d) Tree
5. Inspecting the value at the stack’s top without removing it.
a) peak operation
b) insert operation
c) pop operation
d) push operation
6. Which of the following statement is incorrect for stack?
136
a) Peek <stack>[top]
b) Push <stack>.append(<item>)
c) Pop <stack>.pop()
d) Plus <stack>plus()
Answer the following questions (2 marks)
1. What are the underflow and overflow conditions?
LEVEL 1 ANSWERS
Answer the following questions(1 marks)
1 a) Linear
2 b) Overflow
3 a) Underflow
4 c) Array
5 a) peak operation
6 d) Plus <stack>plus()
Answer the following questions(2 marks)
137
1 Underflow is the condition which occurs when stack is empty while trying to
delete elements. Overflow is the condition which occurs while inserting an
element when memory is exhausted.
Answer the following questions(3 marks)
1 def pop_stack(stk):
if stk==[]:
return "UnderFlow"
else:
e = stk.pop()
if len(stk)==0:
top = None
else:
top = len(stk)-1
return e
2 def peek(stk):
if stk==[]:
return "UnderFlow"
else:
top = len(stk)-1
return stk[top]
3 def AddPlayer(player):
pn=input("enter player name:")
player.append(pn)
def DeletePlayer(player):
if player==[]:
print("No player found")
else:
return player.pop()
138
Answer the following questions(5 marks)
1 def push(stk,item):
stk.append(item)
def Pop(stk):
if stk==[]:
return None
else:
return stk.pop()
stk=[]
d={"Ramesh":58, "Umesh":78, "Vishal":90, "Khushi":60, "Ishika":95}
for i in d:
if d[i]>70:
push(stk,i)
while True:
if stk!=[]:
print(Pop(stk),end=" ")
else:
break
LEVEL – 2
LEVEL 2 ANSWERS
I Answer the following questions (1 marks)
1 LIFO
2 True
3 Push , Pop
4 b) Dynamic
5 c) list.pop()
6 b) DCBA
II Answer the following questions (2 marks)
1 The systematic way of organization, storing, accessing and retrieving data including
well-defined operations, behaviour and properties is known as data structure.
Examples:
String – Contains sequence of characters
List – Contains sequence of different data types
2 def is_underflow(stk):
if stk==[]:
return True
140
else:
return False
3 def push(stk,e):
stk.append(e)
top = len(stk)-1
LEVEL – 3
141
Answer the following questions(2 marks)
1. Define stack.
2. Expand the following:
a) LIFO
b) FIFO
3. What do you mean by the LIFO structure? Support your answer with real-life examples.
LEVEL 3 ANSWERS
Answer the following questions(1 marks)
1 False
2 False
3 a)LIL[0],LIL[1],LIL[2]………LIL[9]
4 c) last in first out
5 a)Stack is the FIFO data structure
1 A stack is a data structure that allows adding and removing elements in a particular 2
order. Every time an element is added, it goes on the top of the stack; the only
element that can be removed is the element that was at the top of the stack.
2 LIFO: Last-In First-Out FIFO: First-In First-Out 1+1
3 LIFO is one of the principle to access data from a data structure. It stands for Last In
First Out. It refers to the item which is inserted last will be access first. So the top
element will be accessed first.
Example:
1. Books in the shelf
2. Stack of coins
3. Pile of chairs
4. Bangles on woman’s wrist
142
UNIT – 2 COMPUTER NETWORKS
1. Computer Network
A computer network is an interconnection among two or more computers or computing devices.
2. Who invented WWW? - Sir Tim Berners-Lee — a British computer scientist invented the
revolutionary World Wide Web in 1990.
3. ARPANET
i. Stands for Advanced Research Projects Agency Network.
ii. Started in 1960s by the U.S. Department of Defence to connect the academic and
research institutions located at different places for scientific collaborations.
iii. Gradually, more and more organisations joined the ARPANET, and many
independent smaller networks were formed which eventually gave birth to the today’s
INTERNET.
4. TYPES OF NETWORKS
i. PAN (Personal Area Network)
ii. LAN (Local Area Network)
iii. MAN (Metropolitan Area Network)
iv. WAN (Wide Area Network)
5. PAN
i. It is formed by connecting personal devices like computers, laptops, mobile phones,
smart phones, printers etc.
ii. The devices should be within an approximate range of 10 metres. A personal area
network may be wired or wireless.
6. LAN
i. A network that connects computers, mobile phones, tablet, mouse, printer, etc., placed
at a limited distance, viz, a LAN can range from a single room, a floor, an office
having one or more buildings in the same premise, laboratory, a school, college, or
university campus.
ii. LAN may be extended up to 1 km. Data transfer in LAN is quite high, and usually
varies from 10 Mbps (called Ethernet) to 1000 Mbps (called Gigabit Ethernet), where
Mbps stands for Megabits per second
7. MAN
i. It is extended form of LAN which covers a larger geographical area like a city or a
town.
ii. Data transfer rate in MAN also ranges in Mbps but it is less as compared to LAN.
iii. Cable TV network or cable based broadband internet services are examples of MAN.
iv. It can be extended up to 30-40 km.
143
8. Modem- It stands for ‘MOdulatorDEModulator’, is a device used for conversion between
electric signals and digital bits.
9. Ethernet card- It is also known as Network Interface Card (NIC card in short), and it is a
network adaptor used to set up a wired network.
13. Router- It is a network device that can receive the data, analyse it and transmit it to other
networks.
14. Gateway- It serves as the entry and exit point of a network, as all data coming in or going out
of a network must first pass through the gateway in order to use routing paths. In other words,
A Gateway is a network point that acts as an entrance to another network using different
protocols.
15. Topology- The arrangement of computers and other peripherals in a network is called its
topology. The Common network topologies are Mesh, Ring, Bus, Star and Tree.
- In mesh topology each communicating device is connected with every other device in the
network.
- In ring topology, each node is connected to two other devices, one each on either side.
- In bus topology, a single backbone wire called bus is shared among the nodes, which
makes it cheaper and easy to maintain.
- In star topology, each communicating device is connected to a central networking device
like a hub or a switch.
- In tree or hybrid topology, there are multiple branches and each branch can have one or
more basic topologies like star, ring and bus.
16. IP address- It is also known as Internet Protocol address, and it is a unique address that can
be used to uniquely identify each node in a network.
Unlike MAC address, IP address can change if a node is removed from one network and
connected to another network.
17. Protocol-A network protocol is an established set of rules that determine how data is
transmitted between different devices in the same network.
It allows connected devices to communicate with each other, regardless of any differences in
144
their internal processes, structure or design.
18. HTML- HTML (HyperText Markup Language) is a language which is used to design
standardised Web Pages so that the Web contents can be read NOTES 2022-23 COMPUTER
NETWORKS 201 and understood from any computer.
19. URI/URL- URI (Uniform Resource Identifier) or URL (Uniform Resource Locator) is a
unique address or path for each resource located on the web.
20. HTTP – The HyperText Transfer Protocol is a set of rules which is used to retrieve linked
web pages across the web. The more secure and advanced version is HTTPS.
21. Domain name - Each computer server hosting a website or web resource is given a name
against its IP address. These names are called the Domain names or hostnames.
22. Domain name resolution-Conversion of the domain name of each web server to its
corresponding IP address is called domain name resolution. It is done through a server called
DNS server.
23. Switching- It is the technique by which nodes control or switch data to transmit it between
specific points on a network. There are 3 common switching techniques: Circuit Switching.
Packet Switching.
24. Circuit switching- In this technique, first a physical path is obtained and dedicated to a single
connection between two endpoints in the network for the duration of a dedicated connection,
and thereafter communication takes place. Ordinary voice phone service uses circuit
switching. Traditional telephone systems (landlines) are examples of a technology that uses
circuit switching.
145
26. Packet switching- In this transfer of small pieces of data across various networks takes place.
These data chunks or “packets” allow for faster, more efficient data transfer.
Examples: Frame Relay, IP, and X. 25
146
Message exist only in one location in the Parts i.e. packets of the message exist in
network. many places in the network.
Physical links are allocated dynamically. Virtual links are made simultaneously.
28. Hacker- A computer enthusiast, who uses his computer programming skill to intentionally
access a computer without authorization is known as hacker. A hacker accesses the computer
without the intention of destroying data or maliciously harming the computer.
a-Guided Media: It is also referred to as Wired or Bounded transmission media. Signals being
transmitted are directed and confined in a narrow pathway by using physical links.
Features:
• High Speed
• Secure
• Used for comparatively shorter distances
It consists of 2 separately insulated conductor wires wound about each other. Generally, several
such pairs are bundled together in a protective sheath. They are the most widely used Transmission
Media. Twisted Pair is of two types:
• Unshielded Twisted Pair (UTP):
UTP consists of two insulated copper wires twisted around one another. This type of
cable has the ability to block interference and does not depend on a physical shield for
this purpose. It is used for telephonic applications.
147
Advantages:
⇢ Least expensive
⇢ Easy to install
⇢ High-speed capacity
⇢ Susceptible to external interference
⇢ Lower capacity and performance in comparison to STP
⇢ Short distance transmission due to attenuation
• Shielded Twisted Pair (STP):
This type of cable consists of a special jacket (a copper braid covering or a foil shield)
to block external interference. It is used in fast-data-rate Ethernet and in voice and data
channels of telephone lines.
Advantages:
⇢ Better performance at a higher data rate in comparison to UTP
⇢ Eliminates crosstalk
⇢ Comparatively faster
⇢ Comparatively difficult to install and manufacture
⇢ More expensive and Bulky
It has an outer plastic covering containing an insulation layer made of PVC or Teflon and 2 parallel
conductors each having a separate insulated protection cover. The coaxial cable transmits
information in two modes: Baseband mode(dedicated cable bandwidth) and Broadband mode(cable
bandwidth is split into separate ranges). Cable TVs and analog television networks widely use
Coaxial cables.
148
Advantages:
• High Bandwidth
• Better noise Immunity
• Easy to install and expand
• Inexpensive
Disadvantages:
• Single cable failure can disrupt the entire network
(iii) Optical Fiber Cable –
It uses the concept of refraction of light through a core made up of glass or plastic. The core is
surrounded by a less dense glass or plastic covering called the cladding. It is used for the
transmission of large volumes of data.
The cable can be unidirectional or bidirectional. The WDM (Wavelength Division Multiplexer)
supports two modes, namely unidirectional and bidirectional mode.
Advantages:
• Increased capacity and bandwidth
• Lightweight
• Less signal attenuation
• Immunity to electromagnetic interference
• Resistance to corrosive materials
Disadvantages:
• Difficult to install and maintain
• High cost
• Fragile
Answer:
Domain name – income.in
URL – http://www.income.in/home.aboutus.hml
Question 2:
Write two characteristics of Wi-Fi.
Answer:It is wireless network.It is for short range.
Question 3:
What is cloud computing?
Answer:
The sharing of compute resources (dedicated, time-shared, or dynamically shared
servers) and related infrastructure components (load balancers, firewalls, network
storage, developer tools, monitors and management tools) to facilitate the
deployment and operation of web and network based applications. Cloud computing
relies on sharing of resources to achieve coherence and economies of scale, similar
to a utility (like the electricity grid) over a net-work.
Question 4:
Explain the purpose of a router.
Answer:
A router established connection between two networks and it can handle network
with different protocols. Using a routing table, routers make sure that the data packets
are travelling through the best possible paths
Question 5:
What are repeaters?
Answer:
A repeater is an electronic device that receives a signal and retransmits it at a higher
level and/ or higher power, or onto the other side of an obstruction, so that the signal
can cover longer distances.
Question 6:
What is VoIP?
Answer:
Voice over Internet Protocol (VoIP) is one of a family of internet technologies,
communication protocols, and transmission technologies for delivery of voice
communications and multi-media sessions over internet protocol (IP) network, such
as the internet.
150
Question 7:
Identify the type of topology from the following:
Answer:
1. Bus topology
2. Star topology
Question 8:
Mahesh wants to transfer data within a city at very high speed. Write the wired
transmission medium and type of network.
Answer:
Wired transmission medium – Optical fibre cable Type of network – MAN.
Question 9:
Indian School, in Mumbai is starting up the network between its different wings. There are four
Buildings named as SENIOR, JUNIOR, ADMIN and HOSTEL as shown below:
151
Number of Computers in Each Building :
Answers:
1.
2. Server can be placed in the ADMIN building as it has the maxium number of
computer.
3. Repeater can be placed between ADMIN
and SENIOR building as the distance is more than 110 m.
4. Radiowaves can be used in hilly regions as they can travel through obstacles.
Question 10:
Write any two differences between twisted pair and co-axial pair cable.
Answer:
152
Question 11:
The following is a 32 bit binary number usually represented as 4 decimal values, each
representing 8 bits, in the range 0 to 255 (known as octets) separated by decimal points.
140.179.220.200. What is it? What is its importance?
Answer:
It is an IP Address. It is used to identify the computers on a network.
Question 12:
What is the difference between domain name
and IP address?
Answer:
Domain Name is alphanumeric address of a resource over network and IP address is a Numeric
Address of a resource in a Network.
Example:
Domain Name- google.com and wikipedia.org
IP Address- 102.112.0.153
UNSOLVED QUESTIONS
Question 1:
In mid 80’s another federal agency, the NSF created a new high capacity network called
NSFnet, which was more capable than ARPANET. The only drawback of NSFnet
was that it allowed only academic research on its network and not any kind of private
business on it. Now, several private organisations and people started working to build
their own networks, named private networks, which were later (in 1990’s) connected
with ARPANET and NSFnet to form the Internet. The Internet really became popular
in 1990’s after the development of World Wide Web.
153
(i). NSFnet stand for _______________________
(ii). ARPANET stand for _______________
(iii). An interconnection of different networks is called ____________
(iv). To join the internet, the computer has to be connected to a _________
(v). Internet access by transmitting digital data over the wires of a local telephone
network is provided by ____________
(vi). A piece of icon or image on a webpage associated with another webpage is called
Question2:
154
(v). Network layer at source is responsible for creating a packet from data coming from another
a.station b. link c. node d. protocol
Question3:
Web server is a special computer system running on HTTP through webpages. The web page
is a medium to carry data from one computer system to another. The working of the web
server starts from the client or user. The client sends their request through the web browser
to the web server. Web server takes this request, processes it and then sends back processed
data to the client. The server gathers all of our web page information and sends it to the
user, which we see on our computer system in the form of a web page. When the client
sends a request for processing to the web server, a domain name and IP address are
important to the web server. The domain name and IP address are used to identify the user
on a large network.
(ii).What does the webserver need to send back information to the user?
a.Home address b.Domain name c.IP address d.Both b and c
(v). Computer that requests the resources or data from other computer is called as computer
a.Server b.Client c.None of the above d. Options a&b
155
(vii). What is the format of IP address?
a.34bit b.32 bit c.16bit d.64 bit
Question4:
GyanDeep International School is planning to connect all computers, each spread over a
distance within 40 m. Suggest an economical cable type having high-speed data transfer,
which can be used to connect these computers
Question5:
Mr. Taufiq Ahmad wants to prevent unauthorised access to/from his company’s local area
network. Write the name of system (software/hardware), which he should install.
Question6:
Beauty Lines Fashion Inc. is a fashion company with design unit and market unit 135 m away
from each other. The company recently connected their LANs using Ethernet cable to share
the stock related information. But after joining their LANs, they are not able to share the
information due to loss of signal in between. Which device out of the following should you
suggest to be installed for a smooth communication?
UPS/Modem /Repeater
Question7:
Refer to the following diagram and answer the questions given below.
156
c.HTTP request & response d.All of these
(iii). Which of the following device(s) can have IP Addresses?
a.A b.D c.F d.All the devices
(iv). Identify the network topology of the above network:
a.Ring b. Star c.Bus d.None of these
(v). ____is a protocol to transmit files (data) over the world wide web.
a.FTP b.HTTP c. SMP d.None of the above
Question 8:
Trine Tech Corporation (TTC) is a professional consultancy company. The company is planning to
set up their new offices in India with its hub at Hyderabad. As a network adviser, you have to
understand their requirement and suggest them the best available solutions. Their queries are
mentioned as (i) to (iv) below.
Physical Locations of the blocked of TTC
157
1. What will be the most appropriate block, where TTC should plan to install their
server?
2. Draw a block to cable layout to connect all the buildings in the most appropriate
manner for efficient communication.
3. What will be the best possible connectivity out of the following, you will suggest to
connect the new setup of offices in Bangalore with its London based office:
o Satellite Link
o Infrared
o Ethernet Cable
4. Which of the following device will be suggested by you to connect each computer in
each of the buildings:
o Switch
o Modem
o Gateway
Question 9:
Identify the following devices:
(i) Devices that are used to connect different types of networks. It performs the
necessary translation so that the connected networks can communicate properly.
(ii) A device that converts data from digital bit stream into an analog signal and vice-versa.
Question 10:
Rovenza Communications International (RCI) is an online corporate training provider company for
IT related courses. The company is setting up their new campus in Kolkata. You as a network
expert have to study the physical locations of various blocks and the number of computers to be
installed. In the planning phase, provide the best possible answers for the queries (i) to (iv) raised
by them.
158
Block to Block Distances(in Mtrs.)
1. Suggest the most appropriate block, where RCI should plan to install the server.
2. Suggest the most appropriate block to block cable layout to connect all three blocks
for efficient communication.
3. Which type of network out of the following is formed by connecting the computers of
these three blocks?
o LAN
o MAN
o WAN
4. Which wireless channel out of the following should be opted by RCI to connect to
students from all over the world?
o Infrared
o Microwave
o Satellite
159
UNIT – 3 DATABASE MANAGEMENT
MYSQL
It is freely available open source Relational Database Management System (RDBMS) that uses
Structured Query Language(SQL). In MySQL database, information is stored in Tables. A
single MySQL database can contain many tables at once and store thousands of individual
records.
➢ Reducing data redundancy – This ensures a consistent database and efficient use of
storage space.
➢ Aiding multiple views of the data: Database management system enables different users
to have a view of the data from their own perspective
➢ Implementation of data integrity The term data integrity refers to the accuracy and
consistency of data. When creating databases, attention needs to be given to data integrity
and how to maintain it.
➢ Data sharing and security – DBMS limits the accessibility of the data to the authorized
users only. This makes data sharing safer. Moreover shared data makes it possible to fulfill
data requirements with minimal modifications.
➢ Centralized data ensures a more effective backup and recovery process than the
conventional file processing systems.
➢ Program & Data independence: Programs and the data are not mutually dependent. If a
programmer wants to change the structure of the database then he/she can do so without
affecting the application programs that are using the database.
➢ Data Abstraction: It ensures that the users get an abstract view of the data without showing
implementation details and the physical storage of thedata.
160
2. Tuple: A row of a relation is generally referred to as a tuple.
6. Primary Key: This refers to a set of one or more attributes that can uniquely identify tuples
within the relation.
7. Candidate Key : All attribute combinations inside a relation that can serve as primary
key are candidate keys as these are candidates for primary key position.
8. Alternate Key: A candidate key that is not primary key, is called an alternate key.
9. Foreign Key : A non-key attribute, whose values are derived from the primary key of
some other table, is known as foreign key in its current table.
REFERENTIAL INTEGRITY
A referential integrity is a system of rules that a DBMS uses to ensure that relationships
between records in related tables are valid, and that users don’t accidentally delete or
change related data. This integrity is ensured by foreign key.
CLASSIFICATION OF SQL STATEMENTS
SQL commands can be mainly divided into following categories:
DATA TYPES
Data types are means to identify the type of data and associated operations for handling it.
MySQL data types are divided into three categories:
➢ Numeric
➢ Date and time
➢ String types
Numeric Datatype
1. int– used for number without decimal.
161
2. decimal(m,d) – used for floating/real numbers. m denotes the total length of number
and d is number of decimal digits.
Date and Time Datatype
1. date–used to store date in YYYY-MM-DD format.
2. time–used to store time in HH:MM:SS format.
String Datatype
1. char(m)–used to store a fixed length string, m denotes max. number of characters.
2. varchar(m)–used to store a variable length string, m denotes max. no. of characters.
DATABASE COMMANDS
1. VIEW EXISTING DATABASE
To view existing database names, the command is: SHOW DATABASES;
162
Eg: insert into employee values(1001,‘Ravi’,‘M’,‘E4’,50000);
Or
Insert into employee(ecode,ename)values(1002,’Meena’);
The left out columns will be filled with null values.
Select Command:
e.g.To display ECODE,ENAME and GRADE of those employees whose salary is between 40000
and 50000,command is:
SELECT ECODE , ENAME ,GRADE FROM EMPLOYEE
WHERE GROSS BETWEEN 40000 AND 50000;
163
NOTE: For displaying records not in the specified range, we have to use not between operator.
CONDITION BASED ON A LIST
The in operator is used to display records based on a list of values.
Eg. To display details of employees who have scored A,B and C grades.
Select * from employee where grade in(‘A’,’B’,’C’);
Note: For displaying records that do not match in the list, we have to use not in operator.
LIKE operator is used for pattern matching in SQL. Patterns are described using two special
wildcard characters: % and _ (underscore)
1. percent(%)– The % character matches any substring.
2. underscore(_)– The _ character matches any single character.
e.g.To display names of employee whose name starts with R in EMPLOYEE table, the command is:
select ename from employee where ename like “R%”;
2) To list all the employees’ details having grades as ‘E4’ but with gross < 9000.
164
Select ecode, ename, grade, gross from employee where grade=‘E4’ and gross< 9000;
3) To list all the employees’ details whose grades are other than ‘G1’.
Select ecode, ename, grade, gross from employee where (NOT grade= ‘G1’);
Results of SQL query can be sorted in a specific order using ORDER BY clause.
The ORDER BY clause allows sorting of query results by one or more columns. The sorting can be
done either in ascending or descending order.
Examples:
Select avg(gross) from employee;
Select min(gross) from employee where deptno= 10;
Select count(*) from emp where gross> 10000;
Select count (DISTINCT gender) from employee;
GROUP BY Clause
GROUP BY clause is used in SELECT statements to display the table contents based on similar
values in a column into groups.
165
Eg: To calculate the number of employees in each grade, the query is:
SELECT grade, count(*) from employee group by grade;
❖ The HAVING clause places conditions on groups in contrast to WHERE clause that places
conditions on individual rows.
❖ WHERE conditions cannot include aggregate functions but HAVING conditions can do so.
Eg: SELECT avg(gross), sum(gross) from employee GROUP BY grade HAVING grade= ‘E4’ ;
DELETE Command
Eg: To remove all the contents of items table, the query is:
DELETE from items;
Eg: To remove the tuples from employee that have gross less than 20000 is :
DELETE from employee WHERE gross<20000;
UPDATE Command
Update Command allows to change some or all the values in an existing rows. Update command
specifies the rows to be changed using the WHERE clause and the new data using the SET
keyword.
Eg. UPDATE employee SET gross= 25000;
The above query sets the gross of all records as 25000.
ALTER TABLE
ALTER TABLE command is used to change the structure of the existing table. It can be used to add
or drop new columns or modify the existing columns of table.
Eg. 1. Alter table Employee Add comm int;
2. ALTER TABLE Emp MODIFY (ename varchar(60));
3. Alter table emp drop comm;
DROP TABLE:
DROP TABLE command allows to remove a table from database. Once the DROP command is
issued, the table will no longer be available in the database.
166
Eg. DROP TABLE employee;
INTEGRITY CONSTRAINTS
A constraint is a condition or check applicable on a field or set of fields.
Common types of constraints include:
ALTER TABLE statement can be used to add constraints to your existing table by using it in
following manner:
SQL JOINS
SQL Joins are essential to display data from more than one table. SQL JOIN clause is used to
combine rows from two or more tables, based on a common field between them. SQL provides
various types of joins:
1. Cartesian Product or Cross Join
2. Equi-Join
3. Natural Join.
Equi-Join
A join which is obtained by putting a condition of equality on cross join is called an 'equi join'.
We can extract meaningful information from the Cartesian product by placing some conditions in the
statement.
The join in which columns are compared for equality is called equi-join.
In this type of join we put * in the select list therefore the common column will appear twice in the
output.
Example: Consider the 2 tables emp and dept.
168
Note: We see that deptno column appears twice in output.
Natural Join
• The join in which only one of the identical columns exists is called natural join.
• It is similar to equi-join except that duplicate columns are eliminated in natural join that would
otherwise appear in equi-join.
Example:
Worksheet – L3
170
(a) Alternate key
(b) Foreign key
(c) Primary key
(d) Super Key
Q10.A non-key attribute, whose values are derived from primary key of some other
table.
(a) Alternate key
(b) Foreign key
(c) Primary key
(d) Super Key
Q21. How can you insert a new row into the “STORE” table.
(a) INSERT ROW(1,‟RAMSINGH‟)INTO STORE;
(b) INSERT VALUES(1,‟RAMSINGH‟)INTO STORE;
(c) INSERT INTO(1,‟RAMSINGH‟)STORE;
(d) INSERT INTO STORE VALUES(1,‟RAMSINGH‟);
Q24. The .................. key word eliminates duplicate rows from the result of a
SELECT statement.
(a) All
(b) Unique
(c) Distinct
(d) IN
Q25. Which operator defines a range of values that the column values must fall in?
(a) In
(b) Like
(c) Between
(d) Is
Q26. To specify a list of values ............... Operator is used.
(a) In
(b) Like
(c) Between
(d) Is
Q27. We use .................. operator with select for condition based on pattern matching.
(a) In
(b) Like
(c) Between
(d) Is
Q28. Which SQL statement will not generate any error message?
(a) SELECT*FROM EMP WHERE EMPNO LIKE(1,2,3,4);
(b) SELECT*FROM EMP WHERE SAL BETWEEN 3000 TO 15000;
(c) SELECT*FROM EMP WHERE COMM IS NOT NULL;
(d) All of the above
Q29.To display the detail of employee having ‘e’ in their name in descending order of
salary. The correct SQL statement is:
(a) SELECT*FROM emp WHERE ename LIKE “e%” ORDER BY SAL;
(b) SELECT*FROM emp ORDER BY SAL DESC WHERE ename LIKE
173
“%e%”;
(c) SELECT*FROM emp WHERE ename LIKE “%e%” ORDER BY DESC
SAL;
(d) SELECT*FROM emp WHERE ename LIKE “%e%” ORDER BY SAL
DESC;
174
Answers
Q.No. Answers
1 B
2 C
3 A
4 d
5 d
6 c
7 a
8 c
9 a
10 b
11 d
12 a
13 a
14 c
15 d
16 c
17 d
18 d
19 b
20 d
21 d
22 b
23 a
24 c
25 c
26 a
27 b
28 c
29 d
30 d
175
WORK SHEET -2
Q2. The clause which is used to group rows based on distinct values that exist
for specified column.
Q3. For conditionally retrieval of row from groups which clause is used?
(a) All
(b) Distinct
(c) Unique
(d) Diverse
Q6. Which option cause a group functions to consider all values including
all duplicated.
(a) All
(b) Distinct
(c) Unique
176
(d) Diverse
(a) AVG
(b) COUNT
(c) MAX
(d) MOD
Consider the relations/tables EMP and DEPT and give the correct answer of following
queries.
Relation: EMP
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 1980-12-17 800.00 NULL 20
7499 ALLEN SALESMAN 7698 1981-02-20 1600.00 300.00 30
7521 WARD SALESMAN 7698 1981-02-22 1250.00 500.00 30
7566 JONES MANAGER 7839 1981-04-02 2975.00 NULL 20
7654 MARTIN SALESMAN 7698 1981-09-28 1250.00 1400.00 30
7698 BLAKE MANAGER 7839 1981-05-01 2850.00 NULL 30
7782 CLARK MANAGER 7839 1981-06-09 2450.00 NULL 10
7788 SCOTT ANALYST 7566 1982-12-09 3000.00 NULL 20
7839 KING PRESIDENT NULL 1981-11-17 5000.00 NULL 10
7844 TURNER SALESMAN 7698 1981-09-08 1500.00 0.00 30
7876 ADAMS CLERK 7788 1983-01-12 1100.00 NULL 20
7900 JAMES CLERK 7698 1981-12-03 950.00 NULL 30
7902 FORD ANALYST 7566 1981-12-03 3000.00 NULL 20
7934 MILLER CLERK 7782 1982-01-23 1300.00 NULL 10
Relation: DEPT
DEPTNO DNAME LOC
10 ACCOUNTING NEWYORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
Q8. SELECT AVG(SAL) FROM EMP WHERE JOB=‘CLERK’;
(a)1037.5
(b)2073.21
(c)1040
(d)2074
(a) 14
(b) 3
(c) 4
(d) 5
177
Q10. SELECT COUNT(DISTINCT JOB) FROMEMP;
(a) 14
(b) 5
(c) 4
(d) 6
(a) 14
(b) 5
(c) 4
(d) 6
(a)2975
(b)5000
(c)3000
(d)2850
(a) 1980-12-17
(b) 1983-01-12
(c) 1982-12-09
(d)None
(a) 1980-12-17
(b) 1983-01-12
(c) 1982-12-09
(d)None
(a) Null
(b) 0
(c)2200
(d)1400
Q17. To display the jobs where the number of employees is less than 3.
(a) SELECT JOB,COUNT(*)FROM EMP WHERE COUNT(*)<3;
(b) SELECT JOB, COUNT(*) FROM EMP WHERE COUNT(*)<3
GROUP BY JOB;
(c) SELECT JOB, COUNT(*) FROM EMP GROUP BY JOB WHERE
COUNT(*)<3;
(d) SELECT JOB,COUNT(*)FROM EMP GROUP BY JOB HAVING COUNT(*)
<3;
Q18.Which join is used for display all possible concatenations are formed of all
rows of two or more tables.
Q19. How many rows are returned when we execute ‘SELECT*FROM EMP,DEPT’;
(a) 14
(b) 4
(c) 18
(d) 56
Q20.To display the name of employee & department name the MySQL statement
used:
(a) SELECT ENAME, DNAME FROM EMP,DEPT;
(b) SELECT ENAME, DNAME FROM EMP,DEPT
WHERE DEPTNO=DEPTNO;
(c) SELECT ENAME, DNAME FROM EMP,DEPT
WHERE EMP.DEPTNO=DEPT.DEPTNO;
(d) None of the above
179
Q22. The join in which only one identical column exists is called………
180
Answers
Q.No. Answers
1 A
2 C
3 C
4 A
5 C
6 C
7 D
8 D
9 B
10 C
11 B
12 B
13 D
14 A
15 B
16 D
17 B
18 A
19 D
20 A
21 B
22 B
23 A
24 A
25 a
INTERFACE PYTHON WITH MYSQL
Basically the process of transfer data between python programs and MySQL database is known as Python
Database Connectivity.
There few steps you have to follow to perform Python Database Connectivity. These steps are as follow:
1. Import the required packages
2. Establish a connection
3. Execute SQL command
4. Process as per the requirements
To perform the Python MySQL Database Connectivity you need to install mysql-connector-python package
using pip command.
pip install mysql connector python
After installation just write the import statement to import the package in python code.
import mysql.connector as msql
Establish a connection
To establish a connection you need to create a connection object in Python. Take a variable as a connection
object and use connect() function with MySQL database specification like host name, username,
passoword or passwd and database itself. For example cn. Observe the code:
Please ensure that you have provided appropriate username, password and database name available in your
MySQL interface.
After doing this, check for the errors if any. If your program runs without errors that means connection is
established. Although you can use is_connected() function to check whether the connection is established
or not! Observe this code:
182 | P a g e
cn=msql.connect(host='localhost',user='root',passwd='root',database='Student')
if cn.is_connected():
print("Connection Established")
else:
print("Connection Errors! Kindly check!!!")
The next step after the successful connection is to write SQL command and fetch rows. The SQL
commands are used to perform DML operations and fetch rows read data from table. So we will see them in
detail later.
You have to create a cursor object for executing SQL command and fetch rows. Cursor object is a special
kind of structure that processes the data row by row in database. You can create cursor object in the
following manner.
cur=cn.cursor()
To perform the DML operations like insert, update or delete follow these steps:
1. Create a cursor object
2. Write command as parameters for execute() function
3. Use commit() function to save the changes and reflect the data in the table.
insert command
update command
delete command
Select Command
As you know the select command is used retrieve records from the database. The result is available in the
resultset or dataset. You can store the select the command in cursor object in python. Then for resultset you
can use the fetch…() function. These are:
1. fetchall(): It will retrieve all data from a database table in form of record or tuple or a row.
2. fetchone(): It will retrieve one record from the resultset as a tuple or a list. It returns the records in a
specific order like first record, the next time next record and so on. If records are not available then
it will return None.
3. fetchmany(n): It will retrieve a number of records from the database. If records are not available
then it will return an empty tuple.
4. rowcount: It is one of the properties of cursor object that return number of rows fetched from the
cursor object.
184 | P a g e
d=cur.fetchone()
print(d)
time.sleep(3)
d=cur.fetchone()
print(d)
time.sleep(3)
d=cur.fetchone()
time.sleep(3)
print(d)
Parameterized Queries
Sometimes we need to access values as per the user’s input. The query result is based on the values user has
passed. So for that we have this option parameterized queries. There are two ways to use parameterized
queries:
1. with % formatting pattern
2. with {}.format pattern
This pattern takes the general form – f % v, where f is a format and v is the value. Consider the following
code:
import mysql.connector as msql
import time
cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')
cur=cn.cursor()
185 | P a g e
cur=cn.cursor()
cur.execute("select * from students where marks >{}" .format(80))
d=cur.fetchall()
for r in d:
print(r)
cur.execute("select * from students where grade='{}'".format('B1'))
d=cur.fetchall()
for r in d:
print(r)
Finally, you have to close the established connect using close() function. It will help to clean up the
memory. Observe the following code:
con.close()
WORKSHEETS
1. A database _________ controls the connection to an actual database, established from within a
Python program.
(a) database object (b) connection object (c) fetch object (d) query object
186 | P a g e
Ans. (b)
2. The set of records retrieved after executing an SQL query over an established database connection is
called ___________ .
(a) table (b) sqlresult (c) result (d) resultset
Ans. (d)
3. A database _________ is a special control structure that facilitates the row by row processing of
records in the resultset.
(a) fetch (b) table (c) cursor (d) query
Ans. (c )
4. To obtain all the records retrieved, you may use the <cursor>. _______ method.
(a) fetchmany( ) (b) fetchall( ) (c) fetchone( ) (d) fetchmultiple( )
Ans. (b)
5. To reflect the changes made in the database permanently, you need to run <connection>. _______
method.
(a) done (b) reflect (c) commit (d) final
Ans. (c)
6. To run an SQL query within Python, you may use the <cursor>. _______ method.
(a) query (b) execute (c) run (d) None of the above
Ans. A connection (represented by the connection object) is the session between the application
program and database. To do anything with database, one must have a connection object.
3. What is a resultset?
Ans. A result set refers to a logical set of records that are fetched from the database by executing a
187 | P a g e
query and made available to the application program.
Ans. A database cursor is a special control structure that facilitates row by row processing of records in
the result set, i.e., the set of records retrieved as per the query.
i. fetchall( ) – fetches all the remaining rows of a query result, current pointer position
forwards
ii. fetchone( ) – fetches the next row as a sequence; returns None when no more data
*************
189 | P a g e