0% found this document useful (0 votes)
2K views146 pages

Question Bank 2023-24 Computer Science

This document provides sample questions and chapters from the CBSE prescribed syllabus for Computer Science for Class 12. It includes sample questions on three units: Unit I on computational thinking and programming which covers Python functions, exception handling, files; Unit II on computer networks which covers topics like data communication, network devices, protocols; and Unit III on database management which discusses SQL and interfacing Python with SQL databases. It also outlines the practical and project sections of the syllabus.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views146 pages

Question Bank 2023-24 Computer Science

This document provides sample questions and chapters from the CBSE prescribed syllabus for Computer Science for Class 12. It includes sample questions on three units: Unit I on computational thinking and programming which covers Python functions, exception handling, files; Unit II on computer networks which covers topics like data communication, network devices, protocols; and Unit III on database management which discusses SQL and interfacing Python with SQL databases. It also outlines the practical and project sections of the syllabus.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 146

INDIAN PUBLIC SCHOOL

SAMBALPUR

ALL INDIA SENIOR SCHOOL


CERTIFICATE EXAMINATION
SESSION- 2023-24

NAME OF THE STUDENT – ………………………………………….

SAMPLE QUESTIONS
CHAPTER WISE

PREPARED BY:-
MR.PRAFULLA KUMAR GOUDA
MOB-7999552828
Computer Science CBSE Prescribed Syllabus (Theroy-70 Marks)
1. Unit I: Computational Thinking and Programming – 2
2. Unit II: Computer Networks
3. Unit III: Database Management

Unit I: Computational Thinking and Programming – 2


● Revision of Python topics covered in Class XI.
● Functions: types of function (built-in functions, functions defined in module, user defined functions), creating user
defined function, arguments and parameters, default parameters, positional parameters, function returning value(s),
flow of execution, scope of a variable (global scope, local scope)
● Exception Handling: Introduction, handling exceptions using try-except-finally blocks
● Introduction to files, types of files (Text file, Binary file, CSV file), relative and absolute paths
● Text file: opening a text file, text file open modes (r, r+, w, w+, a, a+), closing a text file, opening a file using with
clause, writing/appending data to a text file using write() and writelines(), reading from a text file using read(),
readline() and readlines(), seek and tell methods, manipulation of data in a text file
● Binary file: basic operations on a binary file: open using file open modes (rb, rb+, wb, wb+, ab, ab+), close a binary
file, import pickle module, dump() and load() method, read, write/create, search, append and update operations in a
binary file
● CSV file: import csv module, open / close csv file, write into a csv file using writer(),writerow(),writerows() and read
from a csv file using reader()
● Data Structure: Stack, operations on stack (push & pop), implementation of stack using list.

Unit II: Computer Networks


● Evolution of networking: introduction to computer networks, evolution of networking (ARPANET, NSFNET,
INTERNET)
● Data communication terminologies: concept of communication, components of data communication
(sender,receiver, message, communication media, protocols), measuring capacity of communication media
(bandwidth, data transfer rate), IP address, switching techniques (Circuit switching, Packet switching)
● Transmission media: Wired communication media (Twisted pair cable, Co-axial cable, Fiber-optic cable), Wireless
media (Radio waves, Micro waves, Infrared waves)
● Network devices (Modem, Ethernet card, RJ45, Repeater, Hub, Switch, Router, Gateway, WIFI card)
● Network topologies and Network types: types of networks (PAN, LAN, MAN, WAN), networking topologies (Bus,
Star, Tree) ● Network protocol: HTTP, FTP, PPP, SMTP, TCP/IP, POP3, HTTPS, TELNET, VoIP
● Introduction to web services: WWW, Hyper Text Markup Language (HTML), Extensible Markup Language (XML),
domain names, URL, website, web browser, web servers, web hosting

Unit III: Database Management


● Database concepts: introduction to database concepts and its need
● Relational data model: relation, attribute, tuple, domain, degree, cardinality, keys (candidate key, primary key,
alternate key, foreign key)
● Structured Query Language: introduction, Data Definition Language and Data Manipulation Language, data type
(char(n), varchar(n), int, float, date), constraints (not null, unique, primary key), create database, use database, show
databases, drop database, show tables, create table, describe table, alter table (add and remove an attribute, add
and remove primary key), drop table, insert, delete, select, operators (mathematical, relational and logical), aliasing,
distinct clause, where clause, in, between, order by, meaning of null, is null, is not null, like, update command, delete
command, aggregate functions (max, min, avg, sum, count), group by, having clause, joins: cartesian product on two
tables, equi-join and natural join
● Interface of python with an SQL database: connecting SQL with Python, performing insert, update, delete queries
using cursor, display data by using connect(), cursor(), execute(), commit(), fetchone(), fetchall(), rowcount, creating
database connectivity applications, use of %s format specifier or format() to perform queries
Practical (30 Marks)

Project

The aim of the class project is to create something that is tangible and useful using

Python file handling/ Python-SQL connectivity. This should be done in groups of

two to three students and should be started by students at least 6 months before

the submission deadline. The aim here is to find a real world problem that is

worthwhile to solve.
Computational thinking and programming-1-Python
Python Introduction`
It is widely used general purpose, high level programming language. Developed by Guido van
Rossum in 1991.
It is used for:
 software development,
 web development (server-side),
 system scripting,
 Mathematics.

Features of Python
1. Easy to use – Due to simple syntax rule
2. Interpreted language – Code execution & interpretation line by line
3. Cross-platform language – It can run on windows, Linux, Macintosh etc. equally
4. Expressive language – Less code to be written as it itself express the purpose of the code.
5. Completeness – Support wide range of library
6. Free & Open Source – Can be downloaded freely and source code can be modify for improvement

Shortcomings of Python-

1. Lesser libraries – as compared to other programming languages like c++,java,. Net


2. Slow language – as it is interpreted languages, it executes the program slowly.
3. Weak on Type-binding – It not pin point on use of a single variable for different data type

PROCESS OF WRITING PROGRAM


After installation of python, we can work on it in following ways
(i) in Interactive mode
(ii) in Script mode
Interactive mode
Interactive mode is useful for testing code. We can type the commands one by one and get the result
of error immediately for each command. Disadvantages of Interactive mode are that it does not save
commands in form of a program and also output is sandwiched between commands.

Script mode
Script mode is useful for creating programs and then run the programs later and get the complete
output. It is not suitable for testing code.

(Run program file)


a. Click Open command from IDLE’s File menu and select the file you have already saved
b. Click Run-> Run Module or Press F5 Keys
c. It will execute all the commands of program file and display output in separate python shell window
Character Set
A set of valid characters recognized by python.
Python uses the traditional ASCII character set. The latest version recognizes the Unicode character
set. The ASCII character set is a subset of the Unicode character set.
 Letters :– A-Z,a-z
 Digits :– 0-9
 Special symbols :– Special symbol available over keyboard
 White spaces:– blank space,tab,carriage return,new line, form feed
 Other characters:- Unicode
Input and Output
input() Function In Python allows a user to give input to a program from a keyboard but returns
the value accordingly.
e.g.
age = int(input(‘enter your age’))
The print() function prints the specified message to the screen, or other standard output device.
print("Hello World")
print(‘Computer',‘Science')
print(‘Computer',‘Science',sep=' & ')
print(‘Computer',‘Science',sep=' & ',end='.')
Output :-
Computer Science
Computer & Science
Computer & Science.

Indentation
Python uses indentation to create blocks of code. Statements at same indentation level are part
of same block/suite
if 3 > 2:
print(“Three is greater than two!") //syntax error due to not indented
E.g.2x
if 3 > 2:
print(“Three is greater than two!") //indented so no error
Token`
Smallest individual unit in a program is known as token.
1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Punctuators/Delimiters
Keywords
Keywords are reserved words carrying special meaning and purpose to the language
compiler/interpreter. For example, if, elif, etc. are keywords.

Identifiers
Identifiers are user defined names for different parts of the program like variables, objects, classes,
functions, etc. Identifiers are not reserved. They can have letters, digits and underscore. They must
begin with either a letter or underscore. For example, _chk, chess, trail, etc.

Literals
Literals are data items that have a fixed value. The different types of literals allowed in Python are:
 String literals- A string is literal and can be created by writing a text(a group of Characters )
surrounded by a single(”), double(“), or triple quotes.
# in single quote
s = 'geekforgeeks'

# in double quotes
t = "geekforgeeks"

# multi-line String
m = '''geek
for
geeks'''
print(s)
print(t)
print(m)
 Numeric literals- Integer , Float ,Complex
 Boolean literals- True or False
 Special literal- None
 Literal collections- List ,Tuple,Dict,Set

Operators
Operators are tokens that trigger some computation/action when applied to variables and other
objects in an expression.
Operators can be defined as symbols that are used to perform operations on operands.
Types of Operators
1. Arithmetic Operators.
2. Relational Operators.
3. Assignment Operators.
4. Logical Operators.
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
1. Arithmetic Operators Arithmetic Operators are used to perform arithmetic operations like
addition, multiplication, division etc.

2. Relational Operators/Comparison Operator Relational Operators are used to compare the


values.

3. Augmented Assignment Operators


Used to assign values to the variables
4. Logical Operators Logical Operators are used to perform logical operations on the given two
variables or values.

6. Membership Operators
The membership operators in Python are used to validate whether a value is found within a sequence
such as such as strings, lists, or tuples.

7. Identity Operators Identity operators in Python compare the memory locations of two
objects.
Operators Precedence:
Highest precedence to lowest precedence table. Precedence is used to decide, which operator to be
taken first for evaluation when two or more operators comes in an expression.

Variable Python
Python variables are simply containers for storing data values
Example - x=25 here x is a variable

Punctuators/Delimiters
Barebones of a python program

a. Expression : - which is evaluated and produce result. E.g. (20 + 4) / 4


b. Statement :- instruction that does something. e.g a = 20 print("Calling in proper sequence")
c. Comments : which is readable for programmer but ignored by python interpreter i. Single line
comment: Which begins with # sign. ii. Multi line comment (docstring): either write multiple line
beginning with # sign or use triple quoted multiple line. E.g. ‘’’this is my first python multiline
comment ‘’’ d. Function a code that has some name and it can be reused.e.g. keyArgFunc in above
program
e. Block & indentation : group of statements is block.indentation at same level create a block.e.g. all
3 statement of keyArgFunc function

Concept of L Value and R Value in variable


L-value- Lvalue refers to an object to which you can assign value.It refers to a memory location.. It
can appear as LHS or RHS
Example num1=10 or str1= “IPS”

R-value - Rvalue refers to the value we assign to any variable. It can appear on RHS of assignment
Sum=a+b here a+b is R-Value

Dynamic typing
Data type of a variable depend/change upon the value assigned to a variable on each next statement.
Dynamic typing means that the type of the variable is determined only during runtime
Example -
X = 25 # integer type
X = “python” # x variable data type change to string on just next line
Now programmer should be aware that not to write like this:
Y = X / 5 # error !! String cannot be divided
Mutable and Immutable Data type
A mutable data type can change its state or contents and immutable data type cannot.
Mutable data type: list, dict, set, byte array
Immutable data type: int, float, complex, string, tuple, frozen set
[note: immutable version of set], bytes
Mutability can be checked with id() method.
x=10 print(id(x))
x=20
print(id(x))
#id of both print statement is different as integer is immutable

What is the difference between implicit type conversion and explicit type conversion?
Answer

Implicit Type Conversion Explicit Type Conversion

An implicit type conversion is automatically An explicit type conversion is user-


performed by the compiler when differing defined conversion that forces an
data types are intermixed in an expression. expression to be of specific type.

An explicit type conversion is


An implicit type conversion is performed
specified explicitly by the
without programmer's intervention.
programmer.

Example: Example:
a, b = 5, 25.5 a, b = 5, 25.5
c=a+b c = int(a + b)

Debugging
Debugging means the process of finding errors, finding reasons of errors and techniques of their
fixation. An error, also known as a bug, is a programming code that prevents a program from its
successful interpretation. Errors are of three types –

• Compile Time Error

• Run Time Error

• Logical Error

Compile time error :

These errors are basically of 2 types – Syntax Error :Violation of formal rules of a programming
language results in syntax error.
str1=”ips’
print(str1)
Semantics Error: Semantics refers to the set of rules which sets the meaning of statements. A
meaningless statement results in semantics error.

For example - x * y = z
Logical Error

Logical Error If a program is not showing any compile time error or run time error but not
producing desired output, it may be possible that program is having a logical error. Some example-

• Use a variable without an initial value.

• Provide wrong parameters to a function

• Use of wrong operator in place of correct operator required for operation X=a+b (here – was
required in place of + as per requirement

Run time Error

Run time Error These errors are generated during a program execution due to resource limitation.
Python is having provision of checkpoints to handle these errors.

For example –

a=10

b=int(input(“enter a number”))

c=a/b

Value of b to be entered at run time and user may enter 0 at run time,that may cause run time error,
because any number can’t be divided by 0

Run time Error In Python, try and except clauses are used to handle an exception/runtime error
which is known as exception handling

try: # code with probability of exception will be written here.

a=10

b=int(input(“enter a number”))

c=a/b

except:

#code to handle exception will be written here.

print(“divide by zero error”)

Debugger tool

Another technique for removing an error is code tracing.


Control Statements
Control statements are used to control the flow of execution depending upon the specified
condition/logic. There are three types of control statements.
1. Decision Making Statements
2. Iteration Statements (Loops)
3. Jump Statements (break, continue, pass)
Decision Making Statement Decision making statement used to control the flow of execution of
program depending upon condition. There are three types of decision making statement.
1. if statements
2. if-else statements
3. Nested if-else statement
1. if statements An if statement is a programming conditional statement that, if proved true,
performs a function or displays information.

1. if statements
Syntax:
if(condition):
statement
[statements]
e.g.
noofbooks = 2
if (noofbooks == 2):
print('You have ')
print(‘two books’)
print(‘outside of if statement’)
Output
You have two books
2. if-else Statements
2. if-else Statements If-else statement executes some code if the test expression is true (nonzero)
and some other code if the test expression is false.

Syntax:
if(condition):
statements
else:
statements
e.g.
a=10
if(a < 100):
print(‘less than 100')
else:
print(‘more than equal 100')
OUTPUT
less than 100
3. Nested if-else statement The nested if...else statement allows you to check for multiple test
expressions and execute different codes for more than two conditions.

3. Nested if-else statement


Syntax If (condition):
statements
elif (condition):
statements
else: statements
E.G.
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
OUTPUT
Enter a number: 5 Positive number

Iteration statements (loop) are used to execute a block of statements as long as the condition is
true. Loops statements are used when we need to run same code again and again.
Python Iteration (Loops) statements are of three type :-
1. While Loop
2. For Loop
3. Nested For Loops

1. While Loop It is used to execute a block of statement as long as a given condition is true. And
when the condition become false, the control will come out of the loop. The condition is checked
every time at the beginning of the loop.

2. For Loop It is used to iterate over items of any sequence, such as a list or a string.
Syntax
for val in sequence:
statements
e.g.
for i in range(3,5):
print(i)
Output
3
4
2. For Loop continue Example programs
for i in range(5,3,-1):
print(i)
Output
5
4
range() Function Parameters
start: Starting number of the sequence.
stop: Generate numbers up to, but not including this number.
step(Optional): Determines the increment between each numbers in the

Nested Loop
A nested loop is an inner loop in the loop body of the outer loop. The inner or outer loop can be any
type, such as a while loop or for loop. For example, the outer for loop can contain a while loop and
vice versa
String
String is a sequence of characters, which is enclosed between either single (' ') or double quotes ("
"), python treats both single and double quotes same.
Creating String Creation of string in python is very easy.
e.g. a=‘Computer Science'
b=“Informatics Practices“
Accessing String Elements

Iterating/Traversing through string Each character of the string can be accessed sequentially using
for loop.
e.g.
str='Computer Sciene‘
for i in str:
print(i)
output-
C
O
M
P
U
R
String comparison
We can use ( > , < , <= , <= , == , != ) to compare two strings.
Python compares string lexicographically i.e using ASCII value of the characters.
Suppose you have str1 as "Maria" and str2 as "Manoj" . The first two characters from str1 and str2 (
M and M ) are compared. As they are equal, the second two characters are compared. Because they
are also equal, the third two characters ( r and n ) are compared. And because 'r' has greater ASCII
value than ‘n' , str1 is greater than str2 .
Updating Strings
String value can be updated by reassigning another value in it.
e.g.
var1 = 'Comp Sc'
var1 = var1[:7] + ' with Python'
print ("Updated String :- ",var1 )

OUTPUT
('Updated String :- ', 'Comp Sc with Python')
String Special Operators
e.g.
a=“comp”
b=“sc”
Triple Quotes It is used to create string with multiple lines.
e.g.
Str1 = “””This course will introduce the learner to text mining and text manipulation basics. The
course begins with an understanding of how text is handled by python”””
String functions and methods
a=“comp”
b=“my comp”
a=“comp”
String functions and methods
a=“comp”
#Python Program to calculate the number of digits and letters in a string
string=raw_input("Enter string:")
count1=0
count2=0
for i in string:
if(i.isdigit()):
count1=count1+1
count2=count2+1
print("The number of digits is:")
print(count1)
print("The number of characters is:")
print(count2)
List in Python
Introduction

It is a collection of items and each item has its own index value. Index of first item is 0 and the last item is n-1.Here n
is number of items in a list.
Creating a list

Lists are enclosed in square brackets [ ] and each item is separated by a comma.

Initializing a list

Passing value in list while declaring list is initializing of a list

e.g.
list1 = [‘English', ‘Hindi', 1997, 2000]
list2 = [11, 22, 33, 44, 55 ]
list3 = ["a", "b", "c", "d"]
Blank list creation

A list can be created without element

List4=[ ]

Iterating/Traversing Through A List

List elements can be accessed using looping statement.

e.g.
list =[3,5,9]
for i in range(0, len(list)):
print(list[i])
Output
3
5
9
List Operations

1. Joining List
2. Repeating or Replicating Lists
3. Slicing the List
4. Making True Copy of a List

Joining List – Joining of two list + operator is used

list1=[2,5,6]

list2=[“school”, 45.23]

list1+list2

[2,5,6, “school”, 45.23]

Repeating or Replicating Lists- * operator to replicate a list specified number of times.

List1=[1,3,5]

List1*3

[1,3,5,1,3,5,1,3,5]

Slicing the List-

Slicing is the subpart of a list extracted out.


Seq=L[start:stop] Note – stop value-1
list=[10,12,14,20,22,24,30,32,34]
Seq=list[3:-3]
[20,22,24]
e.g.
list =['I','N','D','I','A']
print(list[0:3])
print(list[3:])
print(list[:])
Output ['I', 'N', 'D'] ['I', 'A'] ['I', 'N', 'D', 'I', 'A']
Making True Copy of a List- Make a copy of a list .

a=[1,2,3]

b=a

List functions and methods


1. Len()- Return the length of its arguments
Syntax- len(list)
Example –
list=[1,2,3,4,5,6,7,8,9]
Len(list)
9
2. List () – Returns a list created the passed argument which should be a sequence type(string, list, tuple etc)
Syntax- list[sequence]
Example –
A=list((34,51,100))
24,51,100
3. Index() – returns the index of first matched item
Syntax- list.index(item)
Example –1
L1=[13,18,11,16,18,14]
L1.index(18)
1
Example-2
fruits = ['apple', 'banana', 'cherry']
x = fruits.index("cherry")
print(x)
2
4. Append()- Add an el;elemt to the end of the list
Syntax- List.append(item)
Example –
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits)
['apple', 'banana', 'cherry', 'orange']

5. Extend()- The extend() is also used for adding multiple elements (given in the form of list) to a list.
Syntax-List.extend(list)
Example –
fruits = ['apple', 'banana', 'cherry']
cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo']

6. Insert()- Adds an element at the specified position


Syntax- List.insert(index, item)
Example –
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, "orange")
['apple', 'orange', 'banana', 'cherry']
7. Remove()-Removes the first item with the specified value
Syntax- list. Remove(value)
Example –
fruits = ['apple', 'banana', 'cherry']
fruits.remove("banana")
['apple', 'cherry']
8. Clear()-Removes all the elements from the list
Example –
fruits = ['apple', 'banana', 'cherry', 'orange']

fruits.clear()
[]
9. Count()-Returns the number of elements with the specified value
Syntax- list.count(item)
Example –
fruits = ['apple', 'banana', 'cherry']

x = fruits.count("cherry")

1
10. Revers()-Reverses the order of the list

Syntax- list.reverse()

fruits = ['apple', 'banana', 'cherry']


fruits.reverse()

['cherry', 'banana', 'apple']

11. Sort()- Sorts the list


Syntax- list.sort()
cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
['BMW', 'Ford', 'Volvo']
12. Min()- returns min value, Max()- return max value,Sum()- returns the sum values
Syntax- min(list), max(list), sum(list)
Example-
val=[17,24,15,30]
min(val) -15
max(val)- 30
sum(val)-86
Syntax- min (list)

Tuples
 Introduction
 Creating and Accessing tuples
 Tuples operations
 Tuple Functions and Methods

Tuples- Tuples are immutable sequences of python. We cannot change the elements of a tuple in place.

It is a sequence of immutable objects. It is just like list. Difference between the tuples and the lists is that the tuples
cannot be changed unlike lists. Lists uses square bracket whereas tuples use parentheses.

Creating and Accessing tuples

Creating A Tuple

A tuple is enclosed in parentheses () for creation and each item is separated by a comma.

e.g.
tup1 = (‘comp sc', ‘info practices', 2017, 2018)

tup2 = (5,11,22,44)

NOTE:- Indexing of tuple is just similar to indexing of list.

Tuples operations

 Joining – joining two tuples


tp1=(1,3,5)
tp2=(6,7,8)
tp1+tp2 (1,3,5,6,7,8)
 Slicing the tuples – tuple slices like list and string slice are the sub part of the tuple extracted out.
tp1=(10,12,14,20,22,24,30,32,34)
Seq=tp1[3:-3]
(20,22,24)
 Comparing- Compare two tuples <,>,==, !=
Example-
a=(2,3)
b=(2,3)
a==b
True
 Unpacking- creating a tuple from a set of values is called packing and its reverse. Creating individual values
form tuple elements is called unpacking
Syntax-
<var1>, <var2>, <var3>….=t
Example-
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
output-

apple
banana
cherry

 Deleting - The del keyword can delete the tuple completely

fruit = ("apple", "banana", "cherry")


fruit
print(fruit)
#this will raise an error because the tuple no longer exists after delete this tuple after access it make error.
Tuples function and methods-

1. len()- return the length of a tuple.


Synatx- len(tuple)
employee=(“john”, 10000,24, “sales”)
len(employee)
4
2. max()- return the maximum value of tuple.
Tp1= (“Karan’, “Zubin”, “Zara”, “Ana”)
Max(tp1)
Zubin
3. min() and sum()-
Example –
tp1= (10,12,14,20,22,24,30,32,34)
min(tp1)=10
sum(tp1)=126
4. index()- The index () work with tuples same in list
Example- t1=(3,4,5,6.2)
t1.index(5)
2
Example –
vowels = ('a', 'e', 'i', 'o', 'i', 'u')
index = vowels.index('e')
print('The index of e:', index)
OUTPUT ->1
5. Sorted()-sorted()- returns the sorted elements list
x = (1,4,6)
r= sorted(x)
print(sorted elements in tuple', r)
6. count() - method returns the number of times a specified value appears in the tuple.
t1 = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = t1.count(5)
print(x)
OUTPUT-> 5

Dictionary
It is an unordered collection of items where each item consist of a key and a value. It is
mutable (can modify its contents ) but Key must be unique and immutable

Creating A Dictionary
It is enclosed in curly braces {} and each item is separated from other item by a comma(,).
Within each item, key and value are separated by a colon (:).
Passing value in dictionary at declaration is dictionary initialization.get() method is used to
access value of a key
e.g. dict = {‘Subject': ‘Informatic Practices', 'Class': ‘11'}
Accessing List Item
dict = {'Subject': 'Informatics Practices', 'Class': 11}
print(dict) print ("Subject : ", dict['Subject'])
print ("Class : ", dict.get('Class'))
OUTPUT
{'Class': '11', 'Subject': 'Informatics Practices'}
('Subject : ', 'Informatics Practices')
('Class : ', 11
Iterating / Traversing through A Dictionary Following example will show how dictionary
items can be accessed through loop.
e.g. dict = {'Subject': 'Informatics Practices', 'Class': 11} for i in dict: print(dict[i]) OUTPUT 11
Informatics Practices Updating/Manipulating Dictionary Elements We can change the
individual element of dictionary. e.g. dict = {'Subject': 'Informatics Practices', 'Class': 11}
dict['Subject']='computer science' print(dict) OUTPUT {'Class': 11, 'Subject': 'computer
science'}
Python Revision Tour-I
Multiple Choice Questions (MCQs)
(a) Which of the following is not considered a valid identifier in Python?
(i) two2 (ii) _main (iii) hello_rsp1 (iv) 2 hundred
(b) What will be the output of the following code— print(“100+200”)?
(i) 300 (ii) 100200 (iii) 100+200 (iv) 200
(c) Which amongst the following is a mutable datatype in Python?
(i) int (ii) string (iii) tuple (iv) list
(d) pow() function belongs to which library?
(i) math (ii) string (iii) random (iv) maths
(e) Which of the following statements converts a tuple into a list?
(i) len(string) (ii) list(string) (iii) tup(list) (iv) dict(string)
(f) The statement: bval = str1 > str2 shall return .............................. as the output if two strings
str1 and str2 contains “Delhi” and “New Delhi”.
(i) True (ii) Delhi (iii) New Delhi (iv) False
(g) What will be the output generated by the following snippet?
a = [5,10,15,20,25]
k=1
i =a[1] +1
j =a[2] +1
m = a[k+1]
print(i,j,m)

(i) 11 15 16 (ii) 11 16 15 (iii) 11 15 15 (iv) 16 11


15
(h) The process of arranging the array elements in a specified order is termed as:
(i) Indexing (ii) Slicing (iii) Sorting (iv) Traversing
(i) Which of the following Python functions is used to iterate over a sequence of numbers by
specifying a numeric end value within its parameters?
(i) range() (ii) len() (iii) substring() (iv) random()
(j) What is the output of the following?
d = {0: 'a', 1: 'b', 2: 'c'}
for i in d:
print(i)
(k) What is the output of the following?
x = 123
fori inx:
print(i)
(i) 1 2 3 (ii) 123 (iii) error (iv) infinite loop
(l) Which arithmetic operators cannot be used with strings?
(i) + (ii) * (iii) – (iv) All of the
above
(m) What will be the output when the following code is executed?
2.
>>>str1="helloworld"
>>>str1[:–1]
(i) dlrowolleh (ii) hello (iii) world (iv) helloworld
(b) What is the output of the following statement?
print("xyyzxyzxzxyy".count('yy', 1))
(i) 2 (ii) 0 (iii) 1 (iv) Error
(c) Suppose list1 = [0.5 * x for x in range(0, 4)], list1 is:
(i) [0, 1, 2, 3] (ii) [0, 1, 2, 3, 4]
(iii) [0.0, 0.5, 1.0, 1.5] (iv) [0.0, 0.5, 1.0, 1.5, 2.0]
(d) Which is the correct form of declaration of dictionary?
(i) Day={1:’monday’,2:’tuesday’,3:’wednesday’}
(ii) Day=(1;’monday’,2;’tuesday’,3;’wednesday’)
(iii) Day=[1:’monday’,2:’tuesday’,3:’wednesday’]
(iv) Day={1’monday’,2’tuesday’,3’wednesday’]
(e) Identify the valid declaration of L: L= [1,23,‘hi’,6]
(i) list (ii) dictionary (iii) array (iv) tuple

Answers:(iv) (b)(iii) (c)(iv) (d)(i) (e)(ii) (f) (iv)


(a)
(g)(ii) (h)(iii) (i)(i) (j)(i) (k)(iii) (l) (iii)
(m)(i) (n)(i) (o)(iii) (p)(i) (q)(i)
Higher Order Thinking Skill Questions

1) Which of the following is valid arithmetic operator in Python:


(i)// (ii)? (iii)< (iv)and

2) Write the type of tokens from the following:


(i) if (ii) roll_no

3) Which of the following are valid operators in Python:


(i) ** (ii) */ (iii) like (iv) || (v) is (vi) ^ (vii) between (viii) in

4) Which of the following can be used as valid variable identifier(s) in Python?


(i) 4thSum (ii) Total (iii) Number# (iv) _Data

5) Rearrange the following operators in Highest to Lowest Priority.


% , or, ==, not, =

6) Find the invalid identifier from the followings:


