0% found this document useful (0 votes)
15 views

Class XII CS Notes All Chapters

The document provides an overview of Python programming, including its features, applications, and basic concepts such as variables, data types, and operators. It highlights Python's versatility as a general-purpose language and its ease of learning, making it suitable for various applications like data science, web development, and artificial intelligence. Additionally, it covers the installation of Python, the use of different IDEs, and the structure of Python code, including tokens, keywords, and literals.

Uploaded by

hisas29681
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Class XII CS Notes All Chapters

The document provides an overview of Python programming, including its features, applications, and basic concepts such as variables, data types, and operators. It highlights Python's versatility as a general-purpose language and its ease of learning, making it suitable for various applications like data science, web development, and artificial intelligence. Additionally, it covers the installation of Python, the use of different IDEs, and the structure of Python code, including tokens, keywords, and literals.

Uploaded by

hisas29681
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 167

Unit-I Computational Thinking and Programming – 2

Revision of Python topics covered in class XI


PYTHON BASICS
Python is a simple, general purpose, high level, and object-oriented programming
language.Python is an interpreted scripting language also. Guido Van Rossum is the founder of
Python programming language.Guido was a fan of the popular BBC comedy show of that time,
"Monty Python's Flying Circus". So he decided to pick the name Python for his newly created
programming language.

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.

Applications of Python Programming Language


• Data Science
• Date Mining
• Desktop Applications
• Console-based Applications
• Mobile Applications
• Software Development
• Artificial Intelligence
• Web Applications
• Enterprise Applications
• 3D CAD Applications
• Machine Learning

23
• Computer Vision or Image Processing Applications.
• Speech Recognitions

How To Use Python?


Python can be downloaded from www.python.org. (Standard Installation)
It is available in two versions-
• Python 2.x
• Python 3.x (It is in Syllabus)
Apart from above standard Python. We have various Python IDEs and Code Editors. Some of them
are as under:
(i) Anaconda Distribution: free and open-source distribution of the Python, having various inbuilt
libraries and tools like Jupyter Notebook, Spyder etc
(ii) PyCharm (iii) Canopy (iv) Thonny (v) Visual Studio Code (vi) Eclipse + PyDev
(vii) Sublime Text (viii) Atom (ix) GNU Emacs (x) Vim (xi) Spyder and many
more . .

Python Interpreter - Interactive And Script Mode:


We can work in Python in Two Ways:
(i) Interactive Mode: It works like a command interpreter as shell prompt works in DOS Prompt or
Linux. On each (>>>) symbol we can execute one by one command.
(ii) Script Mode: It used to execute the multiple instruction (complete program) at once.

Python Character Set:


Character Set is a group of letters or signs which are specific to a language. Character set includes
letter, sign, number and symbol.
• Letters: A-Z, a-z
• Digits: 0-9
• Special Symbols: _, +, -, *, /, (, #,@, {, } etc.
• White Spaces: blank space, tab, carriage return, newline, form feed etc.
• Other characters: Python can process all characters of ASCII and UNICODE.
Tokens
A token is the smallest individual unit in a python program. All statements and instructions in a
program are built with tokens.It is also known as Lexical Unit.
Types of token are
• Keywords
• Identifiers (Names)
• Literals
• Operators
• Punctuators

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

Assignment operators: used to assign values to variables


= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Comparison Operators: Comparison operators are used to compare two values.


== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Logical Operators: Logical operators are used to combine conditional statements


and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)

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

Membership operators: used to test if a sequence is present in an object.


in Returns True if a sequence with the specified x in y
value is present in the object
not in Returns True if a sequence with the specified x not in y
value is not present in the object

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)

Assigning Values to Variables


Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to assign
values to variables. Also Python allows you to assign a single value to several variables
simultaneously.
The operand to the left of the = operator is the name of the variable and the operand to the right of the
= operator is the value stored in the variable
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string

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.

The different standard data types −


• Numbers

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

Python supports four different numerical types


• int (signed integers)
• long (long integers, they can also be represented in octal and hexadecimal)
• float (floating point real values)
• complex (complex numbers)
int long float complex
10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j
-786 0122L -21.9 9.322e -36j
080 0xDEFABCECBDAE 32.3+e18 .876j
-0490 535633629843L -90. -.6545+0J
-0x260 -052318172735L -32.54e100 3e+26J
0x69 -4721885298529L 70.2-E12 4.53e-7j

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!'

print str # Prints complete string Hello World!


print str[0] # Prints first character of the string H

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 and Immutable Objects in Python


Everything in Python is an object. So, every variable holds an object instance. All objects in Python
can be either mutable or immutable. When an object is initiated, it is assigned a unique object id.
Its type is defined at runtime and once set can never change, however its state can be changed if it
is mutable. Generally, a mutable object can be changed after it is created, and an immutable object
can’t.

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

❖ Exception: However, there is an exception in immutability as well.Tuple in python is


immutable. But the tuple consists of a sequence of names with unchangeable bindings to
objects.

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

Types of Expression in Python


Constant Expressions x = 10 + 15
Arithmetic Expressions y=x**3+x-2+5/2
Integral Expressions x=10 y=5.00 result = x + int(y)
Floating Expressions result = float(x) + y
Relational Expressions 10+15>20
Logical Expressions r=x and y
Combinational Expressions result = x + (y << 1)

Type Casting in Python


Type Casting is the method to convert the variable data type into a certain data type in order to the
operation required to be performed by users.
There can be two types of Type Casting in Python –
• Implicit Type Casting
• Explicit Type Casting

Implicit Type Conversion


In this, methods, Python converts data type into another data type automatically, where users don’t
have to involve.

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

Explicit Type Casting


In this method, Python need user involvement to convert the variable data type into certain data type
in order to the operation required.Mainly in type casting can be done with these data type function:

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.

E,g, # int variable


a=5
# typecast to float
n = float(a)
print(n)
print(type(n))

Precedence and Associativity of Operators


Operator Precedence: This is used in an expression with more than one operator with different
precedence to determine which operation to perform first.

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’

ii. Multi-line comment (‘‘‘………..’’’) – Comments multiple line.


e.g. ‘‘‘Program -1
A program in python to store a value invariable ‘a’ and display the value stored in it.’’’
a=7
print(a)

Python Input and Output


Python executes code top to bottom, when written in the correct syntax.Once the interpreter is running
you can start typing in commands to get the result.

Input using the input( ) function


input (): This function first takes the input from the user and converts it into a string. The type of the
returned object always will be <type ‘str’>. It does not evaluate the expression it just returns the
complete statement as String. Python provides a built-in function called input which takes the input
from the user. When the input function is called it stops the program and waits for the user’s input.
When the user presses enter, the program resumes and returns what the user typed.
name = input('What is your name?\n')
What is your name?
Ram

Taking multiple inputs from user

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()]

Output using print() function


print() : function prints the message on the screen or any other standard output device.

print(value(s), sep= ' ', end = '\n', file=file, flush=flush)

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

Compile Time Errors


These errors occur when we violate the rules present in a syntax. The compile-time error indicates
something that we need to fix before compiling the code. A compiler can easily detect these errors.
Eg Syntax error and Semantic Error.
Logic errors
These errors are not always easy to recognize immediately. This is due to the fact that such errors,
unlike that of syntax errors, are valid when considered in the language, but do not produce the
intended behavior. These can occur in both interpreted and compiled languages. It may occur due to
the logic of the program.
36
Runtime Errors
These errors occur during the run-time program execution after a successful compilation. Division
error is one of the most common errors (runtime). It occurs due to the division by zero. It is very
difficult for a compiler to find out a runtime error because it cannot point out the exact line at which
this particular error occurs.
---------------------------------------------------------------------------------------------------------------------
Control flow statements
The control flow of a Python program is regulated by conditional statements, loops, and function
calls. In order to control the flow of execution of a program there are three categories of statements
in python. They are:
1. Selection statements
2. Iteration statements
3. Jump statements / Transfer statements

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)

Ladder if else statements (if-elif-else)


The Python compound statement if, which uses if, elif, and else clauses, lets you conditionally
execute blocks of statements. Here’s the syntax for the if statement:
if expression:
statement(s)
elif expression:
statement(s)
elif expression:
statement(s)
...
else:
statement(s)
Example

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

num=int(input(“Enter Number: “))


if ( num<=0):
if ( num<0):
print(“You entered Negative number”)
else:
print(“You entered Zero ”)
else:
print(“You entered Positive number”)

Python Iteration Statements

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)

---------------------------------------------------------------------------------------------------------------------

Python range( ) Function


The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1
(by default), and ends at a specified number.
Syntax:
range( start value, stop value, step value )
Where all 3 parameters are of integer type
● Start value is Lower Limit
● Stop value is Upper Limit
● Step value is Increment / Decrement
Note: The Lower Limit is included but Upper Limit is not included in result.

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

Which of the following is not a Tuple in Python ? (1)


(a) (1,2,3) (b) (‘one’,two’,’three’) (c) (10,) (d) (‘one’)
1
Ans: (‘one’)

What will be output of the following code snippet: (1)


A=[1.2.3.4,5]
2
print(a[3:0:-1])
Ans : [4,3,2]
Write the output of the code given below: (2)
my_dict = {"name": "Kuhan",'Door No.': 100}
my_dict["Door No."] = 128
3
my_dict['address'] = "Karnataka"
print(my_dict.items())
Ans: dict_items([('name', 'Kuhan'), ('Door No.', 128), ('address', 'Karnataka')])
Find and write the output of the following python code:
Msg="CompuTer"
Msg1=''
for i in range(0, len(Msg)):
if Msg[i].isupper():
Msg1=Msg1+Msg[i].lower()
4 (4)
elif i%2==0:
Msg1=Msg1+'*'
else:
Msg1=Msg1+Msg[i].upper()
print(Msg1)
Ans: cO*P*t*R

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)

