0% found this document useful (0 votes)
43 views92 pages

Class Xi Cs Term II-final

Uploaded by

adh1thya.d3vts
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views92 pages

Class Xi Cs Term II-final

Uploaded by

adh1thya.d3vts
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 92

Kendriya Vidyalaya Sangathan

Ernakulam Region

Student Support Material


2021-22

TERM -II
Computer Science

CLASS XI
CHIEF PATRON

Mr R Senthil Kumar
Deputy Commissioner
KVSRO Ernakulam

PATRONS

Mrs. Deepti Nair Mr. Santhosh Kumar N


Asst. Commissioner, KVSRO Ernakulam Assistant Commissioner, KVSRO Ernakulam

CO-ORDINATOR

Mr.Jyothi Mohan N V
Principal
Kendriya Vidyalaya S A P, Peroorkada

PREPARED BY

 Mr.Jimmy John,PGT CS KV OTTAPALAM


 Mrs.Aswathi V, PGT CS,KV THRISSUR
 Mrs. Hema C N PGT CS, KV No.1,KOCHI
 Mrs.Anju Mathew, PGT CS, KV RB KOTTAYAM
 Mrs.Hema R, PGT CS, KV ADOOR SHIFT II
 Mrs.Sindhu S, PGT CS , KV KOLLAM
 Mrs.Sheena B R,PGT CS , KV CRPF PALLIPURAM
TABLE OF CONTENTS

1 LIST PAGE:1

TUPLES & PAGE:13


2
DICTIONARY

PYTHON
3 PAGE:37
MODULES

SOCIETY LAWS
4 & ETHICS
PAGE:48
Computer Science
CLASS - XI
Code No. 083
2021-22
1. Learning Outcomes

Student should be able to


a)develop basic computational thinking
b)explain and use data types
c)appreciate the notion of algorithm
d)develop a basic understanding of computer systems - architecture, operating system and cloud
computing
e) explain cyber ethics, cyber safety and cybercrime
f) Understand the value of technology in societies along with consideration of gender and disability
issues

2. Distribution of Marks
Unit Unit Name Marks Periods
No.
Theory Practical
I Computer Systems and Organisation 10 10 5
II Computational Thinking and Programming - 1 45 50 35
III Society, Law and Ethics 15 20 ----
Total 70 80 40

Term-1 Term-2
Marks Marks
Computer Systems 10 ---
I
and Organisation
Computational
II Thinking and 25 20
Programming - 1
Society, Law and --- 15
III
Ethics
35 35
3. Unit wise Syllabus
TERM 1:

Unit I: Computer Systems and Organisation


● Basic Computer Organisation: Introduction to computer system, hardware, software, input device,
output device, CPU, memory (primary, cache and secondary), units of memory (Bit, Byte, KB, MB,
GB, TB, PB)
● Types of software: system software (operating systems, system utilities, device drivers),
programming tools and language translators (assembler, compiler & interpreter), application
software
● Operating system (OS): functions of operating system, OS user interface
● Boolean logic: NOT, AND, OR, NAND, NOR, XOR, truth table, De Morgan’s laws and logic circuits
● Number system: Binary, Octal, Decimal and Hexadecimal number system; conversion between
number systems.
● Encoding schemes: ASCII, ISCII and UNICODE (UTF8, UTF32)

Unit II: Computational Thinking and Programming – 1

● Introduction to problem solving: Steps for problem solving (analysing the problem, developing an
algorithm, coding, testing and debugging). representation of algorithms using flow chart and
pseudo code, decomposition
● Familiarization with the basics of Python programming: Introduction to Python, features ofPython,
executing a simple "hello world" program, execution modes: interactive mode and script mode,
Python character set, Python tokens (keyword, identifier, literal, operator, punctuator), variables,
concept of l-value and r-value, use of comments
● Knowledge of data types: number (integer, floating point, complex), boolean, sequence (string,
list, tuple), none, mapping (dictionary), mutable and immutable data types
● Operators: arithmetic operators, relational operators, logical operators, assignment operator,
augmented assignment operators, identity operators (is, is not), membership operators (in, not in)
● Expressions, statement, type conversion & input/output: precedence of operators, expression,
evaluation of expression, python statement, type conversion (explicit & implicit conversion),
accepting data as input from the console and displaying output
● Errors: syntax errors, logical errors, runtime errors
● Flow of control: introduction, use of indentation, sequential flow, conditional and iterative flow
control
● Conditional statements: if, if-else, if-elif-else, flowcharts, simple programs: e.g.: absolute value,
sort 3 numbers and divisibility of a number
● Iterative statements: for loop, range function, while loop, flowcharts, break and continue
statements, nested loops, suggested programs: generating pattern, summation of series, finding
the factorial of a positive number etc
● Strings: introduction, indexing, string operations (concatenation, repetition, membership &
slicing), traversing a string using loops, built-in functions: len(), capitalize(), title(), lower(), upper(),
count(), find(), index(), endswith(), startswith(), isalnum(), isalpha(), isdigit(), islower(), isupper(),
isspace(), lstrip(), rstrip(), strip(), replace(), join(), partition(), split()
TERM 2:

Unit II: Computational Thinking and Programming – 1


● Lists: introduction, indexing, list operations (concatenation, repetition, membership & slicing),
traversing a list using loops, built-in functions: len(), list(), append(), extend(), insert(), count(),
index(), remove(), pop(), reverse(), sort(), sorted(), min(), max(), sum(); nested lists, suggested
programs: finding the maximum, minimum, mean of numeric values stored in a list; linear search
on list of numbers and counting the frequency of elements in a list
● Tuples: introduction, indexing, tuple operations (concatenation, repetition, membership & slicing),
built-in functions: len(), tuple(), count(), index(), sorted(), min(), max(), sum(); tuple assignment,
nested tuple, suggested programs: finding the minimum, maximum, mean of values stored in a
tuple; linear search on a tuple of numbers, counting the frequency of elements in a tuple
● Dictionary: introduction, accessing items in a dictionary using keys, mutability of dictionary (adding
a new item, modifying an existing item), traversing a dictionary, built-in functions: len(), dict(),
keys(), values(), items(), get(), update(), del(), clear(), fromkeys(), copy(), pop(), popitem(),
setdefault(), max(), min(), count(), sorted(), copy(); suggested programs : count the number of
times a character appears in a given string using a dictionary, create a dictionary with names of
employees, their salary and access them
● Introduction to Python modules: Importing module using 'import <module>' and using from
statement, Importing math module (pi, e, sqrt, ceil, floor, pow, fabs, sin, cos, tan); random module
(random, randint, randrange), statistics module (mean, median, mode)

Unit III: Society, Law and Ethics


● Digital Footprints
● Digital society and Netizen: net etiquettes, communication etiquettes, social media etiquettes
● Data protection: Intellectual Property Right (copyright, patent, trademark), violation of IPR
(plagiarism, copyright infringement, trademark infringement), open source softwares and
licensing (Creative Commons, GPL and Apache)
● Cyber-crime: definition, hacking, eavesdropping, phishing and fraud emails, ransomware,
preventing cyber crime
● Cyber safety: safely browsing the web, identity protection, confidentiality, cyber trolls and
bullying.
● Safely accessing web sites: malware, viruses, Trojans, adware
● E-waste management: proper disposal of used electronic gadgets
● Indian Information Technology Act (IT Act)
● Technology & Society: Gender and disability issues while teaching and using computers
4. Practical

S.No. Marks Term-1 Term-2


(15 Marks) (15 Marks)
(Total=30)

1. Python program 12 6 6

2. Report file: Minimum 20 Python programs 7 4 3


Term- 1 : Minimum 10 programs based on Term – 1
syllabus
Term- 2 : Minimum 10 programs based on Term – 2
syllabus

Viva voce 3 2 1
3. Project + Viva voce 8 3 5
Term – 1 : Synopsis of the project to be submitted by
the students (documentation only)

Term - 2 : Final coding + Viva voce


(Student will be allowed to modify their Term 1
document and submit the final executable code.)

5. Suggested Practical List


Term - 1
Input a welcome message and display it.
 Input two numbers and display the larger / smaller number.
 Input three numbers and display the largest / smallest number.
 Generate the following patterns using nested loop.
Pattern-1 Pattern-2 Pattern-3
* 12345 A
** 1234 AB
*** 123 ABC
**** 12 ABCD
***** 1 ABCDE
 Write a program to input the value of x and n and print the sum of the following series:
o 1+x+x +x +x +. .......... x
2 3 4 n

o 1-x+x -x +x2 3 x
4 ................................. n

o x - x + x - x + ............ x
2 3 4 n

2 3 4 n
o x+x-x+x2 3 x
4 ................................... n

2! 3! 4! n!
 Determine whether a number is a perfect number, an armstrong number or a palindrome.
 Input a number and check if the number is a prime or composite number.
 Display the terms of a Fibonacci series.
 Compute the greatest common divisor and least common multiple of two integers.
 Count and display the number of vowels, consonants, uppercase, lowercase characters in string.
 Input a string and determine whether it is a palindrome or not; convert the case of characters in a
string.

Term - 2

 Find the largest/smallest number in a list/tuple


 Input a list of numbers and swap elements at the even location with the elements at the odd
location.
 Input a list/tuple of elements, search for a given element in the list/tuple.
 Input a list of numbers and find the smallest and largest number from the list.
 Create a dictionary with the roll number, name and marks of n students in a class and display the
names of students who have scored marks above 75.
6. Suggested Reading Material
 NCERT Textbook for COMPUTER SCIENCE (Class XI)

 Support Materials on the CBSE website.


LIST
List - A List is a standard mutable data type of python than can store a sequence of values belonging to
any data type. Lists are enclosed in square brackets and the elements of the list are separated by
commas.
Eg. [ ] - empty list
[1,2,3] - list of integers
['abc', 'def', 'ghi' ] - list of strings

Creating Lists-
1. Creating empty list- Empty lists can be created by writing empty square brackets or by using
list() method with no parameters.
Eg. L= [ ]
L=list()

2. Creating long list- If a list contains many elements, then the elements can be split in the next
line
Eg. L = [ 'abcdefghijklmnopqrstuvwxyz', 'abcdefghijklmnopqrstuvwxyz' ,
'abcdefghijklmnopqrstuvwxyz', 'abcdefghijklmnopqrstuvwxyz' ]

3. Creating nested list- A list containing within itself another list is known as a nested list.
Eg. L = [ 1 , 2, [ 3,4,5], 6 , 7, [8,9,10] ]

4. Creating list from existing sequence objects- A list can be created from a sequence object ( such
as other list, tuples, strings etc) by passing it as a parameter to the list() function.
Eg. L1=list('hello') # creates the list with elements ['h', 'e', 'l', 'l', 'o']