a) File_name, b) sl1, c) False, d) num34

7) Which of the following is not a valid identifier name in Python? Justify reason for it not
being a valid name.
a) 5Total b) _Radius c) pie d)While

8) Which of the following is not a valid identifier in Python?


a) KV2 b) _main c) Hello_Dear1 d) 7 Sisters

9) Which of the following are valid operators in Python:


(i) * (ii) between (iii) like (iv) ||

10) Which of the following are valid operator in Python:


(i) */ (ii) is (iii) ^ (iv) like

11) How would you write xy-4x9 in python


12) Name the Python Library modules which need to be imported to invoke the following
functions: (i) ceil( ) (ii) randrange( )

13) Evaluate following expressions:


a) 18 % 4 ** 3 // 7 + 9
b) 2 > 5 or 5 == 5 and not 12 <= 9
c) 16%15//16
d) 51+4-3**3//19-3
e) 17<19 or 30>18 and not 19==0

Answers
Ans1. (i)
Ans 2. i) Keyword ii) identifier
Ans 3. i) iv) vi) viii)
Ans 4. ii) and iv)
Ans 5. %, ==, not, or, =
Ans 6. c)False
Ans 7. a) 5Total Reason: An identifier cannot start with a digit
Ans 8. d) 7 Sisters
Ans 9. (iv) ||
Ans 10. Valid operators are : (ii) is (iii) ^
Ans 11. Math.pow(x,y) – 4 * math.pow(x,9)
Ans 12. i) math (ii) random
Ans. 13. a) 11 b) True c) 0 d) 51 e) True
Chapter 1. Python Revision Tour-I (2 Marks Questions)

(1) Distinguish between Dictionary and List

Dictionary List
1.Unordered collection of elements 1. Ordered collection of elements
2. Group of objects are not in any particular 2. Elements are in particular order
order

(2) Distinguish between Keyword and Identifier

Keyword Identifier
1. Special word that has special meaning & is 1.User defined name given to a part of
predefined program
2.these are reserved words 2.These are not reserved words

(3) Distinguish between String and List


Sting List
1.Immutable sequence & stores single type of 1.Mutable sequence & stores multiple type
elements of elements
2.In consecutive locations it starts individual 2.Starts references of its elements
characters

(4) Distinguish between Mutable Objects and Immutable Objects

Mutable Objects Immutable Objects


1.can be changed after creation 1. cannot be changed after creation
2.when you alter an object its id will be same 2. when you alter an object its id will change

T FINDING QUESTIONS

Q1. Find output generated by the following code:


p=10 q=20
p*=q//3
q+=p
q=q**2
print(p, q)
Ans: 60 6400

Q2. Find output generated by the following code:


str="Computer"
print(str[-4:])
print(str*2)
Ans: uter
‘ComputerComputer’

Q3. Find out the output of the Following –


x=20
x=x+5
x=x-10
print (x)
x, y=x-1,50
print (x, y)
Ans: 15
14,50

Q4. Find output generated by the following code:


p=5/2
q=p*4
r=p+q
p+=p+q+r
q‐=p+q*r
print(p,q,r)
Ans: (27.5 ‐ 142.5 12.5)

Q5. Find output generated by the following code:


a=(2 + 3) ** 3 – 6 / 2
b=(2 + 3) * 5// 4 + (4 + 6) / 2
c=12 + ( 3 * 4 – 6 ) / 3
d=12 % 5 * 3 + (2 * 6) // 4
print(a, b, c, d)

Ans: (122.0 11.0 14.0 9)

QUESTIONS BASED ON TUPLE

Q1: Find the output of following codes


1. t1=("sun","mon","tue","wed")
a. print(t1[‐1])
Ans: wed

Q 2. t6=('a','b')
t7=('p','q')
t8=t6+t7
print(t8*2)
Ans: ('a', 'b', 'p', 'q', 'a', 'b', 'p', 'q')

Q 3. t9=('a','b')
t10=('p','q')
t11=t9+t10
print(len(t11*2))
Ans: 8

Q 4. t12=('a','e','i','o','u')
p, q, r, s, t=t12
print("p= ",p)
print("s= ",s)
print("s + p", s + p)
Ans: p= a
s= o
s + p oa

Q5.
t13=(10,20,30,40,50,60,70,80)
t14=(90,100,110,120)
t15=t13+t14
print(t15[0:12:3])
Ans: 10, 40, 70, 100
Q2. Find the errors
1. t1=(10,20,30,40,50,60,70,80)
t2=(90,100,110,120)
t3=t1*t2 Print(t5[0:12:3])
Ans: a. t1*t2 can not multiply
b. P is in uppercase in print command
c. t5 is not defined
2. t1=(10,20,30,40,50,60,70,80)
i=t1.len()
Print(T1,i)
Ans: a. len() is used wrongly
b. P is in uppercase in print command
c. T1 is not defined

3. t1=(10,20,30,40,50,60,70,80)
t1[5]=55
t1.append(90) print(t1,i)
Ans: a. 'tuple' object does not support item assignment in line 2
b. Append() Method is not with tuple

4. t1=(10,20,30,40,50,60,70,80)
t2=t1*2 t3=t2+4
print t2,t3
Ans: a) line 3 cannot concatenate with int
b) Parenthesis is missing in line 4

5. t1=(10,20,30,40,50,60,70,80)
str=”” str=index(t1(40))
print(“index of tuple is ”, str)
str=t1.max()
print(“max item is “, str)

Ans: a. Syntax error in index function


b. Syntax error in max function

LIST BASED QUESTION


Q1. Give the output of the following code:‐
list=['p','r','o','b','l','e','m']
print(list[1:3])
print(list[2:5])
Ans: ['r', 'o']
['o', 'b', 'l']

Q2.Give the output of the following code:‐


l1=[13,18,11,16,13,18,13]
print(l1.index(18))
print(l1.count(18))
l1.append(l1.count(13))
print(l1)
Ans: 1
2
[13,18,11,16,13,18,13,3]

Q3. What is the output of the following:


list1 = [1, 2, 3, 4, 5]
list2 =list1
list2[0] =0;
print("list1= : ", list1)
Ans: [0,2,3,4,5]

Q4. What Will Be The Output Of The Following Code Snippet?


a =[1,2,3,4,5]
print(a[3:0:‐1])
A. Syntax error B. [4, 3, 2]
C. [4, 3] D. [4, 3, 2, 1]
Ans: B

Q5. What Will Be The Output Of The Following Code Snippet?


a = {(1,2):1,(2,3):2}
print(a[1,2])
Ans: 1

6. What do you mean by scope of variables ?


Ans: Scope of variables refers to the part of the program where it is visible, i.e, the area where
you can use it

7. Which of the following is valid arithmetic operator in Python:


(i)// (ii)? (iii)< (iv)and
Ans: (i)

8. Write the type of tokens from the following:


(i) if (ii) roll_no
Ans: i) Keyword
ii)identifier

9. Which of the following are valid operators in Python:


(i) ** (ii) */ (iii) like (iv) ||
(v) is (vi) ^ (vii) between (viii) in
Ans: i) iv) vi) viii)

10. Which of the following can be used as valid variable identifier(s) in Python?
(i) 4thSum (ii) Total (iii) Number# (iv) _Data
Ans: ii) and iv)

11. What is a tuple?


Ans. A tuple is an immutable sequence of values which can be of any type and are indexed
by an integer.
12. Differentiate between lists and tuples.
Ans. Tuples cannot be changed unlike lists; tuples use parentheses, whereas lists use square
brackets.
13. What is a dictionary?
Ans. A Python dictionary is a mapping of unique keys to values. It is a collection of key-value
pairs. Dictionaries are mutable which means that they can be changed.
14. Write a Python program to replace the last element in a list with
another list. Sample data : [1, 3, 5, 7, 9, 10], [2, 4, 6, 8]
Expected Output: [1, 3, 5, 7, 9, 2, 4, 6, 8]
Ans. num1 = [1, 3, 5, 7, 9, 10]
num2 = [2, 4, 6, 8]
num1[-1:] = num2print(num1)

15. Write the type of tokens from the following:


a. if
b. roll_no
Ans. (a) Key word (b) Identifier
Python Revsion Tour-II
Higher Order thinking skill questions
1. Write the output of the following:
(i) for i in '123':
print("guru99",i,)
(ii) for i in [100,200,300]:print(i)
(iii) for j in range(10,6,-2):
print(j*2)
(iv) for x in range(1,6):
for y in range(1,x+1):print(x,'
',y)
(v) for x in range(10,20):
if (x == 15):
break
print(x)
(vi) for x in range (10,20):
if (x % 2 == 0) :
continueprint(x)
2. Write the output of the following program on execution if x = 50:
if x>10:
if x>25:
print("ok")
if x>60:
print("good")
elif x>40:
print("average")
else:
print("no output")

Application based questions


ERROR FINDING QUESTIONS
Q1. Find error in the following code(if any) and correct code by rewriting code and underline
the correction;‐
x= int(“Enter value of x:”)
for in range [0,10]:
if x=y print( x + y)
else: print( x‐y)

Ans:
x= int(“Enter value of x:”)
for in range (0,10):
if x==y :
print( x + y)
else:
print( x‐y)

Q2. Rewrite the following program after finding and correcting syntactical errors and
underlining it.
a, b = 0
if (a = b)
a +b = c
print(c)

Ans:
a,b = 0,0
if (a = =b) :
c=a +b
print(c)

Q3. Rewrite the following code in python after removing all syntax error(s). Underline each
correction done in the code.
STRING=""WELCOME NOTE""
for S in range[0,7]:
print (STRING(S))

Ans:
STRING= "WELCOME NOTE”
for S in range (0, 7) :
print (STRING [S])

OUTPUT FINDING QUESTIONS


Q1. Find out the output of the Following –
for a in range(3,10,3):
for b in range(1,a,2):
print(b, end=’ ‘)
print( )
Ans: 1
135
1357
Q2. FIND OUTPUT OF FOLLOWING
a="WayTOUniversiTY"
z=len(a)
p=0
while p < z:
q=a[p].upper()
if (q=='A' or q=='E' or q=='I' or q=='O' or q=='U'):
print (a[p], end="-")
p=p+1

Ans: a-O-U-i-e-i-

Q3. Find output generated by the following code:


x="one"
y="two"
c=0
while c<len(x):
print(x[c],y[c])
c=c+1
Ans: o t
nw
eo

Q4. Find output generated by the following code:


for i in range(‐1,7,2):
for j in range(3):
print(i,j)
Ans: ‐1 0
‐1 1
‐1 2
10
11
12
30
31
32
50
51
52
Q5. Find output generated by the following code:
string="aabbcc"
count=3
while True:
if string[0]=='a':
string=string[2:]
elif string[-1]=='b':
string=string[:2]
else:
count+=1
break
print(string)
print(count)
Ans: bbcc
4

Q6. Find and write the output of the following python code :
Msg1="WeLcOME"
Msg2="GUeSTs"
Msg3=""
for I in range(0,len(Msg2)+1):
if Msg1[I]>="A" and Msg1[I]<="M":
Msg3=Msg3+Msg1[I]
elif Msg1[I]>="N" and Msg1[I]<="Z":
Msg3=Msg3+Msg2[I]
else:
Msg3=Msg3+"*"
print(Msg3)

Ans: G*L*TME

Q7. Find and write the output of the following python code:
Data = ["P",20,"R",10,"S",30]
Times =0
Alpha = ""
Add = 0
for C in range(1,6,2):
Times= Times + C
Alpha= Alpha + Data[C‐1]+"$"
Add = Add + Data[C]
print (Times,Add,Alpha)
Ans: 1 20 P$
4 30 P$R$
9 60 P$R$S$

Q8. Find and write the output of the following python code:
Text1="AISSCE 2018"
Text2=""
I=0
while I<len(Text1):
if Text1[I]>="0" and Text1[I]<="9":
Val = int(Text1[I])
Val = Val + 1
Text2=Text2 + str(Val)
elif Text1[I]>="A" and Text1[I] <="Z":
Text2=Text2 +(Text1[I+1])
else:
Text2=Text2 + "*"
I=I+1
print(Text2)

Ans: ISSCE*3129
Q 9. Find and write the output of the following python code:
TXT = ["20","50","30","40"]
CNT = 3
TOTAL = 0
for C in [7,5,4,6]:
T = TXT[CNT]
TOTAL = float (T) + C
print( TOTAL)
CNT-=1
Ans: 47.0
35.0
54.0
26.0
Q10. Find output generated by the following code:
line = "I'll come by then."
eline = ""
for i in line:
eline += chr(ord(i)+3)
print(eline)
Ans: L*oo#frph#e|#wkhq1

Q11. Find output generated by the following code:


line = "What will have so will"
L = line.split('a')
for i in L:
print(i, end=' ')
Ans: Wh t will h ve so will

Q12. Find the output of the following


L1 = [100,900,300,400,500]
START = 1
SUM = 0
for C in range(START,4):
SUM = SUM + L1[C]
print(C, ":", SUM)
SUM = SUM + L1[0]*10
print(SUM)
Ans:
1 : 900
1900
2 : 2200
3200
3 : 3600
4600
Find output on random function
1) Study the following program and select the possible output(s) from the options (i)
to (iv) following it. Also, write the maximum and the minimum values that can be
assigned to the variable Y.
Import random
X= random.random()
Y= random.randint(0,4)
print int (X),”:”, Y+ int(X)
i) 0 : 0 ii) 1 : 6 iii) 2 : 4 iv) 0 : 3
Ans: i) and iv) are the possible output(s)
Minimum value that can be assigned to Y = 0 Maximum value assigned to Y = 3
2) What possible output(s) are expected to be displayed on screen at the time of execution of the
following code? Also specify the maximum and minimum value that can be assigned to variable X.

