0% found this document useful (0 votes)
81 views74 pages

Cs Mat 1

The document outlines the syllabus for Class XII Computer Science (083) for the session 2022-2023 at Kendriya Vidyalaya Sangathan, Ahmedabad Region. It includes a detailed breakdown of units, topics to be covered month-wise, and distribution of marks for theory and practical assessments. Additionally, it provides guidelines for practical work and various programming exercises related to Python and SQL.

Uploaded by

psdspace007
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)
81 views74 pages

Cs Mat 1

The document outlines the syllabus for Class XII Computer Science (083) for the session 2022-2023 at Kendriya Vidyalaya Sangathan, Ahmedabad Region. It includes a detailed breakdown of units, topics to be covered month-wise, and distribution of marks for theory and practical assessments. Additionally, it provides guidelines for practical work and various programming exercises related to Python and SQL.

Uploaded by

psdspace007
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/ 74

कें द्रीय विद्यालय क्षेत्रीय कायाालय अहमदाबाद

OUR PATRON
Kendriya Vidyalaya Sangathan Regional Office, Ahmedabad

SMT SHRUTI BHARGAV


Deputy Commissioner,
KVS RO Ahmedabad

CLASS XII

Computer Science(083)
SMT VINITA SHARMA
Based on Latest CBSE Exam Pattern Assistant Commissioner,
KVS RO Ahmedabad
Session 2022-2023
KENDRIYA VIDYALAYA SANGATHAN, AHMEDABAD REGION

SUBJECT CO-ORDINATION BY TERM WISE SPLIT-UP SYLLABUS


SUB: COMPUTER SCIENCE (083)
CLASS - XII (NEW SYLLABUS)
(SESSION 2022 - 23)
DISTRIBUTION OF MARKS
UNIT UNIT NAME THEORY PERIODS
MARKS THEORY PRACTICAL
1 Computational Thinking and 40 70 50
SMT SUNITA GUPTA Programming -2
2 Computer Network 10 15 --
Principal, KV No 1 AFS Jamnagar 3 Data Management 20 25 20
TOTAL 70 110 70

MONTH- WISE DISTRIBUTION


Month Topics to be covered Th. Pr.
CONTENT TEAM Unit I: Computational Thinking and Programming - 2
25 20

• Revision of Python topics covered in Class XI.


• Functions: types of function (built-in functions, functions defined in module, user

April
SMT RAKHI JAIN PGT COMP KV NO.1, AFS, JAMANGAR defined functions), creating user defined function, arguments and parameters,
SH SATISH MAMNANI PGT COMP KV AFS , SAMANA default parameters, positional parameters,
• function returning value(s), flow of execution, scope of a variable (global scope,
SMT RENU BAHETI PGT COMP KV SAC, AHMEDABAD local scope)
SMT SONIA CHOUDHARY PGT COMP KV NO.2 AHMEDABAD CANTT
• Introduction to files, types of files (Text file, Binary file, CSV file), relative and 10 5

May-
June
SH RAHUL AWASTHI PGT COMP KV JUNAGADH absolute paths

SH DHIREN K MESHVANIYA PGT COMP KV JETPUR


• Text file: opening a text file, text file open modes (r, r+, w, w+, a, a+), closing a 20 15
textfile, 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

July
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
csv.writerow() and read from a csv file using csv.reader( )

• Data Structure: Stack, operations on stack (push & pop), implementation of stack using 15 10
August

list.
Septe
mber

• Test (Syllabus covered above)


Unit III: Database Management 10 10
• Database concepts: introduction to database concepts and its need GUIDELINES FOR PRACTICAL
• Relational data model: relation, attribute, tuple, domain, degree, cardinality, keys WORK
(candidate key, primary key, alternate key, foreign key) Structured Query Language: COMPUTER SCIENCE
introduction, Data Definition Language and Data Manipulation Language, data type
(char(n), varchar(n), int, float, date), constraints (not null, unique, primary key), (083) CLASS - XII
create database, use database, show databases, drop database, show tables, create
table, describe table, alter table (add and remove an attribute, add and remove S.No Marks Term-1 Term-2
primary key), drop table, insert, delete,update (Total 30) (15 Marks) (15 Marks)
1 Lab Test: 8 6 2
1. Python program
• select, operators (mathematical, relational and logical), aliasing, distinct clause, where 15 10
clause, in, between, order by, meaning of null, is null, is not null, like, update 2. 3 SQL Queries based on one/two table(s), 2 output 4 --- 4
command, delete command, aggregate functions (max, min, avg, sum, count), group questions based on SQL queries
2 Report file: 7 4 3
October

by, having clause, joins: cartesian product on two tables, equi-join and
natural join Minimum 15 Python programs based on Term - 1Syllabus
• Interface of python with an SQL database: connecting SQL with Python, performing SQL Queries – Minimum 5 sets using one table / twotables.
insert, update, delete queries using cursor, display data by using fetchone(), fetchall(), Minimum 2 programs based on Python - SQLconnectivity.
rowcount, creating database connectivity applications
3 Project (using concepts learnt in Classes 11 and 12) : 8 3 5
• Evolution of networking: introduction to computer networks, evolution ofnetworking 15 0
Coding + Viva voce
(ARPANET, NSFNET, INTERNET)
• Data communication terminologies: concept of communication, components of data 4 Viva voce 3 2 1
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 1. Suggested Practical List:
cable, Fiber-optic cable), Wireless media (Radio waves, Micro waves, Infrared Python Programming
waves)
November

● Read a text file line by line and display each word separated by a #.
• Network devices (Modem, Ethernet card, RJ45, Repeater, Hub, Switch, Router, ● Read a text file and display the number of vowels/consonants/uppercase/lowercase
Gateway, WIFI card)
charactersin the file.
• Network topologies and Network types: types of networks (PAN, LAN, MAN, WAN),
networking topologies (Bus, Star, Tree) ● Remove all the lines that contain the character 'a' in a file and write it to another file.
• Network protocol: HTTP, FTP, PPP, SMTP, TCP/IP, POP3, HTTPS, TELNET, VoIP, ● Create a binary file with name and roll number. Search for a given roll number and
wireless/mobile communication protocol such as GSM, GPRS and WLL display thename, if not found display appropriate message.
• Mobile telecommunication technologies: 1G, 2G, 3G, 4G and 5G ● Create a binary file with roll number, name and marks. Input a roll number and update the
Introduction to web services: WWW, Hyper Text Markup Language (HTML), Extensible marks.
Markup Language (XML), domain names, URL, website, web browser,web servers, web ● Write a random number generator that generates random numbers between 1 and 6
hosting (simulatesa dice).
• Revision, Project Work
● Create a CSV file by entering user-id and password, read and search the password for
given user-id.
ember

Pre Board Exam


Dec

● Write a Python program to implement a stack using list.

Revision and practical Exam -


February

Database Management
January

● Create a student table and insert data. Implement the following SQL commands on the
studenttable:
CBSE BOARD EXAM 2022-23 o ALTER table to add new attributes / modify data type / drop attribute
March
o UPDATE table to modify data
o ORDER By to display data in ascending / descending order
o DELETE to remove tuple(s)

6
o GROUP BY and find the min, max, sum, count and average Unit I: Computational Thinking and Programming - 2
Revision of Python topics covered in Class XI
o Joining of two tables.
Python tokens :
● Similar exercise may be framed for other cases. (1) keyword :
● Integrate SQL with Python by importing suitable module. Keywords are reserved words. Each keyword has a specific meaning to the Python
interpreter, and we can use a keyword in our program only for the purpose for which
● Similar exercise may be framed for other cases. it has been defined. As Python is case sensitive, keywords must be written exactly.
● Integrate SQL with Python by importing suitable module.
(2) Identifier :
Identifiers are names used to identify a variable, function, or other entities in a
program.
The rules for naming an identifier in Python are as follows:
• The name should begin with an uppercase or a lowercase alphabet or an underscore
sign (_). This may be followed by any combination of characters a–z, A–Z, 0–9 or
underscore (_). Thus, an identifier cannot start with a digit.
• It can be of any length. (However, it is preferred to keep it short and meaningful).
• It should not be a keyword or reserved word
• We cannot use special symbols like !, @, #, $, %, etc., in identifiers.

Variables:
A variable in a program is uniquely identified by a name (identifier). Variable in
Python refers to an object — an item or element that is stored in the memory.

Comments:
Comments are used to add a remark or a note in the source code. Comments are not
executed by interpreter. a comment starts with # (hash sign). Everything following
the # till the end of that line is treated as a comment and the interpreter simply
ignores it while executing the statement.

Mutable and immutable data types :


Variables whose values can be changed after they are created and assigned are called
mutable. Variables whose values cannot be changed after they are created and
assigned are called immutable.

● Operators:
An operator is used to perform specific mathematical or logical operation on values.
The values that the operators work on are called operands.