5. Creating list from user input- The user input is always accepted as a string. This string can be
converted to a list object by passing it to either the function list() or to the function eval(). This
list() function will try to convert the string to a list, whereas the eval() function evaluates the
string and finds which data type best matches the string. If the string contains square brackets
with values separated by commas then it creates a list.
Eg. L1=list(input('Enter a list of marks')) # list() used
L2=eval(input(('Enter the list of holidays for the month:')) #eval used

List Functions/Operations

1. Displaying a List
Using print and passing a list object displays a list of elements in square brackets separated by commas.
L = [2,7,9,13,19]
print(L)

o/p:
[2,7,9,13,19]

2. Accessing element of a List


An element of a list can be accessed by using the list name and an integer value known as an index
enclosed in square bracket, L[index].
There are two indexing methods - forward indexing and backward indexing.
• In forward indexing the first element of the list has index number 0, the second element has
index number 1 and so on.
• In backward indexing the last element of the list has index -1, the second last element has index
-2 and so on.

Page 1
• An element of a list can be accessed by using any one of the forward or backward indexing
methods.

Consider the list L= [ 2, 7, 9, 13, 19 ]

forward indexing -----> 0 1 2 3 4


L= 2 7 9 13 19
-5 -4 -3 -2 -1 <----- Backward Indexing

The element 9 of the list can be represented by either L[2] or by L[-3] , both will refer to the same
element.
Eg.

L = [2,7,9,13,19]
print(L[2] )
print (L[-4])

o/p:
9
7

3. Modifying a List element/Mutability of a List


The elements of a list can be modified by using L[index]=new_value. Since a list can be modified in place,
i.e. the existing list object is not destroyed and recreated, the list data type is said to be mutable.
L = [2,7,9,13,19]
L[2]=99
L[-1] = 77
print (L)

o/p:
[2, 7, 99, 13, 77]

4. Creating True Copy of a List


Usually the statement varname=newvalue creates a new variable (if varname is new) and stores
newvalue into that variable.

This concept is modified when existing lists are assigned to a new list variable. Using assignment
statement to assign an existing list to a new variable does not create a new list, but both the old and the
new variable will point to the same list in memory. Any changes made to one variable will reflect in the
other variable also.
L1=[1,2,3,4]
L2 = L1 #both L1 and L2 refer to the same list in memory
L2[1]=99
print('L1=', L1)
print('L2=', L2) #both L1 and L2 values are same

L3=[11,12,13,14]
L4=list(L3) #use list() method to create a new list from an existing list
L3[1]=99
print('L3=', L3)
print('L4=', L4) #L3 and L4 values are different since they are different objects

Page 2
o/p:
L1= [1, 99, 3, 4]
L2= [1, 99, 3, 4]
L3= [11, 99, 13, 14]
L4= [11, 12, 13, 14]

If we want that the new variable create a new copy of an existing list, then the list() method must be
used.

5. Finding number of elements in a List


The len() functions returns the number/count of elements present in a list.
L = [2,7,9,13,19]
x=len(L)
print(x )

o/p:
5

6. Joining/Concatenating two Lists


The + operator can be used to join/concatenate two lists.
L1 = [1,2,3]
L2=[7,8,9]
L3=L2+L1
print(L3 )

o/p:
[7, 8, 9, 1, 2, 3]

7. Replicating Lists
The * operator can be used to replicate lists. The * operator when used with a list, one of the operands
must be an int value that signifies the number of times the list is to be replicated.
L1 = [1,2,3]
L2=L1*3
print(L2 )

o/p:
[1, 2, 3, 1, 2, 3, 1, 2, 3]

8. Adding single element at the end of a List


The append() method can be used to add a single element at the end of a List.
L1 = [1,2,3]
L1.append(9)
print(L1)

o/p:
[1, 2, 3, 9]

Page 3
9. Adding multiple elements at the end of a List
The extend() method can be used to add multiple elements that are present in another list to an existing
list at the end
L1 = [1,2,3]
L2=[9,10]
L1.extend(L2) #L2 is a list. elements of L2 i.e. 9,10 are added at the end of L1
print(L1)

o/p:
[1, 2, 3, 9]

10. Adding single element at particular index


The listname.insert(pos,item) method can be used to add 'item' element at index pos in the list -
listname. All the existing elements from pos onwards till the end are shifted right.
L1 = [4,9,12,17,19]
L1.insert(2, 99) #insert 99 at index 2
print(L1)

o/p:
[4, 9, 99, 12, 17, 19]

11. Deleting single element using del via index position


The del command can be used to delete an element at a particular index location in the list. The syntax
is : del listname[index]
L1 = [2,4,6,8,10]
del L1[3]
print(L1)

o/p:
[2, 4, 6, 10]

12. Deleting single element using pop via index position


The pop() method can also be used to delete from either the end of the list(when no parameter is
passed) or from a particular index(when a single index value is passed). The difference between del and
pop is that pop() also returns the element that was deleted whereas del command does not return the
deleted element.
L1 = [2,4,6,8,10]
print('Now popping ', L1.pop())
print('List is', L1)
x=L1.pop(2)
print('Then popped', x)
print('List is now', L1)

o/p:
Now popping 10
List is [2, 4, 6, 8]
Then popped 6
List is now [2, 4, 8]

Page 4
13. Deleting single element using remove via value
The listname.remove(value) method can be used to remove an element containing a particular 'value'.
This is different from del and pop command which deletes an element from a particular index location.
When using remove() method if there are multiple elements in a list having the same 'value' then only
the first occurrence of 'value' is removed.

L1 = [1,2,3,4,1,2,3,4,1,2,3,4]
L1.remove(2)
print(L1)

o/p:
[1, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]

14. Clearing the list


The clear() method clears all the elements of the list and makes it an empty list.
L1 = [1,2,3,4,1,2,3,4,1,2,3,4]
L1.clear()
print(L1)

o/p:
[]

15. Deleting an object from memory using del


The del objectname command can be used to delete any object from pythons memory. After this
command the variable does not exist in memory.
L1 = [1,2,3,4]
del L1
#print(L1) #This command will give an error since L1 object does not exist in memory

16. Counting the occurrence of elements in a list


The count() method can be used to count the number of times an item appears in the list. If the item is
not present in the list, then count() returns zero.
L1 = [1,2,3,4,1,2,3,4,1,2,3,4]
print(L1.count(2))
print(L1.count(75))

o/p:
3
0

17. Reversing a list


The reverse() method reverses a list in place i.e. a new list is not created and the reversed items are
placed in the same list.
L1 = [1,2,3,4]
L1.reverse()
print(L1)

o/p:
[4, 3, 2, 1]

Page 5
18. Sorting a list using listobject.sort()
The sort() method sorts a list in ascending order. The list is modified in place i.e. a new list is not created
and the sorted items are placed in the same list. To sort in descending order the parameter (reverse =
True) must be passed. The 'key=' parameter can be used to pass a function that will be applied to each
element of the list before being sorted. This can be used on a list of strings to pass the function
'str.lower' (as 'key=str.lower'), in which case the sorting is performed on a case-insensitive manner.
L1 = [9,3,2,4]
L1.sort()
print(L1)

L2=[2, 7, 21, 4]
L2.sort(reverse=True)
print(L2)

L3=['Pqr', 'abc', '2np']


L3.sort(key=str.lower)
print(L3)

o/p:
[2, 3, 4, 9]
[21, 7, 4, 2]
['2np', 'abc', 'Pqr']

19. Sorting a list using sorted()


Syntax: sorted(iterable, *, key=None, reverse=False)
The sorted() method works on any iterable sequence(such as a list, tuple, dictionary) and returns back a
list of elements in sorted order. The original iterable object is passed as a parameter to the sorted()
method and remains unchanged. The sorted method also accepts the parameter reverse=True, in which
case the returned elements are sorted in descending order. The 'key=' parameter can be passed a value
of 'str.lower' when sorting an iterable consisting of strings in which case the sort is performed in a case-
insensitive manner.

L1 = [9,3,2,4]
L2 = sorted(L1)
print('L1=', L1)
print('L2=', L2)

L3=[2, 7, 21, 4]
L4=sorted(L3,reverse=True)
print('L3=',L3)
print('L4=',L4)

L5=['Pqr', 'abc', '2np']


L6=sorted(L5)
L7=sorted(L5,key=str.lower)
print('L5=',L5)
print('L6=',L6)
print('L7=',L7)

o/p:
L1= [9, 3, 2, 4]
L2= [2, 3, 4, 9]
L3= [2, 7, 21, 4]
L4= [21, 7, 4, 2]

Page 6
L5= ['Pqr', 'abc', '2np']
L6= ['2np', 'Pqr', 'abc']
L7= ['2np', 'abc', 'Pqr']

20. Finding the minimum and maximum element in a List


The min() method returns the minimum element in a list and the max() method returns the maximum
element in a list.
L1 = [16,55,3,4]
print(min(L1))
print(max(L1))

o/p:
1
4

21. Finding the sum of elements in a List


The sum() method returns the sum of elements of a list. All the elements of the list must be numbers.

L1 = [16,55,3,4]
print(sum(L1))

o/p:
78

22. Getting the index of an element of a List


The index() method returns the index of an existing element of a list. If multiple elements with same
value is present in the list then the index of the first occurrence is returned. If the list does not contain
the element then python gives an error.
L1 = [9,3,1,2,4, 7, 9, 2]
print(L1.index(2))

#print(L1.index(99)) # will give error as 99 is not present in list

o/p:
3

23. Traversing a list using the index


The for loop can be used to go through all the valid indexes of the list and process the list. For this the
len() function must be used to get count of number of elements of the list.

L1 = [9,3,2,4]
x=len(L1)
for i in range(x):
print(L1[i])
o/p:
9
3
2
4

In this method L1[i] refers to the actual element of the list. Any updates done to L[i] will update the list
in place. Use this method to update the list using for loop.

Page 7
24. Traversing a list using the iterator
The for loop can be used to iterate over the elements of the list and process the list.

L1 = [9,3,2,4]
for i in L1:
print(i)
o/p:
9
3
2
4

Here the loop variable i is only holding a copy of the list element. Any updates done to i does not affect
the list in any way. So do not use this method if the list is to be updated using loops.

25. List Comparisons


The relational operators >, >=, <, <=, ==, != can be applied to two lists to arrive at a True or False value.
The following rules are observed:
a. For equality (==) operator - If equality evaluate to True only when all the elements of one list
match all the elements of the other list and both the list have the same number of elements.
b. For all other operators - The elements are compared sequentially using the operator under
consideration. If a clear answer (either True or False) is arrived then that becomes the result of
the comparison between the two lists. A clear answer is not arrived when elements of both the
list happen to have same value. Then in that case the next set of elements are checked and the
process is repeated.
c. If two lists are of different lengths and if one of the list has an element at an index position and
the other list does not have an element at that position then the evaluation proceeds as follows:
• something/somevalue > empty/nothing evaluates to True
• something/somevalue < empty/nothing evaluates to False

print( [1,2,3] == [1,2,3])


print( [1,2,3] != [1,2,3])
print( [1,2,8,9] < [9,1])
print( [1,2,8,9] >= [1,9])
print( [1,2] < [1,2,3])
print( [2] > [1,2,3])

o/p:
True
False
True
False
True
True

Page 8
26. List Slicing
List slice is creating a new list using elements of an existing list. It is created as:
ListName[start : stop : step] where start, stop , step are integers

The slice [start : stop : step] is used on many objects with index.

The basic rules of slice are:


i. The slice generates index/integers from - start, start + step, start + step + step, and so on. All the
numbers generated must be less than the stop value when step is positive.
ii. If step value is missing then by default is taken to be 1
iii. If start value is missing and step is positive then start value is by default taken as 0.
iv. If stop value is missing and step is positive then start value is by default taken to mean till you
reach the ending index(including the ending index)
v. A negative step value means the numbers are generated in backwards order i.e. from - start,
then start - step, then start -step -step and so on. All the numbers generated in negative step
must be greater than the stop value.
vi. If start value is missing and step is negative then start value takes default value -1
vii. If stop value is missing and step is negative then stop value is by default taken to be till you
reach the first element(including the 0 index element)

Consider the list L:


forward indexing -----> 0 1 2 3 4 5 6 7 8 9
L= 2 7 9 10 13 15 17 19 23 25
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 <----- Backward Indexing

Slice Generates
L[4: ] [13, 15, 17, 19, 23, 25]
L[ : 3] [2,7,9]
L[2: 5] [9,10, 13]
L[4: : 2] [13, 17, 23]
L[2 : 7 : 2] [9, 13, 17]
L[ : : -1] [25, 23, 19, 17, 15, 13, 10, 9, 7, 2]
L[ : : -2] [25, 19, 15, 10, 7]
L[6 : 1: -2] [17, 13, 9]
L[-8 : 8 ] [9, 10, 13, 15, 17, 19]
L[3 : -2 : 2] [10, 15, 19]
L[6 : -9 : -2] [17, 13, 9]

27. Updating / Deleting multiple elements using List Slice


The list slice can be used to update multiple elements of a list. On the left side of the assignment
operator (=) the list slice is written and on the right side of the =, a list containing the same number of
elements as the number of elements in the list slice is written.

For deleting multiple elements in a List, the syntax is: del list_slice

L=[2,7,9,10,13,15,17,19,23,25]
L[1:5:2]=[77,99] #updating index 1 element with 77, index 3 element with 99
print(L)

del L[5: :2] #delete elements at index 5,7,9


print(L)

Page 9
o/p:
[2, 77, 9, 99, 13, 15, 17, 19, 23, 25]
[2, 77, 9, 99, 13, 17, 23]

28. List Membership testing


The in and not in operators can be used to test whether a value is present / is not present in a list.
L=[1,2,3,4,5]
x=int(input('Enter an element to search:'))
if x in L:
print(x, 'is present in', L)
if x not in L:
print(x, 'is not present in', L)

o/p1:
Enter an element to search:2
2 is present in [1, 2, 3, 4, 5]
o/p2:
Enter an element to search:20
20 is not present in [1, 2, 3, 4, 5]

29. Accessing Nested Lists


A list containing another list within it is known as nested list. For accessing nested list member we can
use two square brackets- the first showing the index in the outer list and the next showing the index for
the inner list.
L=[1,2,[3,4,5], [6,7,8] ]
print('L[0]=', L[0])
print('L[2]=', L[2])
print('L[2][1]=', L[2][1])
print('L[3][2]=', L[3][2])

o/p:
L[0]= 1
L[2]= [3, 4, 5]
L[2][1]= 4
L[3][2]= 8

Page 10
EXTRA TOPICS

Identity (id)- Everything in python is structured as an object. All the objects are stored in memory. Each
location in computers memory (RAM) has a unique addressing number, the memory address, associated
with it. The identity (id) of an object is the memory address/location of the first byte where that
particular object is stored. The id() function can be used to access the memory address of any
object/variable.

In python the variable name is stored separately and the memory content is stored separately. For
example the variable declaration
x=200 memory address

The name 'x' is stored separately.


The content/value 200 is stored 500 200
starting at memory address 500.

The function id(x) will return a value of 500. 700 abc


When another statement,
x='abc' is written , the content/value 'abc' is stored starting at memory address 700 and if now id(x) is
executed it will return a value of 700.
In python usually the content/value for almost all types of objects is created only once during an entire
program. This means that if there are two variables x and y as shown below:
x = 200
y=200

Then the content/value/literal 200 of type int is created only once. The variable names x and y are
different, but they will refer to the same memory address i.e. 500 as shown below-

500 200

700 abc

The variables x and y will return the same value when id function is applied to both of them.

is operator - The is operator checks the id of two variables and returns True if both are same otherwise
it returns False.

is not operator- The is not operator check if the ids of two variables are dis-similar. It returns True if the
ids of both the variables are different otherwise it returns False.

Eg.
x=5
y=5
z=6
print(x is y)

Page 11
print(y is z)
print(x is not z)

o/p:
True
False
True

Immutable data type- The data types in which the values of the variables cannot be changed in place
are known as Immutable data type. Eg. int, float, Boolean, complex, strings, tuples, sets.

Mutable data type- The data types in which the values of the variables can be changed in place are
known as mutable data types. Eg. list, dictionary.

In immutable datatype we cannot go the memory location of a variable and overwrite the content of
that memory location.

x = 200
500 200 replace it with 57
id(x) is 500 here This is not possible

Although we can write


x=57, what actually happens is-

A new object with value 57 is


created and the id of variable x 500 200
is changed to 700 to reflect the new object created.

id(x) is now 700. 700 57

In mutable data types we can go to the memory address of an object and replace the existing value with
a new value.
Eg.
L=[10,20,30] #L is a list object with values 10,20,30

500 10
20
Using the statement - 30 This value of 30
L[2]=55 can be overwritten
we can overwrite the value of 30 inplace and replace it with a value with value 55.
of 55.

Page 12
TUPLES AND DICTIONARIES

CONCEPT OF DATA STRUCTURE

Data Structures are the structures that hold and organize data or information

SEQUENCE/COLLECTION DATA STRUCTURES IN PYTHON

 String
 List
 Tuple
 Range
 Dictionary

FEATURES OF TUPLE

 It is a standard data type of Python.


 It is a sequence data type and each element has an index value
 It is a heterogeneous data type
 It is a immutable data type
 It is indicated with the help of paranthesis
 You cant add elements to a tuple because of their immutable property.
 There is no append() and extend () methods
 You cant remove elements from a tuple because of their immutable property.
 Tuples don’t have remove() and pop() methods
 To change a tuple, you can unpack it , change it and then pack it again
 You can also use list() or tuple() method to change the values of a tuple

Creating a Tuple

<tuple name > = ( <tuple of values separated by comma >)

Subject = ( “Eng”, “Phy”, “Chem” , “Mat”, “CS” )

Address = ( 4, “S M Street” , “Calicut”, 673002 )

Difference of List and Tuple

List uses [ ] whereas tuple uses ( )

List is mutable whereas tuple is immutable

Built – in functions of tuple :

Page 13
Function Name Purpose
len() Gives number of elements of tuple

id() Gives address of tuple

type() Gives data type of tuple

index() Gives the index at which element is present

count() Number of occurrences of an element

min() Gives Lowest value of tuple

max() Gives Highest value of tuple

sum() Gives Total of all elements.

any() Gives True if tuple has elements

sorted() Arrange elements in ascending order

Operations on tuple :

Concatenation + Attaches two tuples


T1=(1,2)
T2=(3,4)
T1+T2 = (1,2,3,4)
Replication * Replicates the tuples a particular
number of times
T1=(1,2)
T2=T1*2
T2=(1,2,1,2)
Membership In Checks whether an element is present
not in or not.
T1=(1,2,3)
3 in T1 will give True

Page 14
DICTIONARIES IN PYTHON

Dictionaries are used to store data values in key: value pairs.

A dictionary is a collection which is ordered, changeable and do not allow duplicates.

Each dictionary is a set of key: value pairs.

You can create it by using the following syntax.

dict = {‘key1’:’value1’, ‘key2’:’value2’, ‘key3’:’value3’,


key4’: ’value4’, ……‘keyn’:’valuen’}

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

Dictionary keys

 Dictionary keys must be unique


 A key in a dictionary is like an index in a list
 Python must know exactly which value you want
 Keys can be of any data type as long as it is immutable

Dictionary Values

 Dictionary keys have many rules, but the values do not have many restrictions

 They do not have to be unique


 They can be mutable or immutable
For creating empty dictionaries, following methods can be used

1. dict1={ }
2. dict2 = dict()
print(dict1)  {}

print(dict2)  {}

Page 15
# dict3 is a dictionary that maps names of the students to marks in percentage

dict3 = { ' Neeraj ' : 76, ' Suman' : 56, 'Rony ' : 34, 'Ajmal' : 85}
print (dict3)  {'Neeraj': 76, 'Suman' : 56, 'Rony': 34, 'Ajmal': 85}

ACCESSING DICTIONARY

 The items of a dictionary are accessed via the keys rather than via their relative
positions or indices.

 Each key serves as the index and maps to a value.

print(dict3['Suman’])
56

print(dict3['Ajmal’])
85

If the key is not present in the dictionary, we get KeyError.

TRAVERSING A DICTIONARY

We can access each item of the dictionary or traverse a dictionary using a for loop.

dict3 = { ' Neeraj ' : 76, ' Suman' : 56, 'Rony ' : 34, 'Ajmal' : 85}
# Method 1

for key in dict3:

print(key, ':',dict3[key])

OUTPUT
Neeraj : 76
Suman : 56
Rony : 34

OUTPUT

Page 16
Neeraj : 76
Ajmal : 85
Suman : 56
# Method 2 Rony : 34
Ajmal : 85
for key,value in dict3.items():

print(key,':',value)

TO ADD AN ITEM TO THE DICTIONARY

To add an item to the dictionary (empty string), we can use square brackets for
accessing and initializing dictionary values.

dict3 = { ' Neeraj ' : 76, ' Suman' : 56, 'Rony ' : 34, 'Ajmal' : 85}

dict3[‘Nisha’]=87

print(dict3)  { ' Neeraj ' : 76, ' Suman' : 56, 'Rony ' : 34, 'Ajmal' : 85, ‘Nisha’: 87 }

TO MODIFY AN ITEM IN DICTIONARY

The existing dictionary can be modified by just overwriting the key-value pair.

dict3 = { ' Neeraj ' : 76, ' Suman' : 56, 'Rony ' : 34, 'Ajmal' : 85}

dict3[‘Suman’]=99

print(dict3)  { ' Neeraj ' : 76, ' Suman' : 99, 'Rony ' : 34, 'Ajmal' : 85 }

REMOVING AN ITEM FROM DICTIONARY

You can remove an item from the existing dictionary by using del

command or using pop () method.

Using del command

dict3 = { ' Neeraj ' : 76, ' Suman' : 56, 'Rony ' : 34, 'Ajmal' : 85}

del dict3[‘Suman’]

print(dict3)  { ' Neeraj ' : 76, 'Rony ' : 34, 'Ajmal' : 85 }

To delete the dictionary from the memory we can use:

Page 17
del dictionary_name

del dict3

Using pop() method

pop () method will not only delete the item from the dictionary, but alsoreturn
the deleted value.

Syntax:

dictionary.pop(key)
dict3 = { ' Neeraj ' : 76, ' Suman' : 56, 'Rony ' : 34, 'Ajmal' : 85}

dict3.pop(‘Suman’)
56  It also returns the deleted value

print(dict3)  { ' Neeraj ' : 76, 'Rony ' : 34, 'Ajmal' : 85 }

MEMBERSHIP OPERATORS ( in and not in)


The membership operator in checks if the key is present in the dictionary and
returns True, else it returns False.
dict3 = { ' Neeraj ' : 76, ' Suman' : 56, 'Rony ' : 34, 'Ajmal' : 85}

‘Rony’ in dict3  True

34 in dict3  False

‘Ajmal’ not in dict3  False

85 not in dict3  True

DICTIONARY METHODS AND FUNCTIONS

1. len( ) -- It Returns the length or number of key: value pairs of the dictionary
passed as the argument.
2. keys() -- It Returns a list of keys in the dictionary.
3. values() -- It Returns a list of values in the dictionary.

4. items() -- It Returns a list of tuples (key — value) pair

5. get() -- It Returns the value corresponding to the key passed as the argument.
If the key is not present in the dictionary it will return None.

Page 18
6. del() -- It Deletes the item with the given key.
7. pop () -- method will not only delete the item from the dictionary, but also

return the deleted value.


8. clear() -- It Deletes or clear all the items of the dictionary.

PROGRAMS USING DICTIONARY

# 1. Program to authenticate users

USERS={'admin': '123@wq','staff': '789sdf','student': '709klp'}

userid=input("Enter the user id:")

passwd=input("Enter the password:")

if userid in USERS:

if USERS[userid]==passwd:

print("Login successful, access granted")

else:

print("Incorrect password, access denied")

else:

print ("Wrong credentials")

OUTPUT

Enter the user id: student

Enter the password: 709klp

Login successful, access granted

# 2. Write a program to count the number of times a character appears in a given string.

str=input("Enter a string:")
dict={}
for ch in str:
if ch in dict:
dict[ch]+=1

Page 19
else:
dict[ch]=1
for key in dict:
print (key," : ",dict[key])
OUTPUT

Enter a string: THIS IS A TREE


T : 2
H :1
I : 2
S : 2
: 3
A : 1
R : 1
E : 2

Suggested Programs on Dictionary

Program : Write a program to enter names of employees and their salaries as input and
store them in a dictionary.

#Program to create a dictionary which stores names of the employee and their salary

n = int(input("Enter the number of employees whose data to be stored: "))

count = 1

employee = dict() #create an empty dictionary

while count <= n:

name = input("Enter the name of the Employee: ")

salary = int(input("Enter the salary: "))

employee[name] = salary

count += 1

print("\n\nEMPLOYEE_NAME\tSALARY")

for k in employee:

Page 20
print(k,'\t\t',employee[k])

OUTPUT :

Enter the number of employees whose data to be stored: 5

Enter the name of the Employee: Kiran

Enter the salary: 25000

Enter the name of the Employee: Asha

Enter the salary: 20000

Enter the name of the Employee: Annie

Enter the salary: 35000

Enter the name of the Employee: Vijay

Enter the salary: 50000

Enter the name of the Employee: Aakash

Enter the salary: 15000

EMPLOYEE_NAME SALARY

Kiran 25000

Asha 20000

Annie 35000

Vijay 50000

Aakash 15000

Program : Write a program to count the number of times a character appears in a


given string.

Page 21
#Count the number of times a character appears in a given string

str = input("Enter a string: ")

dict = { } #creates an empty dictionary

for ch in str:

if ch in dict: #if the character is already in the dictionary

dict[ch] += 1

else:

dict[ch] = 1 #if ch appears for the first time

for key in dict:

print(key,':',dict[key])

OUTPUT :

Enter a string : programming

p:1

r:2

o:1

g:2

a:1

m:2

i:1

n:1

MCQ

Page 22
1. Which of the following is a Python tuple?
a) [1, 2, 3]
b) (1, 2, 3)
c) {1, 2, 3}
d) {}

2. Suppose t = (1, 2, 4, 3), which of the following is incorrect?


a) print(t[3])
b) t[3] = 45
c) print(max(t))
d) print(len(t))