import random
L=[10,7,21]
X=random.randint(1,2)
for i in range(X):
Y=random.randint(1,X)
print(L[Y],”$”,end=” ”)
(i)10 $ 7 $ (ii) 21 $ 7 $
(iii) 21 $ 10 $ (iv) 7 $
Ans: Options (ii) & (iv)
Minimum value -1
Maximum value-2
3) What possible output(s) are expected to be displayed on the screen at the time of execution of the
program from the following code?
import random
print( 100+random.randint(5,10), end = " ")
print( 100+random.randint(5,10), end = " ")
print( 100+random.randint(5,10), end = " ")
print( 100+random.randint(5,10))
(i)102 105 104 105 (ii)110 103 104 105
(iii)108 107 110 105 (iv) 110 110 110 110
Ans: (iii)108 107 110 105 (iv) 110 110 110 110
4) Find output and also find maximum value for FROM and TO
import random
name=[‘ALOK’,’HARI’,’JUGAL’,’HANS’,’RAKESH’,’KISHORE’]
FROM= random.randint(1,3)
TO= random.randint(2,4)
for k in range(FROM,TO+1):
print(name[k],end=’%’)
(i) HARI%JUGAL%HANS%Rakesh% (ii) JUGAL%HANS%RAKESH%
(iii) ALOK%HARi (iv) JUGAL%HANS%RAKESH%KISHORE%
Ans: (i) HARI%JUGAL%HANS%RAKESH% (ii) JUGAL%HANS%RAKESH%
Maximum value for FROM is - 2 and TO is - 3

5) Write the possible output (expected on screen out of (i) to (iv)) and write the maximum and
minimum values for the variable T
import random
NUM = [75,95,35,15]
T=random.randint(0,len(NUM))
for r in range (T):
if (NUM[r] % 3==0):
print(NUM[r], end="#")

(i) 75#15# (ii) 75# (iii) 75#95# (iv) 75#95#35#15

Ans: (i) 75#15# (ii) 75#


Maximum T= 3 Minimum T = 0

6) import random
TEXT ="CBSEONLINE"
COUNT =random.randint(0,3)
C=9
while(TEXT[C]!=’L’):
print(TEXT[C]+TEXT[COUNT[+’*’,end=’ ’)
COUNT= COUNT + 1
C =C-1

(i) EC* NB*IS* (iii) ES*NE*IO


(ii) NS* IE*LO* (iv) LE*NO*ON
Ans: (i) and (iii)
Minimum value of count is 0 and Maximum value of count is 3
7) x=random.random()
y=random.randint(0,4)
print (int(x),’:’,y+int(x))
i)0:0 ii)1:6 iii)2:4 iv)0:3
Ans: i) 0:0 and iv) 0:3
Min=0 max=4
8) Find output also find maxvalue and minvalue
import random
colorpick=random.randint(0,3)
color=[‘RED’,’GREEN’,’BLUE’,’WHITE’]
for I in color:
for j in range(1,colorpick):
print(i,end=‘ ‘)
print()
i) REDRED ii) RED
GREENGREEN REDGREEN
BLUEBLUE REDGREENBLUE
WHITEWHITE REDGREENBLUEWHITE
iii) RED iv) RED
GREEN GREENGREEN
BLUE WHITEWHITE
WHITE
Ans: Option (i) and (iii) are possible colorpick
maxval=3 minval=0

9) import random
X= random.random()
Y= random.randint(0,4) print(int(X),":",Y+int(X))
(i) 0 : 0 (ii) 1 : 6 (iii) 2 : 4 (iv) 0 : 3
Ans: Option i) and iv) are correct

10) import random


pick=random.randint(0,3)
city={‘DELHI’,’MUMBAI’,’CHENNAI’,’KOLKATA’}
for i in city:
for j in range(1,pick):
print(i,end=“”)
print()
I) DELHIDELHI III) DELHI IV)DELHI
MUMBAIMUMBAI MUMBAI MUMBAIMUMBAI
KOLKATAKOLKATA CHENNAI KOLKATAKOLKATAKOLKATA
KOLKATA
II)DELHI
DELHIMUMBAI
DELHIMUMBAICHENNAI
Ans: Options - (i) and (iii)
Minimum Value of PICK = 0 Maximum Value of PICK = 3

QUESTIONS BASED ON TUPLE


Q1. t2=("sun","mon","tue","wed","thru","fri")
for i in range (‐6,2):
print(t2[i])
Ans: sun
mon
tue
wed
thru
fri
sun
mon

Q2.
t3=("sun","mon","tue","wed","thru","fri")
if "sun" in t3:
for i in range (0,3):
print(t3[i])
else:
for i in range (3,6):
print(t3[i])

Ans: sun
mon
tue
Q 3.
t4=("sun","mon","tue","wed","thru","fri")
if "sun" not in t4:
for i in range (0,3):
print(t4[i])
else:
for i in range (3,6):
print(t4[i])
Ans: wed
thur
fri

Q 4. t5=("sun",2,"tue",4,"thru",5)
if "sun" not in t5:
for i in range (0,3):
print(t5[i])
else:
for i in range (3,6):
print(t5[i])
Ans:
4
thru
5

Q.5 Find output


old_msg="PasS@2019"
New_msg=""
for m in old_msg:
if m.isupper():
New_msg+=m.lower()
elif m.islower():
New_msg+=m.upper()
elif m.isdigit():
New_msg+="*"
else:
New_msg+="#"
print("New message is:",New_msg)

Ans: New message is: pASs#****

Q6. Find output


L =["X",20,"Y",10,"Z",30]
CNT = 0
ST = ""
INC = 0
for C in range(1,6,2):
CNT= CNT + C
ST= ST + L[C-1]+"@"
INC = INC + L[C]
print (CNT,INC,ST)
Ans:
1 20 X@
4 30 X@Y@
9 60 X@Y@Z@
Q 7. Find output
txt=['20','50','30','40']
cnt=3
total=0
for c in [7,5,4,6]:
t=txt[cnt]
total=float(t)+c
print (total)
cnt-=1
Ans:
47.0
35.0
54.0
26.0

Q8. What Will Be The Output Of The Following Code Snippet?


fruit_list1 = ['Apple', 'Berry', 'Cherry', 'Papaya']
fruit_list2 = fruit_list1
fruit_list3 = fruit_list1[:]
fruit_list2[0] = 'Guava'
fruit_list3[1] = 'Kiwi'
sum = 0
for ls in (fruit_list1, fruit_list2, fruit_list3):
if ls[0] == 'Guava':
sum += 1
if ls[1] == 'Kiwi':
sum += 20
print (sum)
Ans: 22

Q9. What Will Be The Output Of The Following Code Snippet?


my_dict = {}
my_dict[1] = 1
my_dict['1'] = 2
my_dict[1.0] = 4
sum = 0
for k in my_dict:
sum += my_dict[k]
print (sum)
Ans: 6

Q10. What Will Be The Output Of The Following Code Snippet?


my_dict = {}
my_dict[(1,2,4)] = 8
my_dict[(4,2,1)] = 10
my_dict[(1,2)] = 12
sum = 0
for k in my_dict:
sum += my_dict[k]
print (sum)

Ans:30

Q.11 Find output

TXT = ["400","200","700","90"]
CNT = 3
TOTAL = 0
for C in [3,5,7,9]:
T = TXT[CNT]
TOTAL = float(T) + C
print(TOTAL)
CNT -= 1

Ans:
93.0
705.0
207.0
409.0

Q.12. Convert the following for loop into while loop:


for k in range(10,20,5):
print(k)
Ans.
k=10
while(k<20):
print(k)
k+=5

Q.13. Find errors in the following code (if any) and correct the code by rewriting it and underlining the
corrections:
x= int("Enter value for x:"))
for in range[0,11]:
if x = y
print x+y
else:
Print x-y
Ans.
x=int(input("Enter value for x:"))
for y in range(0,11):
if x == y:
print(x+y)
else:
print(x-y)

Q.14. How many times is the word ‘HELLO’ printed in the following statement?
s='python rocks'
for ch ins[3:8]:
print('Hello')
Ans. 5 times

Q.15. Find errors, underline them and rewrite the same after correcting the following code:
d1=dict[]
i= 1
n=input("Enter number of entries:")
while i<=n:
a=input("Enter name:")
b=input("Enter age:")
d1(a)=b
i = i+1
l = d1.key[]
for i in l:
print(i,'\t','d1[i]')
Ans.
d1=dict()
i=1
num=int(input("Enter the no:"))
for i in range(num):
a = input("Enter name:")
b = input("Enter age:")
d1[a] = b
l = d1.keys()
i=i+1
for i in l:
print(i,"\t",d1[i])

Q.16 Rewrite the following code in Python after removing all syntax error(s). Underline each correction
donein the code.
30=To
forKinrange(0,To)
IFk%4==0:
print(K*4)
Else:
print(K+3)
Ans. To=30
for K in range(0,To):
if K%4==0:
print(K*4)
else:
print(K+3)

Very Short Answer Type Questions (1-Mark)


Q1. What is None literal in Python?
Ans: Python has one special literal called “None”. It is used to indicate something that
has not yet been created. It is a legal empty value in Python.

Q2.Can List be used as keys of a dictionary?


Ans: No, List can’t be used as keys of dictionary because they are mutable. And a python
dictionary can have only keys of immutable types.

Short Answer Type Questions (2-Marks)


Q1. What is a python variable? Identify the variables that are invalid and state the
reason
Class, do, while, 4d, a+
Ans: - A variable in python is a container to store data values.
a) do, while are invalid because they are python keyword
b) 4d is invalid because the name can’t be started with a digit.
c) a+ is also not validas no special symbol can be used in name except underscore ( _ ).
Q.2 Predict the output
for i in range( 1, 10, 3):
print(i)
Ans: -
1
4
7

Q3. Rewrite the code after correcting errors: -


if N=>0
print(odd)
else
Print("even")

Ans: -
if N>=0:
print(“odd”)
else:
print("even")
Q.4 What problem occurs with the following code
X=40
while X< 50 :
print(X)

Ans: - The given code does not have the incrementing value of X, thus the loop becomes
endless.
Q5. What will be the output of the following code snippet?
values =[ ]
for i in range (1,4):
values.append(i)
print(values)
Ans:
[1]
[1 ,2 ]
[1,2,3]
Application Based Questions ( 3 Marks)

Q1. Find output of the following code fragment.


x=”hello world”
print(x[:2],x[:-2],x[-2:])
print(x[6],x[2:4])
print(x[2:-3],x[-4:-2])

Ans:
he hello wor ld
w ll
llo wo or
Q2. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
250 = Number
WHILE Number<=1000:
if Number=>750
print (Number)
Number=Number+100
else
print( Number*2)
Number=Number+50

Ans:
Number = 250
while Number<=1000:
if Number >= 750:
print (Number)
Number = Number+100
else:
print (Number*2)
Number = Number+50

Q3. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
Val = int(input("Value:"))
Adder = 0
for C in range(1,Val,3)
Adder+=C
if C%2=0:
Print (C*10)
Else:
print (C*)
print (Adder)

Ans:
Val = int(input("Value:")) # Error 1
Adder = 0
for C in range(1,Val,3) : # Error 2
Adder+=C
if C%2==0 : # Error 3
print( C*10 ) # Error 4
else: # Error 5
print (C ) # Error 6
print(Adder)
Q4. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
25=Val
for I in the range(0,Val)
if I%2==0:
print( I+1):
Else:
print [I-1]

Ans:
Val = 25 #Error 1
for I in range(0,Val): #Error 2 and Error 3
if I%2==0:
print (I+1)
else: #Error 4
print (I-1)

Q5. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
STRING=""WELCOME
NOTE""
for S in range[0,8]:
print (STRING(S))

Ans:
STRING= "WELCOME"
NOTE=" "
for S in range (0, 7) :
print (STRING [S])

Also range(0,8) will give a runtime error as the index is out of range. It should be
range(0,7)

Q6. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
a=int{input("ENTER FIRST NUMBER")}
b=int(input("ENTER SECOND NUMBER"))
c=int(input("ENTER THIRD NUMBER"))
if a>b and a>c
print("A IS GREATER")
if b>a and b>c:
Print(" B IS GREATER")
if c>a and c>b:
print(C IS GREATER)
Ans:

a=int(input("ENTER FIRST NUMBER"))


b=int(input("ENTER SECOND NUMBER"))
c=int(input("ENTER THIRD NUMBER"))
if a>b and a>c:
print("A IS GREATER")
if b>a and b>c:
print(" B IS GREATER")
if c>a and c>b:
print(" C IS GREATER ")

Q7. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
i==1
a=int(input("ENTER FIRST NUMBER"))
FOR i in range[1, 11];
print(a,"*=", i ,"=",a * i)
Ans:
i=1
a=int(input("ENTER FIRST NUMBER"))
for i in range(1,11):
print(a,"*=",i,"=",a*i)

Q8. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
a=”1”
while a>=10:
print("Value of a=",a)
a=+1
Ans:
a=1
while a<=10:
print("Value of a=",a)
a+=1

Q9. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
Num=int(input("Number:"))
sum=0
for i in range(10,Num,3)
Sum+=1
if i%2=0:
print(i*2)
Else:
print(i*3 print Sum)

Ans:
Num=int(input("Number:"))
sum=0
for i in range(10, Num,3):
sum+=1
if i%2==0:
print(i*2)
else:
print(i*3)
print(sum)

Q10. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
weather='raining'
if weather='sunny':
print("wear sunblock")
elif weather='snow':
print("going skiing")
else:
print(weather)

Ans:
weather='raining'
if weather=='sunny':
print("wear sunblock")
elif weather=='snow':
print("going skiing")
else:
print(weather)

Q11. Write the modules that will be required to be imported to execute the following
code in Python.
def main( ):
for i in range (len(string)) ):
if string [i] = = ‘’ “
print
else:
c=string[i].upper()
print( “string is:”,c)
print (“String length=”,len(math.floor()))

Ans: Math module and String module

Q12. Rewrite the following code in python after removing all syntax error(s).Underline
each correction done in the code
x=integer(input('Enter 1 or 10'))
if x==1:
for x in range(1,11)
Print(x)
Else:
for x in range(10,0,-1):
print(x)

Ans:
x=int(input('Enter 1 or 10'))
if x==1:
for x in range(1,11):
print(x)
else:
for x in range(10,0,-1):
print(x)

Q13. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
30=To
for K in range(0,To)
IF k%4==0:
print (K*4)
else
print (K+3)

Ans :
To=30
for K in range(0,To) :
if k%4==0:
print (K*4)
else:
print (K+3)

QUESTIONS - FIND THE OUTPUT

Q11. Find output generated by the following code:


p=5/2
q=p*4
r=p+q
p+=p+q+r
q-=p+q*r
print(p,q,r)

Q2. Find output generated by the following code:


a=(2 + 3) ** 3 – 6 / 2
b=(2 + 3) * 5// 4 + (4 + 6) / 2
c=12 + ( 3 * 4 – 6 ) / 3
d=12 % 5 * 3 + (2 * 6) // 4
print(a, b, c, d)

Q3. Find the output of the give program :


x = "abcdef"
i = "a"
while i in x:
print(i, end = " ")

SOLUTION : FIND THE OUTPUT

Ans 1. (27.5 - 142.5 12.5) Ans 2. (122.0 11.0 14.0 9)

Ans 3. -- aaaaaa OR infiniteloop


www.python4csip.com

WORKSHEET
DATA FILE HANDLING
1 Give one difference between Text file and Binary File
Ans Text file contains EOL character at the end of every line, there is no such character
in binary file
2 Write a Python statement to open a text file “DATA.TXT” so that new contents can
be written on it.
Ans f = open(„DATA.TXT‟,‟w‟)
3 Write a Python statement to open a text file “DATA.TXT” so that new content can be
added to the end of file
Ans f = open(„DATA.TXT‟,‟a‟)
4 Write a Python statement to open a text file “DATA.TXT” so that existing contents
can be read from file.
Ans f = open(„DATA.TXT‟)
5 A file “MYDATA.TXT” is opened as
file1 = open(“MYDATA.TXT”)
Write a Python statement to close this file.
Ans file1.close()
6 What is the different in file opening mode “a” and “w” ?
Ans “w” is used to write in file from the beginning. If file already exists then it will
overwrite the previous content.
“a” (append – add at the end ) is also used to write in file. If file already exists it will
write after the previous content i.e. it will not overwrite the previous content and
add new content after the existing content.
6 What is the significance of adding „+‟ with file opening mode, with context to „r+‟ ?
Ans “+” is used to add alternate action with specified mode i.e. if used with “r” as “r+” it
means it will allows to read and alternate action write.
7 What is the difference between readline() and readlines() ?
Ans readline() allows to read single line from file and return the content as string.
readlines() function will read all the lines from file and return it as a List of
lines/string.
8 What is the purpose of using flush() in file handling operations ?
Ans When we are writing data in file the content will be stored in file only when we close
the file. Before closing the file i.e. during the operations fill will be created but the
content will be in buffer not in file and when we close the file content will be shifted
to file from buffer.
flush() allows the user to send content in file before closing the file. It means when
flush() is used it will clear the buffer and transfer content to file.
9 What is the advantage of opening file using „with‟ keyword?
Ans With keyword reduces the overheads involve in file handling operations like closing
the file after operation or handling the file closing with exceptions. When file is
opened using “with” it will manage these things i.e. file will be automatically closed
after operations. It ensures the closing of file even if exceptions arises.
10 Considering the content stored in file “CORONA.TXT”
O Corona O Corona
Jaldi se tum Go na
Social Distancing ka palan karona
sabse 1 meter ki duri rakhona
Lockdown me ghar me ho to
Online padhai karona

1|Page
www.python4csip.com

Write the output of following statements –


f = open("CORONA.TXT")
sr1 = ____________ # to read first line of file
str2 = ___________ # to read next line of file
str3 = ___________ # to read remaining lines of file

Ans str1 = f.readline()


str2 = f.readline()
str3 = f.readlines() OR str3 = f.read()
11 Considering the content stored in file “CORONA.TXT”
O Corona O Corona
Jaldi se tum Go na
Social Distancing ka palan karona
sabse 1 meter ki duri rakhona
Lockdown me ghar me ho to
Online padhai karona
Complete the missing statement using „for‟ loop to print all the lines of file
f = open(“CORONA.TXT”)
for ______________________ :
print(____)
Ans for line in f :
print(line)
12 What is the difference in write() and writelines()?
Ans write() function is used to write single string in file whereas writelines() function
allows to write List of strings
13 Considering the content stored in file “WORLDCUP.TXT”, write the output
India won the Cricket world cup of 1983
f = open(“WORLDCUP.TXT”)
print(f.read(2))
print(f.read(2))
print(f.read(4))
Ans In
di
a wo
14 Write a function in python to count the number of lines in “POEM.txt” begins from
Upper case character.
For e.g if the content of file is :
O Corona O Corona
Jaldi se tum Go na
Social Distancing ka palan karona
sabse 1 meter ki duri rakhona
Lockdown me ghar me ho to
online padhai karona
Output should be: Lines starting from Capital letters: 4
Ans def UpperCase():
f = open('poem.txt')
count = 0
for line in f:
if line[0].isupper():
count+=1
print("Lines starting from Capital letters: ",count)

2|Page
www.python4csip.com

15 Write a function in python to read lines from file “POEM.txt” and count how many
times the word “Corona” exists in file.
For e.g. if the content of file is :
O Corona O Corona
Jaldi se tum Go na
Social Distancing ka palan karona
sabse 1 meter ki duri rakhona
Lockdown me ghar me ho to
online padhai karona
O Corona O Corona
Jaldi se tum Go na
Output should be: Number of time word Corona occurs : 4

Ans Solution 1:
def CoronaCount():
f = open('poem.txt')
count = 0
for line in f:
words = line.lower().split()
count += words.count('corona')
print("Number of time words Corona occurs: ",count)

