Download as pdf or txt
Download as pdf or txt
You are on page 1of 116

KENDRIYA VIDYALAYA SANGATHAN

SILCHAR REGION

STUDENT SUPPORT MATERIAL


COMPUTER SCIENCE
CLASS: XII (2023-24)
24)
KENDRIYA VIDYALAY
VIDYALAYA SANGATHAN
SILCHAR REGION
PATRONS

SH. P.I.T RAJA


DEPUTY COMMISSIONER
KVS SILCHAR REGION

SH. SATYAVEER SINGH


ASSISTANT COMMISSIONER
KVS SILCHAR REGION
1 STUDENT SUPPORT MATERIAL 2023-24

CONTENT DEVELOPMENT TEAM

Coordinator: Sri Suneel Gupta, Principal KV NIT Silchar

S No Chapter Name Name of the teacher KV Name


Computational thinking and
programming-2 (revision of
1 Mr. G. K. Verma TURA
python 1topics covered in class
XI
Computational thinking and
programming-2 (revision of
NEHU
2 python -2 topics covered in class Ms. Geeta Khemchandani
Shillong
XI): Strings, Lists, Sorting,
Tuple & Dictionary
ONGC
3 Mr Pranab Sarkar
Functions Srikona
4 Mr. Sreehari S MU Aizawl
ONGC
5 Mr. Pramod Kumar
Agartala
Computer Networks
Mr. Prabhod Dinakar
6 NIT Silchar
Palle
7 Database concepts Mr. Mrinal Debnath Kunjaban

COMPUTER SCIENCE WITH PHYTHON Page 1


2 STUDENT SUPPORT MATERIAL 2023-24

INDEX

SNO CHAPTER PAGE PAGE


FROM TO
1 Syllabus 3 5
2 Computational thinking and programming-2
6 22
(revision of python 1topics covered in class XI
3 Computational thinking and programming-2
(revision of python -2 topics covered in class XI): 23 33
Strings, Lists, Sorting, Tuple & Dictionary
4 Functions 34 79
5 Computer Networks 80 102
6 Database concepts 103 114

COMPUTER SCIENCE WITH PHYTHON Page 2


3 STUDENT SUPPORT MATERIAL 2023-24

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:

Computational Thinking and Programming – 2

● Revision of Python topics covered in Class XI.

● 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

scope, local scope)

● 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

COMPUTER SCIENCE WITH PHYTHON Page 3


4 STUDENT SUPPORT MATERIAL 2023-24

● 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

update operations in a binary file

● CSV file: import csv module, open / close csv file, write into a csv file using writer(),writerow(),writerows()

and read from a csv file using reader()

● Data Structure: Stack, opera ons on stack (push & pop), implementation of stack using list. Unit II:

Computer Network

Unit II: Computer Networks

● Evolu on of networking: introduc on to computer networks, evolu on of networking (ARPANET,

NSFNET, INTERNET)

● Data communica on terminologies: concept of communica on, components of data communication

(sender, receiver, message, communication media, protocols), measuring capacity of communication media

(bandwidth, data transfer rate), IP address, switching techniques (Circuit switching, Packet switching)

● Transmission media: Wired communication media (Twisted pair cable, Co-axial cable, Fiber-optic cable),

Wireless media (Radio waves, Micro waves, Infrared waves)

● Network devices (Modem, Ethernet card, RJ45, Repeater, Hub, Switch, Router, Gateway, WIFI card)

● Network topologies and Network types: types of networks (PAN, LAN, MAN, WAN), networking

topologies (Bus, Star, Tree)

● Network protocol: HTTP, FTP, PPP, SMTP, TCP/IP, POP3, HTTPS, TELNET, VoIP

● 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

Unit III: Database Management

● Database concepts: introduc on to database concepts and its need

● Rela onal data model: rela on, a ribute, 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,

COMPUTER SCIENCE WITH PHYTHON Page 4


5 STUDENT SUPPORT MATERIAL 2023-24

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

S.No Unit Name Marks(Total=30)

1 Lab Test: 8
1.Pythonprogram(60%logic+20%documentation
+20%codequality)

2.SQLqueries (4 queries based on one or two tables) 4

2 Report file: 7
● Minimum15Python programs.
● SQL Queries –Minimum 5 sets using one table
/two tables.
● Minimum4programsbasedonPython -SQL connectivity

3 Project (using concepts learnt in Classes11and 12) 8

4 Viva voce 3

COMPUTER SCIENCE WITH PHYTHON Page 5


6 STUDENT SUPPORT MATERIAL 2023-24

Revision Tour-I
Computational thinking and programming-2
(Topics covered in Class XI)
Basics of Python
Observe the program first then memorize the definitions:

Python keyword/ reserve words


Keywords are reserve words. Each keyword has a specific meaning to the Python interpreter,
and we can use a keyword in our program only for the purpose for which it has been defined.
As Python is case sensitive, keywords must be written exactly.

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.

COMPUTER SCIENCE WITH PHYTHON Page 6


7 STUDENT SUPPORT MATERIAL 2023-24

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.

Sequences can used as data type in python


A Python sequence is an ordered collection of items, where each item is indexed by an integer.
The three types of sequence data types available in Python are Strings, Lists and Tuples. A brief
introduction to these data types is as follows:
(A) String
String is a group of characters. These characters may be alphabets, digits or special characters
including spaces. String values are enclosed either in single quotation marks (e.g., ‘KV’) or in
double quotation marks (e.g., “Vidyalaya”). The quotes are not a part of the string, they are
used to mark the beginning and end of the string for the interpreter. For example:
Write your examples here:

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

list1 = [5, 3.4, "New Delhi", "20C", 45]


print(list1) #printin the elements of list1 Output: [5,
3.4, 'New Delhi', '20C', 45]
(C) Tuple
Tuple is a sequence of items separated by commas and items are enclosed in parenthesis (
).Once created, we cannot change the tuple (Records cannot be changed) – i.e. we can say
immutable datatype.
Tuple can be defined as
T=5,
T=(5,)

COMPUTER SCIENCE WITH PHYTHON Page 7


8 STUDENT SUPPORT MATERIAL 2023-24

T=5,6,7,8
T= ‘a’,’b’,’c’,5,6,7
T=(5,6,’r’,’s’,’wel’)

#create a tuple tuple1


tuple1 = (10, 20, "KV", 5.5, 'a')
print(tuple1) #printing the elements of the tuple tuple1

Output: (10, 20, "KV", 5.5, 'a')

(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

Mutable and Immutable Data Types


Variables whose values can be changed after they are created and assigned without changing
their memory location are called mutable. Variables whose values cannot be changed after they
are created and assigned or upon changing values their memory location is changed, are called
immutable. When an attempt is made to update the value of an immutable variable, the old
variable is destroyed and a new variable is created by the same name in new memory location.
Exercise: Define a variable by assigning a value, find and note its ID, change the value and again
find its ID, now observe the difference and do it for different data types.

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)

COMPUTER SCIENCE WITH PHYTHON Page 8


9 STUDENT SUPPORT MATERIAL 2023-24

Order of Precedence (higher to lower)

1 ** Exponentiation (raised to the power)


2 ~ ,+, - Complement, unary plus and unary minus
3 * ,/, %, // Multiply, divide, modulo and floor division
4 +, - Addition and subtraction
5 <= ,< ,> ,>= Relational operators
6 == ,!= Equality operators
7 =, %=, /=, //=, -=, +=, *=, **= Assignment operators
8 is is not Identity operators
9 in, not in Membership operators
10 not, and, or Logical operators

* 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

The if statement has following syntaxes:


1)
if condition:
statement(s)

2)
if condition:
statement(s)
else:
statement(s)

3) if condition:
statement(s)
elif condition:
statement(s)
.
.
elif condition:
statement(s)
else:
statement(s)

COMPUTER SCIENCE WITH PHYTHON Page 9


10 STUDENT SUPPORT MATERIAL 2023-24

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.

Syntax of while loop:-


while test_condition:
body of while

Break and Continue Statement


In certain situations, when some particular condition occurs, we may want to exit from a loop
(come out of the loop forever) or skip some statements of the loop before continuing further in
the loop. These requirements can be achieved by using break and continue statements,
respectively.

COMPUTER SCIENCE WITH PHYTHON Page 10


11 STUDENT SUPPORT MATERIAL 2023-24

PYTHON REVISION TOUR (MCQs with Solution)


Q.NO. QUESTIONS
1. Which of the following is not considered a valid identifier in Python ?
i. Two2 (ii) _main (iii) hello_rsp1 (iv) 2 hundred
2. What will be the output of the following code ?
print(“100+200”)
(i) 300 (ii) 100200 (iii) 100+200 (iv) 200
3. pow( ) function belongs to which library ?
(i) math (ii) string (iii) random (iv) maths
4. What is the output of the following?
x = 123
for i in x:
print(i)

(i) 123 (ii) 1 2 3 (iii) error (iv) infinite


5. What data type is the object below?
L = 1, 23, ‘hello’,1
( a) list (b) dictionary (c) array (d) tuple
6. What is the value of this expression 3**3**1 ?
(i) 27 (ii) 9 (iii) 3 (iv) 1
7. List AL is defined as follows:
AL=[1,2,3,4,5]
Which of the following statement/statements removes the middle element 3 from it so that the list
AL equals [1,2,4,5] ?
( a) del a[2] (b) a[2:3] = [ ] (c) a[2 : 2]=[ ]
(d) a[ 2 ] = [ ] (e) a.remove(3)
8. Find the valid identifier from the following
a) False b) Ist&2nd c) 2ndName d) My_Name
9. Given the lists L=[1,30,67,86,23,15,37,131,9232] , write the output of print(L[3:7])
( a) [67,86,23,15,37] (b) [86,23,15,37]
10. Identify the invalid logical operator in Python from the following.
a) and b) or c) not d) Boolean
11. Suppose a tuple T is declared as T = (10, 12, 43, 39), which of the following is Incorrect?
a) print( T[1] ) b) print(max(T))
c) print(len(T)) d) None of the these
12. A list is declared as
Lst = [1,2,3,4,5,6,8]
What will be the value of sum(Lst)?
i. 29 (ii) 30 (iii) 7 (iv) 8
13. If the following code is executed, what will be the output of the following code?
name="Computer_Science_with_Python"
print(name[-25:10])
i. puter_S (ii) hon (iii) puter_Science
14. Can tuple be nested?
a. Yes (b) No
15. Can we modify/change keys of a dictionary?
(a) Yes (b) No
16. ………………method of list is used to delete a given element from the list.
i. del (ii) extend( ) (iii) remove( ) (iv) append( )
17. A tuple is declared as
T = (2,66,77,55,6,9,55,8)