3. What is the output of the following code:


t=(1,2,4,3)
print( t[1:3] )
a) (1, 2)
b) (1, 2, 4)
c) (2, 4)
d) (2, 4, 3)

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

t=(1,2,4,3)
print( t[1:-1])
a) (1, 2)
b) (1, 2, 4)
c) (2, 4)
d) (2, 4, 3)

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


d={“John”:40,”Peter”:45}
print(d[“John”])
a.40
b. 45
c. “john”
d. “peter”

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


t= (1,2)
print(2*t)

Page 23
a) (1, 2, 1, 2)
b) [1, 2, 1, 2]
c) (1, 1, 2, 2)
d) [1, 1, 2, 2]
7. What will be the output of the following Python code?
T1 =(1,2,3,4)
T2=(1,2,4,3)
print( T1 < T2 )
a) True
b) False
c) Error
d) None
8. What will be the output of the following Python code?
T=(3, 4)
T.append(5)
print(T)

a) 1
b) 2
c) 5
d) Error

9. Which of the following creates a tuple?


a. tuple1=("a","b")
b. tuple1[2]=("a","b")
c. tuple1=(5)*2
d. None of the above

10. Choose the correct option with respect to Python.


a. Both tuples and lists are immutable.
b. Tuples are immutable while lists are mutable.
c. Both tuples and lists are mutable.
d. Tuples are mutable while lists are immutable.

11.Choose the correct option.

a. In Python, a tuple can contain only integers as its elements.


b. In Python, a tuple can contain only strings as its elements.

Page 24
c. In Python, a tuple can contain both integers and strings as its elements.
d. In Python, a tuple can contain either string or integer but not both at a time.

12. What will be the output of below Python code?


tuple1=(5,1,7,6,2)
tuple1.pop(2)
print(tuple1)

a. (5,1,6,2)
b. (5,1,7,6)
c. (5,1,7,6,2)
d. Error

13. What will be the output of below Python code?


tupl=("annie","hena","sid")
print(tupl[-3:0])
a. ("annie")
b. ()
c. None
d. Error as slicing is not possible in tuple.

14. Which of the following options will not result in an error when performed on tuples
in Python where tupl=(5,2,7,0,3)?

a. tupl[1]=2
b. tupl.append(2)
c. tupl1=tupl+tupl
d. tupl.sort()

15. Which one of the following is correct?

a. Dictionary is the only mutable data type


b. Dictionary is an immutable data type
c. Both list and dictionary are mutable data type
d. All of the above

16. What will be the output of above Python code?


d1={"abc":5,"def":6,"ghi":7}
print(d1[0])
a. Abc

Page 25
b. 5
c. {"abc":5}
d. Error

17. What will be the result of above Python code?


dict={"Joy":1,"Rachel":2}
dict.update({"Philip":2})
print(dict)

a. {"Joy":1,"Rachel":2,"Philip":2}
b. {"Joy":1,"Rachel":2}
c. {"Joy":1,"Philip":2}
d. Error

18. Which of the following functions will return the key, value pairs of a dictionary?
a. evs()
b.values()
c. items()
d. all of the above

19. Let d = {“Amit”:40, “Abhay”:45}


To delete the entry for “Amit” what command do we use?

a. d.delete(“Amit”:40)
b. del d(“Amit”:40)
c. del d[“Amit”]
d. d.delete(“Amit”)

20. What will be the output of the following Python code snippet?
d1 = {“Amit”:34, “Arnav”:45}
d2 = {“Amit”:46, “Arnav”:45}
d1 == d2
a. True
b. False
c. None
d. Error

21. What will be the output after the following statements?


x = {1:’Jan’, 2:’Feb’, 3:’March’, 4:’April’}
print(x[2])

Page 26
a. Jan
b. Feb
c. March
d. April

22. What would the following code print?


d = {‘spring’: ‘autumn’, “autumn”: “fall”, “fall”:”spring”}
print (d[“autumn”])

a. autumn
b. fall
c. spring
d. Error

23.What will be the result of the following code?


d1 = {“abc”:5,”def”:6, “ghi”:7}
print (d1[0])
a. Abc
b. 5
c. (“abc” : 5)
d. Error

24. Which of the following will modify key_value pair for key = “lion” in dictionary?
di = {“lion” : “wild”, “tiger” : “wild”, “cat”:”domestic” , “dog” : “domestic”}

a. di.update({“lion”:”king”})
b. di[“lion”]=”king”
c. None
d. Both a and b

25. What is printed by the following statements?


D1 = {“cat”:17, “dog”:6, “elephant”:23, “bear”:20}
print (25 in D1)

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

26. What is printed by the following statements?

Page 27
D1 = {“cat”:17, “dog”:6, “elephant”:23, “bear”:20}
print (“dog” in D1)

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