Solution 2:
def CoronaCount():
f = open('poem.txt')
count = 0
for line in f:
words = line.split()
for w in words:
if w.lower()=='corona':
count+=1
print("Number of time words Corona occurs: ",count)
16 Write a function in python to read lines from file “POEM.txt” and display all those
words, which has two characters in it.
For e.g. if the content of file is
O Corona O Corona
Jaldi se tum Go na
Social Distancing ka palan karona
sabse 1 meter ki duri rakhona
Lockdown me ghar me ho to
online padhai karona
O Corona O Corona
Jaldi se tum Go na
Output should be : se Go na ka ki me me ho to se Go na
Ans def TwoCharWord():
f = open('poem.txt')
count = 0
for line in f:
words = line.split()
for w in words:
if len(w)==2:
print(w,end=' ')
17 Write a function COUNT() in Python to read contents from file “REPEATED.TXT”, to
count and display the occurrence of the word “Catholic” or “mother”.
For example:
If the content of the file is “Nory was a Catholic because her mother was a Catholic , and
Nory‟s mother was a Catholic because her father was a Catholic , and her father was a
Catholic because his mother was a Catholic , or had been

3|Page
www.python4csip.com

The function should display:


Count of Catholic, mother is 9
Ans def COUNT():
f = open('REPEATED.txt')
count = 0
for line in f:
words = line.split()
for w in words:
if w.lower()=='catholic' or w.lower()=='mother':
count+=1
print('Count of Catholic,mother is',count)
18 Write a function dispS() in Python to read from text file “POEM.TXT” and display
those lines which starts with “S”
For example:
If the content of the file is “

O Corona O Corona
Jaldi se tum Go na
Social Distancing ka palan karona
Sabse 1 meter ki duri rakhona
Lockdown me ghar me ho to
online padhai karona
O Corona O Corona
Jaldi se tum Go na
The function should display:
Social Distancing ka palan karona
Sabse 1 meter ki duri rakhona
Ans def dispS():
f = open('poem.txt')
count = 0
for line in f:
if line[0].lower()=='s':
print(line)
19 Write a function COUNTSIZE() in Python to read the file “POEM.TXT” and display
size of file. For e.g. if the content of file is :
O Corona O Corona
Jaldi se tum Go na
Social Distancing ka palan karona
sabse 1 meter ki duri rakhona
Lockdown me ghar me ho to
online padhai karona
O Corona O Corona
Jaldi se tum Go na
The function should display
Size of file is 184
Ans def COUNTSIZE():
f = open('poem.txt')
s = f.read()
print(„Size of file is „,len(s))
20 Write a python function ATOEDISP() for each requirement in Python to read the file
“NEWS.TXT” and
(I) Display “E” in place of all the occurrence of “A” in the word COMPUTER.
(II) Display “E” in place of all the occurrence of “A”:
I SELL COMPUTARS. I HAVE A COMPUTAR. I NEED A COMPUTAR. I WANT A
COMPUTAR. I USE THAT COMPUTAR. MY COMPUTAR CRASHED.
The function should display

4|Page
www.python4csip.com

(I) I SELL COMPUTERS. I HAVE A COMPUTER. I NEED A COMPUTER. I WANT A


COMPUTER. I USE THAT COMPTUER. MY COMPUTER CRASHED.
(II) I SELL COMPUTERS. I HEVE E COMPUTER. I NEED E COMPUTER. I WENT E
COMPUTER. I USE THET COMPTUER. MY COMPUTER CRESHED.
Ans (I)
def ATOEDISP():
f = open('NEWS.TXT')
for line in f:
s = line.split()
for word in s:
if 'computar' in word.lower():
word=word.replace('A','E')
print(word,end=' ')
(I)
def ATOEDISP():
f = open('NEWS.TXT')
s = f.read()
for ch in s:
if ch.lower()=='a':
print('E',end='')
else:
print(ch,end='')

BINARY FILE HANDLING & CSV


1 Letter ____ is prefixed to store string in binary form
Ans b
2 Write a Python statement to open a text file “DATA.TXT” in binary mode so that
new contents can be written on it.
Ans f = open('DATA.TXT','wb')
3 Write a Python statement to open a text file “DATA.TXT” in binary mode so that
new content can be added to the end of file
Ans f = open('DATA.TXT','ab')
4 Write a Python statement to open a text file “DATA.TXT” in binary mode so that
existing contents can be read from file.
Ans f = open('DATA.TXT','rb')
5 _________ function is used to convert string in binary form.
Ans encode()
6 Consider the following Python code, and fill in the blank to complete the
program
f=open("India.txt","wb")
str="India is my country"
f.________(str.encode()) # statement to store the str in file
f.close()

Ans f.write(str.encode())
7 ________ function is used to fetch binary data from binary file
Ans
8 ________ function is used to convert binary string to string
Ans read() and load()
9 ________ function is used in binary mode to send the read pointer to desired
position
Ans seek()

5|Page
www.python4csip.com

Note: seek() function of file object is used to reposition the cursor


Syntax : seek(number of bytes to read, seek_direction)
Seek_direction can be 0 – beginning, 1 – current position , 2- from last (can be in
negative also for backward traversing)

10 Consider a binary file which stores Name of employee, where each name
occupies 20 bytes (length of each name) in file irrespective of actual
characters. Now you have to write code to access the first name, 5th name and
last name.

f = open("Emp.txt","rb")
s = ________ #code to get first record
print(s.decode())
___________ # code to position at 5th record
s = f.read(size)
print(s.decode())
___________ # code to position at last record
s = f.read(20)
print(s.decode())
f.close()
Ans f.read(20)
f.seek((5-1)*20)
f.read(((os.path.getsize(„Emp.txt‟)/20)-1)
11 Write a Python statement to reposition the read pointer to 20 bytes back
from the current position.
f = open("Emp.txt","rb")
f.read(20)
f.read(20)
f.read(20)
f.___________ # reposition read pointer to previous record
f.close()
Ans f.seek(-20,1)
12 Write a function RECCOUNT() to read the content of binary file „NAMES.DAT‟
and display number of records ( each name occupies 20 bytes in file ) in it.
For. e.g. if the content of file is:
SACHIN
AMIT
AMAN
SUSHIL
DEEPAK
HARI SHANKER
Function should display
Total Records are 6
Ans import os
def RECCOUNT():
size_of_rec = 20 #Each name will occupy 20 bytes
file_len = os.path.getsize('Names.dat')
num_record = file_len/size_of_rec
print("Total Records are :",num_record)
13 Write a function SCOUNT() to read the content of binary file „NAMES.DAT‟ and
display number of records (each name occupies 20 bytes in file ) where name
begins from „S‟ in it.

6|Page
www.python4csip.com

For. e.g. if the content of file is:


SACHIN
AMIT
AMAN
SUSHIL
DEEPAK
HARI SHANKER
Function should display
Total Names beginning from „S‟ are 2

Ans def SCOUNT():


s=' '
count=0
with open('Names.dat','rb') as f:
while(s):
s = f.read(20)
s=s.decode()
if len(s)!=0:
if s[0].lower()=='s':
count+=1
print('Total names beginning from "S" are ',count)
14 To read and write collections like LIST, DICTIONARIES Python provides a module
called _________
Ans pickle
15 ___________ is the process of converting structures to byte stream before writing to
file.
Ans Pickling
16 __________ is the process of converting byte stream to original structure.
Ans Unpickling
17 Pickling is done by the function ___________
Ans dump()
18 Unpickling is done by the function ________
Ans load()
19 Consider the following Python code and complete the missing statement:
import pickle
myfile = open("test.dat","wb")
d={1:100,2:200,3:300}
____________ #statement to store dictionary d in file
myfile.close()
Ans pickle.dump(d,myfile)
20 Consider the following Python code and complete the missing statement:
import pickle
myfile = open("test.dat","rb")
d = ___________ #statement to load dictionary data from file to „d‟
print(d)
myfile.close()
Ans pickle.load(myfile)
21 Python‟s standard streams are _________, _________, __________
Ans stdin, stdout, stderr
22 Python‟s standard streams are available in module ___________

7|Page
www.python4csip.com

Ans sys
23 From the given path identify the type of each:
(i) C:\mydata\web\resources\img.jpg
(ii) ..\web\data.conf
Ans (i) Absolute
(ii) Relative
24 Consider the following Binary file „Emp.txt‟, Write a function RECSHOW() to
display only those records who are earning more than 7000

Ans import pickle


def RECSHOW():
emp=[]
f = open('employee.dat','rb')
while True:
try:
emp = pickle.load(f) # loading data in emp list
except EOFError:
break
print("%10s"%"EMP NO ","%20s"%"EMP NAME ","%10s"%"EMP SALARY")
print("*****************************************************")
for e in emp:
if (e[2]>7000):
print("%10s"%e[0],"%20s"%e[1],"%10s"%e[2])
found=True

if found==False:
print("## SORRY EMPLOYEE NUMBER NOT FOUND ##")
f.close()
24 CSV stands for _______________________
Ans Comma Separate Value
25 __________ object is used to read data from csv file?
Ans reader
26 __________ object is used to perform write operation on csv file.
Ans writer
27 __________ function of writer object is used to send data to csv file to store.
Ans writerow()
28 Consider the following CSV file (emp.csv):
1,Peter,3500
2,Scott,4000
3,Harry,5000
4,Michael,2500
5,Sam,4200

Write Python function DISPEMP() to read the content of file emp.csv and display
only those records where salary is 4000 or above

8|Page
www.python4csip.com

Ans import csv


def DISPEMP():
with open('emp.csv') as csvfile:
myreader = csv.reader(csvfile,delimiter=',')
print("%10s"%"EMPNO","%20s"%"EMP NAME","%10s"%"SALARY")
print("==================================================")
for row in myreader:
if int(row[2])>4000:
print("%10s"%row[0],"%20s"%row[1],"%10s"%row[2])
29 Consider the following CSV file (emp.csv):
1,Peter,3500
2,Scott,4000
3,Harry,5000
4,Michael,2500
5,Sam,4200

Write a Python function DISPEMP() to read the content of file emp.csv and count
how many employee are earning less than 5000
Ans import csv
def DISPEMP():
with open('emp.csv') as csvfile:
myreader = csv.reader(csvfile,delimiter=',')
count=0
print("%10s"%"EMPNO","%20s"%"EMP NAME","%10s"%"SALARY")
print("==================================================")
for row in myreader:
if int(row[2])<5000:
count+=1
print("==================================================")
print("%40s"%"#EMPLOYEE GETTING SALARY <5000 :",count)
print("==================================================")
30 Consider the following CSV file (emp.csv):
1,Peter,3500
2,Scott,4000
3,Harry,5000
4,Michael,2500
5,Sam,4200

Write a Python function SNAMES() to read the content of file emp.csv and display
the employee record whose name begins from „S‟ also show no. of employee with
first letter „S‟ out of total record.
Output should be:
2,Scott,4000
5,Sam,4200
Number of „S‟ names are 2/5
Ans import csv
def SNAMES():
with open('emp.csv') as csvfile:
myreader = csv.reader(csvfile,delimiter=',')
count_rec=0
count_s=0
for row in myreader:

9|Page
www.python4csip.com

if row[1][0].lower()=='s':
print(row[0],',',row[1],',',row[2])
count_s+=1
count_rec+=1
print("Number of 'S' names are ",count_s,"/",count_rec)
31 Write a python function CSVCOPY() to take sourcefile, targetfile as parameter
and create a targetfile and copy the contents of sourcefile to targetfile
Ans import csv
def CSVCOPY(sourcefile,targetfile):
with open(sourcefile) as csvfile:
f2 = open(targetfile,'w')
mywriter=csv.writer(f2,delimiter=',')
myreader = csv.reader(csvfile,delimiter=',')
for row in myreader:
mywriter.writerow([row[0],row[1],row[2]])
f2.close()

For any query/suggestions write to me at : [email protected]

10 | P a g e
(Concept of Python Libraries)
CBSE Exam Solved Questions
1 Name the Python Library modules which need to be imported to invoke the following functions:
(i) load() (ii) dump()
2 Name the Python Library modules which need to be imported to invoke the following functions:

(i) log() (ii) match()


3 Name the Python Library modules which need to be imported to invoke the following functions :

(i) mean() (ii) randint()


4 Name the Python Library modules which need to be imported to invoke the following functions:
(i) sin() (ii) search()
5 Identify and write the name of the module to which the following functions belong:
(i) ceil( ) (ii) findall()
6 Name the modules to which the following functions belong:
(i) uniform() (ii) fabs()/abs()

Answers of Worksheet 2

1) (i) pickle (ii) pickle


2) (i) math (ii) re (or RegEx)
3) (i) statistics (ii) random
4) (i) math (ii) re (or RegEx)
5) (i) math (ii) re (or RegEx)
6) (i) random (ii) math

Quick Review on Modules with Function Name

pickle module

load()/dump()

math module

log()/pow()/gamma()/sin()/cos()/tan()/factorial()/degrees()/radians()/remainder()/comb()/dist()/exp()/erf()/
ceil( )/floor()/trunk()/fabs()/abs()

statistics module mean()/median()/mode()

random module
randint()/randrange()/getrandbits()/setstate()/getstate()/uniform()/speed()/choice()/choices()/shuffle()
/sample()/random()/triangular()/gauss()

CHAPTER 4: USING PYTHON LIBRARIES


A python program consist of three main components 1)Library or package
2)Module 3)Function/Sub Modules

RELATIONSHIP BETWEEN A MODULE, PACKAGE AND LIBRARY IN PYTHON

A module is a file containing python definitions, variables and classes and statement with .py extension A
Python package is simply a directory of python modules.
A library in python is collection of various packages. Conceptually there is no difference between package
and python Library.

Advantages of Python Modules


1) Putting code into modules is useful because of the ability to import the module functionality.
2) Reusability: A module can be used in some other python code. Hence it provide facility of code
reusability
3) A module allows us to logically organize our python code.
4) Grouping related code into a module makes the code easier to understand and use.
5) Categorisation: Similar types of attributes can be placed in a single module.

Creation of Module :
The following point must be noted before creating a module
• A module name should always end with .py extension
• We will not able to import module if it does not end with .py
• A module name must not be a Python keyword
A module is simply a python file which contains functions, classes and variables

Let us consider the following example of a module name area.py which contains three functions name
area_circle(r),area_square(s),area_rect(l,b)

import math
def area_circle(r):
return math.pi*r*r def area_square(s):
return s*s def area_rect(l,b):
return l*b

importing Modules:
There are two ways to import a modules
1) Using import statement: we can import single as well as multiple modules
1.1 For importing Single module
Syntax: import modulename

1.2 For importing Multiple modules


Syntax: import modulename1, modulename2, modulename3 To Use function inside module
Syntax modulename.function name

2) Using from Statement :To import some particular Function(s) from module we will use import
statement
2.1 To import Particular Function
Syntax: From <module name> import <write name of Function(s)>
OR
From <module name> import *
(This statement will import all the functions from modules)

To use a function inside a module you have to directly call function if your are importing the modules using
from statement
Example : Let us consider the following code.In this program we import the module with the help of from
statement and directly use the function instead of specifying Module name

from area.py import area_rect area_rect(5,4)

Alias name of Module :


providing another name to module is known as alias name. When we provide an alias name ,then alias name
is used for calling function
Syntax: import modulename as <alias name> example import area as A
now we will call function area_circle using alias name A of module area like as A.area_circle(5)

Note : we can also provide alias name to function of modules whenever we are using it with python from
statement and whenever we have to call any statement then we have to provide function alias name instead
of function original name ‘
Example: from area import area_Circle as C
C(6) # C is the alias name of function area_circle of module area

SECTION A (1 MARK QUESTION)

Q1. Which of these definitions correctly describe a module?


a) Denoted by triple quotes for providing the specifications of certain program elements.
b) Design and implementation of specific functionality to be incorporated into a program
c) Defines the specifications of how it is to be used.
d) Any program that reuses code.

Q2. Which of the following is not true about main modules?


a) When a python file is directly executed ,it is considered main module of a program
b) Main modules may import any number of modules
c) Special name given to main modules is: _main_
d) Other main modules can import main modules

Q3. Which of the following is not a valid namespace?


a) global namespace b) public namespace
c) built in namespace d) local namespace

Q4. Which of the following is false about “import module name” form of import?
a) The namespace of imported module becomes part of importing module
b) This form of input prevents name clash
c) The namespace of imported module becomes available to importing module
d) The identifiers in module are accessed as: modulename.identifier

Q5. what is the order of namespaces in which python looks for an identifier?
a) python first searches the global namespace, then the local namespace and finally the built in
namespace
b) python first searches the local namespace, then the global namespace and finally the built in
namespace
c) python first searches the built in namespace, then the global namespace and finally the local
namespace
d) python first searches the built in namespace , then the local namespace and finally the global
namespace

Q6. Which of these is not an advantage of using the modules?


a) Provides a means of reusing program code
b) Provides a means of dividing up tasks
c) Provides a means of reducing the size of the program
d) Provides a means of testing individual parts of the program

Q7. Which operator is used in the python to import all modules from packages?
(a) . operator (b) * operator
(c) ‐> symbol (d) , operator

Q8. Which file must be part of the folder containing python module file to make it importable python
package?
(a) init.py (b) steup .py
(c) init .py (d) setup.py
Q9. In python which is the correct method to load a module math?
(a) include math
(b) import math
(c) #include<math.h>
(d) using math

Q10. Which is the correct command to load just the tempc method from a module called usable?
(a) import usable,tempc (b) Import tempc from usable
(c) from usable import tempc (d) import tempc

Q11. What is the extension of the python library module?


(a) .mod (b) .lib
(c) .code (d) .py

SECTION B (2 MARK QUESTION)


Q1. How can you locate environment variable for python to locate the module files imported into a
program?

Q2. what is the output of the following piece of code?


#mod1
def change (a):
b=[x*2 for x in a] print (b)
#mod2
def change (a) :
b =[x*x for x in a] print (b)
from mode 1 import change from mode 2 import change
#main S= [1,2,3]
Change (s)
Note: Both the modules mod1 and mod 2 are placed in the same program. (a) [2,4,6] (b) [1,4,9]
(c) [2,4,6][1,4,9] (d) There is a name clash

Q3. What happens when python encounters an import statement in a program? What would happen, if there
is one more important statement for the same module, already imported in the same program?

Q4. What is the problem in the following piece of code?


from math import factorial print (math.factorial (5))

Q5. What is the output of the following piece of code?


#mod1
def change (a):
b=[x*2 for x in a] print (b)
#mod 2
def change (a):
b=[x*x for x in a] print (b)
from mod 1 import change from mod 2 imoprt change #main
S=[1,2,3]
Changes(s)

Q6. What would be the output produced by the following code :


import math import random
print ( math.ceil (random.random()))
Justify your answer.

SECTION C (3 MARK QUESTION)


Q1. Observe the following code and answer the question based on it.
# the math_operation module deff add (a,b):
return a+b def subtract(a,b):
return a‐b

Fill in the blanks for the following code:


1. Math _operation #get the name of the module.
2. print ( ) #output:math_operation
# Add 1and 2
3. print( (1,2) ) # output 3

Q2. Consinder the code given in above and on the basis of it, complete the code given below:
# import the subtract function #from the math_operation module
1. #subtract 1from 2
2. print( (2,1) ) # output : 1
# Import everything from math operations
3.
print (subtract (2,1) ) # output:1
print (add (1,1) ) # output:2

Q3. Consider a module ‘simple’ given below:


#module simple.py
“ “ “Greets or scold on call” “ “ def greet():
“ “ “ Greet anyone you like :‐)” “ “ Print (“Helloz”)
def scold ():
“ “ “ Use me for scolding ,but scolding is not good:‐( “ “ “

Print (“Get lost”) Count =10


Print (“greeting or scolding‐ is it simple?”)
Another program ‘test.py’ imports this module.The code inside test.py is : #test.py
import simple print(simple.count)
What would be the output produced ,if we run the program test.py? justify your answer.

Q4. Consider the following code: import math


import random
print(str(int(math.pow( random.randint (2,4),2) )), end = ‘ ’)
print(str( int ( math.pow(random.randint(2,4), 2))) , end = ‘ ’) print( str ( int (math.pow( random .randint
(2,4),2))))

What would be possible outputs out of the given four choices?


(i) 234
(ii) 944
(iii) 16 16 16
(iv) 249
(v) 494
(vi) 444
ANSWERS
SECTION A (1 MARK ANSWERS )
Ans 1. b) Design and implementation of specific functionality to be incorporated into a program Ans 2. d)
Ans3, b) Ans 4. a) Ans5. b)
Ans6. c) Ans 7. (b)
Ans 8. (c )
Ans 9. (b)
Ans 10. (C)
Ans 11. (d)
SECTION B (2 MARK ANSWERS )
Ans 1. Pythonpath command is used for the same. It has a role similar to path.This variable tells the python
interpreter where to locate the module files imported into a program.It should include the python source
library ,directory containing python source code.
Ans 2. (d)

Ans 3. When python encounters an important statement,it does the following:


• The code of imported module is interpreted and executed.
• Defined functions and variables created in the module are now available to the program that
imported module.
• For imported module, a new namespace is set up with the same name as that of the module. Any
duplicate import statement for the same module in the same program is ignored by python