COMPUTER SCIENCE WITH PHYTHON Page 11


12 STUDENT SUPPORT MATERIAL 2023-24

Write the output of


print(T.index(55))
i. 4 (ii) 3 (iii) 55 (iv) None of these.
18. Which of the following is/are valid declaration of a dictionary?
a) D = {'StuName': 'Alan', 'StuAge': 30, 'StuCity': 'Vizag'}
b) D = ['StuName': 'Alan', 'StuAge': 30, 'StuCity': 'Vizag']
c) D = ('StuName': 'Alan', 'StuAge': 30, 'StuCity': 'Vizag')
d) D = {'StuName'; 'Alan', 'StuAge': 30, 'StuCity': 'Vizag'}
19. If the following code is executed, what will be the output of the following code?
Title="Online Teaching 2020"
print(Title[6:10], Title[-2:-4:-1])

(a) Tea 20 (b) Error (c) e Tea 02


20. Write the output of the following python expression:
print((4>5) and (2!=1) or (4<9))
i. False (ii) True
21. Find the operator which cannot be used with a string in Python from the following:
(a) + (b) in (c) * (d) //
22. Which of the following is not a keyword?
(a) eval
(b) assert
(c) nonlocal
(d) pass
23. Which value type does input () return?
(a) Boolean
(b) String
(c) Int
(d) Float
24. The operator _____ tells if an element is present in a sequence or not.
(a) exists
(b) in
(c) into
(d) inside
25. The keys of a dictionary must be of _____ types.
(a) Integer
(b) mutable
(c) immutable
(d) any of these
26 What is the output when we execute list (“hello”)?
a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
b) [‘hello’]
c) [‘llo’]
d) [‘olleh’]
27 Suppose list1 is [2445,133,12454,123], what is max(list1)?
a) 2445
b) 133
c) 12454
d) 123
28 Suppose list1 is [2, 33, 222, 14, 25], What is list1 [-1]?
a) Error
b) None

COMPUTER SCIENCE WITH PHYTHON Page 12


13 STUDENT SUPPORT MATERIAL 2023-24

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?

COMPUTER SCIENCE WITH PHYTHON Page 13


14 STUDENT SUPPORT MATERIAL 2023-24

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

a) True b) False c) None d) Error


47 What will be the output of the following Python code snippet?

COMPUTER SCIENCE WITH PHYTHON Page 14


15 STUDENT SUPPORT MATERIAL 2023-24

print(‘my_string’.isidentifier())

a) True b) False c) None d) Error


48 What will be the output of the following Python code?

print(‘xyxxyyzxxy.lstrip(‘xyy’))

a) zxxy b) xyxxyyzxxy c) xyxzxxy d) none of the mentioned


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

PYTHON REVISION TOUR


ANSWER KEY (MCQs)
Q.NO. QUESTIONS
1. Which of the following is not considered a valid identifier in Python ?
ii. Two2 (ii) _main (iii) hello_rsp1 (iv) 2 hundred
Ans (iv) 2 hundred
2. What will be the output of the following code ?
print(“100+200”)
(i) 300 (ii) 100200 (iii) 100+200 (iv) 200
Ans (iii) 100+200
3. pow( ) function belongs to which library ?
(i) math (ii) string (iii) random (iv) maths
Ans (i) math
4. What is the output of the following ?
x = 123
for i in x:
print(i)
(i) 123 (ii) 1 2 3 (iii) error (iv) infinite
Ans (iii) error
5. What data type is the object below?
L = 1, 23, ‘hello’,1
( a) list (b) dictionary (c) array (d) tuple
Ans (d) tuple

COMPUTER SCIENCE WITH PHYTHON Page 15


16 STUDENT SUPPORT MATERIAL 2023-24

6. What is the value of this expression 3**3**1 ?


(i) 27 (ii) 9 (iii) 3 (iv) 1
Ans (i) 27
7. List AL is defined as follows:
AL=[1,2,3,4,5]
Which of the following statement/statements removes the middle element 3 from it so that the list
AL equals [1,2,4,5] ?
( a) del a[2] (b) a[2:3] = [ ] (c) a[2 : 2]=[ ]
(d) a[ 2 ] = [ ] (e) a.remove(3)
Ans (a) , (b) and (e)
8. Find the valid identifier from the following
a) False b) Ist&2nd c) 2ndName d) My_Name
Ans (d) My_Name
9. Given the lists L=[1,30,67,86,23,15,37,131,9232] , write the output of print(L[3:7])
( a) [67,86,23,15,37] (b) [86,23,15,37]
Ans (b) [ 86,23,15,37 ]
10. Identify the invalid logical operator in Python from the following.
a) and b) or c) not d) Boolean
Ans (d) Boolean
11. Suppose a tuple T is declared as T = (10, 12, 43, 39), which of the following is Incorrect?
a) print( T[1] ) b) print(max(T))
c) print(len(T)) d) None of the these
Ans d) None of the these
12. A list is declared as
Lst = [1,2,3,4,5,6,8]
What will be the value of sum(Lst)?
ii. 29 (ii) 30 (iii) 7 (iv) 8
Ans (i) 29
13. If the following code is executed, what will be the output of the following
code?
name="Computer_Science_with_Python"
print(name[-25:10])
ii. puter_S (ii) hon (iii) puter_Science
Ans. puter_S
14. Can tuple be nested ?
b. Yes (b) No
14. (a) Yes
15. Can we modify/change keys of a dictionary ?
(a) Yes (b) No
Ans (b) No
16. ………………method of list is used to delete a given element from the list.
ii. del (ii) extend( ) (iii) remove( ) (iv) append( )
Ans. (iii) remove
17. A tuple is declared as
T = (2,66,77,55,6,9,55,8)
Write the output of
print(T.index(55))
ii. 4 (ii) 3 (iii) 55 (iv) None of these.
Ans (ii) 3
18. Which of the following is/are valid declaration of a dictionary?
a) D = {'StuName': 'Alan', 'StuAge': 30, 'StuCity': 'Vizag'}

COMPUTER SCIENCE WITH PHYTHON Page 16


17 STUDENT SUPPORT MATERIAL 2023-24

b) D = ['StuName': 'Alan', 'StuAge': 30, 'StuCity': 'Vizag']


c) D = ('StuName': 'Alan', 'StuAge': 30, 'StuCity': 'Vizag')
d) D = {'StuName'; 'Alan', 'StuAge': 30, 'StuCity': 'Vizag'}
Ans a) D = {'StuName': 'Alan', 'StuAge': 30, 'StuCity': 'Vizag'}
19. If the following code is executed, what will be the output of the following code?

Title="Online Teaching 2020"


print(Title[6:10], Title[-2:-4:-1])

(a) Tea 20 (b) Error (c) e Tea 02


Ans (a) Tea 20
20. Write the output of the following python expression:
print((4>5) and (2!=1) or (4<9))

ii. False (ii) True


Ans (ii) True
21. Find the operator which cannot be used with a string in Python from the following:
(a) + (b) in (c) * (d) //
Ans (d) //
22. Which of the following is not a keyword?
(a) eval (b) assert
(c) nonlocal (d) pass
Ans (c) nonlocal
23. Which value type does input() return?
(a) Boolean (b) String
(c) Int (d) Float
Ans c. String
24. The operator _____ tells if an element is present in a sequence or not.
(a) exists
(b) in
(c) into
(d) inside
Ans (b ) in
25. The keys of a dictionary must be of _____ types.
(a) Integer
(b) mutable
(c) immutable
(d) any of these
Ans (c ) immutable
26 What is the output when we execute list(“hello”)?
a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
b) [‘hello’]
c) [‘llo’]
d) [‘olleh’]
Ans a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
27 Suppose list1 is [2445,133,12454,123], what is max(list1)?
a) 2445 b) 133 c) 12454 d) 123
Ans C
28 Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1]?

COMPUTER SCIENCE WITH PHYTHON Page 17


18 STUDENT SUPPORT MATERIAL 2023-24

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?

COMPUTER SCIENCE WITH PHYTHON Page 18


19 STUDENT SUPPORT MATERIAL 2023-24

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
Ans C
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
Ans B
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”)
Ans B
40 What will be the output of the “hello” +1+2+3?
a) hello123 b) hello c) Error d) hello6
Ans C
41 Say s=”hello” what will be the return value of type(s)?
a) int b) bool c) str d) String
Ans C
42 What is “Hello”.replace(“l”, “e”)?
a) Heeeo b) Heelo c) Heleo d) None
Ans A
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
Ans A
44 What will be displayed by print(ord(‘b’) – ord(‘a’))?
a) 0 b) 1 c) -1 d) 2
Ans B
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


Ans C
46 What will be the output of the following Python code?
print(‘a B’.isalpha())
a) True b) False c) None d) Error
Ans B
47 What will be the output of the following Python code snippet?
print(‘my_string’.isidentifier())
a) True b) False c) None d) Error
Ans A
48 What will be the output of the following Python code?
print(‘xyxxyyzxxy.lstrip(‘xyy’))

COMPUTER SCIENCE WITH PHYTHON Page 19


20 STUDENT SUPPORT MATERIAL 2023-24

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

2 Marks Question as per Board Pattern with Solutions

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

Q2. Predict the output of the Python code given below:

tuple1 = (33, 24, 44, 42, 54 ,65)


list1 =list(tuple1)
new_list = []
for i in list1:
if i>40:
new_list.append(i)

COMPUTER SCIENCE WITH PHYTHON Page 20