5. Consider the given expression : (1)


not True and True or False
Ans : False
6. Given is a Python string declaration: (2)
myexam="@@CBSE Examination 2022@@"
Write the output of: print(myexam[::-3])
Ans: @2 ina B@
7. What will be the output if entered number n is 1 and n is 4 : (3)
i=2
n=int(input("enter the value of n"))
while i<n:
if n % i==0:
break
print(i)
i=i+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

1 State True or False:


The # symbol used for inserting comments in python is a token (1)
Ans : True
2 Which of the following invalid identifier in Python?
(a) name (b) section (c) true (d) break (1)
Ans: (d) break
3 Evaluate the following expressions :
(2)

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)

WORKING WITH FUNCTIONS


Function Definition:
A function is a programming block of codes which is used to perform a single, related,
specific task. It only works when it is called. We can pass data, known as parameters, into a function.
A function can return data as a result.
Python treats functions like a first-class member. It implies that in Python, functions and other
objects are of same significance.Functions can be assigned to variables, stored in collections, or
passed as arguments. This brings additional flexibility to the language.

Advantages of Functions
• Reducing duplication of code
• Decomposing complex problems into simpler pieces
• Improving clarity of the code
• Reuse of code
• Information hiding

Python function types


There are three categories of functions:
• Built-in functions

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.

Structure of functions in Python

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)

Flow of execution in a function call


The flow refers to the order in which statements are executed during a program run. The
function body is a block of statements and python executes every block in an execution frame.
An execution frame contains:
• Some internal information (used for debugging)
• Name of the function
• Values passed to the function
• Variables created within the function
48
• Information about the next instruction to be executed

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.

Parameters and Arguments


The parameters are the variables that we can define in the function declaration. In fact, we
utilized these variables within the function. Also, the programming language in the function
description determines the data type specification. These variables facilitate the function’s entire
execution. In addition, they are known as local variables because they are only available within the
function.
The arguments are the variables given to the function for execution. Besides, the local
variables of the function take the values of the arguments and therefore can process these parameters
for the final output.

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”)

2. With Argument No return


def Add(a,b):
c=a+b
51
print(“The Sum of inputted Numbers is:”, c)
num1=int (input(“Enter First Number”))
num2= int (input(“Enter Second Number”))
add(num1,num2)

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)

Calling function and Called function:


• Function which is called by another Function is called Called Function. The called
function contains the definition of the function and formal parameters are associated
with them.
• The Function which calls another Function is called Calling Function and actual
Paramaters are associated with them.
• In python, a function must be defined before the function call otherwise
python interpreter gives an error.

Difference between Arguments and parameters


These two terms are very interchangeable, so it is not so important to know the difference.
The terms they refer to are almost identical. However, in order to sound more professional, correct
terminology is important.
Function Parameters: Variables that are in brackets when defining the function. When a method is
called, the arguments are the data passed to the method’s parameters.
52
Function arguments : Arguments are used to pass information from the rest of the program to the
function. This information return a result. There is no limit to the number of arguments that can be
written. Depending on the type of function you’re performing, there might even be no argument.
Use commas to separate the arguments in a function. Take into account the number of
arguments you put in a function call. The number of arguments must be exactly the same as the
number of parameters.

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.

Name Resolution(Scope Resolution)


For every name used within program, python follows name resolution rules known as
LEGB rule.
• Local Environment : first check whether name is in local environment, if yes Python uses
its value otherwise moves to (ii)

• Enclosing Environment:if not in local,Python checks whether name is in Enclosing


Environment, if yes Python uses its value otherwise moves to (iii)

• Global Environment:if not in above scope Python checks it in Global environment, if


yes Python uses it otherwise moves to (iv)

• Built-In Environment:if not in above scope, Python checks it in built-in environment, if


yes, Python uses its value otherwise Python would report the error: name <variable>
notdefined.

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

4. What is the output of the below program?

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

5. The default value for a parameter is defined in function ………..


6. Python names the top level segment as…………..
7. Variable declared inside functions may have global scope (True/False)
8. Which arguments given below is skipped from function call?
a)Positional b)Default c)Keyword d)named
9. What is the order of resolving scope in Python?
a)BGEL b)LEGB c)GEBL d)LBEG
10.Complete the function body.
def f(num):
…………..
print (f(8))
a)return 0 b)print(num) c)print(“num”) d)return num
11. The function pow(x,y,z) is evaluated as:
a) (x**y)**z b) (x**y) / z c) (x**y) % z d) (x**y)*z
12. The function seed is a function which is present in the ……………..module
13. What are the outcomes of the functions shown below?
sum(2,4,6)
sum([1,2,3])
14. What is the output of the functions shown below?
min(max(False,-3,-4), 2,7)
a) 2 b) False c) -3 d)0
15. What is the output of the programgiven below?
a = 100
def func (a) :
a = 20
func (a)
print (' a is now ', a)
A. a is now 50
B. a is now 100
C. a is now 2
D. error

16. What will be the output of the following python code:


val = 100
def display(N):
global val
val = 50
if N%14==0:
56
val = val + N
else:
val = val - N
print(val, end="@")
display(40)
print(val)
A. 100@10
B. 50@5
C. 5@50
D. 100@10@
17. What will be the output of the following python code:
def A_func (x=10, y=20):
x =x+1
y=y-2
return (x+y)
print(A_func(5),A_func())
A. 24,29
B. 15,20
C. 20,30
D. 25,30
18. Consider the following code and choose correct answer
def nameage(name=”kishan”, age=20):
return age,name
t=nameage(20,”kishan”)
print(t[1])
A. kishan
B. 20
C. (kishan, 20)
D. (20,kishan)

II. Questions (2 marks)


1. Write the output of the pseudocode
def absolute_value(num):
if num>= 0:
return num
else:
return -num
print(absolute_value(2))

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

III Answer the following 3 marks

1 Floor Function Ceil Function


floor function returns the integer ceil function returns the integer
value just lesser than the given value just greater than the given
rational value. rational value
represented as floor(x). represented as ceil(x)
The floor of negative fractional The ceil of negative fractional
numbers is represented using the numbers are represented using ceil
floor function function.
It returns the value which is just It returns the value which is just
less than or equal to the given greater than or equal to the given
value. value.
Eg. the floor of 78.38 is 78 and the Eg. ceil of 78.38 is 79 and ceil of -
floor of -39.78 is -40. 39.78 is -39.

IV Answer the following 5 marks


1 Python supports four argument types:
Positional Arguments: Arguments passed to a function in correct positional
order, no. of arguments must match with no. of parameters required.
Default Arguments: Assign a default value to a certain parameter, it is used
when the user knows the value of the parameter, default values are specified
in the function header. It is optional in the function call statement. If not
provided in the function call statement then the default value is considered.
Default arguments must be provided from right to left.
Key Word Arguments: Keyword arguments are the named arguments with
assigned values being passed in the function call statement, the user can
combine any type of argument.
Variable Length Arguments: It allows the user to pass as many arguments
as required in the program. Variable-length arguments are defined with the *
symbol.

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.

Formal Parameter is a parameter, which is used in function header of the


called function to receive the value from actual parameter. It is also known
as Parameter. For example,

def addEm(x, y, z):


print(x + y + z)
addEm (6, 16, 26)

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

3. What is the output of the below program?


def func(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is', c)
func(3, 7)
func(25, c = 24)
func(c = 50, a = 100)
60
a)
a is 7 and b is 3 and c is 10
a is 25 and b is 5 and c is 24
a is 5 and b is 100 and c is 50
b)
a is 3 and b is 7 and c is 10
a is 5 and b is 25 and c is 24
a is 50 and b is 100 and c is 5
c)
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
d) None of the mentioned
4. What is the output of below program?
def maximum(x, y):
if x > y:
return x
elif x == y:
return 'The numbers are equal'
else:
return y
print(maximum(2, 3))
a) 2
b) 3
c) The numbers are equal
d) None of the mentioned

5. A function is executed in an execution frame. True / False


6. Function returning values are also known as ………. Functions
7. Default return value for a function that does not return any value is …..
8. Where is the function call and parameters stored in the system?
a.Heap b.Queue c.Array d.Stack
9. What is the output of the function shown below?all([2,4,0,6])
a) Error b) True c) False d)0
10. What is the output of the following function?any([2>8, 4>2, 1>2])
a) Error b) True c) False d) 4>2
11. What is the output of the function shown below?
import math.abs(math.sqrt(25))
a) Error b) -5 c) 5 d) 5.0
12. What is the output of the function: all(3,0,4.2)
a) True b) False c) Error d)0
13. What is the output of the function complex() ?
a) 0j b) 0+0j c) 0 d) Error

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

15. Identify correct output (K)


def fun3(a,b,c):
return a+1,b+2,c+3
t=fun3(10,20,30)
print(t)
A. 11,22,33
B. 11 22 33
C. (11, 22, 33)
D. (11 22 33)
16. The correct way to call a function is:
A. A_func()
B. def A_func()
C. return A_func()
D. call A_func()
Questions (2 marks)
1. What is the output of the below program?
def sayHello():
print('Hello World!')
sayHello()
sayHello()

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)

3. Trace the following code and predict output produced by it.