Ans 4. In the “from–import” from of import, the imported identifiers (in this case factorial()) become part of
the current local namespace and hence their module’s name aren’t specified along with the module name.
Thus, the statement should be:
print( factorial (5) )

Ans 5. There is a name clash. A name clash is a situation when two different entities with the same name
become part of the same scope. Since both the modules have the same function name, there is a name clash,
which is an error..

Ans6. The output Produced would be 1.0

Ans 1 . 1. input
2. math_operation_name_
3. math.operation.add

SECTION C (3 MARK ANSWERS )

Ans 2. 1. from operation import subtract


2. subtract
3. from math operation import*

Ans 3. The output produced would be: Greeting or scolding – is it simple ? 10


The reason being , import module’s main block is executed upon import, so its important statement cause it
to print:
Greting or scolding‐ is it simple?
And print (simple.count) statement causes output’s next line ,i.e., 10

Ans 4. The possible outputs could be (ii), (iii) (v) and (vi).
The reason being that randint( ) would generate an integer between range 2…4, which is then raised to
power 2.
www.python4csip.com

WORKSHEET
DATA STRUCTURE
1 Stack is a data structure that follows _________ order
a. FIFO
b. LIFO
c. LILO
d. FILO
Ans b. LIFO
2 Queue is a data structure that follows ___________ order
a. FIFO
b. LIFO
c. LILO

m
d. FILO
Ans a. FIFO
3 What will be the output of the following Python code :

co
mylist =[‘java’,’c++’,’python’,’vb’,’vc++’,’php’,’cobol’]
print(mylist.pop())
mylist.append(‘c#’)
print(len(mylist))

p.
mylist.insert(3,’basic’)
print(mylist)
mylist.sort()
si
print(mylist)
print(mylist.index(‘php’))
Ans cobol
4c
7
['java', 'c++', 'python', 'basic', 'vb', 'vc++', 'php', 'c#']
['basic', 'c#', 'c++', 'java', 'php', 'python', 'vb', 'vc++']
on

4
4 Identify the error in following code:
(i) List1 = [10,20,30,40]
List1[4]=100
Name=”Michael Jackson”
th

(ii)
Name[2]=”k”
Ans (i) Index 4 is out of range, because List1 contains 4 items (Index 0 to 3 only)
(ii) String is immutable type so we can’t change any character of string in place.
py

5 Write down the status of Stack after each operation:


Stack =[10,20,30,40] where TOP item is 40
(i) Push 70
(ii) Push 100
(iii) Pop an item from Stack
(iv) Peek the Stack
Ans (i) [10,20,30,40,70]
(ii) [10,20,30,40,70,100]
(iii) [10,20,30,40,70]
(iv) 70

Page | 1
www.python4csip.com

6 Write down the status of Queue after each operation:


Queue=[10,20,30,40] where FRONT item is 10
(i) Insert 70
(ii) Remove item from Queue
(iii) Item at the front
Ans (i) [10,20,30,40,70]
(ii) [20,30,40,70]
(iii) 20
7 Identify the Data Structure (Stack/Queue) used for following operations in
computer?
(i) Function calling
(ii) Printer spooling
(iii) Undo operation
(iv) Solving expression

m
(v) Keyboard buffering
Ans (i) Stack
(ii) Queue

co
(iii) Stack
(iv) Stack
(v) Queue
8 Write down the steps to perform Binary Search for the following items in the
given list MYLIST.
(i)
(ii)
17
30
p.
si
MYLIST = [5,11,17,19,25,29,30,32,46,90]
Ans (i)
4c
First we will find mid, here low = 0 and high=9
mid = (low+high)//2 => (0+9)//2 = 4
Now we will compare 17 with middle position item MYLIST[4] which is 25
25 > 17 therefore 17 will be towards the left of 25 so we will update high=mid-1
on

Now we will find mid again


mid = (0+3)//2 => 1
Now we will compare 17 with middle position item MYLIST[1] which is 11
th

11 < 17 therefore 17 will be towards the right of 11 so we will update low=mid+1

Now we will find mid again


py

mid = (2+3)//2 => 2


Now we will compare 17 with middle position item MYLIST[2] which is 17
17 == 17, therefore item found, search successful, position found is index 2

(ii)
First we will find mid, here low = 0 and high=9
mid = (low+high)//2 => (0+9)//2 = 4
Now we will compare 30 with middle position item MYLIST[4] which is 25
25 < 30 therefore 30 will be towards the right of 25 so we will update low=mid+1

Page | 2
www.python4csip.com

Now we will find mid again


mid = (5+9)//2 => 7
Now we will compare 30 with middle position item MYLIST[7] which is 32
32>30, therefore 30 will be towards the left of 32, so we will update high=mid-1

Now we will find mid again


mid = (5+6)//2 => 5
Now we will compare 30 with middle position item MYLIST[5] which is 29
29<30, therefore 30 will be towards the right of 29, so we will update low=mid+1

Now we will find mid again


mid=(6+6)//2=>6
Now we will compare 30 with middle position item MYLIST[6] which is 30
30==30, therefore search successful, item found at position index 6

m
9 Given the list:
MYLIST = [5,11,17,19,25,29,30,30,32,46,90]

co
Write down the Python statements for the following requirement:
(i) To find the number of items in MYLIST
(ii) To find the frequency of item 30 in MYLIST i.e. how many times 30 is in
MYLIST

p.
(iii) Write the code to insert 45 in the above sorted list to its correct position (do
not disturb the sorting)
si
(iv) Write the code to delete 17 from the above sorted list
Ans (i) print(len(MYLIST))
4c
(ii) print(MYLIST.count(30))
(iii) import bisect
bisect.insort(MYLIST,45)
print(MYLIST)
on

(iv) MYLIST.remove(17)
print(MYLIST)

10 Write the function sumAlternate(MYLIST) as argument and calculate the sum of


th

all alternate elements of MYLIST and print it

For e.g. if the elements are


py

5 11 17 19 25 29 30 32 56 90

Output should be :
Total = 133
Ans def sumAlternate(MYLIST):
sum=0
for i in range(0,len(MYLIST),2):
sum+=MYLIST[i]
print("Total = ",sum)

Page | 3
www.python4csip.com

11 Write the function SumEvenOdd(MYLIST) to find the sum of all Even elements
and sum of all Odd elements present in MYLIST
For e.g if the elements are
8 12 17 19 25 29 33 32 56 90
Output should be:
Even Sum = 198
Odd Sum = 123
Ans def SumEvenOdd(MYLIST):
sume=0
sumo=0
for i in range(len(MYLIST)):
if MYLIST[i]%2==0:
sume+=MYLIST[i]
else:

m
sumo+=MYLIST[i]
print("Even Sum = ",sume)
print("Odd Sum = ",sumo)

co
12 Write the function CountEvenOdd(MYLIST) to find the count of all Even
elements and sum of all Odd elements.
For e.g if the elements are

p.
8 12 17 19 25 28 33 32 56 90
Output should be:
Even Count = 6
Odd Sum = 4
si
Ans def CountEvenOdd(MYLIST):
counte=0
4c
counto=0
for i in range(len(MYLIST)):
if MYLIST[i]%2==0:
counte+=1
on

else:
counto+=1
print("Even Count = ",counte)
print("Odd Count = ",counto)
th

13 Write code using list comprehension for the following:


(i) To create a list(mylist) with all even numbers from 2 to 100
(ii) To create a list(mylist) with all alternate values of another list(templist)
py

Ans (i) mylist = [i for i in range(2,101) if i%2==0]


(ii) templist=[10,20,30,40,50,60,70,80,90,100]
mylist = [templist[i] for i in range(0,len(templist),2) ]
14 Write a function PrintDiagonal(MATRIX), where MATRIX is a list storing 3 list
inside it with each list contains 3 items and print only diagonal elements and
also sum of it.
For e.g. is the MATRIX element is [[10,20,30],[40,50,60],[70,80,90]]
Output should be
10
50
90
Sum=150

Page | 4
www.python4csip.com

Ans def PrintDiagonal(MATRIX):


sum=0
for i in range(len(MATRIX)):
for j in range(len(MATRIX[i])):
if i==j:
print(MATRIX[i][j])
sum+=MATRIX[i][j]
print('Sum=',sum)
15 Write a function EvenOdd(MYLIST), which doubles each Odd elements of MYLIST
and half each Even element of MYLIST.
For e.g. if MYLIST = [10,11,40,4,17,23,45,100,80]
The output should be
[5,22,20,2,34,46,90,50,40]
Ans def EvenOdd(MYLIST):

m
for i in range(len(MYLIST)):
if MYLIST[i]%2==0:
MYLIST[i]//=2

co
else:
MYLIST[i]*=2
16 Write a function Sum7End(MYLIST), which display only those items from the list
which ends from the digit 7, also find total of these elements.

The output should be


27
p.
For e.g. if MYLIST = [10,27,15,107,97,5,7,81,47]
si
107
97
4c
7
47
Total = 285
Ans def Sum7End(MYLIST):
on

sum=0
for i in range(len(MYLIST)):
if MYLIST[i]%10==7:
print(MYLIST[i])
th

sum+=MYLIST[i]
print('Total=',sum)
17 Write QueueUp(Student) and QueueDel(Student) methods/function Python to add a
py

new Student and delete a Student from a List of Student names, considering them to
act as insert and delete operations of the Queue data structure
Ans def QueueUp(Student):
name = input('Enter any name')
Student.append(name)
def QueueDel(Student):
if len(Student)==0:
print('Underflow')
else:
name = Student.pop(0)
print('Deleted Name was ',name)

Page | 5
www.python4csip.com

18 Write a function in python, Push(Employee) and Pop(Employee) to add a new


Employee and delete a Employee from a List of Employee Names, considering them to
act as push and pop operations of the Stack data structure.
Ans def Push(Employee):
name=input('Enter Employee name ')
Employee.append(name)
def Pop(Employee):
if len(Employee)==0: # or if Employee==[]:
print('Underflow')
else:
name = Employee.pop()
print('Popped Name was ',name)
19 Write QueueUp(Student) and QueueDisp(Student) methods/function Python to add a
new Student and display Student names from a List of Students, considering them to

m
act as insert and display operations of the Queue data structure
Ans def QueueUp(Student):
name = input('Enter Name')

co
Student.append(name)
def QueueDisp(Student):
if len(Student)==0:
print('Underflow')
else:

p.
print('Queue Items Front-to-Rear')
for i in range(len(Student)):
si
print(Student[i])
20 Write a function in python, Push(Employee) and Show(Employee) to add a new
4c
Employee and display Employee names from a List of Employee, considering them to
act as push and show operations of the Stack data structure.
Ans def Push(Employee):
name=input('Enter name :')
on

Employee.append(name)
def Show(Employee):
if len(Employee)==0:
print('Underflow')
th

else:
print('Employee Names ')
for i in range(len(Employee)):
py

print(Employee[i])

21 Write a function Count(Salary,Val) to count and display number of times Val is


present in the list Salary.
For example
If the Salary contains: 50000,40000,50000,60000,70000,50000,1000 and Val
contains 50000
The function should display
50000 found 3 Times

Page | 6
www.python4csip.com

Ans def Count(Salary,Val):


count=0
for S in Salary:
if S==Val:
count+=1
print(Val,'found',count,'Times')
22 Consider the randomly ordered numbers stored in a list
55,53,57,51,52,54,56
Show the content of list after the First, Second and third pass of the Bubble sort
method used for arranging in descending order
Note: show the status of all elements after each pass very clearly encircling the
changes.
Ans After First Pass
[53, 55, 51, 52, 54, 56, 57]

m
After Second Pass
[53, 51, 52, 54, 55, 56, 57]
After Third Pass

co
[51, 52, 53, 54, 55, 56, 57]
23 Consider the randomly ordered numbers stored in a list
55,53,57,51,52,54,56
Show the content of list after the First, Second and third pass of the Insertion sort

p.
method used for arranging in ascending order
Note: show the status of all elements after each pass very clearly encircling the
changes.
si
Ans After Pass 1
[53, 55, 57, 51, 52, 54, 56]
4c
After Pass 2
[53, 55, 57, 51, 52, 54, 56]
After Pass 3
[51, 53, 55, 57, 52, 54, 56]
on

24 Consider the randomly ordered numbers stored in a list


55,53,57,51,52,54,56
Show the content of list after the First, Second and third pass of the Bubble sort
th

method used for arranging in descending order


Note: show the status of all elements after each pass very clearly encircling the
changes.
py

Ans After Pass 1


[55, 57, 53, 52, 54, 56, 51]
After Pass 2
[57, 55, 53, 54, 56, 52, 51]
After Pass 3
[57, 55, 54, 56, 53, 52, 51]

Page | 7
www.python4csip.com

25 Raj is a Python programmer working on sorting module. For a small list of values he
has written the Bubble sorting code but code is not executing. Help Raj and rewrite
the code after removing all the errors and underlining the correction(s) made:

def BubbleSort(num):
for i in range(num-1):
for j in range(num-1-i):
if num[j+1]>num[j]:
num[i],num[j+1]=num[j+1],num[i]
Ans def BubbleSort(num):
for i in range(len(num)-1):
for j in range(len(num)-1-i):
if num[j]>num[j+1]:

m
num[j],num[j+1]=num[j+1],num[j]
26 Raj is a Python programmer working on sorting module. For this he has written the
Insertion sorting code but code is not executing. Help Raj and rewrite the code after

co
removing all the errors and underlining the correction(s) made:
def InsertionSort(mylist):
i=1
while i<len(mylist):

p.
key=mylist[i]
j=i-1
while j>=0 and mylist[j]<key:
si
mylist[j]=mylist[j+1]
j-=1
4c
key = mylist[j+1]
i-=1
Ans def InsertionSort(mylist):
on

i=1
while i<len(mylist):
key=mylist[i]
th

j=i-1
while j>=0 and mylist[j]>key:
py

mylist[j+1]=mylist[j]
j-=1
mylist[j+1]=key
i+=1
27 Write a Python function/method Count5and7(N), to find and display count of all
number between 1 to N which are either divisible by 5 or by 7.
For e.g. if the N is 20 then output should be:
Count=6
As (5,7,10,14,15,20) are the number between 1 to N which are divisible by either 5 or by 7)

Page | 8
www.python4csip.com

Ans def Count5and7(N):


count=0
for i in range(1,N+1):
if i%5==0 or i%7==0:
count+=1
print('Count=',count)
28 Write a Python function/method SwapMiddle(Codes) to swap the first half of the
content of the list Codes with second half of the list Codes and display the
swapped values.
For e.g. if the list Codes contains : [22,44,55,66,88,11] then function should swap and
display as:

m
[66,88,11,22,44,55]
Ans def SwapMiddle(Codes):

co
i=0
mid = len(Codes)//2

p.
while i<mid:
Codes[i],Codes[mid+i]=Codes[mid+i],Codes[i]
i+=1
si
29 Raj is a Python programmer working of Data structure Stack to store name of visitors,
he has implemented the code for PUSH and POP, but both functions are not
4c
producing the correct result. Help Raj in identifying the error(s) and also write the
Correct code for specific line number:

def PUSH(VISITOR,name):
on

name.append(VISITOR) #Line 1
top = len(VISITOR)-1 #Line 2

def POP(VISITOR):
th

if len(VISITOR)==1: #Line 3
return "Sorry! No Visitor to delete " #Line 4
else:
py

val = VISITOR.pop(1) #Line 5


if len(VISITOR)==1: #Line 6
top=None #Line 7
else
top=len(VISITOR) #Line 8
return val

Ans #Line 1
VISITOR.append(name)

Page | 9
www.python4csip.com

#Line 3
if len(VISITOR)==0:
#Line 5
val = VISITOR.pop()
#Line 6
if len(VISITOR)==0:
#Line 8
top = len(VISITOR)-1
30 Raj is a Python programmer working of Data structure Queue to store name of
REQUESTNO, he has implemented the code for ENQUEUE and DEQUEUE, for insert
and delete operation in Queue resp. But both functions are not producing the correct
result. Help Raj in identifying the Line Number where code is incorrect and also write
the Correct code for same Line Number.
def Enqueue(REQUESTNO,item):

m
REQUESTNO.add(item) #Line 1
if len(REQUESTNO)==1: #Line 2
front=rear=1 #Line 3

co
else:
rear=len(REQUESTNO)-1 #Line4

def Dequeue(REQUESTNO):
if REQUESTNO==0:

else:
print("Underflow")
#Line 5
#Line 6
p.
si
val = REQUESTNO.pop(len(REQUESTNO)-1) #Line 7
if len(REQUESTNO)==0: #Line 8
4c
front=None #Line 9
return val
Ans #Line 1
REQUESTNO.append(item)
on

#Line 3
front = rear = 0
#Line 5
if len(REQUESTNO)==0:
th

#Line 7
val = REQUESTNO.pop(0)
#Line 9
py

front = rear = None

Page | 10
MYSQL REVISION TOUR

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.

DIFFERENT DATA MODELS

A data model refers to a set of concepts to describe the structure of a database , and certain constraints (restrictions)
that the database should obey. The four data model that are used for database management are :

1. Relational data model : In this data model, the data is organized into tables (i.e. rows and columns). These tablesare
called relations.

2. Hierarchical data model 3. Network data model 4. Object Oriented data model

RELATIONAL MODEL TERMINOLOGY

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

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:

1. Data Definition Language(DDL) Commands


Commands that allow you to perform task, related to data definition e.g;
 Creating, altering and dropping.
 Granting and revoking privileges and roles.
 Maintenance commands.
2. Data Manipulation Language(DML) Commands
Commands that allow you to perform data manipulation e.g., retrieval, insertion, deletion and modification of
data stored in a database.

3. Transaction Control Language(TCL) Commands


Commands that allow you to manage and control the transactions e.g.,
 Making changes to database, permanent
 Undoing changes to database, permanent
 Creating savepoints
 Setting properties for currenttransactions.

MySQL ELEMENTS

1. Literals 2. Datatypes 3. Nulls 4. Comments

LITERALS
It refer to a fixed data value. This fixed data value may be of character type or numeric type. For example, ‘replay’ ,
‘Raj’, ‘8’ , ‘306’ are all character literals.
Numbers not enclosed in quotation marks are numeric literals. E.g. 22 , 18 , 1997 are all numeric literals.
Numeric literals can either be integer literals i.e., without any decimal or be real literals i.e. with a decimal point e.g. 17
is an integer literal but 17.0 and 17.5 are real literals.

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 Data Type


1. int – used for numberwithout decimal.
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 Data Type
1. date – used to store date in YYYY-MM-DD format.
2. time – used to store time in HH:MM:SS format.
String Data Types
1. char(m) – used to store a fixed length string. m denotes max. numberof characters.
2. varchar(m) – used to store a variable length string. m denotes max. no. of characters.
DIFFERENCE BETWEEN CHAR AND VARCHAR DATA TYPE

S.NO. Char Datatype Varchar Datatype


1. It specifies a fixed length character It specifies a variable length character string.
String.
2. When a column is given datatype as When a column is given datatype as VARCHAR(n),
CHAR(n), then MySQL ensures that all then the maximum size a value in this column can
values stored in that column have this have is n bytes. Each value that is stored in this
length i.e. n bytes. If a value is shorter column store exactly as you specify it i.e. no blanks
than this length n then blanks are are added if the length is shorter than maximum
added, but the size of value remains length n.
n bytes.
NULL VALUE
If a column in a row has no value, then column is said to be null , or to contain a null. You should use a null value when
the actual value is not known or when a value would not be meaningful.

DATABASE COMMNADS

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


- Tables are created with the CREATE TABLE command. When a table is created, its columns are named, data types
and sizes are supplied for each column.
Syntax of CREATE TABLE command is :
CREATE TABLE <table-name>
( <column name> <data type> ,
<column name> <data type> ,
……… ) ;
E.g. in order to create table EMPLOYEE given below :
ECODE ENAME GENDER GRADE GROSS
We write the following command :
CREATE TABLE employee
( ECODE integer ,
ENAME varchar(20) ,
GENDER char(1) ,
GRADE char(2) ,
GROSS integer );
INSERTING DATA INTO TABLE
- The rows are added to relations(table) using INSERT command of SQL. Syntax of INSERT is :
INSERT INTO <tablename> [<column list>]
VALUE ( <value1> , <value2> , …..) ;
e.g. to enter a row into EMPLOYEE table (created above), we write command as :
INSERT INTO employee
VALUES(1001 , ‘Ravi’ , ‘M’ , ‘E4’ , 50000);

OR
INSERT INTO employee (ECODE , ENAME , GENDER , GRADE , GROSS)
VALUES(1001 , ‘Ravi’ , ‘M’ , ‘E4’ , 50000);

ECODE ENAME GENDER GRADE GROSS


1001 Ravi M E4 50000

In order to insert another row in EMPLOYEE table , we write again INSERT command :
INSERT INTO employee
VALUES(1002 , ‘Akash’ , ‘M’ , ‘A1’ , 35000);

ECODE ENAME GENDER GRADE GROSS