21 STUDENT SUPPORT MATERIAL 2023-24

new_tuple = tuple(new_list)
print(new_tuple)

ANS: (44, 42, 54, 65)

Q3. Predict the output of the code givenbelow:


s="PREboardCS*2022!"
j=2
for i in s.split('*'):
k=i[:j]
if k.isupper():
j=j+1
elif k.isdigit():
j=j+2
else:
j=j+3
print(s [ j : : j ] )

ANS:
brS0!
a*!

Q4. (a). Given is a Python string declaration:


myexam="@@Pre Board 2022@@"

Write the output of: print(myexam[15:11:-1])


Ans: 2202

(b). Write the output of the code given below:


my_dict = {"state": "Assam", "city":”silchar”} my_dict['district'] = “Cachar”
print(my_dict.values())

Ans: dict_values(['Assam', 'silchar', 'Cachar'])

Q5. Predict the output of the Python code given below:

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

COMPUTER SCIENCE WITH PHYTHON Page 21


22 STUDENT SUPPORT MATERIAL 2023-24

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 |

a. i , iii b. ii , iv c. Only i d. ii, iii

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

Indexing of characters in string 'Hello World!'

#initializes a string str1


>>> str1 = 'Hello World!'
#gives the first character of str1
>>> str1[0]
'H'
#gives seventh character of str1
>>> str1[6]
'W'
#gives last character of str1
>>> str1[11]
'!'
#gives error as index is out of range
>>> str1[15]
IndexError: string index out of range
Lists In Python
The data type list is an ordered sequence which is mutable and made up of one or more elements.
 a list can have elements of different
ifferent data types, such as integer, float, string, tuple or even another
list.
 A list is very useful to group together elements of mixed data types.
 Elements of a list are enclosed in square brackets and are separated by comma.
 list indices also start from 0.
 The index of the last element is n-1
n 1 where n is the total number of elements in the list.

#list3 is the list of mixed data types


>>> list3 = [100,23.5,'Hello']
>>> print(list3)
[100, 23.5, 'Hello']
#list4 is the list of lists called nested list
>>>
>> list4 =[['Physics',101],['Chemistry',202],['Maths',303]]
>>> print(list4)
[['Physics', 101], ['Chemistry', 202],['Maths', 303]]
#initializes a list list1
>>> list1 = [2,4,6,8,10,12]
24 STUDENT SUPPORT MATERIAL 2023-24

>>> list1[0] #return first element of list1


2
#return error as index is out of range
>>> list1[15]
IndexError: list index out of range
>>> list1[-1]
1] #return first element from right
12
#length of the list list1 is assigned to n
>>> n = len(list1)
>>> print(n)
6
#return the last element of the list1
>>> list1[n-1]
12
#return the first element of list1
>>> list1[-n]
2
Tuples in Python
A tuple is an ordered sequence of elements of different data types, such as integer,
float, string, list or even a tuple.
 Elements of a tuple are enclosed in parenthesis (round brackets) and are
separated by commas. Like list and string,
 elements of a tuple can be accessed using index values, starting from 0.
 Tuples are immutable datatype
 Put , (comma) for creating tuple of single element.

#tuple1 is the tuple of integers


>>> tuple1 = (1,2,3,4,5)
>>> tuple1
(1, 2, 3, 4, 5)
#tuple2 is the tuple of mixed data types
>>> tuple2 =('Economics',87,'Accountancy',89.6)
>>> tuple2
('Economics', 87, 'Accountancy', 89.6)
#tuple3 is the tuple with list as an element
>>> tuple3 = (10,20,30,[40,50])
>>> tuple3
(10, 20, 30, [40, 50])
#tuple4 is the tuple with tuple as an element
>>> tuple4 = (1,2,3,4,5,(10,20))
>>> tuple4
(1, 2, 3, 4, 5, (10, 20))
#Correct Way of assigning single element to
#tuple
#tuple5 is assigned a single element
>>> tuple5 = (20,) #element f
followed by comma
>>> tuple5
(20,)
>>>type(tuple5) #tuple5 is of type tuple <class 'tuple'>
#a sequence without parentheses is treated as tuple by default
>>> seq = 1,2,3 #comma separated elements
>>> type(seq) #treated as tuple <class 'tuple'>
>>> print(seq)
q) #seq is a tuple
(1, 2, 3)
25 STUDENT SUPPORT MATERIAL 2023-24

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.

#dict1 is an empty Dictionary created


#curly braces are used for dictionary
>>> dict1 = {}
>>> dict1
{}
#dict2 is an empty dictionary created using built-in function
>>> dict2 = dict()
>>> dict2
{}
#dict3 is the dictionary that maps names #of the students to respective marks
in
#percentage
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92,
'Sangeeta':85}
>>> dict3
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,
'Sangeeta': 85}

The following example shows how a dictionary returns the value corresponding to the
given key:

>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}


>>> dict3['Ram']
89
>>> dict3['Sangeeta']
85
#the key does not exist
>>> dict3['Shyam']
KeyError: 'Shyam'

COMPUTER SCIENCE WITH PHYTHON Page 25


26 STUDENT SUPPORT MATERIAL 2023-24

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

6 What will be the output of the following python dictionary operation? 1


data = {'A':2000, 'B':2500, 'C':3000, 'A':4000}
print(data)
a) {'A':2000, 'B':2500, 'C':3000, 'A':4000}
b) {'A':2000, 'B':2500, 'C':3000}
c) {'A':4000, 'B':2500, 'C':3000}
d) It will generate an error.
7 What will be the output of the following string operation. 1
str="PYTHON@LANGUAGE"
print(str[2:12:2])
27 STUDENT SUPPORT MATERIAL 2023-24

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

12 Predict the output of the following python code: 2


data = [2,4,2,1,2,1,3,3,4,4]
d = {}
for x in data:
if x in d:
d[x]=d[x]+1
else:
d[x]=1
print(d)
28 STUDENT SUPPORT MATERIAL 2023-24

13 2

14 2

15 Write the output of following code and explain the 2


difference between a*3 and (a,a,a)
a=(1,2,3)
print(a*3)
print(a,a,a)
16 (a) What will be the output of following program: 2
s="welcome2kv"
n = len(s)
m=""
for i in range(0, n):
if (s[i] >= 'a' and s[i] <= 'm'):
m = m +s[i].upper()
elif (s[i] >= 'n' and s[i] <= 'z'):
m = m +s[i-1]
elif (s[i].isupper()):
m=m+s[i].lower()
else:
m=m+’#’
print(m)
17 a. Given a python list decleration, give the output of the following stmt: 2
Lst1=[39,45,23,15,25,60]
print(Lst1.index(23))
29 STUDENT SUPPORT MATERIAL 2023-24

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

22 Give output of the following code: 3


30 STUDENT SUPPORT MATERIAL 2023-24

23 What will be the output of the following python program? 3


str = ""
name = "9@Days"
for x in name:
if x in "aeiou":
str+=x.upper()
elif not x.isalnum():
2+3
9|Page
str+="**"
elif x.isdigit():
pass
else:
str+=x.lower()
print(str)
24 Write a function INDEX_LIST(L), where L is the list of elements passed as 3
argument to the function. The function returns another list named ‘indexList’
that stores the indices of all Non
Non-Zero Elements of L.
For example:
If L contains [12,4,0,11,0,56]
The indexList will have - [0,1,3,5]
25 Write a function SQUARE_LIST(L), where L is the list of elements passed as 3
argument to the function. The function returns another list named ‘SList’ that stores
the Squares of all Non-Zero Elements of L.
For example:
If L contains [9,4,0,11,0,6,0]
26 Write the output of the code given below: 3
def fun(s):
k=len(s)
m=" "
for i in range(0,k):
if s[i].isupper():
m=m+s[i].lower()
elif s[i].islower():
m=m+s[i].upper()
31 STUDENT SUPPORT MATERIAL 2023-24

elif s[i].isdigit():
m=m+"O"
else:
m=m+'#'
print(m)
fun('CBSE@12@Exam')

Answers to the practice questions:

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

16 Output: vELCcME#Kk (1 mark for vELC and 1 mark for cME#Kk)


17 a. 2
b. 5
18 Thon
32 STUDENT SUPPORT MATERIAL 2023-24

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

Defining a function in Python:

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

In Python a function is defined using the def keyword

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

The basic syntax for using the `return` statement is as follows:

Here's what you need to know about the `return` statement:


1.Returning a Value:
When you want to return a specific value from the function, you can use the
`return` statement followed by the value you want to return.
Note: The function will stop executing immediately after the `return` statement is
encountered, and the value will be passed back to the caller.
36 STUDENT SUPPORT MATERIAL 2023-24

2.Returning Multiple Values:


Python allows you to return multiple values from a function as a tuple. You can simply
separate the values with commas after 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.

4. Early Exit with Return:


You can use the `return` statement to exit a function early if certain conditions are met.
This is useful when you want to terminate the function before reaching the end.

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:

 Variables defined outside of any function or block has a global scope.


 They are accessible from anywhere in the code, including inside functions.
37 STUDENT SUPPORT MATERIAL 2023-24

Local Scope:

 Variables defined inside a function have a local scope.


 They
Local are
when theaccessible
variables only within
are returns.
function created whenthe function
the where
function theyand
is called aredestroyed
defined.

Passing list as argument to the function:

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:

Types of arguments passed to a function:

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:

 math.pi: Represents the mathematical constant π (pi).


 math.e: Represents the mathematical constant e (Euler's
number). Basic Mathematical Functions:
 math.sqrt(x): Returns the square root of x.
 math.pow(x, y): Returns x raised to the power y.
 math.exp(x): Returns the exponential of x (e^x).
 math.log(x, base): Returns the logarithm of x to the specified base
(default base is e).
Trigonometric Functions (all angles are in radians):
 math.sin(x), math.cos(x), math.tan(x): Sine, cosine, and tangent of x,
respectively.
 math.asin(x), math.acos(x), math.atan(x): Arcsine, arccosine, and
arctangent of x, respectively.
Hyperbolic Functions:
 math.sinh(x), math.cosh(x), math.tanh(x): Hyperbolic sine, cosine, and