7 8
Arithmetic operators :four basic arithmetic operations as well as modular division, Introduction :
floor division and exponentiation. (+, -, *, /) and (%, //, **) String is a sequence which is made up of one or more UNICODE characters. Here the
character can be a letter, digit, whitespace or any other symbol. A string can be
Relational operators : created by enclosing one or more characters in single, double or triple quote.
Relational operator compares the values of the operands on its either side and >>> str1 = 'Hello World!'
determines the relationship among them. ==, != , > , < , <=, , >= >>> str2 = "Hello World!"
>>> str3 = """Hello World!"""
Logical operators : >>> str4 = '''Hello World!''
There are three logical operators supported by Python. These operators (and, or, not)
are to be written in lower case only. The logical operator evaluates to either True or Indexing :
False based on the logical operands on either side. and , or , not Each individual character in a string can be accessed using a technique called
indexing. The index specifies the character to be accessed in the string and is written
Assignment operator : in square brackets ([ ]). The index of the first character (from left) in the string is 0
Assignment operator assigns or changes the value of the variable on its left. a=1+2 and the last character is n-1 where n is the length of the string.
Augmented assignment operators :
+= , -= , /= *= , //= %= , **=

Identity operators : is, is not :


Membership operators : in, not in

● Expressions : String operations :


An expression is defined as a combination of constants, variables, and operators. An (i) Concatenation:
expression always evaluates to a value. A value or a standalone variable is also To concatenate means to join. Python allows us to join two strings using
considered as an expression but a standalone operator is not an expression. concatenation operator plus which is denoted by symbol +.

(i) 100 (iv) 3.0 + 3.14 >>> str1 = 'Hello' #First string
(ii) num (v) 23/3 -5 * 7(14 -2) >>> str2 = 'World!' #Second string
(iii) num – 20.4 (vi) "Global" + "Citizen" >>> str1 + str2 #Concatenated strings
'HelloWorld!'
SUMMARY
The if statement is used for selection or decision making. (ii) Repetition :
• The looping constructs while and for allow sections of code to be executed Python allows us to repeat the given string using repetition operator, which is
repeatedly under some condition. denoted by symbol *.
• for statement iterates over a range of values or a sequence. #assign string 'Hello' to str1
• The statements within the body of for loop are executed till the range of values is >>> str1 = 'Hello'
exhausted. #repeat the value of str1 2 times
• The statements within the body of a while are executed over and over until the >>> str1 * 2
condition of the while is false. 'HelloHello'
• If the condition of the while loop is initially false, the body is not executed even
once. (iii) Membership :
• The statements within the body of the while loop must ensure that the condition Python has two membership operators 'in' and 'not in'. The 'in' operator takes two
eventually becomes false; otherwise, the loop will become an infinite loop, leading to strings and returns True if the first string appears as a substring in the second
a logical error in the program. string, otherwise it returns False.
• The break statement immediately exits a loop, skipping the rest of the loop’s body. >>> str1 = 'Hello World!'
Execution continues >>> 'W' in str1
with the statement immediately following the body of the loop. When a continue True
statement is encountered, the control jumps to the beginning of the loop for the next >>> 'Wor' not in str1
iteration. False
• A loop contained within another loop is called a nested loop.
(iv) Slicing :
In Python, to access some part of a string or substring, we use a method called
● STRINGS:
9 10
slicing. This can be done by specifying an index range. Given a string str1, the slice
operation str1[n:m] returns the part of the string str1 starting from index n
(inclusive) and ending at m (exclusive). In other words, we can say that str1[n:m]
returns all the characters starting from str1[n] till str1[m-1]. The numbers of
characters in the substring will always be equal to difference of two indices m and n,
i.e., (m-n).
>>> str1 = 'Hello World!'
#gives substring starting from index 1 to 4
>>> str1[1:5]
'ello'
#gives substring starting from 7 to 9
>>> str1[7:10]
'orl'
#index that is too big is truncated down to
#the end of the string
>>> str1[3:20]
'lo World!'
#first index > second index results in an
#empty '' string
>>> str1[7:2]

(v) Traversing a string using loops :


We can access each character of a string or traverse a string using for loop and
while loop.
(A) String Traversal Using for Loop:
>>> str1 = 'Hello World!'
>>> for ch in str1:
print(ch, end = '')
Hello World! #output of for loop
In the above code, the loop starts from the first character of the string str1 and
automatically ends when the last character is accessed.
(B) String Traversal Using while Loop:
>>> str1 = 'Hello World!'
>>> index = 0
#len(): a function to get length of string
>>> while index < len(str1):
print(str1[index],end = '')
index += 1
Hello World! #output of while loop
Here while loop runs till the condition index < len(str) is True, where index varies
from 0 to len(str1) -1.

(vi) built-in functions:


len(), capitalize(), title(), lower(), upper(), count(), find(), index(), endswith(),
startswith(), isalnum(), isalpha(), isdigit(), islower(), isupper(), isspace(),
lstrip(), rstrip(), strip(), replace(), join(), partition(), split() :

11 12
13 14
Repetition
SUMMARY Python allows us to replicate a list using repetition
A string is a sequence of characters enclosed in single, double or triple quotes. operator depicted by symbol *.
• Indexing is used for accessing individual characters within a string.
• The first character has the index 0 and the last character has the index n-1 where >>> list1 = ['Hello']
n is the length #elements of list1 repeated 4 times
of the string. The negative indexing ranges from -n to -1. >>> list1 * 4
• Strings in Python are immutable, i.e., a string cannot be changed after it is created. ['Hello', 'Hello', 'Hello', 'Hello']
• Membership operator in takes two strings and returns True if the first string appears
as a substring in the second else returns False. Membership operator ‘not in’ does Membership
the reverse. Like strings, the membership operators in checks if the element is present in the list
• Retrieving a portion of a string is called slicing. This can be done by specifying an and returns True, else returns False.
index range.
The slice operation str1[n:m] returns the part of the string str1 starting from index >>> list1 = ['Red','Green','Blue']
n (inclusive) and ending at m (exclusive). >>> 'Green' in list1
• Each character of a string can be accessed either using a for loop or while loop. True
• There are many built-in functions for working with strings in Python. >>> 'Cyan' in list1
False
● Lists:
Introduction: Slicing
The data type list is an ordered sequence which is mutable and made up of one or Like strings, the slicing operation can also be applied to lists.
more elements. Unlike a string which consists of only characters, a list can have
elements of different data types, such as integer, float, string, tuple or even another >>> list1 =['Red','Green','Blue','Cyan',
list. A list is very useful to group together elements of mixed data types. Elements of 'Magenta','Yellow','Black']
a list are enclosed in square brackets and are separated by comma. Like string
indices, list indices also start from 0. >>> list1[2:6]
['Blue', 'Cyan', 'Magenta', 'Yellow']
Indexing :
The elements of a list are accessed in the same way as characters are accessed in a
string. Traversing a list using loops:
List operations (concatenation, repetition, membership & slicing) : We can access each element of the list or traverse a list using a for loop or a while
loop.
Concatenation
Python allows us to join two or more lists using concatenation operator depicted by (A) List Traversal Using for Loop:
the symbol +. >>> list1 = ['Red','Green','Blue','Yellow', 'Black']
>>> for item in list1:
#list1 is list of first five odd integers print(item)
>>> list1 = [1,3,5,7,9]
#list2 is list of first five even integers Output:
>>> list2 = [2,4,6,8,10] Red
Green
#elements of list1 followed by list2 Blue
>>> list1 + list2 Yellow
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10] Black

>>> list3 = ['Red','Green','Blue']


>>> list4 = ['Cyan', 'Magenta', 'Yellow' ,'Black']
>>> list3 + list4
['Red','Green','Blue','Cyan','Magenta', 'Yellow','Black']

built-in functions:
15 16
SUMMARY

Lists are mutable sequences in Python, i.e., we can change the elements of the list.
• Elements of a list are put in square brackets separated by comma.
• A list within a list is called a nested list. List indexing is same as that of strings and
starts at
0. Two way indexing allows traversing the list in the forward as well as in the
backward direction.
• Operator + concatenates one list to the end of other list.
• Operator * repeats a list by specified number of times.
• Membership operator in tells if an element is present in the list or not and not in
does the opposite.
• Slicing is used to extract a part of the list.
• There are many list manipulation functions
including: len(), list(), append(), extend(), insert(),
count(), find(), remove(), pop(), reverse(), sort(),
sorted(), min(), max(), sum().

17 18
●Tuples: Built-in functions:
Introduction :
A tuple is an ordered sequence of elements of different data types, such as integer,
float, string, list or even a tuple. Elements of a tuple are enclosed in parenthesis len(), tuple(), count(), index(), sorted(), min(), max(), sum()
(round brackets) and are separated by commas. Like list and string, elements of a
tuple can be accessed using index values, starting from 0 Method Description Example
len() Returns the length or the number >>>tuple1 = (10,20,30,40,50)
ofelements of the tuple passed as >>> len(tuple1)
Indexing : theargument 5
Elements of a tuple can be accessed in the same way as a list or string using indexing
and slicing. tuple() Creates an empty tuple if no argumentis >>> tuple1 = tuple()
passed >>> tuple1( )
Tuple is Immutable : Creates a tuple if a sequence is >>> tuple1 = tuple('aeiou')#string
passed as argument >>> tuple1
Tuple is an immutable data type. It means that the elements of a tuple cannot be
('a', 'e', 'i', 'o', 'u')
changed after it has been created. An attempt to do this would lead to an error. >>> tuple2 = tuple([1,2,3]) #list
>>> tuple1 = (1,2,3,4,5) >>> tuple2
>>> tuple1[4] = 10 (1, 2, 3)
TypeError: 'tuple' object does not support item assignment >>> tuple3 = tuple(range(5))
>>> tuple3
(0, 1, 2, 3, 4)
Tuple operations : count() Returns the number of times the >>>tuple1=(10,20,30,10,40,10,50)
Concatenation given element appears in the tuple >>> tuple1.count(10)
Python allows us to join tuples using concatenation operator depicted by symbol +. 3
We can also create a new tuple which contains the result of this concatenation >>> tuple1.count(90)
0
operation.
index() Returns the index of the first >>> tuple1 = (10,20,30,40,50)
occurrence of the element in the >>> tuple1.index(30)
>>> tuple1 = (1,3,5,7,9) given tuple 2
>>> tuple2 = (2,4,6,8,10) >>> tuple1.index(90)
>>> tuple1 + tuple2 ValueError: tuple.index(x): x not
#concatenates two tuples in tuple
sorted() Takes elements in the tuple and >>>tuple1=("Rama","Heena","Raj",
(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)
returns a new sorted list. It should "Mohsin","Aditya")
be noted that, sorted() does not make >>> sorted(tuple1)
Repetition any change to the original tuple ['Aditya', 'Heena', 'Mohsin', 'Raj',
Repetition operation is depicted by the symbol *. It is used to repeat elements of a 'Rama']
tuple. We can repeat the tuple elements. The repetition operator requires the first min() Returns minimum or smallest >>>tuple1 = (19,12,56,18,9,87,34)
element of the tuple >>> min(tuple1)
operand to be a tuple and the second operand to be an integer only. max() Returns maximum or largest element 9
>>> tuple1 = ('Hello','World') of the tuple >>> max(tuple1)
>>> tuple1 * 3 sum() Returns sum of the elements of the 87
('Hello', 'World', 'Hello', 'World', 'Hello', 'World') tuple >>> sum(tuple1)
235
Membership
The in operator checks if the element is present in the
● Dictionary:
tuple and returns True, else it returns False.
>>> tuple1 = ('Red','Green','Blue') Introduction :
>>> 'Green' in tuple1 The data type dictionary fall under mapping. It is a mapping between a set of keys
True and a set of values. The key-value pair is called an item. A key is separated from its
value by a colon(:) and consecutive items are separated by commas. Items in
Slicing dictionaries are unordered, so we may not get back the data in the same order in
Like string and list, slicing can be applied to tuples also. which we had entered the data initially in the dictionary.
#tuple1 is a tuple
>>> tuple1 = (10,20,30,40,50,60,70,80) Creating a Dictionary
To create a dictionary, the items entered are separated by commas and enclosed in
curly braces. Each item is a key value pair, separated through colon (:). The keys in
the dictionary must be unique and should be of any immutable data type, i.e.,
number, string or tuple. The values can be repeated and can be of any data type.
19 20
#dict1 is an empty Dictionary created Traversing a dictionary :
#curly braces are used for dictionary We can access each item of the dictionary or traverse a dictionary using for loop.
>>> dict1 = {} >>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
>>>{}
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85} Method 1
>>> dict3 >>> for key in dict1:
{'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85} print(key,':',dict1[key])
Mohan: 95
Accessing items in a dictionary using keys : Ram: 89
We have already seen that the items of a sequence (string, list and tuple) are Suhel: 92
accessed using a technique called indexing. The items of a dictionary are accessed Sangeeta: 85
via the keys rather than via their relative positions or indices. Each key serves as the
index and maps to a value. The following example shows how a dictionary returns Method 2
the value corresponding to the given key: >>> for key,value in dict1.items():
print(key,':',value)
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85} Mohan: 95
>>> dict3['Ram'] 89 Ram: 89
>>> dict3['Sangeeta'] 85 Suhel: 92
#the key does not exist Sangeeta: 85
>>> dict3['Shyam'] KeyError: 'Shyam'
Built-in functions: len(), dict(), keys(), values(), items(), get(), update(), del,
Mutability of dictionary (adding a new item, modifying an existing item) : clear(), fromkeys(), copy(), pop(), popitem(), setdefault(), max(), min(), count(),
Dictionaries are mutable which implies that the contents of the dictionary can be sorted(), copy();
changed after it has been created.
Method Description Example
Adding a new item
len() Returns the length or number >>> dict1 = {'Mohan':95,'Ram':89,
We can add a new item to the dictionary as shown in the following example:
of key: value pairs of the 'Suhel':92, 'Sangeeta':85}
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
dictionary passed as the >>> len(dict1)
>>> dict1['Meena'] = 78
argument 4
>>> dict1
dict() Creates a dictionary from a pair1 = [('Mohan',95),('Ram',89),
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,'Sangeeta': 85, 'Meena': 78}
sequence of key-value pairs ('Suhel',92),('Sangeeta',85)]
>>> pair1
Modifying an Existing Item [('Mohan', 95), ('Ram', 89), ('Suhel',
The existing dictionary can be modified by just overwriting the key-value pair. 92), ('Sangeeta', 85)]
Example to modify a given item in the dictionary: >>> dict1 = dict(pair1)
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85} >>> dict1
#Marks of Suhel changed to 93.5 {'Mohan':95, 'Ram':89,'Suhel':92,'Sangeeta':
85}
>>> dict1['Suhel'] = 93.5
keys() Returns a list of keys in >>> dict1 = {'Mohan':95, 'Ram':89,
>>> dict1
the dictionary 'Suhel':92, 'Sangeeta':85}
{'Mohan': 95, 'Ram': 89, 'Suhel': 93.5,'Sangeeta': 85}
>>> dict1.keys()
dict_keys(['Mohan', 'Ram', 'Suhel','Sangeeta'])
Membership
The membership operator in checks if the key is present in the dictionary and returns values() Returns a list of values in >>> dict1 = {'Mohan':95, 'Ram':89,
True, else it returns False. the dictionary 'Suhel':92, 'Sangeeta':85}
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85} >>> dict1.values()
>>> 'Suhel' in dict1 dict_values([95, 89, 92, 85])
True
items() Returns a list of tuples(key – >>> dict1 = {'Mohan':95, 'Ram':89,
The not in operator returns True if the key is not present in the dictionary, else it
value) pair 'Suhel':92, 'Sangeeta':85}
returns False.
>>> dict1.items()
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
dict_items([( 'Mohan', 95), ('Ram',
>>> 'Suhel' not in dict1
89), ('Suhel', 92), ('Sangeeta', 85)])
False
21 22
get() Returns the value >>> dict1 = {'Mohan':95, 'Ram':89, 1. Which of the following is valid arithmetic operator in Python: 1
corresponding to the key 'Suhel':92, 'Sangeeta':85} (i) // (ii) ? (iii) <(iv) and
passed as the argument >>> dict1.get('Sangeeta') 2. Write the type of tokens from the following: 1
If the key is not present in the 85
(i) if (ii) roll_no
dictionary it will return None >>> dict1.get('Sohan')
3. Name the Python Library modules which need to be imported to invoke 1
update() appends the key-value pair of >>> dict1 = {'Mohan':95, 'Ram':89,
the dictionary passed as the 'Suhel':92, 'Sangeeta':85} the following functions:
argument to the key-value >>> dict2 = {'Sohan':79,'Geeta':89} (i) sin( ) (ii) randint ( )
pair of the given dictionary >>> dict1.update(dict2) 4 What do you understand by the term Iteration? 1
>>> dict1 5 Which is the correct form of declaration of dictionary? 1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92, (i) Day={1:’monday’,2:’tuesday’,3:’wednesday’}
'Sangeeta': 85, 'Sohan': 79, 'Geeta':89}
(ii) Day=(1;’monday’,2;’tuesday’,3;’wednesday’)
>>> dict2{'Sohan': 79, 'Geeta': 89}
(iii) Day=[1:’monday’,2:’tuesday’,3:’wednesday’]
del() Deletes the item with the >>> dict1 = {'Mohan':95,'Ram':89,
given key To delete the 'Suhel':92, 'Sangeeta':85} (iv) Day={1’monday’,2’tuesday’,3’wednesday’]
dictionary from the memory >>> del dict1['Ram'] 6 Identify the valid declaration of L: 1
we write: >>> dict1 L = [1, 23, ‘hi’, 6].
del Dict_name {'Mohan':95,'Suhel':92, 'Sangeeta': 85} (i) list (ii) dictionary (iii) array (iv) tuple
>>> del dict1 ['Mohan'] 7 Find and write the output of the following python code: 1
>>> dict1{'Suhel': 92, 'Sangeeta': 85}
x = "abcdef"
>>> del dict1
>>> dict1NameError: name 'dict1' is not defined i = "a"
clear() Deletes or clear all the items >>> dict1 = {'Mohan':95,'Ram':89, while i in x:
of the dictionary 'Suhel':92, 'Sangeeta':85} print(i, end = " ")
>>> dict1.clear() 8 Find and write the output of the following python code: 1
>>> dict1 a=10
{} def call():
global a
SUMMARY a=15
b=20
Tuples are immutable sequences, i.e., we cannot change the elements of a tuple once print(a)
it is created. call()
• Elements of a tuple are put in round brackets separated by commas. 9 Find the valid identifier from the following 1
• If a sequence has comma separated elements without parentheses, it is also treated a) My-Name b) True c) 2ndName d) S_name
as a tuple.
• Tuples are ordered sequences as each element has a fixed position. 10 Given the lists L=[1,3,6,82,5,7,11,92] , 1
• Indexing is used to access the elements of the tuple; two way indexing holds in What will be the output of print(L[2:5])
dictionaries as in strings and lists.
11 Write the full form of IDLE. 1
• Operator ‘+’ adds one sequence (string, list, tuple) to the end of other.
• Operator ‘*’ repeats a sequence (string, list, tuple) by specified number of times 12 Identify the valid logical operator in Python from the following. 1
• Membership operator ‘in’ tells if an element is present in the sequence or not and a) ? b) < c) ** d) and
‘not in’ does the opposite.
• Tuple manipulation functions are: len(), tuple(), count(), index(), sorted(), min(), 13 Suppose a tuple Tup is declared as Tup = (12, 15, 63, 80), 1
max(),sum(). which of the following is incorrect?
• Dictionary is a mapping (non-scalar) data type. It is an unordered collection of key-
value pair; keyvalue pair are put inside curly braces. a) print(Tup[1])
• Each key is separated from its value by a colon. b) Tup[2] = 90
• Keys are unique and act as the index.
c) print(min(Tup))
• Keys are of immutable type but values can be mutable.
d) print(len(Tup))

MARKS QUESTIONS
23 24
14 Write a statement in Python to declare a dictionary whose keys are 1 (iii) 50#60#70# (iv) 40#50#70#
1,2,3 and values are Apple, Mango and Banana respectively. 4 What do you understand by local and global scope of variables? How can 2
you access a global variable inside the function, if function has a variable
15 A tuple is declared as T = (2,5,6,9,8) 1
with same name.
What will be the value of sum(T)? 5 Evaluate the following expressions: 2
16 Name the built-in mathematical function / method that is used to 1
return square root of a number. a) 8 * 3 + 2**3 // 9 – 4

17 If the following code is executed, what will be the output of the 1 b) 12 > 15 and 8 > 12 or not 19 > 4
following code? str="KendriyaVidyalayaSangathan"
6 Differentiate between call by value and call by reference with a suitable 2
print(str[8:16])
example for each.
18 Which of the following are valid operators in Python: (i) 1
** (ii) between (iii) like (iv) || 7 Rewrite the following code in Python after removing all syntax error(s). 2
19 Given the lists L=[“H”, “T”, “W”, “P”, “N”] , write the output of 1 Underline each correction done in the code.
print(L[3:4])
20 What will be the output of: print(10>20) 1 p=30
for c in range(0,p)
2 MARKS QUESTIONS If c%4==0:
1. Rewrite the following code in python after removing all syntax error(s). 2 print (c*4)
Underline each correction done in the code. Elseif c%5==0:
30=To print (c+3)
for K in range(0,To) else
IF k%4==0: print(c+10)
print (K*4) 8 What possible outputs(s) are expected to be displayed on screen at the 2
Else: time of execution of the program from the following code? Also specify the
print (K+3) maximum values that can be assigned to each of the variables Lower and
2. Find and write the output of the following python code: 2
Upper.
def fun(s):
k=len(s) import random
m=" " AR=[20,30,40,50,60,70];
for i in range(0,k): Lower =random.randint(1,4)
if(s[i].isupper()): Upper =random.randint(2,5)
m=m+s[i].lower() for K in range(Lower, Upper +1):
elif s[i].isalpha(): print (AR[K],end=”#“)
m=m+s[i].upper()
else: (i) 40# (ii) 40#50#60# (iii) 50# (iv) All of these
m=m+'bb'
print(m) 9 Evaluate the following expression. 2
a) 51+4-3**3//19-3
fun('school2@com') b) 17<19 or 30>18 and not 19==0
3. What possible outputs(s) are expected to be displayed on screen at the 2
time of execution of the program from the following code? Also specify the 10 What do you mean by keyword argument in python? Describe with 2
maximum values that can be assigned to each of the variables FROM and example.
TO.
import random 11 Rewrite the following code in python after removing all syntax errors. 2
AR=[20,30,40,50,60,70]; Underline each correction done in the code:
FROM=random.randint(1,3)
def func(a):
TO=random.randint(2,4)
for K in range(FROM,TO+1): for i in (0,a):
print (AR[K],end=”# “) if i%2 =0:

(i) 10#40#70# (ii) 30#40#50# s=s+1

25 26
else if i%5= =0 print (val*4)
m=m+2 Elseif val%5==0:
print (val+3)
else: Else
n=n+i print(val+10)
19 What possible outputs(s) are expected to be displayed on screen at the
print(s,m,n) time of execution of the program from the following code? Also specify the
maximum values that can be assigned to each of the variables Lower and
func(15) Upper.
12 What possible outputs(s) are expected to be displayed on screen at the 2
import random
time of execution of the program from the following code. Select which AR=[20,30,40,50,60,70];
option/s is/are correct Lower =random.randint(1,3)
Upper =random.randint(2,4)
import random for K in range(Lower, Upper +1):
print (AR[K],end=”#“)
print(random.randint(15,25) , end=' ')
print((100) + random.randint(15,25) , end = ' ' ) (i) 10#40#70# (ii) 30#40#50#
(iii) 50#60#70# (iv) 40#50#70#
print((100) -random.randint(15,25) , end = ' ' ) 20 def simple_interest(p, r, t):
print((100) *random.randint(15,25) ) return (p*r*t)/100
print (simple_interest(100,5,2))
(i) 15 122 84 2500
(ii) 21 120 76 1500 Identify the formal and actual parameters in the above code snippet.
Define formal and actual parameters in a function.
(iii) 105 107 105 1800
(iv) 110 105 105 1900 21 c = 10
(i ) (ii) are correct answers. def add():
global c
13 What is Constraint ? Give example of any two constraints. 2 c=c+2
14 Predict the output of the following code. 2 print("Inside add():", c)
def swap(P ,Q):
add()
P,Q=Q,P c=15
print("In main:", c)
print( P,"#",Q)
return (P) output:
R=100 Inside add() : 12
In main: 15
S=200
R=swap(R,S) Consider the above program and justify the output. What is the output if
print(R,"#",S) “global c “ is not written in the function add().
15 Evaluate the following expressions: 2
a) 6 * 3 + 4**2 // 5 – 8 22 Consider the following function headers. Identify the correct statement and
b) 10 > 5 and 7 > 12 or not 18 > 3 state reason
16 Differentiate between actual parameter(s) and a formal parameter(s) with 1) def correct(a=1,b=2,c):
a suitable example for each. 2) def correct(a=1,b,c=3):
17 Explain the use of global key word used in a function with the help of a 3) def correct(a=1,b=2,c=3):
suitable example. 4) def correct(a=1,b,c):
18 Rewrite the following code in Python after removing all syntax error(s).
Underline each correction done in the code. 23 What possible outputs(s) are expected to be displayed on screen at the
Value=30 time of execution of the program from the following code? Also specify the
for val in range(0,Value) maximum AND minimum values that can be assigned to the variable Num
If val%4==0: when P = 7
27 28
import random as r arr=[10,20,23,45]
val = 35 output : [10, 10, 115, 225]
P=7
Num = 0 4 Write a program in Python, which accepts a list Arr of numbers and n is a
for i in range(1, 5): numeric value by which all elements of the list are shifted to left.
Num = val + r.randint(0, P - 1)
Sample Input Data of the list :
print(Num, " $ ", end = "")
Arr= [ 10,20,30,40,12,11], n=2
P=P–1
Output :
Arr = [30,40,12,11,10,20]
(a) 41 $ 38 $ 38 $ 37 $
(b) 38 $ 40 $ 37 $ 34 $
5 Write a program to reverse elements in a list where arguments are start and 3
(c) 36 $ 35 $ 42 $ 37 $
end index of the list part which is to be reversed. Assume that start<end,
(d) 40 $ 37 $ 39 $ 35 $
start>=0 and end<len(list)
Sample Input Data of List :
24 Find the output of the following program;
my_list=[1,2,3,4,5,6,7,8,9,10]
def increment(n):
Output is
n.append([4])
my_list=[1,2,3,7,6,5,4,8,9,10]
return n
l=[1,2,3]
m=increment(l)
6 Write program to add those values in the list of NUMBERS, which are odd. 3
print(l,m)
Sample Input Data of the List
NUMBERS=[20,40,10,5,12,11]
25 Evaluate the following:
OUTPUT is 16
a. 45<89 and 7>12 or not 18>3
b. 6*3+2**4//5-2
7 Write a program to replaces elements having even values with its half and 3
3 MARKS QUESTIONS
elements having odd values with twice its value in a list.
1. Find and write the output of the following python code: 3 eg: if the list contains
def Change(P ,Q=30): 3, 4, 5, 16, 9
P=P+Q then rearranged list as
Q=P-Q 6, 2,10,8, 18
print( P,"#",Q)
return (P) 8 Write a Python program to find the maximum and minimum elements in the 3
list entered by the user.
R=150
S=100 9 Write a program in python to print b power p. 3
R=Change(R,S)
print(R,"#",S) 10 Write a program to print of fibonnaci series upto n. 3
S=Change(S)
2. Write a program in Python, which accepts a list Lst of numbers and n is a for example if n is 50 then output will be :
0
numeric value by which all elements of the list are shifted to left.
1
Sample Input Data of the list : 1
2
Lst= [ 10,20,30,40,12,11], n=2 3
5
Output Lst = [30,40,12,11,10,20] 8
13
3. Write a program in Python, which accepts a list Arr of numbers , the 21
function will replace the even number by value 10 and multiply odd 34

number by 5 .
Sample Input Data of the list is:

29 30
MARKING SCHEME What will be the output of
1 MARKS QUESTIONS
1. Which of the following is valid arithmetic operator in Python: 1 print(L[2:5])
(i) // (ii) ? (iii) <(iv) and Answer [6,82,5]
Answer (i) //
2. Write the type of tokens from the following: 1 11 Write the full form of IDLE. 1
(i) if (ii) roll_no
Answer (i) Key word (ii) Identifier Answer Integrated Development Learning Environment
(1/2 mark for each correct type)
3. Name the Python Library modules which need to be imported to 1 12 Identify the valid logical operator in Python from the following. 1
invoke the
a) ? b) < c) ** d) and
following functions:
(i) sin( ) (ii) randint ( ) Answer d) and
Answer (i) math (ii) random
(1/2 mark for each module) 13 Suppose a tuple Tup is declared as Tup = (12, 15, 63, 80), 1
4 What do you understand by the term Iteration? 1
which of the following is incorrect?
Answer Repeatation of statement/s finite number of times is known as
Iteration. a) print(Tup[1])
(1 mark for correct answer) b) Tup[2] = 90
5 Which is the correct form of declaration of dictionary? 1
(i) Day={1:’monday’,2:’tuesday’,3:’wednesday’} c) print(min(Tup))
(ii) Day=(1;’monday’,2;’tuesday’,3;’wednesday’) d) print(len(Tup))
(iii) Day=[1:’monday’,2:’tuesday’,3:’wednesday’] Answer b) Tup[2]=90
(iv) Day={1’monday’,2’tuesday’,3’wednesday’]
Answer (i) Day={1:’monday’,2:’tuesday’,3:’wednesday’} 14 Write a statement in Python to declare a dictionary whose keys are 1
6 Identify the valid declaration of L: 1 1,2,3 and values are Apple, Mango and Banana respectively.
L = [1, 23, ‘hi’, 6]. Answer Dict={1:’Apple’, 2: ’Mango’,3 : ‘Banana’}
(i) list (ii) dictionary (iii) array (iv) tuple
Answer (i) List 15 A tuple is declared as T = (2,5,6,9,8) 1
7 Find and write the output of the following python code: 1 What will be the value of sum(T)?
x = "abcdef"
i = "a" Answer 30
while i in x:
print(i, end = " ") 16 Name the built-in mathematical function / method that is used to 1
Answer aaaaaa----- OR infinite loop return square root of a number.
8 Find and write the output of the following python code: 1
Answer sqrt()
a=10
def call():
17 If the following code is executed, what will be the output of the 1
global a
following code? str="KendriyaVidyalayaSangathan"
a=15
b=20
print(str[8:16])
print(a)
call() Answer Vidyalay
Answer 15
9 Find the valid identifier from the following 1 18 Which of the following are valid operators in Python: 1

a) My-Name b) True c) 2ndName d) S_name (i) ** (ii) between (iii) like (iv) ||

Answer s) S_name Answer a) (I) and (iv)

10 Given the lists L=[1,3,6,82,5,7,11,92] , 1 19 Given the lists L=[“H”, “T”, “W”, “P”, “N”] , write the output of 1
print(L[3:4])
31 32
Answer [“N”] 4 What do you understand by local and global scope of variables? How 2
20 What will be the output of: 1 can you access a global variable inside the function, if function has
print(10>20) a variable with same name.
Answer False Answer A global variable is a variable that is accessible globally. A local
2 MARKS QUESTIONS variable is one that is only accessible to the current scope, such as
1. Rewrite the following code in python after removing all syntax 2 temporary variables used in a single function definition.
error(s). Underline each correction done in the code. A variable declared outside of the function or in global scope is
30=To known as global variable.
for K in range(0,To) This means, global variable can be accessed inside or outside of the
IF k%4==0: function where as local variable can be used only inside of the
print (K*4) function. We can access by declaring
Else: variable as global A.
print (K+3) 5 Evaluate the following expressions: 2
Answer To=30
a) 8 * 3 + 2**3 // 9 – 4
for K in range(0,To) :
if k%4==0: b) 12 > 15 and 8 > 12 or not 19 > 4
print (K*4) Answer a) 25
else:
print (K+3) b) False
(1/2 mark for each correction) 6 Differentiate between call by value and call by reference with a 2
2. Find and write the output of the following python code: 2 suitable example for each.
def fun(s):
k=len(s) Answer In the event that you pass arguments like whole numbers, strings
m=" " or tuples to a function, the passing is like call-by-value because you
for i in range(0,k): can not change the value of the immutable objects being passed to
if(s[i].isupper()): the function. Whereas passing mutable objects can be considered as
m=m+s[i].lower() call by reference because when their values are changed inside the
elif s[i].isalpha(): function, then it will also be reflected outside the function.
m=m+s[i].upper() 7 Rewrite the following code in Python after removing all syntax 2
else: error(s). Underline each correction done in the code.
m=m+'bb'
print(m) p=30
fun('school2@com')
for c in range(0,p)
Answer SCHOOLbbbbCOM
(2 marks for correct output) If c%4==0:
Note: Partial marking can also be given print (c*4)
3. What possible outputs(s) are expected to be displayed on screen at 2
Elseif c%5==0:
the time of execution of the program from the following code? Also
specify the maximum values that can be assigned to each of the print (c+3)
variables FROM and TO. else
import random print(c+10)
AR=[20,30,40,50,60,70]; Answer p=30
FROM=random.randint(1,3)
TO=random.randint(2,4) for c in range(0,p):
for K in range(FROM,TO+1): if c%4==0:
print (AR[K],end=”# “)
print (c*4)
(i) 10#40#70# (ii) 30#40#50# elif c%5==0:
(iii) 50#60#70# (iv) 40#50#70# print (c+3)
Answer (ii) 30#40#50# Maximum value FROM,TO is 3,4
(1/2 mark each for maximum value) else:
(1 mark for correct option)
33 34
print(c+10) Answer def func(a): #def
8 What possible outputs(s) are expected to be displayed on screen at 2 s=m=n=0 #local variable
the time of execution of the program from the following code? Also for i in (0,a): #indentation and frange function missing
specify the maximum values that can be assigned to each of the
variables Lower and Upper. if i%2==0:
s=s+I
import random
elif i%5==0: #elif and colon
AR=[20,30,40,50,60,70];
m=m+i
Lower =random.randint(1,4) else:

Upper =random.randint(2,5) n=n+i


print(s,m,n) #indentation
for K in range(Lower, Upper +1):
func(15) 2 marks for any four corrections.
print (AR[K],end=”#“)
12 What possible outputs(s) are expected to be displayed on screen 2
(i) 40# (ii) 40#50#60# (iii) 50# (iv) All of these at the time of execution of the program from the following code.
Answer (iv) All of these Select which option/s is/are correct
import random
9 Evaluate the following expression. 2
a) 51+4-3**3//19-3 print(random.randint(15,25) , end=' ')
b) 17<19 or 30>18 and not 19==0
print((100) + random.randint(15,25) , end = ' ' )
Answer 51 print((100) -random.randint(15,25) , end = ' ' )
True print((100) *random.randint(15,25) )
10 What do you mean by keyword argument in python? Describe 2 (i) 15 122 84 2500
with example. (ii) 21 120 76 1500
Answer When you assign a value to the parameter (such as param=value)
(iii) 105 107 105 1800
and pass to the function (like fn(param=value)), then it turns into (iv) 110 105 105 1900
a keyword argument. Answer (i ) (ii) are correct answers.
11 Rewrite the following code in python after removing all 2 13 What is Constraint ? Give example of any two constraints. 2
Answer Constraints are the checking condition which we apply on table to
syntax errors. Underline each correction done in the code:
Def func(a): ensure the correctness of data . example primary key, nut null,

for i in (0,a): default, unique etc

if i%2 =0: 14 Predict the output of the following code. 2


s=s+1 def swap(P ,Q):
else if i%5= =0 P,Q=Q,P
m=m+2 print( P,"#",Q)
else: return (P)
n=n+i R=100
print(s,m,n) S=200
func(15)
R=swap(R,S)

35 36
print(R,"#",S) output:
Inside add() : 12
Answer
200 # 100 In main: 15
200 # 200
15 Evaluate the following expressions: 2
18 Rewrite the following code in Python after removing all syntax
a) 6 * 3 + 4**2 // 5 – 8 error(s).
b) 10 > 5 and 7 > 12 or not 18 > 3
Answer a) 13 Underline each correction done in the code.
b) False Value=30
16 Differentiate between actual parameter(s) and a formal for val in range(0,Value)
parameter(s) with a suitable example for each. If val%4==0:
Answer The list of identifiers used in a function call is called actual
print (val*4)
parameter(s) whereas the list of parameters used in the function
Elseif val%5==0:
definition is called formal parameter(s).
print (val+3)
Actual parameter may be value / variable or expression.
Else
Formal parameter is an identifier.
print(val+10)
Example:
Answer Value=30
def area(side):
for VAL in range(0,Value) :
# line 1
if val%4==0:
return side*side;
print (VAL*4)
print(area(5))
elif val%5==0:
# line 2
print (VAL+3)
In line 1, side is the formal parameter and in line 2, while invoking
else:
area() function, the value 5 is the actual parameter. print(VAL+10
formal parameter, i.e. a parameter, is in the function 19 What possible outputs(s) are expected to be displayed on screen
definition. An actual parameter, i.e. an argument, is in a at the time of execution of the program from the following code?
function call. Also specify the maximum values that can be assigned to each of
the variables Lower and Upper.
17 Explain the use of global key word used in a function with the help
of a suitable example.
Answer Use of global key word: import random
AR=[20,30,40,50,60,70];
In Python, global keyword allows the programmer to modify the
Lower =random.randint(1,3)
variable outside the current scope. It is used to create a global
Upper =random.randint(2,4)
variable and make changes to the variable in local context. A variable
for K in range(Lower, Upper +1):
declared inside a function is by default local and a variable declared
print (AR[K],end=”#“)
outside the function is global by default. The keyword global is
written inside the function to use its global value. Outside the (i) 10#40#70#
function, global keyword has no effect. Example (ii) 30#40#50#
(iii) 50#60#70#
c = 10 # global variable (iv) 40#50#70#
def add():
global c Answer OUTPUT: (ii)
c = c + 2 # global value of c is incremented by 2 Maximum value of Lower: 3
print("Inside add():", c) Maximum value of Upper: 4
20 def simple_interest(p, r, t):
return (p*r*t)/100
add() print (simple_interest(100,5,2))
c=15
print("In main:", c)

37 38
Identify the formal and actual parameters in the above code (d) 40 $ 37 $ 39 $ 35 $
snippet. Define formal and actual parameters in a function. Maximum value of Num when P = 7 : 42
OR Minimum value of Num when P = 7 : 35
24 Find the output of the following program;
Answer Answer: p,r,t is formal parameters and 100,5,2 are actual def increment(n):
parameters n.append([4])
return n
21 c = 10 l=[1,2,3]
def add(): m=increment(l)
global c print(l,m)
c=c+2 Answer [1, 2, 3, [4]] [1, 2, 3, [4]]
print("Inside add():", c)
25 Evaluate the following:
add() a. 45<89 and 7>12 or not 18>3
c=15 b. 6*3+2**4//5-2
print("In main:", c)
Answer a. False
output: b. 19
Inside add() : 12
In main: 15
Consider the above program and justify the output. What is the
output if “global c “ is not written in the function add(). 3 MARKS QUESTIONS
1. Find and write the output of the following python code: 3
Answer Answer : In the function add() global c is increment due to use of def Change(P ,Q=30):
global keyword. In the main program local c is printed as local takes P=P+Q
precedence over global c. Q=P-Q
If global c is not used then c=c+2 will show error as there is no print( P,"#",Q)
local variable c in function. return (P)
22 Consider the following function headers. Identify the correct
statement and state reason R=150
1) def correct(a=1,b=2,c): S=100
2) def correct(a=1,b,c=3): R=Change(R,S)
3) def correct(a=1,b=2,c=3): print(R,"#",S)
4) def correct(a=1,b,c): S=Change(S)
Answer 3) def correct(a=1,b=2,c=3): Answer 250 # 150
Constant parameter can be used from right hand side. 250 # 100
23 What possible outputs(s) are expected to be displayed on screen at 130 # 100
the time of execution of the program from the following code? Also
specify the maximum AND minimum values that can be assigned (1 mark each for correct line)
to the variable Num when P = 7 2. Write a program in Python, which accepts a list Lst of
numbers and n is a numeric value by which all elements
import random as r of the list are shifted to left.
val = 35
P=7 Sample Input Data of the list
Num = 0
for i in range(1, 5): Lst= [ 10,20,30,40,12,11], n=2
Num = val + r.randint(0, P - 1)
Output Lst = [30,40,12,11,10,20]
print(Num, " $ ", end = "")
P=P-1
Answer L=len(Lst)
(a) 41 $ 38 $ 38 $ 37 $ (b) 38 $ 40 $ 37 $ 34 $
for x in range(0,n):
(c) 36 $ 35 $ 42 $ 37 $ (d) 40 $ 37 $ 39 $ 35 $
y=Lst[0]
Answer (a) 41 $ 38 $ 38 $ 37 $ for i in range(0,L-1):
39 40
Lst[i]=Lst[i+1]
Lst[L-1]=y Answer my_mylist=[1,2,3,4,5,6,7,8,9,10]
print(Lst)
l1=mylist[:start:1] ½ Mark
#Note : Using of any correct code giving the same result
l2=mylist[end:start-1:-1] ½ Mark
is also accepted.
l3=mylist[end+1:] ½ Mark
final_list=l1+l2+l3 ½ Mark
3. Write a program in Python, which accepts a list Arr of
print (final_list) ½ Mark
numbers , the function will replace the even number Or any other relevant code
by value 10 and multiply odd number by 5 . 6 Write program to add those values in the list of 3
NUMBERS, which are odd.
Sample Input Data of the list is:
Sample Input Data of the List
arr=[10,20,23,45] NUMBERS=[20,40,10,5,12,11]
OUTPUT is 16
output : [10, 10, 115, 225]
Answer NUMBERS=[20,40,10,5,12,11]
Answer l=len(arr) s=0
for a in range(l): for i in NUMBERS:
if(arr[a]%2==0): if i%2 !=0:
arr[a]=10 s=s+i
else: print(s)
arr[a]=arr[a]*5 7 Write a program to replaces elements having even values 3
print(arr) with its half and elements having odd values with twice its
value in a list.
1 mark for function
1 mark for loop and condition checking eg: if the list contains
1 mark for if and else 3, 4, 5, 16, 9
4 Write a program in Python, which accepts a list Arr of then rearranged list as
numbers and n is a numeric value by which all elements 6, 2,10,8, 18
of the list are shifted to left. Answer L=[3, 4, 5, 16, 9]
Sample Input Data of the list
for i in range(n):
Arr= [ 10,20,30,40,12,11], n=2
if L[i] % 2 == 0:
Output L[i] /= 2
Arr = [30,40,12,11,10,20] else:
Answer Arr= [ 10,20,30,40,12,11], n=2 L[i] *= 2
print (L)
L=len(Arr) 8 Write a Python program to find the maximum and minimum 3
for x in range(0,n): elements in the list entered by the user.
y=Arr[0] Answer lst = []
num = int(input(“How many numbers”))
for i in range(0,L-1):
Arr[i]=Arr[i+1] for n in range (nm):
Arr[L-1]=y numbers = int(input”Enter number :”))
print(Arr) lst.append(numbers)
5 Write a program to reverse elements in a list where 3
arguments are start and end index of the list part which is print(“Maximum element in the list is :”,max(lst))
to be reversed. Assume that start<end, start>=0 and print(“Minimum element in the list is :”,min(lst))
end<len(list) 9 Write a program in python to print b power p. 3
Sample Input Data of List Answer b=int(input("Enter base number"))
my_list=[1,2,3,4,5,6,7,8,9,10] p=int(input("Enter exp no."))
Output is
my_list=[1,2,3,7,6,5,4,8,9,10] t=b
41 42
for i in range(p-1): • One of the most useful tools available in Python is the print() function. This simply
t=t*b allows the program to display or print data for the user to read. For example:
print(t) red='Hi, how are you?"
10 Write a program to print of fibonnaci series upto n. 3 print (red)
Output : Hi, how are you?
for example if n is 50 then output will be : • Python has an input function which lets you ask a user for some text input. In
0 Python 2, you have a built-in function raw_input(), whereas in Python 3, you have
1 input() for inputting by user. The syntax is:
1 mydata = ninput("Prompt:')
2 print(mydata)
3 Output: Prompt:
5 • In Python, a number mathematical operations can be performed with ease by
8 importing a module named "math" which defines various functions which makes
13 our task easier.
21 o ceil(x): Returns the ceiling of x as a float, the smallest integer value greater
34 than or equal to x.
Answer n=int(input("Enter any nubmer")) o floor(x): Returns floor of x as a float, the largest integer value less than or
a=0 equal to x.
b=0 o fabs(x): Returns the floating point absolute value of x.
c=1 • exp(x): Return e**x
while a<=n: • log(x,(base)): With one argument, returns the natural logarithm of x (to base e).
print(a)
b=c With two arguments, returns the logarithm of x to the given base calculate as
c=a log(x)log(base)
a=b+c • log10(x): Returns the base-10 logarithm of x. This is usually more accurate than
log(x,10).
• pow(x, y): Returns x raised to the power y. In particular, pow(10, x) and pow(x,
FUNCTIONS 0.0) always return 1.0, even when x is a zero or a NaN. If both x and y are finite,
Notes x is negative, and y is not an integer then pow(x, y) is undefined, and raises
ValueError.
• The act of partitioning a program into individual components is called "Modularity". • sqrt(x): Returns the square root of x.
• A module is a separately saved unit whose functionality can be reused. • cos(x): Returns the cosine of x radians.
• A Python module has the .py extension. • sin(x): Returns the sine of x radians.
• A Python module can contain objects like docstrings, variables, constants, classes, • tan(x): Returns the tangent of x radians.
objects, statements, functions etc. • degrees(x): Converts angle x from radians to degrees.
• The Python modules that come preloaded with Python are called "standard library • radians(x): Converts angle x from degrees to radians.
modules". • A function is a block of organized and reusable code that is used to perform a
• A function is a named block of statements that can be invoked by its name. single, related action. Functions provide better modularity for your application and
• Python can have three types of functions i.e., built-in functions, functions in a high degree of code reusability.
modules and user-defined functions • Function blocks begin with the keyword def followed by the function name and
• The docstrings are useful for documentation purpose. parentheses ().
• Python module can be imported in a program using import statement. • Any input parameters or arguments should be placed within these parentheses.
• There are two forms of import statements: You can also define parameters inside these parentheses.
(i) import <module name> • The first statement of a function can be an optional statement-the documentation
(ii) from <module name> import <object> string of the function or docstring.
• The built-in functions of Python are always available, one needs not import any • The code block within every function starts with a colon (:) and is indented.
module for them. • The statement return [expression] exit a function, optionally passing back an
• The math module of Python provides mathematical functionality. expression to the caller. A return statement with no arguments is the same as
• sys.stdin is the most widely used method to read input from the command line or return None.
terminal. • Defining a function only gives a name, specifies the parameters that are to be
• The command line sys.argv arguments is another way that we can grab input, and included in the function, a structure the blocks of code.
environment be used from within our programs. • The scope of a variable determines the portion of the program where you can
• The basic I/O (Input/Output) functions are input() and print() respectively. access a particular identifier. There are two basic scopes of variables in Python :
43 44
1. Global variables
2. Local variables Passing different objects as an arguments :
• Variables that are defined inside a function body have a local scope, and those You can send any data types of argument to a function as string, number, list,
defined outside have a global scope. dictionary etc., and it will be treated as the same data type inside a function.

• Built-in These are the functions that are always available in Python and can be e.g. List as an argument
accessed by a programmer without importing any module. def fun(Fruit):
• Examples of Some Built-in Functions for i in Fruit:
(i) print(): It prints objects to the text stream file. print(i)
(ii) input(): It reads the input, converts it to a string and returns that.
(iii) sorted(): Returns a new sorted list from the items in iterable.. Food ["Mango", "Cherry", "Grapes", "Banana"]
(iv) bool(): Returns a boolean value i.e., True or False.. fun(Food)
(v) min(): Returns the smallest of two or more arguments.
(vi) any(): Returns True if any element of the iterable is True. Output:-
Mango
• String Functions Cherry
(i) partition(): It splits the string at the first occurrence of the given argument Grapes
and returns a tuple containing three parts. Banana
(ii) join(): It takes a list of string and joins them as a regular string.
(iii) split(): It splits the whole string into the items with separator as a delimeter. Short Answer Type Questions – (1 mark for correct answer)
• Modules: It is a file containing Python definitions and statements. We need to Q.1 Find and write the output of the following python code:
import modules use any containing part before separator, separator parameter a=10
and part after the separator if the separator parameter is found in the string of its def call():
function or variable in our code. global a
• Examples of Some Module Functions a=15
(i) fabs(): It returns the absolute value of a number. call()
(ii) factorial(): This method finds the factorial of a positive integer. print(a)
(iii) random(): It produces an integer between the limit arguments. Q.2. What do you mean by modularity?
(iv) today(): This method returns the current date and time. Q.3. What is a function call?
(v) search(): This function searches the pattern inside the string. Q.4. Name the three categories of functions.
(vi) capitalize(): It returns the copy of string in capital letters. Q.5. What is the role of an argument of a function?
Q.6. What are docstrings?
• User-Defined Functions: User defined functions are those that we define ourselves Q.7. What are docstring conventions?
in our program and then call them wherever we want. Q.8. What is the use of following functions?
• Parameters: These are the values provided in the parentheses in the function Q.9. Name the constant available in math module.
header when we define the function Q.10. Write two ways in which you are able to use constant pi in your programs.
• Arguments: These are the values provided in function call/invoke statement. Q.11. What is dot notation?
• Function Arguments: You can call a function by using the following types of formal Q.12. What is a function?
arguments: Q.13. What is an argument?
o Required arguments/Positional arguments Q.14. What is the general syntax for defining a function in Python?
o Keyword arguments Q.15. What is function header?
o Default arguments Q.16. What are parameters?
o Variable-length arguments Q.17. The convention for indentation within a block is four spaces. Is it true?
Q.18. Find the error in the following codes.
• Required arguments are the arguments passed to a function in correct positional def minus(total_decrement)
order. output= total_decrement
• Keyword arguments are related to the function calls. When you use keyword Q. 19. What is _main_?
arguments in a function call, the caller identifies the arguments by the parameter Q. 20. What is _name_?
name. Q. 21. What is the difference between arguments and parameters?
• A default argument is an argument that assumes a default value, if a value is not Q. 22. Name two types of function in Python.
provided in the function call for that argument. Q. 23. Trace the flow of execution for following program.
• All variables in a program may not be accessible at all locations in that program. 1 def power (b,p):
This depends on where you have declared a variable or the scope of variable. 2 r = b**p
45 46
3 return r Q. 3. Write a program that uses a function which take two string arguments and
4 returns the string comparison result of the two passed strings.
5 def calcsquare(a): Q. 4. Write definition of a function
6 a= power(a,2) 1. OddSum(Numbers) to add Odd values in the list Numbers.
7 return a 2. EvenSum(Numbers) to add Even values in the list Numbers.
8 Q.5. Define a function overlapping () that takes two lists and returns true if they have
9 n=5 at least one member in common, False otherwise.
10 result = calcsquare(n) Q.6. Write a program for nth multiple of Fibonacci Series. Also show proper
11 print(result) documentation.
Q. 24. What will be the output of the following code? Q. 7. Write a Python program to reverse a string.
def addEm(x,y,z): Q.8. A function checkMain() defined in module Allchecks.py is being used in two
print(x+y+z) different programs
In program 1 as
def prod(x,y,z): Allchecks.checkMain(3,'A')
return x*y*z and in program 2 as
checkMain(4,'Z').
a= addEm(6,16,26) Why are the functions call statements different in each program?
b= prod(2,3,6) Q. 9. Write a python program to find simple interest using a user defined function
print(a,b) with parameters and with return value.
Q.25. What is the use of return statement? Q. 10. Explain any three string functions with example?

Short Long Answer Type Questions - (2 mark for correct answer) Case Base Questions - (5 mark for correct answer)
Q. 1. Find and write the output of the following Python code:
def fun(s): Q. 1. Kids Elementary is a playway school that focuses on 'Play and learn' strategy
k= len(s) that helps toddlers understand concepts in a fun way. Being a senior programmer,
m="" you have taken responsibility to develop a program using user-defined functions to
for i in range(0,k): help children differentiate between upper case and lower case letters/English
if(s[i].isupper()): alphabet in a given sentence. Make sure that you perform a careful analysis of the
m=m+s[i].lower() type of alphabets and sentences that can be included as per age and curriculum.
elif s[i].isalpha():
m=m+s[i].upper() Write a Python program that accepts a string and calculates the number of upper
else: case letters and lower case letters.
m=m+'bb'
print(m) Q. 2. Traffic accidents occur due to various reasons. While problems with roads or
fun('school2@com') inadequate safety facilities lead to some accidents, majority of the accidents are
Q. 2. What do you understand by local and global scope of variables? How can you caused by drivers' carelessness and their failure to abide by traffic rules.
access a global variable inside the function, if function has a variable with same ITS Roadwork is a company that deals with manufacturing and installation of traffic
name. lights so as to minimize the risk of accidents. Keeping in view the requirements,
Q. 3. What are the differences between parameters and arguments? traffic simulation is to be done. Write a program in Python that simulates a traffic
Q. 4. What are default arguments? light. The program should perform the following:
(a) A user-defined function trafficlight() that accepts input from the user, displays
Q. 5. What are keyword arguments? an error message if the user enters anything other than RED, YELLOW and GREEN.
Q. 6. What are the advantages of keyword arguments? Function light() is called and the following is displayed depending upon return value
Q. 7. Write a generator function generatesq () that displays the square roots of from light():
numbers from 100 to n where n is passed as an argument. (i) "STOP, Life is more important than speed" if the value returned by light() is
Q. 8. What are the advantages of dividing a program into modules. 0.
Q. 9. Differentiate between Built-in functions and user defined functions. (ii) "PLEASE GO SLOW." if the value returned by light() is 1.
Q. 10. Differentiate between Built-in functions and functions defined in modules. (iii) "You may go now." if the value returned by light() is 2.
(b) Auser-defined function light() that accepts a string as input and returns 0 when
Long Answer Type Questions - (3 mark for correct answer) the input is RED, 1 when the input is YELLOW and 2 when the input is GREEN. The
Q. 1. List a type of arguments and explain any 2 type of arguments. input should be passed as an argument.
Q. 2. Write a method in Python to find and display the prime number between 2 to (c) Display "BETTER LATE THAN NEVER" after the function trafficLight() is executed.
N. Pass N as argument to the method.
47 48
Summary Short Answer Type Questions – (1 mark for correct answer)
Q.1 Find and write the output of the following python code:
➢ A module is a separately saved unit whose functionality can be reused at will. a=10
➢ A function is a named block of statements that can be invoked by its name. def call():
➢ Python can have three types of functions: global a
• Built-in functions, a=15
• Functions in modules, and call()
• User-defined functions. print(a)
➢ A Python module can contain objects like docstrings, variables, constants, classes, Ans. 15
objects, statements, functions
➢ A Python module has the py extension. Q.2. What do you mean by modularity?
➢ A Python module can be imported in a program using import statement. Ans. The act of partitioning a program into individual components (modules) is called
➢ There are two forms of Importing Python module statements: modularity.
(i) import <modulename>
(ii) from <module> import <object> Q.3. What is a function call?
➢ The built-in functions of Python are always available; one need not import any Ans. To use a function that has been defined earlier, a function call statement is
module for them. written in Python.
➢ The math module of Python provides math functionality. Its syntax is <function name> (<value to be passed to argument>)
➢ Functions make program handling easier as only a small part of the program is e.g. print ()
dealt with at a time, thereby avoiding ambiguity.
➢ The values being passed through a function-call statement are called arguments Q.4. Name the three categories of functions.
(or actual parameters or actual arguments). Ans. 1. Built-in-Functions
➢ The values received in the function definition/header are called parameters (or 2. Functions defined in modules
formal parameters or formal arguments). 3. User defined Functions.
➢ Keyword arguments are the named arguments with assigned values being passed
in the function-call statement. A function may or may not return a value. Q.5. What is the role of an argument of a function?
➢ A void function internally returns legal empty value None. The program part(s) in Ans. An argument passes the value to the function to work upon.
which a particular piece of code or a data value (e.g., variable) can be accessed
is known as Variable Scope. Q.6. What are docstrings?
➢ In Python, broadly, scopes can either be global scope or local scope. Ans. The docstrings are triple quoted strings in a Python module program which are
➢ A local variable having the same name as that of a global variable hides the global displayed as document when help (<module or program name>) command is
variable in its function. issued. (1 mark for correct answer) 1
➢ A file that contains a collection of related functions grouped together and other
definitions is called module. Q.7. What are docstring conventions?
➢ A search path is the list of directories that the interpreter searches before Ans. General docstring conventions are:
importing a module. (1) First Letter of the first line is a capital letter.
➢ A library is just a module that contains some useful definitions. (2) Second line as blank line.
➢ The random() function generates a floating point random value from 0 to <1. (3) Rest of the details begin from third line.
➢ A function is said to be recursive if it calls itself.
➢ There are two cases in each recursive function-the recursive case and the base Q.8. What is the use of following functions?
case. An infinite recursion is when a recursive function calls itself endlessly. (a) ceil (b) sqrt (c) exp (d) fabs
➢ if there is no base case or if the base case is never executed, infinite recursion Ans (a) ceil() function returns smallest integer not less than the argument.
occurs. (b) sqrt() function returns square-root of the argument.
➢ Iteration uses the same memory space for each pass contrary to recursion where (c) exp() function returns natural logarithm e raised to the argument power.
fresh memory is allocated for each successive call. (d) fabs() function returns the absolute value of the supplied argument.
➢ Recursive functions are relatively slower than their iterative counterparts. Some
commonly used recursive algorithms are factorial, gcd, fibonacci series printing, Q.9. Name the constant available in math module.
binary search, etc. Ans. math.pi (where pi(#)=3.1415....)
➢ String can be passed to a function as argument but it is used as pass by value. math.e (where e = 2.718281.....)
➢ Tuple value cannot be modified in a function.
➢ In Python, everything is an object, so the dictionary can be passed as an Q. 10. Write two ways in which you are able to use constant pi in your programs.
argument to a function like other variables are passed. Ans. 1st method
import math m
49 50
print (math.pi) (½ mark for each function type) 1

2nd method Q. 23. Trace the flow of execution for following program.
from math import pi 1 def power (b,p):
print (pi) 2 r = b**p
Q. 11. What is dot notation? 3 return r
Ans. When a module is import, we can use its functions or constants by specifying 4
the .name of the module and of the function, separated by a dot. 5 def calcsquare(a):
e.g. <module name>. <function name>() 6 a= power(a,2)
This is called dot notation. 7 return a
8
Q.12. What is a function? 9 n=5
Ans. A function is a block of statements that is given a name. This name can be used 10 result = calcsquare(n)
to invoke the function. 11 print(result)
Ans. 1→5→9→10→6→2→3→7→11
Q.13. What is an argument?
Ans. An argument is data passed to a function through function call statement. Q. 24. What will be the output of the following code?
def addEm(x,y,z):
Q. 14. What is the general syntax for defining a function in Python? print(x+y+z)
Ans. def<function name> ([parameters]):
["""<functions docstrings>"""] def prod(x,y,z):
<statement> return x*y*z
[<statement>]
a= addEm(6,16,26)
Q. 15. What is function header? b= prod(2,3,6)
Ans. The first line of function definition that specifies It begins name of the functions print(a,b)
and parameters. with keyword def and ends with a colon(). Ans. 48
Syntax: def <function_name> ([parameters]); None 36.

Q.16. What are parameters? Q.25. What is the use of return statement?
Ans. Parameters are variables listed within parentheses of a function header. Ans. The return statement terminates the execution of a function and returns control
to the calling function.
Q.17. The convention for indentation within a block is four spaces. Is it true?
Ans. Yes. Short Answer Type Questions - (2 mark for correct answer)
Q. 18. Find the error in the following codes.
def minus(total_decrement) Q. 1. Find and write the output of the following Python code:
output= total_decrement def fun(s):
Ans. Colon (:) is missing in function header. It should be k= len(s)
def minus(total_decrement): m=""
for i in range(0,k):
Q. 19. What is _main_? if(s[i].isupper()):
Ans. The segment with top level statements is named as_main_ by Python. m=m+s[i].lower()
elif s[i].isalpha():
Q. 20. What is _name_? m=m+s[i].upper()
Ans. _name_ is a built in variable that states the name of the top level statements else:
i.e. _main_. m=m+'bb'
print(m)
Q. 21. What is the difference between arguments and parameters? fun('school2@com')
Ans. Value that are being passed are called arguments and values that are received Ans. SCHOOLbbbbCOM
are called parameters.
Q. 2. What do you understand by local and global scope of variables? How can you
Q. 22. Name two types of function in Python. access a global variable inside the function, if function has a variable with same
Ans. Non-void and void functions. name.
51 52
Ans. A global variable is a variable that is accessible globally. A local variable is one modules are predefined in modules and can be used only when the
that is only accessible to the current scope, such as temporary variables used corresponding module is imported e.g. to use predefined function sqrt() the
in a single function definition. A variable declared outside of the function or in math module needs to be imported as import math.
global scope is known as global variable. This means, global variable can be
accessed inside or outside of the function where as local variable can be used Long Answer Type Questions - (3 mark for correct answer)
only inside the function. We can access by declaring variable as global A.
Q. 1. List a type of arguments and explain any 2 type of arguments.
Q. 3. What are the differences between parameters and arguments? Ans. Type of arguments:
Ans. • Positional arguments
S.No. Parameters Arguments • Default arguments
Values provided in function Values provided in function • Keyword arguments
1 • Variable length arguments
header call.
(eg) def area (r): (eg) def main() Keyword arguments :
→r is the parameter radius = 5.0 If there is a function with many parameters and we want to specify only
2 some of them in function call, then value for such parameters can be provided
area (radius)
→ radius is the argument by using their names instead of the positions.
Q. 4. What are default arguments?
Ans. Python allows function arguments to have default values; if the function is called These are called keyword arguments.
without the argument, the argument gets its default value. e.g. def simpleinterest(p, n=2, r=0.6):
def simpleinterest(p, r=0.2, n=3):
Q. 5. What are keyword arguments? Default arguments
Ans. If there is a function with many parameters and we want to specify only some Python allows function arguments to have default values; if the function
of them in function call, then value for such parameters can be provided by is called without the argument, the argument gets its default value.
using their names instead of the positions. e.g. def add(a,b=0)
These are called keyword arguments. def mul(a=1,b=1)
(e.g.) def simpleinterest(p, n=2, r=0.6): (Note:Student may explain any 2 type of argument)
def simpleinterest(p, r=0.2, n=3):
Q. 2. Write a method in Python to find and display the prime number between 2 to
Q.6. What are the advantages of keyword arguments? N. Pass N as argument to the method.
Ans. It is easier to use since we need not to remember the order of the arguments. Ans. def prime(N):
We can specify the values for only those parameters which we want, and others for a in range (2, N):
will have default values. prime = 1
Q.7. Write a generator function generatesq () that displays the square roots of for i in range (2, a):
numbers from 100 to n where n is passed as an argument. if a%i ==0:
Ans. import math prime = 0
def generates(n): if prime == 1:
for i in range(100,n): print (a)
print(math.sqrt(i))
OR
Q. 8. What are the advantages of dividing a program into modules. def prime(N):
Ans. The advantages of dividing a program into modules : for a in range (2, N):
• It reduces complexity of the program. for i in range (2, a):
• It creates well-defined boundaries within the program. if a%i == 0:
• It increases the reusability of the module. break
else:
Q. 9. Differentiate between Built-in functions and user defined functions. print (a)
Ans. Built in functions are predefined functions that are already defined in Python break
and can be used anytime.
e.g. len(), type(), int(), etc. Q. 3. Write a program that uses a function which take two string arguments and
User defined functions are defined by the programmer. returns the string comparison result of the two passed strings.
Q. 10. Differentiate between Built-in functions and functions defined in modules. Ans. def stringComp (str1, str2):
Ans. Built-in functions are predefined functions that are already defined in Python if str1.length()!=str2.length:
and can be used anytime e.g. len(), type(), int() etc. Functions int defined in return(False)
53 54
else: f1 = f2
for i in range (str1.length()): f2=f3
if str1[i]:= str2[i]: if f2%k == 0:
return(False) return n*i
else: i+=1
return (True) return
# Multiple no.
fstring=input ("Enter First string:") n=5
sstring=input ("Enter Second string:") #Number of whose multiple we are finding
if stringComp (fstring, sstring): k=4
print ("Strings are same.")
else: print("Position of nth multiple of k in")
print ("Strings are different") print("Fibonacci series is", findPosition(k,n))

Q. 4. Write definition of a function Q. 7. Write a Python program to reverse a string.


1. OddSum(Numbers) to add Odd values in the list Numbers. Ans. def string_reverse(str1):
2. EvenSum(Numbers) to add Even values in the list Numbers. rstr1= “”
index = len(str1)
Ans. def OddSum(Numbers):
Sum=0 while index > 0:
for i in range(len(Numbers)): rstr1+= str1[index-1]
if(Numbers[i]%2!=0): index = index-1
Sum+=Numbers[i] return rstr1
print(Sum) print(string_reverse("1234abcd'))

def EvenSum(Numbers): Q. 8. A function checkMain() defined in module Allchecks.py is being used in two
Sum=0 different programs
for i in range(len(Numbers)): In program 1 as
if(Numbers[i]%2==0): Allchecks.checkMain(3,'A')
Sum+=Numbers[i] and in program 2 as
print(Sum) checkMain(4,'Z').
Why are the functions call statements different in each program?
Q.5. Define a function overlapping () that takes two lists and returns true if they have
at least one member in common, False otherwise. Ans. In program 1, the complete module Allchecks.py must have been imported as
Ans. def overlapping (list1, list2): import Allchecks
l1= len(list1) So a SpaceName is created and we need to specify the module name.
l2= len(list2) In program 2, only the function checkMain() must have been imported as
flag=False
for i in range (11):
for j in range (12): From Allchecks import checkMain()
if list1[i]==list2[j]: So the checkMain() function is imported into the namespace of the program2
flag=True and hence can be used independently.
return flag
Q. 6. Write a program for nth multiple of Fibonacci Series. Also show proper Q. 9. Write a python program to find simple interest using a user defined function
documentation. with parameters and with return value.
Ans. # Python Program to find position of nth multiple Ans. #Python program to calculate simple interest using function
# of a number k in Fibonacci Series def simpleInterest(P, N, R):
def findPosition(k, n): SI = (P * N * R)/100
f1 = 0 return SI
f2=1 P = float(input("Enter the principal amount : "))
i=2 N = float(input("Enter the number of years : "))
while i!=0: R = float(input("Enter the rate of interest : "))
f3=f1+f2 #calculate simple interest by using this formula
55 56
SI = simpleInterest(P, N, R) inadequate safety facilities lead to some accidents, majority of the accidents are
#print caused by drivers' carelessness and their failure to abide by traffic rules.
print("Simple interest : ",SI) ITS Roadwork is a company that deals with manufacturing and installation of traffic
lights so as to minimize the risk of accidents. Keeping in view the requirements,
Q. 10. Explain any three string functions with example? traffic simulation is to be done. Write a program in Python that simulates a traffic
Ans. 1) isupper():The isupper() method returns True if all the characters are in light. The program should perform the following:
upper case, otherwise False.
txt = "THIS IS NOW!" (a) A user-defined function trafficlight() that accepts input from the user, displays an
x = txt.isupper() error message if the user enters anything other than RED, YELLOW and GREEN.
print(x) Function light() is called and the following is displayed depending upon return value
2) upper() : The upper() method returns a string where all characters are in from light():
upper case. (i) "STOP, Life is more important than speed" if the value returned by light() is 0.
txt = "Hello my friends" (ii) "PLEASE GO SLOW." if the value returned by light() is 1.
x = txt.upper() (iii) "You may go now." if the value returned by light() is 2.
print(x) (b) Auser-defined function light() that accepts a string as input and returns 0 when
3) isdigit() : The isdigit() method returns True if all the characters are digits, the input is RED, 1 when the input is YELLOW and 2 when the input is GREEN. The
otherwise False. input should be passed as an argument.
txt = "50800" (c) Display "BETTER LATE THAN NEVER" after the function trafficLight() is executed.
x = txt.isdigit()
print(x) Ans. # Program to simulate a traffic light comprising of
(Note: Student may write any three string functions) # two user defined functions trafficLight() and light().

def trafficlight ():


Case Base Questions - (5 mark for correct answer) signal input ("Enter the colour of the traffic light: ")
if (signal not in ("RED", "YELLOW", "GREEN")):
Q. 1. Kids Elementary is a playway school that focuses on 'Play and learn' strategy print("Please enter a valid Traffic Light colour in CAPITALS")
that helps toddlers understand concepts in a fun way. Being a senior else:
programmer, you have taken responsibility to develop a program using user- value= light(signal)# function call to light()
defined functions to help children differentiate between upper case and lower ` if(value==0):
case letters/English alphabet in a given sentence. Make sure that you perform print ("STOP, Life is more important than speed")
a careful analysis of the type of alphabets and sentences that can be included elif (value==1):
as per age and curriculum. print ("PLEASE GO SLOW.")
else:
Write a Python program that accepts a string and calculates the number of print ("You may go now.")
upper case letters and lower case letters. def light (colour):
if (colour "RED"):
Ans. #A user-defined function that accepts a string return (0)
# and calculates the number of upper case letters and lower case letters elif (colour "YELLOW"):
def string_test(s): return (1)
d= {"UPPER CASE": 0, "LOWER CASE":0} else:
for c in s: return (2) #function end a here
if c.isupper(): trafficlight ()
d["UPPER CASE"]+=1 print ("BETTER LATE THAN NEVER")
elif c.islower ():
d["LOWER CASE"]+=1 Files – Text Files
else:
pass A text file stores information in the form of a stream of ASCII or Unicode characters.
print ("Original String: ", s) In text files, each line of text is terminated, (delimited) with a special character known
print ("No. of Upper case characters: ", d["UPPER CASE"]) as EOL (End of Line) character. In Python, by default, this EOL character is the
print ("No. of Lower case characters: ", d["LOWER CASE"]) newline character ('\n') or carriage-return, newline combination ('\r\n').
string_test("Play Learn and Grow") The text files can be of following types:

Q. 2. Traffic accidents occur due to various reasons. While problems with roads or

57 58
1. Regular Text files: These are the text files which store the text in the same
form as typed. Here the newline character ends a line and the text translations a+: Opens a file for both appending and reading. The file pointer is at the
take place. These files have a file extension as .txt. 6 end of the file if the file exists. The file opens in the append mode. If the
2. Delimited Text files: In these text files, a specific character is stored to file does not exist, it creates a new file for reading and writing.
separate the values, i.e., after each value, e.g., a tab or a comma after every
value.
File Read Methods:
a. When the comma is used to separate the values stored, these are called
CSV files (Comma Separated Values files). These files take the extension Sr.No. Methods & Description
as .csv.
Filehandle.read([n]): reads and return n byres, if n is not specified it
Files – Binary Files 1
reads entire file.
A binary file stores the information in the form of a stream of bytes. A binary file
contains information in the same format in which the information is held in memory,
i.e., the file content that is returned to you is raw (with no translation or no specific Filehandle.readline([n]): reads a line of input. If n is specified reads at
encoding). As a result, binary files are faster and easier for a program to read and 2 most n bytes. Read bytes in the form of string ending with end of line
write than are text files. As long as the file doesn't need to be read by people or need character of blank string if no more bytes are left for reading.
to be ported to a different type of system, binary files are the best way to store
program information.
3 Filehandle.readlines(): reads all the lines and return them in a list.
File Object: A file object is a reference to a file on disk. It opens the file and makes
it available for a number of different tasks.
Absolute Vs Relative path: File Write Methods:
An absolute path is defined as specifying the location of a file or directory from the
Sr.No. Methods & Description
root directory. In other words, we can say that an absolute path is a complete path
from start of actual file system from / directory.
Relative path is defined as the path related to the present working directly. 1 Filehandle.write(str): Write string str to file referenced by filehandle.

File Modes: A file mode govern the type of operations (read/write/append)


Filehandle.writelines(L): Write all strings in list L as lines to file
possible in the opened file. 2
referenced by filehandle.
Sr.No. Modes & Description

r: Opens a file for reading only. The file pointer is placed at the beginning Opening text file:
1 open() function: The open() function is used to open a file in the following manner:
of the file. This is the default mode.
<file-objectname> = open(<filename>)
<file-objectname> = open(<filename>,<mode>)
r+: Opens a file for both reading and writing. The file pointer placed at By default the file open mode is read mode.
2
the beginning of the file.
with statement: with statement will automatically close the file after the nested block
of code. It is guaranteed to close the file no matter how the nested block exits. Even
w: Opens a file for writing only. Overwrites the file if the file exists. If the if an exception occurs with statement will handle it and close the file. It is used in the
3
file does not exist, creates a new file for writing. following manner:
with open(<filename>,<filemode>) as <filehandle>:
<file manipulation statements>
w+: Opens a file for both writing and reading. Overwrites the existing file
4 if the file exists. If the file does not exist, creates a new file for reading
Closing a text file: A close() function breaks the link of file-object and the file on
and writing. the disk. No tasks cab be performed after the file is closed. It is used in the following
way:
a: Opens a file for appending. The file pointer is at the end of the file if <file-handle>.close()
5 the file exists. That is, the file is in the append mode. If the file does not
exist, it creates a new file for writing. The tell() Function: The tell() function returns the current position of the file pointer
in a file. It is used as per the following syntax:

59 60
<file-object>.tell() Q7. What is the full form of CSV?
a. Common segregated values
The seek() Function: the seek() function changes the position of the file pointer by b. Comma separated values
placing the file pointer at the specified position in the opened file. Its is used as per c. Common separated values
the following syntax: d. None of the above
<file-object>.seek(offset[, mode])
offset: is a number specifying number of bytes. Q8. If a file is opened for writing
mode: 0 – for beginning of the file – by default 0 a. File must exist before opening
1 – for current position of file pointer b. File will be created if does not exist
2 – for end of the file
c. None of the above
d. Both a and b

Questions – 1 Mark - MCQ Q9. If the cursor in the file is at the end of the file, then what will the read()
function return?
Q1. To open a file c:\ss.txt for appending data we use a. None
a. file = open(‘c:\\ss.txt’,’a’) b. False
b. file = open(r‘c:\ss.txt’,’a’) c. Exception
c. file = open(‘c:\\ss.txt’,’w’) d. Empty string
d. both a and b Q10. Which is the value of mode parameter to set the offset of the cursor from the
end of the file?
Q2. To read the next line of the file from the file object infi, we use a. 0
a. infi.read(all) b. 1
b. infi.read() c. 2
c. infi.readline() d. None of the above
d. infi.readlines()
Q3. Which function is used to ensure that the data in written in the file Answer Key
immediately? 1.d 2.c 3.c 4.c 5.b 6.c 7.b 8.a 9.d 10.c
a. <filehandle>.write()
b. <filehandle>.writelines() Questions – 2 Marks – Short Answer
Q1. What is the difference between opening mode ‘a’ and ‘w’?
c. flush()
d. <filehandle>.close()
Q2. What is the purpose of flush() in file handling operations?
Q4. What is the datatype of the value returned by readlines() function?
a. Integer
Q3. What is the advantage of opening file using with keyword?
b. String
c. List of strings Q4. Consider the following file ‘corona.txt’
d. None of the above O corona O corona
Jaldi se tum Go na
Q5. What is the position of the cursor when the file is opened in append mode? Social Distancing ka palan karona
a. Start of file Sabse 1 meter ki duri rakho na
b. End of file Write the output of the following statement:
c. At the 11th byte f = open(‘corona.txt’)
d. Unknown str1 = ____________ # to read first line
str2 = ____________ # to read next line of file
Q6. How to open a file such that close function is not needed to be called in order str3 = ____________ # to read remaining lines of the file
to close the connection between file and python program?
a. Using open() method Q5. Consider the following file ‘corona.txt’
b. Using read() method O corona O corona
c. Using with keyword Jaldi se tum Go na
Social Distancing ka palan karona
d. Using open with method
Sabse 1 meter ki duri rakho na
Complete the missing statement using fir loop to print all the lines of code:
61 62
f = open(‘corona.txt’) 7 Text files are stored in the human readable format. These have some
for ____________: internal conversions like newlines etc.
print(____) Binary file store data in pure binary form and hence can be used on any
machine/hardware with appropriate software.
Q6. Given a file ‘data.txt’ write a function atoesidp() to display the file after 8 No output (Empty string).
replacing ‘a’ with ‘e’. fh.read() in the second line puts the cursor at the end of the file. That is
why the read function in the third line will return an empty string.
Q7. What is the advantage of saving a file in text form and binary form? 9 0123456789abcdefxyz1234
10 Bye
Q8. What is the output of following code? Existing data will be overwritten.
fh = open(‘main.txt’,’r’)
size = len(fh.read()) Questions – 3 Marks – Long Answer
print(fh.read())
Q1. Differentiate between ‘r’ and ‘w’ file open modes and ‘w’ and ‘a’ file open mode.
Q9. Write the output of the following program
f = open(‘data.txt’, ’w+’) Q2. Write a function stats() that accepts a filename and reports the files longest line.
f.write(‘0123456789abcdef’)
f.write(‘xyz1234’) Q3. A text file contains alphanumeric text (say an.txt). Write a program that reads
f.seek(0) this text file and prints only the numbers or digits from the file.
print( f.read())
f.close() Q4. Write a program to read a text file and display the count of lowercase and
uppercase letters in the file.
Q10. If a file ‘f.txt’ contains data ‘Good’ and then what is the content of the file
f.txt then following program in run? Q5. Write a method in python to read lines from a text file INDIA. TXT, to find and
f = open(‘f.txt’, ‘w’) display the Occurrence of the word "India".
f.write(‘Bye’)
f.close() Q6. Write a program that copies a text file "source.txt” onto "target.txt" barring the
starting with a "@" sign.
S.No Answer Key
1 ‘w’ is used to write in file from the beginning. If file already exists then it Q7. Take a sample text file and find the most commonly occurring word. Also, list
will overwrite the previous content. the frequencies of words in the text file.
‘a’ is also used to write in the file. If file already exists it will write after Q8. Write a program to read a text file line by line and display each word separated
the previous content. by a #.
2 The flush function forces the writing of data on disk still pending in output
buffer. Flush allows the user to send the content in file before closing the Q9. Write a function remove_lowercase() that accepts two filenames, and copies all
file. the lines that do not start with a lowercase letter from the first file into the second.
3 With keyword reduces the overheads involved in the closing of the file
after file operation or handling the file closing after exception have Q10. Write a program to display all the records in a file along with line/record
occurred. When file is opened using ‘with’ it will manage the closing of file number.
at the end of the operations or after an exception automatically.
4 f.readline() S.No Answer Key
f.readline() 1. Refer the notes above.
f.readlines() 2. def stats(filename):
5 for line in f: longest = ""
print(line) for line in file(filename):
6 def atoedisp(): if len(line) > len(1ongest):
f = open(‘data.txt’) longest = line
r = f.read() print("Longest line's length =", len(longest))
for ch in r: print(longest)
if ch == ‘a’: 3. F open("an. txt", "r")
print(‘e’, end = ‘’) for line in F:
else: words line.split()
print(ch, end = ‘’) for i in words:
63 64
for letter in i: print("The word ' "+ word+" ‘ occurs maximum number of times, ", high,
if( letter.isdigit () ) : "times. ")
print(letter) print("\n other words have these frequencies: ")
4. myfile = open( "Answer.txt", "r") print (wordfreg)
ch = “ ” #initially stored a space ( a non-None value) 8. myfile = open( "Answer.txt", "r")
lcount = 0 #variable to store count of lowercase letters line = " ”
ucount 0 while line:
while ch: #while ch stores a Non-None value line = myfile.readline() # one line read from file
ch = myfile.read(1) #one character read from file # printing the line word by word using split()
if ch.isupper() == True: for word in line.split():
ucount ucount+1 print (word, end = '#*)
else: print()
lcount = lcount + 1 #close the file
print("Uppercase letters in the file: ", ucount) myfile.close()
print ("Lowercase letters in the file: ", lcount) 9. def remove_lowercase (infile, outfile):
#close the file output file (outfile, "w")
myfile.close() for line in file(infile):
5. def display1(): if not line[e] in "abcdefghijklmnopqrstuvwxyz" :
count = 0 output.write(line)
file = open( 'INDIA. TXT, 'r°) output.close ()
for LINE in file: 10. fh = open("Result.det", "r")
Words LINE. split() count = 0
for W in Words rec = “”
if W= "India": while True:
count count +1 rec fh.readline()
print (count) if rec != "":
file.close() count count +1
6. def filter (oldfile, newfile): print(count, rec)
fin = open(oldfile, "r") fh.close()
fout open(newfile, "w")
while True:
text fin.readline() Questions – 5 Marks – Case Based Questions
if len(text) != 0:
if text[e] != "@": Q1. Dhanush's teacher has given him the following text file (HigherEd. txt).
fout.write(text)
fin.close() Higher education improves an individual' s quality of life.
fout.close() Studies show that, compared to high school graduates, college graduates have
filter("source.txt", "target.txt") longer life spans, better access to health care, better dietary and health
7. with open ("nanthem.txt", "r") as fh: practices, greater economic stability and security.
contents = fh.read() We must ensure that our whole population receives an education that will allow full
Wordlist = contents.split() and continuing participation in this dynamic period of economic history.
Wordfreq= []
High = 0 And the following incomplete code:
Word = ‘’ def fileFunction1(______ ) #Fil1_line5
existing = [] fin = ________ #Fi11_line6
for w in wordlist: print( _______(N1)) #Fi11_line7
wcount = wordlist.count(w) _____________ #Fil1_line8
if w not in existing: print( _______(N2)) #Fil1_line9
wordfreq.append( [w,wcount]) #__main__
existing.append(w) N1 = __________ #Fill_Line1
if wcount> high: N2 = __________ #fill_Line2
high = wcount Filename = _________ #Fill_Line3
Word = w fileFunction1 (Filename, N1, N2) #Line4
65 66
Help Dhanush to complete his work as per the following instructions: 1 a. N1 = int(input ("Enter number1: "))
a. Add code to blank lines Fill_Linel and Fill_Line2 so that two integer numbers N2 = int(input ("Enter number 2:"))
are read into variables N1 and N2. fileName= "HigherEd. txt”
Also, complete Fill_Line3 so that the function call below it makes sense, which is fileFunction1 (fileName, N1, N2)
sending 3 arguments : filename, and two numbers N1 and N2. b. def fileFunction1 (fname, N1, N2):
b. As per the function call, complete the function header in Fill _Line5. c. fin open(fname, "")
c. Complete Fill _Line6 so that the text file is opened for reading in the file object d. print(fin.read(N1))
fin. print(fin.read(N2))
d. Complete Fill_Line7 and Fill_Line9 so that the passed number of characters are e. fin.readline()
read from the file and printed. 2 a. fileFunction1(" Education.txt', string)
b. def fileFunction1(fname, string):
e. Complete Fill_ Line8 so that the characters till the end of the line from the
c. fi open(fname, "a")
current position of the file pointer are read but not printed.
d. fi.write(string)
fi.write('\n')
Q2. SHRUTHI has to complete her file-based assignment by tonight. She has been e. Done
given the following text file (Education.txt): Higher education
college graduates have
Higher education improves quality of life. [‘longer 1ife spans.\n', 'Education is birth right.\n', 'India
College graduates have longer life spans. strengthening\n']
Education is birthright.
Shruthi has also received the following incomplete code. Binary files store data in the binary format (0’s and 1’s) which is understandable by
the machine. So when we open the binary file in our machine, it decodes the data
def fileFunction1 (____,____) #Fill_Line5 and displays in a human-readable format.
fi = ___(fname,___) #Fill_Line6
fi._______ #Fill_Line7 Binary File Modes: File mode governs the type of operations read/write/append
fi._______ #Fill_Line8 possible in the opened file. It refers to how the file will be used once its opened.
fi.close()
File Mode Description
print("Done")
rb Read Only: Opens existing file for read operation
def fileFunction2(fname, N1, N2):
wb Write Only: Opens file for write operation. If file does not exist, file is
fi = open(fname)
print(fi.read(N1)) created. If file exists, it overwrites data.
fi.readline() ab Append: Opens file in write mode. If file exist, data will be appended
print( fi.read(N2) ) at the end.
a = fi.readlines () rb+ Read and Write: File should exist, Both read and write operations can
print(a) be performed.
N1 = 16 #Line1
wb+ Write and Read: File created if not exist, If file exist, file is truncated.
N2 = 22 #Line2
String = "India strengthening" #Line3 ab+ Write and Read: File created if does not exist, If file exist data is
fileFunction1( ____,____) #Fill_Line4 truncated.
fileFunction2 ( 'Education.txt', N1, N2)
Help her to complete her assignment as per the following instructions. Write data to a Binary File:
a. Complete Fill_Line4 so that the function call to FileFunction1() passes two
arguments: First as the filename and the second as the string given in Line 3. Pickle is a special python package that is used to generate data in binary format.
b. Complete Fill_Line5 so that the function header is as per its function call. Pickle comes with few methods like dump( ) to write data in binary format.
c. Complete Fill_Line6 so that the file is opened in a mode that will allow it to Example:
write the string at the end of the file without deleting anything from the file. import pickle
d. Complete Fill_Line7 and FilI_Line8 so that the passed string is written on to the list =[ ] # empty list
file, followed by a newline character. while True:
e. What will be the output produced by the complete code? roll = input("Enter student Roll No:")
sname = input("Enter student Name :")
S. No Answer Key student = {"roll":roll,"name":sname} # create a dictionary
list.append(student) # add the dictionary as an element
67 68
in the list Record Updated
choice= input("Want to add more record(y/n) :")
if(choice=='n'): Delete a record from binary file:
break import pickle
file = open("student.dat","wb") # open file in binary and write roll = input('Enter roll number whose record you want to delete:')
mode pickle.dump(list, file) file = open("student.dat", "rb+")
file.close( ) list = pickle.load(file)
found = 0
OUTPUT: lst = []
Enter student Roll No:1201 for x in list:
Enter student Name :Anil if roll not in x['roll']:
Want to add more record(y/n) :y lst.append(x)
Enter student Roll No:1202 else:
Enter student Name :Sunil found = 1
Want to add more record(y/n) :n if found == 1:
file.seek(0)
Read data from a Binary File: pickle.dump(lst, file)
print("Record Deleted ")
To read the data from a binary file, we have to use load( ) function of pickle else:
module. print('Roll Number does not exist')
file.close( )
Example: OUTPUT:
import pickle file = open("student.dat", "rb") Enter roll number whose record you want to delete:1201
list = pickle.load(file) print(list) Record Deleted
file.close( )
OUTPUT: Search a record in a binary file:
[{'roll': '1201', 'name': 'Anil'}, {'roll': '1202', 'name': 'Sunil'}] import pickle
roll = input('Enter roll number that you want to search in binary file :')
Update a record in Binary File: file = open("student.dat", "rb")
list = pickle.load(file)
Locate the record to be updated by searching for it. file.close( )
Make changes in the loaded record in memory for x in list:
Write back onto the file at the exact location of record. if roll in x['roll']:
import pickle print("Name of student is:", x['name'])
roll = input('Enter roll number whose name you want to update in binary file :') break
file = open("student.dat", "rb+") else:
list = pickle.load(file) print("Record not found")
found = 0 OUTPUT:
lst = [ ] Enter roll number that you want to search in binary file :1202
for x in list: Name of student is: Harish
if roll in x['roll']:
found = 1 tell( ) and seek( ) methods:
x['name'] = input('Enter new name: ') tell( ): It returns the current position of cursor in file.
lst.append(x) Example:
if found == 1: fout=open("story.txt","w")
file.seek(0) fout.write("Welcome Python")
pickle.dump(lst, file) print(fout.tell( ))
print("Record Updated") fout.close( )
else: print('roll number does not exist')
file.close( ) Output:
OUTPUT: 15
Enter roll number whose name you want to update in binary file :1202
Enter new name: Harish seek(offset, reference_point) : Change the cursor position by bytes as specified by
69 70
the offset, from the reference point. 6. Which of the following file mode opens a file for reading and writing both as well
Example: as overwrite the existing file if the file exists otherwise creates a new file?
fout=open("story.txt","w") a. w b. wb+ c. wb d. rwb
fout.write("Welcome Python")
fout.seek(5) 7. Mr Sharma is working on a binary file and wants to write data from a list to a
print(fout.tell( )) binary file.
fout.close( ) Consider list object as l1, binary file sharma_list.dat, and file object as f.
Which of the following can be the correct statement for him?
Output: a. f = open(‘sum_list’,’wb’); pickle.dump(l1,f)
5 b. f = open(‘sum_list’,’rb’); l1=pickle.dump(f)
c. f = open(‘sum_list’,’wb’); pickle.load(l1,f)
Pickle Module: Python Pickle is used to serialize and deserialize a python object d. f = open(‘sum_list’,’rb’); l1=pickle.load(f)
structure. Any object on python can be pickled so that it can be saved on disk.
8. Every file has its own identity associated with it. Which is known as
Pickling: Pickling is the process whereby a Python object hierarchy is converted into a. icon b. extension c. format d. file type
a byte stream.
9. EOL Stands for :
Unpickling: A byte stream is converted into object hierarchy. a. End of Lines b. End of Line c. End of List d. End of Location
To use the picking methods in a program, we have to import pickle module using
import keyword. 10. Which of the following file types allows to store large data files in the computer
memory?
Example: a. Binary Files b. Text Files c. CSV Files d. None of these
import pickle
In this module, we shall discuss to functions of pickle module, which are:
i. dump( ) : To store/write the object data to the file. 2 Mark Questions
ii. load( ) : To read the object data from a file and returns the object data.
1. Write a program in python to write and read structure, dictionary to the binary
Syntax:
file.
Write the object to the file:
pickle.dump(List_name, file-object ) 2. BINARY file is unreadable and open and close through a function only so what are
Read the object from a file: the advantages of using binary file
pickle.load(file-object) 3. Write a statement to open a binary file name sample.dat in read mode and the file
sample.dat is placed in a folder ( name school) existing in c drive
1 Mark Questions 4. When do you think text files should be preferred over binary files?
1. The process of converting byte stream back to the original structure is known as
5. Consider a binary file employee.dat containing details such as
a. Picklingb. b. Unpickling c. Packing d. Zipping
empno:ename:salary (seperator ':') write a python function to display details of
2. Which file mode is used to handle binary file for reading. those employees who are earning between 20000 and 30000(both values
a. rb b. rw c. r d. w inclusive)
6. Differentiate between pickle.load() and pickle.dump() methods with suitable
3. Which of the following is not a correct statement for binary files? example.
a. Easy for carrying data into buffer 7. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].Write
b. Much faster than other file systems
a user defined function CreateFile() to input data for a record and add to Book.dat
c. Characters translation is not required
d. Every line ends with new line character ‘\n’ 8. A binary file “STUDENT.DAT” has structure (admission_number, Name,
Percentage). Write a function countrec() in Python that would read contents of the
4. Which one of the following is correct statement? file “STUDENT.DAT” and display the details of those students whose percentage is
a. import – pickle b. pickle import c. import pickle d. All the above above 75.
9. A binary file “Store.dat” has structure [ItemNo, Item_Name, Company, Price].
5. Which of the following file mode opens a file for append or read a binary file and Write a function CountRec(Company) in Python which accepts the Company name
moves the files pointer at the end of the file if the file already exist otherwise create as parameter and count and return number of Items by the given Company are
a new file? stored in the binary file “Store.dat”.
a. a b. ab c. ab+ d. a+

71 72
10. A binary file “Store.dat” has structure [ItemNo, Item_Name, Company, 9. A binary file named “TEST.dat” has some records of the structure [TestId,
Price]. Subject, MaxMarks, ScoredMarks] Write a function in Python named
Write a function AddRecord(<List>) which accepts a List of the record [ItemNo, DisplayAvgMarks(Sub) that will accept a subject as an argument and read the
Item_Name, Company, Price] and appends in the binary file “Store.Dat” contents of TEST.dat.

10. Write a python program to search and display the record of the student from
3 mark Questions
1. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price]. a binary file “Student.dat” containing students records (Rollno, Name and Marks).
i. Write a user defined function CreateFile() to input data for a record and add Roll number of the student to be searched will be entered by the user.
to
“Book.dat” . 5 Mark Questions
ii. Write a function CountRec(Author) in Python which accepts the Author name
1. A binary file “student.dat” has structure [rollno, name, marks]. i. Write a
as parameter and count and return number of books by the given Author are stored
user defined function insertRec() to input data for a student and add to student.dat.
in the binary file “Book.dat”
ii. Write a function searchRollNo( r ) in Python which accepts the student’s rollno as
parameter and searches the record in the file “student.dat” and shows the details of
2. A binary file “SCHOOL.DAT” has structure [Roll_Num, Name, Percentage] student i.e. rollno, name and marks (if found) otherwise shows the message as ‘No
record found’.
i) Write a function Count_Rec() in Python that would read contents of the file
“SCHOOL.DAT” and display the details of those students whose percentage is below 2. Write a python program to create binary file dvd.dat and write 10 records in
33 . it Dvd id,dvd name,qty,price Display those dvd details whose dvd price more than
ii) Write a function Disp_Rec(alphabet) in Python that would read contents of the file 25.
“SCHOOL.DAT” and display the details of those students whose name begin with the
alphabet as passed as parameter to the function.
ANSWERS
3. A binary file “STOCK.DAT” has structure [ITEMID, ITEMNAME, QUANTITY, 1 Mark Questions Answers
PRICE]. Write a user defined function MakeFile( )to input data for a record and add 1 A 6 B
to Book.dat. 2 A 7 A
3 D 8 B
4 C 9 B
4. Write a function GetPrice(ITEMID) in Python which accepts the ITEMID as
5 C 10 A
parameter and return PRICE of the Item stored in Binary file STOCK.DAT.
2 Mark Question Answers
5. A binary file “EMPLOYEE.DAT” has structure (EMPID, EMPNAME, SALARY). 1.
Write a function CountRec( ) in Python that would read contents of the file import pickle
“EMPLOYEE.DAT” and display the details of those Employees whose Salary is above d1={'jan':31,'feb':28,'march':31,'april':30}
20000. f=open('binfile.dat','wb+')
pickle.dump(d1,f)
6. A binary file “EMPLOYEE.DAT” has structure (EMPID, EMPNAME, SALARY). d2=pickle.load(f)
print(d2)
Write a function to display number of employees having Salary more than 20000.
f.close()

7. A binary file named “EMP.dat” has some records of the structure [EmpNo, 2. Binary file are easier and faster than text file. Binary files are also used to
EName, Post, Salary], Write a user-defined function named NewEmp() to input the store binary data such as images, video files, and audio files.
details of a new employee from the user and store it in EMP.dat. 3. f1=open(“c:\school\sample.dat”,’r’)

8. Write a user-defined function named SumSalary(Post) that will accept an 4. Text file should be preferred when we have to save data in text format and
argument the post of employees & read the contents of EMP.dat and calculate the security of file is not important
SUM of salary of all employees of that Post. 5.
def Readfile():

73 74
i=open( “Employee.dat” , “rb+”) rec=pickle.load(fobj)
x=i .readline() if Author==rec[2]:
while(x): num = num + 1
I= x.split(‘:’)
except:
if ( (float (I[2]) >=20000) and (float I[2])<=40000):
print(x) fobj.close()
x= i.readline() return num
6.
dump( ) : To store/write the object data to the file. 10.
load( ) : To read the object data from a file and returns the object data. def AddRecord(rec):
Syntax: print (“Record to be Added is”,rec)
Write the object to the file: pickle.dump(rec,fobj)
pickle.dump(List_name, file-object ) fobj.close()
Read the object from a file:
pickle.load(file-object)
3 Mark questions answers
7.
import pickle 1.
def createFile(): import pickle
def createFile():
fobj=open("Book.dat","ab") f=open("Book.dat","ab")
BookNo=int(input("Book Number : ")) BookNo=int(input("Book Number : "))
Book_name=input("Name :") Book_name=input("Name :")
Author = input(“Author: “) Author = input("Author:" )
Price = int(input("Price : ")) Price = int(input("Price : "))
rec=[BookNo,Book_Name,Author,Price] rec=[BookNo,Book_Name,Author,Price]
pickle.dump(rec,fobj) pickle.dump(rec,f)
fobj.close() f.close()

8. def CountRec(Author):
import pickle f=open("Book.dat","rb")
def CountRec(): num = 0
fobj=open("STUDENT.DAT","rb") try:
num = 0 while True:
try: rec=pickle.load(f)
while True: if Author==rec[2]:
rec=pickle.load(fobj) num = num + 1
if rec[2] > 75: except:
print(rec[0],rec[1],rec[2],sep="\t") f.close()
num = num + 1 return num
except:
fobj.close()
return num
2.
9. import pickle
import pickle def CountRec():
def CountRec(Cname): fobj=open("SCHOOL.DAT","rb")
fobj=open("store.dat","rb") num = 0
num = 0 try:
try: while True:
while True: rec=pickle.load(fobj)

75 76
if rec[2] < 33: num=num+1
print(rec[0],rec[1],rec[2],sep="\t") except:
num = num + 1 fobj.close()
return num
except:
fobj.close() 6. import pickle
return num def CountRec():
import pickle fobj=open("EMPLOYEE",'rb')
def Disp_Rec(alpha): num=0
fobj=open("SCHOOL.DAT","rb") try:
num = 0 while True:
try: rec=pickle.load(fobj)
while True: if(rec[2]>20000):
print(rec[0],rec[1],rec[2])
rec=pickle.load(fobj)
num=num+1
if rec[1][0] == alpha : except:
print(rec[0],rec[1],rec[2],sep="\t") fobj.close()
except: return num
fobj.close()
7.
3. import pickle
def MakeFile():
fobj=open("STOCK.DAT",'ab')
itemid=input("Enter ITEM ID")
itemname=input("Enter name of the Item")
Q=int(input("Enter the quantity of Item"))
price=float(input("Enter the price"))
rec=[itemid,itemname,Q,price]
pickle.dump(rec,fobj)
fobj.close()

4. def GetPrice(ITEMID):
fobj=open("STOCK.DAT",'rb')
try:
while True:
rec=pickle.load(fobj)
if(rec[0]in str(ITEMID)):
print("Price of ", rec[0], "item is",rec[3])
return rec[0]
except:
8.
fobj.close()

5. import pickle
def CountRec():
fobj=open("EMPLOYEE",'rb')
num=0
try:
while True:
rec=pickle.load(fobj)
if(rec[2]>20000):
print(rec[0],rec[1],rec[2])
77 78
def insertRec():
f=open("student.dat","ab")
rollno = int (input("Enter Roll Number : "))
name=input("Enter Name :")
marks = int(input("Enter Marks : "))
rec = [rollno, name, marks ]
pickle.dump( rec, f ) f.close()

ii. def searchRollNo( r ):


f=open("student.dat","rb")
flag = False
while True:
try:
rec=pickle.load(f)
if rec[0] == r :
9. print(rec[‘Rollno’])
print(rec[‘Name’])
print(rec[‘Marks])
flag = True
except EOFError:
break
if flag == False:
print(“No record Found”)
f.close()

2
import pickle
f=open("pl.dat","ab")
ch="Y"

10. while ch=="Y":


import pickle l=[]
f1 = open("E:\Student.dat", "rb")
Stud_rec = pickle.load(f1) pi=int(input("enter dvd id "))
rno = int(input(“Enter the roll no to search: ”))
pnm=input("enter dvd name ")
flag = 0
for r in Stud_rec: sp=int(input("enter qty "))
if rno == r[0]:
print (rollno, name, marks) p=int(input("enter price(in rupees) "))
flag = 1 l.append(pi)
if flag == 0:
print(“Record not found…”) l.append(pnm)
f1.close() l.append(sp)
l.append(p)
pickle.dump(l,f)
5 Mark Questions answers
ch=input("do you want to enter more rec(Y/N): ").upper()
1
if ch=="Y":
i. import pickle

79 80
continue import csv
else: with open('C:\\data.csv','rt') as f:
break data = csv.reader(f) #reader function to generate a reader object

f.close() for row in data:

f=open("pl.dat","rb+") print(row)

try:
while True: OUTPUT:
['Roll No.', 'Name of student', 'stream', 'Marks']
l=pickle.load(f)
['1', 'Anil', 'Arts', '426']
if l[3]>25:
['2', 'Sujata', 'Science', '412']
print(l)
except EOFError:
Write data to a CSV file:
pass
When we want to write data in a CSV file you have to use writer( ) function.
f.close()
To iterate the data over the rows (lines), you have to use the writerow( ) function.

Working with CSV Files: CSV (Comma Separated Values)


CODE:
import csv
A csv file is a type of plain text file that uses specific structuring to arrange tabular
with open('C:\\data.csv', mode='a', newline='') as file:
data. csv is a common format for data interchange as it is compact, simple and
writer = csv.writer(file, delimiter=',', quotechar='"' ) #write new record in file
general.
writer.writerow(['3', 'Shivani', 'Commerce', '448'])
Each line of the file is one line of the table.
writer.writerow(['4', 'Devansh', 'Arts', '404'])
csv files have .csv as file extension.

OUTPUT:
Let us take a data.csv file which has the following contents:
['Roll No.', 'Name of student', 'stream', 'Marks']
Roll No., Name of student, stream, Marks
['1', 'Anil', 'Arts', '426']
1, Anil, Arts, 426
['2', 'Sujata', 'Science', '412']
2, Sujata, Science, 412
['3', 'Shivani', 'Commerce', '448']
['4', 'Devansh', 'Arts', '404']
As you can see each row is a new line, and each column is separated with a comma.
This is an example of how a CSV file looks like.
When we shall open the file in notepad (Flat file) then the contents of the file will look
To work with csv files, we have to import the csv module in our program.
like this:
Roll No.,Name of student,stream,Marks
Read a CSV file:
1,Anil,Arts,426
To read data from a CSV file, we have to use reader( ) function. The reader function
2,Sujata,Science,412
takes each row of the file and make a list of all columns.
3,Shivani,Commerce,448
CODE:
81 82
4,Devansh,Arts,404 import csv
with open("user_info.csv", "w") as obj:
For Practical Explanation
fileobj = csv.writer(obj)
Program-1:-Write a program to perform read and write operation with .csv file. fileobj.writerow(["User Id", "password"])
while(True):
CODE: user_id = input("enter id: ")
import csv password = input("enter password: ")
def readcsv(): record = [user_id, password]
with open('C:\\data.csv','rt')as f:
fileobj.writerow(record)
data = csv.reader(f) #reader function to generate a reader object
for row in data: x = input("press Y/y to continue and N/n to terminate the program\n")
print(row) if x in "Nn":
break
def writecsv( ): elif x in "Yy":
with open('C:\\data.csv', mode='a', newline='') as file: continue
writer = csv.writer(file, delimiter=',', quotechar='"') #write new record in file with open("user_info.csv", "r") as obj2:

writer.writerow(['4', 'Devansh', 'Arts', '404']) fileobj2 = csv.reader(obj2)


given = input("enter the user id to be searched\n")
for i in fileobj2:
print("Press-1 to Read Data and Press-2 to Write data: ")
a=int(input()) next(fileobj2)
if a==1: # print(i,given)
readcsv() if i[0] == given:
elif a==2:
print(i[1])
writecsv()
else: break
print("Invalid value") OUTPUT:
enter id: cbse
OUTPUT: enter password: 123
press Y/y to continue and N/n to terminate the program
Press-1 to Read Data and Press-2 to Write data: 1 y

['Roll No.', 'Name of student', 'stream', 'Marks'] enter id: computer_science

['1', 'Anil', 'Arts', '426'] enter password: python


press Y/y to continue and N/n to terminate the program
['2', 'Sujata', 'Science', '412']
n
['3', 'Shivani', 'Commerce', '448']
enter the user id to be searched
['4', 'Devansh', 'Arts', '404']
cbse
123
Program-2:- CreateaCSVfilebyenteringuser-
>>>
idandpassword,readandsearchthepasswordforgivenuser-id. Sample Questions & Answers
CODE:
83 84
1. What does the acronym CSV stand for in its full form?
a. Common Separated Value for item in csv_reader:
b. Comma System Value print(item)
c. Comma Separated Value
d. Common System Vault a. The individual value data that is separated by the delimiter
Ans: c. Comma Separated Value b. The row data as a list
c. The column data as a list
2. What is the default delimiter of a CSV file d. The full line of the file as a string
a. Tab
b. Comma Ans: b. The row data as a list.
c. Semicolon
d. Space
7. Case study Question-
Ans: b. Comma
Neha is making software on “Items & their prices” in which various records are to be
3. In regards to separated value files such as .csv and .tsv, what is the delimiter? stored/retrieved in STORE.CSV data file. It consists some records (Item & Price).
a. Any character such as the comma (,) or tab (\t) that is used to separate She has written the following code in python. As a programmer, you have to help her
the row data to successfully execute the program.
b. Anywhere the comma (,) character is used in the file
c. Delimiters are not used in separated value files import ___________ # Statement-1
d. Any character such as the comma (,) or tab (\t) that is used to separate def AddItem(Item, Price) ___ # Statement-2
the column data. f=open(“STORE.CSV”, ___ ) # Statement-3
fw=csv.writer(f)
Ans: d. Any character such as the comma (,) or tab (\t) that is used to separate fw.writerow([Item, Price])
the column data. ____________ # Statement-4

4. In separated value files such as .csv and .tsv, what does the first row in the file def ShowRecord():
typically contain? with open(“STORE.CSV”,”r”) as NI:
a. The source of the data NewItem=csv._______ (NI) # Statement-5
b. The author of the table data for rec in NewItem:
c. Notes about the table data print(rec[0], “#”, rec[1])
d. The column names of the data
#main-code
Ans: d. The column names of the data AddItem(“Sugar”, 38.00)
AddItem(“Rice”, 48.50)
5. Assume you have a file object my_data which has properly opened a separated ShowRecord() # Statement-6
value file that uses the tab character (\t) as the delimiter.
What is the proper way to open the file using the Python csv module and assign it Q1. Which module should be imported in Statement-1.
to the variable csv_reader? A. pickle B. csv C. file D. text
Assume that csv has already been imported.
a. csv_reader = csv.tab_reader(my_data) Ans: B. csv
b. csv_reader = csv.reader(my_data)
c. csv_reader = csv.reader(my_data, tab_delimited=True) Q2. Which file mode to be passed to add new record in Statement-3.
d. csv_reader = csv.reader(my_data, delimiter='\t') A. w+ B. w C. wb D. a

Ans: d. csv_reader = csv.reader(my_data, delimiter='\t') Ans: D. a

6. When iterating over an object returned from csv.reader(), what is returned with Q3. What should be written in Statement-4 to close the file?
each iteration? A. close() B. fw.close() C. f.close() D. csv.close()
For example, given the following code block that assumes csv_reader is an
object Ans: C. f.close()
returned from csv.reader(), what would be printed to the console with each
iteration? Q4. Which function to be used in Statement-5 to read the data from a csv
85 86
file. 18
A. read() B. readline() C. readlines() D. reader() 32
top
(c) Push ‘18’
Ans: D. reader()

Q5. Output after executing Statement-6 will be - 32


Top=None top
(a) Stack empty (b) Push ‘32’
A. (“Sugar”, “38.0”) B. Sugar 38.0
(“Rice”, “48.50”) Rice 48.0 18 29
Element at the element
C. Sugar, 38.0 D. Sugar # 38.0 Top popped popped
Rice, 48.50 Rice # 48.50
Ans: D. Sugar # 38.0 29
top
Rice # 48.50 32 32 32
(d) Pop 1 top
top
element (f) Pop 1 element
(e) Push 29
Data Structure: Stack, operations on stack (push & pop), implementation
of stack using list Stack is a dynamic data structure as it grows (with an increase in the number of
Introduction : elements) or shrinks (with a decrease in the number of elements). A static data
structure is the one that has fixed size.
Data structures : A data structure is a named group of data of different data types
which is stored in a specific way and can be processed as a single unit. It has well- Implementation of Stack using List
defined operations, behavior and properties.
The basic operations performed on the Stack are:
Stack : It is a linear structure implemented in LIFO (Last In First Out) manner where 1. Creating a Stack
insertions and deletions are restricted to occur only at one end – stack’s top. 2. PUSH Operation / Adding Elements to a Stack
3. Pop Operation / Deleting Elements from a Stack
LIFO means element last inserted would be the first one to be deleted. 4. Traversal / Displaying a Stack.
For example, a pile of books, a stack of coins, where you can remove only the top Checking the Status of Stack : Before implementing these operations, it is
book or the coin placed at the top (Fig.1). important to check Stack status.

1. Creating a Stack
To create an empty Stack, use inbuilt function list() or [] as per the syntax given
Fig.1 : Pile of Books / Stack of Coins below:
Some of the applications of Stack in real life Syntax :
are: Stack=list()
• Pile of clothes in an almirah. Stack=[]
• Multiple chairs in a vertical pile In order to access the elements in a Stack, index values are used. Thus, the first
• Bangles worn on wrist element in the Stack will be Stack[0], and so on.
• Pile of boxes of eatables in a pantry or on a kitchen shelf
2. PUSH Operation adding Elements into a Stack
The list function append() is used to add elements into the Stack.
Stack follows these rules : Syntax:
1) Data can only be removed from the top (pop). The removal of element from a Stack.append(x)
stack is called POP operation. Here, x is the element to be inserted into the Stack and is inserted at the end of the
2) A new data element can only be added to the top of the stack (push). The list implemented as a Stack.
insertion of element in a stack is called PUSH operation. peek() :peek() function is used to get the most recent value of stack, i.e., top
element of the stack without removing it or value at the top. It will throw an
Following figure illustrates the operations on a stack. exception if the stack is empty or null.

3. Pop Operation/Deleting an Element from a Stack


The list function pop() is used to pop / remove/delete elements from a Stack.
Syntax :
Stack.pop()
87 88
It returns the popped / deleted elements from the list. if letter not in Stack:
Stack.append(letter)
4. Traversing /displaying Stack Elements print(Stack)
In this process the elements from the top position, i.e., last inserted element, get print("The number of different vowels present in ",word," is ",len(Stack))
displayed and processed in the reverse order.

Applications of Stacks Practical Implementation – 3


1. Reversing a Word/Line.
2. The compilers use Stacks to store the previous state of a program when a function Write a program in Python to implement the following operation on Stack
is called or during recursion. containing employee code and name. 1. PUSH 2. POP 3. DISPLAY
3. Backtracking : Backtracking is a form of recursion. But it involves choosing only employee = []
one option out of possibilities. It is used in large number of puzzles like Sudoku and choice = 'y'
in optimization problems such as knapsack. while (choice=='y' or choice=='Y'):
4. Undo Mechanism in text Editors. print("1. PUSH")
print("2. POP")
Practical Implementation-1 print("3. DISPLAY STACK")
choice1 = int(input("Enter any choice: "))
Write a Python program to implement all basic operations of a Stack, such if(choice1==1):
as adding element, removing element and displaying the Stack elements e_id= input('Enter employee code ')
using lists. ename=input('Enter name ')
s=[] emp = (e_id, ename)
c="y" employee.append(emp)
while (c=="y"): elif(choice1==2):
print("1. PUSH") if len(employee)==0:
print("2. POP") print('Stack empty')
else:
print("3. Display") e_id, ename = employee.pop()
choice=int(input("Enter your choice: ")) print('Deleted element is ',e_id, ename)
if (choice==1): elif(choice1==3):
a = input("enter any number :") top = len(employee)
s.append(a) while top>0:
elif (choice==2): print(employee[top-1])
if (s==[]): top = top -1
print("Stack Empty") else:
else: print('Wrong Input')
print("Deleted element is : ",s.pop()) choice = input('Do you want to continue? y or n: ')
elif (choice==3):
l=len(s)
MCQ / Short Answer Type Question – 1 Mark
for i in range(l-1,-1,-1):
1. Choose the correct output for the following stack operation(* top position)
print(s[i])
Push(5) Push(8) Pop() Push(2) Push(5) Pop() Push(1)
else:
(a) 8 5 2 5 1* (b) 8 5 5 2 1* (c) 2 5 5 1* (d) 5 2 1*
print("Wrong Input")
2. Which list method can be used to perform Push operation in a stack implemented
c=input("Do you want to continue or not?")
by list?
(a) append() (b) extend() (c) push() (d) insert()
Practical Implementation – 2
3. Which list method can be used to perform Pop operation in a stack implemented
by list?
Write a program to display unique vowels present in the given word using
(a) pop() (b) pop(1) (c) remove() (d) pop(0)
Stack.
4. Consider the following operation performed on a stack of size 3, What will be the
vowels=['a','e','i','o','u']
output? (* top position)
word=input("Enter the word to search for vowels :")
Push(10) Push(20) Push(30) Pop() Push(40) Push(50)
Stack=[]
(a) overflow (b) underflow (c) 10 20 30 40 50* (d) 10 20 40 50*
for letter in word:
5. What is the situation called when an insertion is attempted in a full Stack?
if letter in vowels:
89 90
6. What is the situation called when read/deletion is attempted in an empty Stack? 1. Write a function in Python PUSH_IN(L), where L is a list of numbers. From this
7. LIFO data structure is?
list, push all even numbers into a stack which is implemented by using another list.
8. Name the operation for insertion in a stack.
9. Name the operation for deletion from a stack.
10. Define Stack. 2. Write a function in Python POP_OUT(Stk), where Stk is a stack implemented by
Short Long Answer Type Question – 2 Marks a list of numbers. The function returns the value which is deleted/popped from the
1. Write some applications of stack. stack.
2. Consider STACK=[‘a’,’b’,’c’,’d’]. Write the STACK content after each operations:
a) STACK.pop( )b) STACK.append(‘e’) c) STACK.append(‘f’) d) STACK.pop( ) 3. Write a function in Python PUSH(Arr), where Arr is a list of numbers. From this list
3. Write a program to implement a stack for the students(studentno, name). Just push all numbers divisible by 5 into a stack implemented by using a list. Display the
implement Push. stack if it has at least one element, otherwise display appropriate error message.
4. Given a bounded stack of capacity 4 which is initially empty, write the stack content
4. Write a function in Python POP(Arr), where Arr is a stack implemented by a list of
after each steps:
numbers. The function returns the value deleted from the stack.
a) Push ‘1’ b) Push ‘2’ c) Push ‘3’ d) Push ‘4’ e) Pop f) Pop
g) Push(‘5’) h)Pop i)Pop j)Pop 5. Write a function in python, PushEl(e) to add a new element and PopEl(e) to delete
5. What is Stack? What basic operations can be performed on them? a element from a List ,considering them to act as push and pop operations of the
6. Find the output of the following code: Stack data structure .
result=0
numberList=[10,20,30] 6. Write a function POP(Book) in Python to delete a Book from a list of Book titles,
numberList.append(40) considering it to act as a pop operation of the Stack data structure.
result=result+ numberList.pop()
result=result+ numberList.pop() 7. Julie has created a dictionary containing names and marks as key value pairs of 6
print(result) students. Write a program, with separate user defined functions to perform the
print(numberList) following operations:
7. Find the output of the following code:
answer=[] ● Push the keys (name of the student) of the dictionary into a stack, where the
output=’ ‘ corresponding value (marks) is greater than 75.
answer.append(‘T’)
● Pop and display the content of the stack.
answer.append(‘A’)
answer.append(‘M’) For example: If the sample content of the dictionary is as follows:
ch=answer.pop()
output=output+ch R={"OM":76, "JAI":45, "BOB":89, "ALI":65, "ANU":90, "TOM":82}
ch=answer.pop()
output=output+ch The output from the program should be: TOM ANU BOB OM
ch=answer.pop()
output=output+ch 8. Alam has a list containing 10 integers. You need to help him create a program with
print(“Result=”,output) separate user defined functions to perform the following operations based on this list.

8. What is backtracking? What is the use of it? ● Traverse the content of the list and push the even numbers into a stack.

● Pop and display the content of the stack.


9. Find the output of the following code:
stack =["Amar", "Akbar", "Anthony"] For Example: If the sample Content of the list is as follows:
stack.append("Ram")
stack.append("Iqbal") N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
print(stack)
print(stack.pop()) Sample Output of the code should be: 38 22 98 56 34 12
print(stack)
print(stack.pop()) 9. Coach Abhishek stores the races and participants in a dictionary. Write a program,
print(stack) with separate user defined functions to perform the following operations:
10. What is the use of peek() function?
Push the names of the participants of the dictionary onto a stack, where the distance
Long Answer Type Question – 3 Marks is more than 100.

91 92
Pop and display the content of the stack. a) colour==[]: b) colour.isEmpty(): c) len(colour)=0: d) None of the above
(iv) Fill in the statement to delete an element from the stack?
For example: If the sample content of the dictionary is as follows: a) colour.pop(1) b) colour.pop() c) del colour[1] d) colour.delete(1)
(v) Fill the statement 5, to call pop function
Races ={100:'Varnika', 200 :'Jugal', 400:'Kushal', 800:'Minisha'}} a) pop(c)b) pop(colour) c) call pop(colour) d) def pop(colour)
The output from the program should be: Minisha Kushal Jugal
2. Based on the below given code, Write answer to the following questions i to v.
10. Reva has created a dictionary containing Product names and prices as key value course_dict = {'BSC':8000, 'MSC':12000, 'BCA':15000, 'PGDCA':9000,
pairs of 4 products. Write a user defined function for the following: 'MCA':30000, 'MBA':50000 }
STACK = [ ]
● PRODPUSH() which takes a list as stack and the above dictionary as the def NEWDATA():
parameters. course = input('Enter course name :')
fee = int(input('Enter fee '))
Push the keys (Pname of the product) of the dictionary into a stack, where the ______________ #statement 1
corresponding price of the products is less than 6000. Also write the statement to print('Data saved successfully ')
call the above function. print(course_dict)
def PUSH():
for key in course_dict:
if ____________ > 10000: #statement 2
For example: If Reva has created the dictionary is as follows: STACK.__________ #statement 3
Product={"TV":10000, "MOBILE":4500, "PC":12500, "FURNITURE":5500} def POP():
if ___________==0: #statement 4
The output from the program should be: [ ‘FURNITURE’, ‘MOBILE’] print('STACK EMPTY, No course with fee>10000')
else:
print('course fee more than 10000')
Case Based Questions – 5 Marks for top in range(len(STACK), 0, -1):
1. Based on the below given code, Write answer to the following questions i to v print(__________) #statement 5
#function definition NEWDATA()
def push(colour,n): PUSH()
------------------------------# statement1 POP()
#function calling Consider a dictionary with keys as course name and fee as value. Write a program
colour=[] to push course name in stack where fee is more than 10000. Pop and display
c=['red','blue','violet','white','black'] contents of stack on the screen
for i in range(0,len(c),2): i) Write a code to add the fee and course name to course_dict.
…………………………# statement2 ii) Complete the code to compare the fee of the given key(course).
print(colour[::-1]) iii) Write a code to insert the element in the Stack.
#function definition iv) Write a code to find the length of the Stack.
def pop(colour): v) Write a code to delete the element of the Stack..
if ………………………………..#statement 3
return "underflow" ANSWER KEY
else: MCQ / Short Answer Type Question – 1 Mark
return ……………………..#statement 4 1.(d) 5 2 1* 2. (a) append() 3. (a) pop() 4. (a) overflow
#function calling 5. Overflow 6. Underflow 7. STACK 8. PUSH
for i in range(len(colour)+1): 9. POP
print(………………………….)#statement 5 10. It is a linear structure implemented in LIFO (Last In First Out) manner where
(i)Identify the suitable code for statement 1? insertions and deletions are restricted to occur only at one end – stack’s top.
a) colour.insert(len(colour),n)
b) colour.append(len(colour),n) Short Long Answer Type Question – 2 Marks
c) colour.append() 1. Reversing a string, compilers use stack to store previous state of program, undo
d) colour.extend() mechanism in text editors and backtracking.
(ii) Identify the suitable code for statement 2? 2. a) ['a', 'b', 'c']
a) push(colour,c[i]) b) push(colour) c) push(c[i]) d) push(colour,i) b) ['a', 'b', 'c',’e’]
(iii) Identify the suitable code for statement 3? c) ['a', 'b', 'c',’e’,’f’]

93 94
d) ['a', 'b', 'c',’e’] if stk==[]:
3. Ans: Program for push operation in a stack return True
stk=[] else:
top=-1 return False
def PUSH(stk,student): def POP_OUT(stk):
stk.append(student) if isEmpty(stk): # verifies whether the stack is empty or not
top=len(stk)-1 print("Stack Underflow")
sno=int(input(“Enter student No:”)) else: # Allow deletions from the stack
sn=input(“Enter student Name:”) item=stk.pop()
data=[sno,sn] if len(stk)==0:
PUSH(stk,data) top=-1
4. a) stack=[‘1’] b) stack=[‘1’,’2’] c) stack=[‘1’,’2’,’3’] else:
d) stack=[‘1’,’2’,’3’,’4’] top=len(stk)
e) stack=[‘1’,’2’,’3’] f) stack=[‘1’,’2’] g) stack=[‘1’,’2’,’5’] return item
h) stack=[‘1’,’2’] i) stack=[‘1’] j) stack=[]
5. Stack is a linear structure implemented in LIFO (Last In First Out) manner where 3.
insertions and deletions are restricted to occur only at one end – stack’s top.
Following basic operations can be performed on Stack. def PUSH(Arr,value):
(i) PUSH, i.e., insertion of element in the Stack.
(ii) POP, i.e., deletion of an element from the Stack. s=[]
(iii) Traversal , i.e., displaying all the elements of the Stack.
for x in range(0,len(Arr)):
6. 70
[10,20] if Arr[x]%5==0:
7. Result=MAT
8. Backtracking is a form of recursion. But it involves choosing only one option out s.append(Arr[x])
of possibilities. It is used in large number of puzzles like Sudoku and in optimization
problems such as knapsack. if len(s)==0:
9.
['Amar', 'Akbar', 'Anthony', 'Ram', 'Iqbal'] print("Empty Stack")

Iqbal else:
['Amar', 'Akbar', 'Anthony', 'Ram']
print(s)
Ram
4.
['Amar', 'Akbar', 'Anthony']
10. peek() function is used to get the most recent value of stack, i.e., top element def popStack(st) : # If stack is empty
of the stack without removing it or value at the top. It will throw an exception if
if len(st)==0:
the stack is empty or null.
print("Underflow")
Long Answer Type Question – 3 Marks
else:
1. top=-1
L = len(st)
stk=[]
val=st[L-1]
def PUSH_IN(L): # Allow additions to the stack
for i in L: print(val)
if i%2==0:
st.pop(L-1)
stk.append(i)
top=len(stk)-1
5.
2.
def PushEl(element):
def isEmpty(stk): # checks whether the stack is empty or not
a=int(input("enter package title : "))
95 96
element.append(a) break
def PopEl(element): 9.
if (element==[]):
Races ={100:'Varnika',200:'Jugal', 400:'Kushal',800:'Minisha'}
print( "Stack empty")
def PUSH(Stk,N):
else:
Stk.append(N)
print ("Deleted element:", element.pop())
def POP(Stk):
6.
if Stk!=[]:
def POP(Book): return Stk.pop()
if (Book ==[]):
else:
print(“Stack empty”)
return None
else:
stack1=[]
print(“Deleted element :”) for i in Races:
Book.pop() if i>=200:
7.
PUSH(stack1,Races[i])
R={"OM":76, "JAI":45, "BOB":89, "ALI":65, "ANU":90, "TOM":82} while True:
def PUSH(S,N):
if stack1!=[]:
S.append(N)
print(POP(stack1),end=" ")
def POP(S): else:
if S!=[]:
break
return S.pop()
else: 10.
return None
Product={"TV":10000, "MOBILE":4500, "PC":12500, "FURNITURE":5500}
ST=[] stack=[]
for k in R:
def PRODPUSH(stack, P):
if R[k]>=75:
for k in Product:
PUSH(ST,k) if P[k]<6000:
while True:
stack.append(k)
if ST!=[]:
print(POP(ST),end=" ")
PRODPUSH(stack, Product)
else:
print(stack)
break
Case Based Questions – 5 Marks
8.
1. (i). a colour.insert(len(colour),n)
N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
(ii). a push(colour,c[i])
def PUSH(S,N): (iii).a colour==[]
S.append(N)
(iv). b colour.pop()
def POP(S):
(v). b pop(colour)
if S!=[]:
return S.pop() 2. i) course_dict[course] = fee
ii) course_dict[key]
else:
iii) append(key)
return None iv) len(STACK)
ST=[] v) STACK.pop()

for k in N:
if k%2==0:
PUSH(ST,k) Unit II: Computer Networks
while True:
a. Evolution of networking: introduction to computer networks, evolution of
if ST!=[]: networking (ARPANET, NSFNET, INTERNET)
print(POP(ST),end=" ")
b. Data communication terminologies: concept of communication, components of
else: data communication (sender, receiver, message, communication media,
97 98
protocols), measuring capacity of communication media (bandwidth, data Switching Techniques
transfer rate), IP address, switching techniques (Circuit switching, Packet
switching) Circuit switching is a switching method where an end-to-end path is created
Point wise notes/Key Points/ Summary between two stations within a network before starting the data transfer.

A system of interconnected computers and computerized peripherals such as printers Packet switching is the transfer of small pieces of data across various networks.
is called computer network. This interconnection among computers facilitates These data chunks or “packets” allow for faster, more efficient data transfer.
information sharing among them. Computers may connect to each other by either Often, when a user sends a file across a network, it gets transferred in smaller
wired or wireless media. data packets, not in one piece.
Network Applications
Computer systems and peripherals are connected to form a network. They provide One marks Questions
numerous advantages: 1) ARPANET stands for ____________________.
• Resource sharing such as printers and storage devices 2) Give any two advantages of computer network.
• Exchange of information by means of e-Mails and FTP 3) Give any two disadvantages of computer network.
• Information sharing by using Web or Internet 4) NFSNET stands for _____________________.
• Interaction with other users using dynamic web pages 5) TCP / IP stands for _____________________.
• IP phones 6) Which one is not a part of data communication.
• Video conferences a. Sender d. Protocol
• Parallel computing b. Receiver e. None of these
• Instant messaging c. Message
7) ISP stands for________________________.
ARPANET, in full Advanced Research Projects Agency Network, experimental 8) What is a protocol?
computer network that was the forerunner of the Internet. The Advanced Research 9) LAN stands for _______________________.
Projects Agency (ARPA), an arm of the U.S. Defense Department, funded the 10) Telephone network is an example of __________.
development of the Advanced Research Projects Agency Network (ARPANET) in the a. Circuit Switching c. Message Switching
late 1960s. Its initial purpose was to link computers at Pentagon-funded research b. Packet Switching d. All of these
institutions over telephone lines. 11) 1 kbps = ________ bps.
12) Modem stands for ______________.
NSFNET: A variety of regional research and education networks, supported in part 13) Circuit switching requires a dedicated path. (True / False)
by NSF, were connected to the NSFNET backbone, thus extending the Internet’s reach 14) Packet switching is more efficient because the cost of the link is shared
throughout the United States. by many users. (True / False)
15) Out of the following which is the fastest wired medium of
communication.
INTERNET Infrared, Coaxial cable, Ethernet Cable, Microwave, Optical Fiber.
The Internet is a collection of computers connected by network cables or through 16) Out of the following which is the fastest wireless medium of
satellite links. Rather than connecting every computer on the Internet with every communication.
other computer, individual computers in an organization are normally connected Infrared, Coaxial cable, Ethernet Cable, Microwave, Optical Fiber.
in a local area network (LAN). One node on this local area network is physically 17) Name the protocol that is used to send emails.
connected to the Internet. So, the Internet is a network of networks. 18) Which communication medium is to be suggested for very effective
and fast communication in guided medium?
PROTOCOL
Two marks Questions
A network protocol is an established set of rules that determine how data is 1) Define a network. What is its need?
transmitted between different devices in the same network. Essentially, it allows 2) What is a network? What are its goals and applications.
connected devices to communicate with each other, regardless of any differences 3) Write any two advantages and disadvantages of network.
in their internal processes, structure or design. Network protocols are the reason 4) Rearrange the following terms in increasing order of data transfer rates.
you can easily communicate with people all over the world, and thus play a critical Gbps, Kbps, Mbps, Tbps, Bps, Kbps
role in modern digital communications. 5) What is a protocol? Name some commonly used protocols.
6) How many switching techniques are there? Explain any one with example.
An IP address is a unique address that identifies a device on the internet or a local
7) Define baud, bps and Bps. How are these interlinked?
network. IP stands for "Internet Protocol," which is the set of rules governing the
8) Why we used HTTP protocol.
format of data sent via the internet or local network.
9) Why packet switching is more efficient than circuit switching?
10) Rakshana, a class Xi student, has just started understanding the basics of internet and web
99 100
technologies. She is a bit confused about the terms “World Wide Web” and “Internet”. Help her 5) Expand the POP protocol. (1 Marks)
to understand both the terms with the help of suitable example of each.
11) Define the following terms. Summary:
a. Baud A system of interconnected computers and computerized peripherals such as
b. Communication Channel printers is called computer network. This interconnection among computers facilitates
12) Computer network is made from computers only, Justify the sentence. information sharing among them. Computers may connect to each other by either
13) Protocols are more important in the computer network because they help to control computer wired or wireless media. To connect we require protocols, Switching technology,
network. Is it true or false? Give the proper reason for true or false. communication media and structure of computer network. We can use computer
Three marks Questions network in Resource sharing such as printers and storage devices, Information
1) Describe the role of ARPANET and NSFNET in evolution of network. sharing by using Web or Internet and Interaction with other users using dynamic web
2) Differentiate the Analog and Digital modes of data transmission using real time applications. page.
3) List and explain the components of Data Communication.
4) Neha is confused in the working process of landline Telephone Network and Mobile Network. Answers :
Kindly help her to explain Circuit switching and Packet switching with proper examples.
5) Where we can used packet switching? Explain the packet switching with example. One Marks questions:
6) What is TCP/IP? How FTP is different from HTTP? 1) Advanced Research Project Agency Network
7) Expand the below terms regarding protocol. (Any 6) 2) Resource sharing, Reliability of data or any related it.
a. HTTP d. IMAP g. POP 3) Cost of setup, Threat to Data Security or any related it.
b. PPP e. FTP h. IP 4) National Science Federation Network
c. SMAP f. TCP/IP 5) Transmission Control Protocol over Internet Protocol
8) Define the below terminology of networks. 6) E. none of these 13) True
a. Server 7) Internet Service Provider 14) True
b. IP Address 8) 1 mark for correct definition 15) Optical Fiber
c. Domain Name 9) Local Area Network 16) Microwave
10) A. Circuit Switching 17) IMAP, POP
Case Study 1 11) 1024 18) Optical Fiber
Kiran has started a business all over India and he wants to establish a network among its offices and 12) Modulator Demodulator
branches. Help him to choose various communication media as per requirement.
Head Office: Ahmedabad, Gujarat, 10 Computers Case Study 1
Branch 1: Delhi, 50 Computers 1) Fiber Optic Cable
Branch 2: Mumbai, 100 Computers 2) Co-axial cable or Twisted Pair Cable
Branch 3: Kolkata, 100 Computers 3)
a. Guided Media
1) Kiran wants high speed network in Branch 1, Delhi. Which cable he has to used to provide i. Fiber Optic
maximum speed among computers. (1 Marks) ii. Co-axial
2) Kiran has low budget in Branch 2, Mumbai. Which cable he has to use to keep low cost network b. Unguided Media
establishment. (1 Marks) i. Radio Wave
3) Kiran does not know about guided or unguided media. Kindly help him to classify the below ii. Micro Wave
media into Guided and Unguided media. (2 Marks) 4) Satellite Link
a. Fiber Optic Case Study 2
b. Radio wave 1) IMAP, POP 4) FTP
c. Co-axial 2) HTTP 5) Post Office Protocol
d. Microwave 3) HTTPS
4) Kiran wants to connect Head office with all branches. Which communication media he has to
used to connect head office with all branches. (1 Marks)
Case Study 2 TRANSMISSION MEDIA ( 1 Mark questions )
Jinesh is studying in one of the popular Hardware and Networking institute. He already learned
Network Topology, Types of Network and Communication media. He has just started to learn about 1. How many type of transmission media are there? List the types.
protocol. Kindly help him to learn protocols with below question answers. Ans: Two types: Wired and Wireless.
1) Which protocol is used to send or receive emails? (1 Marks) 2. List wired media.
2) Which protocol is used to surf the web? (1 Marks) Ans: Twisted Pair, Coaxial, Fibre Optics cable.
3) Which protocol is used to surf the web securely? (1 Marks) 3. List Wireless Media.
4) Which protocol is used to send or receive the files? (1 Marks) Ans: Bluetooth, Infrared, Wi-Fi, Radio waves, Satellite Link.
101 102
4. What is the maximum distance to which twisted pair cable can send data? • Can have separate wires
Ans: 100m • Easiest
5. What is the maximum distance to which co-axial cable can send data? • More secure than others
Ans: 500m 8. What is Ethernet Card?
6. The network type connected through Bluetooth is __________ • A hardware for connecting nodes
Ans: PAN • Transmit data to network from computer
7. Satellite link is the example of which type of network? • Receive data from network to computer
Ans: WAN • Can connect one cable or more
8. KVKV co. has established a network which spreads in Jaipur city. Which type of 9. What is repeater?
network KVKV co. has established among LAN/MAN/WAN? • Repeater is a network device used to boost the signal.
Ans: MAN. • Used to boost the signals to send for long distance.
9. ISRO (India) wants to establish a direct connection with NASA (US) and ESA • Also known as signal booster.
(Europe). Which connection media can be used? • Its task is to amplify the signal.
Ans: Satellite link or Fibre optics. 10. Explain networking Hub.
10. Wired media is also known as, • A Hub is a networking device that allows you to connect multiple PCs to a single
Ans: Guided media, Physical media, Conducted media. network.
11. Which connector is used to plug the twisted pair cable with device? • It is used to connect segments of a LAN.
Ans: RJ45 connector • A hub stores various ports, so when a packet arrives at one port, it is copied to
12. What is bandwidth of cat-6 twisted pair cable? various other ports.
Ans: 1 Gbps. • Hub works as a common connection point for devices in a network.

2 marks questions 3 mark questions.


1. Write two features of LAN
- Can spread in a room or small area. 1. Write three disadvantages of co-axial cable.
- Established with twisted pair cable or wi-fi. - Less flexible.
2. Write the two features of PAN. - More expensive than twisted pair.
- Established with USB cable, Bluetooth or infrared. - Not compatible with modern cables.
- Very small area upto few feet. - Difficult to install.
- Ad-hoc network. Devices can join and leave anytime.
- Less secure. 4. What is the structure of fibre optics cable?
3. Write any two advantages of co-axial cable. Core − It is the innermost portion of an optical fiber through which light propagates.
- High bandwidth. It is cylindrical in shape and it made up of a flexible glass of high refractive index.
- Can be used for upto 500 mtr distance. The diameter of the core of a single mode fiber is 8 – 10 μm while multimode fibers
4.What is RJ 45 connector? are 50 μm in diameter. It is also called the optical waveguide since it is the main
• Used with twisted pair cable channel through which light signals are transmitted.
• Full form is Registered Jack Cladding − The core is surrounded by a glass cladding. The glass of cladding has a
• Plugin to network devices lower refractive index than the core. This enables total internal reflection of light
• Primarily for LANs waves in the core, and eventually propagation of light waves within the core.
5. Write features of Tree topology. Outer Coating or Jacket − The outer jacket is a thin plastic sheath or coating that is
• No cycle opaque to light. It prevents light rays from outside to enter the optical fiber. Fibers
• Connection to all PCs are typically bundles together, where each bundle is covered by a protective outer
• Either direct or through other PCs sheath that prevents the fibers from physical damage.
• Can say, it is a group of stars
• A fault breakdowns the network
6. Write features of Mesh topology. 5. How data are transmitted through fibre optics?
• Connected in many to many concept. - The binary data is converted into light signals/pulses.
• Fastest connection topology - The light pulses are passed into fibre optics core through LED.
• Very costly - The light passes through class core of fibre optics and reaches at another end.
• Lots of cable required - The receiver at another end receives light pulses and converts them back to binary
• Robust network data.
• High speed 6. Write advantages and disadvantages of fibre optics.
7. What is peer to peer network? • Advantages
• Only two devices • Free from EMI coz it has no electrical signals
103 104
• Secure • It store the addresses of all connected nodes to it
• High speed • IT can manage flow of data and path of data
• Very long distance 12. Write short note about switch.
• Most efficient cable for computer networks • Switch is an electronic device
• Disadvantages • Connects computers together
• Costly • It receive and forward data to particular node
• Fragile • It uses hardware addresses (MAC)
• Complicated installation and maintenance. • It has many LAN ports
7. Explain Infrared. • LAN cable can be attached to any port
• A very short distance transmission. • Its size can be few inches
• Used the Infrared Light using LED. • If Switch speed is 100Mbps or more, it is Ethernet switch
• Sends the IR light pulses(codes), which is received by IR receiver. 13. What is modem?
• Connection can be within 100 ft (30.5mtrs) • Its task is Modulation, Demodulation of signals.
• 10 Mbps speed. • Converts analog to digital and digital to analog signal
• Insensitive to radio-frequency interference • Electronic device
• Can be degraded by bright light. • Used to transmit information over telephone line
8. Write short note about Bluetooth • Types
• Ad-hoc network. Means established when required and with which devices is to • Internal
be connected with. • External
• Can connected limited number of devices. 14. Explain Bus topology
• Devices ex: Mouse, keyboard, headsets, printers etc. uses Bluetooth to connect • Simplest
wirelessly. • All connected to main cable
• It uses 2.4 GHz frequency. • Co-axial cable
• Max distance for proper connection is 10 mtrs. • Sent to all nodes, but receives only intended
• Transfer rate is 50 Mbps of Bluetooth 5.0 • Advantages
9. Write short note about Wi-Fi • Easy to connect
• Wireless Fidelity • Less cable length
• High-speed, low-cost access to internet • New node addition is easy
• Distance 100 meters=328 ft • Less maintenance cost
• Faster then Bluetooth • Disadvantages
• Wi-Fi access points are deployed in Dept stores, railway stations, airports, • If main cable damages, whole network break down
colleges, hotels etc. • Terminators required
• IEEE 802.11 standard stands for Wi-Fi. • Speed will be decreased by adding more nodes
10. Write features of radio waves, its advantages and disadvantages. • Multiple sharing not possible
• Radio Waves • Difficult to find problem
• Electromagnetic wave/sine waves 15. Explain star topology
• Wavelength 0.5cm to 30000m • Most common
• Transmitter, Receiver • All are connected to central node. Central device can be,
• License required to use • Hub
• Benefits • Switch
• Mobility • Router
• Cheaper than cables • UTP or STP cable – Unshielded/Shielded Twisted Pair can be used.
• Ease of communication over difficult terrain • More secure.
• Land acquisition not required • More costly.
• Disadvantages • Better speed than bustopology.
• Insecure • A failure doesn’t affect whole network
• Susceptible to weather 16. Explain satellite link
11. Write short note about router. • Uses Microwave signals.
• Connects two or more networks • It works like relay system: Re-transmit the ground signals
• Router contains the processor and memory • Satellite type is synchronous satellite
• It can process the network data for filtering, validating • Time saving&Fast implementation
• It can store data for traffic management • Broad coverage
• Router has on-board OS and firmware • Prone to natural disasters like, flood, earthquake etc.
105 106
17. Benefits of Microwave network • Presentation layer –It resolves data representation related issues of different
• Benefits end systems ,it encodes the data in standard format , using encryption ,
• Cheaper than optical fiber compression .
• Land acquisition not required • Application layer –The different parts of application specially on distributed
• Communication over difficult terrain systems are managed by this layer.
• Over ocean HTTP (Hyper Text Transfer Protocol)
18. Disadvantages of Microwave network ➢ It is an application level protocol.
• Interference with out-of-phase signals ➢ It provide communication between web browser and web server.
• Susceptible to weather ➢ It is client server protocol ie. request is sent by browser and hyperemedia
• Bandwidth allocation is limited documents will be provided by server.
• Cost of design, implementation, maintenance is high ➢ It can work as generic protocol.
19. What is Personal Area Network? ➢ It is used to deliver data (HTML files, image files, query results, etc.) on the
• Personal area network is a very short distance network. different websites.
• It can be established between computer handheld devices, Camera, Keyboard, FTP (File Transfer Protocol)
Mouse, Cell phone etc. ➢ It works on application layer of OSI model.
• Proximity is up to 10 mtrs ➢ It is used to transfer the files on internet.
• Connectivity ➢ Making projects being on long distance is possible with transferring files using
• Wired: USB this protocol.
• Wireless: Bluetooth, IR ➢ FTP ensures to use different conventions while naming files.
• Used for transferring files, photos, videos etc. ➢ It provides secure login method for effective transfer of files.
➢ It provides the different directory structure for different files.
NETWORK PROTOCOLS Point to Point Protocol (PPP)
The OSI Reference Model ➢ It works on data link layer of OSI model.
The Open Systems Interconnection (OSI) reference model was developed by ➢ It establishes direct and dedicate connection between two devices .
the International Standards Organisation (ISO) as a model for computer ➢ Example – Two routers direct communicate using PPP.
communications architectures, various protocols were standardized by this model. the ➢ Our home computer when connects to internet with ISP through modem then
Communication process is divided under this model within seven layers. there PPP protocol is used.
➢ For using PPP duplex mode is required for communicating devices , it also ensures
data integrity and security , failing which using acknowledge method it resends
the lost or damaged data .
Simple Mail Transfer Protocol (SMTP)
➢ SMTP works on application layer of OSI model.
➢ It is used for email services .
➢ It is not concerned with message of email , it only uses the information contained
in email header .
➢ Outgoing emails are collected in queue .
➢ SMTP takes emails one by one from queue and send messages to destination as
per address mentioned in header of the mail .
➢ After sending the mail to destination it removes the messages from outgoing
queue , and same time it also removes the receiver’s address from mails
destination list.
➢ At receiving end SMTP receiver program sends the mails mail to their
corresponding mail boxes .
• Physical layer –It is related with physical transmission , hubs , repeaters
works at this layer. Transmission control protocol / Internet Protocol ( TCP / IP )
• Data link layer –Ensures flow control of bits , error detection , connection ➢ TCP / IP works with 4 layers i.e. Network , Internet , Transport and Application.
between various network topologies devices . Bridges , switches work at this ➢ It uses client – server model of communication .
layer , Ethernet is an example of a data link layer protocol. ➢ TCP breaks the messages in packets .
• Network layer – It decide the routes of packets on internet using IP address ➢ IP decides the destination addresses for packets .
. Routers work at this layer. ➢ Packets are sent on internet they reach at destination by routing various
• Transport layer –It ensures delivery of data with error free and duplicity. intermediate nodes and paths .
• Session layer –Connection is established by this layer between end system of ➢ Different packets of same message will travel through different paths depending
applications so that communication can be done between them . on traffic at particular path.
107 108
➢ TCP is responsible for ordering the packets at receiving and destination. customers. This system is based on radio networks which provide services like telephone in
remote areas. Different types of wireless local loop include Broadband Wireless Access, Radio in
the Loop, Fixed Radio Access and Fixed Wireless Access. Microwave frequencies are used to
Post office Protocol Version 3 (POP 3) provide wireless broadband connection. The local loop can be referred as "last mile" of the
➢ It works on application layer of OSI model . telecom network which resides between Central office (CO) and user's location.
➢ It is used to transferring messages from email server to email client .
➢ It is used to access the remote serve email and receive and filters the email at Generations of Mobile technology:
appropriate user folders.
➢ Messages are downloaded from mail server to hard disk using this protocol. ➢ 1G technology was used in the first mobile phones. 1G used analog radio signals.
1G was introduced in 1980s
➢ 2G technology was introduced in 1992. 2G technology used a digital format and
Hypertext Transfer Protocol Secure (HTTPS) introduced text messaging. 2G also introduced data services for mobiles, starting
Hyper Text Transfer Protocol Secure (HTTPS) is the secure version of HTTP, the protocol over with SMS.
which data is sent between your browser and the website that you are connected ➢ 3G technology has introduced more efficient ways of carrying data, making it
to. The 'S' at the end of HTTPS stands for 'Secure'. It means all communications between possible to have faster web- services, live chat, fast downloading, video
your browser and the website are encrypted. conferencing etc. over mobile phones. Today we are living in the world of 3G.
➢ 4G technology unlike previous generations of mobile technology, 4G mobile
technology will be used for internet access on computers also, and it will be totally
Remote Access Protocol (Telnet) wireless. 4G will provide internet access, high quality streaming video and
This protocol helps a user (Telnet Client) to log in at a remote computer (Telnet Server) and function "anytime, anywhere" voice and data transmission at a much faster speed than
as if he/she were connected directly to that computer. Telnet is the main internet protocol for 3G. The "anytime, anywhere" feature of 4G is also referred to as "MAGIC" (Mobile
creating a connection with a remote machine. It allows you to connect to remote computers (called multimedia; Anytime/anywhere; Global mobility support; Integrated wireless
remote hosts) over a TCP/IP network (such as the Internet). Once your telnet client establishes a solution; Customized personal services).
connection to the remote host, your client becomes a virtual terminal, allowing you to 5G technology - It can provide higher speed, lower latency and greater
communicate with the remote host from your computer with whatever privileges you may have capacity than 4G LTE networks. It is one of the fastest, most robust
been granted to the specific application and data on that host computer. technologies the world has ever seen.
In healthcare, 5G technology and Wi-Fi 6 connectivity will enable patients
to be monitored via connected devices that constantly deliver data on key
VoIP health indicators, such as heart rate and blood pressure. I
VOIP: Voice over Internet Protocol (Voice over IP, VoIP and IP telephony) is a
group of technologies for the delivery of voice communications and multimedia
sessions over Internet. The terms Internet telephony, broadband telephony, and
broadband phone service specifically refer to the provisioning of communications
services (voice, fax, SMS, voice-messaging) over the public Internet, rather than
via the public switched telephone network (PSTN). This method of making phone
calls is much cheaper than convectional way because the service of Introduction to Web Services
Telecommunication Company is not used.

Wireless/Mobile Communication protocol


GSM: (Global System for Mobile communication): is a digital mobile telephony system that is widely
used in Europe and other parts of the world. GSM) is a second generation (2G) standard for mobile
networks. The GSM standard has given birth to wireless services like General Packet Radio Service
(GPRS) and Enhanced Data Rates for GSM Evolution (EDGE). GSM uses a variation of time division
multiple access (TDMA) and is the most widely used telephony technology.
GPRS (General Packet Radio Service): is a packet oriented mobile data service
on the 2G and 3G GSM communications. GPRS usage is typically charged based
on volume of data transferred.

WLL (Wireless Local Loop): Wireless local loop (WLL), is the use of a wireless communications link for
delivering telephone service (POTS) or Internet access (broadband) to telecommunications
109 110
WWW (World Wide Web): WWW is a network of web servers. It can be defined as a hypertext pages, text documents, graphics, downloadable files, services or programs.
information retrieval system on the Internet. It is the universe of the information available on the Every network resource on the web has a unique URL in the following format:
internet. All the web pages on WWW use HTTP for making hypertext jumps. Protocol: // domain name /path / file name
HTML (Hypertext Markup Language) XML (eXtensible Markup
➢ HTML is a markup language to create Language)
and design webcontent. ➢ XML is a markup language that is
➢ It is used to display the data in self- descriptive.
formattedmanner. ➢ It is used to carry, store or
➢ It has a variety of predefined tags exchange data. The URL text string consists of three parts:
➢ It does not have predefined tags. It ❖ Network Protocol: The network protocol identifies the protocol to be used to
and attributes for defining the layout
and structure of the web document. is possible to define new tags in access the network resource. These strings are short names followed by the
➢ HTML is not casesensitive XML. It allows the programmer to three characters ': //’. Some examples of protocols include http, gopher, ftp
➢ A HTML document has the extension use customized tags. and mailto.
➢ XML is case sensitive. ❖ Domain name: It identifies the host/server that holds the resource. For
.htmor
.html. ➢ A HTML document has the example: www. School.com is a domain name.
extension .xml ❖ Resource Location: It consists of the path or directory and the file name of
➢ HTML documents have a head
andbody. ➢ resource. For example in the URL :
<html> ➢ XML documents form a tree http://www.school.com/syllabus/preprimary/nursery.htm the file
<head>……………… structure. nursery.htm is stored in the sub directory preprimary, of the directory syllabus
</head> <root> on the server www.school.com
<body>……………… <child> Website: Related web pages from a single web domain is termed as a website.
</body> <subchild>..... A website has multiple web pages providing information about a particular entity.
</html> </subchild> Web browser: Web browser is software program to navigate the web pages on
</child> the internet. A browser interprets the coding language of the web page and
</root> displays it in graphic form. Internet works on client -server model. A web browser
is a client which requests the information from the web server. The web server
Domain Names: Every computer on the network has a unique numeric address assigned to it which is a sends the information back to the client. Some of the web browsers are: Netscape
combination of four numbers from 0-255 separated by a dot. For example, 59.177.134.72 since it is Navigator, Internet Explorer, Mozilla Firefox etc.
practically impossible for a person to remember the IP addresses. A system has been developed which Web Server: A Web server is a computer or a group of computers that stores web pages on the
assigns domain names to web servers and maintains a database of these names and corresponding IP internet. It works on client/server model. It delivers the requested web page to web browser. Web
addresses on DNS (Domain Name Service) server. servers use special programs such as Apache or IIS to deliver web pages over the http protocol.
Examples of some domain names are cbse.nic.in, indianrailway.gov.in etc. A domain
name usually has more than one part for example, in the domain name Each server has a unique IP address and domain name. In order to access a webpage, the user writes
www.cbse.nic.in the URL of the site on the address bar of the browser. The machine on which the browser is running
➢ in is the primary domain name sends a request to the IP address of the machine running the web server for that page. Once the
➢ nic is the sub-domain of in web server receives that request, it sends the page content back to the IP address of the computer
➢ cbse is the sub-domain of nic asking for it. The web browser then translates that content into all of the text, pictures, links,
➢ www indicates the server is on world wide web. videos, etc. A single web server may support multiple websites or a single website may be hosted
on several linked servers.
Top level domains are further divided into two categories:
Generic Domain Names: Country Specific Domain Names: Web hosting: Web hosting is the process of uploading/saving the web content
· com - commercial business .in - India on a web server to make it available on WWW. In case an individual or a
·edu - Educational institutions ·au - Australia company wants to make its website available on the internet, it should be
·gov - Government agencies ·ca - Canada hosted on a web server.
·mil - Military .ch - China
·net - Network organizations .nz - New Zealand
·org - Organizations (non-profit .pk - Pakistan Web page: Web page is an electronic document designed using HTML. It displays information in textual or
graphical form. It may also contain downloadable data files, audio files or video files. Traversal from one
.jp - Japan
webpage to another web page is possible through hyperlinks. A web page can be classified into two types:
.us - United States of America

URL (Uniform resource locator): A URL is a formatted text string used to


identify a network resource on the Internet. Network resources can be plain Web

111 112
Static web page: A web page which Dynamic web page: An interactive web possible to have faster web- services, live chat, fast downloading, video
displays same kind of information page is a dynamic webpage. A dynamic conferencing etc. over mobile phones. Today we are living in the world of 3G.
whenever a user visits it is known as web page uses scripting languages to ➢ 4G technology - 4G provides internet access, high quality streaming
a static web page. A static web page display changing content on the web video and "anytime, anywhere" voice and data transmission at a much faster
generally has .htm or .html as page. Such a page generally has .php, speed than 3G.
extension .asp or .jspas extension. ➢ 5G technology - It can provide higher speed, lower latency and greater
capacity than 4G LTE networks. It is one of the fastest, most robust technologies
the world has ever seen.

SUMMARY WWW (World Wide Web): WWW is a network of web servers.


HTML (Hypertext Markup Language)
HTTP (Hyper Text Transfer Protocol) ➢ HTML is a markup language to create and design web content.
➢ It is used to deliver data (HTML files, image files, query results, etc.) on the different ➢ It is used to display the data in formatted manner.
websites. XML (eXtensible Markup Language)
FTP (File Transfer Protocol) ➢ XML is a markup language that is self- descriptive.
➢ It is used to transfer the files on internet. ➢ It is used to carry, store or exchange data.
Point to Point Protocol (PPP) Domain Names: A system has been developed which assigns domain names to web servers and
➢ Our home computer when connects to internet with ISP through modem then there maintains a database of these names and corresponding IP addresses on DNS (Domain Name
PPP protocol is used. Service) server.
Simple Mail Transfer Protocol (SMTP) URL- Uniform resource locator
➢ SMTP takes emails one by one from queue and send messages to destination as per Examples – Website :www.rajkot.kvs.ac.in
address mentioned in header of the mail . • Web server :Apache HTTP Server , Microsoft Internet Information Services (IIS) ,
Transmission control protocol / Internet Protocol ( TCP / IP ) Sun Java System Web Server.
➢ TCP breaks the messages in packets . Web Browser : Google Chrome , Mozila Firefox , Internet Explore .
➢ IP decides the destination addresses for packets . Definition :
Post office Protocol Version 3 (POP 3) Web Page : page of website .
➢ It is used to transferring messages from email server to email client . Web Hosting :Web site hosting / Web hosting / and Webhosting is the business of
Hypertext Transfer Protocol Secure (HTTPS) housing, serving, and maintaining files for one or more Web sites.
➢ The 'S' at the end of HTTPS stands for 'Secure'. It means all communications between your
browser and the website are encrypted. Question Bank
Remote Access Protocol (Telnet) : 1 Mark Questions
➢ This protocol helps a user (Telnet Client) to log in at a remote computer (Telnet Server) and function
as if he/she were connected directly to that computer. Q1 Mr. Ramesh is not able to identify the Domain Name in the given URL. Identify and
VOIP: Voice over Internet Protocol write it for him.
➢ This is a group of technologies for the delivery of voice communications and Q2 Expand following –
multimedia sessions over Internet. (i) HTTPS
GSM: (Global System for Mobile communication) (ii) TDMA
➢ GSM) is a second generation (2G) standard for mobile networks. The GSM standard Q3 Name any two most popularly used search engines.
has given birth to wireless services like General Packet Radio Service (GPRS) and Q4 Given below two addresses
Enhanced Data Rates for GSM Evolution (EDGE). (i) 59.177.134.72
GPRS (General Packet Radio Service) (ii) http://www.ccc.nic.in/welcome.htm
➢ This is a packet oriented mobile data service on the 2G and 3G GSM Identify which one of the above is an IP address and which one is a URL?
communications. GPRS usage is typically charged based on volume of data Q5 Mr. Mahesh wants to prevent unauthorised access to/from his company’s local
transferred. area network. Write the name of system (software/hardware), which he should install.
WLL (Wireless Local Loop) Q6. Write any one disadvantages of VoIP.
Wireless local loop (WLL), is the use of a wireless communications link for delivering Q7 Write the full form of following –
telephone service (POTS) or Internet access (broadband) to telecommunications 1. GSM 2. GPRS
customers. Q8. What is Error-404?
Mobile Technologies Q9. Name an open source web browser.
➢ 1G technology was used in the first mobile phones. 1G used analog radio Q 10. Name any two common web browser.
signals. 1G was introduced in 1980s Q 11 What is a protocol? Which protocol is used to search information from Internet
➢ 2G technology 2G also introduced data services for mobiles, starting with SMS. using an Internet browser?
➢ 3G technology has introduced more efficient ways of carrying data, making it
113 114
2 Mark Questions system in the form of a web page. When the client sends a request for processing to
Q1 Expand following – the web server, a domain name and IP address are important to the webserver. The
(i) XML domain name and IP address are used to identify the user on a large network.
(ii) GSM 1.
Q2 What is an IP address , explain with example ? 1. Web servers are:
Q3 Write a short note on WWW. 1. IP addresses
Q4 Ramesh is a class 12 computer science student. 2. Computer systems
He is confused between ‘web’ and ‘internet’. As a friend of Ramesh, explain her the 3. Webpages of a site
difference between web and internet. 4. A medium to carry data from one computer to another
Q5 Write short note on VoIP. 2. What does the webserver need to send back information to the user?
Q6 Write two advantages of VoIP. 1. Home address
Q7. Write a short note on web hosting. 2. Domain name
Q8 Define browser. 3. IP address
Q9. What is DNS? 4. Both b and c
Q10 What is work of SMTP explain. 3. What is the full form of HTTP?
Q 11 What is work of TCP / IP explain . 1. Hypertext Transfer Protocol
Q12 What is Telnet expain . ? 2. Hypertext Transfer Procedure
Q 13 write full form of following – 3. Hyperlink Transfer Protocol
(i) PPP 4. Hyperlink Transfer Procedure
(ii) FTP 4. The _____ translates internet domain and host names to IP address
(iii) POP 1. Domain name system
(iv) WLL 2. Routing information protocol
3. Google
3 Mark Questions 4. Network time protocol
Q 1 Identify the domain name, protocol, sub-domain from the following domain. 5. Computer that requests the resources or data from other computer is called as
https://www.csiplearninghub.com/class-11-ch-1/mcq ____ computer
Q 2 . Suresh is running a business. He has studied till class 10. He wants to launch a 1. Server
website for his business. He is confused between static and dynamic web page. As a 2. Client
website developer, help him to understand the difference between static and dynamic 3. None of the above
web page. 4. a and b
Q 3. Define the following terms :
1. Website 6. DNS stands for:
2. Webpage 1. Domain Name Security
3. Web server 2. Domain Number System
Q4. Write the steps to host a website. 3. Document Name System
Q5 – Write note on 1G , 2G , 3G of mobile technologies. 4. Domain Name System
Q6 – Write note on 4G , 5G of mobile technologies.
Q7 Write differences between HTML and XML ? Case 2: In 1989, Tim Berners Lee, a researcher, proposed the idea of World Wide
Q8 Explain working of SMTP ? Web). Tim Berners Lee and his team are credited with inventing Hyper Text Transfer
Q9 Explain working of TCP / IP ? Protocol (HTTP), HTML and the technology for a web server and a web browser. Using
Q10 What do you mean by domain name explain with example . hyperlinks embedded in hypertext the web developers were able to connect web
Q 11 Explain PPP ( Point to Point) Protocol . pages. They could design attractive webpages containing text, sound and graphics.
This change witnessed a massive expansion of the Internet in the 1990s.

1. What is a web browser?


CASE STUDY BASED QUESTIONS 1. A program that can display a webpage
2. A program used to view HTML documents
Case 1: Web server is a special computer system running on HTTP through web 3. It enables a user to access the resources of internet
pages. The web page is a medium to carry data from one computer system to another. 4. All of the above
The working of the webserver starts from the client or user. The client sends their 2. Dynamic web page _____
request through the web browser to the webserver. Web server takes this request, a) is same every time whenever it displays
processes it and then sends back processed data to the client. The server gathers all of b) generates on demand by a program or a request from browser
our web page information and sends it to the user, which we see on our computer c) both is same every time whenever it displays and generates on demand by a
115 116
program or a request from browser 4. A web cookie is a small piece of data that is __________
d) is different always in a predefined order a) sent from a website and stored in user’s web browser while a user is browsing a
3. URL stands for _______ website
a) unique reference label b) sent from user and stored in the server while a user is browsing a website
b) uniform reference label c) sent from root server to all servers
c) uniform resource locator d)1.
d) unique resource locator 5. Google Chrome is an good –
1. Web server.
2. Web browser.
3. Web protocol.
4. Subset of website sent from the root server to other root servers

ANSWER KEY
1 Mark Questions

Q1 Mr. Ramesh is not able to identify the Domain Name in the given URL. Identify and
write it for him.
Ans1 Domain in http://www.cbsenic.in/aboutus.htm is “www.cbsenic.in”.
Q2 Expand following –
(iii) HTTPS
(iv) TDMA
Ans2
(i) Hypertext Transfer Protocol Secure (HTTPS)
(ii) Time division multiple access (TDMA)
Q3 Name any two most popularly used search engines.
Ans3 Two most popular search engines are google and grotel.
(url:http://www.google.com and http://grotel.com)
Q4 Given below two addresses
(i) 59.177.134.72
(ii) http://www.ccc.nic.in/welcome.htm
Identify which one of the above is an IP address and which one is a URL?
Ans4 i) IP Address 59.177.134.72
(ii) URL http://www.ccc.nic.in/welcome.htm
Q5 Mr. Mahesh wants to prevent unauthorised access to/from his company’s local area
network. Write the name of system (software/hardware), which he should install.
Ans 5 He should install firewall system to prevent unauthorised access.

Q6. Write any one disadvantages of VoIP.


Ans6. The disadvantage of VoIP is that its call quality is dependent on
Internet connection speed. Slow Internet
connection will lead to poor quality voice calls.
Q7 Write the full form of following –
2. GSM
3. GPRS
Ans 7.
1. Global System for Mobile communication
2. General Packet RadioServices
3.
Q8. What is Error-404?
Ans8. If the server is not able to locate the page, it sends a page containing
the error message (Error 404 – page not found) to the client’s browser.
Q9. Name an open source web browser.
Ans 9. Mozilla Firefox is an open source web browser.

117 118
Q 10. Name any two common web browser. Q7. Write a short note on web hosting.
Ans 10 . Some of the commonly used web browsers are Google Chrome, Ans 7. Web hosting is a service that allows us to put a website or a web page
Internet Explorer, Mozilla Firefox, Opera, etc. onto the Internet, and make it a part of the World Wide Web. Once a website
Q 11 What is a protocol? Which protocol is used to search information from Internet is created, we need to connect it to the Internet so that users across the globe
using an Internet browser? . can access.
Ans 11 . Protocol refers to the rules which are applicable for a network. These
protocols define the standardised format for data packets to be transmitted over the Q8 Define browser.
network, techniques for detecting errors and correcting them etc. Ans 8. A browser is a software application that helps us to view the web
The protocol used to search the information from Internet using browser is HyperText page(s). In other words, it helps us to view the data or information that is
Transfer Protocol (HTTP). retrieved from various web servers on the Internet.
2 Mark Questions
Q9. What is DNS?
Q1 Expand following – Ans 9. The domain name system (DNS) is a service that does the mapping
(iii) XML between domain name and IP address. When the address of a website is
(iv) GSM entered in a browser, the DNS finds out the IP address of the server
Ans1 Answer: corresponding to the requested domain name and sends the request to that
(i) Xtensible Markup Language. server.
(ii) Global System for Mobile Communication.
Q10 What is work of SMTP explain.
Q2 What is an IP address? Ans 10. SMTP or Simple Mail Transfer Protocol is an application that is used to send,
Ans2. An Internet Protocol address (IP address) is a numerical unique address of a receive, and relay outgoing emails between senders and receivers. When an email is
device in a network. IP is a datagram-oriented connectionless protocol, therefore each sent, it's transferred over the internet from one server to another using SMTP. In
packet must contain a header with the source IP address, the destination IP address, simple terms, an SMTP email is just an email sent using the SMTP server.
and other data in order to be delivered successfully.
Q 11 What is work of TCP / IP explain .
Q3 Write a short note on WWW. Ans 11 . TCP breaks the message into packets and IP decides the destination address
Ans3. The World Wide Web (WWW) or web in short, is an ocean of for packets .
information, stored in the form of trillions of interlinked web pages and web
resources. The resources on the web can be shared or accessed through the Q12 What is Telnet expain . ?
Internet. Ans 12 Telnet is a network protocol used to virtually access a computer and to provide
a two-way, collaborative and text-based communication channel between two
Q4 Ramesh is a class 12 computer science student. machines. It follows a user command Transmission Control Protocol/Internet
He is confused between ‘web’ and ‘internet’. As a friend of Ramesh, explain her the Protocol (TCP/IP) networking protocol for creating remote sessions.
difference between web and internet.
Ans4. The Internet as we know is the huge global network of interconnected Q 13 write full form of following –
computers, which may or may not (v) PPP
have any file or webpage to share with the world. The web on the other hand (vi) FTP
is the interlinking of a collection of WebPages on these computers which are (vii) POP
accessible over the Internet. (viii) WLL
Ans 13 (i) PPP – Point to Point Protocol.
Q5 Write short note on VoIP. (ii) FTP – File Transfer Protocol.
Ans5. Voice over Internet Protocol or VoIP, allows us to have voice call (iii) POP – Post office protocol.
(telephone service) over the Internet, i.e., the voice transmission over a WLL – Wireless in Local loop .
computer network rather than through the regular telephone network. It is
also known as Internet Telephony or Broadband Telephony. 3 Mark Questions
Q 1 Identify the domain name, protocol, sub-domain from the following domain.
Q6 Write two advantages of VoIP. https://www.csiplearninghub.com/class-11-ch-1/mcq
Ans6. Advantages of VoIP are : Ans 1 . Domain name = www.csiplearninghub.com
1. These services are either free or very economical, so people use them to Sub Domain Name = www
save on cost. That is why these days even international calls are being Protocol = https
made using VoIP.
2. VoIP call(s) can be received and made using IP phones from any place
having Internet access.

119 120
Q 2 . Suresh is running a business. He has studied till class 10. He wants to launch a
website for his business. He is confused between static and dynamic web page. As a 5G technology - It can provide higher speed, lower latency and greater capacity than
website developer, help him to understand the difference between static and dynamic 4G LTE networks. It is one of the fastest, most robust technologies the world has ever
web page. seen.
In healthcare, 5G technology and Wi-Fi 6 connectivity will enable patients to be
Ans 2. A static webpage is one whose content always remains static, i.e., does monitored via connected devices that constantly deliver data on key health indicators,
not change for person to person. A dynamic web page is one in which the such as heart rate and blood pressure.
content of the web page can be different for different users. They are more
complex and thus take more time to load than static web pages. Q7 Write differences between HTML and XML ?
Ans 7.
Q 3. Define the following terms :
4. Website HTML (Hypertext Markup Language) XML (eXtensible Markup Language)
5. Webpage ➢ HTML is a markup language to create and design ➢ XML is a markup language that is self-
6. Web server webcontent. descriptive.
Ans 3. Website : A website (usually referred to as a site in short) is a ➢ It is used to display the data in formattedmanner. ➢ It is used to carry, store or exchangedata.
collection of web pages related through hyperlinks, and saved on a web ➢ It has a variety of predefined tags and attributes for ➢ It does not have predefined tags. It is possible
defining the layout and structure of the web to define new tags in XML. It allows the
server. A visitor navigates from one page to another by clicking on
document. programmer to use customizedtags.
hyperlinks.
➢ HTML is not casesensitive ➢ XML is casesensitive.
Webpage : A web page (also referred to as a page) is a document on the ➢ A HTML document has the extension .htmor ➢ A HTML document has the extension.xml
WWW that is viewed in a web browser. Basic structure of a web page is .html. ➢ XML documents form a treestructure.
created using HTML (Hyper Text Markup Language) and CSS. ➢ HTML documents have a head andbody. <root>
Web Server: A web server is used to store and deliver the contents of a <html> <child>
website to clients such as a browser that request it. A web server can be <head>……………… <subchild>.....
software or hardware. </head> </subchild>
<body>……………… </child>
Q4. Write the steps to host a website. </body> </root>
Ans 4. Steps to host a website are : </html>
1. Select the web hosting service provider that will provide the web server
space. Q8 Explain working of SMTP ?
2. Identify a domain name, which best suits our requirement. Ans 8.Simple Mail Transfer Protocol (SMTP)
3. Create logins with appropriate rights and note down IP address to ➢ SMTP works on application layer of OSI model.
manage web space. ➢ It is used for email services .
4. Upload the files in properly organised folders on the allocated space. ➢ It is not concerned with message of email , it only uses the information contained
5. Get domain name mapped to the IP address of the web server. in email header .
➢ Outgoing emails are collected in queue .
Q5 – Write note on 1G , 2G , 3G of mobile technologies. ➢ SMTP takes emails one by one from queue and send messages to destination as
Ans 5 - per address mentioned in header of the mail .
➢ 1G technology was used in the first mobile phones. 1G used analog radio ➢ After sending the mail to destination it removes the messages from outgoing
signals. 1G was introduced in 1980s queue , and same time it also removes the receiver’s address from mails
➢ 2G technology was introduced in 1992. 2G technology used a digital format destination list.
and introduced text messaging. 2G also introduced data services for mobiles, ➢ At receiving end SMTP receiver program sends the mails mail to their
starting withSMS. corresponding mail boxes .
➢ 3G technology has introduced more efficient ways of carrying data, making it Q9 Explain working of TCP / IP ?
possible to have faster web- services, live chat, fast downloading, video Ans 9 Transmission control protocol / Internet Protocol ( TCP / IP )
conferencing etc. over mobile phones. Today we are living in the world of3G. ➢ TCP / IP works with 4 layers ie .Network , Internet , Transport and Application .
➢ It uses client – server model of communication .
Q6 – Write note on 4G , 5G of mobile technologies. ➢ TCP breaks the messages in packets .
Ans6 : 4G technology unlike previous generations of mobile technology, 4G ➢ IP decides the destination addresses for packets .
mobile technology will be used for internet access on computers also, and it will ➢ Packets are sent on internet they reach at destination by routing various
be totally wireless. 4G will provide internet access, high quality streaming video intermediate nodes and paths .
and "anytime, anywhere" voice and data transmission at a much faster speed ➢ Different packets of same message will travel through different paths depending
than 3G. The "anytime, anywhere" feature of 4G is also referred to as "MAGIC" on traffic at particular path.
(Mobile multimedia; Anytime/anywhere; Global mobility support; Integrated ➢ TCP is responsible for ordering the packets at receiving and destination.
wireless solution; Customized personal services).

121 122
Q10 What do you mean by domain name explain with example . 5. Google Chrome is an good –
Ans10 Domain Names: Every computer on the network has a unique numeric address Ans : Web Browser .
assigned to it which is a combination of four numbers from 0-255 separated by a dot.
For example, 59.177.134.72 since it is practically impossible for a person to remember
the IP addresses. A system has been developed which assigns domain names to web
servers and maintains a database of these names and corresponding IP addresses on
DNS (Domain Name Service) server.

Examples of some domain names are cbse.nic.in, indianrailway.gov.in etc. A Unit III - DBMS concepts and SQL
domain name usually has more than one part for example, in the domain name Database
www.cbse.nic.in A database is an organized collection of structured data, stored electronically in a
1. in is the primary domainname computer system.
2. nic is the sub-domain ofin
3. cbse is the sub-domain ofnic Relational Database
4. www indicates the server is on world wideweb A relational database is a collection of data items organized as logically related tables.

Q 11 Explain PPP ( Point to Point) Protocol .


Ans 11
Point to Point Protocol (PPP)
➢ It works on data link layer of OSI model.
➢ It establishes direct and dedicate connection between two devices .
➢ Example – Two routers direct communicate using PPP.
➢ Our home computer when connects to internet with ISP through modem then
there PPP protocol is used.
➢ For using PPP duplex mode is required for communicating devices , it also
ensures data integrity and security , failing which using acknowledge method it
resends the lost or damaged data .

CASE STUDY BASED QUESTIONS

Case 1
Web servers are:
Ans. 2 Database Management System
What does the webserver need to send back information to the user? The software required to manage a database is known as a database management
Ans. 4 system (DBMS).
What is the full form of HTTP?
Ans. 1 A DBMS serves as an interface between the database and its end users, allowing users
The _____ translates internet domain and host names to IP address to retrieve, update, and manage how the information is organized and optimized.
Ans. 1
Computer that requests the resources or data from other computer is called as ____ A DBMS also facilitates oversight and control of databases, enabling a variety of
computer administrative operations such as performance monitoring, tuning, and backup and
ans. 2 recovery.
DNS stands for:
Ans. 4 handle/manipulate these table/relations is known as Relational Database Management
System (RDBMS). Some examples of popular DBMSs are MySQL, Microsoft Access,
Case 2 1. What is a web browser? Microsoft SQL Server, FileMaker Pro, Oracle Database, and dBASE
Ans. 4
2. Dynamic web page _____ Table/Relation
ans. 2 A group of rows and columns form a table. The horizontal subset of the Table is known
3. URL stands for _______ as a Row/Tuple. The vertical subset of the Table is known as a Column/an Attribute.
ans. 3
4. A web cookie is a small piece of data that is __________
ans. 1

123 124
A relation in a database has the following characteristics:
• Values are atomic.
• Column values are of the same kind.
• Each row is unique.
• The sequence of columns is insignificant.
• The sequence of rows is insignificant.
• Each column must have a unique name.

Database Terminology
Degree
No. of columns of Table.

Cardinality
No. of Rows of Table
SQL - Structured Query Language
Domain
A domain is the collection of values that a data element may contain. Structured Query Language (SQL) is a specialized language for accessing and manipulating
databases.
Key SQL commands are classified by function:
An Attribute/group of attributes in a table that identifies a tuple uniquely is known as
a key. Data definition language (DDL) - used to define or change database structure(s)
(e.g., CREATE, ALTER, DROP)
A table may have more than one such attribute/group of identifies that identifies a Data manipulation language (DML) - used to select or change data (e.g., INSERT,
tuple uniquely, all such attributes(s) are known as Candidate Keys. UPDATE, DELETE, SELECT)
Transaction Control language - used to control logical units of work (e.g., COMMIT,
Out of Candidate keys, one is selected as Primary key, and others ROLLBACK)
become Alternate Keys.
CREATE DATABASE statement: The CREATE DATABASE statement is used to
A Foreign Key is defined in a second table, but it refers to the primary key in the first create a new SQL database. Syntax:
table.
CREATE DATABASE databasename;
CREATE DATABASE school;

SHOW DATABASES statement


The SHOW DATABASES statement is used to know the names of existing databases.
SHOW DATABASES;

USE statement
In order to use the database, the following SQL statement is required. Syntax:
USE databasename;

DROP DATABASE statement


The DROP DATABASE statement is used to delete a database from system. Syntax:
DROP DATABASE databasename;
DROP DATABASE school;
125 126
CREATE TABLE statement Syntax:INSERT INTO table_name
A database consists of many tables. In order to create a table in database VALUES (value1, value2, value3,...);

CREATE TABLE statement is used. Syntax: INSERT INTO table_name (column1, column2, column3,...)
CREATE TABLE table_name VALUES(value1,value2,value3,...);
(
column_name1 data_type (size) constraint, INSERT INTO student VALUES(10, 'Alex', 7800, '1998-10-03','K12');
column_name2 data_type (size) constraint,
column_name3 data_type (size) constraint, INSERT INTO student(rollnumber, name, fees, dob, class) values(11, 'Peter', 6700,
.... '1997-11-15',
);
QUESTION NO 1 TO 10 OF ONE MARKS.
Data Types of attribute (column) 1. What is the full form of DBMS?
char(n) A FIXED length string. The n specifies the column length. The parameter n a) Data of Binary Management System
can be from 0 to 255. Default is 1 b) Database Management System
varchar(n) A VARIABLE length string. The n parameter specifies the maximum column c) Database Management Service
length in characters - can be from 0 to 65535 d) Data Backup Management System
int An integer. Range is from -2147483648 to 2147483647.
2. What is a database?
float A floating point number. a) Organized collection of information that cannot be accessed, updated, and
date A date. Format: YYYY-MM-DD. managed
b) Collection of data or information without organizing
Constraints c) Organized collection of data or information that can be accessed, updated, and
Constraints are the certain types of restrictions on the data values that an attribute managed
can have. d) Organized collection of data that cannot be updated
Constraint Description
3. What is DBMS?
NOT NULL Ensures that a column cannot have NULL a value a) DBMS is a collection of queries
UNIQUE Ensures that all the values in a column are different b) DBMS is a high-level language
DEFAULT Sets a default value for a column if no value is specified c) DBMS is a programming language
PRIMARY The column which can uniquely identify each row/record in a table. d) DBMS stores, modifies and retrieves data
KEY
FOREIGN The column which refers to value of an attribute defined as primary key 4.Who created the first DBMS?
KEY in another table a) Edgar Frank Codd
Example : b) Charles Bachman
CREATE TABLE student c) Charles Babbage
( d) Sharon B. Codd
rollnumber int NOT NULL,
name char(25) NOL NULL, 5.Which type of data can be stored in the database?
fees int DEFAULT 7000, a) Image oriented data
dob date, b) Text, files containing data
class char(3), c) Data in the form of audio or video
PRIMARY KEY (rollnumber) d) All of the above
);
6. In which of the following formats data is stored in the database management
DESCRIBE statement system?
Provides a description of the specified table. Syntax: a) Image
DESCRIBE table_name; b) Text
DESCRIBE student; c) Table
d) Graph
INSERT INTO statement
Inserting a new row at the bottom of the table. 7. What does an RDBMS consist of?
a) Collection of Records
b) Collection of Keys

127 128
c) Collection of Tables POPULATION INTEGER
d) Collection of Fields 14.What is different between WHERE and HAVING clause.
15. What is the importance of primary key in a table? Explain with suitable
8. The values appearing in given attributes of any tuple in the referencing relation example.
must likewise occur in specified attributes of at least one tuple in the referenced 16. Differentiate between Primary key and Candidate key.
relation, according to _____________________ integrity constraint. 17. Differentiate between Degree and Cardinality
a) Referential 18. What are DDL AND DML.
b) Primary 19.What is relation. what is difference between a tuple and attribute?
c) Referencing 20.Differentiate between SQL commands DROP TABLE and DROP VIEW.
d) Specific
QUESTION NO 21 TO 30 OF (THREE MARKS)
9.The DBMS acts as an interface between ________________ and 21.A table, ITEM has been created in a database with the following fields:
________________ of an enterprise-class system. ITEMCODE, ITEMNAME, QTY, PRICE
a) Data and the DBMS Give the SQL command to add a new field, DISCOUNT (of type Integer) to the ITEM
b) Application and SQL table.
c) Database application and the database Categorize following commands into DDL and DML commands?
d) The user and the software INSERT INTO, DROP TABLE, ALTER TABLE, UPDATE...SET

10. The ability to query data, as well as insert, delete, and alter tuples, is offered by 22. Write a output for SQL queries (i) to (iii), which are based on the table: STUDENT
____________ given below:
a) TCL (Transaction Control Language)
b) DCL (Data Control Language) Table: STUDENT
c) DDL (Data Definition Langauge)
d) DML (Data Manipulation Langauge)

QUESTION NO 11 TO 20 OF (TWO MARKS)

11. Differentiate between char(n) and varchar(n) data types with


respect to databases.

12. Consider the table, MOVIEDETAILS given below:


Table: MOVIEDETAILS
MOVIEID TITLE LANGUAGE RATING PLATFORM
(i) SELECT COUNT(*), City FROM STUDENT GROUP BY CITY HAVINGCOUNT(*)>1;
M001 Minari Korean 5 Netflix
(ii) SELECT MAX(DOB),MIN(DOB) FROM STUDENT;
M004 MGR Magan Tamil 4 Hotstar (iii)SELECT NAME,GENDER FROM STUDENT WHERE CITY=”Delhi”;
M010 Kaagaz Hindi 3 Zee5 23. Write the output of the queries (a) to (c) based on the table, Furniture given
M011 Harry Potter and the Chamber of Secrets English 4 Prime Video below:
M015 Uri Hindi 5 Zee5 Table: FURNITURE
M020 Avengers: Endgame English 4 Hotstar FID NAME DATE OF COST DISCOUNT
a. Identify the degree and cardinality of the table. PURCHASE
b. Which field should be made the primary key? Justify your answer. B001 Double Bed 03-Jan-2018 45000 10
T010 Dining Table 10-Mar-2020 51000 5
13. Charu has to create a database named MYEARTH in MYSQL. B004 Single Bed 19-Jul-2021 22000 0
She now needs to create a table named CITY in the database to store the records of C003 Long Back 30-Dec-2016 12000 3
various cities across the globe. The table CITY has the following structure: Chair 6
Table: CITY T006 Console 17-Nov- 15000 12
FIELD NAME DATA TYPE REMARKS Table 2019
CITYCODE CHAR(5) Primary Key B006 Bunk Bed 01-Jan-2021 28000 14
1. SELECT SUM(DISCOUNT) FROM FURNITURE WHERE COST>15000
CITYNAME CHAR(30)
2. SELECT MAX(DATEOFPURCHASE) FROM FURNITURE
SIZE INTEGER(3) 3. SELECT * FROM FURNITURE WHERE DISCOUNT>5 AND FID LIKE "T%";
AVGTEMP INTEGER
POLLUTIONRATE INTEGER

129 130
24. Write queries (a) to (d) based on the tables EMPLOYEE and DEPARTMENT given 805 Gurdeep Kaur Chandigarh
below: 1. Alter table sales
Add primary key sales(S No);
Table: EMPLOYEE 2. Select SNAME WHERE SNO=’805’ FROM sales;
EMPID NAME DOB DEPTID DESIG SALARY
3.Select SNAME, ADDRESS FROM sales WHERE S NO=’502’;
120 Alisha 23-Jan-1978 D001 Manager 75000
CASE BASED QUESTIONS (5 mark)
123 Nitin 10-Oct-1977 D002 AO 59000 1.MR MITTAL is using a table with following columns:
129 Navjot 12-Jul-1971 D003 Supervisor 40000 Name,Class,Stream_id,Stream_name
130 Jimmy 30-Dec-1980 D004 Sales Rep He needs to display names of students who have not been assigned any stream or
131 Faiz 06-Apr-1984 D001 Dep Manager 65000 have been assigned stream name that ends with “computers”.

Table: DEPARTMENT He wrote the following command, which did not give the desired result.
DEPTID DEPTNAME FLOORNO SELECT Name,Class From StudentsWhere Stream_name=NULL OR
Stream_name=”%computers”;
D001 Personal 4
SELECT Name From StudentsWhere Stream_name=NULL ;
D002 Admin 10 SELECT Class From StudentsWhere Stream_name=”%computers”;
D003 Production 1 SELECT Name From Students Where Stream_id=Null;
D004 Sales 3 SELECT Class From Students Where Stream_name=”%computers”;
Help Mr.Mittal to run the query by removing the error and write correct query.
2.Sarthak a student of class XII, created a table” Class” with following attribute
a. To display the average salary of all employees, department wise. Sname, Sroll,Smark and Grade . Grade is one of the columns of this table. To find the
b. To display name and respective department name of each employee whose details of students where Grades have not been entered, he wrote the following Mysql
salary is more than 50000. query which did not give the desired result:
c. To display the names of employees whose salary is not known, in alphabetical SELECT Sname FROM Class WHERE Grade=”Null”;
order. SELECT Sroll FROM Class WHERE Grade=”Null”;
SELECT Smark FROM Class WHERE Grade=”Null”;
25.Give a suitable Example of a table with sample data and illustrate primary key and SELECT * FROM Class WHERE Grade=”Null”;
Candidate keys in it. SELECT Grade FROM Class WHERE Grade=”Null”;
26. Give a suitable Example of a table with sample data and illustrate primary key and Help Sarthak to run the query by removing the errors from the query and write the
Alternate keys in it. correct query.
27.What do you understand by primary key? Give a suitable of Primary Key from a SUMMARY
table containing some meaningful data. The basic element of MYSQL SQL is: literals, datatypes, nulls and comments. Some
28. Differentiate between Candidate Key and Alternate Key in context of RDBMS. Key feature of MYSQL are portability, secure system, scalable and support localization.
29. Write SQL queries for (i) to (iii) which are based on the table. A relational data model organizes the data into tables knows as RELATIONS.
TABLE: ACCOUNT Table/Relation divided into two-part TUPLE/ROW and ATTRIBUTE/COLUMN. Some
ANO ANAME ADDRESS KEYS are used in TABLES like:
101 Nirja Singh Bangalore PRIMARY KEY, CANDIDATE KEY, ALTERNATE KEY and FOREIGN KEY.
102 Rohan Gupta Chennai SQL (STRUCTURED QUERY LANGUAGE). A non –procedural UGL used for querying
103 Ali Reza Hyderabad upon relation databases.
104 Rishabh Jain Chennai SQL statement can be classified into:
105 Simran Kaur Chandigarh Data Definition Language(DDL),
Data Manipulation Language (DML),
1. Select ANAME,ADDRES FROM ACCOUNT; Transaction Control Language (TCL).
2. Select ANAME WHERE ANO=’101’ FROM ACCOUNT; ANSWER KEY
3. Select DISTICT ADDRESS FROM ACCOUNT; 1. Answer: b
2. Answer: c
30. Write SQL queries for (i) to (iii) which are based on the table. 3. Answer: d
TABLE: SALES 4. Answer: d
S NO SNAME ADDRESS
501 Ajay Singh Bangalore 5. Answer: d
502 Ram Gupta Chennai 6. Answer: c
703 Ali Hyderabad 7. Answer: c
704 Rishabh Chennai 8. Answer: a
9. Answer: c
131 132
10. Answer: d 22.
11. char(n): stores a fixed length string between 1 and 255 (1) 8, Mumbai
Characters if the value is of smaller length, adds blank spaces Delhi
some space is wasted Moscow
varchar(n): stores a variable length string no blanks are added even if value is of (2) MAX DOB (07/05/1993) ,MIN DOB(08/12/1995)
smaller length no wastage of space (3) sanal F
12. Degree: 5 store M
Cardinality: 6 23. 1. 29
MOVIEID should be made the primary key as it uniquely identifies 2. 19- Jul-2021
each record of the table 3. T006 Console Table 17-Nov-2019 15000 12
13. CREATE DATABASE MYEARTH;
CREATE TABLE CITY 24. (a) SELECT AVG(SALARY)
( FROM EMPLOYEE
CITYCODE CHAR (5) PRIMARY KEY, GROUP BY DEPTID;
CITYNAME CHAR (30), (b) SELECT NAME, DEPTNAME
SIZE INT, FROM EMPLOYEE, DEPARTMENT
AVGTEMP INT, WHERE EMPLOYEE.DEPTID= DEPARTMENT.DEPTID
POPULATIONRATE INT, AND SALARY>50000;
POPULATION INT (c ) SELECT NAME FROM EMPLOYEE
); WHERE SALARY IS NULL
14. A HAVING clause is like a WHERE clause, but applies only to groups as a whole ORDER BY NAME;
(that is, to the rows in the result set representing groups), whereas the WHERE clause 25. A table may have more than one such attribute or a group of an attribute that
applies to individual rows. identifies a row/ tuple uniquely, all such attribute(s) are known as Candidate keys.
15. Primary key is a set of one or more attributes that can uniquely identify tuples Out of the Candidate keys, one is selected as Primary key.
within the relation. For example, in the following table ITEM, the column Ino can Table : Stock
uniquely identify each row in the table, hence Ino is the primary key of the following Id Item Qty
table. 101 pen 3
Ino Name Quantity 102 pencil 4
1 Pen 220 102 cd 5
2 Cd 530 Id = Primary key Id and Qty = Candidates Keys
3 Dvd 450 26. A table can have multiple choices for a primary key but only one can be set as the
primary key. All the keys which are not primary key are called an Alternate Key.
16. Primary key is a minimal super key, so there is one and only one primary key in Example: In this table, StudID, Roll No, Email are qualified to become a primary key.
any relationship but there is more than one candidate key can take place. Candidate Table : Student
key's attributes can contain a NULL value which opposes to the primary key. For StuID Roll No Sname Email
example, Student{ID, First_name, Last_name, Age} 101 210 Ajay Kumar Ajay04@
17. Cardinality refers to the number of tuples/rows in a table whereas, Degree refers 102 220 Vijay Kumar Vijay09@
to the number of attributes/columns in a table. 102 240 Anil Anil11@
18. DDL(data definition language): Deals with the structure(create,remove,or modify)
of databases and tables. E.g. Create,Drop ,alter. DML(data manupulation
StuID = Primary key Id and Roll No & Email = Alternate Keys
language):use to manipulate data/values within table e.g. insert,delete,update
19. An attribute value is an attribute name paired with an element of that attribute's
domain, and a tuple is a set of attribute values in which no two distinct elements have
27. A primary key is a column -- or a group of columns -- in a table that uniquely
the same name.
identifies the rows of data in that table. For example, in the table below, CustomerNo,
which displays the ID number assigned to different customers, is the primary key.
20. DROP is a Data Definition Language, DDL command and is used to remove named
Table : Customer
elements of schema like relations/table, constraints or entire schema.
Id No Customer_Name Dob
Removes an existing view from a database. DROP VIEW statement is used to remove B001 Smith 28/03/1976
a view or an object view from the database C002 Corth 23/09/1967
21. ALTER TABLE Item D007 John 03/02/1985
ADD (Discount INT); Id No = Primary key
DDL: DROP TABLE, ALTER TABLE 28. Alternate Key: In a table when more than one column is used for the
DML: INSERT INTO, UPDATE...SE identification of tuples in the table, then that is an alternate key.
133 134
Each table has only one primary key, although there are several choices. mysql> SELECT <Col Names> FROM <Table Name>WHERE <Condition>;
All the columns in the table other than the primary key act as an alternate key for that
table.
Candidate Key: This key is also used to identify the rows in a table.
It contains a group of attributes that can be used to identify a particular row.
Every table must have at least one column as a candidate key.
In the candidate key column it does not contain any NULL value.
29. i
ANAME ADDRESS
Nirja Singh Bangalore • Selecting/displaying entire data from the table
Rohan Gupta Chennai SELECT * fromtablename;
Ali Reza Hyderabad
Rishabh Jain Chennai
Simran Kaur Chandigarh

ii. Nirja Singh


iii. Bangalore Chennai Hyderabad Chandigarh

30. i ) table Altered. • Removing duplicate value from the column using distinctclause
s.no primary key. Table :Student
ii) Gurdeep Kaur
iii) Ram Gupta Chennai Roll_no Name Class Marks City
101 Rohan XI 400 Chennai
CASE BASE
102 Aneeta XII 390 Bengaluru
1.
103 Pawan Kumar IX 298 Mysore
SELECT Name,Class From Students Where Stream_name IS NULL OR
Stream_nameLIKE”%computers”; 104 Rohan IX 376 Mangalore
SELECT Name From StudentsWhere Stream_name IS NULL ; 105 Sanjay VII 240 Mumbai
SELECT Class From Students Where Stream_nameLIKE”%computers”; 113 Anju VIII 432 Delhi
SELECT Name From Students WhereStream_id IS Null;
SELECT Class From Students Where Stream_nameLIKE”%computers”;
2.
SELECT Sname FROM Class WHERE Grade IS ”Null”;
SELECT Sroll FROM Class WHERE Grade IS ”Null”;
SELECT Smark FROM Class WHERE Grade IS ”Null”;
SELECT * FROM Class WHERE Grade IS ”Null”;
SELECT Grade FROM Class WHERE Grade IS ”Null”;

Topics: Select, Operators(mathematical, relational and logical), aliasing, distinct clause, where clause,
in, between, order by, group by, having clause, meaning of null, is null, is not null, like, update
command, delete command, aggregate functions(max, min, avg, sum , count), joins: Cartesian
product on two tables, equi join and naturaljoin.
Insert, Update andDelete

Queries:
To retrieve information from a database we can query the databases. SQL SELECT statement is used to
select rows and columns from a database/relation
SELECT Command
This command can perform selection as well as projection.
Selection:This capability of SQL can return you the tuples form a relation with all the attributes.
Projection: This is the capability of SQL to return only specific attributes in the relation.
• Select data from Table using Selectstatement

135 136
SELECT DISTINCT column_name FROM tablename; The above query returns name and city columns of table student sorted by name in
DISTINCT keyword is used to restrict the duplicate rows from the results of a SELECT statement. increasing/ascending order.
e.g. SELECT DISTINCT name FROMstudent;
e.g. SELECT * FROM student ORDER BY cityDESC;
The above command returns,
Name It displays all the records of table student ordered by city in
Roha descendingorder. Note:- If order is not specifies that by default the
n sorting will be performed in ascendingorder.
Anee
ta GROUP BY Clause
Pawan Kumar The GROUP BY clause can be used in a SELECT statement to collect data across multiple records
and group the results by one or more columns.
Display all data from column using all clause The syntax for the GROUP BY clause is:
➢ SELECT ALL column_name FROMtablename; SELECT column1, column2, ... column_n, aggregate_function
➢ SELECT * FROM student; command will display all the tuples in (expression) FROM tables
therelation student WHERE conditions
GROUP BY column1, column2, ... column_n;
➢ SELECT * FROM student WHERE Roll_no<=102;
aggregate_functioncan be a function such as SUM, COUNT, MAX, MIN, AVG etc.
The above command display only those records whose Roll_no less than or equal to 102.
Select command can also display specific attributes from a relation.
e.g SELECT name, COUNT(*) as "Numberof
➢ SELECT name, class FROMstudent;
employees“ FROM student WHERE
The above command displays only name and class attributes from student table.
marks>350 GROUP BYcity;
➢ SELECT count(*) AS “Total Number of Records” FROMstudent;
HAVING Clause
Displays the total number of records with title as “Total Number of Records” i.e an alias We can
The HAVING clause is used in combination with the GROUP BY clause. It can be used in a SELECT
also use arithmetic operators in select statement, like statement to filter the records that a GROUP BY returns.
➢ SELECT Roll_no, name, marks+20 FROMstudent; The syntax for the HAVING clause is:
➢ SELECT name, (marks/500)*100 FROM student WHERE Roll_no>103; SELECT column1, column2, ... column_n, aggregate_function
(expression) FROM tables
Conditions based on a range WHERE predicates
SQL provides a BETWEEN operator that defines a range of values that the column value must fall for GROUP BY column1, column2, ...
the condition to become true. column_n HAVING condition1 ...
e.g. SELECT Roll_no, name FROM student WHERE Roll_no BETWENN 100 AND 103; condition_n;
The above command displays Roll_no and name of those students whose Roll_no lies in the range 100 e.g SELECT SUM(marks) as "Total marks"
to 103 (both 100 and 103 are included in the range). FROMstudent
GROUP BY department HAVING
Conditions based on a list SUM(sales) > 1000;
To specify a list of values, IN operator is used. This operator select values that match any value in Note: select statement can contain only those attribute which are already present in the group by
the given list. clause.
e.g. SELECT * FROM student WHERE city
IN (‘Bengaluru’,’Delhi’,’Chennai’); MODIFYING DATA IN TABLES
The above command displays all those records whose city is either Bengaluru or ❖ Syntax: UPDATE
Delhi or Chennai ,TABLENAME> SET
ORDER BY Clause <COLNAME> = <VALUE>;
ORDER BY clause is used to display the result of a query in a specific order(sorted order). Write a command to modify the salary of all employee by increasing it with 5000.
The sorting can be done in ascending or in descending order. It should be kept in mind that the UPDATE EMP
actual data in the database is not sorted but only the results of the query are displayed in SET SALARY = SALARY + 5000;
sorted order.

e.g. SELECT name, city FROM student ORDER BYname; ❖ DELETING DATA FROMTABLES
137 138
Syntax: DELETE FROM <TABLE NAME> WHERE <SEARCH CONDITION>;
Write a command to delete all rows from EMP whose deptno is 10. DELETE FROM
EMP WHERE DEPTNO = 10;
Comparing NULL is null – is not null
❖ ALTERINGTABLES NULL (Absence of value) value cannot be compared using Relational operator. The above statement
is used to check whether column contains NULL or not.
Syntax: ALTER TABLE <TABLENAME>; ADD/MODIFY/CHANGE Relational Operator
<COLNAME><DATATYPE>; > greater than
< less than
Write a command to add a new column PHNO in table emp. >= greater than equal to
<= less than equal to
ALTER TABLE EMP = equal
ADD PHNO INT; ! = or <> not equal to
Logical Operator
Write a command to modify column Job the table EMP , change the width of it to And – evaluated true if all the logical expression is true otherwise false. Or - evaluated
30. true if any the logical expression is true otherwise false. Logical operator is used
ALTER TABLEEMP to combine two or more logical expression,
MODIFY JOB VARCHAR(30); Membership Operator
in –
Write a command to change the existing column name ENAME to EMPNAME in table EMP. N
o
ALTER TABLE EMP t
CHANGE ENAME EMPNAME VARCHAR(30); i
n
❖ DROPPINGTABLES The IN operator allows you to specify multiple values in a WHERE clause. The IN operator
is a shorthand for multiple OR conditions.
Syntax : Aggregate Functions
DROP TABLE [IF EXISTS] <TABLE NAME>; ➢ An aggregate function performs a calculation on multiple values and
returns a single value.
Write a command to drop table emp. DROP ➢ These function work on multiple rows collectively return single value.
TABLE IF EXISTS EMP; ➢ List of Aggregate functions are
• max() : return maximum value in set of value
Performing simple calculation in the query Syntax: • min() – return minimum value from the set of values
Select 2+4; • avg() –return average value in set of non-null values
All operation can be perform such as addition (+), subtraction (-), multiplication (*), division (/) • sum() - Return the summation of all non-NULL values of the set of values.
and remainder (%)
Number of row in result depend on total number of rows in the table. count() - Return the number of rows in a group
➢ Performing calculation oncolumn ▪ count(*) – return number of rows, including rows with NULL
Syntax:SELECT column1 operator value, column2…. FROM Tablename clause

➢ Working with nullvalue

Any operation on NULL will result into NULL, MySql provide ifnull() function to work with null value.
If column contain null value it is replace value given value, otherwise display original value.
Syntax: if null(column, value_to_replace‟)

Here, comm column contains null value


▪ count(column_name) - return number of rows, excluding rows
which is replaced by „N/A‟.
with NULL for the given column
▪ count (distinct column_name) – return number of rows
with duplicateremoved

139 140
In above example there are 14 row in the EMP table, but distinct clause only
consider unique value. Non-EquiJoin
A non-equi join is a join condition containing something other than an equality operator, e.g. there
JOIN are
A JOIN is a query through which we can extract queries from two or more tables. It means, it two given tables EMPLOYEES and JOB_GRADES
combines rows from two or more tables. Rows in one table can be joined to rows in another table
according to common values existing in corresponding columns.
A relational database consists of multiple related tables linking together using common columns,
which are known as foreign key columns.
➢ It is used retrieve data from multiple tables.
➢ Consider the tables below EMPLOYEES, DEPARTMENTS and JOBGRADES
that stored related information, all the examples on join will be explained with
helpof these following three tables.

1. EQUI-JOIN
In an EQUI-JOIN operation, the values in the columns are being joined and compared for equality. All The relationship between the EMPLOYEES table and JOB_GRADES table has an example of a non-
the columns in the tables being joined are included in the results, e.g. Two tablesEMPLOYEES and equi join. A relationship between the two tables is that the SALARY column in the EMPLOYEES
DEPARTMENTS are given below: table must be between the values in LOWEST_SAL and HIGHEST_SAL columns of the
JOB_GRADES table. The relationship is obtained using an operator other than equals (=).

To determine the employees grade according to salary, we need to write following query:
SELECT e.Last_name, j.GRA FROM EMPLOYEES e, JOELGRADES j WHERE
e.SALARY BETWEEN j.LOWEST_SAL AND j.HIGHEST SAL;
Output

Todetermine an employee‟s department name you compare the value Department_id column in the
EMPLOYEES table with Department_id values in theDEPARTMENTS table. The
relationship between the EMPLOYEES and
DEPARTMENTS tables is an equi-join that is, values in the Department_id column on both
tables must be equal. 2. NaturalJoin
Todetermineemployee‟sdepartmentname,weneedtowritefollowingquery: Usually the result of an equi-join contains two identical columns. Here by restarting the query, we
can eliminate one of the two identical columns. It is known as Natural Join.
SELECT EMPLOYEES.Employee_id, DEPARTMENTS.Department_name FROM We can also join two tables using the natural join using NATURAL JOIN clause. SELECT * FROM <tablel>
EMPLOYEES, DEPARTMENTS NATURAL JOIN <table2>; e.g. there are two given tables FOOD and COMPANY:
WHERE EMPLOYEES. Department_id = DEPARTMENTS. Department_Id;
Output

The relationship between the FOOD table and COMPANY table has an example of a Natural Join. To
get all the unique columns from FOOD and COMPANY tables, the following sql statement can be
used.

141 142
e.g.SELECT * FROM FOODNATURAL JOIN COMPANY; Ans. fetchmany()
Output 4. Which method is used to close the open database connection?
Ans. <connectionobject>.close()
5. To make the changes made by any SQL Queries permanently in
database, which function is used after execution of the query ?
Ans. <connectionobject>.commit()

6. Which function is used to execute an SQL query from within a Python


Cartesian Product program?
The cartesian product is a binary operation and is denoted by (x). The degree of new relation is the Ans. execute()
sum of the degrees of two relations on which Cartesian product is operated. The number of 7. Identify the name of connector to establish bridge between Python and MySQL
tuples, of the new relation is equal to the product of the number of tuples, of the two relations a) mysql.connection
on which Cartesian product is performed. b) connector
e.g. if A = {1, 2, 3} and B = {a, b, c}, find A x B. c) mysql.connect
A x B = ((1, a), (1, b), (1, c), (2, a), (2, b), (2, c), (3, a), (3, b), (3, c)) d) mysql.connector
In SQL the CROSS JOIN or CARTESIAN JOIN is used to produce the cartesian product of two Ans. d. mysql.connector
tables. 8. In the following connection string: Identify the elements:
The Cartesian product is a basic type of join that matches each row from one table to every row connect(<<1>> =127.0.0.1, <<2>> =‟root‟, <<3>> =„admin‟)
from another table. a. <<1>> = User, <<2>> = password, <<3> =host
e.g. Consider the following EMPLOYEES and DEPARTMENTS tables: b. <<1>> = host, <<2>> = user, <<3> =password
c. <<1>> = host, <<2>> = password, <<3> =user
d. <<1>> = IP, <<2>> = user, <<3> = password
Ans. b. <<1>> = host, <<2>> = user, <<3> = password
connect(host= 127.0.0.1, user= ‘root’, password= ‘admin’)
9. Which of the following component act as a container to hold all the data returned from the
query and from there we can fetch data one at a time?
To get the cartesian product, the following sql statement can be used: a) ResultSet c) Container
b) Cursor d) Table
SELECT EMP_name, EMPjd FROM EMPLOYEESCROSS JOIN DEPARTMENTS: Ans. b. Cursor
Output 10.Which attribute of cursor is used to get number of records stored in cursor (Assuming cursor
name ismycursor)?
a) mycursor.count
b) mycursor.row_count
c) mycursor.records
d) mycursor.rowcount

1 MARK QUESTIONS

1. What is connection? What is its role?


Ans. A Connection (represented through a connection object) is the session
between the application program and the database. To do anything with database,
one must have a connection object
2. Which package must be imported in Python to create a database
connectivity application?
Ans. There are multiple packages available through which database connectivity
applications can be created in Python. One such package is mysql.connector.
3. Which function is used to get multiple records retrieved as the result of
SQL query executed?
143 144
se=”MYPROJECT”)
Ans. d. mycursor.rowcount 2. The given program is used to connect with MySQL abd show the name of the all
2 MARKS QUESTIONS the record from the table “stmaster” from the database “oraclenk”. You are
1. Write the code to create the connection in which database’s name is Python, required to complete the statements so that the code can be executed properly.
name of host, user and password can taken by user. Also, print that connection? import _____.connector__pymysql
Ans.import mysql.connector dbcon=pymysql._____________(host=”localhost”, user=”root”,
mycon = mysql.connector.connect( host = “localhost”, user = “root”, passwd = “tiger”, ________=”sia@1928”)
database = “Python”) if dbcon.isconnected()==False
print(mycon) print(“Error in establishing connection:”)
3. Explain the following results retrieval methods with examples- cur=dbcon.______________()
fetchone () rowcount () query=”select * from stmaster”
Ans. fetchone() :- The fetchone() method will return only one row from the result set in the cur.execute(_________)
form of tuple containing a record. resultset=cur.fetchmany(3)
rowcount() :- cursor.rowcount() that always return how many records have been retrieved for row in resultset:
so for using any of the fetch..() methods. print(row)
3. Write a small python program to insert a record in the table books with dbcon.______()
attributes (title ,isbn).
Ans. import mysql.connector as Sqlator Ans. import mysql.connectoraspymysql
conn =sqlator.connect(host=”localhost”,user=”root”,passwd=””,database=”test”) dbcon=pymysql.connect(host=”localhost”, user=”root”, passwd=”sia@1928”)
cursor=con.cursor() if dbcon.isconnected()==False
query=”INSERT into books(title,isbn) values(‘{}’{})”.format(‘Neelesh’,’5143’) print(“Error in establishing connection:”)
cursor.execute(query) cur=dbcon.cursor()
con.close() query=”select * from stmaster”
4. Differentiate between fetchone() and fetchall() methods. cur.execute(query)
Ans. fetch(): It returns the next row from the result set as tuple. If there are no more resultset=cur.fetchmany(3)
rows to retrieve, None is returned. for row in resultset:
fetchall():It fetches all the rows of a query result. It returns all the rows as a list of tuples. print(row)
An empty list is returned if there is no record to fetch. dbcon.close()
5. Consider the following Python code for updating the records:
def Update(eno): 3. Explain various database operations one can perform using MySQL-Python
#Assume basic setup import, connection(con) and cursor(mycursor) is created query="update emp set connectivity.
salary=90000 where empno=” + str(eno) mycursor.execute(query) Ans. INSERT, READ, UPDATE, DELETE, ROLLBACK (explain in detail )
4. Consider the information stored in the table: EMP
Codeisrunningbuttherecordinactualdatabaseisnotupdating,whatcouldbethepossible reason?
a) save() function ismissing EMPNO ENAME DEPT SALARY
b) con.save() function ismissing 1 ALEX MUSIC 60000
c) con.commit() function ismissing 2 PETER ART 67000
d) commit() function ismissing 3 JOHNY WE 55000
4 RAMBO P&HE 48000
Ans. c. con.commit() function is missing
Following python code is written to access the records of table : EMP, What will be the output of following
3 MARKS QUESTIONS
code?
1. Avni is trying to connect Python with MySQL for her project. Help her to write
the python statement on the following:-
(i) Name the library, which should be imported to connect MySQL with Python. # Assume All basic setup related to connection and cursor creation is already done
(ii)Name the function, used to run SQL query in Python. query="select * fromemp"
(iii) Write Python statement of connect function having the arguments values mycursor.execute(query)
as :Host name :192.168.11.111 results = mycursor.fetchone()
User : root results = mycursor.fetchone()
Password: Admin results = mycursor.fetchone()
Database : MYPROJECT d = int(results[3])
print(d*3)
Ans. (i) import mysql.connector Ans. 165000
(ii) execute (<sql query >) 5. Find the output:
(iii)mysql.connector.connect(host=”192.168.11.111”,user=”root”,passwd=”Admin”,databa

145 146
Ans. Total records fetched so far are 1
Total records fetched so far are2
Total records fetched so far are4

147

You might also like