27. Which of the following data types fall under mappings:

a. List
b. Tuple
c. String
d. Dictionary

28. Which of the following will give error?


Let dict1={“a”:1, “b” :2, “c” :3 }

a. print(len(dict1))
b. print(dict1.get("b"))
c. dict1["a"]=5
d. None of these.

29. Which one of the following is correct?

a. In python, a dictionary can have two same keys with different values.
b. In python, a dictionary can have two same values with different keys
c. In python, a dictionary can have two same keys or same values but cannot have
two same key-value pair
d. In python, a dictionary can neither have two same keys nor two same values.

30.Which of the following will delete key_value pair for key="tiger" in dictionary?
dic={"lion" : "wild","tiger" : "wild","cat" : "domestic","dog" : "domestic"}

a. del dic["tiger"]
b. dic["tiger"].delete()
c. delete(dic.["tiger"])
d. del(dic.["tiger"])

Page 28
MCQ Answers:

QNO OPTION QNO OPTION QNO OPTION


1 b 11 c 21 b
2 b 12 d 22 b
3 c 13 b 23 d
4 c 14 c 24 d
5 a 15 c 25 b
6 a 16 d 26 a
7 a 17 a 27 d
8 d 18 c 28 d
9 a 19 c 29 b
10 b 20 a 30 a

OUTPUT FINDING QUESTIONS

1. Find output of the following code:


mydict={'a':27,'b':43,'c':25,'d':30}
val=''
for i in mydict:
if i>val:
val=i
valb=mydict[i]
print(val)
print(valb)
print (30 in mydict)

2. Find output:
d1={5:"number","a":"string",(1,2):"tuple"}
for x in d1.keys():
print(x,":",d1[x],end="")
print(d1[x]*3)
print()

Page 29
3. Find output:
d=dict()
d['left']='<'
d['right']='>'
print(d['left'] and d['right']or d['right'] and d['left'])

4. Find output:
text="abracadabraaabbccrr"
counts={}
lst=[]
for word in text:
if word not in lst:
lst.append(word)
counts[word]=0
counts[word]=counts[word]+1
print(counts)

5. Find output:
d={1:"a",2:"b",3:"c"}
d1={}
for x in d:
d1[d[x]]=x
print(d1)

6. Find output:
d1={1:"a",2:"b"}
d2={3:"c",2:"d"}
for x in d1:
if x in d2:
print(x)

7. Find output:

Page 30
tuple = {}
tuple[(1,2,4)] = 8
tuple[(4,2,1)] = 10
tuple[(1,2)] = 12
_sum = 0
for k in tuple:
_sum += tuple[k]
print(len(tuple) + _sum)

8. Find output:
T = 'abcde'
a, b, c, d, e = T
b = c = '*'
T = (a, b, c, d, e)
print(T)

9. Find output:
T = (1, 2, 3, 4, 5, 6, 7, 8)
print(T[T.index(5)], end = " ")
print(T[T[T[6]-3]-6])

10.Find output:
D = dict()
for i in range (3):
for j in range(2):
D[i] = j
print(D)

11. Find output


d1={"a":45,"b":78}
d2={"c":45,"b":88}
d1.update(d2)
print(d1)

Page 31
12.Find output:
d1={"a":45,"b":78}
d2={"c":45,"b":88}
d3=d2.copy()
print(d1.keys())
print(d2.values())
print(d3.keys())

13.Find output:
d1={101:["A","B"],102:["C","D"],103:["E","F"]}
for i in d1:
for j in d1[i]:
print(j, end=" ")
print()

14.Find output:
d1={1:"Mars",2:"Venus",3:"Earth"}
d1[3]="Jupiter"
print(d1)
print(d1.items())

15.Find output:
d1={1:"Mars",2:"Venus",3:"Earth"}
for i in d1:
s=d1[i]
print(len(s))

Answers- Output finding

1. Ans:
d
30
False
2. Ans:
5 : numbernumbernumbernumber
a : stringstringstringstring
(1, 2) : tupletupletupletuple

3. Ans:

Page 32
>
4. Ans:
{'a': 7, 'b': 4, 'r': 4, 'c': 3, 'd': 1}
5. Ans:
{'a': 1, 'b': 2, 'c': 3}
6. Ans:
2
7. Ans
33
8. Ans:
('a', '*', '*', 'd', 'e')
9. Ans:
5 8
10. Ans:
{0: 1, 1: 1, 2: 1}
11. Ans:
{'a': 45, 'b': 88, 'c': 45}
12. Ans:
dict_keys(['a', 'b'])
dict_values([45, 88])
dict_keys(['c', 'b'])
13. Ans:
AB
CD
EF

14.Ans:
{1: 'Mars', 2: 'Venus', 3: 'Jupiter'}
dict_items([(1, 'Mars'), (2, 'Venus'), (3, 'Jupiter')])
15.Ans:
4
5
5

Page 33
PROGRAMS
1. Write a program to read a tuple from the user using loop
n=int(input("Enter the number of elements:"))
t=tuple()
for i in range(n):
a=int(input("Enter number"))
t=t+(a,)
print(t)

2. Read a tuple from user and find the mean of the elements
t=eval(input("Enter a tuple of numbers"))
s=sum(t)
mean=s/len(t)
print("Mean is ",mean)

3. Read a tuple from the user and print its reverse .

t=eval(input("Enter a tuple of numbers"))


print("Revrse is : ",t[::-1])

4. Read a tuple from the user and add an element at the end of it using list.
t=eval(input("Enter a tuple of numbers"))
l=list(t)
a=int(input("Enter the number to add at the end:"))
l.append(a)
t=tuple(l)
print(t)

5. Read a tuple from the user and modify it so that all the even numbers get
multiplied by 2 and all odd numbers get multiplied by 3.
t=eval(input("Enter a tuple of numbers"))
l=list(t)
for i in range(len(l)):
if l[i]%2==0:
l[i]=l[i]*2
else:
l[i]=l[i]*3
t=tuple(l)
print(t)

Page 34
6. Write a program to interchange to tuples. For example, if t1=(1,2) and t2=(3,4),
then the tuples must be changed as t1=(3,4) and t2=(1,2)
t1=eval(input("Enter first tuple"))
t2=eval(input("Enter second tuple"))
t1, t2=t2, t1
print(t1, t2)

7. Write a program to read a tuple from the user and create a list from the tuple
which contains unique elements of the tuple.
t1=eval(input("Enter first tuple"))
l=[]
for i in t1:
if t1.count(i)==1:
l.append(i)
print(l)

8. Create a dictionary of books with book number as key and book name as value
n=int(input("Enter number of books:"))
d={}
for i in range(n):
key=int(input("Enter book number:"))
val=input("Enter name:")
d[key]=val
print(d)

9. Create a dictionary of books with book number as key and book name as value.
Read a book number and search for it.
n=int(input("Enter number of books:"))
d={}
for i in range(n):
key=int(input("Enter book number:"))
val=input("Enter name:")
d[key]=val
print(d)
x= int(input("Enter book number to search:"))
if x in d:
print("Found")
else:
print("Not Found")

Page 35
10.Create a dictionary of students with roll number, name and mark with roll
number as key and name as values in the form of tuple.
n=int(input("Enter number of students:"))
d={}
for i in range(n):
key=int(input("Enter roll no:"))
val1=input("Enter name:")
val2=int(input("Enter total mark:"))
d[key]=(val1,val2)
print(d)

11.Create a dictionary of students with roll number, name and mark with roll
number as key and name as values in the form of tuple. Display the details of
student who has scored marks above 75
n=int(input("Enter number of students:"))
d={}
for i in range(n):
key=int(input("Enter roll no:"))
val1=input("Enter name:")
val2=int(input("Enter total mark:"))
d[key]=(val1,val2)
print(d)
for i in d:
t=d[i]
if t[1]>75:
print(d[i])
12.Create a dictionary of items with item number and price. Display the sum of all
items.
n=int(input("Enter number of items:"))
d={}
for i in range(n):
key=int(input("Enter item no:"))
price=int(input("Enter price"))
d[key]=price
print(d)
s=0
for item in d:
s+=d[item]
print("Sum is ",s)

Page 36
INTRODUCTION TO PYTHON MODULES

A module is a logical organization of Python code. Related codes are grouped into a
module which makes the code easier to understand and use. Any python module is an
object with different attributes which can be bind and referenced.

Simply, it is a file containing a set of functions which can be included in our application.

Python provide inbuilt standard modules, like math, random etc.

Using a Module

We can use the import statement in three ways to be able to use functions from a
particular module.

Page 37
1. import <module-name>

For example, in order to find the square root of a given number, we can use the sqrt()
function from the math module, we can write the following code:

import math

x=int(input("Enter a number"))

print(math.sqrt(x))

Output:

Enter a number 81

9.0

We can also use the following two ways to import modules and use the functions they
contain:

2. from <module-name> import <method-name>

Example:

from math import sqrt

print(sqrt(81))

Output:

9.0

Page 38
3. from <module-name> import *

Example:

from math import *

print(sqrt(81))

Output:

9.0

Note that in the first method we need to specify the module name followed by the
function name in order to use the function.

Math module

The math module is a standard module in Python and is always available. To use
mathematical functions under this module, we have to import the module using import
math statement.

Method Description

sqrt() Accepts a number and return its square root

ceil() Accepts a floating-point value and returns a


smallest integer greater than or equal to the
argument passed

floor() Accepts a floating-point value and returns the


largest integer less than or equal to the given
number

pow() Accept two numbers (x,y) and return x raised to


y, same as x**y

fabs() Accepts a number and returns absolute value

sin() Accepts a number (value of angle in radians) and

Page 39
return its sine value

cos() Accepts a number (value of angle in radians) and


return its cosine value

tan() Accepts a number (value of angle in radians) and


return its tangent value

How to use math function

import math

math.sqrt(4)

math.sqrt()

The math.sqrt() method returns the square root of a given number.

>>>math.sqrt(100)

Output-10.0

>>>math.sqrt(3)

Output- 1.7320508075688772

The ceil() function approximates the given number to the smallest integer, greater than
or equal to the given floating point number. The floor() function returns the largest
integer less than or equal to the given number.

>>>math.ceil(4.5867)

Output-5

>>>math.floor(4.5687)

Output- 4

math.pow()

Page 40
The math.pow() method receives two float arguments, raises the first to the second and
returns the result. In other words, pow(2,3) is equivalent to 2**3.

>>>math.pow(2,4)

Output- 16.0

math.fabs()

Returns the absolute value of x

>>> import math

>>> math.fabs(-5.5)

Output-5.5

The math module contains functions for calculating various trigonometric ratios for a
given angle. The functions (sin, cos, tan, etc.) need the angle in radians as an argument.

>>> math.sin(270)

Output-0.1760459464712114

Using the random module

This module contains functions to generate random numbers between two values.
Among other uses the random module can be used to display elements randomly from a
list , dictionary etc.

Method Description

random () Does not accept any argument.Returns a


floating point random number in the range 0.0
to 1.0(upper limit not included)

randint() Accept two numbers (a &b) and returns a


random integer between the two numbers(a and
b inclusive)

Page 41
randrange() Accepts three arguments as
range(start,stop[,step]) .Third one is optional
with default value 1.Returns a random integer in
the range.

1. random()

This function generates a random number between 0.0 and 1.0(not including) . It des
not accept any argument in the brackets.

Example:

import random

print(random.random())

Output-0.7489153508852794

In order to get a larger number or use it as part of a larger calculation, we can multiply
it by an integer.

Example -To generate a number between 1.0 and 10.0:

import random

print(random.random()*10)

Output-7.168087410165594

2. randitn(x,y)

Page 42
The randint() function accepts two arguments and generates a random number between
the two. For example if the arguments are x and y it will generate an integer value
between x and y.

Example:

import random
print(random.randint(2,7)) #will generate a number between 2 and 7, inclusive

Output:

We can also use the randint() function to generate and assign a random number to a
variable. For example; p=randint(9,11), will assign a value between 9 and 11 to the
variable p.

The randint() function can be implemented in numerous ways.

Example:

Consider the code below:

import random
y=random.randint(4,9) #y will be assigned a value between 4 and 9
for i in range(1,y+1): # depending on the value of y, the loop will run from
1 to n where 4<=n<=9
print(i, end=" ")

In the above code y can have value between 4 and 9. Thus the loop will run from 1 to
n, n being in the range 4-9. Thus we can have any one of the following outputs in this
case:

option 1: 1 2 3 4

Page 43
option 2: 1 2 3 4 5

option 3: 1 2 3 4 5 6

option 4: 1 2 3 4 5 6 7

option 5: 1 2 3 4 5 6 7 8

option 6: 1 2 3 4 5 6 7 8 9

Here the minimum value generated for y is 4 and maximum 9.

Let's take a look at another example:

import random
x=random.randint(2,4)
y=random.randint(4,7)
for i in range(x,y+1):
print(i, end=" ")

There are two random numbers generated in the above code, x and y. The minimum and
maximum values that the variables x and y will assume are as follows:

| x | y

_________________

min | 2 | 4

_________________

max | 4 | 7

Thus the loop will give output starting with anything between 2 - 4 and ending between
4-7.

Page 44

3. randrange (x,y,z)

This function also generates a random integer between x and y but there is a step value,
z which has a default value of 1. Also the step parameter is optional.

Example:

import random
y=random. randrange (4,20,2) # y will be assigned value between 4 and 20 which are
even as step is 2. So it can be

#4,6,8,10,12,14,16,18,20

print(y)

Output:

18

In the above example y will be assigned a value between 4 and 20 in multiples of 2.

Statistics Module

This module offers functions that perform statistical tasks on numeric data. There are
numerous functions in this module. We shall cover three of these, viz, mean(),
median( )and mode().

Method Description

mean() Calculate the mean(average) of a set of values or


data

Page 45
median() Calculates the median(middle value) of a set of
values or data

mode() It returns the value with the most number of


occurences in a set of values or data

​ 1. mean()