tangent of x, respectively.
Angular Conversion:
 math.degrees(x): Converts x from radians to degrees.
 math.radians(x): Converts x from degrees to
radians. Miscellaneous:
 math.ceil(x): Returns the smallest integer greater than or equal to x.
 math.floor(x): Returns the largest integer less than or equal to x.
 math.factorial(x): Returns the
factorial of x. Study the following
examples:

Example 1:

Example 2:

Example 3:
41 STUDENT SUPPORT MATERIAL 2023-24

Statistics module:

 The statistics module in Python is another built-in module that


provides functions for working with statistical data.
 It offers a variety of statistical functions to compute measures like
mean, median, standard deviation, variance, etc.
 The statistics module is part of the Python Standard Library, so there's
no need to install any additional packages to use it.
Here are some commonly used functions provided by the statistics module:
 statistics. mean (data): Calculates the arithmetic mean (average) of the data.
 statistics.median(data): Computes the median value of the data.
 statistics.mode(data): Finds the mode (most common value) in the data.

Example 1:

Example 2:

Random module

 The random module in Python is another built-in module that provides


functions for generating random numbers, sequences, and making
random choices.
42 STUDENT SUPPORT MATERIAL 2023-24

 It is commonly used for tasks such as random number generation,


random shuffling, and random sampling.
Here are some commonly used functions provided by the random module:

 random.random(): Generates a random float number in the range [0.0, 1.0).


 random.uniform(a, b): Generates a random float number in the range [a, b).
 random.randint(a, b): Generates a random integer in the range [a, b] (inclusive).
 random.choice(sequence): Picks a random element from a sequence (list, tuple, string, etc.).
 random.shuffle(sequence): Shuffles the elements of a sequence randomly (in- place).

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:

iii. 29: 26:24 :28 : iv. 29: 26:25:26:


Solution:
Option iv
43 STUDENT SUPPORT MATERIAL 2023-24

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

1. What will be the output of the following code?

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

3. What is the scope of a variable defined inside a function?


a. Global scope
b. Local scope
c. Universal scope
d. Function scope

4. In Python, can a function return multiple values simultaneously?


a. Yes
b. No
44 STUDENT SUPPORT MATERIAL 2023-24

5. What is the purpose of the "return" statement in a function?


a. It specifies the type of the function.
b. It defines the input parameters of the function.
c. It indicates the end of a function.
d. It returns a value from the function to the caller.

6. Which of the following module functions generates an integer?


a. randint()
b. uniform()
c. random()
d. all of these

7. The return type of the input() function is


a. string
b. integer
c. list
d. tuple

8. The values being passed through a function call statements are called
. Actual parameter
a. Formal parameter
b. default parameter
c. None of these

9. Which of the following components are part of a function header in Python?


a. Function Name
b. Return Statement
c. Parameter List
d. Both a and c

10. Which of the following function header is correct?


a. def cal_si(p=100, r, t=2)
b. def cal_si(p=100, r=8, t)
c. def cal_si(p, r=8, t)
d. def cal_si(p, r=8, t=2)
11. Which of the following is the correct way to call a function?
. my_func()
a. def my_func()
b. return my_func
c. call my_func()

COMPUTER SCIENCE WITH PHYTHON Page 44


45 STUDENT SUPPORT MATERIAL 2023-24

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

15. statistics.mode([10,10,11,12,14,11,11,15,15,16,15]) will return (consider module is imported)


a. 10
b. 15
c. 11
d. Error

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

18. What will be the output of the following code?


>>> def a(b=11, c=21):
b += 13
c -= 13
return b+c 0.77
>>> print(a(25), a(35)) a)
15 18
b) 46 56
c) 25 35
d) 13 12

19. What will be the output of the following code?


num=100
def showval(X):
global num num = 85
if(X%2==0):
num += X else:
num -= X print(num,end="#")
showval(33)
print(num)
a) 100#52
b) 85#52
c) 85#33
d) 185#52
47 STUDENT SUPPORT MATERIAL 2023-24

20. Find the impossible option from the following


>>> import random
>>> L=[i for i in range(random.randint(3,5))] a) [0,
1, 2, 3]
b) [0, 1, 2, 3, 4]
c) [0, 1, 2, 3, 4, 5]
d) [0, 1, 2]

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

22. Predict output:

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]

23. Predict output:

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

25. What will be the output of the following Python code?


def add (num1, num2):
sum = num1 + num2
sum = add(20,30)
print(sum)
26. Find and write the output of following
python code: def Alter(M,N=45):
M = M+N N = M-N
print(M,"@",) return M
A=Alter(20,30)
print(A,"#") B=Alter(30)
print(B,"#")
27. 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 FROM and TO.


a) 10#40#70#
b) 30#40#50#
c) 50#60#70#
d) 40#50#70#

28. Predict output:


49 STUDENT SUPPORT MATERIAL 2023-24

29. Predict output:

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

34. What will be the output of the following code?

35. What is the output of the following code snippet?

i. ii.

36. What will be the output of the following code?

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('Fun@Python3.0')
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 #

Write the output of the following Python code:


52 STUDENT SUPPORT MATERIAL 2023-24

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

43. Predict output :

44. What possible outputs(s) will be obtained when the following code is executed?

Options:
a) RED* b) WHITE*
WHITE* BLACK* BLACK*

c) WHITE* WHITE* BLACK* BLACK* d) YELLOW* WHITE*WHITE* BLACK* BLACK* BLACK*


53 STUDENT SUPPORT MATERIAL 2023-24

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

48. What are the possible outcome/s :

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

2 Score=[ 25,20,34,56, 72, 63]


Myscore = Score[2 + random.randint(0,2)] print(Myscore)

Output Options :
a. 25
b. 34
c. 20
d. None of the above

3 Marks = [99, 92, 94, 96, 93, 95]


MyMarks = Marks [1 + random.randint(0,2) ] print(MyMarks)

Output Options :
a. 99
b. 94
c. 96
d. None of the above

4 Disp=22 Rnd=random.randint(0,Disp)+15 N=1


for I in range(3,Rnd,4):
print(N,end=" ")
N+=1
print()
Output Options:
a) 1
b) 1 2 3 4
c) 1 2
d) 1 2 3

COMPUTER SCIENCE WITH PHYTHON Page 54


55 STUDENT SUPPORT MATERIAL 2023-24

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:

50. Predict output :

i. ii.
56 STUDENT SUPPORT MATERIAL 2023-24

iii. iv.

51. What will be the output of the following code fragments:

i. ii.

iii. iv.

52. What will be the output of the following Python Code?


57 STUDENT SUPPORT MATERIAL 2023-24

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.

c. In this we need to close the file.


d. In this mode if we are writing into a file then we have to close the file otherwise our
data will not be written into the file till now the file is not closed. The data remains in the
output buffer and when we close the file then data is shifted from the output buffer to the
file.
e. flush( ): It forces the data waiting in the buffer immediately written into the file
without waiting for closing of file.

2. with open(“file name”,”access specifier”) as file_object:


a. i.e. with open(“test.txt”,”r”) as f:
b. i.e. with open(r”C:\Users\pranab\AppData\Local\Programs\Python\Python311\test.txt ”,”r”) as f:
Or
with open(”C:\\Users\\pranab\\AppData\\Local\\Programs\\Python\\Python311\\t est.txt”,”r”) as
f:
c. In this there is no need to close the file. It will automatically close the file.

Close Files: close( ) function is used to close files in python.


a. file_object.close( )

COMPUTER SCIENCE WITH PHYTHON Page 57


58 STUDENT SUPPORT MATERIAL 2023-24

b. i.e. f.close( )

Access Specifiers in Files:

Access Access Access Description File


Mode for Mode Mode for Pointe
Text Files for CSV Files r Position
Binary
Files

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

COMPUTER SCIENCE WITH PHYTHON Page 58


59 STUDENT SUPPORT MATERIAL 2023-24

Method Prototype Description

seek( ) Syntax: seek() function is used to change the


<file_object>.seek(<offset>,<from_where>) position of the File Handle to a given
specific position. File handle is like a
where:
cursor, which defines from where the
offset: number of positions to be more forward data has to be read or written in the file.
from_where: it defines to reference point
Then it returns the new absolute position. i.e.
f.seek(10,0)
0: sets the reference point at the
Here, f is the file handle, 10 is the offset (it moves the beginning of the file. (default)
cursor 10 bytes forward), 0 means reference point at
the beginning of file. 1: sets the reference point at the current
file position.
2: sets the reference point at the end of
the file

Note: In the case of a text file we can use


only ‘0’ as a reference point.

tell( ) Syntax: <file_object>.tell( ) tell() function returns the current position


i.e. of the file object. This method takes no
parameters and returns an integer value.
position=f.tell( ) Initially the file pointer points to the
beginning of the file(if not opened in
Here, position will hold the integer value of the file
append mode). So, the initial value of
pointer returned by tell function.
tell() is zero.
f is the file handle.

Text Files:

 It stores information in the form of ASCII or Unicode characters


 Each line of text is terminated with a special character called EOL (End of
Line), which is the new line character (‘\n’) in python by default.
 File extension will be .txt

COMPUTER SCIENCE WITH PHYTHON Page 59


60 STUDENT SUPPORT MATERIAL 2023-24

Working with Text Files:

1. Reading data from a file.


2. Writing data into a file.

Reading data from files

There are three ways to read data from text file:


1. read function i.e. read( )
2. readline function i.e. readline( )
3. readlines function i.e. readlines( )

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

file_pointer.read(n): It will read the maximum n bytes/characters from the file.

f.read(7) # it will read 7 bytes/characters from the position of file pointer.

file_pointer.read( ): It will read the entire content of the file.


f.read( ) # it will read all the data of the file from the position of file pointer.

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:

COMPUTER SCIENCE WITH PHYTHON Page 60


61 STUDENT SUPPORT MATERIAL 2023-24

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

Writing data into Files

If the file doesn’t exist then it will create the file.

1. write( ): It takes string as an input and writes it into the file.