1001 Ravi M E4 50000
1002 Akash M A1 35000

INSERTING NULL VALUES

- To insert value NULL in a specific column, we can type NULL without quotes and NULL will be inserted in that
column. E.g. in order to insert NULL value in ENAME column of above table, we write INSERT command as :

INSERT INTO EMPLOYEE


VALUES (1004 , NULL , ‘M’ , ‘B2’ , 38965 ) ;

ECODE ENAME GENDER GRADE GROSS


1001 Ravi M E4 50000
1002 Akash M A1 35000
1004 NULL M B2 38965

SIMPLE QUERY USING SELECT COMMAND


- The SELECT command is used to pull information from a table. Syntax of SELECT command is :
SELECT <column name>,<column name>
FROM <tablename>
WHERE <condition name> ;
SELECTING ALL DATA
- In order to retrieve everything (all columns) from a table, SELECTcommand is used as :
SELECT * FROM <tablename> ;
e.g.
In order to retrieve everything from Employee table, we write SELECT command as :
EMPLOYEE
ECODE ENAME GENDER GRADE GROSS
1001 Ravi M E4 50000
1002 Akash M A1 35000
1004 NULL M B2 38965

SELECT * FROM Employee ;


SELECTING PARTICULAR COLUMNS
EMPLOYEE
ECODE ENAME GENDER GRADE GROSS
1001 Ravi M E4 50000
1002 Akash M A1 35000
1004 Neela F B2 38965
1005 Sunny M A2 30000
1006 Ruby F A1 45000
1009 Neema F A2 52000
- A particular column from a table can be selected by specifying column-names with SELECTcommand. E.g. in above
table, if we want to select ECODE and ENAME column, then command is :
SELECT ECODE , ENAME
FROM EMPLOYEE ;
E.g.2 in order to select only ENAME, GRADE and GROSS column, the command is :
SELECT ENAME , GRADE , GROSS
FROM EMPLOYEE ;

SELECTING PARTICULAR ROWS


We can select particular rows from a table by specifying a condition through WHERE clause along with SELECT
statement. E.g. In employee table if we want to select rows where Gender is female, then command is :
SELECT * FROM EMPLOYEE
WHERE GENDER = ‘F’ ;
E.g.2. in order to select rows where salary is greater than 48000, then command is :
SELECT * FROM EMPLOYEE
WHERE GROSS > 48000 ;

ELIMINATING REDUNDANT DATA


The DISTINCT keyword eliminates duplicate rows from the results of a SELECT statement. For example ,
SELECT GENDER FROM EMPLOYEE ;

GENDER
M
M
F
M
F
F

SELECT DISTINCT(GENDER) FROM EMPLOYEE ;

DISTINCT(GENDER)
M
F

VIEWING STRUCTURE OF A TABLE


- If we want to know the structure of a table, we can use DESCRIBE or DESC command, as per following syntax :
DESCRIBE | DESC <tablename> ;
e.g. to view the structure of table EMPLOYEE, commandis : DESCRIBE EMPLOYEE ; OR DESC EMPLOYEE ;

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> ;
e.g. In output, suppose we want to display ECODE column as EMPLOYEE_CODE in output , then command is :
SELECT ECODE AS “EMPLOYEE_CODE”
FROM EMPLOYEE ;

CONDITION BASED ON A RANGE


- The BETWEEN operator defines a range of values that the column values must fall in to make the condition true. The
range include both lowervalue and uppervalue.

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 ;
Output will be :

ECODE ENAME GRADE


1001 Ravi E4
1006 Ruby A1

CONDITION BASED ON A LIST


- To specify a list of values, IN operator is used. The IN operator selects value that match any value in a given list of
values. E.g.

SELECT * FROM EMPLOYEE


WHERE GRADE IN (‘A1’ , ‘A2’);
Output will be :

ECODE ENAME GENDER GRADE GROSS


1002 Akash M A1 35000
1006 Ruby F A1 45000
1005 Sunny M A2 30000
1009 Neema F A2 52000

- The NOT IN operatorfinds rows that do not match in the list. E.g.
SELECT * FROM EMPLOYEE
WHERE GRADE NOT IN (‘A1’ , ‘A2’);
Output will be :

ECODE ENAME GENDER GRADE GROSS


1001 Ravi M E4 50000
1004 Neela F B2 38965

CONDITION BASED ON PATTERN MATCHES


- LIKE operator is used for pattern matching in SQL. Patterns are described using two special wildcard characters:

1. percent(%) – The % character matches any substring.


2. underscore(_) – The _ character matches any 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%’ ;
Output will be :

ENAME
Ravi
Ruby

e.g. to display details of employee whose second character in name is ‘e’.


SELECT *
FROM EMPLOYEE
WHERE ENAME LIKE ‘_e%’ ;

Output will be :

ECODE ENAME GENDER GRADE GROSS


1004 Neela F B2 38965
1009 Neema F A2 52000

e.g. to display details of employee whose name ends with ‘y’.


SELECT *
FROM EMPLOYEE
WHERE ENAME LIKE ‘%y’ ;

Output will be :

ECODE ENAME GENDER GRADE GROSS


1005 Sunny M A2 30000
1006 Ruby F A1 45000

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 ;
e.g.
STUDENT
Roll_No Name Marks
1 ARUN NULL
2 RAVI 56
4 SANJAY NULL
to display the names of those students whose marks is NULL, we use the command :
SELECT Name
FROM EMPLOYEE
WHERE Marks IS NULL ;
Output will be :
Name
ARUN
SANJAY
SORTING RESULTS
Whenever the SELECT query is executed , the resulting rows appear in a predecided order.The ORDER BY clause allow
sorting of query result. The sorting can be done either in ascending or descending order, the default is ascending.

The ORDER BY clause is used as :


SELECT <column name> , <column name>….
FROM <tablename>
WHERE <condition>
ORDER BY <column name> ;

e.g. to display the details of employees in EMPLOYEE table in alphabetical order, we use command :
SELECT *
FROM EMPLOYEE
ORDER BY ENAME ;
Output will be :
ECODE ENAME GENDER GRADE GROSS
1002 Akash M A1 35000
1004 Neela F B2 38965
1009 Neema F A2 52000
1001 Ravi M E4 50000
1006 Ruby F A1 45000
1005 Sunny M A2 30000

e.g. display list of employee in descending alphabetical order whose salary is greater than 40000.
SELECT ENAME
FROM EMPLOYEE
WHERE GROSS > 40000
ORDER BY ENAME desc ;
Output will be :
ENAME
Ravi
Ruby
Neema

MODIFYING DATA IN TABLES


you can modify data in tables using UPDATE command of SQL. The UPDATE command specifies the rows to be changed
using the WHERE clause, and the new data using the SET keyword. Syntax of update command is :
UPDATE <tablename>
SET <columnname>=value , <columnname>=value
WHERE <condition> ;

e.g. to change the salary of employee of those in EMPLOYEE table having employee code 1009 to 55000.
UPDATE EMPLOYEE
SET GROSS = 55000
WHERE ECODE = 1009 ;
UPDATING MORE THAN ONE COLUMNS
e.g. to update the salary to 58000 and grade to B2 for those employee whose employee code is 1001.
UPDATE EMPLOYEE
SET GROSS = 58000, GRADE=’B2’
WHERE ECODE = 1009 ;
OTHER EXAMPLES
Increase the salary of each employee by 1000 in the EMPLOYEE table.
UPDATE EMPLOYEE
SET GROSS = GROSS +100 ;
Double the salary of employees having grade as ‘A1’ or ‘A2’ .
UPDATE EMPLOYEE
SET GROSS = GROSS * 2 ;
WHERE GRADE=’A1’ OR GRADE=’A2’ ;
Change the grade to ‘A2’ for those employees whose employee code is 1004 and name is Neela.
UPDATE EMPLOYEE
SET GRADE=’A2’
WHERE ECODE=1004 AND GRADE=’NEELA’ ;

DELETING DATA FROM TABLES


To delete some data from tables, DELETE command is used. The DELETE command removes rows from a table. The
syntax of DELETE command is:
DELETE FROM <tablename>
WHERE <condition> ;
For example, to remove the details of those employee from EMPLOYEE table whose grade is A1.
DELETE FROM EMPLOYEE
WHERE GRADE =’A1’ ;

TO DELETE ALL THE CONTENTS FROM A TABLE


DELETE FROM EMPLOYEE ;

So if we do not specify any condition with WHERE clause, then all the rows of the table will be deleted. Thus above
line will delete all rows from employee table.

DROPPING TABLES
The DROP TABLE command lets you drop a table from the database. The syntax of DROP TABLE command is :
DROP TABLE <tablename> ;
e.g. to drop a table employee, we need to write :
DROP TABLE employee ;
Once this command is given, the table name is no longer recognized and no more commands can be given on that table.
After this command is executed, all the data in the table along with table structure will be deleted.

S.NO. DELETE COMMAND DROP TABLE COMMAND


1 It is a DML command. It is a DDL Command.
2 This command is used to delete only rows This command is used to delete all the data of the table
of data from a table along with the structure of the table. The table is no
longer recognized when this command gets executed.
3 Syntax of DELETE command is: Syntax of DROP command is :
DELETE FROM <tablename> DROP TABLE <tablename> ;
WHERE <condition> ;

ALTER TABLE COMMAND


The ALTER TABLE command is used to change definitions of existing tables.(adding columns,deleting columns etc.). The
ALTER TABLE command is used for :
1. adding columns to a table
2. Modifying column-definitions of atable.
3. Deleting columns of a table.
4. Adding constraints to table.
5. Enabling/Disabling constraints.

ADDING COLUMNS TO TABLE

To add a column to a table, ALTER TABLE command can be used as per following syntax:

ALTER TABLE <tablename>


ADD <Column name> <datatype> <constraint> ;
e.g. to add a new column ADDRESS to the EMPLOYEE table, we can write command as :

ALTER TABLE EMPLOYEE


ADD ADDRESS VARCHAR(50);
A new column by the name ADDRESS will be added to the table, where each row will contain NULL value for
the new column.
ECODE ENAME GENDER GRADE GROSS ADDRESS
1001 Ravi M E4 50000 NULL
1002 Akash M A1 35000 NULL
1004 Neela F B2 38965 NULL
1005 Sunny M A2 30000 NULL
1006 Ruby F A1 45000 NULL
1009 Neema F A2 52000 NULL

However if you specify NOT NULL constraint while adding a new column, MySQL adds the new column with the default
value of that datatype e.g. for INT type it will add 0 , for CHAR types, it will add a space, and so on.

e.g. Given a table namely Testt with the following data in it.

Col1 Col2
1 A
2 G

Now following commands are given for the table. Predict the table contents after each of the following statements:
(i) ALTER TABLE testt ADD col3 INT ;
(ii) ALTER TABLE testt ADD col4 INT NOT NULL ;
(iii) ALTER TABLE testt ADD col5 CHAR(3) NOT NULL ;
(iv) ALTER TABLE testtADD col6 VARCHAR(3);

MODIFYING COLUMNS

Column name and data type of column can be changed as per following syntax :

ALTER TABLE <table name>


CHANGE <old column name> <new column name> <new datatype>;
If Only data type of column need to be changed, then

ALTER TABLE <table name>


MODIFY <column name> <new datatype>;
In table EMPLOYEE, change the column GROSS to SALARY.

ALTER TABLE EMPLOYEE


CHANGE GROSS SALARY INTEGER;
In table EMPLOYEE , change the column ENAME to EM_NAME and data type from VARCHAR(20) to
VARCHAR(30).

ALTER TABLE EMPLOYEE


CHANGE ENAME EM_NAME VARCHAR(30);
In table EMPLOYEE , change the datatype of GRADE column from CHAR(2) to VARCHAR(2).

ALTER TABLE EMPLOYEE


MODIFY GRADE VARCHAR(2);

DELETING COLUMNS

To delete a column from a table, the ALTER TABLE command takes the following form :

ALTER TABLE <table name>


DROP <column name>;
e.g. to delete column GRADE from table EMPLOYEE, we will write :
ALTER TABLE EMPLOYEE
DROP GRADE ;

ADDING/REMOVING CONSTRAINTS TO A TABLE


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

 TO ADD PRIMARY KEY CONSTRAINT


ALTER TABLE <table name>
ADD PRIMARY KEY (Column name);

e.g. to add PRIMARY KEY constraint on column ECODE of table EMPLOYEE , the command is :
ALTER TABLE EMPLOYEE
ADD PRIMARY KEY (ECODE) ;

 TO ADD FOREIGN KEY CONSTRAINT

ALTER TABLE <table name>


ADD FOREIGN KEY (Column name) REFERENCES Parent Table (Primary key of Parent Table);

REMOVING CONSTRAINTS
- To remove primary key constraint from a table, we use ALTER TABLE command as :
ALTER TABLE <table name>
DROP PRIMARY KEY ;
- To remove foreign key constraint from atable, we use ALTER TABLE command as :
ALTER TABLE <table name>
DROP FOREIGN KEY ;

ENABLING/DISABLING CONSTRAINTS
Only foreign key can be disabled/enabled in MySQL.
To disable foreign keys : SET FOREIGN_KEY_CHECKS = 0 ;
To enable foreign keys : SET FOREIGN_KEY_CHECKS = 1 ;
INTEGRITY CONSTRAINTS/CONSTRAINTS
- A constraint is a condition or check applicable on a field(column) orset of fields(columns).
- 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 CHECK Makes sure that all values in a column satisfy certain criteria
5 PRIMARY KEY Used to uniquely identify a row in the table
6 FOREIGN KEY Used to ensure referential integrity of the data

NOT NULL CONSTRAINT


By default, a column can hold NULL. It you not want to allow NULL value in a column, then NOT NULL constraint must be
applied on that column. E.g.

CREATE TABLE Customer


( SID integer NOT NULL ,
Last_Name varchar(30) NOT NULL ,
First_Name varchar(30) ) ;

Columns SID and Last_Name cannot include NULL, while First_Name can include NULL.

An attempt to execute the following SQL statement,


INSERT INTO Customer
VALUES (NULL , ‘Kumar’ , ‘Ajay’);
will result in an error because this will lead to column SID being NULL, which violates the NOT NULL constraint on that
column.

DEFAULT CONSTARINT
The DEFAULT constraint provides a default value to a column when the INSERT INTO statement does not provide a
specific value. E.g.

CREATE TABLE Student


( Student_ID integer ,
Name varchar(30) ,
Score integer DEFAULT 80);

When following SQL statement is executed on table created above:


INSERT INTO Student
no value has been provided for score field.
VALUES (10 , ‘Ravi’ );

Then table Student looks like the following:

Student_ID Name Score


10 Ravi 80 score field has got the default value

UNIQUE CONSTRAINT
- The UNIQUE constraint ensures that all values in a column are distinct. In other words, no two rows can hold the
same value for a column with UNIQUE constraint.
e.g.
CREATE TABLE Customer
( SID integer Unique ,
Last_Name varchar(30) ,
First_Name varchar(30) ) ;

Column SID has a unique constraint, and hence cannot include duplicate values. So, if the table already contains the
following rows :

SID Last_Name First_Name


1 Kumar Ravi
2 Sharma Ajay
3 Devi Raj

The executing the following SQL statement,


INSERT INTO Customer
VALUES (‘3’ , ‘Cyrus‘ , ‘Grace’) ;
will result in an error because the value 3 already exist in the SID column, thus trying to insert another row with that
value violates the UNIQUE constraint.

CHECK CONSTRAINT
- The CHECK constraint ensures that all values in a column satisfy certain conditions. Once defined, the table will only
insert a new row or update an existing row if the new value satisfies the CHECK constraint.

e.g.
CREATE TABLE Customer
( SID integer CHECK(SID > 0),
Last_Name varchar(30) ,
First_Name varchar(30) ) ;

So, attempting to execute the following statement :


INSERT INTO Customer
VALUES (-2 , ‘Kapoor’ , ‘Raj’);

will result in an error because the values for SID must be greater than 0.

PRIMARY KEY CONSTRAINT


- A primary key is used to identify each row in a table. A primary key can consist of one or more fields(column) on a
table. When multiple fields are used as a primary key, they are called a composite key.

- You can define a primary key in CREATE TABLE command through keywords PRIMARY KEY. e.g.

CREATE TABLE Customer


( SID integer NOT NULL PRIMARY KEY,
Last_Name varchar(30) ,
First_Name varchar(30) ) ;

Or
CREATE TABLE Customer
( SID integer,
Last_Name varchar(30) ,
First_Name varchar(30),
PRIMARY KEY (SID) ) ;

- The latterway is useful if you want to specify acomposite primary key, e.g.

CREATE TABLE Customer


( Branch integer NOT NULL,
SID integer NOT NULL ,
Last_Name varchar(30) ,
First_Name varchar(30),
PRIMARY KEY (Branch , SID) ) ;

FOREIGN KEY CONSTRAINT


- Foreign key is a non key column of a table (child table) that draws its values from primary key of another table(parent
table).
- The table in which a foreign key is defined is called a referencing table or child table. A table to which a foreign key
points is called referenced table or parent table.

e.g.
Parent Table
TABLE: STUDENT
ROLL_NO NAME CLASS
Primary key
1 ABC XI
2 DEF XII
3 XYZ XI Child Table
TABLE: SCORE
ROLL_NO MARKS
1 55
2 83
3 90

Here column Roll_No is a foreign key in table SCORE(Child Table) and it is drawing its values from Primary key
(ROLL_NO) of STUDENT table.(Parent Key).

CREATE TABLE STUDENT


( ROLL_NO integer NOT NULL PRIMARY KEY ,
NAME VARCHAR(30) ,
CLASS VARCHAR(3) );

CREATE TABLE SCORE


( ROLL_NO integer ,
MARKS integer,
FOREIGN KEY(ROLL_NO) REFERNCES STUDENT(ROLL_NO) ) ;

* Foreign key is always defined in the child table.


Syntax for using foreign key
FOREIGN KEY(column name) REFERENCES Parent_Table(PKof Parent Table);

REFERENCING ACTIONS
Referencing action with ON DELETE clause determines what to do in case of a DELETE occurs in the parent table.
Referencing action with ON UPDATE clause determines what to do in case of a UPDATE occurs in the parent table.

Q: Distinguish between a Primary Key and a Unique key in a table.


S.NO. PRIMARY KEY UNIQUE KEY
1. Column having Primary key can’t contain Column having Unique Key can contain
NULL value NULL value
2. There can be only one primary key in Table. Many columns can be defined as Unique key

Q: Distinguish between ALTER Command and UPDATE command of SQL.


S.NO. ALTER COMMAND UPDATE COMMAND
1. It is a DDL Command It is a DML command
2. It is used to change the definition of It is used to modify the data values present
existing table, i.e. adding column, in the rows of the table.
deleting column, etc.
3. Syntax for adding column in a table: Syntax for using UPDATE command:
ALTER TABLE <tablename> UPDATE <Tablename>
ADD <Column name><Datatype> ; SET <Columnname>=value
WHERE <Condition> ;
AGGREGATE / GROUP FUNCTIONS
Aggregate / Group functions work upon groups of rows , rather than on single row, and return one single output.
Different aggregate functions are : COUNT( ) , AVG( ) , MIN( ) , MAX( ) , SUM ( )

Table : EMPL

EMPNO ENAME JOB SAL DEPTNO


8369 SMITH CLERK 2985 10
8499 ANYA SALESMAN 9870 20
8566 AMIR SALESMAN 8760 30
8698 BINA MANAGER 5643 20
8912 SUR NULL 3000 10

1. AVG( )
This function computes the average of given data.
e.g. SELECT AVG(SAL)
FROM EMPL ;

Output
AVG(SAL)
6051.6

2. COUNT( )
This function counts the number of rows in a given column.
If you specify the COLUMN name in parenthesis of function, then this function returns rows where COLUMN is not
null.
If you specify the asterisk (*), this function returns all rows, including duplicates and nulls.

e.g. SELECT COUNT(*)


FROM EMPL ;
Output
COUNT(*)
5

e.g.2 SELECT COUNT(JOB)


FROM EMPL ;
Output
COUNT(JOB)
4

3. MAX( )
This function returns the maximum value from a given column or expression.

e.g. SELECT MAX(SAL)


FROM EMPL ;
Output
MAX(SAL)
9870
4. MIN( )
This function returns the minimum value from a given column or expression.

e.g. SELECT MIN(SAL)


FROM EMPL ;
Output
MIN(SAL)
2985

5. SUM( )
This function returns the sum of values in given column or expression.

e.g. SELECT SUM(SAL)


FROM EMPL ;

Output
SUM(SAL)
30258

GROUPING RESULT – GROUP BY


The GROUP BY clause combines all those records(row) that have identical values in a particular field(column) or a group of
fields(columns).
GROUPING can be done by a column name, or with aggregate functions in which case the aggregate produces a value for
each group.
Table : EMPL

EMPNO ENAME JOB SAL DEPTNO