This function will return the average of a list of values.

Example:

import statistics
list1=[3,4,20,7,9,8]
print(statistics.mean(list1))

Output-8.5

In the above code the numbers in the list are are added and then divided by 6 to give
average or mean.

2. median()

The function median() returns the middle value in a list of given numbers/data by first
arranging them in ascending order and then finding the exact middle element.

​ Example:

import statistics
list1=[3,4, 7,9,8] #when ordered, the list will be; 3,4,7,8,9 and the
middle is 7
print(statistics.median(list1))

​ Output-7

​ If the list contains even numbers then the two middle numbers (after arranging the
list) are added and divided by two to get the median.

Page 46

Example:

import statistics
list1=[2,15,4,6,8,9] #ordered list will be : 2,4,6,8,9,15 and the middle two
values are 6,8. So median=(6+8)/2=7
print(statistics.median(list1))

Output-7.0

​ 3. mode()

This function returns the value in a given list that occurs the most number of times.

​ Example:

import statistics
list1=[2,15,4,6,8,9,4,9,8,4,9,9,7]
print(statistics.mode(list1))

​ Output-9

​ NOTE: If there are more than one values in the list having same number of
occurrences, then this function returns the first number.

​ Example:

import statistics
list1=[2,15,4,6,8,9,4,9,8,4,9,9,7,4] # 4 and 9 each occur four times in the list
print(statistics.mode(list1))

Output-4

Page 47
Unit III: Society, Law and Ethics – I
Topics covered
 Digital Footprints
 Digital society and Netizen: net etiquettes, communication etiquettes, social media etiquettes
 Data protection: Intellectual Property Right (copyright, patent, trademark), violation of IPR
(plagiarism, copyright infringement, trademark infringement), open source software and licensing
(Creative Commons, GPL and Apache)
 Cyber-crime: definition, hacking, eavesdropping, phishing and fraud emails, ransomware, preventing
cyber crime

Introduction
We are living in the era called information age where we see that most our activities are technology-
influenced such as online payment, creating or development of own piece of art. With the reach of
technology to our day to day life, there has been a paradigm shift, and it has also raised specific issues and
problems related to society, ethics and law. This creates the significance of learning the net etiquettes and
related knowledge on cyber safety.
Digital Footprints
Digital Footprints are the records and traces individuals leave behind as they use the Internet. Your
interaction on social media, your friend circle on social media sites, site you visits, online purchase, location
visited through Facebook check-ins. etc. all make up your Digital Footprints.
Digital footprints are also referred to as "digital tattoos". Digital footprints get created actively and passively.
An active digital footprint includes data that you intentionally submit online, e.g., Sending an email, sending
messages online, posting a social media post, replying to post or commenting online etc.
A passive digital footprint gets created through your data trail that you unintentionally leave online. For
example, when you visit a website, the web server may log your IP address, which identifies your Internet
service provider and your approximate location.
Digital society and Netizen
Digital society reflects the growing trend of using digital technologies in all spheres of human
activities. But while online, all of us need to be aware of how to conduct ourselves, how best to relate with
others and what ethics, morals and values to maintain. Anyone who uses digital technology along with
Internet is a digital citizen or a netizen. Being a good netizen means practicing safe, ethical and legal use of
digital technology. A responsible netizen must abide by net etiquettes, communication etiquettes and social
media etiquettes.
 Net Etiquettes:
It refers to online manners while using Internet or working online. While online, you should
be courteous, truthful and respectful of others. Following lines list basics rules of netiquettes.

1. Refrain from personal abuse. If you disagree to something, you may express robust
disagreement, but never call them names or threaten them with personal violence.
2. Never spam. That is, don't repeatedly post the same advertisement for products or services.
3. Write clearly and concisely. On a site that has many non-native English speakers, avoid using slang
they may not understand.
4. Always post correct content in respectful language. Remember that your posts are
public. They can be read by your friends, your siblings, your parents, or your teachers.
5. In a discussion forum, stick to the topic. Don't post about football in a hair-care forum
or about hair care in a gardening forum!
6. Never expect other people to do your homework for you. Never ask for or expect that

Page 48
your complete homework solution will be made available to you. Also, while asking for help, include
details of what attempts you've made to solve the problem. It will save
time and also show people that you are making an effort to help yourself,
7. Do not post copyrighted material to which you do not own the rights. It is plagiarism
If you need to use the copy righted material, then follow these rules :
(a) Ask permission from the copyright holder.
(b) Enclose the copyrighted information that you are using and cite its source. Hing this will put you
and the site in legal trouble.
 Communication Etiquettes:
 Email Etiquettes:
It is important that whether for business or personal use that we should follow the basics of email
etiquettes. Following lines enlist some important email etiquette that everyone needs to be aware
of and follow.
1. Be concise and to the point. Do not make an e-mail longer than it needs to be. A long e-mail
can be very discouraging to read.
2. Use proper spelling, grammar & punctuation. It is important for conveying the
message properly. Improper spelling, grammar and punctuation give a bad impression.
3. Use proper structure & layout. Since reading from a screen is more difficult than reading from
paper, the structure and lay out is very important for e-mail messages Use short paragraphs and
blank lines between each paragraph. When making points, number them or mark each point as
separate to keep the overview.
4. Do not write in CAPITALS (Case Sensitivity). IF YOU WRITE IN CAPITALS IT
SEEMS AS IF YOU ARE SHOUTING. This can be highly annoying and might trigger an
unwanted response. Therefore, try not to send any email text in capitals.
5. Add an e-mail disclaimer. Disclaimers in your internal and external mails can help protect you
from liability if you inadvertently forwarded a virus by e-mail.
6. Handle abbreviations and emoticons with care. In business e-mails, use of abbreviations (such
as BTW for by the way) and emoticons (smiley faces) is generally inappropriate.
7. Gender Sensitivity. If you are writing to a person unknown to you, your email should be
gender neutral.
 Social Media Etiquettes:
Rules to be followed while working on social networking sites
• Don't give or post any personal information.
• Never give out your password to anyone except your parent or guardian.
• When you are choosing a social networking site, privacy issues should be considered.
• Add only those people as friends to your page whom you know in real life.
• Delete any unwanted messages, inappropriate comments and immediately report those
comments to the networking site.
Care about the share: Social media wants us to share as much as we can, but “Never share your
passwords, private/personal information, your location, etc.” Always use strong passwords that
are difficult to guess.
• Privacy Matters: Regularly check your privacy settings on social media and always think before
posting because it spreads all over the internet. Respect privacy of others: Ask your friends'
permission before uploading their photos and videos.
• Keep everything updated: Most security breaches on the internet happen as the software is not
up-to-date. Be vigilant about updating software like apps, anti-viruses and the browsers.
• Be aware of Spams: It is the modern version of junk mails. Learn the difference between real
mails and messages and dodgy things with unreliable links. Always be suspicious of emails with
hyperlinks.
Data Protection:
Data or Information forms the intellectual capital for a person or body. There are many ethical issues
involved with the usage and availability of information online. Some common ethical issues are:
Page 49
 Intellectual Property Rights: Intellectual property rights are the rights of the
information to decide how much information is to be exchanged shared or distributed. Also it
gives the owner a right to decide the price for doing (exchanging / sharing/distributing) so.
The creator/producer of the information is the real owner of information. And the owner has
every right to protect his/her intellectual property. To protect one's intellectual property rights one
can get information copyrighted or patented or use trademarks.
 Copyright: A copyright is a collection of rights automatically vested to someone who has created
an original work. The copyright owner has the authority to keep or to transfer the rights to
use/distribute, individually to one or more people, or to transfer them collectively to one or more
people.
 Patent: A patent is a grant of exclusive right to the inventor by the government. Patents give the
holder a right to exclude others from making, selling, using or importing a particular product or
service, in exchange for full public disclosure of their invention.
 Trademark: A trademark is a word, phrase, symbol, sound, colour and/or design that identifies
and distinguishes the products and goods of one party from those of others.
 Violation of Intellectual Property Rights:
 Plagiarism: Plagiarism is stealing someone else's intellectual work (can be an idea, literary work
or academic work etc.) and representing it as your own work without citing the source of
information.
Any of the following acts would be termed as Plagiarism:
o Using some other author's work without giving credit to the author.
o Using someone else's work in incorrect form than intended originally by the author/creator.
o Modifying/lifting someone's production such as music-composition etc. without attributing it to
the creator of the work.
o Giving incorrect or incorrect source of information i.e., wrongful citation.
o Failure in giving credit or acknowledging the contribution of others in a collaborative effort, to
which you are also part of.
 Copyright Infringement: When someone uses a copyrighted material without permission, it is
called copyright infringement. Copyright infringement is the use or production of copyright-
protected material without the permission of the copyright holder.
 Trademark Infringement:
Trademark Infringement means unauthorised use of other’s trademark on products and services.
An owner of a trademark may commence legal proceedings against
someone who infringes its registered trademark
 Open Source Software and Licensing:
Open source software can be feely used in terms of making modifications, constructing
business models around the software and so on. But it doesn’t have to be free of charge. Here
the company constructing the business models around open source software may receive
payments concerning support, further development.
 Creative Commons license:
Creative Commons is a non-profit organisation (https://
creativecommons.org/) that aims to build a publically
accessible global platform where a range of creative and academic works are shared freely.
Any one across the globe can access them, share them, and even use them for creating their
own work out of it without infringing the copyright or Intellectual Property rights of the
owners. In fact, it gives proper attribution to the owners.
A Creative Commons license is one of several public copyright licenses that enable the free
distribution of an otherwise copyrighted "work". A Creative Commons license is used when an
author wants to give other people the right to share, use, and build upon a work that the author
has created. Creative Commons provides an author flexibility (for example, they might choose
to allow only non-commercial uses of a given work) and protects the people who use or

Page 50
redistribute an author's work from concerns of copyright infringement as long as they abide by
the conditions that are specified in the license by which the author distributes the work.
 GPL
The GNU General Public License (GNU GPL or simply GPL) is a series of widely used free
software licenses that guarantee end users the four freedoms to run, study, share, and modify
the software.
 Apache
The Apache License is a permissive free software license written by the Apache Software
Foundation (ASF). It allows users to use the software for any purpose, to distribute it, to
modify it, and to distribute modified versions of the software under the terms of the license,
without concern for royalties.

Cyber-crime
Cyber-crime is any criminal offense that is facilitated by, or involves use of electronic communications of
information system including any electronic device, computer or the Internet.
 Hacking
Hacking refers to gaining unauthorised access to a network or computer or digital files, with
an intention to steal or manipulate data or information or to install malware.
Hacking can be ethical or unethical. Ethical Hacking is done
on behalf of a company, which wants to find out the loopholes
in the system in context to security. Unethical Hacking, on the
install malware, other hand, is done in order to harm or cause loss to an individual or a
company.
 Eavesdropping:
Unauthorised monitoring of other people’s communications is called eavesdropping. It
is a passive attack in which an attacker gains access to the communication medium through
which some communication is taking place and then listens to the communication and gets
information about the content of the message.
 Phishing:
Phishing is the practice of attempting to acquire sensitive, information from individuals over
the internet, by means of deception. Phishing attacks are the practice of sending fraudulent
communications that appear to come from a reputable source. It is usually done through email.
The goal is to steal sensitive data like credit card and login information, or to install malware
on the victim's machine.
 Fraud emails:
Email fraud (or email scam) is intentional deception for either personal gain or to
damage another individual by means of email.
 Ransomware:
Ransomware is a type of malware, or malicious software, which locks all known files
through strong encryption and prevents users and administrators from accessing their
networks, systems or data.
Ransomware effectively denies access to organizational data by encrypting it and
withholding decryption tools until a ransom is paid. Paying the ransom assumes the
bad guys are ethical, but there is no guarantee that paying will get an organization the
decryption key they need to access their data. The sole objective of ransomware is to
make sure that people cannot access their electronic files.
 Preventing Cyber-crimes:
The challenges of cyber crime can be mitigated with the twin approach of being alert
and taking legal help.Following points can be considered as safety measures to reduce
the risk of cyber crime:
• Take regular backup of important data.

Page 51
• Use an antivirus software and keep it updated always.
• Avoid installing pirated software. Always download software from known and secure
(HTTPS) sites.
• Always update the system software which include the Internet browser and other
application software
• Do not visit or download anything from untrusted websites.
• Usually the browser alerts users about doubtful websites whose security certificate
could not be verified; avoid visiting such sites.
• Use strong password for web login, and change it periodically. Do not use same
password for all the websites. Use different combinations
of alphanumeric characters including special characters. Ignore common words or
names in password.
• While using someone else’s computer, don’t allow browser to save password or auto
fill data, and try to browse in your private browser window.
• For an unknown site, do not agree to use cookies when asked for through a Yes/No
option.
• Perform online transaction like shopping, ticketing, and other such services only
through well-known and secure sites.
• Always secure wireless network at home with strong password and regularly change
it.

MCQ
1. You are planning to go for a vacation. You surfed the Internet to get answers for the following
queries —
a) Places to visit
b) Availability of air tickets and fares
c) Best hotel deals
d) All of these
Which of your above mentioned actions might have created a digital footprint?
2. A responsible netizen must abide by __________
a. Net etiquettes
b. Communication etiquettes
c. Social media etiquettes
d. All of the above
3. Which of the following activity is an example of leaving Active digital footprints?
a) Surfing internet
b) Visiting a website
c) Sending an email to a friend
d) None of the above
4. Legal term to describe the rights of a creator of original creative or artistic work is called ……..
a) Copyright
b) Copyleft
c) GPL
d) BSD
5. A software that can be freely accessed and modified is called
(a) Synchronous Software
(b) Package Software
(c) Open Source Software
(d) Middleware