a. Syntax: file_object.write(string)
b. i.e. f.write(“Hello World”)

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

Content in “Topper.txt” file

But, we want these names in separate lines.

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.

We are planning a trip to the mountains next weekend.”


The output of the function should be: Count of is/am/are in file: 2

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.

COMPUTER SCIENCE WITH PHYTHON Page 63


64 STUDENT SUPPORT MATERIAL 2023-24

Opening a file in binary format


Syntax:
<file object>=open(<filename>,mode)
eg:fp=open(“example.dat”,”rb”)
Modes

Binary Description Notes


Modes
rb Read only File must exists, otherwise
Python raises I/O errors
wb Write only If file not exists, file is created If file exists, python
will truncate existing data and overwrite the file.
ab Append File is in write mode only, new data will be added to the end of
existing data i.e. no overwriting. If file not exists it is created
rb+ Read and File must exists otherwise error is raised Both reading and writing can
write take place
wb+ Write and File is created if not exists, if exists data will be
read truncated, both read and write allowed
ab+ Write and Same as above but previous content will be retained and both read and
read write allowed.
Binary file operations

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

COMPUTER SCIENCE WITH PHYTHON Page 64


65 STUDENT SUPPORT MATERIAL 2023-24

Writing list to the binary file


import pickle #module for binary file operations
lst=[1,2,3,4] #list to be written to the file
fp=open("data.dat","wb") # opening the binaryfile data.dat in write mode
pickle.dump(lst,fp) #writing the datastructure using dump() function
fp.close() #closing the file
Reading a list from binary file
import pickle #module for binary file operations
lst=[1,2,3,4] #list to be written to the file
fp=open("data.dat","rb") # opening the binaryfile data.dat in read mode
lst=pickle.load(fp) #reading the datastructure using load() function
print(lst) #printing the list
fp.close() #closing the file

Multiple Choice Questions from Binary files


1. Which module is required to use built in functions dump() and load()?
a.math b. flush c. pickle d. unpickle
Ans:pickle . math is the library used for mathematical functions ,flush ,unpickle are not libraries in
python
2. Which of the following function is use to write data in binary mode?
a.write b. output c. dump d. send
Ans:dump. write is used for writing to the text file and output and send are not functions used for file
operations
3. Unpickling is done by .
a. open() b. close() c. load() d. dump()
Ans:load() . open() is used for opening a file,close() is used for closing a file,dump() is used for writing to
the binary file
4. In which file opening mode if file not exists, file is created if file exists, python will truncate existing data
and overwrite the file.

a. rb b. wb c.both a and b d.None of these


Ans:wb .rb is used for opening the file for reading.If file does not exists error occurs
5.Which of the following statement will cause error if file does not exists?

a.fp=open(“data.dat”,”ab”) b. fp=open(“data.dat”,”rb”) c.both a and b d.None of These


Ans: fp=open(“data.dat”,”rb”). fp=open(“data.dat”,”ab”) will open the file in append mode if file does
not exits it will be created.

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

COMPUTER SCIENCE WITH PHYTHON Page 65


66 STUDENT SUPPORT MATERIAL 2023-24

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

COMPUTER SCIENCE WITH PHYTHON Page 66


67 STUDENT SUPPORT MATERIAL 2023-24

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:

COMPUTER SCIENCE WITH PHYTHON Page 67


68 STUDENT SUPPORT MATERIAL 2023-24

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

COMPUTER SCIENCE WITH PHYTHON Page 68


69 STUDENT SUPPORT MATERIAL 2023-24

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

COMMA SEPARATED VALUE (CSV FILE)


 CSV is a simple file format used to store tabular data, such as a spreadsheet or database.
 Files in the CSV format can be imported to and exported from programs that
store data in tables, such as Microsoft Excel or OpenOffice Calc.
 CSV stands for "comma-separated values“.
 A comma-separated values file is a delimited text file that uses a comma by default to
separate values.
 Each line of the file is a data record. Each record consists of one or more fields,
separated by commas. The use of the comma as a field separator is the source of the
name for this file format
READING FROM CSV FILE
To read data from csv files, reader() method of csv module is used.
csv.reader() returns a reader object.

STEPS TO READ

COMPUTER SCIENCE WITH PHYTHON Page 69


70 STUDENT SUPPORT MATERIAL 2023-24

1. import csv module


import csv
2. Open csv file in read mode.
f = open(“csv_demo.csv”,”r”)
3. Create the reader object.
demo_reader = csv.reader(f)
4. Fetch data through for loop, row by row.
for x in demo_reader:
print(x)
5) Close the file
f.close()
WRITING IN TO CSV FILES:
As a list To write data into csv files, writer() function of csv module is used.
csv.writer(): This function returns a writer object which writes data into csv file.
Significance of writer object
The csv.writer() returns a writer object that converts the data into a delimited string.The string can be
later converted into csv files using the writerow() or writerows() method. Syntax:
<writerobject>.writerow() : Writes one row of data in to the file .
<writerobject>.writerows() :Writes multiple rows into the file.
STEPS TO WRITE
1. import csv module
import csv
2. Open csv file in write mode.
f = open(“csv_demo.csv”,”w”,newline=””) #newline=”” given to avoid EOL translation and thus
creating a blank row
3. Create the writer object.
demo_writer = csv.writer(f)
4. Write the data to the file
demo_writer.writerow(dat) # if data is a single list representing a row
or
demowriter.writerows(dat) # if data is a nested list representing multiple rows

5) Close the file


f.close()
Multiple Choice questions from csv files
1.Which module is imported for working with CSV files in Python?
a. csv b. python-csv connector c. CSV d. python.csvconnector
Ans: a. csv
2.CSV stands for :
a.Content separated Variable b.Comma Separated Value c.Comma separated Variable d.None of These
Ans: b.Comma Separated Value
3._______is the function used for writing multiple rows to a CSV file.
a.writelines() b.writerow() c.writerows() d.None Of These
Ans: c.writerows()

COMPUTER SCIENCE WITH PHYTHON Page 70


71 STUDENT SUPPORT MATERIAL 2023-24

4._________ is the function used to write a single row to a CSV file.


a.writelines() b.writerow() c.writerows() d.None Of These
Ans: b.writerow()
5.Which of the following option can be used to fill the blank space
________.writer(fp)
a.writeObj b.writerows() c.csv d.None Of These
Ans: c.csv
6.To open a file c:\data.csv for reading we use _____python statement
a.fp=open(“c:\data.csv”,”r”) b. fp=open(“c:\\data.csv”,”r”) c.Both a and b d.None Of These
Ans: b. fp=open(“c:\\data.csv”,”r”)
7.CSV files are binary files state True or False
a.True b.False Ans: b.False
8.The default delimiter character of CSV file is ___________
a. : (Colon) b.\t (tab) c. ,(comma) d.None of These
Ans: c. ,(comma)
9.To cancel the EOL translation in csv file while writing the data ____argument is used with open()
a.newline b.next c.open d.EOL
Ans: a.newline
10.To read entire content from the csv file we use _____python statement.
a.fp.read() b.fp.reader() c.csv.reader(fp) d.csv.readlines()
Ans: c. csv.reader(fp)

FOUR MARKS QUESTIONS FROM CSV FILES


1.Sushant is a Python programmer working in a software company. As part of a project , he has created a
csv file named Accounts.csv, to store the account details of bank customers . The structure of
Accounts.csv is : [Acno, cus_name, Address, Actype] Where Acno is account number (integer) cus_name is
Customer Name (string) Address is address of the customer(string) Actype is account type whose values
can be 'Savings', 'Current' or 'FD'(string) .For efficiently maintaining data of the customers, Subhash wants
to write the following user defined functions:
GetCustomer() – to accept a record from the user and add it to the file Accounts.csv. The column
headings should also be added on top of the csv file.
countFD() – to count the number of customers who have FD account. As a Python expert, help him
complete the task.
Ans:
import csv

COMPUTER SCIENCE WITH PHYTHON Page 71


72 STUDENT SUPPORT MATERIAL 2023-24

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

COMPUTER SCIENCE WITH PHYTHON Page 72


73 STUDENT SUPPORT MATERIAL 2023-24

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)

COMPUTER SCIENCE WITH PHYTHON Page 73


74 STUDENT SUPPORT MATERIAL 2023-24

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

def getTopper ():

COMPUTER SCIENCE WITH PHYTHON Page 74


75 STUDENT SUPPORT MATERIAL 2023-24

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:

COMPUTER SCIENCE WITH PHYTHON Page 75


76 STUDENT SUPPORT MATERIAL 2023-24

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

COMPUTER SCIENCE WITH PHYTHON Page 76


77 STUDENT SUPPORT MATERIAL 2023-24

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

THREE MARKS QUESTIONS ON STACK.


1.A list, city contains following record as list elements:
[City, Country, distance from Mumbai]
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 tour.
i. Push_element(city): It takes the nested list as an argument and pushes a list object containing name of the
city and country, which are in India and distance is less than 3000 km from Mumbai.

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

for cty in city:

if(cty[1]=="India" and cty[2]<3000):

tour.append([cty[0],cty[1]])

def pop_element():

while(len(tour)!=0):

print(tour.pop())

print("Stack Empty")

2. A list employee contains following record as list elements:


[Empid,empname,salary]

COMPUTER SCIENCE WITH PHYTHON Page 77


78 STUDENT SUPPORT MATERIAL 2023-24

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

for emp in employee:

if(emp[2]>10000):

office.append([emp[1],emp[2]])

def pop_element():

while(len(office)!=0):

print(office.pop())

print("Stack Empty")

3. A list product contains following record as list elements:


[pid,pname,price]
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 store.
Push_product(product): It takes the nested list as an argument and pushes a list object containing name of the
product and price, whose price is greater than 2500

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

for pdct in product:

if(pdct[2]>2500):

store.append([pdct[1],pdct[2]])

def empty_stack():

while(len(store)!=0):

print(store.pop())

print("Stack Empty")

COMPUTER SCIENCE WITH PHYTHON Page 78


79 STUDENT SUPPORT MATERIAL 2023-24

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)