(a)
1. def power (b, p):
2. y = b **p
3 return y
4.
5 def calcSquare(x) :
6. a = power (x, 2)
7. return a
8.
9. n=5
10. result = calcSquare (n) + power (3, 3)
11. print(result)

(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

II Answer the following 2 marks


64
1 Hello World!
Hello World!
2 Function header-- def processNumber(x):
Function call--- processNumber (y)
Arguments----- y
Parameters ----- x
Function body-------x = 72
return x + 3
Main program-------- y = 54
res processNumber(y)

III Answer the following 3 marks


1 A function is a set of instructions or subprograms that are used to perform a
specific task. It divides the large program into smaller blocks of a program that
processes the data and often returns a value. Functions are needful
-To make the program easy
-Divide the large program into a small block of codes
-Reduce the lines of code
-Easy to update
-Reuse of the code is possible
-Error correction is easier

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.

Formal Parameter is a parameter, which is used in function header of the called


function to receive the value from actual parameter. It is also known as
Parameter. For example,

def addEm(x, y, z):


print(x + y + z)
addEm (6, 16, 26)

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

II. Questions (2 marks)


1. What is the local variable and global variable?
2. Write the output of the code
def res():
eng = 56
math = 40
sci = 60
if eng<=35 || math<=35 || sci=35:
print(‘Not Qualified’)
else:
print(“Qualified”)

res()

3. Write the output of the code


def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()

68
print("Value outside function:",x)
4. What are default arguments? What are the advantages of keyword arguments?

III. Questions (3 marks)


1. What is a function? Why do we need functions in python programming?
2. Write and explain the types of functions supported by python.
3. What are keyword arguments?
4.
IV. Questions (5 marks)
1. Explain the following built-in functions.
(a) id ()
(b) chr ()
(c) round ()
(d) type ()
(e) pow ()

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.

Local Variable: A name declared in a specific function body is called a


local variable
2 Qualified
3 Value inside function: 10
Value outside function: 20
4 Python allows function arguments to have default values; if the function is
called without the argument, the argument gets its default value
III Answer the following 3 marks
2 Built in Functions: Pre-defined functions of python such as len(), type(),
input() etc.
Functions defined in modules: Functions defined in particular modules, can
be used when the module is imported. A module is a container of functions,
variables, constants, classes in a separate file which can be reused.
User Defined Functions: Function created by the programmer
4 If there is a function with many parameters and we want to specify only
some of them in function call,
then value for such parameters can be provided by using their names instead
of the positions. These are called keyword argument.

(eg) def simpleinterest(p, n=2, r=0.6)


def simpleinterest(p, r=0.2, n=3)

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.

(b) chr ():


Return the string representing a character whose Unicode code point is the integer
i. For example, chr(97) returns the string 'a', while chr(8364) returns the string
'€'. This is the inverse of ord().
The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base
16). ValueError will be raised if i is outside that range.

(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.

In Python, File Handling consists of following three steps:


• Open the file.
• Process file i.e.perform read or write operation.
• Close the file.
72
Opening Files :
To perform file operation, it must be opened first then after reading, writing,editing
operation can be performed.To create any new file then too it must be opened. On opening
of any file, a file relevant structure is created in memory as well as memory space is created
to store contents. Once we are done working with the file, we should close the file.
Itisdoneusing open() function as per one of the following syntax:
<fileobjectname>=open(<filename>)
<fileobjectname>=open(<filename>,<mode>)
For example:
stu=open("students.txt")
The above statement open file"students.txt" in file mode as read mode(defaultmode) and attaches it to
file object namely stu.
Consider one more file open statement: - stu=open
("e:\\main\\students.txt","w")
The above statement open file"students.txt"(storedinfoldere:\main)in write mode(because
of"w"givenasmode)and attaches it to file object namely stu.

• 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+’ ‘ab+’ Read and write – Append new data

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

Reading from Text Files


Python provides three types of read functions to read from a data file.
• Filehandle.read([n]) : reads and return n bytes, if n is not specified it reads entire file.
• Filehandle.readline([n]) : reads a line of input. If n is specified reads at most n bytes. Read
bytes in the form of string ending with line character or blank string if no more bytes are left
for reading.
• Filehandle.readlines(): reads all lines and returns them in a list
Examples:
Let a text file “Book.txt” has the following text:

“Python is interactive language. It is case sensitive language.


It makes the difference between uppercase and lowercase letters. It is official language of
google.”

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:

fin=open("D:\\python programs\\Book.txt",'r') Python is interactive language. It is case sensitive


str=fin.readline( ) language.
print(str) fin.close( )
Example-4:usingreadlines()function: OUTPUT:

fin=open("D:\\python programs\\Book.txt",'r') ['Python is interactive language. It is case


str=fin.readline( ) sensitive language.\n', 'It makes the difference
print(str) between uppercase and lowercase letters.\n', 'It
fin.close( ) is official language of google.']

Writing onto Text Files:


Like reading functions , the writing functions also work on open files.
• <filehandle>.write(str1): Wrties string str1 to file referenced by <file handle>.
• <filehandle>.writelines(L): Wrties all strings in list L as lines to file referenced by
<file handle>.

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( )

Example-2:Program using writelines()function: OUTPUT:


f=open(r’Myfile.txt’,’a’) #It will append the content.
data=[‘I have a dog., ‘\nI love my cat.’]
f.writelines(data)
My name is Aarav.I have a dog.
f.close( )
f=open(r’Myfile.txt’,’r’) I love my cat.
data = f.read( )
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

1 To open a file "c:marks.txt" for reading, we use


(a) file_read = open("c:marks.txt", "r")
(b) file_read = open("c:marks.txt", "r") 1
(c) file_read = open(file = "c:marks.txt", "r")
(d) file_read = open(file = "c:marks.txt", "r")
2 What is the use of tell() method in Python?
(a) returns the current position of record pointer within the file
(b) returns the end position of record pointer within the file 1
(c) returns the current position of record pointer within the line
(d) none of the above
3 Which of the following commands can be used to read "n" number of characters from
a file using the file object <File>? 1
(a) File.read(n) (b) N = file.read() (c) File.readline(n) (d) File.readlines()
4 What is the correct syntax of open() function?
(a) File = open(file_name[, access_mode][, buffering])
(b) File object = open(file_name [, access_mode][,buffering]) 1
(c) File object = open(file_name)
(d) None of the above
5 Write the coding to display the content of file "welcome.txt". 1
6 Write the output of the given program:

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

the output of the given program:


6 Write a function to count the Upper case vowel in file “All.txt”. 2
7 Write a function to read the content from the file “Story.txt”. The function will take a
string as parameter 2
and search the string into the file.
8 Aarti is new in python data-handling. Please help her to count the number of lines
which begins with ‘W’ or ‘w’ in poem.txt.

(a) # Line 1 : To open file POEM.txt in read mode


(b) # Line 2 : To check first character of every line is ‘W’ or ‘w’.
(c) # Line 3 : To increase the value of count by 1.
(d) # Line 4 : To call the function count_poem.

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

8 (a) file1 = open("POEM.TXT","r")


(b) r1[0]=='W' or r1[0]=='w':
(c) count=count+1
(d) count_Poem()
LEVEL-3
1 To read the content of the file as a string via a file object "f"
1
(a) f.read(2) (b) f.read()(c) f=file.readline() (d) f.readlines()
2 The readlines() returns
(a) only first line from the file
(b) only last line from the file 1
(c) all lines from the file
(d) none of the above
3 Observe the following code and answer the questions that follow:

(i) What type (Text/Binary) of file is Mydata?


(ii) Fill the Blank 1 with statement to write “ABC” in the file “Mydata”.
81
4 A text file “Quotes.Txt” has the following data written in it:
Living a life you can be proud of
Doing your best
Spending your time with people and activities that are important to you
Standing up for things that are right even when it’s hard
1
Becoming the best version of you.

Write the output of the given program.

5 Write a method in Python to read lines from a text file INDIA.TXT, to find and

display the occurrence of the word "India".

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}

7 Mohan has written the following code:

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.

What will be the output?


(i) True (ii) False (iii) None (iv) Error
(c) The read() method returns____________.
(i) str (ii) list (iii) tuple (iv) None of these
(d) The readline() method returns ______________.
(e) The readlines() method returns _______________.

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

7 (a) (iii) It will display first 20 bytes.


(b) (i) True
(c) (i) str
(d) str (e) list

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:

• read: This mode is written as rb


• write: This mode is written as wb
• append: This mode is written as ab

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.

To open a binary file follow this syntax:

file = open(<filepath>, mode)


For example: f = open(“one.dat”,”rb”)

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

Unpickling: A byte stream is converted into object hierarchy.


To use the pickling methods in a program, we have to import pickle module using
import keyword.

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 )

Read the object from a file:

pickle.load(file-object)

Write data to a Binary File:


Example:
import pickle
list =[ ] # empty list
while True:
roll = input("Enter student Roll No:")
sname=input("Enter student Name:")
student={"roll":roll,"name":sname} # create a dictionary
list.append(student) #add the dictionary as an element in the list
choice=input("Want to add more record(y/n):")
if(choice=='n'):
break
file=open("student.dat","wb") # open file in binary and write mode
pickle.dump(list, file)
file.close()

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'}]

Update a record in Binary File:


def update():
name=input("Enter the name to be updated ")
newstu=[]
while True:
try:
stu=p.load(f)
for i in stu:
if i[1].lower()==name.lower():
rno=int(input("Enter the updated Roll number"))
s=[rno,name]
newstu.append(s)
else:
newstu.append(i)
except:
break
f.close()
f=open("student.dat","rb+")
update()
p.dump(newstu,f)
print(“Record updated”)
f.close()

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