8369 SMITH CLERK 2985 10
8499 ANYA SALESMAN 9870 20
8566 AMIR SALESMAN 8760 30
8698 BINA MANAGER 5643 20

e.g. Calculate the number of employees in each grade.


SELECT JOB, COUNT(*)
FROM EMPL
GROUP BY JOB ;
Output
JOB COUNT(*)
CLERK 1
SALESMAN 2
MANAGER 1

e.g.2. Calculate the sum of salary for each department.


SELECT DEPTNO , SUM(SAL)
FROM EMPL
GROUP BY DEPTNO ;
Output
DEPTNO SUM(SAL)
10 2985
20 15513
30 8760
e.g.3. find the average salary of each department.
Sol: select avg(sal)
FROM EMPL
GROUP BY DEPTNO ;

NESTED GROUP
- To create a group within a group i.e., nested group, you need to specify multiplefields in the GROUP BY expression.
e.g. To group records job wise within Deptno wise, you need to issue a query statement like :

SELECT DEPTNO , JOB , COUNT(EMPNO)


FROM EMPL
GROUP BY DEPTNO , JOB ;
Output
DEPTNO JOB COUNT(EMPNO)
10 CLERK 1
20 SALESMAN 1
20 MANAGER 1
30 SALESMAN 1

PLACING CONDITION ON GROUPS – HAVING CLAUSE


- The HAVING clause places conditions on groups in contrast to WHERE clause that places condition on individual
rows. While WHERE conditions cannot include aggregate functions, HAVING conditions can do so.
- e.g. To display the jobs where the number of employees is less than 2,
SELECT JOB, COUNT(*)
FROM EMPL
GROUP BY JOB
HAVING COUNT(*) < 2 ;
Output
JOB COUNT(*)
CLERK 1
MANAGER 1

MySQL FUNCTIONS
A function is a special type of predefined command set that performs some operation and returns a single value.
Types of MySQL functions : String Functions , Maths Functions and Date & Time Functions.
Table : EMPL

EMPNO ENAME JOB SAL DEPTNO


8369 SMITH CLERK 2985 10
8499 ANYA SALESMAN 9870 20
8566 AMIR SALESMAN 8760 30
8698 BINA MANAGER 5643 20
8912 SUR NULL 3000 10

STRING FUNCTIONS
1. CONCAT( ) - Returns the Concatenated String.
Syntax : CONCAT(Column1 , Column2 , Column3, …….)
e.g. SELECT CONCAT(EMPNO , ENAME) FROM EMPL WHEREDEPTNO=10;
Output
CONCAT(EMPNO , ENAME)
8369SMITH
8912SUR

2. LOWER( ) / LCASE( ) - Returns the argument in lowercase.


Syntax : LOWER(Column name)
e.g.
SELECT LOWER(ENAME) FROM EMPL ;
Output
LOWER(ENAME)
smith
anya
amir
bina
sur

3. UPPER( ) / UCASE( ) - Returns the argument in uppercase.


Syntax : UPPER(Column name)
e.g.
SELECT UPPER(ENAME) FROM EMPL ;
Output
UPPER(ENAME)
SMITH
ANYA
AMIR
BINA
SUR

4. SUBSTRING( ) / SUBSTR( ) – Returns the substring as specified.


Syntax : SUBSTR(Column name, m , n), where m specifies starting index and n specifies number of characters
from the starting index m.
e.g.
SELECT SUBSTR(ENAME,2,2) FROM EMPL WHERE DEPTNO=20;
Output
SUBSTR(ENAME,2,2)
NY
IN

SELECT SUBSTR(JOB,-2,2) FROMEMPL WHERE DEPTNO=20;


Output
SUBSTR(JOB,-4,2)
SM
AG

5. LTRIM( ) – Removes leadingspaces.


e.g. SELECT LTRIM(‘ RDBMS MySQL’) ;
Output
LTRIM(‘ RDBMS MySQL’)
RDBMS MySQL
6. RTRIM( ) – Removes trailing spaces.
e.g. SELECT RTRIM(‘ RDBMS MySQL ’) ;
Output
RTRIM(‘ RDBMS MySQL’)
RDBMS MySQL

7. TRIM( ) – Removes trailing and leading spaces.


e.g. SELECT TRIM(‘ RDBMS MySQL ’) ;
Output
TRIM(‘ RDBMS MySQL’)
RDBMS MySQL

8. LENGTH( ) – Returns the length of a string. e.g.


SELECT LENGTH(“CANDID”) ;
Output
LENGTH(“CANDID”)
6

e.g.2.
SELECT LENGTH(ENAME) FROM EMPL;
Output
LENGTH(ENAME)
5
4
4
4
3

9. LEFT( ) – Returns the leftmost numberof characters as specified.


e.g. SELECT LEFT(‘CORPORATE FLOOR’ , 3) ;
Output
LEFT(‘CORPORATE FLOOR’, 3)
COR

10. RIGHT( ) – Returns the rightmost numberof characters as specified.


e.g. SELECT RIGHT(‘CORPORATE FLOOR’ , 3) ;
Output
RIGHT(‘CORPORATE FLOOR’, 3)
OOR

11. MID( ) – This function is same as SUBSTRING( ) / SUBSTR( ) function. E.g.


SELECT MID(“ABCDEF” , 2 , 4 ) ;
Output
MID(“ABCDEF” , 2 , 4 )
BCDE

NUMERIC FUNCTIONS
These functions accept numeric values and after performing the operation, return numeric value.

1. MOD( ) – Returns the remainder of given two numbers. e.g. SELECT MOD(11 , 4) ;
Output
MOD(11, 4 )
3

2. POW( ) / POWER( ) - This function returns mn i.e , a numberm raised to the nth power.
e.g. SELECT POWER(3,2) ;
Output
POWER(3, 2 )
9

3. ROUND( ) – This function returns a numberrounded off as per given specifications.


e.g. ROUND(15.193 , 1) ;
Output
ROUND(15.193 , 1)
15.2

e.g. 2. SELECT ROUND(15.193 , -1); - This will convert the number to nearest ten’s .

Output
ROUND(15.193 , -1)
20

4. SIGN( ) – This function returns sign of a given number.


If number is negative, the function returns -1.
If number is positive, the function returns 1.
If number is zero, the function returns 0.

e.g. SELECT SIGN(-15) ;


Output
SIGN(-15)
-1

e.g.2 SELECT SIGN(20) ;


Output
SIGN(20)
1

5. SQRT( ) – This function returns the square root of a given number. E.g.
SELECT SQRT(25) ;
Output
SQRT(25)
5

6. TRUNCATE( ) – This function returns a number with some digits truncated. E.g.
SELECT TRUNCATE(15.79 , 1) ;

Output
TRUNCATE(15.79 , 1)
15.7

E.g. 2. SELECT TRUNCATE(15.79 , -1); - This command truncate value 15.79 to nearest ten’s place.
Output
TRUNCATE(15.79 , -1)
10

DATE AND TIME FUNCTIONS


Date functions operate on values of the DATE datatype.

1. CURDATE( ) / CURRENT_DATE( ) – This function returns the current date. E.g.


SELECT CURDATE( ) ;
Output
CURDATE( )
2016-12-13

2. DATE( ) – This function extracts the date part from a date. E.g.
SELECT DATE( ‘2016-02-09’) ;
Output
DATE( ‘2016-02-09’)
09

3. MONTH( ) – This function returns the month from the date passed. E.g.
SELECT MONTH( ‘2016-02-09’) ;
Output
MONTH( ‘2016-02-09’)
02

4. YEAR( ) – This function returns the yearpart of a date. E.g.


SELECT YEAR( ‘2016-02-09’) ;
Output
YEAR( ‘2016-02-09’)
2016

5. DAYNAME( ) – This function returns the name of weekday. E.g.


SELECT DAYNAME( ‘2016-02-09’) ;
Output
DAYNAME( ‘2016-12-14’)
Wednesday

6. DAYOFMONTH( ) – This function returns the day of month. Returns value in range of 1 to 31.
E.g. SELECT DAYOFMONTH( ‘2016-12-14’) ;
Output
DAYOFMONTH( ‘2016-12-14’)
14

7. DAYOFWEEK( ) – This function returns the day of week. Return the weekdayindex for date. (1=Sunday,
2=Monday,……., 7=Saturday)
SELECT DAYOFWEEK( ‘2016-12-14’) ;
Output
DAYOFWEEK( ‘2016-12-14’)
4

8. DAYOFYEAR( ) – This function returns the day of the year. Returns the value between 1 and 366. E.g.
SELECT DAYOFYEAR(‘2016-02-04) ;
Output
DAYOFYEAR( ‘2016-02-04’)
35

9. NOW( ) – This function returns the current date and time.


It returns a constant time that indicates the time at which the statement began to execute.

e.g. SELECT NOW( );

10. SYSDATE( ) – It also returns the current date but it return the time at which SYSDATE( ) executes. It differs from the
behavior for NOW( ), which returns a constant time that indicates the time at which the statement began to execute.
e.g. SELECT SYSDATE( ) ;
JOINS

- A join is a query that combines rows from two or more tables. In a join- query, more than
one table are listed in FROM clause.

Table : empl

EMPNO ENAME JOB SAL DEPTNO


8369 SMITH CLERK 2985 10
8499 ANYA SALESMAN 9870 20
8566 AMIR SALESMAN 8760 30
8698 BINA MANAGER 5643 20

Table : dept

DEPTNO DNAME LOC


10 ACCOUNTING NEW DELHI
20 RESEARCH CHENNAI
30 SALES KOLKATA
40 OPERATIONS MUMBAI

CARTESIAN PRODUCT/UNRESTRICTED JOIN/CROSS JOIN

- Consider the following query :


SELECT *
FROM EMPL, DEPT ;

This query will give you the Cartesian product i.e. all possible concatenations are formed of all rows
of both the tables EMPL and DEPT. Such an operation is also known as Unrestricted Join. It returns
n1 x n2 rows where n1 is number of rows in first table and n2 is number of rows in second table.

EQUI-JOIN

- The join in which columns are compared for equality, is called Equi- Join. In equi-join, all the
columns from joining table appear in the output even if they are identical.
e.g. SELECT * FROM empl, dept
WHERE empl.deptno = dept.deptno ;
deptno column is appearing twice in output.

Q: with reference to empl and dept table, find the location of employee SMITH.

ename column is present in empl and loc column is present in dept. In order to obtain the result, we
have to join two tables.

SELECT ENAME, LOC


FROM EMPL, DEPT
WHERE EMPL.DEPTNO = DEPT.DEPTNO AND ENAME=’SMITH’;

Q: Display details like department number, department name, employee number, employee
name, job and salary. And order the rows by department number.

SELECT EMPL.deptno, dname,empno,ename,job,sal


FROM EMPL,DEPT
WHERE EMPL.DEPTNO=DEPT.DEPTNO
ORDER BY EMPL.DEPTNO;

QUALIFIED NAMES

Did you notice that in all the WHERE conditions of join queries given so far, the field(column) names
are given as: <tablename>.<columnname>

This type of field names are called qualified field names. Qualified field names are very useful in
identifying a field if the two joining tables have fields with same time. For example, if we say deptno
field from joining tables empl and dept, you’ll definitely ask- deptno field of which table ? To avoid
such an ambiguity, the qualified field names are used.
TABLE ALIAS

- A table alias is a temporary label given along with table name in FROM clause.

e.g.

SELECT E.DEPTNO, DNAME,EMPNO,ENAME,JOB,SAL


FROM EMPL E, DEPT D
WHERE E.DEPTNO = D.DEPTNO
ORDER BY E.DEPTNO;
In above command table alias for EMPL table is E and for DEPT table , alias is D.

Q: Display details like department number, department name, employee number, employee
name, job and salary. And order the rows by employee number with department number. These
details should be only for employees earning atleast Rs. 6000 and of SALES department.

SELECT E.DEPTNO, DNAME,EMPNO, ENAME, JOB, SAL


FROM EMPL E, DEPT D
WHERE E.DEPTNO = D.DEPTNO
AND DNAME=’SALES’
AND SAL>=6000
ORDER BY E.DEPTNO;

NATURAL JOIN
By default, the results of an equijoin contain two identical columns. One of the two identical
columns can be eliminated by restating the query. This result is called a Natural join.

e.g. SELECT empl.*, dname, loc


FROM empl,dept
WHERE empl.deptno = dept.deptno ;

empl.* means select all columns from empl table. This thing can be used with any table.

The join in which only one of the identical columns(coming from joined tables) exists, is called
Natural Join.

LEFT, RIGHT JOINS


When you join tables based on some condition, you may find that only some, not all rows from
either table match with rows of other table. When you display an equi join or natural join, it shows
only the matched rows. What if you want to know which all rows from a table did not match with
other. In such a case, MySQL left or right JOIN can be very helpful.
LEFT JOIN
- You can use LEFT JOIN clause in SELECT to produce left join i.e.
SELECT <select-list>
FROM <table1> LEFT JOIN <table2>
ON <joining-condition>;
- When using LEFT JOIN all rows from the first table will be returned whether there are
matches in the second table or not. For unmatched rows of first table, NULL is shown in
columns of second table.

S1 S2
Roll_no Name Roll_no Class
1 A 2 III
2 B 4 IX
3 C 1 IV
4 D 3 V
5 E 7 I
6 F 8 II
SELECT S1.ROLL_NO, NAME,CLASS
FROM S1 LEFT JOIN S2 ON S1.ROLL_NO=S2.ROLL_NO;

RIGHT JOIN
- It works just like LEFT JOIN but with table order reversed. All rows from the second table are
going to be returned whether or not there are matches in the first table.
- You can use RIGHT JOIN in SELECT to produce right join i.e.
SELECT <select-list>
FROM <table1> RIGHT JOIN <table2> ON <joining-condition>;

e.g SELECT S1.ROLL_NO, NAME,CLASS


FROM S1 RIGHT JOIN S2 ON S1.ROLL_NO=S2.ROLL_NO;
WORKSHEET - 1
NETWORKING
1 Expand the following Terms:
SMTP, VoIP, GMS, WLL, MBPS, WAN, CDMA, FTP, PPP, WWW, XML, ASP, HTTP, TCP/IP
Ans. SMTP : Simple Mail Transfer Protocol
VoIP : Voice over Internet Protocol
WLL : Wireless Local Loop
MBPS : Megabyte per second
WAN : Wide Area Network
CDMA : Code Division Multiple Access
FTP : File Transfer Protocol
PPP : Point to Point Protocol

om
WWW : World Wide Web
XML : Extensible Markup Language
ASP : Active Server Pages
HTTP: Hypertext Transfer Protocol
TCP/IP : Transmission Control Protocol / Internet Protocol

.c
2 Differentiate between Start Topology and Bus Topology. What are the advantages and
disadvantages of Star Topology over Bus Topology?
Ans.
STAR
Each node is connected to each other
through central node i.e. Switch / Hub
ip BUS
Each node is connected to each other
though backbone cable
cs
If Switch/Hub fails entire network will If Backbone cable fails entire network
be stopped will be stopped
Data transmission speed is fast Data transmission speed is slow as
compare to Star
4
More cable is required Less cable is required
Fault Diagnosis is easy Fault Diagnosis is difficult
Adding/Removal of node is easy Difficult as compare to Star to
on

Add/Remove nodes
High cost setup Low cost setup as compare to Star
Signal transmission is not unidirectional Signal transmission is unidirectional
3 Classify each of the following Web Scripting as Client Side Scripting and Server Side
th

Scripting :
(i) Java Scripting
(ii) ASP
py

(iii) VB Scripting
(iv) JSP
Ans. Client Side : Java Scripting, VB Scripting
Server Side : ASP, JSP
4 Raj has been informed that there had been a backdoor entry to his computer, which
has provided access to his system thought a malicious user/program, allowing
confidential and personal information to be subjected to theft. It happened because
he clicked a link provided in one of the pop-ups from a website announcing him to
be the winner of prizes worth 10 Million Dollars. Which of the following has caused
this out of the following?
(i) Virus (ii) Worm (iii) Trojan Horse
Also mention what he should do to prevent this infection
Ans. (ii) Trojan Horse
5 Raj Singhania is in India and he is interested in communicating with her uncle in
America. He wants to show one of her own designed gadgets to him and also wants
to demonstrate its working without physically going America. Which protocol out of
the following will be ideal for the same?
(i) POP3 (ii) SMTP (iii) VoIP (iv) HTTP
Ans. (ii) VoIP
6 Give 2 differences between 3G and 4G telecommunication technologies.
Ans. i) 4G data transfer rate is faster than 3G
ii) Better video calling and video conferencing in 4G
7 Write the expanded names for the following abbreviated terms used in Networking

om
and Communications:
(i) MBPS (ii) WAN (iii) CDMA (iv) WLL
Ans. MBPS : Mega byte per second
WAN : Wide Area Network
CDMA : Code division multiple access
WLL : Wireless local loop

.c
8 Identify and expand the terms used in Designing the web page:
(i) HTTP (iv) XML (iii) FTP (iv) HTML
Ans. HTTP : hypertext transfer protocol
XML : extensible markup language
FTP : File transfer protocol
HTML : hypertext markup language ip
cs
9 Which of the following device send data to every connected node:
(i) Switch (ii) Hub (iii) Router (iv) Gateway
Ans. HUB
10 In which type of switching first the connection is established between sender and
4

receiver and then the data is transferred?


Ans. Circuit Switching
on

11 _________ is used to provide short-range wireless connectivity between two electronic devices
that within the distance of 5-10 meters
Ans. Infrared
12 Which out of the following, will you use to have an audio-visual chat with an expert sitting in
a far-away place to fix up a technical issue?
th

(i) VoIP
(ii) Email
(iii) FTP
py

Ans. VoIP
13 Identify the cable which consists of an inner copper core and a second conducting outer
sheath:
(i) Twisted Pair (ii) Co-axial (iii) Fiber Optical (iv) Shielded Twisted Pair
Ans. Co-axial
14 In fiber optic transmission, data is travelled in the form of:
(i) Light (ii) Radio link (iii) Microwave Link (iv) Very low frequency
Ans. Light
15 Out of the following, Which transmission media has the highest transmission speed in a
network?
(i) Twisted Pair Cable (ii) Co-axial Cable (iii) Fiber Optical (iv) Electrical Cable
Ans. Fiber Optical
16 Which of the following devices modulates digital signals into analog signals that can be sent
over traditional telephone lines?
(i) Router (ii) Gateway (iii) Bridge (iv) Modem
Ans. Modem
17 What is the name of earliest form of Internet? Also expand it
Ans. ARPANet :Advanced Research Project Agency Network
18 A Local telephone line network is an example of ___________ network
(i) Packet Switched (ii) Line Switched (iii) Circuit Switched (iv) Bit switched
Ans. Circuit Switched
19 Packet switching is based on the _____________ principal
a. Stop and Wait
b. Store and Forward

om
c. Store and Wait
d. Stop and Forward
Ans. Store and Forward
20 The required resources for communication between end systems are reserved for the
duration of the session between end systems in ________ method
a. Packet Switching

.c
b. Line Switching
c. Parallel Switching
d. Circuit Switching
Ans.
21
Circuit Switching

ip
In which type of Switching techniques, the resources are allocated on demand?
a. Packet Switching
cs
b. Line Switching
c. Parallel Switching
d. Circuit Switching
Ans. Packet Switching
4
22 What is Internet? What are the major services offered by Internet?
Ans. A global computer network providing a variety of information and communication facilities,
consisting of interconnected networks using standardized communication protocols.
on

Or any other suitable definition


Major services offered by Internet :
a) Email
b) Chat
c) Information Search
th

d) Online Shopping
e) Online Education
f) E-Governance etc.
py

23 Which client server program allows multiple users to communicate online with real time
audio, video and text chat in dynamic 3D environment?
Ans. Interspace
24 What is Bandwidth? What is the measuring unit of Bandwidth in term of range of
frequencies a channel can pass?
Ans. Bandwidth: Data transfer rates that can be supported by a network is called its bandwidth.
Bandwidth can be measured in 2 ways:
(i) In Hertz : KHz, MHz, GHz
(ii) In Bits per second : Mbps, Gpbs
25 What are the different types of Transmission Media? Give example of each.
Ans. There are 2 types of Transmission media:
(i) Wired : Twisted pair cable, co-axial cable, fiber optical cable
(ii) Wireless : Radio waves, microwaves, infrared, satellite
26 What is the difference between Radio wave transmission and Microwave transmission?
Ans. Radio waves Microwaves
It travels in Omni-directional It travels in straight line
It can penetrate solid objects It cannot penetrate solid objects
Sender and receiver antenna need not to be Sender and receiver antenna must be
properly aligned proper aligned as it is line-of-sight
transmission

om
27 Which wireless transmission medium is used for controlling our TV, AC with Remote?
Ans. Infrared
28 Which of the transmission is suitable for the transferring data from one place to anywhere in
the world?
Ans. Satellite
29 Out of the following guided media, which is not susceptible to external interference?