print(“No of elements pushed to the stack is”,len(stack))

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)

print(“No of elements pushed to the stack is”,len(stack))

COMPUTER SCIENCE WITH PHYTHON Page 79


80 STUDENT SUPPORT MATERIAL 2023-24

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

COMPUTER SCIENCE WITH PHYTHON Page 80


81 STUDENT SUPPORT MATERIAL 2023-24

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.

COMPUTER SCIENCE WITH PHYTHON Page 81


82 STUDENT SUPPORT MATERIAL 2023-24

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

COMPUTER SCIENCE WITH PHYTHON Page 82


83 STUDENT SUPPORT MATERIAL 2023-24

media. Transmission media is grouped into two types


Guided Media or Wired Technologies
In guided media or wired technologies, the computers in a network are connected through wire or cable. The data
signal physically gets transferred from the transmitting computer to the receiving computer through the wired
transmission medium. Some of guided media are given below
1. Ethernet Cable or Twisted Pair Cable
In this cable, wires are twisted together, which are surrounded by an insulating material and an outer layer called
jacket. One of the wire is used to carry signals to the receiver and the other is used only as a ground reference.
e.g. Local Area Networks (LAN’s) are used twisted pair cable. There are two types of twisted pair cables
(i) Shielded Twisted Pair (STP) Cable It has shielding of the individual pair of wires, which protects it from external
interference and crosstalk.
(ii) Unshielded Twisted Pair (UTP) Cable It has two unshielded wires twisted around each other. UTP cables are
found in many LAN networks and telephone systems.
Advantages of Twisted Pair Cable
Simple structure, Physically flexible, Easy to install, Low weight, Very inexpensive.
Disadvantages of Twisted Pair Cable
Due to high attenuation, signals cannot be transport over a long distance without using repeaters.
Due to low bandwidth, it is unsuitable for broadband application.
Data rates supported are 1 Mbps to 10 Mbps.
2. Co-axial Cable
It consists of a solid wire core surrounded by foil shields or conducting braid or wire mesh, each separated by some
kind of plastic insulator. The inner solid wire core carries the signal through the network and the shield is used to
provide earthing or ground. Co-axial cable is commonly used in transporting multi-channel television signals in
cities. The two most commonly used types of co-axial cable are:
(i) Thicknet This form of co-axial cable is thick. The length of thicknet co-axial cable segments can be upto 500
metre long.
(ii) Thinnet This form of co-axial cable is thinner and using this cable, nodes having maximum distance of 185 metre
can be joined.
Advantages of Co-axial Cable
1. Transmission quality of co-axial cable is better than twisted pair cable.
2. It can be successfully used for shared cable network.
3. It can transmit several channels simultaneously, so that used for broadband transmission. It offers high
bandwidth

Disadvantages of Co-axial Cable


1. It is expensive compared to twisted pair cable.
2.These are difficult to manage and reconfigure as compared to twisted pair cable

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.

COMPUTER SCIENCE WITH PHYTHON Page 83


84 STUDENT SUPPORT MATERIAL 2023-24