roll=input('Enter roll number whose record you want to delete:')


list = pickle.load(fw)
found=0
lst= []
for x in list:
if roll not in x['roll']:
lst.append(x)
else:
found=1
fw=open(“student.dat”,”rb+”)
delestudent()
pickle.dump(lst,fw)
fw.close()
if found==1:
print(“Record Deleted”)
else:
print(“Record not found”)

OUTPUT:
Enter roll number whose record you want to delete:1201
Record Deleted

WORKSHEET
LEVEL – 1
I Answer the following questions Marks

1 Which type of file does not have delimiters? 1


2 The process of converting the structure to a byte stream before writing 1
to the file is known as _________.
3 The process of converting byte stream back to the original structure is 1
known as _______

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?

5 The prefix ______ in front of a string makes it raw string that is no 1


special meaning attached to any character.

88
6 Pickling is otherwise known as ________________ 1

7 CSV files are opened with __________argument to supress EOL 1


translation.
8 Which of the following statement is incorrect in the context of binary 1
files?
a. Information is stored in the same format in which the information is
held in memory.
b. No character translation takes place
c. Every line ends with a new line character
d. pickle module is used for reading and writing
II Answer the following
1 What is EOFError? How can we handle EOFError in python? 2
2 How text files and binary files are stored inside computer memory? 2
3 Name any two exceptions that occur while working with pickle module. 2

4 What is the difference between writer object’s writerow() and 2


writerows() function?
III Answer the following
1 Binary files are the best way to store program information. Discuss 3

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()

IV Answer the following


1 What are the different file access modes? Explain 5

2 Write the differences between read(), readline(), readlines(). Explain it with 5


this example
a) Consider the following lines.
The Dowry system is evil in society. It has reduced the sacred affair of
marriage to a business deal. Brides are treated as a marketable
commodity. The parents of the brides are often put under inhuman
pressure for a handsome dowry.

3 Arun, during Practical Examination of Computer Science, has been assigned 5


an incomplete search() function to search in a pickled file student.dat.
The Filestudent.dat is created by his Teacher and the following
information is known about the file.
• File contains details of students in [roll_no,name,marks] format.
• File contains details of 10 students (i.e. from roll_no 1 to 10) and
separate list of each student is written in the binary file using dump().
Arun has been assigned the task to complete the code and print details of roll
number 1.
def search():
f = open("student.dat",____)#Statement-1
____: #Statement-2
while True:
rec = pickle.____#Statement-3
if(____): #Statement-4
print(rec)
except:
pass
____ #Statement-5

I. In which mode Arun should open the file in Statement-1?


a) r
b) r+
c) rb
d) wb
90
II. Identify the suitable code to be used at blank space in line marked as
Statement2
a) if(rec[0]==1)
b) for i in range(10)
c) try
d) pass
III. Identify the function (with argument), to be used at blank space in line
marked
as Statement-3.
a) load()
b) load(student.dat)
c) load(f)
d) load(fin)
IV. What will be the suitable code for blank space in line marked as
Statement-4.
a) rec[0]==2
b) rec[1]==2
c) rec[2]==2
d) rec[0]==1
V. Which statement Arun should use at blank space in line marked as
Statement4 to close the file.
a) file.close()
b) close(file)
c) f.close()
d) close()
Answers
I 1. Binary files
2. Pickling
3. Unpickling
4. FileNotFoundError
5. r
6. Serialization.
7. Newline
8. Every line ends with a new line character
II 1.EOFError is raised when one of the built-in functions input() or
raw_input() hits an end-of-file condition (EOF) without reading any
data. We can overcome this issue by using try and except keywords in
Python, called Exception Handling.

2.A text file stores information in the form of a stream of ASCII or


Unicode characters based on the default state of programming
languages.
Binary file store information as stream of bytes .
3. Pickle.PicklingError and pickle.Unpickling Error

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

2. a) read() – Reads at most n bytes. If no n is specified it will read the


entire file
e.g. f1=open(“E:\\mydata\\info.txt”)
info=f1.read(15)
output:
The Dowry syste
b) readline() – Reads a line of input. If n is specified it reads at most n bytes.

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

1 A collection of bytes stored in computer’s secondary memory is known 1


as ______

2 Default EOL character in Python is the _______ 1

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()

9 Which of the following statement is incorrect in the context of binary 1


files?
a. Information is stored in the same format in which the information is
held in memory.
b. No character translation takes place
c. Every line ends with a new line character
d. pickle module is used for reading and writing
10 Which of the following statement opens a binary file record.bin in write 1
mode and writes data from a list L = [1,2,3,4] on the binary file?

a. with open('record.bin','wb') as myfile:


pickle.dump(L,myfile)

b. with open('record.bin','wb') as myfile:


pickle.dump(myfile,L)

c. with open('record.bin','wb+') as myfile:


94
pickle.dump(myfile,L)

d. with open('record.bin','ab') as myfile:


pickle.dump(myfile,L)
II Answer the following questions
1 What are delimited text files? Give examples 2
2 What is a file object? 2
3 What is the difference between write() and writelines()? 2

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

5 Write a code to include list of items Apple, Mango, Banana to a Binary 2


File.
6 Read the following Python code carefully and answers the question 2
given after the code

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

7 What will be displayed by the following code ? 2


import pickle
Names = ['First', 'second', 'third', 'fourth', 'Fifth']
for i in range(-1, -5, -1):
lst.append(Names[i])
with open('test.dat', 'wb') as fout:
pickle.dump(1st, fout)
with open('test.dat', 'rb') as fin:
nlist = pickle.load(fin)
print(nlist)
III
1 What is pickle module? Why we use pickle module? 3

2 Write a code to show how a dictionary is stored as binary file. 3

3 A binary file “salary.DAT” has structure [employee id, employee name, 3


salary]. Write a function countrec() in Python that would read contents
of the file “salary.DAT” and display the details of those employee
whose salary is above 20000.

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)

II 1.Text files where a particular character is stored to separate the data in


it are known as delimited text files. In these files. there will be a tab (→)
, comma(,) , pipe(│) or tilde(~ ) placed after each value.

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.

load() function is used to retrieve pickled data.


mylist = pickle.load(filehandle)
Arguments
The primary argument is the filehandle that you get by opening the file
in read-binary (rb) mode.
7. The code includes following steps,
Import of pickle module.Opens the TRAIN.DAT file as read-only in
binary format and starts reading from the beginning of the file.using
while loop searches the "Delhi".if the "Delhi" does not exits its results
a string " Not found ! ! ! "
import pickle
def search():
file open("TRAIN.DAT","rb")
found = 0
try:
while True :
Train = pickle.load(file)
if Train [ "To" ] · 'Delhi':
print(Train)
found=1
except EOFError :
if found == 0:

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

4. Raghav is trying to write a tuple t = (1,2,3,4,5) on a binary file test.bin. 1


Consider the following code written by him.
import pickle
t = (1,2,3,4,5)

102
myfile = open("test.bin",'wb')
pickle._________ #Statement 1
myfile.close()

Identify the missing code in Statement 1.


a. dump(myfile,t)
b. dump(t, myfile)
c. write(t,myfile)
d. load(myfile,t)

5. Computers store every file as a collection of ……… 1


a)strings b)Bytes c)characters d)object e)none of the
above
6. The default file-open mode is ……….. 1
a)r b)a c)w d)w+ e)none of the above
7. Which of the following file mode open a file for reading and writing both in the 1
binary file?
a) r b) rb c) rb+ d) rwb
8. The _____ file mode is used to handle binary file for reading. 1
a)rb b)wb c)r+ d)wb+ e)None of the above
9. Which of the following file mode opens a file for reading and writing both as 1
well as overwrite the existing file if the file exists otherwise creates a new
file?
a) w b) wb+ c) wb d) rwb
10. ______ module is used to store data into an python objects with their structure. 1
a)csv b)pickle c)os d)numpy
11. A _________ is a file format which stores records separated by comma. 1
a)numpy b)tsv c)csv d)dat
II Answer the following
12. What are the two types of data files? Give examples for each. 2

13. What is pickling and unpickling of data? 2

14. What is aBinary File? Give examples 2

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

III Answer the following


1 Amritya Seth is a programmer, who has recently been given a task to write a 5
python code to perform the following binary file operations with the help of
two user defined functions/modules:
a. AddStudents() to create a binary file called STUDENT.DAT containing
student information – roll number, name and marks (out of 100) of each
student.
b. GetStudents() to display the name and percentage of those students who
have a percentage greater than 75. In case there is no student having percentage
> 75 the function displays an appropriate message. The function should also
display the average percent.
He has succeeded in writing partial code and has missed out certain statements,
so he has left certain queries in comment lines. You as an expert of Python
have to provide the missing statements and other related queries based on the
following code of Amritya
Answer any four questions (out of five) from the below mentioned questions.
import pickle
def AddStudents():
____________ #1 statement to open the binary file to write data
while True:
Rno = int(input("Rno :"))
Name = input("Name : ")
Percent = float(input("Percent :"))
L = [Rno, Name, Percent]
____________ #2 statement to write the list Linto the file
Choice = input("enter more (y/n): ")
if Choice in "nN":
break

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()

I. Which of the following commands is used to open the file


