Xii - Cs Final Material
Xii - Cs Final Material
SILCHAR REGION
INDEX
Computer Science
CLASS-XII Code No. 083
2023-24
1. Prerequisites Computer Science- Class XI
2. Learning Outcomes Student should be able to
a) Apply the concept of function.
b) Explain and use the concept of file handling.
c) Use basic data structure: Stacks
d) Explain basics of computer networks.
e) Use Database concepts, SQL along with connectivity between Python and SQL.
3. Distribution of Marks:
Unit No. Unit Name Marks Periods
Theory Practical
I Computational Thinking and Programming –2 40 70 50
II Computer Networks 10 15 …
III Database Management 20 25 20
Total 70 110 70
4. Unit wise Syllabus Unit I:
● Func ons: types of function (built-in functions, functions defined in module, user defined
functions), creating user defined function, arguments and parameters, default parameters,
positional parameters, function returning value(s), flow of execution, scope of a variable (global
● Excep on Handling: Introduc on, handling excep ons using try-except-finally blocks
● Introduc on to files, types of files (Text file, Binary file, CSV file), rela ve and absolute paths
● Text file: opening a text file, text file open modes (r, r+, w, w+, a, a+), closing a text file, opening a file
using with clause, writing/appending data to a text file using write() and writelines(), reading from a text file
using read(), readline() and readlines(), seek and tell methods, manipulation of data in a text file
● Binary file: basic opera ons 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
● CSV file: import csv module, open / close csv file, write into a csv file using writer(),writerow(),writerows()
● Data Structure: Stack, opera ons on stack (push & pop), implementation of stack using list. Unit II:
Computer Network
NSFNET, INTERNET)
(sender, receiver, message, communication media, protocols), measuring capacity of communication media
(bandwidth, data transfer rate), IP address, switching techniques (Circuit switching, Packet switching)
● Transmission media: Wired communication media (Twisted pair cable, Co-axial cable, Fiber-optic cable),
● Network devices (Modem, Ethernet card, RJ45, Repeater, Hub, Switch, Router, Gateway, WIFI card)
● Network topologies and Network types: types of networks (PAN, LAN, MAN, WAN), networking
● Network protocol: HTTP, FTP, PPP, SMTP, TCP/IP, POP3, HTTPS, TELNET, VoIP
● Introduc on to web services: WWW, Hyper Text Markup Language (HTML), Extensible Markup Language
(XML), domain names, URL, website, web browser, web servers, web hosting
● Rela onal data model: rela on, a ribute, Tuple, domain, degree, cardinality, keys (candidate key,
● Structured Query Language: introduc on, Data Defini on Language and Data Manipula on Language,
data type (char(n), varchar (n), int, float, date), constraints (not null, unique, primary key), create database,
use database, show databases, drop database, show tables, create table, describe table, alter table (add
and remove an attribute, add and remove primary key), drop table, insert, delete, select, operators
(mathematical, relational and logical), aliasing, distinct clause, where clause, in, between, order by,
meaning of null, is null, is not null, like, update command, delete command, aggregate functions (max, min,
avg, sum, count), group by, having clause, joins: cartesian product on two tables, equi-join and natural join
● Interface of python with an SQL database: connec ng SQL with Python, performing insert, update, delete
queries using cursor, display data by using connect(), cursor(), execute(), commit(), fetchone() , fetchall(),
rowcount, creating database connectivity applications, use of %s format specifier or format() to perform
queries
5. Practical
1 Lab Test: 8
1.Pythonprogram(60%logic+20%documentation
+20%codequality)
2 Report file: 7
● Minimum15Python programs.
● SQL Queries –Minimum 5 sets using one table
/two tables.
● Minimum4programsbasedonPython -SQL connectivity
4 Viva voce 3
Revision Tour-I
Computational thinking and programming-2
(Topics covered in Class XI)
Basics of Python
Observe the program first then memorize the definitions:
Identifiers:
In programming languages, identifiers are names used to identify (Name) 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 reserve 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. Value of a variable can be a string
(e.g., ‘b’, ‘Global Citizen’), numeric (e.g., 345) or any combination of alphanumeric characters
(CD67). In Python we can use an assignment statement to create new variables and assign
specific values to them.
Comments:
Comments are used to add a remark or a note in the source code. Comments are not executed by
interpreter. Comments in python can be created as:
For single line comment use # (hash symbol)
For multi line comment use ‘‘‘ text ’’’ (in triple quotes)
Data Types:
Every value belongs to a specific data type in Python. Data type identifies the type of data
values a variable can hold and the operations that can be performed on that data.
Number:
Number data type stores numerical values only. It is further classified into three different types:
int, float and complex. Try the following statements on system in shell mode and observe the
output:
Boolean:
var3= True # (var3 variable contain Boolean Value)
print(type(var3)) # print type Bool
Variables of simple data types like int, float, boolean, etc. hold single values. But such variables
are not useful to hold a long list of information, for example, names of the months in a year,
names of students in a class, names and numbers in a phone book or the list of artefacts in a
museum. For this, Python provides data types like tuples, lists, dictionaries and sets.
Prove this statement using proper example: We cannot perform numerical operations on strings, even when
the string contains a numeric value.
(B) List
List is a sequence of items separated by commas and the items are enclosed in square brackets [ ]. In
list we can change the items so we can say it’s a mutable datatype #To create a list
T=5,6,7,8
T= ‘a’,’b’,’c’,5,6,7
T=(5,6,’r’,’s’,’wel’)
(D) Dictionary
Dictionary in Python holds data items in key : value pairs. Items in a dictionary are enclosed in curly
braces {}. Every key is separated from its value using a colon (:) sign. The key : value pairs of a
dictionary can be accessed using the key. The keys are usually strings and their values can be any
data type. In order to access any value in the dictionary, we have to specify its key in square brackets
[ ].
(E) None
None is a special data type with a single value. It is used to signify the absence of value in a
situation. None supports no special operations, and it is neither False nor 0 (zer
Precedence of Operators
Evaluation of the expression is based on precedence of operators. When an expression contains
different kinds of operators, precedence determines which operator should be applied first.
Higher precedence operator is evaluated before the lower precedence operator. (Simply apply
BODMAS rules)
* For operators with equal precedence, the expression is evaluated from left to right except
** which is executed from right to left.
Flow of Control
Selection
2)
if condition:
statement(s)
else:
statement(s)
3) if condition:
statement(s)
elif condition:
statement(s)
.
.
elif condition:
statement(s)
else:
statement(s)
NOTE
Indentation
Python uses indentation for block as well as for nested block structures. Leading whitespace
(spaces and tabs) at the beginning of a statement is called indentation. In Python, the same
level of indentation associates statements into a single block of code. The interpreter checks
indentation levels very strictly and throws up syntax errors if indentation is not correct. It is a
common practice to use a single tab for each level of indentation.
Repetition
Repetition of a set of statements in a program is made possible using looping constructs.
The ‘for’ Loop
The for statement is used to iterate over a range of values or a sequence. The for loop is
executed for each of the items in the range. These values can be either numeric, or they can be
elements of a data type like a string, list, tuple or even dictionary.
Syntax of the for Loop
for <control-variable> in <sequence/ items in range>:
<statements inside body of the loop>
The ‘while’ Loop
The while statement executes a block of code repeatedly as long as the control condition of
the loop is true. The control condition of the while loop is executed before any statement inside
the loop is executed. After each iteration, the control condition is tested again and the loop
continues as long as the condition remains true. When this condition becomes false, the
statements in the body of loop are not executed and the control
is transferred to the statement immediately following the body of while loop. If the condition of
the while loop is initially false, the body is not executed even once.
c) 25
d) 2
29 Suppose list1 is [2, 33, 222, 14, 25], What is list1[:-1]?
a) [2, 33, 222, 14]
b) Error
c) 25
d) [25, 14, 222, 33, 2]
30 To add a new element to a list we use which command?
a) list1.add(5)
b) list1.append(5)
c) list1.addLast(5)
d) list1.addEnd(5)
31 To insert 5 to the third position in list1, we use which command?
a) list1.insert(3, 5)
b) list1.insert(2, 5)
c) list1.add(3, 5)
d) list1.append(3, 5)
32 Suppose list1 is [3, 4, 5, 20, 5], what is list1.index(5)?
a) 0
b) 1
c) 4
d) 2
Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1.count(5)?
a) 0 b) 4
c) 1 d) 2
33 Suppose listExample is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after listExample.extend ([34, 5])?
a) [3, 4, 5, 20, 5, 25, 1, 3, 34, 5]
b) [1, 3, 3, 4, 5, 5, 20, 25, 34, 5]
c) [25, 20, 5, 5, 4, 3, 3, 1, 34, 5]
d) [1, 3, 4, 5, 20, 5, 25, 3, 34, 5]
34 Suppose listEx is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after listEx.pop() ?
a) [3, 4, 5, 20, 5, 25, 1]
b) [1, 3, 3, 4, 5, 5, 20, 25]
c) [3, 5, 20, 5, 25, 1, 3]
d) [1, 3, 4, 5, 20, 5, 25]
35 Suppose d = {“john”:40, “peter”:45}, to delete the entry for “john” what command do we use?
a) d.delete(“john”:40)
b) d.delete(“john”)
c) del d[“john”]
d) del d(“john”:40)
36 Which of the following is not a declaration of the dictionary?
a) {1: ‘A’, 2: ‘B’}
b) dict([[1,”A”],[2,”B”]])
c) {1,”A”,2”B”}
d) { }
37 Which of the following isn’t true about dictionary keys?
a) More than one key isn’t allowed
b) Keys must be immutable
c) Keys must be integers
d) When duplicate keys encountered, the last assignment wins
38 What will be the output of the following Python code?
a={}
a[2]=1
a[1]=[2,3,4]
print(a[1][1])
a) [2,3,4]
b) 3
c) 2
d) An exception is thrown
39 Which of the following statement prints hello\example\test.txt?
a) print(“hello\example\test.txt”)
b) print(“hello\\example\\test.txt”)
c) print(“hello\”example\”test.txt”)
d) print(“hello”\example”\test.txt”)
40 What will be the output of the “hello” +1+2+3?
a) hello123
b) hello
c) Error
d) hello6
41 Say s=”hello” what will be the return value of type(s)?
a) int
b) bool
c) str
d) String
42 What is “Hello”.replace(“l”, “e”)?
a) Heeeo
b) Heelo
c) Heleo
d) None
43 What will be the output of the following Python code?
Given a string example=”hello” what is the output of example.count(‘l’)?
a) 2
b) 1
c) None
d) 0
44 What will be displayed by print(ord(‘b’) – ord(‘a’))?
a) 0 b) 1
c) -1 d) 2
45 What will be the output of the following Python code?
print(“abc DEF”.capitalize())
a) abc def
b) ABC DEF
c) Abc def
d) Abc Def
46 What will be the output of the following Python code?
print(‘a B’.isalpha())
print(‘my_string’.isidentifier())
print(‘xyxxyyzxxy.lstrip(‘xyy’))
print(‘abcdef12’.replace(‘cd’,’12’))
a) ab12ef12
b) abcdef12
c) ab12efcd
d) none of the mentioned
50 What will be the output of the following Python code?
list1 = [1,2,3,4]
list2 = [5,6,7,8,]
print(len(list1+list2))
a) 2
b) 4
c) 5
d) 8
a) Error b) None
c) 25 d) 2
Ans C
29 Suppose list1 is [2, 33, 222, 14, 25], What is list1[:-1]?
a) [2, 33, 222, 14] b) Error
c) 25 d) [25, 14, 222, 33, 2]
Ans A
30 To add a new element to a list we use which command?
a) list1.add(5)
b) list1.append(5)
c) list1.addLast(5)
d) list1.addEnd(5)
Ans B
31 To insert 5 to the third position in list1, we use which command?
a) list1.insert(3, 5)
b) list1.insert(2, 5)
c) list1.add(3, 5)
d) list1.append(3, 5)
Ans B
32 Suppose list1 is [3, 4, 5, 20, 5], what is list1.index(5)?
a) 0
b) 1
c) 4
d) 2
Ans D
Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1.count(5)?
a) 0 b) 4 c) 1 d) 2
Ans D
33 Suppose listExample is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after listExample.extend([34, 5])?
a) [3, 4, 5, 20, 5, 25, 1, 3, 34, 5]
b) [1, 3, 3, 4, 5, 5, 20, 25, 34, 5]
c) [25, 20, 5, 5, 4, 3, 3, 1, 34, 5]
d) [1, 3, 4, 5, 20, 5, 25, 3, 34, 5]
Ans A
34 Suppose listExample is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after listExample.pop()?
a) [3, 4, 5, 20, 5, 25, 1]
b) [1, 3, 3, 4, 5, 5, 20, 25]
c) [3, 5, 20, 5, 25, 1, 3]
d) [1, 3, 4, 5, 20, 5, 25]
Ans A
35 Suppose d = {“john”:40, “peter”:45}, to delete the entry for “john” what command do we use?
a) d.delete(“john”:40) b) d.delete(“john”)
c) del d[“john”] d) del d(“john”:40)
Ans C
36 Which of the following is not a declaration of the dictionary?
a) {1: ‘A’, 2: ‘B’}
b) dict([[1,”A”],[2,”B”]])
c) {1,”A”,2”B”}
d) { }
C
37 Which of the following isn’t true about dictionary keys?
a) zxxy b) xyxxyyzxxy
c) xyxzxxy d) none of the mentioned
Ans A
49 What will be the output of the following Python code snippet?
print(‘abcdef12’.replace(‘cd’,’12’))
a) ab12ef12 b) abcdef12
c) ab12efcd d) none of the mentioned
Ans A
50 What will be the output of the following Python code?
list1 = [1,2,3,4]
list2 = [5,6,7,8,]
print(len(list1+list2))
a) 2 b) 4 c) 5 d) 8
Ans D
Q1. Rahul has written a code to input a number and return its reverse. His code is having errors. Rewrite
the correct code and underline the corrections made.
def reverse()
n=int(input("Enter number :: ")
rev=0
while(num>0):
r=num%10
rev=rev*10+r
num=num//10
return rev
ANS:
def reverse():
n=int(input("Enter number :: ")
rev=0
while(num>0):
r=num%10
rev=rev*10+r
num=num//10
return rev
new_tuple = tuple(new_list)
print(new_tuple)
ANS:
brS0!
a*!
TXT = ["20","50","30","40"]
CNT = 3
TOTAL = 0
for C in [7,5,4,6]:
T = TXT[CNT]
TOTAL = float (T) + C
print (TOTAL)
CNT-=1
Ans: 47.0
35.0
54.0
26.0
Q6. Rewrite the following code in Python after removing all syntax error(s). Underline
each correction done in the code.
S=””EXAM
for i in range [0,6]:
print [S(i)]
Ans:
S=”EXAM” # EXAM must be enclosed in double quotes
for i in range (0,6):
print(S[i]) # () to be replaced with [],[] instead of ()
Q7. Which of the following options can be the output for the following code?
import random as r
week_day={1:'Mon',2:'Tue',3:'Wed',4:'Thu',5:'Fri',6:'Sat',7:'Sun'}
ue',3:'Wed',4:'Thu',5:'Fri',6:'Sat',7:'Sun'}
day_num=r.randint(0,5)+ 2
for var in range(2,day_num):
print(" Day ",week_day[var],end=' | ')
i. Day Mon | Day Tue | Day Wed | Day Thu | Day Fri | Day Sat |
ii. Day Tue | Day Wed | Day Thu | Day Fri |
iii. Day Mon | Day Tue | Day Wed | Day Thu | Day Fri | |
iv. Day Tue | Day Wed | Day Thu | Day Fri | Day Sat |
Ans. b. ii , iv
DATA TYPES
23 STUDENT SUPPORT MATERIAL 2023-24
Strings in Python
A String is a data structure in Python that represents a sequence of characters.
It is an immutable data type, meaning that once you have created a string, you cannot change it.
Strings are used widely in many different appapplications,
lications, such as storing and manipulating text data,
representing names, addresses, and other types of data that can be represented as text.
a single character is simply a string with a length of 1.
Indexing can be used to access each element in string
Forward
orward and backward indexing
Dictionaries in Python
The data type dictionary fall under mapping. It is a mapping between a set of keys 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 dictionaries are unordered, so we may not get back the data in the same
order in which we had entered the data initially in the 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.
The following example shows how a dictionary returns the value corresponding to the
given key:
Exercise
Q.NO Question Marks
1 String Traversal can be done using for loop only, [Y/N] 1
2 Give output: 1
list1 = [1,2,'a','c',[6,7,8],4,9]
print(list1[4])
I. [6,7,8]
II. [6]
III. ‘[c]’
IV. Error
3 1
4 1
5 1
8 1
9 Membership operator in takes two strings and returns True if the first string 1
appears as a substring in the second else returns False. [T/F]
10 message='FirstPreBoardExam@2023-24'
message='FirstPreBoardExam@2023
Write the output of:
print(message[ : : -3].upper())
11 Vivek
ivek has written a code to input a number and check whether it is even or 2
odd number. His code is having errors. Rewrite the correct code and underline
the corrections made.
Def checkNumber(N):
status = N%2
return
#main-code
num=int( input(“ (“ Enter a number to check :))
k=checkNumber(num)
if k = 0:
print(“This is EVEN number”)
else:
print(“This is ODD number”)
13 2
14 2
18 2
19 2
20 Rewrite the following code in python after removing all syntax error(s). 2
Underline each
correction done in the code.
Num=int(rawinput("Number:"))
sum=0
for i in range(10,Num,3)
sum+=1
if i%2=0:
print(i*2)
else:
print(i*3)
print (Sum)
21 Consider the following string mySubject: 3
mySubject = "Computer Science"
What will ill be the output of the following string operations:
i. print(mySubject[0:len(mySubject)])
ii. print(mySubject[-7:-1])
iii print(mySubject[len(mySubject)
print(mySubject[len(mySubject)-1])
iv. print(2*mySubject)
v. print(mySubject[::-2])
vi. print(mySubject[:3] + mySubject[3:])
elif s[i].isdigit():
m=m+"O"
else:
m=m+'#'
print(m)
fun('CBSE@12@Exam')
1 False
2 i. [6,7,8]
3 (d)
4 ©
5 ©
6 {'A':4000, 'B':2500, 'C':3000}
7 TO@AG - No partial marking
8 (A) 322ADORSF
9 True
10 432ADORSF
11
12 {2: 3, 4: 3, 1: 2, 3: 2}
The dictionary elements can be written in any order.
13 1 20 L@
4 60 L@M@
9 120 L@M@N@
(½ M + ½ M + 1 M) means ½ - ½ marks for first two lines and 1 mark for fo last line.
14
[(2, 4), (4, 16)]
( ½ mark for each correct pair of tuple , ½ mark for enclosing in parenthesis) means concept of tuple and
list
15
5
19 9 A#B#C# 120
20
21
22 c&&vVpP
23 70 40 30
110 60 50
24
25
33 STUDENT SUPPORT MATERIAL 2023-24
FUNCTIONS
Python Function:- Functions is a block of code that is identified by its name. A function can be
executed by calling it. Writing the name of the function will call a function. Functions are internally
declared in a separate memory area. So, a function can declare variables with the same as declared in the
outer part of the program.
Types of Functions
Name the function and specifies what to do when the function is called. Python interpreter ignores the
function definition until the function is called.
Calling a function:
Calling the function actually performs the specified actions with the indicated parameters
Function Definition in Python
Arguments: Information can be passed into functions as arguments. Arguments are specified after the
function name, inside the parentheses. You can add as many arguments as you want, just separate
them with a comma.
34 STUDENT SUPPORT MATERIAL 2023-24
Actual Parameters (Arguments) are values supplied to the function when it is invoked/called
Formal Parameters are variables declared by the function that get values when the function is
called.
Example :
Observe the following code:
Output:
In the above example, a user defined function “function1” has been defined that
receives one argument. Once the function is defined, it can be called any number of
times with different arguments.
Formal argument: x
Actual argument:
“first call to function “ passed in first call “second call to function” passed in second call
Example : Write a function ADD(A,B) that receives two integer arguments and prints
their sum.
Output:
Example :
Observe the following code:
Output:
35 STUDENT SUPPORT MATERIAL 2023-24
In the above example, a user defined function “function1” has been defined that
receives one argument. Once the function is defined, it can be called any number of
times with different arguments.
Formal argument: x
Actual argument:
“first call to function “ passed in first call
“second call to function” passed in second call
Example 2: Write a function ADD(A,B) that receives two integer arguments and prints
their sum.
Output:
return keyword:
In Python, the `return` keyword is used in functions to specify the value that the function will return when
it is called. When a function is executed, it may perform some computations or operations, and the result
can be sent back to the caller using the
`return`statement.
3.Returning None:
If a function doesn't have a `return` statement or has a `return` statement without any
value, it implicitly returns `None`.
`None` is a special constant in Python that represents the absence of a value.
The `return` statement is a powerful tool that enables functions to produce results and
pass data back to the calling code. Understanding how to use it correctly will help you
design and implement effective functions in Python.
Scope of a variable: In Python, the scope of a variable refers to the region of the program where the
variable is accessible. The scope determines where a variable is created, modified, and used.
Global Scope:
Local Scope:
Please note that when a list if passed as arguments, the original copy of List is passed to the function
i.e if any change is made at any index in the list inside the function, it is reflected in original list. That is
because list is a mutable datatype and in Python, when you pass a list as an argument to a function, you
are actually passing a reference to the list rather than a copy of the list. This means that the function
parameter will point to the same memory location as the original list. As a result, any changes made to the
list within the function will be reflected in the original list outside the function.
However, if you assign a different list to a variable inside a function in Python, it will create a new local
variable that is separate from any variables outside the function. This local variable will only exist within
the scope of the function, and changes made to it won't affect the original list outside the function.
38 STUDENT SUPPORT MATERIAL 2023-24
Output:
Global keyword
In Python, the global keyword is used to indicate that a variable declared inside a function should be
treated as a global variable, rather than a local variable. When you assign a value to a variable inside a
function, Python, by default, creates a local variable within that function's scope. However, if you need to
modify a global variable from within a function, you must use the global keyword to specify that you want
to work with the global variable instead.
Here's the basic syntax for using the global keyword:
For example:
Positional Arguments:
These are the most common type of arguments and are matched to
the function parameters based on their positions. The first argument
corresponds to the first parameter, the second argument corresponds
to the second parameter, and so on.
The number and order of positional arguments must match the
function's parameter list.
Default Arguments:
Default arguments are used when a function is called with fewer arguments than there
are parameters.
The default values are specified in the function definition.
39 STUDENT SUPPORT MATERIAL 2023-24
If a value is not provided for a parameter during the function call, the
default value is used.
Keyword Arguments:
In this type, each argument is preceded by a keyword (parameter
name) followed by an equal sign.
The order of keyword arguments does not matter, as they are
matched to the function parameters based on their names.
These arguments provide flexibility to call a function with arguments
passed in any order.
Python modules:
In Python, a module is a file containing Python code that defines variables, functions,
and classes.
Modules allow you to organize and reuse code by breaking it into separate files, making
it easier to maintain and understand complex programs.
Python's standard library comes with a vast collection of built-in modules that cover
various functionalities
If needed, you can also create your own custom modules.
To use a module in your Python code, you need to import it using the import statement.
math module:
The math module in Python is a built-in module that provides various mathematical
functions and constants.
It is part of the Python Standard Library i.e. it does not require any additional
installation to use.
To use the math module, you need to import it at the beginning of your Python script.
Once you've imported the module, you can access its functions and constants using the
math prefix.
Here are some commonly used functions and constants provided by the math module:
40 STUDENT SUPPORT MATERIAL 2023-24
Mathematical Constants:
Example 1:
Example 2:
Example 3:
41 STUDENT SUPPORT MATERIAL 2023-24
Statistics module:
Example 1:
Example 2:
Random module
Example 1:
What is the possible outcome/s of following code?
Possible options:
a. green
b. yellow
c. blue
d. orange
Solution:
Here, the possible values for variable random-sample are 3, 4 and 5. Hence, the possible Outputs of
above code are b) Yellow and d) orange.
Example 2:
What are the possible output/s for the following code?
Output Options:
i. 29: 26:25 :28 : ii. 24: 28:25:26:
Example 3:
What are the possible outcome/s for the following code:
Output Options:
i. 103#102#101#100# ii. 100#101#102#103#
iii. 100#101#102#103#104# iv. 104#103#102#101#100#
Solution:
Option i and option iv
a. 10
b. 30
c. error
d. 20
2. Name the Python Library modules which need to be imported to invoke the following functions:
a. sin()
b. randint()
8. The values being passed through a function call statements are called
. Actual parameter
a. Formal parameter
b. default parameter
c. None of these
12. Consider the code given below: Which of the following statements should be given in the blank for
#Missing Statement, if the output produced is 110?
a. global a
b. global b=100
c. global b
d. global a=100
13. What will be the output?
a. 5
b. 6
c. 4
d. This code will raise an error.
14. A function is defined as below, the function call parameters can be:
a. Two tuples
b. Two numbers
c. One number
d. All of the above
16. What possible outputs(s) are expected to be displayed on screen at the 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 Upper.
46 STUDENT SUPPORT MATERIAL 2023-24
a) 10#40#70#
b) 30#40#50#
c) 50#60#70#
d) 40#50#70#
17. What will be the output of the Python code?
>>> def testify(a,b):
return a-b
>>> sum=testify(22,55)
>>> sum+30
a. 33
b) -33
c. 3
d. -3
21. Look at the function definition and the function call and determine the correct output
>>> def test(a):
if(a>10):
a += 10
if(a>20):
a += 20
if(a>30):
a +=30
print(a)
>>> test(11)
a) 21
b) 72
c) 61
d) 71
a) [1, 2, 3, 4, 5, 6]
b) [100, 2, 3, 4, 5, 6]
c) [100, 2, 3, 4, 5]
d) [1, 2, 3, 4, 5]
a) [1, 2, 3, 4]
48 STUDENT SUPPORT MATERIAL 2023-24
b) [5, 6, 7]
c) [1, 2, 3, 4, 5, 6, 7]
d) This code will raise an error.
24. Assertion (A): To use a function from a particular module, we need to import the module.
Reason (R): import statement can be written anywhere in the program, before
using a function from that module.
a. Both A and R are true and R is the correct explanation for A
b. Both A and R are true and R is not the correct explanation for A
c. A is True but R is False
d. A is false but R is True
30. Rewrite the following code after removing the syntactical errors (if any).
Underline each correction.
31. What will be the output of the following code? def my_func(var1=100, var2=200):
var1+=10
var2 = var2 - 10 return var1+var2
print(my_func(50),my_func())
32. What will be the output of the following code?
33.
34. What will be the possible outcomes:
50 STUDENT SUPPORT MATERIAL 2023-24
a. Delhi#Mumbai#Chennai#Kolkata#
b. Mumbai#Chennai#Kolkata#Mumbai#
c. Mumbai# Mumbai #Mumbai # Delhi#
d. Mumbai# Mumbai #Chennai # Mumbai
i. ii.
37. Find and write the output of the following Python code:
def Display(str):
m=""
for i in range(0,len(str)):
if(str[i].isupper()):
m=m+str[i].lower() elif str[i].islower():
m=m+str[i].upper()
51 STUDENT SUPPORT MATERIAL 2023-24
else:
if i%2==0:
m=m+str[i-1] else:
m=m+"#" print(m)
Display('[email protected]')
38. Find and write the output of the following python code:
I ii
39. What are the possible outcome/(s) for the following code.Also specify the maximum and minimum
value of R when K is assigned value as 2:
a. Stop # Wait # Go
b. Wait # Stop #
c. Go # Wait #
d. Go # Stop #
40. Explain the positional parameters in Python function with the help of suitable example.
41. Predict the output of following:
i. ii.
iii. iv.
v vi
44. What possible outputs(s) will be obtained when the following code is executed?
Options:
a) RED* b) WHITE*
WHITE* BLACK* BLACK*
45. What possible outputs(s) are expected to be displayed on screen at the time of execution of the
program from the following code? Also specify the maximum values that can be assigned to each of the
variables BEGIN and END.
a) 60#35#
b) 60#35#70#50#
c) 35#70#50#
d) 40#55#60#
46. What possible outputs(s) are expected to be displayed on screen at the 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 Upper.
a) 10#40#70#
b) 30#40#50#
c) 50#60#70#
d) 40#50#70#
47. What are the possible outcome/s for the following code:
Options:
a) 34:31:30:33:
b) 29:33:30:31:
c) 34:31:30:31:
d) 34:31:29:33:
54 STUDENT SUPPORT MATERIAL 2023-24
1 Guess=65
for I in range(1,5):
New=Guess+random.randint(0,I)
print(chr(New),end=' ')
Output Options:
a. ABBC
b. ACBA
c. BCDA
d. CABD
Output Options :
a. 25
b. 34
c. 20
d. None of the above
Output Options :
a. 99
b. 94
c. 96
d. None of the above
5 Area=["NORTH","SOUTH","EAST","WEST"]
for I in range(3):
ToGo=random.randint(0,1) + 1 print(Area[ToGo],end=":")
print()
Output Options:
a. SOUTH : EAST : SOUTH :
b. NORTH : SOUTH : EAST :
c. SOUTH : EAST : WEST :
d. SOUTH : EAST : EAST :
6 MIN = 25
SCORE = 10
for i in range (1,5):
Num = MIN + random.randint(0,SCORE) print(Num,end=":")
SCORE-=1;
print()
Output Options:
a) 34:31:30:33:
b) 29:33:30:31:
c) 34:31:30:31:
d) 34:31:29:33:
49. Ms. Sana wants to increase the value of variable x by 1 through function modify(). However this
code raises error .Help sana to rectify the code:
i. ii.
56 STUDENT SUPPORT MATERIAL 2023-24
iii. iv.
i. ii.
iii. iv.
FILE HANDLING
Files are used to store data permanently and can be retrieved later.
Type of Files
1. Text Files
2. Binary Files
3. CSV Files
Steps for File handling:
1. Open File
2. Read/Write
3. Close File
Open Files: open( ) function is used to open files in python. There are two ways to open files in python:
1. file_object = open(“file name”, “ access specifier”)
a. i.e. f=open(“test.txt”,”r”) #here our test file exists in the same directory of python.
b. i.e. f=open(r”C:\Users\pranab\AppData\Local\Programs\Python\Python311\test.t xt”,”r”)
Use ‘r’ before path indicates the data within quotes will be read as raw string and
no
special meaning attached with any character.
Or
f=open(”C:\\Users\\pranab\\AppData\\Local\\Programs\\Python\\Python311\\test.txt”,”r”)
The slash in the path has to be doubled.
b. i.e. f.close( )
r rb r Read mode. Opens a file for reading.If the file does Beginning
not exist, open() raises a FileNotFoundError. of File
r+ rb+ It opens the file for both reading and writing. If the Beginning
file does not exist, open() raises a FileNotFoundError. of File
w wb w Write mode. It opens the file for writing only. If the Beginning
file exists, the content of the file will be removed. If of File
the file does not exist, it is created.
w+ wb+ The w+ mode opens the file for both writing and Beginning
reading. Like w, if the file exists, then the content of of File
the file will be removed. If the file does not exist, it is
created.
a ab a The a mode opens the file for appending. In this the End of File
new content is added after the existing content. If
the file does not exist, it creates the new file.
a+ ab+ The a+ mode opens the file for both appending and End of File
reading. In this the new content is added after the
existing content. If the file does not exist, it is
created.
Default mode for file opening in “r” read mode. If we didn’t specify mode during the opening of the file
then it will automatically open the file in read mode.
File Object Methods (seek( ) & tell( ))
Text Files:
read( ) : It is used in text files to read a specified number of data bytes from the file. It returns
the result in the form of a string.
Syntax: file_object.read( )
readline( ): It will read one complete line in one go from the file. It returns the data in the form of a string.
Syntax: file_object.readline( )
file_pointer.readline( ): It will read the entire line.
f.readline( ) #it will read one complete line in one go.
file_pointer.readline(n): It will read the first ‘n’ bytes from the file.
f.readline(5) #it will read the first 5 characters/bytes from the file.
readlines( ): It will return all the lines of the file as the elements of the list. I.e. the 1st line of
the file will be the first element of the list and so on.
Syntax: file_object.readlines( )
file_pointer.readlines( ): It will read all the lines of the file as the elements of the list.
f.readlines( ) #it will read all the lines of the file as the elements of the list.
Example 1:
Write a function count_char() that reads a file named “char.txt” counts the number of times
character “a” or “A” appears in it.
Example 2:
Write a function count_word() that reads a text file named “char.txt” and returns the
number of times word “ the” exists.
Example 3:
Write a function count_line() that reads a text file named “char.txt” and returns the number
of lines that start with a vowel.
62 STUDENT SUPPORT MATERIAL 2023-24
2. writelines( ): It is used to write multiple lines as a list of strings into the file. In this
each element of the list will be treated as a separate line in the file.
a. Syntax: file_object.writelines(list of strings)
b. I.e. data=[“I am a student of DOE”, “I studies in class 12th”]
f.writelines(data)
Code Output
Output:
Content of “Topper.txt” File:
Question: Write a program in python with reference to above program, the content of the
text files should be in different lines.
I.e.
Priya Disha
Tanisha
Krishna
Aman
63 STUDENT SUPPORT MATERIAL 2023-24
Code
Write a program in python to count vowels, consonants, digits, spaces, special characters, spaces, words
and lines from a text file named “student.txt”.
Exercise
1. Define a function SGcounter() that counts and display number of S and G present in a text file
‘A.txt”
e.g., SAGAR JOON IS GOING TO MARKET.
It will display S:2 G:2
2. Write a function in Python that counts the number of “is”, “am” or “are” words present in a text
file “HELLO.TXT”. If the “HELLO.TXT” contents are as follows:
Here are two sentences that contain "is," "am," or "are":
“She is studying for her final exams.
3. Write a method in python to read lines from a text file HELLO.TXT to find and display the
occurrence of the word “hello”.
4.Write a user-defined function named Count() that will read the contents of a text file named “India.txt”
and count the number of lines which start with either “I” or “T”.
E.g. In the following paragraph, there are 2 lines starting with “I” or “T”:
“The Indian economy is one of the largest and fastest-growing in the world, characterized by a diverse
range of industries including agriculture, manufacturing, services, and information technology. It boasts a
sizable consumer base and a dynamic entrepreneurial spirit. However, it also faces challenges such as
income inequality, poverty, and infrastructure gaps, which the government continually addresses through
policy reforms and initiatives to foster sustainable growth and development.”
BINARY FILES
A binary file is a file whose content is in a binary format consisting of a series of sequential bytes, each of
which is eight bits in length.
It stores the information in the same format as in the memory i.e. data is stored
according to its data type.
In binary file there is no delimiter for a new line
Binary files are faster and easier for a program to read and write than text files.
Data in binary files cannot be directly read, it can be read only through a program
code written in any programming language for the same.
•If we want to write a structure such as list or dictionary to a file and read it subsequently we need to use
the Python module pickle.
•Pickling is the process of converting structure to a byte stream before writing to a file and while reading
the content of file a reverse process called Unpickling is used to convert the byte stream back to the
original format.
Steps to perform binary file operations
First we need to import the module called pickle.
This module provides 2 main functions:
dump() : to write the object in file which is loaded in binary mode
Syntax :pickle.dump(object_to_write, fileobject)
load() : dumped data can be read from file using load() i.e. it is used to read
object from binary file.
Syntax: object =pickle.load(fileobject)
6. In which mode the file must exists otherwise error is raised and both reading and writing can take place.
a.rb+ b.wb+ c.Both a and b d.None of These
Ans:rb+ . In wb+ mode file is created if not exists, if exists data will be truncated, both read and write
allowed
7.In which mode file is created if not exists, if exists data will be truncated, both read and write
allowed?
a.rb+ b.wb+ c.Both a and b d.None of These
Ans: wb+ . rb+ mode the file must exists otherwise error is raised and both reading and writing can
take place
8. _________is the process of converting structure to a byte stream before writing to a file
a.streaming b.pickling c.unpickling d.dumping
Ans:pickling. Unpickling is the process of converting byte stream to a structure before writing to a file.
9. _________is the process of converting byte stream to a structure while reading from file.
a.streaming b.pickling c.unpickling d.dumping
Ans:unpickling.pickling is the process of converting byte stream to a structure before writing to a file.
10.Data can be read from binary file using which function?
a.dump b.read c.load d.All of the above
Ans:load. dump function is used for writing data to the binary file.
Five marks questions from binary files
1.(i)Differentiate between r+ and w+ file modes in Python.
ii) Consider a file, STUDENT.DAT, containing records of the following structure: [StudName, Age, Marks]
Write a function, copyData(), that reads contents from the file STUDENT.DAT and copies the records
with Marks greater than 75 to the file named DISTINCTION.DAT.
The function should return the total number of records copied to the file
ANS: r+ mode:
∙ Primary function is reading
∙ File pointer is at beginning of file
∙ if the file does not exist, it results in an error
w+ mode:
∙ primary function is writing
∙ if the file does not exist, it creates a new file.
∙ If the file exists, previous data is overwritten
∙ File pointer is at the beginning of file
import pickle
def copyData():
fp=open("student.dat","rb")
fw=open("distinction.dat","wb")
count=0
while(True):
try:
dat=pickle.load(fp)
if(dat[2]>75):
pickle.dump(dat,fw)
count=count+1
except: #exception occurs when end of file is reached
fp.close()
fw.close()
return count
2. i)How are text files different from binary files?
ii)A Binary file, BOOK.DAT has the following structure: {BNO:[BNAME, BTYPE]} Where BNO – Book
Number BNAME – Book Name BTYPE is Book Type. Write a user defined function, findType(btype), that
accepts btype as parameter and displays all the records from the binary file BOOK.DAT, that have the
value of Book Type as btype.
ANS:
i)Text files use encoding such as ASCII or UTF-8 to store data in human-readable characters. Binary
files are made up of complicated sequences of 0s and 1s that represent a wider range of data kinds
ii)
def findType(btype):
fp=open("book.dat","rb")
while(True):
try:
dat=pickle.load(fp)
for k in dat:
if(data[k][1]==btype):
print(dat)
except:
fp.close()
3. .(i)What is the difference between w and a file opening modes.
ii) Consider a file, PRODUCT.DAT, containing records of the following structure:
[Product Name,Price,discount]
Write a function,writeMaxDiscount (), that reads contents from the file PRODUCT.DAT and copies the
productName and price as a list object with discount greater than 50% to the file named
DISCOUNT.DAT.
The function should return the total number of records copied to the file DISCOUNT.DAT.
ANS:
i)w mode opens the file in write mode.Previous contents will be overwritten.
’a’ mode opens the file in append mode.it writes the contents to the end of the file.Previous contents
will not be overwritten
ii)
import pickle
def writeMaxDiscount():
fp=open("product.dat","rb")
fw=open("discount.dat","wb")
count=0
while(True):
try:
dat=pickle.load(fp)
if(dat[2]>50):
ls=[dat[0],dat[1])
pickle.dump(ls,fw)
count=count+1
except:
fp.close()
fw.close()
return count
4.
i. What do you mean by pickling?
ii. A Binary file, RESTAURANT.DAT has the following structure: {RNO:[RNAME, RTYPE]}
Where RNO – Restaurant Number RNAME – Restaurant Name RTYPE is Restaurant Type.
Write a user defined function, VegNonVeg(rtype), that accepts rtype as parameter and
displays all the records from the binary file RESTAURANT.DAT, that have the value of
Restaurant Type as rtype.
ANS:
i)Pickling is the process of converting structure to a byte stream before writing to a file
and while reading the content of file a reverse process called Unpickling is used to convert the byte
stream back to the original format.
ii)
def VegNonVeg(rtype):
fp=open("restaurant.dat","rb")
while(True):
try:
dat=pickle.load(fp)
for k in dat:
if(data[k][1]==rtype):
print(dat)
except:
fp.close()
5. (i) Which is the default file opening mode.
ii) Consider a file, FLIGHT.DAT, containing records of the following structure:
[FightName,From,To]
Write a function,FlyingToDelhi (), that reads contents from the file FLIGHT.DAT and copies the
records of the flights flying to Delhi to the file named DELHI.DAT.
The function should return the total number of flights flying to Delhi.
ANS:
i) The default file opening mode is r .If file opening mode is not given the file will be opened for
reading.
ii)
def FlyingToDelhi():
fp=open("flight.dat","rb")
fw=open("delhi.dat","wb")
count=0
while(True):
try:
dat=pickle.load(fp)
if(dat[2]=="Delhi"):
pickle.dump(dat,fw)
count=count+1
except:
fp.close()
fw.close()
return count
STEPS TO READ
def GetCustomer():
fp=open("Accounts.csv","w",newline="")
heading=["Accno", "cus_name", "Address", "Actype"]
csv_writer=csv.writer(fp)
acno=int(input("Enter account number"))
cus_name=input("Enter customer name")
address=input("Enter address")
Actype=input("Enter Ac type")
dat=[acno,cus_name,address,Actype]
csv_writer.writerow(heading)
csv_writer.writerow(dat)
fp.close()
def countFD():
count=0
fp=open("Accounts.csv","r")
csv_reader=csv.reader(fp)
for row in csv_reader:
if(row[3]=="FD"):
count=count+1
return count
2 .Stuti is a Data Scientist. As part of a project, she has created a csv file named products.csv, to store the details of
different products. The structure of products.csv is : [pno, pname, price, qty_sold] Where pno is product number
(integer) pname is product Name (string) ,price is price of the product(float) qty_sold is number of units of that
product sold .For analysis purpose, stuti wants to write the following user defined functions:
writeProduct() – to accept a record from the user and add it to the file product.csv. The column headings should
also be added on top of the csv file.
maxQty(target) – to count the number of products whose qty_sold is greater than target. As a Python expert, help
her complete the task.
Ans:
import csv
def writeProduct():
fp=open("products.csv","w",newline="")
heading=["pno", "pname", "Price", "Qty_sold"]
csv_writer=csv.writer(fp)
pno=int(input("Enter product number"))
pname=input("Enter product name")
price=float(input("Enter price")
Qty_sold=int(input("Enter Qty sold")
dat=[pno,pname,price,Qty_sold]
csv_writer.writerow(heading)
csv_writer.writerow(dat)
fp.close()
def maxQty(target):
count=0
fp=open("products.csv","r")
csv_reader=csv.reader(fp)
for row in csv_reader:
if(row[3]>=target):
count=count+1
return count
3. Isak is a python programmer. As part of a project, he has created a csv file named houseprice.csv, to store year
wise house price in a city. The structure of houseprice.csv is: [year,price] .For analysis purpose, Isak wants to write
the following user defined functions:
getHousePrice – to accept a record from the user and add it to the file houseprice.csv. The column headings should
also be added on top of the csv file.
getPrice(year) – to get the houseprice of a particular year. As a Python expert, help him complete the task.
import csv
def getHousePrice ():
fp=open("houseprice.csv","w",newline="")
heading=[“year”,”price”]
csv_writer=csv.writer(fp)
year=int(input("Enter year"))
price=float(input("Enter house price"))
dat=[year,price]
csv_writer.writerow(heading)
csv_writer.writerow(dat)
fp.close()
def getPrice (year):
count=0
fp=open("houseprice.csv","r")
csv_reader=csv.reader(fp)
for row in csv_reader:
if(row[0]==year):
return row[1]
4.LalPekhlui is a python programmer.As part of a project she created a csv file named student.csv,to store
the marks of three subjects of a student.The structure of student.csv is:[rollno,name,sub1,sub2,sub3]
where rollno is the roll number of the student(integer),name is the name of the student(string),sub1,sub2
and sub3 are three subject marks(float).For analysis purpose she wants to write the following user
defined functions:
writeStudDetails()-to accept a record from the user and add it to the file student.csv. The column headings should
also be added on top of the csv file
getTopper()-to display the name of the student who scored maximum marks. As a Python expert, help her
complete the task.
import csv
def writeStudDetails():
fp=open("student.csv","w",newline="")
heading=["rollno", "name", “sub1”, “sub2”, “sub3”]
csv_writer=csv.writer(fp)
rollno=int(input("Enter roll number"))
name=input("Enter student name")
sub1=float(input("Enter subject1 mark")
sub2=float(input("Enter subject2 mark")
sub3=float(input("Enter subject3 mark")
dat=[rollno,name,sub1,sub2,sub3]
csv_writer.writerow(heading)
csv_writer.writerow(dat)
fp.close()
count=0
fp=open("student.csv","r")
csv_reader=csv.reader(fp)
top=0
for row in csv_reader:
sum=row[2]+ row[3]+ row[4]
if(sum>top):
top=sum
topper=row[1]
return topper
5.Barsat is a python programmer.As part of a project he created a csv file movies.csv,to store the details of
different movies.The structure of movies.csv is:[movie_name,rating] where movie_name is the name of the movie
(string) and rating is a five scale rating of the movie which will have values from 1 to 5.For analysis purpose Barsat
wants to write the following user defined functions:
getMovies()-to accept a record from the user and add it to the file movies.csv. The column headings should also be
added on top of the csv file
getToprated()-to display the movies which are having rating more than 3
import csv
def getMovies():
fp=open("movies.csv","w",newline="")
heading=[“moviename”,”rating”]
csv_writer=csv.writer(fp)
mvname=input("Enter moviename")
rating=int(input("Enter rating"))
dat=[ mvname, rating]
csv_writer.writerow(heading)
csv_writer.writerow(dat)
fp.close()
def getToprated ():
count=0
fp=open("movies.csv","r")
csv_reader=csv.reader(fp)
for row in csv_reader:
if(row[1]>3):
print(row[0])
DATA STRUCTURES
Stack
A stack is a linear data structure implemented in LIFO(Last In First Out) manner. This is because in a stack,
insertion and deletion of elements can only take place at one end, which is called top of the stack.
Consider the following examples of stacks:
1. A pile of books
2. A stack of coins
3. Glass plates placed one above another.
The two operations performed on the stack are:
• Push operation: It means inserting element at the top of the stack. This can be done with the help of append()
method of the list as: st.append(element) where ‘st’ is a list.
• Pop operation: It means removing the topmost element from the stack. This can be performed using pop()
method of the list as: st.pop() where ‘st’ is a list. This method returns the removed element that can be displayed.
MULTIPLE CHOICE QUESTIONS ON STACK
1.LIFO stands for __________
a.Last Input First Output b.Last In First Out c.Least Input Fast Output d.None of These
Ans: b.Last In First Out
2.Insertion and deletion takes place in a stack at __________
a.top b.bottom c.side d.left
Ans: a.top
3.Stack is a ___________datastructure
a.Non Linear b.Heirarchical c.Linear d.None Of These
Ans: c.Linear
4.Inserting data into the stack is called ________ operation
a.insert b.append c.add d.push
Ans: d.push
5.Removing element from the stack is called___________
a.remove b.delete c.pop d.None Of These
Ans: c.pop
6.The list function used for adding an element to the end of the list is_______
a.add() b.insert() c.append() d.None of These
Ans: c.append()
7.The list function used to remove an element from the end of the list is______
a.pop() b.popfromlast() c.removelast() d.None Of These
Ans: a.pop()
8.In stack we cannot insert an element in between the elements that are already inserted.
a.True b.False Ans:a.True
9.In a stack the condition in which if a user tries to remove an element from empty stack is called ____
a.Empty stack b.Underflow c.Overflow d.None Of These
Ans: b.Underflow
10.If the elements ‘A’,’B’,’C’ and ‘D’ are placed in a stack and are deleted one at a time in what order will they be
removed?
a.ABCD b.DCBA c.DCAB d.ABDC
Ans: b.DCBA
ii. Pop_element(): It pops the objects from the stack and displays them. Also, the function should display
“Stack Empty” when there are no elements in the stack.
Ans:
tour=[]
def push_element(city):
tour.append([cty[0],cty[1]])
def pop_element():
while(len(tour)!=0):
print(tour.pop())
print("Stack Empty")
Each of these records are nested together to form a nested list. Write the following user defined functions in
Python to perform the specified operations on the stack named office.
i. Push_element(employee): It takes the nested list as an argument and pushes a list object containing name
of the employee and salary, who are having salary greater than 10000
ii. Pop_element(): It pops the objects from the stack and displays them. Also, the function should display
“Stack Empty” when there are no elements in the stack.
Ans:
office=[]
def push_element(employee):
if(emp[2]>10000):
office.append([emp[1],emp[2]])
def pop_element():
while(len(office)!=0):
print(office.pop())
print("Stack Empty")
Empty_stack(): It pops the objects from the stack and displays them. Also, the function should display “Stack
Empty” when there are no elements in the stack.
store=[]
def push_product(product):
if(pdct[2]>2500):
store.append([pdct[1],pdct[2]])
def empty_stack():
while(len(store)!=0):
print(store.pop())
print("Stack Empty")
4. Write a function in Python, Push(product) where , product is a dictionary containing the details of
products– {pname:discount}.The function should push the names of those products in the stack
having discount more than 50%. Also display the count of elements pushed into the stack.
Ans:
stack=[ ]
def push(product):
for pdct in product:
if(product[pdct]>50):
stack.append(pdct)
5. Write a function in Python, Store(student) where, student is a dictionary containing the details of
students– {sname:marks}.The function should push the names of those students in the stack having
marks more than 80. Also display the count of elements pushed into the stack.
Ans:
stack=[ ]
def store(student):
for stud in student:
if(student [stud]>80):
stack.append(stud)
Unit-2
Computer Networks
A computer network is a collection of computers and other hardware’s interconnected by communication channels
that allow sharing of resources and information.
A computer networking is the practice for exchanging information between two or more computer devices
together for the purpose of data sharing.
Benefits of Networking
Computer network is very useful in modern environment. Some of the benefits of networking are discussed here:
(i) File Sharing Networking of computer helps the user to share data files.
(ii) Hardware Sharing Users can share devices such as printers, scanners, CD-ROM drives, hard drives, etc. in
a computer network.
(iii) Application Sharing Applications can be shared over the network and this allows implementation
of client/server applications.
(iv)User Communication This allows users to communicate using E-mail, newsgroups, video conferencing
within the network.
Access to Remote Database This allows users to access remote database, e.g. airline reservation database may be
accessed for ticket booking.
Evolution of Networking
Evolution of networking is described below
ARPANET
The Advanced Research Projects Agency NETwork (ARPANET) was the world’s first operational packet switching
network.
The U.S department of defence sponsored a project named ARPANET, whose goal was to connect computers at
different universities and U.S defence.
In 1969, the University of California at Los Angeles, the University of California and the University of Utah were
connected as the beginning of the ARPANET using 50 Kbits circuits.
In mid 80’s, the National Science Foundation created a new network called NSFnet, which was more capable than
ARPANET.
WWW
The World Wide Web (WWW) is a system of interlinked hypertext documents accessed via Internet. With a
web browser, one can view web pages that may contain text, images, videos and other multimedia and can
navigate between them via hyperlinks.
The Internet is a global system of interconnected computer networks. In short, the web is a way of exchanging
information between computers on the Internet.
Internet (INTERconnection NETwork)
The Internet is a network of the interlinked computer networking worldwide, which is accessible to the general
public.
Internet is a huge network of several different interlinked networks relating to the business, government, academic
and even smaller domestic networks. Therefore, Internet is known as the network of all the other networks.
These networks enable the Internet to be used for various important functions, which include the several means of
communications like the file transfer, the online chat and even the sharing of the documents and websites on the
WWW or the World Wide Web.
Interspace
It is a client/server program that allows multiple users to communicate online with real-time audio, video and
text chat in dynamic 3D environments.
Interspace provides the most advanced form of communication available on the Internet today.
The Interspace is a future vision of what the Internet will become tomorrow, when users cross-correlate the
information of multiple sources. It will be an application environment for interconnecting spaces to manipulate
information like Internet.
Intranet
An intranet is a network that connects the computers and networks with in an organisation that is based on
Internet technology.
It uses the TCP/IP protocols, server and browser software used for the Internet. With an intranet, the basic services
of the Internet like E-mail, FTP, etc. are used.
Data Communication
Communication is an act of sending or receiving data. Thus, data communication refers to the exchange of data
between two or more networked or connected devices.
These devices must be capable of sending and receiving data over a communication medium. Examples of such
devices include personal computers, mobile phones, laptops etc.
Components of Data Communication
Whenever we talk about communication between two computing devices using a network, five most important
aspects come to our mind.
These are sender, receiver, communication medium, the message to be communicated and certain rules called
protocols to be followed during communication. The communication media is also called transmission media.
Five components in data communication are:
(i) Sender It is a computer or any such device which is capable of sending data over a network. It can be a
computer, mobile phone, smartwatch, walkie-talkie, video recording device, etc.
(ii) Receiver It is a computer or any such device which is capable or receiving data from the network. It can be
any computer, printer, laptop, mobile phone, television, etc. In computer communication, the sender and
receiver are known as nodes in a network.
(iii) Message It is the data or information that needs to be exchanged between the sender and the
receiver. Messages can be in the form of text, number, image, audio, video, multimedia, etc.
(iv)Communication Media It is the path through which the message travels between source and destination. It
is also called medium or link which is either wired or wireless.
Protocols It is a set of rules that need to be followed by the communicating parties in order to have successful and
reliable data communication.
Switching Techniques
Switching techniques are used for transmitting data across networks. Different types of switching techniques are
employed to provide communication between two computers. These are as follows
Circuit Switching
Circuit switching is a methodology of implementing a telecommunication network in which two network nodes
establish a dedicated communication channel (circuit).
The main advantage of circuit switching is guaranteed delivery. The circuit switching guarantees the full bandwidth
of the channels and remains connected for the duration of the communication session.
Example of a circuit switched network is early analog telephone network. When a call is made from one telephone
to another, switches within the telephone exchanges create a continuous wire circuit between the two telephones
for as long as the call last.
Message Switching
Message switching is a network switching technique, in which data is routed entirely from the source node to the
destination node. In this technique, no physical path is established between source and destination.
During message routing, every intermediate switch in the network stores the whole message
If the entire network’s resources are engaged or the network becomes blocked, the message switched network
stores and delays the message until some resource become available for effective transmission of the message.
Packet Switching
In packet based networks, the message gets broken into small data packets. These packets are sent out from the
computer and they travel around the network seeking out the most efficient route to travel as circuits become
available.
The main advantage of packet switching is that the packets from many different sources can share a line,
allowing for very efficient use of the communication medium.
Data Communication Terminologies
The various data communication terminologies are as shown below
Channel
A communication channel is a medium that is used in the transmission of a message from one point to another.
It may refer to the entire physical medium such as a tele- phone line, optical fibre, co-axial cable or twisted pair
wire. Depending on their speed, there are three broad categories of communication channels
Narrow band is slow and used for telegraph lines and low speed terminals.
Voice band used for ordinary telephone communication.
Broadband, is fastest and used for transmitting large volumes of data at high speed.
Baud Rate
It is a measure of the number of symbols (signals) transferred or line changes every second. It may represent more
than one binary bit. Each symbol can represent or convey one (binary encoded signal) or several bits of data. For a
binary signal of 20 Hz, this is equivalent to 20 baud (there are 20 changes per second).
Bandwidth
It is the frequency range of a channel, measured as the difference between the highest and lowest frequencies that
the channel supports. The maximum transmission speed is dependent upon the available bandwidth. The larger the
bandwidth, the higher the transmission speed. In analog systems, bandwidth is defined in terms of the difference
between the highest frequency signal component and the lowest frequency signal component. Frequency is
measured in cycles per second, i.e. hertz (Hz). One Hz equals one cycle per second.
A kilohertz (kHz) represents a thousand Hz per second and a megahertz (MHz) represents a thousand kHz per
second.
Data Transfer Rate (DTR)
A data transfer rate (or just data rate) is the amount of digital data that is moved from one place to another in a
given time, usually in a second on a network. In telecommunication, data transfer is usually measured in bits per
second.
Bits Per Second (bps)
This is an expression of the number of data bits per second. Where, a binary signal is being used, this is same as the
baud rate.When the signal is changed to another form, it will not be equal to the baud rate, as each line change can
represent more than one bit (either two or four bits).
Transmission Media
The media through which data is transferred from one place to another is called transmission or communication
3. Optical Fibre
Optical fibre or fibre optic cable consists of thin threads made up of glass or glass like material, which are capable
of arrying light signals from a source at one end to another end. At the source, there are either Light Emitting
Diodes (LEDs) or Laser Diodes (LDs) present, which modulate the data into light beam using frequency modulation
techniques. At the receiver’s end, the signals are demodulated. There are three main parts in optical fibre:
(i) Core It is the section through which data travels in the form of light.
(ii) Cladding The cladding is covering of the core. Its function is to reflect back the light into the core, as it is a
denser medium.
(iii) Protective Coating It is the outer cover of cladding for the protection of the optical fibre.
There are two types of fibre optic cables
(i) Single Mode It supports a segment length of upto 2 kms and bandwidth of upto 100 Mbps.
(ii) Multi Mode The maximum segment length of multi mode is upto 100 kms and bandwidth of upto 2 Gbps.
Advantages of Optical Fibre Cable
i. It is immune to electrical and magnetic fields. So, the data does not get disturbed and pure data is retrieved on
the other end.
ii. Highly suitable for harsh industrial environment.
iii.It guarantees secure transmission and has a very high transmission capacity.
iv.It can be used for broadband transmission, where several channels are handled in parallel.
v.Bandwidth is upto 10 Gbps.
Disadvantages of Optical Fibre Cable
i. Connecting two fibres together or a light source to a fibre is difficult.
ii. Because of noise immunity, these are virtually impossible to tap.
iii. Optical cables are expensive to install but last longer than copper cables.
iv. Optical fibres require more protection around the cable as compared to copper cables.
v. Installation problem. Fibre optic cables are quite fragile and may need special care to make them sufficiently
robust for an office environment.
Unguided Media or Wireless Technologies
When the computers in a network are interconnected and data is transmitted through waves, then they are said to
be connected through unguided media. Some of the unguided media are given below:
1. Bluetooth
It is used for exchanging data over a short distance from fixed and mobile devices. The name bluetooth is derived
from Herald Bluetooth, a king in Denmark.
Advantages of Bluetooth
i. We are able to share data without any cord.
ii. We are able to share data without disclosing our private data.
iii. We can use Bluetooth on many different devices, as it
is available in all devices such as laptops, cell phones, music players, hand sets, printers and a lotmore other
products.
Disadvantages of Bluetooth
i. Battery consumption
ii. Data transfer is very slow
2. Infrared
It is the frequency of light that is not visible to human eye. These high frequencies allow high speed data
transmission.
Infrared communiucation requires a transceiver (a combination of transmitter and receiver) in both devices that
communicate. Infrared communication is playing an important role in wireless data communication due to the
popularity of laptop computers, personal digital assistants (PDAs), digital cameras, mobile phones, pagers and
other devices but being a line-of-sight transmission, it is sensitive to fog and other atmospheric conditions.
Advantages of Infrared
■
Power consumption is less.
■
Circuitry cost is less.
■
Circuitry is simple.
■
Secure mode of transmission.
Disadvantages of Infrared
■
Line of sight, need to be in a straight line for communication.
■
Limited in a short range.
■
Can be blocked by common materials like walls, people, plants, etc.
3. Radiowave
When two terminals communicate by using radio frequencies, then such type of communication is known as radio
wave transmission. Radio wave transmission set-up has two parts; Transmitter and Receiver.
(i) Devices which transmit signals are termed as transmitter.
(ii) Devices which receive signals are termed as receiver.
Both the transmitter and receiver use antennas to radiate and capture the radio signal.
Advantages of Radio wave
■
Cheaper than wired network.
■
Circuitry cost is less.
■
Circuitry is simple.
■ Secure mode of transmission.
Disadvantages of Infrared
i. Line of sight, need to be in a straight line for communication.
ii. Limited in a short range.
iii. Can be blocked by common materials like walls, people, plants, etc.\
3. Radiowave
When two terminals communicate by using radio frequencies, then such type of communication is known as
radiowave transmission. Radiowave transmission set-up has two parts; Transmitter and Receiver.
(i) Devices which transmits signals are termed as transmitter.
(ii) Devices which receives signals are termed as receiver.
Both the transmitter and receiver use antennas to radiate and capture the radio signal.
Advantages of Radiowave
i. Cheaper than wired network.
ii. Provides mobility.
iii. Easy to use over difficult terrain.
Disadvantages of Radiowave
i. Insecure communication can be easily taped.
ii. It is affected by the weather conditions such as rain, storms, thunder, etc.
4. Microwave
It permits data transmission rates of about 16 gigabits per second. This type of transmission uses high frequency
radio signals to transmit data through space. Like radio waves, microwaves can pass through obstacles viz.
buildings, mountains etc. Microwaves offer a line of sight method of communication.
A transmitter and receiver of a microwave system are mounted on very high towers and both should be visible to
each other (line of sight). In case of microwave transmission, curvature of the earth, mountains and other
structures often block the line of sight. Hence several repeater stations are required for long distance transmission
thereby increasing the cost considerably. It is generally used for long distance telephonic communications.
Advantages of Microwave
i. Microwave transmission does not require the expense of laying cables.
ii. It can carry 25000 voice channels at the same time.
iii. Since no cables are to be laid down so it offers ease of communication over difficult terrains like hilly areas.
Disadvantages of Microwave
i. Signals become weak after travelling a certain distance and require amplification. To overcome this problem,
repeaters are used at regular intervals (25-30 kms). The data signals are received, amplified and then
These networks typically involve a mobile computer, a cell phone and/or handheld computing devices such as a
PDA. Person can use these networks to transfer files including e-mail and calendar appointments, digital photos
and music. These are used in a limited range, which is in the reachability of individual person. It generally covers a
range of less than 10 metres and can be constructed with cables or wirelessly. Few examples of PAN are Bluetooth,
Wireless USB, Z-wave and Zig Bee.
Virtual Private Network (VPN)
VPN is an encrypted connection over the Internet from a device to a network. It can be used to access region -
restricted websites, shield your browsing activity from prying eyes on public Wi-Fi and more. It prevents
unauthorised people from eavesdropping on the traffic and allows the user to conduct work remotely. VPN
technology is widely used in corporate
environments.
Network Architecture
Network architecture is the logical and structural layout of the network, consisting of transmission equipment,
software, communication protocols and infrastructure (i.e. wired or wireless), transmission of data and
connectivity between components.
There are two types of network architecture
Point-to-Point (P2P) Network In P2P or Peer-to-Peer network, each node can receive from exactly one sender and
each sender sends to exactly one receiver. Sending and receiving can be done on separate wires or they can take
turns over the same wire using a variety of techniques.
Client/Server Network The model of interaction between two application programs in which a program at one end
(client) requests a service from a program at the other end (server). It is a network architecture which separates
the client from the server. It is scalable architecture, where one computer works at server and other as client. In
this architecture, client acts as the active device and server behaves as passively.
Network Devices
Hardware device that are used to connect computers, printers, fax machines and other electronic devices to a
network are called network device.
There are many types of network devices used in networking and some of them are described below
Repeater: It is a hardware device which is used to amplify the signals when they are transported over a long
distance. The basic function of a repeater is to amplify the incoming signal and retransmit it, to the other device.
Repeaters are mainly used for extending the range. If you want to connect two computers, which are more than
100 meters apart you need repeater.
Hub: A hub is a device, used with computer systems to connect several computers together. It acts as a centralized
connection to several computers with the central node or server. It is a multiport device, which provides access to
computers. All incoming data packets received by the hub are sent to all hub ports and from them the data is sent
to all the computers connected in a hub network.
There are two types of hub
(i) Active Hub It acts as repeaters. It amplifies the signal as it moves from one device to another.
(ii) Passive Hub It simply passes the signal from one connected device to another.
Switch: A switch is a hardware device, which is used to connect devices or segments of the network into smaller
subsets of LAN segments. The main purpose of segmenting is to prevent the traffic overloading in a network.
Switch forwards a data packet to a specific route by establishing a temporary connection between the source and
the destination. After the transmission or once the conversation is done, the connection is terminated. There is a
vast difference between switch and hub. A hub forward each incoming packet (data) to all the hub ports, while a
switch forwards each incoming packet to the specified recipient.
Gateway: A gateway is a device, which is used to connect dissimilar networks. The gateway establishes an
intelligent connection between a local network and external networks, which are completely different in structure.
The gateway is a node in a network, which serves as a proxy server and a firewall system and prevents the
unauthorized access. It holds the information from a website temporarily, so that the repeated access to same
website or web page could be directed to the proxy server instead of actual web server. Thus, it helps in reducing
the traffic load.
Bridge: It serves a similar function as switches. A bridge filters data traffic at a network boundary. Bridges reduce
the amount of traffic on a LAN by dividing it into two segments. Traditional bridges support one network boundary,
whereas
switches usually offer four or more hardware ports. Switches are sometimes called multiport bridges.
Router: It is a hardware device, which is designed to take incoming packets, analyse the packets, moving and
converting the packets to another network interface, dropping the packets, directing packets to the appropriate
locations, etc.
Modem (MOdulator DEModulator): It is a device that converts digital signal to analog signal (modulator) at the
sender’s site and converts back analog signal to digital signal (demodulator) at the receiver’s end, in order to make
communication possible via telephone lines. It enables a computer to transmit data over telephone or cable lines.
Modems are of two types
(i) Internal Modem Fixed within a computer.
(ii) External Modem Connected externally to a computer.
When a network contains largest number of system/computer it needed modem.
RJ45 Connector: RJ45 stands for Registered Jack-45. It is an eight wire connector. RJ45 connector is used to connect
computers onto a Local Area Network (LAN). It is commonly used in telephony applications and networking. It is
also used for serial connections.
RJ11 Connector: RJ11 connector is the typical connector used on two pair, four wire handset wiring. RJ11
connector wiring comes in two standard assortments Unshielded Twisted Pair (UTP) and flat-satin cable or the
untwisted. RJ11 connectors are used to terminate phone lines and are typically deployed with single line Plain Old
Telephone Service (POTS) telephone jacks.
Ethernet Card: An Ethernet card is a kind of network adapter. These adapters support the Ethernet standard for
high-speed network connections via cables. Ethernet cards are sometimes known as Network Interface Cards
(NICs). Ethernet cards are available in several different standard packages called form factors. Newer Ethernet
cards installed inside desktop computers use the PCI standard and are usually installed by the manufacturer.
Ethernet cards may operate at different network speeds depending on the protocol standard they support.
Wi-Fi Card: These are small and portable cards that allow connecting to the Internet through a wireless network. In
these cards, transmission is done through radio waves. The antenna transmits the radio signals to those
equipment, which has
Wi-Fi cards. Wi-Fi cards can be external or internal. If a Wi-Fi card is not installed in your computer, you may
purchase a USB antenna attachment and have it externally connected to your device. Many newer computers,
mobile devices, etc., are equipped with wireless networking capability and do not require a Wi-Fi card.
Network Topology
The arrangement of computers and other peripherals in a network is called its topology.
The main network topologies are as follows
Bus Topology (Linear Topology)
A bus topology is an arrangement in which the computers and the peripheral devices are connected to a common
single
data line. All the computers or devices are directly connected to the data line. The data is transmitted in small
blocks known as packets. Each packet has a header containing the destination address. When data is transmitted
on the cable, the destination node identifies the address on the packet and thereby processes the data.
Advantages of Bus Topology
i. All the nodes are connected directly, so very short cable length is required.
ii. The architecture is very simple, reliable and linear.
iii. Bus topology can be extended easily on either sides.
Disadvantages of Bus Topology
i. In case of any fault occurred in data transmission, fault isolation is very difficult. We have to check the entire
network to find the fault.
ii. Becomes slow with increase in number of nodes.
iii. Only a single message can travel at a particular time.
Ring or Circular Topology
In this type of topology, the node is connected to two and only two neighboring nodes. The data travels in one
direction only from node to node around the ring. After passing through each node, the data returns to the sending
node.
Advantages of Ring or Circular Topology
i. Short length cable is required.
ii. Suitable for optical fibre as the data flow in one direction.
Disadvantages of Ring or Circular Topology
i. In ring topology, each node is connected in a circular way with its two neighbouring nodes, so when there is
transmission problem anywhere in the network, entire network stops functioning.
ii. Fault diagnosis is very difficult.
Star Topology
In star topology, each communicating device is connected to a central node which is a networking device like a hub
or a
switch. The central node can be either a broadcasting device means data will be transmitted to all the nodes in the
network or a unicast device means the node can identify the destination and forward data to that node only.
Advantages of Star Topology
i. Installation of star topology is very easy as all the nodes are directly connected to the central node or server.
ii. Easy to detect faults and remove it.
iii.Failure of single system will not bring down the entire network.
iv. Allows several types of cables in same network.
tags enclosed in angular brackets (like <html>), within the web page content. HTML tags most commonly come in
pairs like <h1> and </h1>, which are known as container tags, although some tags known as empty elements, are
unpaired, e.g. <img>. The <html> tag is the start tag and the </html> tag is the end tag (they are also called opening
tags and closing tags). In between these tags, web designers can add text, some other tags, comments and other
types of text based content. An HTML document has the extension .htm or .html.
The purpose of a web browser is to read HTML documents and compose them into visible or audible web
pages. The browser does not display the HTML tags, but uses the tags to interpret the content of the page. HTML
elements form the building blocks of all websites. HTML allows images and objects to be embedded and can be
used to create interactive forms. It provides a means to create structured documents by denoting structural
semantics for text such as headings, paragraphs, lists, links, quotes and other items. It can embed scripts written in
languages such as JavaScript, which affect the behaviour of HTML web pages.
eXtensible Markup Language (XML)
XML is a markup language that defines a set of rules for encoding documents in a format, that is both human-
readable and machine-readable. It is defined in the XML 1.0 specification produced by the W3C and several other
related specifications. The design goals of XML emphasise simplicity, generality and usability over the Internet. e.g.
in web services. Because the Internet is based on IP addresses, not domain names, every web server requires a
Domain Name System (DNS) server to translate domain names into IP addresses.
Domain Name
A domain name is a unique name that identifies a particular website and represents the name of the server,
where the web pages store. Domain names are formed by the rules and procedures of the Domain Name System
(DNS). Domain names are used in various networking contexts and application specific naming and addressing
purposes. In general, a domain name represents an Internet Protocol (IP) resource, such as a personal computer
used to access the Internet, a server computer hosting a website or the website itself or any other service
communicated via the Internet.
Uniform Resource Locator (URL)
A uniform resource locator, abbreviated URL, also known as web address, is a specific character string that
constitutes a reference to a resource. In most web browsers, the URL of a web page is displayed on top inside an
address bar. A URL is a formatted text string used by web browsers, E-mail clients and other software to identify a
network resource on the Internet. Network resources are files that can be plain web pages, other text documents,
graphics or programs.
URL consists of three parts
(i) Network protocol
(ii) Host name or address
(iii) File or resource location.
These parts are separated by special characters as follows Protocol://host/location
An example of a typical URL would be
"http://en.example.org/wiki/Main_Page".
IP Address (Internet Protocol Address)
The Internet Protocol (IP) is the method or protocol by which data is sent from one computer to another on the
Internet. Each computer (known as a host) on the Internet has atleast one IP address that uniquely identifies it
from all other computers on the Internet.
The format of an IP address is a 32 bits numeric address written as four numbers separated by periods (.). Each
number can be in range 0 to 255. e.g. 1.160.10.240
Web Page
The backbone of the World Wide Web is made up of files or documents called pages or web pages, that contain
information and links to resources both text and multimedia. It is created using HTML. The web is a collection of
large number of computer documents and web pages that stored on computers around the world which are
connected to one
another using hyperlink.
A web page can be of two types
Static Web Page
A web page which displays same kind of information whenever a user visits, it is known as a static web page. A
static web page generally has .htm or .html as extension.
Dynamic Web Page
An interactive web page is a dynamic web page. A dynamic web page uses scripting languages to display changing
content on the web page. Such a page generally has .php, .asp or .jsp as extension.
Website
A group of related web pages that follow the same theme and are connected together with hyperlinks is called a
website. A website displays related information on a specific topic. Each website is accessed by its own address
known as URL (Uniform Resource Locator). The main or first page of a website is known as home page.
Web Browser
A web browser (commonly referred to as a browser) is a software application for retrieving, presenting and
traversing information resources on the World Wide Web. An information resource is identified by a Uniform
Resource Identifier (URI) and may be a web page, image, video or other piece of content. Although, browsers are
primarily intended to use the World Wide Web, they can also be used to access information provided by web
servers in private networks or files in file systems. The major web browsers are Google Chrome, Firefox, Internet
Explorer, Opera and Safari.
Web Server
The term web server can refer to either the hardware (the computer) or the software (the computer application)
that helps to deliver web content, accessible through the Internet. The most common use of web server is to host
websites, but there are other uses such as gaming, data storage or running enterprise applications.
Any computer can be turned into a web server by installing server software and connecting the machine to the
Internet.
There are many web server software applications including public domain software from NCSA and Apache and
commercial packages from Microsoft, Netscape and others.
Web Hosting
A web hosting service is a type of Internet hosting service that allows individuals and organizations to make their
website accessible via the World Wide Web. A web host is the business of providing server space, web services and
file maintenance for websites controlled by individuals or companies that do not have their own web servers. Many
ISPs (Internet Service Providers), such as America Online will allow subscribers a small amount of server space to
host a personal web page.
Web hosting can be of four types as follows
(i) Free hosting (ii) Virtual or Shared hosting (iii) Dedicated Hosting (iv) Co-location Hosting
1. The ____________ project has been started in 1960s to provide interconnection between academic and
research institutions for research purpose.
1. University of California
4. NSFNET program was launched by the National Science Foundation in 1986. (True/False)
5. _____________ is a program that provides information to users with different URLs and create
relationships with websites.
7. The ____________ is a powerful computer in the network that control, manage and provide different
services to the other computers in the network.
8. Every computer is having a hardware device attached to the computer internally, is known as
_________________.
9. Which of the following is responsible for connecting various network devices in the network?
1. Communication Channels
2. Protocols
3. Topology
4. Internet
10. The __________ is a range of frequency of data transmission available in kHz, MHz or GHz.
11. Which of the following is used to measure the speed of data transfer in the network?
1. KHz
2. km/s
3. mbps
4. mps
13. Which of the following uses a dedicated channel through the network?
1. message switching
2. packet switching
3. circuit switching
4. All of these
14. Which of the following switching technique divide the data into small parts?
1. message switching
2. packet switching
3. circuit switching
4. All of these
1. 1240 kbps
2. 1240 Mbps
3. 1240 bps
4. 1240 Gbps
16. Which of the following switching technique increases the performance as access time is reduced?
1. Packet Switching
2. Circuit Switching
3. Message Switching
4. All of these
17. The bandwidth and data transfer rates are exactly similar in networking. (True/False)
18. The ______________ use some simple names rather than using a numerical complex addresses.
Answers:
1. ARPANET
2. 3 US Department of Defense
3. TELNET
4. True
5. WWW
7. server
9. 1 Communication Channel
10. bandwidth
11. 3 mbps
12. internet
17. False
19. E-mail
20. True
5 MARKS QUESTIONS
1.Sanskar University of Himachal Pradesh is setting up a secured network for its campus at Himachal Pradesh for
operating their day-to-day office & web based activities. They are planning to have network connectivity between
four buildings. Answer the question (i) to (iv) after going through the building positions in the campus & other
details which are given below:
As a network expert, you are required to give best possible solutions for the given queries of the
university administration:-
(a) Suggest cable layout for the connections between the various buildings
(b) Suggest the most suitable building to house the server of the network of the university
(c) Suggest the placement of following devices with justification: 1. Switch/Hub 2. Repeater
(d) Suggest the technology out of the following for setting-up very fast Internet connectivity among
buildings of the university 1. Optical Fibre 2. Coaxial cable 3. Ethernet Cable.
(e) Suggest the suitable place to install modem in order to get internet to entire network.
99 STUDENT SUPPORT MATERIAL 2023-24
2. Suggest the most suitable place (i.e., building) to house the server of this school, provide a suitable reason.
o Repeater
o Hub/Switch
4. The organisation also has inquiry office in another city about 50-60
60 km away in hilly region. Suggest the
suitable transmission media to interconnect to school and inquiry office out of the following :
o Microwave
o Radiowave
Answer:
1.
100 STUDENT SUPPORT MATERIAL 2023-24
2. Server can be placed in the ADMIN building as it has the maxium number of computer.
4. Radio waves can be used in hilly regions as they can travel through obstacles.
3. Vidya Senior Secondary Public School in Nainital is setting up the network between its different wings. There are
4 wings named as SENIOR(S), JUNIOR(J), ADMIN(A) and HOSTEL(H).
Distance between various wings are given below:
1. Name the most suitable wing where the Server should be installed. Justify your answer.
3. Which communication medium would you suggest to connect this school with its main branch in Delhi?
Answer:
3. Since the distance is more, wireless transmission would be better. Radiowaves are reliable and can travel
through obstacles.
4. To provide telemedicine faculty in a hilly state, a computer network is to be setup to connect hospitals in 6 small
villages (VI, V2, …, V6) to the base hospital (H) in the state capital. This is shown in the following diagram.
101 STUDENT SUPPORT MATERIAL 2023-24
1. Out of the following what kind of link should be provided to setup this network: Microwave link, Radio Link,
Wired Link ?
3. Many times doctors at village hospital will have to consult senior doctors at the base hospital. For this
purpose, how should they contact them: using email, sms, telephone, or video conference ?
(b) Out of SMTP and POP3 which protocol is used to receive emails ?
(c) What are cookies in the context of computer networks?
(d) Rajeshwari is trying for on-line
line subscription to a magazine. For this she has filled in a form on the magazine’s
web site. When the clicks submit button she gets a message
mess that she has left e-mail
mail field empty and she must fill it.
For such checking which type of script is generally executed client side script or server
server-side
side script ?
(e) Mention any one difference between free free-ware and free software.
Answer:
(a)
1. Radio Link
2. MAN
3. e-mail
(b) POP3
(c) Cookies are files that store user information that is used to identify the user when he logs into the system.
(d) Server-side script
(e) Freeware is a software that has the user to get unlimited usage for. Free software may be frefree for a certain
period only.
5.(For practice) ABC company is planning to set up their new offices in India with its hub at Guwahati. As
a Network advisor, understand their requirements and suggest to them best solution.
Block Computer
Human Resource 125
Finance 25
Conference 60
(i) Suggest a cable layout of connections between the buildings.
(ii) What is the most suitable block to install server?
(iii) What will be the best possible connectivity out of the following to connect its new office in
Bengaluru with its London-based office?
a) Infrared b) Satellite c) Ethernet Cable
(iv) Which of the devices will you suggest to connect each computer in each of the above blocks?
a) Gateway b) Switch c) Modem
(v) Differentiate between LAN and WAN.
UNIT 3
Database Management
● Database concepts: introduc on to database concepts and its need
● Rela onal data model: relation, attribute, tuple, domain, degree, cardinality, keys (candidate key,
primary key, alternate key, foreign key)
● Structured Query Language: introduc on, Data Defini on Language and Data Manipula on Language,
data type (char(n), varchar(n), int, float, date), constraints (not null, unique, primary key), create
database, use database, show databases, drop database, show tables, create table, describe table, alter
table (add and remove an attribute, add and remove primary key), drop table, insert, delete, select,
operators (mathematical, relational and logical), aliasing, distinct clause, where clause, in, between, order
by, meaning of null, is null, is not null, like, update command, delete command, aggregate functions (max,
min, avg, sum, count), group by, having clause, joins: cartesian product on two tables, equi-join and
natural join
Theory:
Relational Data Model:
In this model, data is organized in two-dimensional tables called relations. The tables or relations are
related to each other. A relational database is based on this relational model developed by E.F. Codd. In
this type of database, the data and relations between them are organized into tables, having logically
related records containing the same fields.
Advantages:
Limitation
Relational Database:
Relational databases are based on the relational model, an intuitive, straightforward way of representing
data in tables.
Terminology
Entity: An entity is something that exists and about which we can store some information. It is an
object which can be distinctly identified. For example, student entity, employee entity, item
entity, etc. Entity becomes the name of the table.
Attribute: In a relational table, an attribute is a set of values of a particular type. The term
attribute is also used to represent a column. A table consists of several records (row); each record
can be broken into several smaller entities known as fields or attributes or columns. A set of
attributes defines the characteristics or properties of an entity.
Tuple: Each row in a table is known as tuple. It is also called a row/record. A single entry in a table
is called a record or row. A record in a table represents a set of related data.
Database Keys:
Key allow us to identify an attribute or a set of attributes on the basis of which a table is identified.
They are used to establish and identify relation among two or more tables. They also ensure that
each record within a table can be uniquely identified by a combination of one or more fields
within a table.
Primary Key: A primary key is a set of one or more attributes/fields which uniquely identifies a tuple/row
in a table. The salient features of a primary key are as follows:
(a) It is always unique in nature, i.e., non-redundant. It does not have duplicate values in a relation.
(b) It arranges the table in its own order.
(c) It cannot be re-declared or left null.
(d) One table can have only one primary key; however, primary key can be a combination of more than
one field.
Candidate Key: A candidate key refers to all the attributes in a relation that are candidates or are capable
of becoming a primary key.
Candidate Keys – Primary Key = Alternate Key
Alternate Key: A candidate key that is not the primary key is called an alternate key. In other words, any
attribute that is a candidate for the primary key, i.e., which is capable of becoming a primary key but is
not a primary key, is an alternate key.
Foreign Key: A foreign key is a non-key attribute whose value is derived from the primary key of another
table; in other words, a primary key in some other table having relationship with the current or original
table.
105 STUDENT SUPPORT MATERIAL 2023-24
Sql Joins:
An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between
them. While querying for a join, more than one table is considered in FROM clause.
SYNTAX:
SELECT * FROM table1 NATURAL JOIN table2;
Union:
The UNION operator is used to combine the result-set of two or more SELECT statements.
SYNTAX:
SELECT Name FROM boys WHERE Rollno < 12 UNION SELECT Name FROM girls WHERE Rollno > 6;
106 STUDENT SUPPORT MATERIAL 2023-24
Question:
MCQ:
Sl Question Marks
No
1 In a table in MYSQL database, an attribute A of datatype varchar(20) has the value 1
“Keshav”. The attribute B of datatype char(20) has value “Meenakshi”. How many
characters are occupied by attribute A and attribute B? (CBSE SQP)
A. 20,6
B. 6,20
C. 9,6
D. 6,9
Ans Option B 6,20
2 In MYSQL database, if a table, Alpha has degree 5 and cardinality 3, and another table, 1
Beta has degree 3 and cardinality 5, what will be the degree and cardinality of the
Cartesian product of Alpha and Beta? (CBSE SQP)
A. 5,3
B. 8,15
C. 3,5
D. 15,8
Ans Option B 8,15
3 In the Database, there are two tables with the instance given below:
i. Choose the command to display name and game of those students whose address is available in 1
students’ table.
a. SELECT NAME, GAME FROM STUDENTS, SPORTS WHERE STUDENTS.ADMNO=SPORTS.ADMNO
AND ADDRESS IS NOT NULL;
b. SELECT NAME, GAME FROM STUDENTS, SPORTS WHERE STUDENTS.ADMNO=SPORTS.ADMNO
AND ADDRESS IS NULL;
c. SELECT NAME, GAME FROM STUDENTS, SPORTS WHERE STUDENTS.ADMNO=SPORTS.ADMNO,
ADDRESS IS NULL;
d. SELECT NAME, GAME FROM STUDENTS, SPORTS WHERE STUDENTS.ADMNO=SPORTS.ADMNO
NOT ADDRESS IS NULL
Ans a. SELECT NAME, GAME FROM STUDENTS, SPORTS WHERE STUDENTS.ADMNO=SPORTS.ADMNO
AND ADDRESS IS NOT NULL;
ii. Identify the statement to delete a column phone from the table students. 1
a. ALTER TABLE STUDENTS DROP PHONE;
b. DROP PHONE;
c. UPDATE DROP PHONE; d. DELETE FROM STUDENTS WHERE DROP PHONE;
107 STUDENT SUPPORT MATERIAL 2023-24
c) where
d) group by
Ans (b)
True/False
Sl No Question Marks
1 There can be 2 primary key in a relational table. True or False? 1
Ans False
2 The two property of primary key if UNIQUE and NOT NULL. True or False? 1
Ans True
2-MARK QUESTIONS:
Sl Question Marks
No
1 Observe the following table and answer the parts (i) and (ii) accordingly 2
Pno Name Qty Purchase
101 Pen 600 12-12-2011
102 Pencil 200 21-02-2013
103 Eraser 300 09-08-2010
113 clips 500 12-12-2011
a) Write the names of most appropriate columns, which can be considered as candidate keys.
b) What is the degree and cardinality of the above table?
Ans a. Candidate key-Pno, Name
b. Degree-4 Cardinality-4
3-MARK QUESTIONS:
Sl Question Marks
No
1 Consider the table CLUB given below and write the output of the SQL queries that follow. 1*3= 3
[10]
a)
COUNT(DISTINCT SPORTS)
4
b)
CNAME SPORTS
AMINA CHESS
c)
Based on the given table, write SQL queries for the following:
a. Increase the salary by 5% of personals whose allowance is known.
b. Display Name and Total Salary (sum of Salary and Allowance) of all personals. The
column heading ‘Total Salary’ should also be displayed.
c. Delete the record of personals who have salary greater than 25000
Ans: a. UPDATE Personal SET Salary=Salary + Salary*0.5 WHERE Allowance IS NOT NULL
b. SELECT Name, Salary + Allowance AS "Total Salary" FROM Personal;
c. DELETE FROM Personal WHERE Salary>25000
b)Write the output of the queries (i) to (iv) based on the table EMPLOYEE given below
Empid Empname Salary Deptid
E1 Prabhath 12000 D1
E2 Nikhil 14000 D1
E3 Devansh 10000 D2
E4 Debraj 15000 D3
E5 Aron 18000 D1
Ans
(i)
Deptid
D1
D2
D3
(ii)
Deptid count(*) min(salary)
D1 3 12000
(iii)
Empname
Aron
Debraj
(iv)
Sum(Salary)
33000
4 Write the outputs of the SQL queries (i) to (iv) based on the 3
relations Teacher and Placement given below:
BOOK
Book_id Book_name Price Qty Author_id
1001 My first C++ 323 12 204
1002 SQL basics 462 6 202
1003 Thunderbolts 248 10 203
1004 The tears 518 3 204
AUTHOR
Author_id Author_name Country
201 William Hopkins Australia
202 Anita India
203 Anna Roberts USA
204 Brain&Brooke Italy
Ans
(i)
Author_id Avg(price)
204 420.5
202 462
203 248
(ii)
MAX(price) MIN(price)
518 248
(iii)
Book_name Author_name Country
My First C++ Brain&Brooke Italy
SQL Basics Anita India
The Tears Brain&Brooke Italy
(iv)
Author_name
Anita
Anna Roberts
4-MARK QUESTIONS:
Sl Question Marks
No
1 Consider the following tables EMPLOYEES and EMPSALARY. Write SQL commands for the 1*4=4
statements (i) to (iv)
i. To display Firstname, Lastname, Address and City of all employees living in Paris from the
table EMPLOYEES.
ii. To display the content of EMPLOYEES table in descending order of FIRSTNAME.
iii. To display the Firstname, Lastname, and Total Salary of all Managers from the tables
EMPLOYEES and EMPSALARY, where Total Salary is calculated as Salary + Benefits.
iv. To display the Maximum salary among Managers and Clerks from the table EMPSALARY
113 STUDENT SUPPORT MATERIAL 2023-24
Ans i. Select FIRSTNAME, LASTNAME, ADDRESS, CITY From EMPLOYEES Where CITY= ‘Paris’;
ii. Select * From EMPLOYEES Order By FIRSTNAME DESC;
iii. Select FIRSTNAME, LASTNAME, SUM (SALARY+BENEFITS) From EMPLOYEES, EMPSALARY
Where EMPLOYEES.EMPID=EMPSALARY.EMPID;
iv. Select Max(SALARY) From EMPSALARY Where DESIGNATION = ‘Manager’ OR DESIGNATION
= ‘Clerk
5-MARK QUESTIONS:
Sl Question Marks
No
1 Consider the tables PRODUCT and BRAND given below: 1*5=
4
Table: PRODUCT
Table: BRAND
BID BName
M02 Dant Kanti
M03 Medimix
M04 Pepsodent
M05 Dove
2 Consider the following tables Doctor and Recipient. Write SQL commands for the statements (i) to
(iv) and give the outputs for SQL queries (v) to (viii).