Page 52
6. Data which has no restriction of usage and is freely available to everyone under Intellectual
Property Rights is categorised as :
(a) Open Source
(b) Open Data
(c) Open Content
(d) Open
7. Which of the following is an advantage of 'open source software ?
(a) You can edit the source code to customise it.
(b) You need to be an expert to edit code.
(c) You have to pay.
(d) Can sometimes be too generic for specialist purposes.
8. Which of the following is a disadvantage of 'open source software?
(a) High quality software with lots of features
(b) Not as customizable
(c) May not have been tested as much as proprietary software, so might have bugs
(d) You can edit the source code to customise it
9. Which of the following would be a creative work protected by copyright?
(a) A list of all Indian President names
(b) A portrait of your family
(c) A song you wrote
(d) The name of your pet dog
10. Which of the following is not a type of cybercrime?
(a) Data theft
(b) Forgery
(c) Damage to data and systems
(d) Installing antivirus for protection
11. What is meant by the term 'cyber-crime'?
(a) Any crime that uses computers to jeopardise or attempt to jeopardise
(b) The use of computer networks to commit financial or identity fraud
(c) The theft of digital information
(d) Any crime that involves computers and networks
12. The rights of the owner of information to decide how much information is to be
shared/exchanged/distributed, are collectively known as ___ (IPR).
(a) Intelligent Property Rights
(b) Intellectual Property Rights
(c) Interactive Property Rights
(d) Instance Property Rights
13. Stealing someone else's intellectual work and representing it as own, is called
(a) Intellectual steal
Page 53
(b) Pluckism
(c) Plagiarism
(d) Pickism
14. The information/art/work that exists in digital form is called
(a) e-work
(b) e-asset
(c) digital property
(d) e-property
15. Every activity you perform on the Internet is saved for how long?
(a) one month
(b) one year
(c) as per my setting
(d) forever
16. The digital trail which gets created as a person's Internet usage using computers, smartphones,
gaming consoles etc. is called -
(a) Internet data
(b) Internet trail
(c) Digital footprint
(d) e-footprint
17. Gaining unauthorised access to a network or computer or digital files with malicious called
(a) Cracking
(b) Hacking
(c) Banging
(d) Phishing
18. Legal term to describe the rights of a creator of original creative or artistic work is called
(a) Copyright
(b) Copyleft
(c) GPL
(d) none of these
19. OSS stands for ……………
(a) Open Source Software
(b) Open Software Source
(c) Open Software Service
(d) Open Service Software

Page 54
20. Any fraudulent business practice that extracts money from an unsuspecting, ignorant person is called
a ………….
(a) Plagiarism
(b) Scam
(c) Hacking
(d) Phishing
21. The attack that focuses on capturing small packets from the network transmitted by other computers and
reading the data content in search of any type of information is ……………
(a) Phishing
(b) Eavesdropping
(c) Scam
(d) PC intrusion
22. Which of the following is / are source of spreading viruses from one computer to another?
(a)Email
(b) Infected data
(c ) Infected programs
(d) All of the above
23……….. are the attempts by individuals to obtain confedential information from you through an original
looking site and URL.
(a) Phishing Scam
(b) Spoofing
(c) Eavesdropping
(d) Pharming
24……… is an attempt where a hacker tries to divert network traffic to a bogus site.
(a) Phishing Scam
(b) Spoofing
(c) Eavesdropping
(d) Pharming attack
25. A research student is excepted to write a thesis on a topic. The student browses Internet for the topic and
luckily finds it on the internet. He copies and submits the entire thesis as his own research work. Which of
the following activities appropriately categorises the act of the writer ?
(a) Spamming
(b) Phishing
( c) Plagiarism
(e) Trojan

ANSWERS
1. d) All of these
2. d. All of the above
Page 55
3. c) Sending an email to a friend
4. a) Copyright
5. c) Open Source Software
6. (b) Open Data
7. (a) You can edit the source code to customise it.
8. (c) May not have been tested as much as proprietary software, so might have bugs
9. (c) A song you wrote
10. (d) Installing antivirus for protection
11. (d) Any crime that involves computers and networks
12. (b) Intellectual Property Rights
13. (c) Plagiarism
14. (c) digital property
15. (d) forever
16. (c) Digital footprint
17. (b) Hacking
18. (a) Copyright
19. (a) Open Source Software
20. (b) Scam
21. (b) Eavesdropping
22. (d) All of the above
23. (a) Phishing Scam
24. (d) Pharming attack
25. ( c) Plagiarism

Page 56
Cyber Safety

Cyber safety is trying to be safe on the internet and is the knowledge of maximizing the
user's personal safety and security risks to private information and property associated with
using the internet.

Safely browsing the web: Protecting yourself by securing your devices, software and
connections is important. There are potential risks involved in doing things online, but by
making smart choices you can reduce that risk.

By using a combination of preventative measures and making good choices online you can
stay safe when browsing the web.

Update software: Protect yourself before you start browsing the web by making sure that
your operating system, web browser, security software, browser plugins (like Java or
Adobe products) and other applications are up-to-date.

Protect web browser: Most web browsers will give you warnings when they detect you
visiting a malicious website or possibly being exposed to malicious content. Pay attention
to these warnings – they can help protect you from malware, phishing and identity theft.

Use safe behaviour:

Use the following advice when browsing the web to significantly reduce your risk of being
a victim of cybercrime:

 Use strong unique passwords online.


 Only download files and applications from websites that you trust, such as from official
app stores or legitimate organisations..
 Think carefully before clicking on links in email, messages or on social networking
sites. Don’t click on links in messages if you don’t know the sender or if the message is
unexpected.
 If you do not recognize or trust the address, try searching for relevant key terms in a
web browser. This way you can find the article, video, or webpage without directly clicking
on the suspicious link.
 Expand shortened URLS to check if they are safe. Short URLs are often used in social
media.
 Be wary of offers that seem too good to be true. Leave websites that ask for your
personal or banking details in return for money – these are scams.
Page 57
 Don’t agree to friend requests from people you don’t know on social media networks -
people are not always who they say they are.

Identity protection: Your personal identity is important as it defines who you are. Your
identity includes your personal information; information such as name, address, contact
information, bank account, credit card numbers, and social security numbers should all be
kept private.

Confidentiality: Confidentiality is roughly equivalent to privacy. Measures undertaken to


ensure confidentiality are designed to prevent sensitive information from reaching the
wrong people, while making sure that the right people can in fact get it: Access must be
restricted to those authorized to view the data in question. It is common, as well, for data to
be categorized according to the amount and type of damage that could be done should it fall
into unintended hands. More or less stringent measures can then be implemented according
to those categories.
Sometimes safeguarding data confidentiality may involve special training for those privy to
such documents. Such training would typically include security risks that could threaten
this information. Training can help familiarize authorized people with risk factors and how
to guard against them. Further aspects of training can include strong passwords and
password-related best practices and information about social engineering methods, to
prevent them from bending data-handling rules with good intentions and potentially
disastrous results.
A good example of methods used to ensure confidentiality is an account number or routing
number when banking online. Data encryption is a common method of ensuring
confidentiality. User IDs and passwords constitute a standard procedure; two-factor
authentication is becoming the norm. Other options include biometric verification and
security tokens, key fobs or soft tokens. In addition, users can take precautions to minimize
the number of places where the information appears and the number of times it is actually
transmitted to complete a required transaction. Extra measures might be taken in the case of
extremely sensitive documents, precautions such as storing only on air gapped computers,
disconnected storage devices or, for highly sensitive information, in hard copy form only.

Social networks: Social networking is playing a huge role in our life. Now a days
businesses heavily rely on social media for their promotions and sale of their products. But
on the other hand lot of frauds are being done using social media. Person shouldn’t accept
any random request. There are lot of fake accounts on social media which might be hackers
they might intrude in your PC.

Cyber bullying
Cyberbullying is a form of bullying or harassment using electronic means. It includes
any insulting, degrading or intimidating online behaviour like repeated posting of
rumours, giving threats online, posting the victim’s personal information, comments
aimed to publicly ridicule somebody etc.

Page 58
Cyber Troll
A cyber troll is a person who starts flame wars or intentionally upsets people on the
Internet by posting inflammatory and digressive, extraneous, or off-topic messages in
an online community with the intent of provoking readers into displaying emotional
responses and normalizing tangential discussion, either for the troll's amusement or a
specific gain.

Network Security: Network security is concerned with protection of our device as well
as data from illegitimate access or misuse.

Malware (Malicious software): Malware is any software developed with an intention


to damage hardware devices, steal data, or cause any other trouble to the user. Viruses,
Worms, Ransomware, Trojans, and Spyware are some of the kinds of malware.

1. Virus: A virus is a piece of software code created to perform malicious activities


and hamper resources of a computer system like CPU time, memory, personal files, or
sensitive information. a computer virus infects other computer systems that it comes into
contact with by copying or inserting its code into the computer programs or software
(executable files). A virus remains dormant on a system and is activated as soon as the
infected file is opened (executed) by a user. Some of the most common intentions or
motives behind viruses include stealing passwords or data, corrupting files, spamming
the user’s email contacts, and even taking control of the user’s machine. Some well-
known viruses include CryptoLocker, ILOVEYOU, MyDoom, Sasser and Netsky,
Slammer, Stuxnet, etc.
2. Worms: Worms are also malicious software but they are standalone programs that
are capable of working on its own. Whereas a virus needs human trigger for replication
(i.e. when a user pens/executes the infected file), a worm replicates on its own and can
spread to other computers through the network. Some prominent examples of worms
include Storm Worm, Sobig, MSBlast, Code Red, Nimda, Morris Worm, etc.
3. Trojan: A Trojan is a malware, that looks like a legitimate software and once it
tricks a user into installing it, it acts pretty much like a virus or worm. However, a Trojan
does not self-replicate or infect other files, it spreads through user interaction such as
opening an email attachment or downloading and executing a file from the Internet.
Some Trojans create backdoors to give malicious users access to the system.
4. Adware: An Adware is a malware that is created to generate revenue for its
developer. An adware displays online advertisements using pop-ups, web pages, or
installation screens.
5. Trojan: A Trojan is a malware, that looks like a legitimate software and once it
tricks a user into installing it, it acts pretty much like a virus or worm. However, a Trojan
does not self-replicate or infect other files, it spreads through user interaction such as
opening an email attachment or downloading and executing a file from the Internet.
Some Trojans create backdoors to give malicious users access to the system.

Page 59
6. Adware: An Adware is a malware that is created to generate revenue for its
developer. An adware displays online advertisements using pop-ups, web pages, or
installation screens.

Preventive measures against malware


 Using antivirus, anti-malware, and other related software and updating them on a
regular basis.
 Configure your browser security settings
 Always check for a lock button in the address bar while making payments.
 Never use pirated on unlicensed software. Instead go for Free and Open Source
Software (FOSS).
 Applying software updates and patches released by its manufacturers.
 Taking a regular backup of important data.
 Enforcing firewall protection in the network.
 Avoid entering sensitive (passwords, pins) or personal information on unknown or
public computers.
 Avoid entering sensitive data on an unknown network (like Wi-Fi in a public
place) using your own computer.
 Avoid clicking on links or downloading attachments from unsolicited emails.
 Scan any removable storage device with an antivirus software before transferring data
to and from it.
 Never share your online account or banking password/pins with anyone.
 Remove all the programs that you don’t recognise from your system.
 Do not install an anti-spyware or antivirus program presented to you in a pop-up or ad.
 Use the pop-up windows ‘X’ icon located on the top-right of the popup to close the
ad instead of clicking on the ‘close’ button in the pop-up. If you notice an installation has
been started, cancel immediately to avoid further damage.
Antivirus: Antivirus is software that detects and removes viruses as well as other malware
from a system.

E-waste:
E-waste or electronic waste is used to describe all discarded electric and electronic
devices. All electronic items are made up of plastics and contain traces of rare metals. If
e-waste is not handled properly then chances of all the pollutants leaking into the
atmosphere, contaminating the soil and water resources is there.

E-waste Disposal Techniques:

Page 60
• Sell/Donate your e-waste to someone in need.
• Dispose e-waste to certified e-waste recycler
• Refurbish/Reuse the e-waste
• Segregate if possible different kinds of e-waste and give to appropriate recyclers.
• Give back e-waste in buyback or exchange schemes or at company recommended drop
points

Health concerns related to the usage of technology


 Using improper posture while using computer/mobile/device for a long time can
cause serious health issues such as fatigue, backaches, neck and shoulder pains.
Ergonomically designed furniture/products can reduce the strain on the body.
 Spending too much time on the internet can be addictive
 Social bonds can become weak
 Children tend to be attracted towards online games rather than actually playing
outdoors which can lead to long term health issues

Indian Information Technology Act 2000 (ITA-2000 or IT act):


It is the primary law in India dealing with cyber law, cybercrime and electronic
commerce. Some of the major sections are:
SECTI OFFENCE PENALTY
ON
66A Sending of offensive
messages
67A Publishing images Imprisonment up to 7 years and/or fine up to Rs.
containing 10,00,000.
sexual acts
67B Publishing child porn or Imprisonment up to 5 years and/or fine up to
predating children online Rs. 10,00,000 on 1st conviction. Imprisonment
up to 7 years and/or fine up
to Rs. 10,00,000 on 2nd conviction.
67C Failure to maintain records Imprisonment up to 3 years and/or fine up to Rs.
2,00,000.
68 Failure/Refusal to comply Imprisonment up to 7 years and/or possible fine.
with
orders
69 Failure/Refusal to decrypt Imprisonment up to 3 years and/or fine up to Rs.
data 1,00,000.
70 Securing access or Imprisonment up to 10 years and/or fine.
attempting to
secure access to protected
system
71 Misrepresentation Imprisonment up to 3 years and/or fine up to Rs.
1,00,000.

Page 61
Technology & Society: Gender and disability issues while teaching and using
computers

Whenever we are designing a software or a hardware product/service care should be


taken to see that it is usable by people with different background, gender,
nationalities, differently abled persons etc.
For example-
 If you are designing a hardware product, then it should be usable by both the
sexes as well as by left- handed and right handed persons also.
 If you are designing a software/terminal designed to be used by the general public