(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

COMPUTER SCIENCE WITH PHYTHON Page 84


85 STUDENT SUPPORT MATERIAL 2023-24


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

COMPUTER SCIENCE WITH PHYTHON Page 85


86 STUDENT SUPPORT MATERIAL 2023-24

retransmitted. This makes it a very expensive mode of communication


ii. Installation and maintenance of microwave links is very expensive.
iii. The transmission is affected by weather conditions like rain, thunderstorms etc.
5. Satellite Communication
Satellites are an essential part of telecommunications systems worldwide. They can carry a large amount of data
in addition to TV signals. When the data is transmitted using satellite then it is said to be satellite communication.
Satellite communication is a special use of microwave transmission system. A satellite is placed precisely at
36000km above the equator where its orbit speed exactly matches the earth’s rotation speed. Hence it always
stays over the same point with respect to the earth. This allows the ground station to aim its antenna at a fixed
point in the sky.
Satellites are especially used for remote locations, which are difficult to reach with wired infrastructure. Also
communication and data transfer on Internet, is only possible through satellites
Advantages of Satellite Communication
i. It covers a vast range of area.
ii. The wired communication is almost impossible and too costly to use across the continents, where the satellite
communication proves to be the best alternative.
iii. It is very useful in long distance television distribution.
iv. Earth station, which receives the signals can be fixed position or relatively mobile.
Disadvantages of Satellite Communication.
i. It is very costly. So, it is not used for personal or low budget communication.
ii. There is atmospheric loss of transmitted signals.
iii. Due to low antenna signals, bandwidth is overcrowded.
Types of Network
Networks can be widely divided into following types
Local Area Network (LAN)
In a LAN, a group of computers and other devices are connected over a relatively short distance. Generally, it is a
privately owned networks within a single building or campus, upto a few kilometres in size. Users can share
expensive devices, such as laser printers, as well as data on LAN and can also use the LAN to communicate with
each other, by sending mails or engaging in chat sessions. Mostly, cables are used to connect the computers in
LANs. However, there is also a limit on the number of computers that can be attached to a single LAN. Now-a-days,
we also have WLAN(Wireless LAN) which is based on wireless network.
Metropolitan Area Network (MAN)
This is basically a bigger version of LAN and normally uses similar technology. It might cover few buildings in a city
and might either be private or public. This is a network which spans a physical area (in the range of 5 to 50 km)
that is larger than a LAN but smaller than a WAN. MANs are usually characterised by very high-speed connections
using optical fibres or other digital media and provides uplink services to Wide Area Networks (WANs) and the
Internet. e.g. in a city, a MAN, which can support both data and voice might even be related to local cable television
network. It is also frequently used to provide a shared connection to other networks using a link to a WAN.
Wide Area Network (WAN)
WAN spans a large geographical area, often a country or a continent and uses various commercial and private
communication lines to connect computers. Typically, a WAN combines multiple LANs that are geographically
separated.
Like the LAN, most WANs are not owned by any one organization, but rather exist under collective or distributed
ownership and management. The world’s most popular WAN is the Internet
Personal Area Network (PAN)
PAN refers to a small network of communication. It is a computer network organised around an individual person.

COMPUTER SCIENCE WITH PHYTHON Page 86


87 STUDENT SUPPORT MATERIAL 2023-24

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.

COMPUTER SCIENCE WITH PHYTHON Page 87


88 STUDENT SUPPORT MATERIAL 2023-24

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

COMPUTER SCIENCE WITH PHYTHON Page 88


89 STUDENT SUPPORT MATERIAL 2023-24

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.

Disadvantages of Star Topology


i.Requires more cable length than bus topology
ii. If hub or server fails, the entire network will be disabled.
iii.Difficult to expand, as the new node has to connect all the way to central node.
Tree Topology
A tree topology is an extension and variation of bus topology. Its basic structure is like an inverted tree, where the
root act as a server. In tree topology, the nodes are interlinked in the form of tree. If one node fails, then the node
following that node gets detached from the main tree topology.
Advantages of Tree Topology
i.The tree topology simulates hierarchical flow of data. So, it is suitable for applications, where hierarchical flow of
data and control is required.
ii. We can easily extend the network.
iii. Faulty nodes can easily be isolated from the rest of the network.
Disadvantages of Tree Topology
i. Long cables are required.
ii. There are dependencies on the root node.

COMPUTER SCIENCE WITH PHYTHON Page 89


90 STUDENT SUPPORT MATERIAL 2023-24

iii. Installation and reconfiguration is very difficult.


Mesh Topology
It is also known as completely interconnected topology. In mesh topology, every node has a dedicated point-to-
point
link to every other node. This topology is also more secure as compared to other topologies because each cable
between
two nodes carries different data.
Advantages of Mesh Topology
i. Excellent for long distance networking.
ii. Communication possible through the alternate e-route, if one path is busy.
¢ A network can handle large amount of traffic since multiple nodes can transmit data simultaneously.
Disadvantage of Mesh Topology
i. Long wire/cable length is required.
ii. Wiring is complex and cabling cost is high in creating such networks.
Network Protocols
Protocol refers to the set of rules applicable for a network. The protocol defines standardised format for the data
packet
to be transmitted through the network. Some of the commonly used protocols are as follows
HTTP (HyperText Transfer Protocol)
HTTP is an application layer protocol. It is widely used protocol. This protocol is used by the world wide web. HTTP
defines how messages are formatted and transmitted and what actions web servers and browsers should take in
response to various commands. It is a request/response standard between a client (end-user) and a server
(website). e.g. when you enter a URL in your browser, this actually sends an HTTP command to the web server
directly to fetch and transmit the requested web page. It is generic, stateless and object oriented protocol.
TCP/IP (Transmission Control Protocol/Internet Protocol)
TCP/IP is the communication protocol for the Internet. It defines the rules, computers must follow to communicate
with
each other over the Internet. The TCP/IP is a protocol used in E-mail transmission. The TCP/IP is a protocol, which is
responsible for finding path for the destination. It also splits the message into several datagrams, if it does not fit in
one datagram. Therefore, these datagram’s are sent through different alternate paths towards the destination. The
TCP makes sure that the datagram arrives at the destination correctly. While IP is responsible for moving packet of
data from source to destination. It handles the address part of each packet so that it reaches to the right
destination.
PPP (Point-to-Point Protocol)
It is a data link layer protocol, which encapsulates other network layer protocols for transmission on synchronous
and
asynchronous communication lines. The PPP is used with dial-up Internet connections including ISDN. It is a layered
protocol, which is used for transmitting the IP data packets over usual telephone lines. It encapsulates packets into
PPP frames and then forwards them to the server over the serial transmission lines. PPP defines the format of
frame to be exchanged between devices on one or multiple links and also defines the authenticity of the two
devices.
FTP (File Transfer Protocol)
It is a standard network protocol used to transfer files from one host to another host over a TCP-based network,
such as the Internet . FTP is based on client/server principle. It establishes two connections between the hosts. One
connection is used for data transfer, which is opened and closed for each file transfer and the other for control
information, which remains connected during the entire interactive FTP session.

COMPUTER SCIENCE WITH PHYTHON Page 90


91 STUDENT SUPPORT MATERIAL 2023-24

Remote Login (Telnet)


Telnet is a protocol used for creating a connection with a remote computer. Once your telnet client establishes a
connection to the remote host, telnet client becomes a virtual terminal, allowing you to communicate with the
remote host from your computer. It establishes a connection either with command line client or with a
programmatic interface. Telnet provides an error free connection, which is always faster than the latest
conventional modems.
Post Office Protocol (POP)
POP is an application-layer Internet standard protocol, used b local E-mail clients to retrieve E-mail from a remote
server over a TCP/IP connection.
POP3 (Post Office Protocol version 3) is the most recent version of a standard protocol for receiving E-mail. POP3 is
a client/server protocol in which E-mail is received and held for you by your Internet server. Each POP3 mail server
has a different address, which is usually provided to an individual by their web hosting company. This address must
be entered into the E-mail program so that the program can connect effectively with the protocol.
Simple Mail Transfer Protocol (SMTP)
SMTP is the protocol used for sending E-mail over the Internet. Your E-mail client uses SMTP to send a message to
the mail server and the mail server uses SMTP to relay that message to the correct receiving mail server. Basically,
SMTP is a set of commands that authenticate and direct the transfer of electronic mail. When configuring the
settings for your E-mail program, you usually need to set the SMTP server to your local Internet Service Provider’s
SMTP settings.
Voice over Internet Protocol (VoIP)
VoIP is a technology that enables voice communications over the Internet through the compression of voice into
data packets that can be efficiently transmitted over data networks and then converted back into voice at the
other end. It required broadband connection.
Various benefits of VoIP are as follows
(i) Using services of VoIP, subscribers can call one another at no cost to other party.
(ii) Routing phone calls over existing data networks eliminate the need for separate voice and data networks.
(iii) The ability to transmit more than one telephone call over a single broadband connection.
(iv) VoIP consists advance telephone features, e.g. call routing, screen POP and IVR.
Web Services
Web services are built on many technologies, which work in conjunction with emerging standards to ensure the
manageability and standards, which extend the World Wide Web infrastructure to provide the means for software
to connect to other software applications. Applications access web services via web protocols and data formats
such as HTTP, XML and SOAP, with no need to worry about how each web service is implemented. Web services
combine the best aspects of component based development.
Some of the web services are as follow
World Wide Web (WWW)
The World Wide Web (WWW) is an Internet service, which allows a particularly configured server computer to
distribute
documents across the Internet in a standard way. This web standard allows programs on many different computer
platforms to properly format and display the information server. These programs are called web browsers. The
WWW is a collection of millions of files stored on thousands of computers all over the world. The flow of
information is controlled by a protocol. The protocol used in this exchange is called HyperText Transfer Protocol
(HTTP).
HyperText Markup Language (HTML)
HyperText Markup Language (HTML) is the main markup language for creating web pages and other
information that can be displayed in a web browser . HTML is written in the form of HTML elements consisting of

COMPUTER SCIENCE WITH PHYTHON Page 91


92 STUDENT SUPPORT MATERIAL 2023-24

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

COMPUTER SCIENCE WITH PHYTHON Page 92


93 STUDENT SUPPORT MATERIAL 2023-24

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

COMPUTER SCIENCE WITH PHYTHON Page 93


94 STUDENT SUPPORT MATERIAL 2023-24

FULL FORMS OF THE FOLLOWING NETWORKING TERMS:

1. SSL– Secure Sockets Layer

2. IMAP– Internet Message Access Protocol

3. FTP– File transfer protocol-

4. WiFi– Wireless Fidelity

5. HTTPs– Hyper Text Transfer Protocol Secure

6. WAP– Wireless Application Protocol

7. VoIP– Voice Over Internet Protocol

8. SMTP– Simple Mail Transfer Protocol

9. TDMA– Time Division Multiple Access

10. CDMA– Code Division Multiple Access

11. TCP/IP– Transmission Control Protocol/Internet Protocol

12. LAN– Local Area Network

13. WAN– Wide Area Network

14. MAN– Metropolitan Area Network

15. PAN– Personal Area Network

16. IR– Infrared

17. IRC– Internet Relay Chat

18. GPRS– General Packet Radio Service

19. GSM– Global System for Mobile Communications

20. e-mail– Electronic Mail

21. ASP– Active Server Pages

22. JSP– Java Server/Script Pages

23. XML– eXtensible Markup Language

24. HTML– Hyper Text Markup Language

25. Bps– Bytes per Second

26. bps– bits per second

27. ARPAnet– Advanced Research Project Agency Network

COMPUTER SCIENCE WITH PHYTHON Page 94


95 STUDENT SUPPORT MATERIAL 2023-24

28. POP– Post office Protocol

29. nfc– Near field Communication

30. sms-short message service

Objective Type Questions

1. The ____________ project has been started in 1960s to provide interconnection between academic and
research institutions for research purpose.

2. Which of the following started a project of ARPANET?

1. University of California

2. Stanford Research Institute

3. U.S. Department Of Defence

4. U.S. Department of Communications

3. The _____________ is a commercial name of ARPANET.

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.

6. Each computer in the network is known as _________________.

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

COMPUTER SCIENCE WITH PHYTHON Page 95


96 STUDENT SUPPORT MATERIAL 2023-24

12. The ____________ is a network of Networks.

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

15. 10 Gbps is equal to

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.

19. A ___________________ is similar service like a networking message.

20. The TCP/IP protocol was used with TelNet. (True/False)

Answers:

1. ARPANET

2. 3 US Department of Defense

3. TELNET

4. True

5. WWW

COMPUTER SCIENCE WITH PHYTHON Page 96


97 STUDENT SUPPORT MATERIAL 2023-24

6. node or workstation or client

7. server

8. Network Interface Card/Unit or NIC/NIU

9. 1 Communication Channel

10. bandwidth

11. 3 mbps

12. internet

13. 3 circuit switching

14. 2 packet switching

15. 2 1240 mbps

16. 3 message switching

17. False

18. Domain Name System

19. E-mail

20. True

COMPUTER SCIENCE WITH PHYTHON Page 97


98 STUDENT SUPPORT MATERIAL 2023-24

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. Indian School, in Mumbai is starting up the network between


between its different wings. There are four Buildings named
as SENIOR, JUNIOR, ADMIN and HOSTEL as shown below:

The distance between various buildings is as follows:

Number of Computers in Each Building :

1. Suggest the cable layout of connections betwee


between the buildings.

2. Suggest the most suitable place (i.e., building) to house the server of this school, provide a suitable reason.

3. Suggest the placement of the following devices with justification.

o Repeater

o Hub/Switch

4. The organisation also has inquiry office in another city about 50-60
60 km away in hilly region. Suggest the
suitable transmission media to interconnect to school and inquiry office out of the following :

o Fiber optic cable

o Microwave

o Radiowave

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.

3. Repeater can be placed between ADMIN


and SENIOR building as the distance is more than 110 m.

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.

2. Suggest where all should Hub(s)/Switch (es) be placed in the network.

3. Which communication medium would you suggest to connect this school with its main branch in Delhi?

Answer:

1. Server should be in Wing S as it has the maxi-mum number of computers. 1

2. All Wings need hub/switch as it has more than


one computer.

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

No village is more than 20 km away from the state capital.


(a)Imagine yourself ass a computer consultant for this project and answer the following questions with justification:

1. Out of the following what kind of link should be provided to setup this network: Microwave link, Radio Link,
Wired Link ?

2. What kind of network will be formed; LLAN, MAN, or WAN ?

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 to Block distance (in Meters):


Block From Block Distance
Human Resource Conference 60
Human Resource Finance 60
Conference Finance

Expected Number of Computer installed in each building block:


102 STUDENT SUPPORT MATERIAL 2023-24

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.

COMPUTER SCIENCE WITH PHYTHON Page 102


103 STUDENT SUPPORT MATERIAL 2023-24

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:

 A relational model provides structural independence by using independent tables.


 Changes made in the table structure do not affect the data access or other application programs.
 Built-in query support based on SQL is provided by RDBMS

Limitation

 RDBMS incurs hardware and system software overheads.


 The size of database becomes very large.

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.

COMPUTER SCIENCE WITH PHYTHON Page 103


104 STUDENT SUPPORT MATERIAL 2023-24

 Cardinality of Relation: It is the number of records or tuples in the relation.


 Degree of Relation: Number of columns or attributes is known as degree of a relation.
 Domain of Relation: It defines the kind of data represented by the attribute. It is the set of all
possible values that an attribute may contain. For example, in the given table Student, domain for
the field Gender is two since it can have either ‘M’ or ‘F’ as the possible and available values that it
may contain.
 Body of the Relation: It consists of an unordered set of 0 or more tuples

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.

The types of SQL joins are as follows:

 Cartesian Product (Cross Product)


 Equi Join
 Natural Join

Cartesian Product (Cross Product):


The Cartesian product is a binary operation and is denoted by (X). The degree of the new relation formed
is the sum of the degrees of two relations on which Cartesian product is performed. The number of tuples
in the new relation is equal to the product of the number of tuples of the two tables on which Cartesian
product is performed.

SELECT Name, gname FROM student, games;


Equi Join:
An Equi join is a simple SQL join condition that uses the equal to sign (=) as a comparison operator for
defining a relationship between two tables on the basis of a common field

Syntax for Equi Join:


SELECT column1, column2,.... FROM table1, table2 WHERE <table1.column1> = <table2.column2>;
Natural Join:
The SQL NATURAL JOIN is a type of EQUI JOIN and is structured in such a way that, columns with the same
name of associated tables will appear once only.

Natural Join: Guidelines:


The associated tables have one or more pairs of identically named columns.
The columns must be the same data type.
Don’t use ON clause in a natural join.

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

Ans a. ALTER TABLE STUDENTS DROP PHONE;


iii. Choose the command to display Name of the students who are studying in class 12 and their 1
corresponding Coach names
a. SELECT NAME, COACHNAME FROM STUDENTS, SPORTS WHERE CLASS LIKE “12%” AND
STUDENTS.ADMNO =SPORTS.ADMNO;
b. SELECT NAME, COACHNAME FROM STUDENTS, SPORTS WHERE CLASS LIKE “12%” AND
STUDENTS.ADMNO= SPORTS.ADMNO;
c. SELECT NAME, COACHNAME FROM STUDENTS, SPORTS WHERE CLASS LIKE “12%” AND
ADMNO.STUDENTS =ADMNO.SPORTS;
d. SELECT NAME, COACHNAME FROM STUDENTS, SPORTS WHERE CLASS LIKE= “12%” AND
STUDENTS.ADMNO =SPORTS.ADMNO;
Ans a. SELECT NAME, COACHNAME FROM STUDENTS,SPORTS WHERE CLASS LIKE “12%” AND
STUDENTS.ADMNO=SPORTS.ADMNO ;
iv which two select queries will give the same output 1
A. SELECT NAME, GRADE FROM STUDENTS,SPORTS WHERE ADDRESS IS NULL AND
STUDENTS.ADMNO =SPORTS.ADMNO ;
B. SELECT NAME, GRADE FROM STUDENTS,SPORTS WHERE ADDRESS IS NOT NULL AND
STUDENTS.ADMNO =SPORTS.ADMNO ;
C SELECT NAME, GRADE FROM STUDENTS,SPORTS WHERE ADDRESS IS NULL OR
STUDENTS.ADMNO=SPORTS.ADMNO ;
D. SELECT ST.NAME, SP.GRADE FROM STUDENTS ST,SPORTS SP WHERE ADDRESS IS NULL AND
ST.ADMNO=SP.ADMNO ;
a. A AND B
b. B AND C
c. A AND D
d. C AND D
Ans c. A AND D
v. Choose the command to count the number of students who play volleyball 1
a. SELECT COUNT(*) FROM STUDENTS,SPORTS WHERE GAME=”VOLLEYBALL” AND
STUDENTS.ADMNO=SPORTS.ADMNO ;
b. SELECT COUNT(GAME) FROM STUDENTS,SPORTS WHERE GAME=”VOLLEYBALL” AND
STUDENTS.ADMNO=SPORTS.ADMNO ;
c. SELECT COUNT(*) FROM STUDENTS,SPORTS WHERE GAME=”VOLLEYBALL” ;
d. SELECT COUNT(*) FROM STUDENTS,SPORTS WHERE SPORTS=”VOLLEYBALL” AND
STUDENTS.ADMNO=SPORTS.ADMNO
Ans a. SELECT COUNT(*) FROM STUDENTS,SPORTS WHERE GAME=”VOLLEYBALL” AND
STUDENTS.ADMNO=SPORTS.ADMNO ;
4 A table contains 5 rows and 7 columns. What will be its cardinality and degree? 1
a) Degree 7,cardinality 5
b) Degree 5,cardinality 7
c) Degree 5,cardinality 7
d) cardinality 7, Degree 7
Ans (a)
5 What is not a MySQL function? 1
a) mult()
b) min()
c) count()
d) sum()
Ans. (a)
6 Which clause is used to group the column(s) with aggregate function? 1
a) order by
b) like