.c
(i) Twisted Pair (ii) Co-axial Cable (iii) Fiber Optical (iv) Electric Wire
Ans. Fiber Optical
30 Raj is working as a manager in ABC Ltd. He wants to install CCTV Camera in every part of

(i) Twisted Pair


Ans. Co-axial cable
(ii) Co-axial Cable
ip
multistory Building of his office. Select the best wire media to connect each CCTV camera.
(iii) Fiber Optical (iv) Electric Wire
cs
31 Which connector is used connect Ethernet Cable to LAN Card?
Ans. RJ-45 (Registered jack)
32 What is NIC? Give the name of unique number assigned to each NIC.
4
Ans. Network Interface Card. The unique number assigned to each NIC is MAC Address (Media
access control)
33 Which of the following device is used for sorting and distribution of data packet to their
on

destination based on their IP Address?


(i) Gateway (ii) Router (iii) Bridges (iv) Switch
Ans. Router
34 Why Switch is known as Intelligent Hub?
th

Ans. Switch filters the incoming packets and finds the destination node from the MAC table. It
transmit data only to intended node.
35 Which of the following device is used to connect network of different protocols so that they
py

can communicate properly?


(i) Gateway (ii) Router (iii) Bridges (iv) Switch
Ans. Gateway
36 802.11 is used for _________

Ans. Wi-Fi (wireless fidelity)


37 Raj, is a web programmer, He is creating a user registration form through which new user
will be registered. In this form, The form contains USERNAME textbox,
CHECKAVAILABILITY button, PASSWORD box, REGISTER button and few other controls.
Requirement is “User Name cannot be Blank”, CHECKAVAILABILITY will check whether ID
is available to create or not? “Password will be of certain length and pattern”, REGISTER will
create the user. Identify the type of Script (Client Side/Server Side) to use for each
requirement(control)
USER NAME BOX= ______ CHECK AVAILAIBILTY BUTTON= ________
PASSWORD BOX= ______ REGISTER BUTTON = _____________
Ans. USER NAME : Client Side, CHECK AVAILABILITY: Server Side
PASSWRD : Client Side, REGISTER : Server Side
38 What is Bus Topology? What are its advantages and disadvantages?
Ans. Bus : In bus topology all the nodes are connected to a main cable called backbone.
Advantages :
(1) It is easy to install
(2) Less cable length

om
(3) Failure of node does not affect the network
Disadvantages:
(1) Fault diagnosis is difficult
(2) At a time only one node can transmit data
(3) In case of backbone failure, entire network will fail.
39 In Star topology all the nodes are connected though which device?

.c
Ans. Switch / Hub
40 What is Star Topology? What are its advantages and Disadvantages?
Ans. Star Topology : In star topology each node is directly connected to a hub/switch.
Advantages:
(1) Easy to install
(2) Easy to expand the node
(3) Fault diagnosis is easy ip
cs
Disadvantages:
(1) Switch failure means entire network failure
(2) More cable required
(3) Costly
4
41 What is Tree Topology? What is the main purpose of using Tree Topology?
Ans. Tree Topology: is a combination of bus and star topologies.
on

The main purpose of Tree topology is to combine multiple star topology networks. All star are
connected together like bus.
42 Which type of Network is generally privately owned and links the devices in a single office,
building or Campus?
a. LAN
th

b. MAN
c. WAN
d. PAN
Ans. LAN
py

43 Uploading photo from mobile phone to Desktop computer is an example of _________


a. LAN
b. PAN
c. MAN
d. WAN
Ans. PAN
44 Data communication system spanning states, countries or the whole world is ________
a. PAN
b. LAN
c. WAN
d. MAN
Ans. WAN
45 Internet is an example of most common type of _________ network
a. LAN
b. PAN
c. MAN
d. WAN
Ans. WAN
46 The network designed for customers who need a high speed connectivity is _________
a. LAN
b. MAN
c. WAN
d. PAN
Ans. MAN

om
47 Rearrange the following types of network PAN, MAN, LAN, WAN in descending order of their
area coverage.
Ans WAN > MAN >LAN >PAN
48 What is the possible maximum area covered by LAN
a. 100-500 meter
b. 1-5 KM

.c
c. 1-10 KM
d. 1-2KM
Ans. 1-10KM

establishing LAN?
a. Ethernet
b. Telephone ip
49 Which of the following Cabling technique is considered best between buildings for
cs
c. Optical fiber
d. Co-axial

Ans. Ethernet
4
50 Raj is a Cable TV operator; he wants to give connection to his customers. Which type of
Cable will be best for Raj to connect his subscribers in the different areas of City?
on

a. Ethernet
b. Telephone
c. Optical fiber
d. Co-axial
Ans. Co-axial
th

WORKSHEET – 2
py

NETWORKING
1 Every device connected to network must follow certain rules known as?
Ans. Protocol
2 Out of following protocol, which protocol is used for sending emails to recipient?
a. POP3
b. SLIP
c. SMTP
d. HTTP
Ans. SMTP
3 Out of the following protocol, which protocol is used to establish connection between sender
and receiver through handshaking process?
a. HTTP
b. TCP/IP
c. FTP
d. SMTP
Ans. TCP/IP
4 Out of the following protocol, which protocol is used for downloading or uploading of file from
local PC to web server and vice-versa?
a. FTP
b. SMTP
c. HTTP
d. TCP/IP

om
Ans. FTP
5 In which type of protocol, data is transmitted between two directly connected computers?
a. TCP/IP
b. HTTP
c. SLIP
d. PPP

.c
Ans. PPP
6 Raj is looking for some information about How Router works, for this he opens the browser
and typed the URL of requested site. In few moments he received the requested page on his
browser screen. Identify the type of protocol, used between Browser (Client) and Web Server
for the communication?
a. TCP/IP
b. HTTP ip
cs
c. SMTP
d. POP3
Ans. HTTP
7 Raj is a working as Group Leader in XL corporation. 30 employees are working under Raj,
and they have to constantly report to Raj through email, and also Raj communicate to them
4

through email. Now Raj wants a system through which emails are automatically downloaded
to Outlook so that later on he will be able to read emails even if offline. Identify the protocol
on

which will help Raj in this scenario?


a. POP3
b. SMTP
c. HTTP
d. TCP/IP
th

Ans. POP3
8 Identify the Protocol used for voice communication over Internet through compression of
py

voice data into packets.


a. HTTP
b. VoIP
c. POP3
d. SLIP
Ans. VoIP
9 Raj, is working as a Tech Support Engineer and sometimes he wants to work on Client’s
computer from his office. Identify the traditional protocol used for this purpose?
a. FTP
b. Telnet
c. HTTP
d. POP3
Ans. Telnet
10 In which type of Mobile communication Protocol SIM card is used in handset?
a. CDMA
b. GPRS
c. GSM
d. WLL
Ans. GSM
11 Expand the terms: GSM, GPRS, CDMA, WLL
Ans. GSM : Global System for Mobile Communication
GRPS: General Packet Radio Services
CDMA : Code Division Multiple Access
WLL : Wireless Local Loop
12 In which type of Mobile communication Protocol, no external SIM card was allowed to insert

om
and it was inbuilt in the handset?
a. CDMA
b. GPRS
c. GSM
d. WLL
Ans. CDMA

.c
13 Which service was used in 2G and 3G network for Internet connection which charges the
user on the basis of volume of data used?
a. CDMA
b. GPRS

Ans. GRPS
c. GSM
d. WLL
ip
cs
14 ________ consists of user handset and a base station. The base station is connected to central
exchange as well as antenna.
a. CDMA
b. GPRS
c. GSM
4

d. WLL
Ans. WLL
on

15 What is the difference between 3G and 4G technology?


Ans. i) 4G data transfer rate is faster than 3G
ii) Better video calling and video conferencing in 4G
16 List out the features of 4G technology
 The speed of this generation is from 100 Mbps to 1Gbps
th

Ans.
 Based on LTE-Advanced (Long Term Evolution)
 Voice as VoIP (Voice over Internet Protocol (VoLTE)
 Better Video calling than 3G, Video conferencing etc.
py

17 In which generation only voice call was possible and there was not data exchange?
a. 1G
b. 2G
c. 3G
d. 4G
Ans. 1G
18 Name any two popular Mobile processors?
Ans. Qualcomm Snapdragon, Apple A13 Bionic
19 What are the 2 main sub processors of Mobile processor?
Ans. Communication Processing Unit & Application Processing Unit
20 Which sub-processor of Mobile process is responsible for making and receiving calls?
Ans. Communication Processing Unit
21 The status code of HTTP, when page not found is?
Ans. 404
22 The status code of HTTP, which page is found is?
Ans. 200
23 Which of the following is reliable communication protocol?
a. IP
b. TCP
c. FTP
d. All of the above
Ans. All of the above
24 This is the telecommunication protocol that all computers must use to be part of the
Internet.

om
a. FTP
b. IP
c. TCP
d. POP
Ans. TCP
25 In network HTTP resource are located by:

.c
a. Uniform Resource Identifier
b. Uniform Resource Log
c. Unique Resource Locator
d. Uniform Resource Locator
Ans.
26
Ans.
Uniform Resource Locator
What are the two popular Chat protocols?
IRC (Internet Relay chat) ip
cs
XMPP (Extensible Messaging and Presence Protocol)
27 Out of the 2 Chat protocols IRC and XMPP, which one is used in the latest apps like
Facebook, WhatsApp for Chat?
Ans. XMPP
4
28 Raj is working as a Sales promoter in XL corporation; He is right now in Sri Lanka, and
wants to address to some of his subordinates. Raj wants to have meeting in which they can
watch each other and also communicate with audio in real time. Identify the Protocol used
on

for this requirement.


Ans. Video Conferencing / H.323
20 H.323 is a identifier of __________________ Protocol
Ans. Video Conferencing
th

21 What is Wi-Fi? What unique protocol number is assigned to Wi-Fi?


Ans. Wireless Fidelity. Protocol number : 802.11x
22 What is the difference in Wi-Fi and Wi-Max
Ans. Wi-Fi : (i) used in LAN (ii) Area coverage is upto 100 meters
py

Wi-Max (i) used in MAN (ii) maximum area coverage is 90 KM


23 Case Study based questions
(A)

om
.c
(i) ip
Suggest the most suitable place (i.e. School/Center) to install the server of this
cs
university with suitable reason
(ii) Suggest an ideal layout for connecting these school/center for a wired connectivity
(iii) Which device will you suggest to be placed/installed in each of these school/center
to efficiently connect all the computers within these school/center?
(iv) The university is planning to connect its admission center in the closest big city,
4

which is more than 350 KM from the University. Which type of network out of LAN,
MAN, WAN will be formed? Justify your answer.
on

Ans (i) Admin Center (it holds maximum number of computer)

(ii) Admin Center


th

25 m 45 m
py

Technology School
Business School

Law School
60 m

(iii) Switch
(iv) WAN (distance is more than 50 km which is higest area coverage of MAN to transfer data)
(B) Ravya industries has setup its new center at kakadeo nagar for its office and web based
activities. The company compound has 4 buildings as shown in the diagram below :

om
.c
(i)

(ii)
(iii) ip
Suggest the most suitable place (i.e. School/Center) to install the server of this
university with suitable reason
Suggest an ideal layout for connecting these school/center for a wired connectivity
Suggest the placement of following devices with suitable reason:
cs
(a) Internet Connecting Device/ Model
(b) Switch
(iv) The organization is planning to link its sale counter situated in various parts of the
same city, which type of network out of LAN, MAN or WAN will be formed? Justify
4
your answer
(C) Arogya Training Education Institute is setting up its centre in Kanpur with four specialized
departments for Orthopedics, Neurology and Pediatrics along with an administrative office in
on

separate buildings. The physical distances between theses department buildings and the
number of computers to be installed in these department and administrative office are given
as follows. You, as a network expert, have to answer the queries as raised by them in (i) to
(iv)
Shortest distance between various locations in meters:
th

Administrative Office to Orthopedics Unit 55


Neurology Unit to Administrative Office 30
Orthopedics Unit to Neurology Unit 70
py

Pediatrics Unit to Neurology Unit 50


Pediatrics Unit to Administrative Office 40
Pediatrics Unit to Orthopedics Unit 110

Number of computers installed at various locations are as follows:


Pediatrics Unit 40
Administrative Office 140
Neurology 50
Orthopedics 80
(i) Suggest the most suitable location to install the main server of this institution to
get efficiently connectivity.

om
(ii) Suggest the best cable layout for effective network connectivity of the building
having server with all the other buildings
(iii) Suggest the devices to be installed in each of these buildings for connecting
computers install within the building out of the following:
 Gateway
 Model
 Switch

.c
(iv) Suggest the topology of the network and network cable for efficiently connecting
each computer installed in each of the buildings out of the following:
Topologies : Bus Topology, Star Topology

Ans. (i)
ip
Network Cable : Single Pair Telephone Cable, Coaxial Cable, Ethernet Cable
Administrative office (maximum number of computer here)
cs
(ii)
4
55m 40m
on

30m
th
py

(iii) Switch
(iv) Star / Ethernet cable
WORKSHEET
NETWORK SECURITY, WEB SERVICE AND EPAYMENT
1 Virus that fool a user into downloading and /or executing them by pretending to be useful
applications are also sometimes called
a. Crackers
b. Key loggers
c. Trojan Horse
d. Worm
Ans. Trojan Horse
2 __________ are often delivered to a PC through an email attachment & are often designed to do
harm
a. Email messages
b. Virus

om
c. Spam
d. Portals
Ans. Virus
3 What is the most common way to get a virus in your computer „s hard disk
a. By opening emails
b. By uploading pictures from mobile to PC

.c
c. By installing games from CD-ROM
d. None of the above
Ans. By opening emails
4

ip
_________ is the action of recording the keys struck on a keyboard, typically covertly, so that
the person using the keyboard is unaware that their actions are being monitored
a. Spamming
cs
b. Key logging
c. Denial of Service
d. Exploits
Ans. Key logging
5 What is the software called which when get downloaded on computer scans your hard drive for
4

personal information and your internet browsing habits?


a. Malware
on

b. Antiware
c. Backdoors
d. Spyware
Ans. Spyware
6 Which type of Virus replicates itself and eats your entire disk space or network bandwidth?
th

a. Trojan Horse
b. Adware
c. Worm
d. Spamming
py

Ans. WORM
7 Which of the following is a type of program that either pretends to have, or is described as
having, a set of useful or desirable features but actually contains damaging code.
a. Trojans
b. Viruses
c. Worm
d. Adware
Ans. Trojans
8 Which of the following is a program capable of continually replicating but requires user
intervention
a. Trojans
b. Virus
c. Worm
d. Adware
Ans. Virus
9 Which of the following is software that, once installed on your computer, tracks your internet
browsing habits and sends you popups containing advertisements related to the sites and
topics you‟ve visited?
a. Trojans
b. Adware
c. Spam
d. Virus
Ans. Adware
10 Unwanted commercial email is known as ___________
a. Malware
b. Virus

om
c. Spam
d. Adware
Ans. Spam
11 What is the difference in Virus and Worm?
Ans. VIRUS WORK
They are designed to damage files, corrupt They do not damage the files

.c
OS files and cause annoying effects
It requires user intervention to replicate It replicate itself without user intervention

12

ip
What is Trojan? Any two type of activities performed by Trojan
Ans. Is a program that appears harmless (such as text editor or a utility program) but actually
performs malicious functions such as deleting or damaging files.
cs
Activities performed by Trojans:
• Data theft
• Installation of unwanted softwares
• Keystroke logging
• Downloading or uploading of files, etc.
4

13 _________ is a small text file created by web server on client computer to store user preferences,
user name, session information etc.
on

Ans. Cookies
14 Raj, an executive in a multinational company, one day when he logged in to check emails he
found lots of commercial promotional emails are there and he is not able to track the useful
mails and it is taking too much of time also his time killed in deleting those mails. What kind
of attack Raj is facing?
th

a. Adware
b. Spam
c. Trojan
py

d. Virus
Ans. Spam
15 What are the 2 main security concerns with Cookie?
Ans. 1) Session Data (Chance of hacking of username and password)
2) Tracking information
16 ________ is a software/hardware of combination of both is used to block unauthorized access
and allows only authorized user allowed by administrator.
Ans Firewall
17 HTTPS is abbreviated as _________
Ans. Hypertext Transfer protocol Secure (SSL – Secure Socket Layer)
18 Users are able to see a pad-lock icon in the address bar of the browser when there is _______
connection.
a. HTTP
b. HTTPS
c. SMTP
d. FTP
Ans. HTTPS
19 Raj a web developer working on online payment screen. Requirement of Client is that the
confidential information entered by the customer should be transfer securely over the network.
What kind of network security protocol used by Raj to achieve this task?
a. HTTP
b. FTP
c. HTTPS
d. FTP
Ans. HTTPS
20 Which types of network security protocol ensure data is transferred in encrypted form to keep
it secure from eavesdropper and cannot be stolen?

om
a. HTTPS
b. TCP/IP
c. SMTP
d. PPP
Ans. HTTPS
21 When IT Act 2000 came into effect in India?

.c
a. October 17, 2001
b. October 17, 2000
c. November 11, 2001
d. November 11, 2000
Ans.
22
October 17, 2000
How many schedules are there in IT Act 2000
a. 1 ip
cs
b. 2
c. 3
d. 4
Ans. 4
4
23 Which is the Act which provides legal framework for e-Governance in India?
a. IT(amendment) Act 2008
b. IPC
on

c. IT Act 2000
d. None of the above
Ans. IT Act 2000
24 What is/are component of IT Act 2000?
a. Legal recognition to Digital Signatures
th

b. Regulation of Certification Authorities


c. Digital Certificates
d. All of the above
py

Ans. All of the above


25
Major amendments to IT Act 2000 was introduced in the form of IT (amendment) Act 2008,
which came into effect on
a. October 2008
b. October 2009
c. October 2010
d. November 2009
Ans.
October 2009
26 Which Act in India focuses on data privacy and information technology?
a. Banking regulation Act 2009
b. IT Act 2000
c. IT(amendment) 2008
d. IPC
Ans IT Act 2000
27 Which section of IT Act 2000 deals with the Child pornography?
a. 67 A b. 67 B c. 67 C d. 70
Ans 67B
28 What is Cybercrime? Give example of any 2 types of Cybercrime
Ans. Cybercrime: Is any criminal offense that is facilitated by, or involves use of electronic
communications of information system including any electronic device, computer or the
Internet.
Example of Cybercrime:
1) CYBER TROLLS AND BULLYING
2) CYBER BULLYING
3) CYBER STALKING, etc.

om
29 Raj is a social worker, one day he noticed someone is writing, insulting or demeaning
comments on his post. What kind of Cybercrime Raj is facing?
Ans. Cyber Bullying.
30 When a person is harassed repeatedly by being followed, called or be written to he/she is a
victim of
a. Bullying

.c
b. Identify Theft
c. Stalking
d. Phishing
Ans. Stalking
31
Ans.
32
Local Police Station
Expand the term IPR ip
When any cybercrime happed with you, whom will you approach first?
cs
Ans. Intellectual Property Rights
33 What is Intellectual Property Rights? What are the two categories of IPR issues?
Ans. IPR refers to something owner has legal rights. Intellectual Property refers to creations of the
intellect, inventions, literacy and artistic work, symbols, names, image and design used in
4
commerce are part of it.
Two Categories of IPR:
1) INDUSTRIAL PROPERTY
on

2) COPYRIGHT
34 What is the difference between Hacking and Cracking?
Ans. Hacking: Process to gain access to systems with a view to fix the identified weakness. They
may also perform penetration testing and vulnerability assessments.
Cracking: Refers to gain unauthorized access to computer systems for personal gain. The
th

intent is usually to steal corporate data, violate privacy rights, transfer funds from bank
accounts etc.
35 Explain the term WWW? When it was invented?
py

.
36 What is the difference between HTML and XML?

37 What is Domain name? give example of any domain name

38 Out of the following, which is not a Web Browser?


a. Chrome b. Firefox c. Google Drive d. Opera
39 What is Web Servers?
40 Give any 2 languages which are under
(i) Client Side Scripting (ii) Server Side Scripting
41 Expand the terms: ASP, JSP, PHP
42 Give any 2 features of Web 2.0?
43 What is E-Commerce Payment? What are the different methods available for E-Commerce
payment (Any Two)?
44 What information is required for Payment from Credit Card?
45 What is UPI? Give the name of Indian government UPI?
46 Give name of any 2 popular payment wallets?
47 Payment by “Cash on Delivery” is also an example of E-commerce payment (True/False)
48 What is CVV on Debit card and CVN on Credit card?
49 Give the name of any 2 website built on Web 2.0
50 Raj a web designer creating website for any organization. After completion he will upload this
website on Internet. The process by which Raj will upload website on Internet so that any one
can access from anywhere is known as ______________

om
.c
ip
4 cs
on
th
py

You might also like