such as a kiosk/ATM machine, it should be in multiple languages. It should have features
such as voice controlled operations/touch screen operations such that even people with
visual disabilities can be able to operate it.
 Whenever you are designing a product to be used by general public, preferably
use gender neutral language for the user interface.
 Avoid using language/content that discriminates especially
based on the user's gender/background/ physical abilities etc.

Short Answer Question

1. What is cyber safety?


Ans: Cyber safety refers to the safe and responsible use of internet to ensure
safety and security of personal information. It also includes not creating threat
for anyone else’s information.
2. What is cyber crime?

Any illegal activity done with the help of electronic communication system,
computer and internet is called cyber crime.
3. What is virus? What can it do to our computer?
Virus stands for Vital Information Resource Under Seize. It a computer
software that can harm your computer. It can harm our computer in following
ways:
It can delete files.
It can corrupt operating system.
It can slow down the computer.

Page 62
4. What should we practise confidentiality of information?
1. Use firewall wherever possible.
2. Control browser settings to block tracking.
3. Browse privately wherever possible.
4. Be careful while posting on Internet.
5. Ensure Safe sites while entering crucial information.
6. Carefully handle emails.
7. Do not give sensitive information on wireless networks.
8. Avoid using public computers.
5. How can we safely browse the web?
We can safely browse the web by keeping following things in mind:
1.Try to avoid opening websites which are not secure (without HTTPS).
2.Don’t provide your email, contact number , credit card/debit card
information , address and other such information on websites/apps you are
not fully sure of.
3.Don’t download softwares or other files from every website.
6.Which types of gender and disability issues are created while teaching and
using computer?

1.There is decline in women in the field of computer and this has made gender gap for
using computer and males are more interested in the usage of computer.
2.The disability issues while using computer for those individuals with blindness find it
difficult to access the computer monitor and some individuals with low visions also face
the same problem.
3. Some individuals have hearing or speech impairments in such case they can
use standard keyboard sign language devices are used for this purpose.

7.What are malware? What type damages can they cause to your computer?

"Malware" is short for malicious software and used as a single term to refer to virus,
spy ware, worm etc. Malware is designed to cause damage to a stand-alone computer or
a networked pc. So wherever a malware term is used it means a program which is
designed to damage your computer it may be a virus, worm or Trojan.

8.What is the need for secure passwords?

A password that is difficult to detect by both humans and computer programs,


effectively protecting data from unauthorized access. A strong password consists of at
least six characters (and the more characters, the stronger the password) that are a
combination of letters, numbers and symbols (@, #, $, %, etc.) if allowed. Passwords

Page 63
are typically casesensitive, so a strong password contains letters in both uppercase and
lowercase. Strong passwords also do not contain words that can be found in a dictionary

9. What are different types of threats to computer security?


A Threat is a potential violation of security. When a threat is actually executed, it
becomes attack. Those who execute such actions, or cause them to be executed are
called attackers. Some common threats the average computer user faces everyday are
1. Viruses 2. Worms 3. Trojans 4. Spyware 5. Adware 6. Spamming 7. PC Intrusion: 8.
Denial of Service 9. Sweeping 10. Password Guessing 11. Phishing

10. What is the significance of Firewall in a computer‟s security scheme?


An Internet firewall is a device or a software that is designed to protect the computer
from data and virus.

Page 64
Kendriya Vidyalaya Sangathan,Ernakulam Region
Sample Question Paper
COMPUTER SCIENCE
SET-I
CLASS XI

Maximum Marks: 35 Time: 2 hours

General Instructions
 The question paper is divided into 3 sections – A, B and C
 Section A, consists of 7 questions (1-7). Each question carries 2 marks.
 Section B, consists of 3 questions (8-10). Each question carries 3 marks.
 Section C, consists of 3 questions (11-13). Each question carries 4 marks.
 Internal choices have been given for question numbers 7, 8 and 12.

Section -A
Each question carries 2 marks
1 How are Tuples different from Lists when both are sequences? 2

2 (i) What do you mean by eavesdropping? 2


(ii) Write any two tips to safely browse internet.

3 (i) What is the length of the tuple shown below? 2

T = (((("a", 1), "b", "c"), "d", 2), "e", 3)

(ii) Find the output of the following code

import math
k=math.pow (2,4)
print(k)

4 (i)Name any 2 social networking apps 2


(ii) A computer program encrypts (lock by password) all your important
documents on the computer and asks you to deposit money in a certain
bank account to decrypt (unlock) those files. What that malicious
program is known as?

5 How can we hide our identity on the internet? (Any two points) 2
1
6 What are nested Lists? Give an example 2

7 What is cyber Bullying? Give an example to explain it. 2

OR

(i) Which of the following is not a type of cybercrime?


a)Unauthorized account access
b) Email spoofing and spamming
c)Mass attack using Trojans as botnets
d) Report vulnerability in any system
(ii) A __________ is a computer program that can replicate itself and
spread
from one computer to another.
i) Antivirus ii) Pendrive iii) Mouse iv) Computer Virus

SECTION – B
Each question carries 3 marks
8 (i) Predict the output of the following code: 3
L1=[16,52,14]
L2=["Hello","Good",56]
L3=L1
L3.append("Morning")
print(L3)
L1.extend(L2)
print(L1)
(ii) Which is the correct form of declaration of dictionary?
a) Day={1:’monday’,2:’tuesday’,3:’wednesday’}
b) Day=(1;’monday’,2;’tuesday’,3;’wednesday’)
c) Day=[1:’monday’,2:’tuesday’,3:’wednesday’]
d) Day={1’monday’,2’tuesday’,3’wednesday’]

OR

(i) List is said to be a mutable datatype. Explain the reason


(ii)Write a program to accept a list of numbers and find the sum of
all the numbers in the list.

9 Write a program to accept a list of numbers and replace all numbers 3


greater than or equal to 33 with “PASS” and less than 33 with
“FAIL” eg: if the accepted list is [23,45,56,29,90,33], it should be
replaced as [“FAIL”,” PASS”,” PASS”,” FAIL”,” PASS”,” PASS”]

10 (i) Expand IPR 3


(ii) Indian IT Act came to existence in ----------
2
(iii) Which of the following is not a proper e-waste disposal
technique?
a) Dismantling
b) Segregation
c) Recycling
d) Throwing away
Section C
Each question carries 4 marks
11 (i)Write a program to accept a string tuple and print all those strings 4
which are palindrome in it.
eg: if the accepted tuple is
(‘hello’,’level’,’good’,’morning’,’malayalam’) output should be
level
Malayalam

(ii) What will be the output of following code?


t1 = ("computer science", "informatics practices", 2017,
2018)
t2 = ( 15, 21, 26, 88, 9, 33)
print("t1[-3:]:", t1[-3:])
print("t2[1:5]:", t2[1:5])

12 (i) Write a program to accept name and marks of 10 students. 4


Create a dictionary with name as key and marks as values
(ii) Predict the output of the following code:

d1={"Physics":52,"Maths":69,"Chemistry":58}
d2={"Maths":87,"Biology":55,"IP":54}
d2.update(d1)
print(d1)
print(d2)

OR
Ms. Niya, a computer science teacher created the following list
List = [12,15,18,19,45,76,11,28,16]
(i) She wants to know the number of elements in the list.
Which function she should use to get an answer.
(ii) Ms. Niya wants to add two new elements 25,11 in the
last. Which of the following is the correct option?
a. List.append(25,11)
b. List.insert(25,11)
c. List.extend(25,11)
d. List.extend([25,11])

(iii) She wants to remove value 15 from the list. Please


help her to write correct code.
(iv) Help her to write code to display the values of the list
in descending order.

3
13 The school offers wireless facility (Wi-Fi) to the Computer Science 4
students of Class XI. For communication, the network security staff of
the school have a registered URL schoolwifi.edu. On 17 January 2022,
the following email was mass distributed to all the Computer Science
students of Class XI. The email claimed that the password of the
students was about to expire. Instructions were given to go to URL to
renew their password within 24 hours.

(i) Do you find any discrepancy in this email?


(ii) What will happen if the student click on the given URL?
(iii) Is the email an example of cyber crime? If yes, then specify
which type of cyber crime is it
(iv) Is the email an example of Hacking? If yes, then justify your
answer

4
Marking Scheme
COMPUTER SCIENCE
CLASS XI

Maximum Marks: 35 Time: 2 hours

General Instructions
 The question paper is divided into 3 sections – A, B and C
 Section A, consists of 7 questions (1-7). Each question carries 2 marks.
 Section B, consists of 3 questions (8-10). Each question carries 3 marks.
 Section C, consists of 3 questions (11-13). Each question carries 4 marks.
 Internal choices have been given for question numbers 7, 8 and 12.

Section -A
Each question carries 2 marks
1 Tuples are similar to lists in many ways like indexing, slicing, and 2
accessing individual values, but they are different in the sense that
 Tuples are immutable while lists are mutable.
 List can grow or shrink while tuples cannot

2 (i) Eavesdropping is the act of secretly or stealthily listening to 2


the private conversation or communications of others without
their consent in order to gather information
(ii) Only download software from sites you trust. Carefully
evaluate free software and file-sharing applications before
downloading them
Update your operating system regularly
Increase your browser security settings.
Type in a trusted URL for a company's site into the address
bar of your browser to bypass links in an email or instant
message.
Use antivirus protection and a firewall
(Any two)

3 (i) 3 2
(ii) 16.0

4 (i) Ans: Facebook, WhatsApp, Twitter, Instagram, Snapchat, 2


LinkedIn, etc (Any 2 from these)
1
(ii) Ransomware
5  Use Virtual Private Network (VPN) 2
 Use Proxy (Torr Browser has proxy integrated in it)
 Use Incognito Browsing
6 A list can have an element in it, which itself is a list. Such a list is called 2
a nested list.
e.g.
L = [1,2,3,4, [5,6,7],8]

7 Harassing, demeaning, embarrassing, defaming or intimidating 2


someone using modern technologies like social networking sites,
internet, cell phones, etc. is called cyber bullying.
Dev and Jerin had a fight. After fight, Jerin started posting negative
comments about Dev on the facebook. This incident can be considered
as cyber bullying.

OR
(i) d) Report vulnerability in any system
(ii) iv)Computer Virus

SECTION – B
Each question carries 3 marks
8 (i)[16, 52, 14, 'Morning'] (1 mark) 3
[16, 52, 14, 'Morning', 'Hello', 'Good', 56] ( 1 mark)

(ii) option a ( 1 mark)