COMPUTER SCIENCE WITH PHYTHON Page 107


108 STUDENT SUPPORT MATERIAL 2023-24

c) where
d) group by
Ans (b)

FILL IN THE BLANKS:


Sl Question Marks
No
1 An attribute in a relation is foreign key if it is the _________key in any other relation. 1
Ans Primary
2 INSERT INTO employee______(1002, “Ted”, 2000,”1889-12-29”); 1
Ans Values
3 SELECT name FROM class WHERE subject_____NULL; 1
Which comparison operator may be used to fill the blank space in above query?
Ans Is/is not
4 Out of one or more candidate keys, the attribute chosen by the database designer to uniquely 1
identify the tuples in a relation is called__________________
Ans Primary key
5 __________means same data are duplicated in different places. 1
Ans Redundancy
6 ________occurs when same data maintained in different places do not match 1
Ans Data Inconsistency

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

2 Explain the use of ‘Primary Key’ in a Relational Database Management System. 2


Ans Primary key is to uniquely identify tuples or Rows in a relational table. Primary has two property ,
that is unique and not null.
3 What is called DDL commands in mySQL?Give examples? 2

Ans DDL-DATA DEFENITION LANGUAGE


EXAMPLE:CREATE ,DROP,ALTER

COMPUTER SCIENCE WITH PHYTHON Page 108


109 STUDENT SUPPORT MATERIAL 2023-24

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]

CID CNAME AGE GENDER SPORTS PAY DOAPP


5246 AMRITA 35 FEMALE CHESS 900 2006-03-27
4687 SHYAM 37 MALE CRICKET 1300 2004-04-15
1245 MEENA 23 FEMALE VOLLEYBALL 1000 2007-06-18
1622 AMRIT 28 MALE KARATE 1000 2007-09-05
1256 AMINA 36 FEMALE CHESS 1100 2003-08-15
1720 MANJU 33 FEMALE KARATE 1250 2004-04-10
2321 VIRAT 35 MALE CRICKET 1050 2005-04-30

c. SELECT COUNT(DISTINCT SPORTS) FROM CLUB;


d. SELECT CNAME, SPORTS FROM CLUB WHERE DOAPP<"2006-04-30" AND CNAME LIKE
"%NA";
e. SELECT CNAME, AGE, PAY FROM CLUB WHERE GENDER = "MALE" AND PAY BETWEEN
1000 AND 1200;
Ans

a)
COUNT(DISTINCT SPORTS)
4
b)
CNAME SPORTS
AMINA CHESS

c)

CNAME AGE PAY


AMRIT 28 1000
VIRAT 35 1050
2 Consider the table Personal given below: 1*3= 3
Table: Personal
P_ID Name Desig Salary Allowance
P01 Rohit Manager 89000 4800
P02 Kashish Clerk NULL 1600
P03 Mahesh Superviser 48000 NULL
P04 Salil Clerk 31000 1900
P05 Ravina Superviser NULL 2100

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

COMPUTER SCIENCE WITH PHYTHON Page 109


110 STUDENT SUPPORT MATERIAL 2023-24

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

3 Consider the following tables -Product and Supplier:


Table:Product
Pid pname sid
P1 pen S1
P2 ball S2
P3 pencil S3
Table:Supplier
Sid sname
S1 Anmol
S2 Aradhya
S3 Sunil
S4 Vishal

What will be the output of the following statement?


SELECT * FROM product NATURAL JOIN SUPPLIER;
ANS:
Pid pname sid Sname
P1 Pen S1 Anmol
P2 Ball S2 Aradhya
P3 Pencil S3 Sunil

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

(i)SELECT DISTINCT deptid from Employee;


(ii)SELECT deptid,count(*),min(salary) from employee GROUP BY deptid HAVING
count(deptid)>2;
(iii)SELECT empname FROM employee WHERE salary>14000 ORDER BY empname;
(iv)SELECT SUM(SALARY) FROM Employee WHERE SALARY BETWEEN 15000 AND 18000;

Ans
(i)

Deptid
D1
D2
D3

COMPUTER SCIENCE WITH PHYTHON Page 110


111 STUDENT SUPPORT MATERIAL 2023-24

(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

SELECT Author_id, avg(price) FROM BOOK GROUP BY Author_id;


SELECT MAX(price),MIN(price) FROM BOOK;
SELECT Book_name,Author_name,country FROM BOOK B, AUTHOR A WHERE B.
Author_id = A. Author_id AND price>300;
iv) SELECT Author_name FROM AUTHOR WHERE Author_name LIKE “A%”;

Ans
(i)
Author_id Avg(price)
204 420.5
202 462
203 248
(ii)

COMPUTER SCIENCE WITH PHYTHON Page 111


112 STUDENT SUPPORT MATERIAL 2023-24

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

PCode PName UPrice Rating BID


P01 Shampoo 120 6 M03
P02 Toothpaste 54 8 M02
P03 Soap 25 7 M03
P04 Toothpaste 65 4 M04
P05 Soap 38 5 M05
P06 Shampoo 245 6 M05

Table: BRAND

BID BName
M02 Dant Kanti
M03 Medimix
M04 Pepsodent
M05 Dove

Write SQL queries for the following:


i. Display product name and brand name from the tables PRODUCT and BRAND.
ii. Display the structure of the table PRODUCT.
iii. Display the average rating of Medimix and Dove brands
iv. Display the name, price, and rating of products in descending order of rating.
v. Display all the product names whose price is more than 60 and rating is more than
5

Ans a. SELECT PName, BName FROM PRODUCT P, BRAND B WHERE P.BID=B.BID;


b. DESC PRODUCT;
c. SELECT BName, AVG(Rating) FROM PRODUCT P, BRAND B WHERE P.BID=B.BID GROUP BY
BName HAVING BName='Medimix' OR BName='Dove';
d. SELECT PName, UPrice, Rating FROM PRODUCT ORDER BY Rating DESC;
e. SELECT PName form PRODUCT where UPrice>60 and Rating>5;

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

COMPUTER SCIENCE WITH PHYTHON Page 113


114 STUDENT SUPPORT MATERIAL 2023-24

1.To display Recipient details in ascending order of RecName


2.To display number of Patient from each city
3.SELECT A.DoctorName, B.RecName From Doctor A, Recipient B Where A.DoctorID = B.DoctorID
AND B.RecCity =’Mumbai’;
4.SELECT RecName, RecAddress From Recipient Where RecCity NOT IN (‘Mumbai’, ‘Kolkata’) ;
5.SELECT RecID, RecName FROM Recipent Where DoctorID=’MU02’ or DoctorID=’ND50’

Ans 1.SELECT * from Recipent ORDER ByRecName;


2.SELECT COUNT (*) from Recipient Group ByRecCity;
3.A.DoctorName B.RecName
R Jain H Singh S Jha P K Swamy
4. RecName RecAddress
S Mahajan 116, A Vihar
S Tripathi 13, BID, MayurVihar
5. RecID RecName
ND08 S Mahajan
ND48 STripath

You might also like