“STUDENT.DAT”
for writing only in binary format? (marked as #1 in the Python code)
a. F= open("STUDENT.DAT",'wb')
b. F= open("STUDENT.DAT",'w')
c. F= open("STUDENT.DAT",'wb+')
d. F= open("STUDENT.DAT",'w+')

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

V. Which of the following statements correctly explain the function of


seek() method?
a. tells the current position within the file.
b. determines if you can move the file position or not.
c. indicates that the next read or write occurs from that position in a file.

106
d. moves the current file position to a given specified position

2 Compare Text files, Binary Files and CSV files 5


ANSWERS
I 1.file = open("student.dat", "rb+")
2.pickling is used for object serialization
3.a) ab
b)pickle.dump(employee,outfile)
4. dump(t, myfile)
5. b
6.a
7.c
8.c
9.b
10 b
11. c
II 12.
There are two types of files:
Text Files- A file whose contents can be viewed using a text editor is called
atext file. A text file is simply a sequence of ASCII or Unicode
characters.Python programs, contents written in text editors are some of the
example oftext files.
Binary Files-A binary file stores the data in the same way as as stored in
thememory. The .exe files, mp3 file, image files, word documents are some of
theexamples of binary files. We can’t read a binary file using a text editor
13.
Pickling is the process of transforming data or an object in memory (RAM) to
a stream of bytes called byte streams. These byte streams in a binary file can
then be stored in a disk or in a database or sent through a network.
Unpickling is the inverse of pickling process where a byte stream is converted
back to Python object

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

Advantages of csv files:


• CSV is human readable and easy to edit manually.
• CSV is simple to implement and parse.
• CSV is processed by almost all existing applications.
• CSV is smaller in size
• CSV is considered to be standard format
• CSV is compact. For XML you start tag and end tag for each column in each row. In CSV
you write the column headers only once.
• CSV can handle large unstructured data generated by social media effectively

Examples of some valid formats of CSV files are:

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

Semicolon separated values

Raghu ;23;100
Tisha;45;230
Yatin;67;90

Using CSV module to handle csv files


What is csv module?
The csv module implements classes to read and write tabular data in CSV format. The csv module
handles the different types of delimiters and quoting characters in CSV files and efficiently
manipulate such data, hiding the details of reading and writing the data from the programmer.
The module has to be imported in python program to handle csv files.

import csv as c
or
import csv

READING FROM A CSV FILE-READER OBJECT


Reading from a csv file is done using a reader object. The CSV file is opened as a text
file with Python’s built-in open() function, which returns a file object. This creates a
special type of object to access the CSV file (reader object), using the reader()
function.
111
The reader object is an iterable that gives us access to each line of the CSV file as a
list of fields. You can also use next() directly on it to read the next line of the CSV file,
or you can treat it like a list in a for loop to read all the lines of the file (as lists of the
file’s fields).
Syntax:
csv.reader(fileobject,delimiter=“ “)-> it returns a reader object

PROGRAM TO READ AND DISPLAY CONTENTS OF CSV FILE

#reading and displaying contents from a csv file


import csv as c
with open(‘12ACS.csv’,"r") as mycsv:
csvreader=c.reader(mycsv,delimiter=",")
for row in csvreader:
print (row)
CREATING A CSV FILE THROUGH A PYTHON PROGRAM FOR WRITING DATA
To write to a CSV file in Python, we can use the csv.writer() function. The
csv.writer() function returns a writer object that converts the user's data into a
delimited string.
This string can later be used to write into CSV files using the writerow() function.
In order to write to a CSV file, we create a special type of object to write to the CSV
file "writer object", which is defined in the CSV module, and which we create using
the writer() function.
The writerow() method allows us to write a list of fields to the file. The fields
can be strings or numbers or both. Also, while using writerow(), you do not need to
add a new line character (or other EOL indicator) to indicate the end of the line,
writerow() does it for you as necessary.

PROGRAM TO CREATE A CSV FILE AND WRITE DATA IN IT


def createcsv():
f=open("cricket.csv","w",newline='')
s=csv.writer(f,delimiter="-")
s.writerow(["playername","runsscored","Matchsplayed"])
while True:
c=eval(input("Enter the name ,runs, matches"))
s.writerow(c)
ch=input("Do you want to continue (Y/N)")
if ch.upper()!="Y":
break
f.close()

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.

import ____________ # Line 1

# to write / add data into the CSV file


def addRecord(user,password):
file=open('users.csv','___',newline='') # Line 2
cwriter = csv.writer(file)
cwriter.writerow([user,password])
file.close()

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.

2 What are the different file access modes? Explain


3 Puneeta is storing the data of her gift store in a csv file named gift.csv which will store Gift_code
and Gift_name of items of her gift store. She has written the following code .As a
programmer help her to successfully execute her program in python:

import ___________ # Line 1

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()

#CSV file for reading


def readFile():
with ________(„gift.csv‟,‟r‟) as newF #Line 4
FR=csv.reader(newF)
for row in FR:
if row[0]==101:
print(row)

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?

Statement1: Only database can support import/export to CSV format


Statement2: CSV file can be created and edited using any text editor
Statement3: All the columns of CSV file can be separated by comma only

a. Statement 1 and statement 2


b. Statement 2 and statement 3
c. Statement 2
d. Statement 3
ans c. Statement 2

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

writer = csv.writer(writeFile) #writerows()method writes multiple rows


to a csv file
writer.writerows(lines)

III Answer the following Marks


1 a) Write a Python program to read each row from a given csv file and 2+1
print a list of strings
department_id,department_name,manager_id,location_id
10,Administration,200,1700
20,Marketing,201,1800
30,Purchasing,114,1700
40,Human Resources,203,2400
50,Shipping,121,1500
60,IT,103,1400
70,Public Relations,204,2700
80,Sales,145,2500

120
90,Executive,100,1700

b) What does tell() method do?


Ans import csv
a
with open('departments.csv', newline='') as csvfile:
data = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in data:
print(', '.join(row))

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

(a) Name the module he should import in Line 1.


(b) In which mode, Ranjan should open the file to add data into the file
(c) Fill in the blank in Line 3 to read the data from a csv file.
(d) Fill in the blank in Line 4 to close the file.
(e) Write the output he will obtain while executing Line 5.
ans a) Line 1 : csv
b) Line 2 : a
c) Line 3 : reader
d) Line 4 : close()
e) . Line 5 : Arjun 123@456
Arunimaaru@nima
Frieda myname@FRD
2 Ronit has a CSV file “marks.csv” which has name, class and marks 5
separated by comma. He is writing a Python program to copy only the

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()

----- b ----- open('marks.csv') as csvfile:


data = csv. ----- c------- (csvfile)
for row in data:
writer.writerow([----d ------ ,-----e --------- ])

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()

with open('marks.csv') as csvfile:


data = csv.reader(csvfile)
for row in data:
writer.writerow([row[0],row[1]])
3 Write the different methods to read a CSV File in Python. 5
ans There are two ways to read a CSV file.
(i) Use the csv modules reader function
(ii) Use the DictReader class.

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 - data with default delimiter comma (,)

* CSV file - data with Space at the beginning

* CSV file - data with quotes

* CSV file - data with custom Delimiters

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:

['SNO', 'NAME', 'CITY']


['12101', 'RAM', 'CHENNAI']
['12102', 'LAVANYA', 'TIRUCHY']
['12103', 'LAKSHMAN', 'MADURAI']

Reading CSV File Into A Dictionary:

(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.

(vi) For Example Reading “sample8.csv” file into a dictionary

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’}

In the above program, DictReader() is used to read “sample8.csv” file and


map into a dictionary. Then, the function dict() is used to print the data in
dictionary format without order. Remove the dict() function from the above
program and use print(row).Check you are getting the following output

OrderedDict([(‘ItemName ‘, ‘Keyboard ‘), (‘Quantity’, ‘48’)])


OrderedDict([(‘ItemName ‘, ‘Monitor’), (‘Quantity’, ‘52’)])
OrderedDict( [(‘ItemName ‘, ‘Mouse ‘), (‘Quantity’, ‘20’)])
126
4 Radha Shah is a programmer, who has recently been given a task to write a
python code to perform the following CSV file operations with the help of
two
user defined functions/modules:
a. CSVOpen() : to create a CSV file called BOOKS.CSV in append mode
containing information of books – Title, Author and Price.
b. CSVRead() : to display the records from the CSV file called
BOOKS.CSV where the field title starts with 'R'.
She has succeeded in writing partial code and has missed out certain
statements,
so she has left certain queries in comment lines.
import csv
def CSVOpen():
with open('books.csv','______',newline='') as csvf: #Statement-1
cw=______ #Statement-2
______ #Statement-3
cw.writerow(['Rapunzel','Jack',300])
cw.writerow(['Barbie','Doll',900])
cw.writerow(['Johnny','Jane',280])
def CSVRead():
try:
with open('books.csv','r') as csvf:
cr=______ #Statement-4
for r in cr:
if ______: #Statement-5
print(r)
except:
print('File Not Found')

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)

ans Correct Answer: b. csv.writer(csvf)


4.3 Choose the correct option for Statement 3 to write the names of the column
headings in the CSV file, BOOKS.CSV.
a. cw.writerow('Title','Author','Price')
b. cw.writerow(['Title','Author','Price'])
c. cw.writerows('Title','Author','Price')
d. cw.writerows(['Title','Author','Price'])

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)

ans Correct Answer: b. csv.reader(csvf


4.5 Fill in the appropriate statement to check the field Title starting with ‘R’
for
Statement 5 in the above program.
a. r[0][0]=='R'
b. r[1][0]=='R'
c. r[0][1]=='R'
d. d) r[1][1]=='R'

Correct Answer: a. r[0][0]=='R'


ans
LEVEL – 3
I Answer the following Marks
1 Which of the following module is provided by Python to do several 1
operations on the CSV files?