OR
(i) List is said to be a mutable datatype because individual
elements inside the list can be modified in place at run time.
(1 mark)
(ii) slist=eval(input("Enter a list of numbers:"))
sumlist=0
for ele in slist:
sumlist+=ele
print("Sum of elements=", sumlist)
(2 marks)
9 mark=eval(input("Enter a list of numbers:")) 3
length=len(mark)
for i in range(length):
if mark[i]>=33:
mark[i]="PASS"
else:
mark[i]="FAIL"
print("Modified List=“, mark)
2
10 (i) Intellectual Property Rights 3
(ii) 2000
(iii) Throwing away
Section C
Each question carries 4 marks
11 (i) 4
t1 = eval(input("Enter a tuple of strings:")) ( 2 mark)
for s in t1:
if s==s[::-1]:
print(s)

(ii) t1[-3:]: ('informatics practices', 2017, 2018) ( 2 mark)


t2[1:5]: (21, 26, 88, 9)
12 (i) d={} 4
for i in range(5):
nm=input("Enter name of student:")
mk=eval(input("Enter mark of student:"))
d[nm]=mk
print(d)
(ii) {'Physics': 52, 'Maths': 69, 'Chemistry': 58}
{'Maths': 69, 'Biology': 55, 'IP': 54, 'Physics': 52, 'Chemistry': 58}

OR
(i) len(List)
(ii) List.extend([25,11])
(iii) List.remove(15) or List.pop(1)
(iv) List.sort(reverse=True)
print(List)
13 (i) Yes 4
(ii) If the student clicks on the URL, they will be directed to a fake
website which captures personal information
(iii) Yes. Phishing
(iv) Yes. Hacking is the process of obtaining user’s information
without their consent. By the above process, the hacker will
gain access to users’ username and password without their
knowledge

3
KENDRIYA VIDYALAYA SANGATHAN,ERNAKULAM REGION
CLASS XI – COMPUTER SCIENCE (083)
SET-II
General Instructions
 The question paper is divided into 3 sections – A, B and C
 Section A, consists of 7 questions (1-7). Each question carries 2 marks.
 Section B, consists of 3 questions (8-10). Each question carries 3 marks.
 Section C, consists of 3 questions (11-13). Each question carries 4 marks.
 Internal choices have been given for question numbers 7, 8 and 12.

Section -A
Each question carries 2 marks
1 Given the lists L=[22,7,8,16,9,177,91,56,33] Write output of
i. print(L[5 : 7]) 2
ii. print(L[-7:-2])

2 a Identify the correct option to print the value 58 from the following data: 1
T=(15,28,36,58,41,9,81)

b Suppose d=4,5,6. Write name of datatype d represents? 1

3 a Write a statement in Python to declare a dictionary whose keys are X,Y2, 3.3 and 1
values are Monday, Tuesday and Wednesday respectively.

b What will be the output of following python code 1


>>>d1={"abc":5,"def":6,"ghi":7}
>>>d1["abc"]

4 What we can see on the screen as output 2


m1=['x','y',8,10]
m1.extend([55,44])
print(m1)
m1.append(6)
print(m1)
5 Write the difference between list pop() method and remove() method 2

6 Predict the output: 2


t1=('Mega')*2
print(t1)
print(t1+2)
7 Match the following:
Column A Column B
A Column B Fakers, by offering special rewards or money prize 2
Plagiarism asked for personal information, such as bank account
information
Hacking Copy and paste information from the Internet into
your report and then organise it
Credit card fraud The trail that is created when a person uses the
Internet.
Digital Foot Print Breaking into computers to read private emails
and other files

OR
What is meant by confidentiality of information? List any two best practices for
confidentiality of information?
SECTION – B
Each question carries 3 marks
8 Write a program to accept elements of a list from the user . Multiply elements of the list 3
with 7,if an elements is a multiple of 7 otherwise multiply each element with 4. After
processing , display the elements.

OR

Consider the following list, s=['W','e','a','r', ' ' ,'a', ' ' , 'M','a','s','k']
Write a program to display each character along with its positive index and negative
index.
9 a What are the possible outcome(s) executed from the following code? Also specify the 2
maximum and minimum values that can be assigned to variable N.

import random
NAV = ["LEFT","FRONT","RIGHT","BACK"]
NUM = random.randint(1,3)
NAVG = ""
for i in range(NUM,1,-1):
NAVG = NAVG+NAV[i]
print(NAVG)
b Write the use of import statement in python?

10 What do you understand by Net Ettiquetes? Explain any two such ettiquetes. 3

SECTION – C
Each question carries 4 marks
11 Consider the following list
L=[13,18,20,10,18,23] 4
Write python statements to perform
(a) count number of times the value 18 is repeating
(b)arrange values in descending order
(c) remove the last element
(d)insert 15 at index position 3
12 Consider the following tuple:
r=(7,14,21,23,8,88,5,10)
Write output of :
(a) r[2:6] 4
(b) r[0:7:2]
(c) r[::3]
(d) r[-8:-2]

OR
Consider the following tuples, tuple1 and tuple2:
tuple1 = (23,1,45,67,45,9,55,45)
tuple2 = (100,200)
Find the output of the following statements:
i. print(tuple1.index(45))
ii. print(max(tuple1))
iii. print(tuple1 + tuple2)
iv. print(sorted(tuple1))
print(tuple1)
13 Consider the following dictionary Capital: 4

Capital={"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai", "Rajasthan":"Jaipur"}

Find the output of the following statements:

i. print(Capital.get("Bihar"))
11. print(Capital.items())
iii. print("Maharashtra" in stateCapital)
iv. del stateCapital["Rajasthan"]
print(stateCapital)
Answers
Section -A
Each question carries 2 marks
1 i. [177, 91] ii. [8, 16, 9, 177, 91]

2 a. T[3] 2. tuple
3 a. d1={‘X’:’Monday’, ‘Y2’:’Tuesday , 3.3:’Wednesday’}
b. Key Error

4 ['x', 'y', 8, 10, 55, 44]


['x', 'y', 8, 10, 55, 44, 6]
5 remove( )  Removes the given element from the list. If the element is present
multiple times, only the first occurrence is removed. If the element is not present,
then ValueError is generated
>>> list1 = [10,20,30,40,50,30]
>>> list1.remove(30)
>>> list1
[10, 20, 40, 50, 30]
>>> list1.remove(90)
ValueError:list.remove(x):x not in the list

pop() Returns the element whose index is passed as parameter to this function
and also removes it from the list. If no parameter is given, then it returns and
removes the last element of the list
>>> list1 = [10,20,30,40,50,60]
>>> list1.pop(3)
40
>>> list1
[10, 20, 30, 50, 60]
>>> list1 = [10,20,30,40,50,60]
>>> list1.pop()
60
>>> list1
[10, 20, 30, 40, 50]
6 MegaMega
TypeError: can only concatenate str (not "int") to str
7
Column A Column B
A Column B Copy and paste information from the Internet into
Plagiarism your report and then organise it

Hacking Breaking into computers to read private emails


and other files
Credit card fraud Fakers, by offering special rewards or money prize
asked for personal information, such as bank account
information
Digital Foot Print The trail that is created when a person uses the
Internet.

OR
Confidentiality of Information ensures that only authorized users get access to
sensitive and protected data.
Best practices used to ensure confidentiality are
1.Use of Firewall.
2.Control browser settings to block Tracking.
3.Browse Privately.
4.Be careful while posting on Internet.
5.Ensure safe sites while entering crucial information.
SECTION – B
Each question carries 3 marks
8 h=eval(input("Enetr values")) 3
length=len(h)
for x in range(0,length):
if h[x]%7==0:
h[x]=h[x]*7
else:
h[x]=h[x]*4
print("Elements are ",h)

OR

s=['W','e','a','r', ' ' ,'a', ' ' , 'M','a','s','k']


length=len(s)
for i in range(length):
print("The element ",s[i], "is at indexes ",i, "and" ,(i-length))

9 a i) BACKRIGHT
Max value 3 and minimum value 1 for variable NUM
b When the import is used, it searches for the module initially in the local scope
by calling __import__() function. The value returned by the function is then
reflected in the output of the initial code.
10 Net Ettiquets refers to the proper manners and behaviour we need to exhibit
while being online.
These include :
1. No copyright violation: we should not use copyrighted materials without the
permission of the creator or owner. We should give proper credit to
owners/creators of open source content when using them.
2. Avoid cyber bullying: Avoid any insulting, degrading or intimidating online
behaviour like repeated posting of rumours, giving threats online, posting the
victim’s personal information, or comments aimed to publicly ridicule a victim.
11 (a) L.count(18)
(b) L.sort(reverse=True)
(c) L.pop()
(d) L.insert(3,15)

12 r=(7,14,21,23,8,88,5,10)

Outputs of :

(a) r[2:6]  (21, 23, 8, 88)


(b) r[0:7:2]  (7, 21, 8, 5)
(c) r[::3]  (7, 23, 5)
(d) r[-8:-2]  (7, 14, 21, 23, 8, 88)

OR
tuple1 = (23,1,45,67,45,9,55,45)
tuple2 = (100,200)
Outputs of the statements:
i. print(tuple1.index(45))  print(tuple1.index(45))
ii. print(max(tuple1))  67
iii. print(tuple1 + tuple2)
 (23, 1, 45, 67, 45, 9, 55, 45, 100, 200)
iv. print(sorted(tuple1))
print(tuple1)
 [1, 9, 23, 45, 45, 45, 55, 67]
(23, 1, 45, 67, 45, 9, 55, 45)
13 Capital={"AndhraPradesh":"Hyderabad", "Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}

Outputs of the statements:

i. print(Capital.get("Bihar"))  Patna
ii. print(Capital.items()) 
dict_items([('AndhraPradesh', 'Hyderabad'), ('Bihar', 'Patna'), ('Maharashtra',
'Mumbai'), ('Rajasthan', 'Jaipur')])

iii. print("Maharashtra" in Capital)  True

iv. del Capital["Rajasthan"]


print(Capital)

{'AndhraPradesh': 'Hyderabad', 'Bihar': 'Patna', 'Maharashtra': 'Mumbai'}
KENDRIYA VIDYALAYA SANGATHAN ,ERNAKULAM REGION
SAMPLE QUESTION PAPER TERM 2-SET 3
COMPUTER SCIENCE(CODE:083)
TOTAL CLASS XI
MARKS Time: 2
Hours
35
General Instructions
 The question paper is divided into 3 sections – A, B and C
 Section A, consists of 7 questions (1-7). Each question carries 2 marks.
 Section B, consists of 3 questions (8-10). Each question carries 3 marks.
 Section C, consists of 3 questions( 11-13). Each question carries 4 marks.
 Internal choices have been given for question numbers – 1 , 3, 8 and 12.

SECTION A
Each Question carry 2 marks
QNO QUESTION MARKS
1 A List is declared as L = [5,6,9,8,16,8], What will be the output of the following : 2
(i) print(len(L))
(ii) print(L[2:6])
OR
Write the built in functions for the following:
(i) To find the maximum value from a given list L
(ii) (ii) Reverses the order of elements in the given list
(iii)
2 A tuple is declared as tuple1 = (2,4,6,8,10,12) 2
Write the output of the following:
(i)print(tuple1[1+4])
(ii) print(tuple1[-1])

3 Consider the following dictionary stateCapital: 2


stateCapital =
{"AndhraPradesh":"Hyderabad","Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
Find the output of the following statements:
(i) print(stateCapital.values())
(ii) print("Maharashtra" in stateCapital)
OR
Write the output of the following python statements:
i) >>>math.floor(3.5687)
ii) print(random.randint(2,7))

4 The following functions belongs to which module: 2


(i) fabs()
(ii) randint()
(iii) mode()
(iv) ceil()
(v)
5 Differentiate between active digital footprint and passive digital footprint 2
6 Define IPR .Give one example. 2

7 Name the cyber crime committed in the below cases: 2

(i) Sanush Copied and pasted information from the Internet into his
report and then organise it. And submitted to the teacher as his
own work.
(ii) Breaking into computers to read private emails and other files .

SECTION – B
Each question carries 3 marks

8 What will be the output of the following code segment: 3


myList = [1,2,3,4,5,6,7,8,9,10]
for i in range(0,len(myList)):
if i%2 == 0:
print(myList[i])

OR
What possible outputs(s) are expected to be displayed on screen at the time of
execution of the program from the following code?

import random
x=3
N = random, randint (1, x)
for i in range (N):
print(i, ‘#’, i + i)

a. What is the minimum and maximum number of times the loop will
execute?
b. Find out, which line of output(s) out of (i) to (iv) will not be
expected from the program?
i. 0#1
ii. 1#2
iii. 2#3
iv. 3#4

9 Write a program to enter names of employees and their salaries as input and store them in 3
a dictionary.

10 Write any three health hazards caused due to over usage of digital technologies. 3
Suggest any three safety measures to prevent the same.

SECTION – C
Each question carries 4 marks
11 Consider the following tuples, tuple1 and tuple2: 4
tuple1 = (23,1,45,67,45,9,55,45)
tuple2 = (100,200)
Find the output of the following statements:
i. print(tuple1.index(45))
ii. print(tuple1.count(45))
iii. print(tuple1 + tuple2)
iv. print(len(tuple2))

12 Write a program to search an element from a list. 4


OR
WAP to check whether the number is divisible by 7 or not in a list.

13 Explain the following: 4


i)FOSS
ii)Proprietry Software
iii)Identity Theft
iv) Copyright Infringement

**************************************************************************
KENDRIYA VIDYALAYA SANGATHAN ,ERNAKULAM REGION
SAMPLE QUESTION PAPER TERM 2-SET 3
COMPUTER SCIENCE(CODE:083)
TOTAL CLASS XI
MARKS
Time:
35 2 Hours

MARKING SCHEME
SECTION A
Each Question carry 2 marks
QNO PART QUESTION MARKS
NO
1 (i) 6 2
(ii) [9,8,16,8]
OR
(iv) print(max(L))
(v) L.reverse()
2 (i) 12 2
(ii) 12

3 (iii) dict_values([‘Hyderabad ', ' Patna ', ' Mumbai ', ' Jaipur ']) 2
(iv) True
OR
i) 3
ii) will generate a number between 2 and 7, inclusive
4 (vi) fabs()-math module 2
(vii) randint()-random module
(viii) mode()-statistics module
(ix) ceil()-math module
5  Active digital footprints which includes data that we intentionally 2
submit online. This would include emails we write, or responses or
posts we make on different websites or mobile Apps, etc

 The digital data trail we leave online unintentionally is called passive


digital footprints. This includes the data generated when we visit a
website, use a mobile App, browse Internet, etc.,

6  Intellectual Property Rights (IPR) help in data protection through 2


copyrights, patents and trademarks.

Intellectual Property refers to the inventions, literary and artistic expressions,


designs and symbols, names and logos.
7 2
 Plagiarism
 Hacking
SECTION – B
Each question carries 3 marks
8 1 3
3
5
7
9
OR
OUTPUT: (ii)
a. Minimum Number = 1
Maximum number = 3
b. Option (iv)
9 num = int(input("Enter the number of employees whose data to be stored: ")) 3
count = 1
employee = dict() #create an empty dictionary
while count <= num:
name = input("Enter the name of the Employee: ")
salary = int(input("Enter the salary: "))
employee[name] = salary
count += 1
print("\n\nEMPLOYEE_NAME\tSALARY")
for k in employee:
print(k,'\t\t',employee[k])
10 Health Hazards 3
 Eye strain is a symptom commonly complained by users of digital
devices.
 Bad posture, backaches, neck and shoulder pains.
 Stress, physical fatigue and obesity are the other related impacts.
Safety Measures
 It is better to periodically focus on distant objects, and take a break for
outdoor activities.
 Position devices and t position our posture.
 Arranging workplaces including the furniture, equipments and systems
so that it becomes safe and comfortable for the user.

SECTION – C
Each question carries 4 marks
11 i. 2 4
ii. 3
iii (23, 1, 45, 67, 45, 9, 55, 45, 100, 200)
iv. 2
12 Write a program to search an element from a list. 4
lst=eval(input("enter the elements:"))
n=len(lst)
x=int(input("enter the element to be searched:"))
for i in range(n):
if(x==lst[i]):
print("The element",x," is found at index",i)
break
else:
print("The element is not found")
OR
WAP to check whether the number is divisible by 7 or not in a list.
lst=eval(input("enter the elements:"))
n=len(lst)

for i in range(n):
if(lst[i]%7==0):
print("The element",lst[i]," is divisible by 7")
else:
print("The element",lst[i]," is not divisible 7")
13  Explain the following: 4
 i)FOSS-OPEN SOURCE SOFTWARE
 Free and Open Source Software (FOSS) allow users to not only access
but also to modify (or improve) them.(Python,MySQL etc)
 ii)Proprietry Software-
 Proprietary software that we use are sold commercially and their
program code (source code) are not shared or distributed.(Microsoft
Office,Wndows etc)
 iii)Identity Theft-
 Personal information stolen from computers or computer networks, to
commit fraud by using the data gained unlawfully is calledidentity
theft. A user’s identifiable personal data like demographic details,
email ID, banking credentials, passport, PAN, Aadhaar number and
various such personal data are stolen and misused by the hacker on
behalf of the victim
 iv) Copyright Infringement-
 Copyright infringement is when we use other person’s work without
obtaining their permission to use or we have not paid for it, if it is being
sold.

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

You might also like