(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

a) capable of storing large amount of data


b) easier to create
c) preferred export and import format for databases and spread sheets
d) All the above
Ans d) All the above
5 .A _________ is a file format which stores records separated by comma. 1
a)numpy b)tsv c)csv d)dat
Ans csv
II Answer the following Marks
1 Deepesh works as a programmer with Delta Technologies. He has been 2
assigned the job of generating the salary of all employees using the file
“employee.csv”. He has written a program to read the CSV file
“employee.csv” which will contain details of all the employees. He has

130
written the following code. As a programmer, help him to successfully
execute the given task.

import______ # Line 1

def readCsvEmp( ): # to read data from the CSV file


with ______(’employees.csv’, newline=”) as f: # Line 2
reader = csv.______ (f) # Line 3
data_list = ______(reader) # Line 4
print (data_list)
i) Name the module he should import in Line 1.
ii)Write the method that he should use to open the file to read data from
it.
iii)Fill in the blank in Line 3 to read the data from a csv file
iv)Fill in the blank in Line 4 with the method to convert the data read
from the file into list.
Ans i)
import csv
ii)
open
iii)
reader
iv)
list
III Answer the following Marks
1 What is CSV file? What are its characteristics? 3
Ans CSV (Comma Separated Values) is a file format for data storage which
looks like a text file.
It is used to store tabular data, such as a spreadsheet or database.
The information is organized with one record on each line

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

IV Answer the following Marks


1 What are the Advantages and disadvantages of CSV files? 5
Ans Advantages of CSV:
•CSV is faster to handle
•CSV is smaller in size and is easy to generate
•CSV is human readable and easy to edit manually
•CSV is simple to implement and parse
•CSV is processed by almost all existing applications

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()

writerows(rows): Writes multiple rows (sequence) to the writer’s file


object
e.g.
import csv
f1=open(‘one.csv’,’w’)
w1=csv.writer(f1,delimiter = ‘,’)
w1.writerow([‘S.No’, ‘Name’, ‘Marks’])
w1.writerows([[1, ‘Ronit’, 84],[2,’Nihir’,90]])
f1.close()

Data structures - Stacks

❖ Introduction to Python data structure stack


❖ Implementation of stack using List
❖ Push function
❖ Pop Function
❖ Display function
❖ Checking stack underflow

Introduction to Python data structure-Stack

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:

1. The data can be inserted or deleted from the top only


2. Elements can be inserted or deleted any time
3. The insert operation is known as push
4. The delete operation is known as pop
5. When the top element is inspected, it is known as a peek or inspection
6. When we have a fixed-length list and we are trying to push an element in a list, it raises one
error that is known as overflow
7. When the list is empty and we are trying to pop an element, it will raise an error that is
known as underflow

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

BOARD PATTERN QUESTIONS


Considering the dictionary storing the price of vegetables,
veg={‘potato’:30,’beans’:40,’carrot’:40,’cabbage’:20,’brinjal’:10,’tomato’:50,’drumstick’:60}
a) Write python function to build a stack costly by pushing the names of vegetables whose
price is > 40 from dictionary veg.
b) Pop and display the items in stack costly
Note:Write only 2 functions pushcostly(veg,costly) and popcostly(costly).Write appropriate
statements in the main part to call the functions.

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?

Answer the following questions (3 marks)


1. Write a python function to delete an element from the stack.
2. Write a function to inspect an element from the stack.
3. Write functions AddPlayer(player) and DeletePlayer(player) in python to add and remove a
player by considering them as push and pop operations in a stack.

Answer the following questions (5 marks)


1. Vedika has created a dictionary containing names and marks as key-value pairs of 5 students.
Write a program, with separate user-defined functions to perform the following operations:
• Push the keys (name of the student) of the dictionary into a stack, where the
corresponding value (marks) is greater than 70.
• Pop and display the content of the stack.
The dictionary should be as follows:
d={“Ramesh”:58, “Umesh”:78, “Vishal”:90, “Khushi”:60, “Ishika”:95}
Then the output will be: Umesh Vishal Ishika

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

Answer the following questions(1 marks)


1. Stack data structure is following ____________ principle.
2. The peek operation refers to accessing/inspecting the top element in the stack. (True/False)
3. Stack overflow condition is raised in ____________ operation where as Stack underflow
condition is raised in _____________ operations.
4. Stack is a ___________ data structure.
a) Static
b) Dynamic
c) Double
139
d) Single
5. While implementing Stack using list when we want to delete element we must use pop
function as__________
a) list.pop(pos)
b) list.pop(0)
c) list.pop()
d) list.push()
6. If the elements “A”, “B”, “C” and “D” are placed in a stack and are deleted one at a time, in
what order will they be removed?
a) ABCD
b) DCBA
c) DCAB
d) ABDC
Answer the following questions (2 marks)
1. What do you mean by data structure? Explain your answer with a suitable example.
2. Write a python function named is_underflow() to check a stack is an underflow.
3. Write a function to push an element into the stack.
Answer the following questions (3 marks)
1. Write a function to display the stack elements.

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

III Answer the following questions (3 marks)


1 def display(stk):
if stk==[]:
print("Stack is Empty")
else:
top = len(stk)-1
print(stk[top],"-Top")
for i in range(top-1,-1,-1):
print(stk[i])

LEVEL – 3

Answer the following questions (1 marks)


1. The insert operation in the stack is known as pop. (True/False).
2. You can replace any element position in the stack. (True/False)
3. If the name of linear list of 10 elements is LIL, then its element will be referenced
a) LIL[0],LIL[1],LIL[2]………LIL[9]
b) LIL[0],LIL[1],LIL[2]………LIL[10]
c) LIL(0),LIL(1),LIL(2)………LIL(9)
d) LIL(0),LIL(1),LIL(2)………LIL(10)
4. LIFO Full form –
a) logical in first out
b) First in first out
c) last in first out
d) last in logical out
5. Which of the following statement(s) about stack data structure is/are NOT correct?
a) Stack data structure can be implemented using linked list
b) New node can only be added at the top of the stack
c) Stack is the FIFO data structure
d) The last node at the bottom of the stack has a NULL link

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

II Answer the following questions(2 marks)

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.

10. MAC address


- It helps in uniquely identifying a computer on a network.
- The MAC address is also known as the physical or hardware address.
-It is a unique permanent value associated with a network adapter called a NIC.
-It is used to physically identify a machine on the network.

11. Repeater- It is a device that regenerate or amplifies the signals on a network.

12. Switch- It is a networking device used to connect multiple computers or communicating


devices.

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.

25. Message switching- In this technique, end-users communicate by sending and


receiving messages wherein, the sender and receiver are not directly connected. There are
a number of intermediate nodes that transfer data and ensure that the message reaches its
destination. It works on store and forward technique. Mobile sms is an example for it.

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

27. Difference between Packet and message switching techniques

Message Switching Packet Switching

A complete message is passed across a Message is broken into smaller units


network. known as Packets.

In this, computer language used is ASCII Here, binary type is used.

In message switching there is no limit on Packet switching places a tight upper


block size. limit on block size.

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.

Access time is reduced due to increase in


performance as packets are stored in disk. Packets are stored in main memory.

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.

29. Transmission media-Transmission media is a communication channel that carries the


information from the sender to the receiver.

30. Types of Transmission Media


In data communication terminology, a transmission medium is a physical path between the
transmitter and the receiver i.e. it is the channel through which data is sent from one place
to another. Transmission Media is broadly classified into the following types:

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

b- Unguided media – By means of waves. Examples: Infrared, Radiowave, Microwave and


Satellite.

There are 3 major types of Guided Media:


(i) Twisted Pair Cable –

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

(ii) Coaxial Cable

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

Worksheet – Solved questions


Question1:
Identify the Domain name and URL from the following:
149
http://www.income.in/home.aboutus.hml

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:

1. Each node is connected with the help of a single cable


2. Each node is connected with the help of independent cable with central switching.

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:

The distance between various buildings is as follows:

151
Number of Computers in Each Building :

1. Suggest the cable layout of connections between the buildings.


2. Suggest the most suitable place (i.e., building) to house the server of this school,
provide a suitable reason.
3. Suggest the placement of the following devices with justification.
o Repeater
o Hub/Switch
4. The organisation also has inquiry office in another city about 50-60 km away in hilly
region. Suggest the suitable transmission media to interconnect to school and inquiry
office out of the following :
o Fiber optic cable
o Microwave
o Radiowave

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:

TCP/IP, or the Transmission Control Protocol/Internet Protocol, is a suite of communication


protocols used to interconnect network devices on the internet. TCP/IP can also be used as
a communications protocol in a private computer network (an intranet or an extranet).
TCP defines how applications can create channels of communication across a network.It also
manages how a message is assembled into smaller packets before they are then transmitted
over the internet and reassembled in the right order at the destination address.
IP defines how to address and route each packet to make sure it reaches the right destination.
Each gateway computer on the network checks this IP address to determine where to
forward the message. TCP/IP uses the client-server model of communication in which a
user or machine (a client) is provided a service (like sending a webpage) by another
computer (a server) in the network. Collectively, the TCP/IP suite of protocols is classified
as stateless, which means each client request is considered new because it is unrelated to
previous requests. Being stateless frees up network paths so they can be used continuously.
(i). Which of the following protocols is used in the internet?
a. HTTP b. DHCP c. DNS d.All of these
(ii). Which protocol assigns IP address to the client connected to the internet?
a.DHCP b. IP c.RPC d. RSVP
(iii). Several protocols for upper layers in Bluetooth use:
a.UDP b.HSP c.ITC d. L2CAP
(iv). Internet protocols are a set of rules to govern:
a.communication between computers on a network
b.bandwidth
c.standard communication
d.metropolitan communication

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.

(i). Web servers are:


a.IP addresses b.Computer systems
c.Webpages of a site d.A medium to carry data from one computer to another

(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

(iii). What is the fullform of HTTP?


a.Hypertext Transfer Protocol b.Hypertext Transfer Procedure
c.Hyperlink Transfer Protocol d.Hyperlink Transfer Procedure

(iv).The __________translates internet domain and hostnames to IP address


a.Domain name system b.Routing information protocol
c. Google d.Network time protocol

(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

(vi). DNS stands for:


a. Domain Name Security b.Domain Number System
c.Document Name System d.Domain Name System

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.

(i). Which of the following devices acts as a server?


a.A b.B c.C d.D
(ii). The arrow from device D to pointing to A represents?
a. HTTP request b.HTTP response

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.)

Expected computers to be installed in each block

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.

SQL (Structured Query Language)


SQL is a language that enables you to create and operate on relational databases, which are sets of
related information stored in tables.

ADVANTAGES OF USING DBMS

➢ 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.

RELATIONAL MODEL TERMINOLOGY

1. Relation: A table storing logically related data is called a Relation.

160
2. Tuple: A row of a relation is generally referred to as a tuple.

3. Attribute: A column of a relation is generally referred to as an attribute.

4. Degree: This refers to the number of attributes in a relation.

5. Cardinality: This refers to the number of tuples in a relation.

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;

2. CREATING DATABASE IN MYSQL


For creating the database in MySQL, we write the following command:
CREATE DATABASE <databasename>;
e.g.In order to create a database Student, command is:
CREATE DATABASE Student;
3. ACCESSING A DATABASE
For accessing already existing database,we write:
USE<databasename>;
e.g.to access a database named Student, we write command as:
USE Student;
4. DELETING DATABASE
For deleting any existing database,the command is:
DROP DATABASE <databasename>;
e.g.to delete a database, say student, we write command as:
DROP DATABASE Student;
5. VIEWING TABLE IN DATABASE
In order to view tables present in currently accessed database, command is:
SHOW TABLES;
CREATING TABLES IN MYSQL
Syntax of CREATE TABLE command is:
CREATE TABLE <table-name>(<colname> datatype,<colname> datatype,…);
E.g. Inorder to create table EMPLOYEE given below:
ECODE ENAME GENDER GRADE GROSS
Create table employee (ecode integer, ename varchar(20),gender char(1),grade char(2),gross
integer);
Inserting Data into Table:
Syntax:
Insert into <tablename> values(<v1>,<v2>,…);
Or
Insert into <tablename>(<column list> )values(<values list>);

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:

It helps to display the records as per our requirement.

Different forms of select command:


1. Select * from employee;
It displays all rows and columns from the table.

2.Select ecode, ename from employee;


It displays selected columns from the table.

3.For displaying particular rows.


Syntax: select * from <tablename> where <cond>;
Eg. Select * from employee where gender=’M’;

4. ELIMINATING REDUNDANT DATA


The distinct keyword is used to eliminate duplicate records from the table.

Eg. Select distinct (gender) from employee;


DISTINCT(GENDER)
M
F

5. USING COLUMN ALIASES


The columns that we select in a query can be given a different name, i.e.column alias name for
output purpose.
Syntax: SELECT <columnname>AS column alias ,<columnname>AS column alias
…..FROM<tablename>;
Eg.select ecode as “EMP_Code” from employee;
CONDITION BASED ON A RANGE
The BETWEEN operator defines a range of values that the column values must fall into make the
condition true. The range include both lower value and upper value.

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.

CONDITION BASED ON PATTERN MATCHES

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%”;

e.g. To display details of employee whose second character in name is:


select * from employee where ename like ‘_e%’;

SEARCHING FOR NULL


The NULL value in a column can be searched for in a table using IS NULL in the WHERE
clause. E.g. to list employee details whose salary contain NULL, we use the command:
Select * from employee where gross is null;
Note: For listing employees who earn salary, then it is:
Select * from employee where gross is not null;
Relational Operators
• To compare two values, a relational operator is used. The result of the comparison is true or false.
Relational Operators recognized by SQL: =, >, <, <=, >=, <> (not equal or !=)

Eg. Select * from employee where ecode <> 1001;


Above query will not display those employee details whose ecode column value is 1001.

Logical Operators- (OR, AND, NOT)

1) To list the employee details having grades E2 or E3.


Select ecode, ename, grade, gross from employee where (grade=‘E2’ OR grade=‘E3’);

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’);

Sorting Results- ORDER BY clause

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.

Eg. Select * from emp order by ename;


Above query arranges the records in alphabetical order of ename value. By default order by clause
arranges in ascending order.

TO DISPLAY RECORDS IN DESCENDING ORDER

❖ Select * from employee order by ename desc;


Above query gives output in descending order of ename.
❖ Select * from employee ORDER BY grade DESC, ename ASC;
Above query displays records first in the descending order of grade and within the same
grade, employees are displayed in the ascending order of Ename.

SQL AGGREGATE FUNCTIONS:


All the aggregate functions ignore null values except count(*).

Avg – to compute average value


Min – to find minimum value
Max – to find maximum value
Sum – to find total value
Count – to count non-null values in a column
Count( *) – to count total number of rows in a table including null values.

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;

Placing conditions on Groups HAVING Clause

❖ 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

This command removes rows from a table.


Syntax: DELETE FROM <tablename> [WHERE <cond>];

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.

UPDATE employee SET gross=40000, grade=’A’ WHERE ecode=1001;


The above query changes the gross and grade values for the record with ecode 1001.

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:

S.No. Constraints Description


1 NOT NULL Ensures that a column cannot have NULL value
2 DEFAULT Provides a default value for a column when none is
specified
3 UNIQUE Ensures that all values in a column are different
4 PRIMARY KEY Used to uniquely identify a row in the table
5 FOREIGN KEY Used to ensure referential integrity of the data

ADDING CONSTRAINT TO A TABLE

ALTER TABLE statement can be used to add constraints to your existing table by using it in
following manner:

Eg: alter table employee add primary key(ecode);


REMOVING CONSTRAINTS FROM A TABLE
Eg: alter table employee drop primary key;

Setting primary and foreign key constraint:

Eg: CREATE TABLE STUDENT(ROLL_NO integer PRIMARY KEY ,NAME


VARCHAR(30),CLASSVARCHAR(3));

CREATE TABLE SCORE(ROLL_NO integer ,MARKS integer, FOREIGN KEY(ROLL_NO)


REFERENCES STUDENT(ROLL_NO));

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.

Cartesian Product (Cross Join)


Cartesian product of two tables is obtained by pairing up each row of one table with each row of
the other table.
167
❖ The number of columns in the Cartesian product is the sum of the number of columns in
both the tables.
❖ The number of rows in the Cartesian product is the product of rows of the tables.
Example:

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.

On performing equi-join, the result is as follows:

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:

Note: We see that deptno column appears only once in output.

Worksheet – L3

Q1. What does the abbreviation DBMS stand for?

(a) Data Borrowing and Movement Software.


(b) Database Management System.
(c) DigitalBase Mapping System.
(d) Database Manipulation Software.

Q2. Which is not an advantage of DBMS?

(a) Database Systems reduce data redundancy


(b) Database Systems control data inconsistency
(c) Database Systems restrict sharing of data
(d) Database Systems ensure data security.

Q3. In ..............,the data is organized into tables i.e. rows &columns.


169
(a) Relational Model
(b) Network Model
(c) Hierarchical Model
(d) ObjectOriented Model

Q4. The essential features of Object Oriented Data Model are;

(a) Object identity


(b) Encapsulation
(c) DataAbstraction
(d) All of the above

Q5. Which statement is false in context to the term Relation?

(a) Relation is a table storing logically related data.


(b) Data must be atomic in cell
(c) All rows of relation are distinct.
(d) Ordering of rows & columns is relevant.

Q6. A row of relation generally referred to as ............. and column of a relation is


…………

(a) Domain & Attribute


(b) Attribute & Domain
(c) Tuple & Attribute
(d) Attribute & Tuple
Q7. A relation has 45 tuples & 5 attributes, what will be the Degree & Cardinality
of that relation?
(a) Degree5,Cardinality45
(b) Degree45,Cardinality5
(c) Degree50,Cardinality45
(d) Degree50,Cardinality2250

Q8. Is the attribute or group of attributes that uniquely identify


occurrence of each entity.
(a) Foreign key
(b) Super Key
(c) Primary Key
(d) All of these

Q9. A Candidate key that is not a primary key, is called ……………

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

Q11. MySQL database system consists of-


(a) MySQLServerInstance
(b) MySQLDatabase
(c) MySQL Query Optimizer
(d) (a)&(b)both

Q12. Which commands are used to define or redefine schema objects?


(a) DDL
(b) DML
(c) TCL
(d) (a)&(b)both

Q13. Data definition includes:


(a) Creating of database
(b) Undoing changes to the database.
(c) Modification of data stored in the database.
(d) All of the above

Q14. Which is not a TCL command?


(a) Commit
(b) Rollback
(c) Exit
(d) Savepoint

Q15. Which is not a function of DML?


(a) Retrieval of data stored in the database
(b) Insertion of data into the database
(c) Deletion of data from the database
(d) Making changes permanent to the database.

Q16. Which is not a numeric type?


171
(a) Int
(b) Float
(c) Blob
(d) Double

Q17. The default date format in MySQL is:


(a) DD/MM/YYYY
(b) YYYY/MM/DD
(c) MM-DD-YYYY
(d) YYYY-MM-DD

Q18. Which is not a way to represent comment in MySQL?


(a)/* ------------- */
(b) --
(c) #
(d) //

Q19. The command is used to access database in MySQL is-


(a) Open <databasename>;
(b) USE <databasename>;
(c) Access <databasename>;
(d) (a)&(b) both

20. Which is a valid CREATE TABLE statement?


(a) Create table emp add(id integer(3));
(b) Create table emp(id integers(3));
(c) Create table emp modified(id integer(3));
(d) Create table emp(id integer(3));

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‟);

Q22. Select statement has four clauses 1.Where 2.Having 3.Group By


4.Orderby

The correct order of all clauses in a select is:-


(a)1,2,3&4
(b)1,3,2&4
(c)1,4,3&2
(d)1,3,4&2
172
Q23. Conditionally retrieval of rows from a table with SELECT, which clause is
used?
(a) Where
(b) Having
(c) Group By
(d) Order by

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;

Q30. Which statement is valid?


(a) ALTER TABLE EMPLOYEE MODIFY(last_name CHAR2(2000));
(b) ALTER TABLE EMPLOYEE CHANGE(last_name CHAR2(2000));
(c) ALTERTABLE EMPLOYEE CHANGE(last_name VARCHAR2(2000));
(d) ALTER TABLE EMPLOYEE MODIFY(last_name VARCHAR2(2000));

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

Q1. Which is true in respect of Select Statement?

(a) By Select we can retrieve all the rows from table.


(b) By Where clause with select we can retrieve selected rows from table.
(c) We can retrieve unique rows from table with the use of Distinct keyword.
(d) All of the above.

Q2. The clause which is used to group rows based on distinct values that exist
for specified column.

(a) Group by clause


(b) Having clause
(c) Order by Clause
(d) Where Clause

Q3. For conditionally retrieval of row from groups which clause is used?

(a) Where clause


(b) Having Clause
(c) Order By Clause
(d) (a)&(b)both

Q4. Group functions are also known as.

(a) Aggregate functions


(b) Multiple row functions
(c) Single row functions
(d) (a)&(b)both

Q5.Which option cause a group function to consider only distinct values.

(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

Q7. Which is not a group function?

(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

Q9. SELECT COUNT(*) FROM EMP WHERE DEPTNO=10;

(a) 14
(b) 3
(c) 4
(d) 5

177
Q10. SELECT COUNT(DISTINCT JOB) FROMEMP;

(a) 14
(b) 5
(c) 4
(d) 6

Q11. SELECT COUNT(ALL JOB)FROM EMP;

(a) 14
(b) 5
(c) 4
(d) 6

Q12. SELECT MAX(SAL) FROM EMP WHERE JOB=‘MANAGER’;

(a)2975
(b)5000
(c)3000
(d)2850

Q13. SELECT MIN(HIREDATE) FROM EMP;

(a) 1980-12-17
(b) 1983-01-12
(c) 1982-12-09
(d)None

Q14. SELECT MAX(HIREDATE) FROM EMP;

(a) 1980-12-17
(b) 1983-01-12
(c) 1982-12-09
(d)None

Q15. SELECT SUM(COMM) FROM EMP;

(a) Null
(b) 0
(c)2200
(d)1400

Q16.Which statement is used to display the total no. of employees in each


department?
(a) SELECT COUNT(*) FROM EMP WHERE DEPTNO;
178
(b) SELECTCOUNT(*)FROMEMPGROUPBYDEPTNO;
(c) SELECTCOUNT(DEPTNO)FROMEMPGROUPBYDEPTNO;
(d) (b)&(c)both

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.

(a) Unrestricted join


(b) Cartesian Join
(c) Equi Join
(d) (a)&(b) both

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

Q21.The join where columns are compared for equality is called………………

(a) Equi Join


(b) Natural Join
(c) Cross Join
(d) Right Join

179
Q22. The join in which only one identical column exists is called………

(a) Equi Join


(b) Natural Join
(c) Cross Join
(d) Right Join

Q23. Which statement represent Cartesian join?

(a) SELECT*FROM EMP,DEPT;


(b) SELECT*FROM EMP JOIN DEPT;
(c) SELECT*FROM EMP CROSS JOIN DEPT;
(d) All of the above

Q24. Using sub-clause with JOIN causes a ................join where as on sub-clause


with JOIN produces .......... join.

(a) Natural & Equi


(b) Equi & Natural
(c) Cross & Equi
(d) Natural & Cross.

Q25. Scalar functions are also known as:

(a) Single row function


(b) Multiple row function
(c) Group functions
(d) None

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

Import the required packages

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

importing package mysql connector in python


Here I have instantiated msql to mysql.connector which can be work as an alias name for the connector.

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:

import mysql.connector as msql


cn=msql.connect(host='localhost',user='root',passwd='root',database='Studentdb')

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:

import mysql.connector as msql

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!!!")

Execute SQL command and fetch rows

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()

Performing DML operations (insert, update and delete)

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

Observe the following code:

import mysql.connector as msql


cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')
cur=cn.cursor()
cur.execute("insert into students values(1111,'Asmita',78.50,'B1'))
cn.commit()

update command

import mysql.connector as msql


cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')
cur=cn.cursor()
cur.execute("update students set marks=80.5 where rollno=1111")
cn.commit()

delete command

import mysql.connector as msql


cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')
cur=cn.cursor()
183 | P a g e
cur.execute("delete from students where rollno=1111")
cn.commit()

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.

Observe the below-given code for fetchall() function:

import mysql.connector as msql


cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')
cur=cn.cursor()
cur.execute("select * from students")
d=cursor.fetchall()
for r in d:
print(r)

Observe the below-given code for fetchmany(n) function:

import mysql.connector as msql


cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')
cur=cn.cursor()
cur.execute("select * from students")
d=cursor.fetchmany(3)
for r in d:
print(r)

The above code will return 3 rows from the database.

Observe the below-given code for fetchone() function:

import mysql.connector as msql


import time
cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')
cur=cn.cursor()
cur.execute("select * from students")

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

with % formatting 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()

#display records more than 80%


cur.execute("select * from students where marks >%s" %(80,))
d=cur.fetchall()
for r in d:
print(r)

#display records having B1 grade


cur.execute("select * from students where grade='%s'" %('B1',))
d=cur.fetchall()
for r in d:
print(r)

with {}.format pattern


In this pattern you can write {} where the value is placed followed by .format(values). Consider the
following code:

import mysql.connector as msql


import time
cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')

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)

Close the connection

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

L3 – Very Short Answer questions (1 mark)


1. Which package do we import in Python to establish MySQL connectivity ?
Ans. mysql.connector

2. What is the significance of using connect( ) function ?


Ans. connect( ) function is used to connect or establish a connection with MySQL database.

3. What is the role of execute( ) ?


Ans. The role of the execute function is execution of queries which are MySQL queries along
with Python interface.

4. What is the command to install mysql connector ?


Ans. pip install mysql-connector (OR)
pip install mysql-connector-python

5. What is a database connectivity ?


Ans. A database connectivity refers to the connection and communication between an
application and database system.

L3 – Multiple Choice Questions (1 mark)

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

L2 – Short Answer Questions (2 marks)

1. What are the steps for creating database connectivity applications ?

Ans. To create database connectivity, follow the given steps:


Step 1: Start Python
Step 2: Import mysql.connector
Step 3: Open a connection to the database
Step 4: Create a cursor instance
Step 5: Execute a query
Step 6: Extract data from result set
Step 7. Clean up the environment

2. What is a connection? What is its role?

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.

4. What is a database cursor?

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.

5. How to retrieve data from a table?

Ans. There are multiple ways to retrieve data:

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

L1 – Long Answer Questions (3 marks)

1. Write a Python code to connect to a database


Ans.
import mysql.connector
Mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”,database=”project”)
Print(mycon)

2. How to create a database in MySQL through Python ?


Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”)
cursor=mycon.cursor( )
cursor.execute(“create database education”)

3. Write the Python code to display the present databases in MySQL


Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”)
cursor=mycon.cursor()
cursor.execute(“show databases”)
for i in cursor:
print(i)
4. How to create a table in MySQL through Python ?
Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”)
cursor=mycon.cursor()
cursor.execute(“create table student(admn_no int primary key,sname varchar(30),gender char(2),DOB
date, stream varchar(15), marks float”)

5. Write the Python code to insert data into a table in MYSQL


188 | P a g e
Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”)
cursor=mycon.cursor()
ano=int(input(“Enter admission no: “))
n=input(“Enter name: “)
g=input(“Enter gender:”)
dob=input(“Enter DOB: “)
s=input(“Enter stream: “)
m=float(input(“Enter marks:”))
query=”insert into student values({},’{}’,’{}’,’{}’,’{}’,’{}’,{})”.format(ano,n,g,dob,s,m)
cursor.execute(query)
mycon.commit( )

6. How to fetch data in Python from a table in MySQL ?


Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”,
database=”education”)
cursor=mycon.cursor()
cursor.execute(“select * from student”)
for row in cursor:
print(row)

7. Write the Python code to update a record in the table


Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”,
database=”education”)
cursor=mycon.cursor()
cursor.execute(“update student set marks=67 where admn_no=3456”)
mycon.commit( )

8. Write the Python code to delete a record from the table


Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”,
database=”education”)
cursor=mycon.cursor()
cursor.execute(“delete from student where admn_no=3455”)
mycon.commit( )

*************

189 | P a g e

You might also like