11 CS SSM 2022-23 Ahmd
11 CS SSM 2022-23 Ahmd
11 CS SSM 2022-23 Ahmd
Class XI
Computer Science(083)
1
OUR PATRON
2
SUBJECT CO-ORDINATION BY
CONTENT TEAM
3
KENDRIYA VIDYALAYA SANGATHAN, AHMEDABAD REGION
SPLIT-UP OF SYLLABUS
SUB: COMPUTER SCIENCE (083)
CLASS - XI (NEW SYLLABUS)
Session 2022-23
DISTRIBUTION OF MARKS
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
4
• Familiarization with the basics of Python programming: Introduction to Python, features 15 15
of Python, 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 features
of Python, Python Character Set, Token & Identifiers, Keywords, Literals,
Delimiters, Operators.
• 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
AUGUST
operators (in, not in)
OCT • Lists: introduction, indexing, list operations (concatenation, repetition, membership &
slicing), traversing a list using loops, built-in functions: 15 10
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
5
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
PRACTICAL WORK
S.No. UNIT NAME MARKS
1 Lab Test (12 marks)
Python program (60% logic + 20% documentation + 20% code quality) 12
2 Report File + viva (10 marks)
Report file: Minimum 20 Python programs 7
Viva voce (based on the report file) 3
3 Project (that uses most of the concepts that have been learnt) Project 8
may be allotted to group of 2-3 students.
6
Suggested Practical List Python Programming
• 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:
𝟏+𝒙+𝒙𝟐 +𝒙𝟑 …+𝒙𝒏
𝟏−𝒙+𝒙𝟐 −𝒙𝟑 …+(−𝟏)𝒏𝒙𝒏
𝒙− 𝒙𝟐 + 𝒙𝟑 − 𝒙𝟒…+(−𝟏)𝒏 𝒙𝒏
𝟐! 𝟑! 𝟒! 𝒏!
𝒙− 𝒙𝟐 + 𝒙𝟑 − 𝒙𝟒…+(−𝟏)𝒏 𝒙𝒏
𝟐 𝟑 𝟒 𝒏
ooOoo
7
CLASS : XI
SUB : Computer Science ( 083 )
Session – 2022-23
Unit I: Computer Systems and Organization
Memory : A computer system needs memory to store the data and instructions for
processing. Whenever we talk about the ‘memory’ of a computer system, we usually talk
about the main or primary memory. The secondary memory (also called storage device) is
used to store data, instruction sand results permanently for future use.
Software : The sole purpose of a software is to make the computer hardware useful and
operational. A software knows how to make different hardware components of a computer
work and communicate with each other as well as with the end-user. We cannot instruct
the hardware of a computer directly. Software acts as an interface between human users
and the hardware. Depending on the mode of interaction with hardware and functions to be
performed, the software can be broadly classified into three categories viz.
(i) System software, (ii) Programming tools and (iii) Application software.
9
Questions No 1 to 10 Short Answer Type Question- 1 Mark
1. CPU has sub components namely Control Unit, registers and __________
2. _________ converts a high level language to machine code & execute it line by line.
3. Write full form of EEPROM.
4. ASCII stands for __________________
5. Storage of 2 KB means the following number of bytes:
6. Name the encoding scheme that could represent characters of all the known languages.
7. Which gate gives high output when odd number of inputs are high ?
8. State both DeMorgan’s Laws.
9. 1 TB = ___________ MB
10. Full form SRAM is ?
(125)10 = ( ? )16 = ( ? )8
14. Write the equivalent Boolean expression for the following logic circuit.
67 79 86 73 68
16. Draw logic circuit diagram for the following Boolean expression:
𝑌 = 𝑃 𝑄̅ + 𝑅
10
(i) GUI (ii) USB (iii) BIT (iv) CD
20. Drive the Boolean expression for the logic circuit shown below:
23. Why are language processors used? List their types and explain.
24. Write De-Morgan’s laws and prove anyone law out of them using truth table.
25. Draw truth table for given Boolean expression:
𝐸 = 𝑋. 𝑌(𝑌. 𝑍 + 𝑍̅)
26. Draw the logic circuit diagram for the expression: X=AB'+B'C'+ABC
11
Marking Scheme
1 to 10 Short Answer - 1 Mark
1. ALU
2. Interpreter
3. Electrically Erasable Programmable Read Only Memory.
4. American Standard Code for Information Interchange
5. 2048
6. Unicode
7. XOR
8. (A+B)’=A’.B’ and (A.B)’=A’+B’
9. 1024 X 1024
10. Static Random Access Memory
11. Operating system : It is the interface between user and computer system
Ex : Windows, Linux
• Process management
• Memory management
13. (125)10 = ( 7D )16 = ( 175 )8
14. w.x’+y’.z
15. C O V I D
16.
12
17. (i) GUI : Graphical User Interface
(ii) USB : Universal Serial Bus
(iii) BIT : Binary Digit
(iv) CD : Compact Disk
18. UTF-8 is an encoding system which is used in UNICODE system. It is a type of multi-
byte encoding. It can use 1,2,3 or 4 Octets i.e. 8 bits, 16 bits, 24 bits or 32 bits depending
upon the requirement or size of the data.
19. Nibble—Byte—KB---MB---GB---TB---PB
20. C(A+B) + D
21. Both RAM and ROM are parts of the primary memory
RAM refers to random access memory where both read and write operations can take
place. RAM is a volatile memory; its contents are lost when power is turned off. Types :
SRAM, DRAM.
ROM refers to read only memory where only read operation can take place. The ROM is a
non-volatile memory.
Types : PROM, EPROM, EEPROM
23. Programs written in a high level language are required to be converted into a machine
language. This task is accomplished by the language processor. The types are – Assembler,
Interpreter, Compiler.
Compiler : Converts High Level Language into Low level language in one go.
Interpreter : Converts High level language into low level language line by line
Assembler : Converts Assembly language to machine language.
13
Prove using truth table:
A B A+B (A+B)’ A’ B’ A’.B’
0 0 0 1 1 1 1
0 1 1 0 1 0 0
1 0 1 0 0 1 0
1 1 1 0 0 0 0
26. Draw the logic circuit diagram for the expression: X = AB' + B'C' + ABC
14
28. There are four main functions of the computer system:
Input: The process of data feeding by the user (Data means raw facts and figures)
Process: The actual work done in computers
Output: The result of user’s task (It can be: On-screen (Soft Copy), On
Paper (Hard Copy) or On Air)
Storage: The process of saving data
15
Higher dependency on electronic gadgets:
30. Secondary Memory : Primary memory has limited storage capacity and
is either volatile (RAM) or read-only (ROM). Thus, a computer system needs auxiliary or
secondary memory to permanently store the data or instructions for future use. The
secondary memory is non-volatile and has larger storage capacity than primary memory. It
is slower and cheaper than the main memory. But, it cannot be accessed directly by the
CPU. Contents of secondary storage need to be first brought into the main memory for the
CPU to access. Examples of secondary memory devices include Hard Disk Drive (HDD),
CD/DVD, Memory Card,
However, these days, there are secondary storage devices like SSD which support very fast
data transfer speed as compared to earlier HDDs. Also, data transfer between computers
have become easier and simple due to the availability of small-sized and portable flash or
pen drives.
16
UNIT – II COMPUTATIONAL THINKING AND PROGRAMMING – 1
17
• A good algorithm, which is precise, unique and finite, receives input and produces an
output.
• In order to write effective algorithms we need to identify the input, the process to be
followed and the desired output.
• A flowchart is a type of diagram that represents the algorithm graphically using boxes of
various kinds, in an order connected by arrows.
• An algorithm where all the steps are executed one after the other is said to execute in
sequence.
• Decision making involves selection of one of the alternatives based on outcome of a
condition.
• An algorithm may have a certain set of steps, which are repeating for a finite number of
times, such an algorithm is said to be iterative.
• There can be more than one approach to solve a problem and hence we can have more
than one algorithm for a particular problem.
• The choice of algorithm should be made on the basis of time and space complexity.
INTRODUCTION TO PYTHON
Introduction:
General-purpose Object Oriented Programming language, High-level language Developed in
late 1980 by Guido van Rossum at National Research Institute for Mathematics and
Computer Science in the Netherlands.
It is derived from programming languages such as ABC, Modula 3, small talk, Algol- 68.
It is an Open Source Scripting language. It is Case-sensitive language (Difference between
uppercase and lowercase letters). One of the official languages at Google.
Characteristics of Python:
• Interpreted: Python source code is compiled to byte code as a .py file, and this byte
code can be interpreted by the interpreter.
• Interactive Object Oriented Programming Language
• Easy & Simple
• Portable
• Scalable: Provides improved structure for supporting large programs.
• Integrated
• Expressive Language
Python Interpreter:
Names of some Python interpreters are:
• PyCharm
• Python IDLE
• The Python Bundle
• pyGUI
• Sublime Text etc.
18
There are two modes to use the python interpreter:
i. Interactive Mode
ii. Script Mode
i. Interactive Mode: Without passing python script file to the interpreter, directly
execute code to Python (Command line).
Example:
>>>6+3
Output: 9
Note: >>> is a command the python interpreter uses to indicate that it is ready. The
interactive mode is better when a programmer deals with small pieces of code.
ii. Script Mode: In this mode source code is stored in a file with the .py extension
and use the interpreter to execute the contents of the file. To execute the script
by the interpreter, you have to tell the interpreter the name of the file.
Example:
if you have a file name Demo.py , to run the script you have to follow the following
steps:
Step-1: Open the text editor i.e. Notepad
Step-2: Write the python code and save the file with .py file extension. (Default directory is
C:\Python33/Demo.py)
Step-3: Open IDLE ( Python GUI) python shell
Step-4: Click on file menu and select the open option
Step-5: Select the existing python file
Step-6: Now a window of python file will be opened
Step-7: Click on Run menu and the option Run Module.
20
8. The following box denotes?
(A) Decision
(B) Initiation
(C) Initialization
(D) I/O
Answer:--- (A) Decision
Q.18 What will be the output of the following code: Give reason for your output.
#This is a Sample Code
#to print some lines
#print(“Just like “)
print(“Hello! how are you?”)
print(“Are you from India?”)
21
Short Answer Type Questions (2 Marks)
Q1 Write an algorithm and flowchart that converts the input Celsius degree into its
Equivalent Fahrenheit degree. Use the formula: F = (9/5) *C+32.
Q2 Swapping of 2 variables without using temporary (or 3rd variable).
22
Ans1.
Ans 2
23
Knowledge of Data Types
A variable is like a container that stores values that you can access or change. A variable,
as the name suggest, has been derived from the word ‘vary’ which states that a variable
may vary during the execution of a program.
Through variables, we store the value in computer’s memory. Variable is a named unit of
storage. Every variable has a type and this type defines the format and behavior of the
variable.
Example: x=3
It will automatically assign a value 3 to variable named x, which is an integer.
A variable has three main components:
➢ Identity of the variable
➢ Type of the variable
➢ Value of the variable
A. Identity of the variable: It refers to the variable’s address in the memory. The
address of an object can be checked using the method id().
Syntax: id(object/variable)
Example: >>>x = 10
>>> id(x) Address of
1254668541 memory location
storing value 10
B. Type of the variable: By type, we refer to the data type of a variable. In Python, each
value is an object and has a data type associated with it. Data type of a value refers to the
value it is and the allowable operations on those values. A data type in Python can be
categorized as follows:
1. Number:
Number data type stores numerical values.
NOTE: One of the most distinguished feature of Python is that you don’t really have to
declare a numeric value to define its type. Python can easily differentiate one data type
from another when you write and run your statement.
(a) int(integer): Integer represents whole numbers without any fractional part. They can
be positive or negative and have unlimited size in Python. Example: -6, 468, 0, 4, -43.
(b) float(floating point number): Floating point numbers denote real numbers or
floating point values (i.e., numbers with fractional part). Example: 3.14, 565.34, 0.76, 4.0
(c) Complex Numbers: Complex numbers in Python are made up of pairs of real and
imaginary numbers. They take the form ‘x + yj’ or ‘x + yJ’
Example: (i) >>> x = 2 + 5j
>>>print(x.real, x.imag)
2.0 5.0
(ii) >>> y = 4 – 2j
>>>print(y.real, y.imag)
4.0 -2.0
24
2. str(string):
A string is a sequence of characters that can be a combination of letters, numbers and
special symbols, enclosed within quotation marks, single, double, or triple (‘ ‘ or “ “ or ‘‘‘
’’’). These quotes are not part of the string.
Example: >>> str = “Hello Python”
>>> print(str)
Hello Python
3. bool(Boolean):
Boolean data type represents one of the two possible values, True or False. Any expression
which can be True or False has the data type bool.
Note: A Boolean True value is non-zero, non-null and non-empty.
Example: >>> bool_1 = 6>10
>>> print(bool_1)
False
4. None:
This is a special data type with a single value. It is used to signify the absence of
value/condition evaluating to False in a situation. It is represented by None.
Note: Python doesn’t display anything when we give a command to display the value of a
variable containing value as None. On the other hand, None will be displayed by printing
the value of the variable containing None using print() statement.
Example: >>>val1 = None
>>> val1
>>> print(val1)
None
5. List:
A list is a collection of values or an ordered sequence of values/items. The items in a list
can be of any type such as string, integers, float, objects or even a list.
Elements of a list are enclosed in square brackets [ ], separated by commas.
Example: >>> L = [10, 20, 30, 40, 50]
>>>print( L )
[10, 20, 30, 40, 50]
6. Tuple:
Tuple is an another sequence data type similar to the list. A tuple consists of a number of
values separated by commas. Unlike lists however, tuples are enclosed within parentheses.
Elements in a tuple need not be of the same type, they can be heterogeneous.
Example: >>> T = ( 10, 20, 30, 40, 50 )
>>>print( L )
( 10, 20, 30, 40, 50 )
7. Dictionary:
Python-dictionary is an unordered collection of items where each item is a key-value pair.
We can also refer to a dictionary as a mapping between a set of keys and set of values. The
25
items of a dictionary are enclosed within curly braces and items are separated by commas.
The key value pairs are separated by colon (:).
Example: D = { “Jan” : 31, “Feb” : 28, “Mar” : 31 }
Operators:
Used to perform specific mathematical or logical operations on values. The values that the
operators works on are called operands. Following are the types of operators:
1. Arithmetic Operator
2. Relational Operator
3. Assignment Operator
4. Logical operators
5. Membership Operator
6. Identity Operators
1. Arithmetic Operator
Operator Operation Description Example
+ Addition Adds two numbers >>>n1=5
>>>n2=4
>>>n1+n2
9
- Subtraction Subtract the operand on the right >>>n1=5
from the operand on the left >>>n2=4
>>>n1-n2
1
* Multiplication Multiplies the two values >>>n1=5
>>>n2=4
>>>n1*n2
20
/ Division Divides the operand on the left >>>n1=5
with the operand on the right >>>n2=2
>>>n1/n2
2.5
% Modulus Divides the operand on the left >>>n1=5
with the operand on the right and >>>n2=2
returns the remainder >>>n1%n2
1
26
// Floor Floor division. To find the integer >>>n1=5
Division part of the quotient when one >>>n2=2
number is divided by the other. >>>n1//n2
The result is always the largest 2
integer less than or equal to the
actual quotient.
** Exponent To raise a number to the power of >>>n1=5
another number. >>>n2=2
>>>n1 ** n2
25
2. Relational Operator
Operator Operation Description Example
== Equals to Compares two values. If both >>>n1=2
values are equal then returns True >>>n2=3
else returns False >>>n3=2
>>>n1==n2
False
>>>n1==n3
True
27
3. Assignment Operator
28
4. Logical operators
Operators Description Example
and Combines two conditions and returns >>>n1=10
True if both conditions are True else >>>n2=20
returns False >>>n1==10 and n2==20
True
>>>n1==10 and n2==10
False
5. Membership Operator
Operators Description Example
in return True if value exists in the >>>L=[1,2,3]
sequence, else false. >>>1 in L
True
>>> 4 in L
False
not in return True if value does not exists in the >>>L=[1,2,3]
sequence, else false. >>>1 not in L
False
>>>4 not in L
True
6. Identity operator
Operator Description Example
is Evaluates to True if the variables on x is y, here result is True if
either side of the operators points to id(x) equals to id(y)
the same object and False otherwise
is not Evaluates to False if the variables on x is not y, here result is
either side of the operators points to True if id(x) is not equals to
the same object and True otherwise id(y)
Precedence of Operators:
The order in which the operators are executed in an expression is called the operator
precedence. Operator precedence of some common operators are given below:
29
Expressions: An expression is a combination of constants, variables and operators which
always evaluates to a value which is also an expression.
Example: x = 3 + 4 –y * 2
Statement:
An instruction which does something e.g. a=4 will assign a value 4 to variable a.
Evaluation of expressions:
The expressions are evaluated based on the precedence and associativity of the operators.
Input :
To enter values from the user input( ) function is used. It accepts all type of values (either
a number, alphabet or special character) as string.
Syntax : variable = input([prompt])
Example: age=input(“Enter your age”)
30
The input( ) function takes exactly what is typed from the keyboard, converts it into a
string and assign it to a variable on left hand side of the assignment operator(=).
Output :
print() – used to output data to standard output device. The function print() evaluates the
expression before displaying it on screen.
Syntax : print(value)
Example: >>> L = [10, 20, 30, 40, 50]
>>>print( L )
[10, 20, 30, 40, 50]
1. Implicit Type Conversion : In this, Python automatically converts value from one data
type to another without user involvement.
Example: >>> N1=20 # N1 in integer
>>> N2 = 10.5 # N2 in float
>>> S = N1 + N2 # S will be float
>>> print(S)
output will be 30.5
2. Explicit Type Conversion: In this type of conversion, user converts the data type of an
object to required data type. A predefined functions like int(), float() or str( ) can be used.
Example: >>> N1=10 # N1 is integer
>>> N2=‘30‘ # N2 in string
>>> N3 = int(N2) # N3 will integer (N2 is converted to integer)
>>> print(N3) # 30 will be printed
Debugging :
The process of identifying and removing logical errors and runtime errors is called
debugging. Due to errors in program, it may not execute or generate wrong output. The
errors are of the following types:
1. Syntax Error
2. Logical Error
3. Runtime Error
1. Syntax Error:
Syntax errors are produced by Python when it is translating the source code into byte code.
They usually indicate that there is something wrong with the syntax of the program.
31
Example: Omitting the colon at the end of a for statement yields the somewhat redundant
message SyntaxError: invalid syntax.
Example 1: print(“Hello”) #syntactically correct
Example 2: print(“Hello” #syntax error due to right parenthesis is missing
2) Logical Error:
Logical errors are the most difficult to fix. They occur when the program runs without
crashing, but produces an incorrect result. The error is caused by a mistake in the
program's logic. You won't get an error message, because no syntax or runtime error has
occurred.
Example:
x = 10
y = 20
avg = x + y / 2
print(“Average of x and y = “, avg)
# this will give wrong average as y/2 will be calculated first instead of (x+y)/2.
3) Runtime Error :
Run time errors causes abnormal termination of program while it is executing. It occurs
when statement is correct syntactically, but interpreter cannot execute it.
Eg: a statement having division operation in program, if denominator value is zero then it
will give a runtime error “division by zero”.
32
Short Answer Type Questions :
11. What is debugging?
12. Write all logical operators in Python?
13. What are mutable and immutable data types in Python?
14. Explain the difference between tuple and list.
15. What is type casting and its type?
16. What are shorthand operators? Explain with the help of example.
17. What are identity operators? Explain with the help of an example.
18. How we can take input from user in Python?
19. Find the output of the following code:
X=4
Y=2
X+=Y+2
Y-=X+3
print(X, Y)
20. Convert the following expression into equivalent Python statements:
(i) z = 3abc + 4
𝑥+2
(ii) a = 𝑏−1
Long Answer Type Questions :
21. What do you understand by precedence of operators? What is the precedence of
arithmetic operators?
22. What is the difference between ‘=’ and ‘==’? Explain with the help of an example.
23. What is syntax error? Give one example.
24. What is logical error? Give one example.
25. What is runtime error? Give one example.
26. Solve the following expression:
(i) 12 * (3 % 4) //2 + 6
(ii) 12 % 3 ** 4//5 +6
27. What is type casting? Explain its types with the help of examples.
28. Find the output of the following.
P = 10
Q = 20
P * = Q//3
Q += P + Q ** 2
print(P, Q)
29. Write a program to input temperature in Celsius and convert it into Fahrenheit using
the formula:
F = C * 9 / 5 + 32
30. Write Python expression to represent the following situations:
(i) Add remainder of 8/3 to the product of 8 and 3
(ii) Find the square root of the sum of 8 and 43
(iii) Find the sum of square roots of 8 and 43.
33
Case Based Questions :
31. Ajit a student of class 11 wants to convert the temperature from Celsius to Fahrenheit.
He knows the formula of converting Celsius to Fahrenheit and has written a Python
program for the same. The formula for converting temperature is as follows:
9𝐶
F= +32
5
The program written by him is as follows:
C = input(“Enter temperature in Celsius”) # Line 1
F = 9 * C + 32 / 5 # Line 2
Print(“Temperature in Fahrenheit is = “, F) # Line 3
After running the program, he get an unexpected result. Help him correct the program by
answering the following questions.
(i) There is an error in line 1. Write the correct statement.
(ii) At line 2 Ajit has written wrong conversion of the formula of converting temperature
from Celsius to Fahrenheit. Write the correct code for the same.
(iii) After correcting errors at Line 1 and Line 2, Ajit is still getting error. Correct the error
and write the correct statement.
(iv) What will the output if the user input 37 at statement 1.
(v) Write a Python statement to convert temperature from Fahrenheit to Celsius.
Answers:
A1. Dictionary
A2. This is a special data type with a single value. It is used to signify the absence of
value/condition evaluating to False in a situation. It is represented by None.
A3. integer
A4. Error will be generated as string and integer cannot be added.
A5. String
A6. 57.0
A7. True is a Boolean value and a keyword while ‘True’ is a string value.
A8. A list is a collection of values or an ordered sequence of values/items. The items in a
list can be of any type such as string, integers, float, objects or even a list.
Elements of a list are enclosed in square brackets [ ], separated by commas.
Example: >>> L = [10, 20, 30, 40, 50]
A9. Tuple is another sequence data type similar to the list. A tuple consists of a number of
values separated by commas. Unlike lists however, tuples are enclosed within parentheses.
Elements in a tuple need not be of the same type, they can be heterogeneous.
Example: >>> T = ( 10, 20, 30, 40, 50 )
A10. Python-dictionary is an unordered collection of items where each item is a key-value
pair. We can also refer to a dictionary as a mapping between a set of keys and set of
values. The items of a dictionary are enclosed within curly braces and items are separated
by commas. The key value pairs are separated by colon (:).
34
Example: D = { “Jan” : 31, “Feb” : 28, “Mar” : 31 }
A11. The process of identifying and removing logical errors and runtime errors is called
debugging.
A12. There are three logical operators: and, or, not.
A13. Mutable data types: Data types where the value can be changed in place. Example:
dictionary, sets, lists etc.
Immutable data types: Data types where the values cannot be changed in place. Example:
integer, float, string, tuples etc.
A14. List and tuple are ordered collection of elements. Elements in list are enclosed in
square brackets [] while elements in tuple are enclosed in parentheses (). List is a mutable
data structure while tuple is a immutable data structure.
A15. The process of converting the value of one data type to another data type is called
type conversion or type casting.
There are two types of type conversions in Python:
1. Implicit Type Conversion
2. Explicit Type Conversion
A16. A shorthand assignment operator (or compound assignment operator or an
augmented operator) is a combination of a binary operation and assignment.
Example: +=, -=, *=, /=, %=, //= and **=
A17. Identity operators are used to check whether two variables are pointing to same
memory location or not. There are two identity operators: is and not is.
Operator Description Example
is Evaluates to True if the variables on x is y, here result is True
either side of the operators points to if id(x) equals to id(y)
the same object and False otherwise
is not Evaluates to False if the variables on x is not y, here result is
either side of the operators points to True if id(x) is not equals
the same object and True otherwise to id(y)
A24. Logical errors are the most difficult to fix. They occur when the program runs without
crashing, but produces an incorrect result. The error is caused by a mistake in the
program's logic . You won't get an error message, because no syntax or runtime error has
occurred.
Example:
x = 10
y = 20
avg = x + y / 2
print(“Average of x and y = “, avg)
# this will give wrong average as y/2 will be calculated first.
A25. Run time errors causes abnormal termination of program while it is executing. It
occurs when statement is correct syntactically, but interpreter cannot execute it.
Eg: a statement having division operation in program, if denominator value is zero then it
will give a runtime error “division by zero”
A26. (i) 24
(ii) 8
A27. The process of converting the value of one data type to another data type is called
type conversion.
There are two types of type conversions in Python:
1. Implicit Type Conversion: In this, Python automatically converts value from one data
type to another without user involvement.
Example: >>> N1=20 # N1 in integer
>>> N2 = 10.5 # N2 in float
>>> S = N1 + N2 # S will be float
>>> print(S)
output will be 30.5
2. Explicit Type Conversion: In this type of conversion, user converts the data type of an
object to required data type. A predefined functions like int(), float() or str( ) can be used.
Example: >>> N1=10 # N1 is integer
>>> N2=‘30‘ # N2 in string
>>> N3 = int(N2) # N3 will integer (N2 is converted to integer)
36
>>> print(N3) # 30 will be printed
A28. 60 480
A29. C = float(input(“Enter temperature in Celsius:”))
F = C * 9 / 5 + 32
print(“Temperature in Fahrenheit is =”, F)
A30. (i) 8 % 3 + 8 * 3
(ii) (8+43)**0.5
(iii) 8**0.5 + 43**0.5
FLOWOFCONTROL:
1. Decision Making and branching (Conditional Statement)
2. Looping or Iteration
3. Jump statements
Decision making is about deciding the order of execution of statements based on certain
conditions. Decision structures evaluates multiple expressions which produce TRUE or
FALSE as outcome.
There are three types of conditions in python :
1. If statement
2. if-else statement
3. elif statement
37
1. if statement : It is a simple if statement. When condition is true, then code
which is associated with if statement will execute.
Example:
a=40
b=20
if a>b:
print(“a is greater than b”)
2. if – else statement:
When the condition is true, then code associated with if statement will execute,
otherwise code associated with else statement will execute.
Example:
a=10
b=20
if a>b:
print(“a is greater”)
else:
print(“b is greater”)
3. elif statement: It is short form of else-if statement. If the previous conditions were
not true, then do this condition". It is also known as nested if statement.
Example:
a=input(“Enter first number”)
b=input("Enter Second Number:")
if a>b:
print("a is greater")
elif a==b:
print("both numbers are equal")
else:
print("b is greater")
38
LOOPS IN PYTHON :
Loop: Executes a set of statements repeatedly until a particular condition is satisfied.
1. while loop
2. for loop
1. while loop: With the while loop we can execute a set of statements as long as a
condition is true. It requires to define an indexing variable.
Example: To print table of number 2 :
i=2
while i<=20:
print(i)
i+=2
2. for loop: The for loop iterate over a given sequence (it may be list, tuple or string).
Note: The for loop does not require an indexing variable to set before hand, as the for command
itself allows for this.
primes = [2, 3, 5, 7]
for x in primes:
print(x)
39
The range() function:
It generates a list of numbers, which is generally used to iterate over with for loop. range()
function uses three types of parameters, which are:
a. range(stop)
b. range(start,stop)
c. range(start,stop,step)
Note:
➢ All parameters must be integers.
➢ All parameters can be positive or negative.
For x in range(4):
print(x)
Output:
0
1
2
3
b. range(start,stop) : It starts from the start value and upto stop, but not including
stop value.
Example:
for x in range(2,6):
print(x)
40
Output:
2
3
4
5
print(x)
Output:
3
5
7
Q4 What will be the data type of the var in the below code snippet?
var = 10
print(type(var))
var = "Hello" a)
print(type(var))
41
a) int and str
b) int and int
c) str and str
d) float and str
Q5 How is a code block indicated in Python? b)
a) Brackets
b) Indentation
c) Key
d) None of the above
Q6 What will be the output of the following code snippet?
a = [1, 2, 3] d)
a = tuple(a)
a[0] = 2
print(a)
a) [1,2,3]
b) (1,2,3)
c) [2,2,3]
d) error
Q7 What will be the output of the following code snippet? d)
print(type(5 / 2))
print(type(5 // 2))
x =['ab','cd']
forIin x:
i.upper()
print(x)
a) [‘ab’, ‘cd’]
b) [‘AB’, ‘CD’]
c) [None, None]
d) none of the mentioned
a) 5 6 7 8 9 10
b) 5 6 7 8
c) 5 6
d) error
Q10 What will be the output of the following Python code? c)
i=1
while True:
if i%3 == 0:
break
print(i)
i+=1
a) 1 2
b) 1 2 3
c) error
d) none of the mentioned
Q1) What are loops in python? Name the two types of loop.
Q2) What a range() function does? Give an example.
Q3) What will be the output of the following code?
for i in range(2):
print(i)
for i in range(4,6):
print(i)
43
Q8) Write a program to make the following pattern:
*
***
*****
*******
*********
ANSWERS
Ans 1) A loop in Python is a control flow statement that is used to repeatedly execute a
group of statements as long as the condition is satisfied. The two types of loops are for and
While loop.
Ans 2) The Python range() function returns the sequence of the given number between
the given range.
Example:
for i in range(0,10,2):
print(i, end=" ")
print()
Ans3)
0
1
4
5
Ans 4)
Syntax of if-elif-else
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
Ans 5)
year = int(input('Enter year : '))
if (year%4 == 0 and year%100 != 0) or (year%400 == 0) :
print(year, "is a leap year.")
else :
print(year, "is not a leap year.")
44
Ans 6)
vowels = ['a', 'e', 'i', 'o', 'u']
text = input("Enter a character: ")
if text in vowels:
print("It is a vowel")
else:
print("It is not a vowel")
Ans 7)8 12
Ans 8)
rows = 5
k=0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(end=" ")
while k!=(2*i-1):
print("* ", end="")
k += 1
k=0
print()
Ans 9)
For Loop While Loop
It is used when the number of iterations is It is used when the number of
known. iterations is not known.
In case of no condition, the loop is repeated In case of no condition, an error will
infinite times. be shown.
Initialization is not repeated. Initialization is repeated if carried out
during the stage of checking.
Statement of Iteration is written after Can be written at any place.
running.
Initialization can be in or out of the loop Initialization is always out of the
loop.
The nature of the increment is simple. The nature of the increment is
complex.
Used when initialization is simple. Used when initialization is complex.
Ans 10)
Indentation is basically the leading white space character added at the beginning of
statements to indicate a block of code.
Example:
if (a>b):
45
a=a+b #block1
b=b+c #block1
c=c*9 #block1
else:
a=a+1 #block2
Q1) What is the difference between else and elif construct of if statement?
Q2) Find the output of the following program segments:
I. a = 10
while a > 2:
print (a)
a -= 2
III. var = 7
while var > 0:
print (“current variable value: ” , var)
var = var – 1
if var == 3:
break
else:
if var == 6:
var = var – 1
continue
print (“Good bye!”)
46
Q5) Write a Python program to find the factorial of a positive number
Q6) What are the four elements of a while loop in Python?
Q7) What are endless loops ? Why do such loops occur? Give example.
Q8) Draw flowchart for displaying first 10 odd numbers.
Q9) What is a flowchart? How is it useful?
Q10) What is empty statement in Python? What is its need?
Answers
Ans 1) ‘else’ is used along with ‘if’ to define the alternative path if the condition
mentioned in the ‘if’ statement is incorrect. This means that only one statement
can be evaluated using if else statement.
If more than one statements need to be evaluated, ‘elif’ construct is used.
There is no limit on the number of ‘elif’ construct which should be used in a statement.
However, the conditions mentioned in each ‘elif’
construct should be mutually exclusive i.e. if one of the conditions in elif is correct,
it stops and doesn’t evaluate the rest.
Ans 2) i) 10
ii) 20
22
24
26
28
iii) current variable value : 7
current variable value : 5
Good bye !
current variable value : 4
Ans 3)
NumList = []
Number = int(input("Please enter the Total Number of List Elements: "))
for i in range(1, Number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
NumList.append(value)
NumList.sort()
print("Element After Sorting List in Ascending Order is : ", NumList)
47
Ans 4) rnpnear
1. Initialization Expressions — It initializes the loop control variable and it is given outside the
while loop before the beginning of the loop.
2. Test Expression — If its truth value is true then the loop-body gets executed otherwise not.
3. The Body of the Loop — It is the set of statements that are executed repeatedly in loop.
4. Update Expressions — It updates the value of loop control variable and it is given inside the
while loop.
Ans 7)Endless loops are loops which don’t terminate for the condition never
becomes False. They occur because the variable in the condition is not
e.g.
k=5
while K > 0:
pass
while k > 0:
k += 1
Ans 8)
48
Ans 9)A flowchart is a pictorial representation of an algorithm. It uses boxes of different
shapes to represent different types of instructions. These boxes are connected with arrow
marks to indicate the flow of operations. It helps in:
Ans 10)In Python, an empty statement is pass statement. Its syntax is:
pass
When pass statement is encountered, Python does nothing and moves to next statement in the flow
of control. It is needed in those instances where the syntax of the language requires the presence
of a statement but where the logic of the program does not.
Explanation of output: 3 is starting value, 8 is stop value and 2 is step value. First
print 3 and increase it by 2, that is 5, again increase is by 2, that is 7. The output can’t
exceed stop-1 value that is 8 here. So, the output is 3,5,8.
1. break statement : With the break statement we can stop the loop even if it is true.
49
Example:
Inwhileloop in forloop
i=1 languages = ["java", "python", "c++"]
while forxin languages:
i<6:print(i) if x ==
ifi==3: "python":break
break print(x)
i+= 1
Output: Output:
1 java
2
3
Note: If the break statement appears in a nested loop, then it will terminate the very loop it is
in i.e. if the break statement is inside the inner loop then it will terminate the inner loop only
and the outer loop will continue as it is.
TOPIC -STRING
INTRODUCTION –
It is a collection of characters.
It is represented using single quotes or double quotes.
Ex:- ‘Hello’ or “Hello”
INDEXING –
String indexing in Python is zero-based: the first character in the string has index 0, the
next has index 1, and so on. The index of the last character will be the length of the string
minus one.
Ex:-
INDEX ->
0 1 2can be
The individual characters 3 accessed
4 5 6by index as follows:
>>> S="WELCOME"
>>>S[0]
'W'
>>>S[5]
'M'
STRING OPERATIONS –
a) Concatenation operator ( +) – The Concatenation operator adds or concat two strings.
ex:- s1=‘Welcome’
s2 = ‘All’
print(s1+s2)
50
=>Output :- WelcomeAll
c) Membership Operators :-
i) in
ex:- ‘a’ in ‘hello’ => False
‘e’ in ‘hello’ => True
ii) not in
ex:- ‘a’ not in ‘hello’ => True
‘e’ not in ‘hello’ => False
Positive Index 0 1 2 3 4 5 6
Negative Index -7 -6 -5 -4 -3 -2 -1
51
(String slicing With start, stop and step)
Ex:-s = ‘welcome’
s[m : n : o]
It will start with index m to n-1 printing every oth character.
Note#if no value is given for m, by default it will take it as 0
if no value is given for n, by default it will take it as length -1
if no value is given for o, by default it will take it as 1
Ex:-s [0 :6 :2] => ‘wlo’
It will print every 2nd character from index 0 to 5
Ex:-s [2 :6 :3] => ‘lm’
It will print every 3rd character from index 2 to 5
Ex:-s[2::] =>'lcome'
It will print every character from index 2 to n-1(5)
TRAVERSING A STRING –
Traversing means iterating through the elements of string, one character at a time.
Ex:-s=‘hello’
for x in s :
print(x,’*’,end=‘’)
Output :- h*e*l*l*o*
52
title( ) – It return title case string.(capitalizes first character)
ex:- s='hello all'
s.title( ) => Hello All
endswith(<char>) – It returns True if the string ends with the specified value,
otherwise False.
ex :- s = ‘Hello’
s.endswith('o') =>True
s.endswith('a') =>False
startswith(<char>) – It returns True if the string starts with the specified value,
otherwise False.
ex:- s = ‘Hello’
s.startswith('H') =>True
s.startswith('h') =>False #case sensitive
isalpha( ) - it returns true if all the characters in the string are alphabets.
ex:- s = ‘hello’
s.isalpha( ) => True
isdigit( ) - it returns True if all the characters in the string are digits.
ex:- s = ‘123’
s.isdigit( ) => True
islower( ) - it returns True if all the characters in the string are in lowercase.
ex:- s = ‘Hello’
s.islower( ) => False
isupper( ) - it returns True if all the characters in the string are in uppercase.
ex:- s = ‘HELLO’
s.isupper( ) => True
isspace( ) - it returns true if all the characters in the string are space.
ex:- s = ‘ ’
s.isspace( ) => True
QUESTIONS
VERY SHORT ANSWER TYPE QUESTIONS [1 mark]
1. What is a string in Python ?
Ans. It is a collection of characters enclosed in ‘ ‘ or “ “.
2. Identify valid string literals : ‘marks’’, ‘mark’, “mark”, “mark’.
Ans. ‘mark’, “mark”
3. What is the index value of first character of string in Python ?
Ans. 0
4. If A = “Hello” then what will be the value of A[1] ?
Ans. ‘e’
5. If s = ‘Delhi’, then what will be the output of s.isalpha( ) ?
Ans. True
6. If X[m:n:o] is used for string slicing in Python, what is the default
Value of o if no value is provided ?
Ans. 1
7. What does find ( ) function of string returnsif the substring is not found in the range?
Ans. -1.
8. If output of A.isspace( ) is True, what could be the reason for the same ?
And. It means, all the characters of string are space only.
9. If s= ‘hello’, find the value of len(s).
55
Ans. 5
10. Is 123 or ‘123’ same ?
Ans. No. 123 is a number & ‘123’ is a string.
Output :- h*e*l*l*o*
56
s.index(‘e’ ) it will return => 1
=>Output :- WelcomeAll
=>Output :- WelcomeAll
5. If X = ‘COMPUTER’ and Y = ‘SCIENCE’ then what will be the output of the following?
a) ‘a’ not in X b) X +Y c) Y.replace(‘I’, ‘#’)
Ans. a) True b) ‘COMPUTERSCIENCE’ c) ‘SC#ENCE’
6. If a=”Skylight”, then what will be the output of the following?
a) a.startswith(‘s’) b)a.islower() c) a.endswith(‘t’)
Ans. a) False b) False c) True
7. Write a python code to give this output :
H #
E #
L #
L #
0 #
Ans. s='HELLO'
for x in s:
print(x,'#')
10. Write a program to change a given string to a new string exchanging first and last
character
Ans. s=input(“Enter any string”)
ns = s[-1:] + s[1:-1] + s[:1]
print (“New String- ”,ns )
59
Ans. a) ‘COMPUTER’
b) ‘puter’
c) False
d) -1
e) 1
continue statement : With the continue statement we can stop the current
iteration, and continue with the next iteration.
Example:
inwhileloop in forloop
i=0 languages = ["java", "python", "c++"]
while forxin languages:
i<6:i+= 1 if x ==
if i == "python":continue
3:contin print(x)
ue
print(i)
Output: Output:
1 java
2 c++
4
5
6
60
Nested Loop:
A loop inside another loop is known as nested loop.
Syntax:
for<variable-name>in<sequence>:
for <variable-name> in
<sequence>:statement(s)
statement(s)
Example:
for i in range(1,4):
for j in range(1,i):
print("*", end=" ")
print("")
Programs related to Conditional, looping and jump statements
1. Write a program to check a number whether it is even or odd.
num=int (input("Enter the number:"))
if num%2==0:
print(num, " is even number")else:
print (num, "is odd number")
else:
print(num, "is not Armstrong number")
62
7. To check whether the number is perfect number or not
num=int(input("Enter a number : "))
sum=0
for i in range(1,num):
if(num%i==0):
sum=sum+i
if num==sum:
print(num, "is perfect number")
else:
print(num, "is not perfect number")
63
List & Tuple
List :
Introduction :Lists are used to store multiple items in a single variable.
#Create a List:
a = [ ]# a blank list
My_list=list() # creating a list using list() function
b=[1,2,3,4,5] # here b is a integer list
thislist = ["apple", "banana", "cherry"] # list of fruits
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
Mix_List = ["abc", 34, True, 40, "male"] # list with mix data types
Indexing :List items are indexed, the first item has index [0], the second item has
index [1] etc.
Python has a set of built-in methods that you can use on lists :
Sl Method Description
1. append() Adds an element at the end of the list
2. clear() Removes all the elements from the list
3. copy() Returns a copy of the list
4. count() Returns the number of elements with the specified value
5. extend() Add the elements of a list (or any iterable), to the end of
the current list
6. index() Returns the index of the first element with the specified value
7. insert() Adds an element at the specified position
8. pop() Removes the element at the specified position
9. remove() Removes the first item with the specified value
10. reverse() Reverses the order of the list
11. sort() Sorts the list
Nested list :
A list in a another list is called nested list :-
i.e. - list1 =[10,20,30, [40,50],60] # here value 40 & 50 are in nested list
Important Questions :-
01. Differentiate between
1.1 List and string
1.2 append() and extend() list methods
1.3 pop() and remove()
1.4 mutable and non mutable data types
1.5 reverse() and sort() method
Q 3. The record of a student (Name, Roll No., Marks in five subjects and percentage of
marks) is stored in the following Record = ['Raman','A-36',[56,98,99,72,69], 78.8]
Write Python statements to retrieve the following information from the list stRecord.
a) Percentage of the student
b) Marks in the fifth subject
c) Maximum marks of the student
d) Roll no. of the student
e) Change the name of the student from ‘Raman’ to ‘Raghav’
Q 4 Write a program to find the number of times an element occurs in the list.
Q 5. Write a program to read a list of n integers and find their median.
66
Tuples:
Introduction :A tuple is an ordered sequence of elements of different data types, such as integer,
float, string, list or even a tuple. Elements of a tuple are enclosed in parenthesis (round brackets)
and are separated by commas.
for example :
>>> a = (1, ‘a’, 7, 6.5) # a is the tuple of mixed data type
>>> b = (2, 4, 6, 8, 10) # b is a tuple of only integers
>>> c = (“English”, “Hindi”, “Math”, “Science”) # c is a tuple of only string
>>> d = (2, 4, 7, [4, 5, 6]) # d is a tuple with list as an element
Verification : Verification :
Tuples in Python :
>>>a[4] # Output is U (fifth element of tuple)
>>>a[7] # Output is R (Eighth element of tuple)
>>>a[-1] # Output is R (last element of tuple or first element from right)
>>>a[9] # Output is IndexError: tuple index out of range
Tuple is Immutable :
Tuple is an immutable data type. It means that the elements of a tuple cannot be changed
after it has been created. for example :
>>> a = (‘C’ , ‘ O’ , ‘M’ , ‘P’ , ‘U’ , ‘T’ , ‘E’ , ‘R’)
>>>a[2] = ‘S’
TypeError: ‘tuple’ object does not support item assignment.
67
It is mutable data type. It is an immutable data type.
Elements are enclosed in Square brackets ie[ ] Elements are enclosed in Parenthesis. ie( )
Iterating through a list is slower as compared Iterating through a tuple is faster as compared
to a tuple to a list
Tuples in Python
Tuple Operations : Various operations of tuple are done by various operators like
Operation
Description Example
Name
>>>t1 = (1, 2, 3)
>>>t2 = (8, 9, 11)
>>>t1+t2
OUTPUT :
(1, 2, 3, 8, 9, 11)
(#concatenates two tuples)
>>>t1 = (1, 2, 3)
Joining of two or more tuples is >>>t2 = (8, 9, 11)
called concatenation >>>t3 = t1+t2
(#Created new tuple)
Concatenation (+)
OUTPUT :
Python allows us to join tuples (1, 2, 3, 8, 9, 11)
using concatenation operator (+).
Concatenation operator can also
be used for extending an
existing tuple.
>>>t1 = (1, 2, 3)
>>>t1 = t1 + (7,8,9)
>>>t1
OUTPUT :
(1, 2, 3, 7, 8, 9)
>>>t1 = (1, 2, 3, 7, 8, 9)
>>>t1[2:4]
(3, 7)
>>>t1[: : -1]
(80, 70, 60, 50, 40, 30, 20, 10)
>>>t1 = tuple()
>>>type(t1)
<class ‘tuple’>
>>>t1 = tuple(range(7))
>>>t1
(0, 1, 2, 3, 4, 5, 6)
>>>t1=tuple(“tuples in python”)
This function returns the frequency
count( ) >>>t1.count(‘p’)
of an element in the tuple. 2
>>>t1=tuple(“tuples in python”)
This function returns the index of the >>>t1.index(‘n’)
index( ) first occurrence of the element in the 8
given tuple.
>>>t1=tuple(“tuples in python”)
69
>>>t1.index(‘f’)
ValueError: tuple.index(x): x not
in tuple
Tuple Assignment :
It allows a tuple of variables on the left side of the assignment operator to be assigned
respective values from a tuple on the right side. The number of variables on the left
should be same as the number of elements in the tuple. for example---
>>>(n1,n2) = (5,9)
>>>print(n1)
5
print(n2)
9
>>>(a,b,c,d) = (5,6,8) #values on left side and right side are not equal
ValueError: not enough values to unpack
Nested Tuples :
A tuple inside another tuple is called a nested tuple. In nested tuples we can access the
elements in the same way of nested list. for example
>>>t1 = ((“Amit”, 90), (“Sumit”, 75), (“Ravi”, 80))
>>>t1[0]
(‘Amit’, 90)
70
>>>t1[1]
(‘Sumit’, 75)
>>>t1[1][1]
75
Important Questions & Answers
1. Which of the following is a Python tuple?
a) [1, 2, 3]
b) (1, 2, 3)
c) {1, 2, 3}
d) {}
i. print(tuple1.index(45))
ii. print(tuple1.count(45))
iii. print(tuple1 + tuple2)
iv. print(len(tuple2))
v. print(max(tuple1))
vi print(min(tuple1))
vii. print(sum(tuple2))
viii. print ( sorted ( tuple1) )
print(tuple1)
ix. s=("Cbse Exam 2020-2021")
print(s)
r=""
for i in s:
if i.isupper()== False:
72
r+=i.lower()
elifi.islower()== False:
r+=i.upper()
else:
r=r+i print(r)
3 Marks Questions
1 Write a program to read email IDs of n number of students and store them
in a tuple. Create two new tuples, one to store only the usernames from the
email IDs and second to store domain names from the email ids. Print all
three tuples at the end of the program.
[Hint: You may use the function split()]
2 Write a program to input names of n students and store them in a tuple.
Also, input a name from the user and find if this student is present in the
tuple or not. We can accomplish these by:
(a) writing a user defined function (b) using the built-in function
3 Write a program to swap two numbers without using a temporary variable.
4 This is a program to create a nested tuple to store roll number, name and
marks of students
5 Write a program to input n numbers from the user. Store these numbers in
a tuple. Print the maximum and minimum number from this tuple.
6 Explain tuple methods with suitable examples.
7 Explain tuple slicing with suitable examples
8 Write a program to find the minimum, maximum, mean of values stored in
a tuple .
9 WAP to perform linear search on a tuple of numbers, counting the
frequency of elements in a tuple.
10 WAP to perform linear search on a tuple of numbers, counting the
frequency of elements in a tuple.
73
Dictionary
Dictionary :- Python Dictionary is used to store the data in a key-value pair format.
-Python Dictionaries are unordered collection.
- Dictionaries are mutable means values in a dictionary can be changed using
its key.
- Keys are unique. - Enclosed within brace { }
Creating the dictionary:-The dictionary can be created by using multiple key-value pairs
enclosed with the curly brackets {}, and each key is separated from its value by the colon (:)
Accessing items in a dictionary using keys:- The elements are accessed through the
keys defined in the key:value pairs
Syntax:-<dictionary-name>[<key>]
Mydict['Name']
Output:- Raj
print(Mydict.keys())
print(Mydict.values())
# update value
74
my_dict['age'] = 27
print(my_dict)
# add item
my_dict['address'] = 'Downtown'
print(my_dict)
Output:-
get() method:-
print(Mydict.get('Age'))
Output:---- 15
for k, v in Mydict.items():
Output:---
75
2. dict() :- dict() function creates a dictionary.
x=dict(name="Yug",age=37,country="India")
print(x.keys())
12
Raj
6. update():- updates the dictionary with the elements from another dictionary object
or from an iterable of key/value pairs.
mydict = {'Africa':200,'australia':300,'England':400}
print("Country Name: ",mydict)
mydict.update({'China':500})
print("updated country name: ",mydict)
Country Name: {'Africa': 200, 'australia': 300, 'England': 400}
updated country name: {'Africa': 200, 'australia': 300, 'England': 400, 'China':
500}
76
7. del() :- The del keyword can be used to in-place delete the key that is present in
the dictionary in Python.
# Initializing dictionary
test_dict = {"Arushi": 22, "Mani": 21, "Haritha": 21}
The dictionary before performing remove is : {'Arushi': 22, 'Mani': 21, 'Haritha':
21}
The dictionary after remove is : {'Arushi': 22, 'Haritha': 21}
8. pop() method removes the specified item from the dictionary and return the
corresponding value.
Mydict = {'Name': 'Raj', 'Age': 15, 'Class': 12, 'Totalmarks':450}
Mydict.pop('Name')
'Raj'
9. popitem():- The popitem() method removes the item that was last inserted into the
dictionary.
Mydict = {'Name': 'Raj', 'Age': 15, 'Class': 12, 'Totalmarks':450}
K= Mydict.popitem()
print("Last item of dictionary = ", K)
10. fromkeys():- The dict.fromkeys() method creates a new dictionary from the
given iterable (string, list, set, tuple) as keys and with the specified value.
77
Syntax:
dictionary.fromkeys(sequence, value)
11. copy() :- copy() method returns a copy (shallow copy) of the dictionary.
original = {'Name': 'Raj', 'Age': 15, 'Class': 12, 'Totalmarks':450}
new = original.copy()
print('Orignal: ', original)
print('New: ', new)
12. setdefault():- The setdefault() method returns the value of a key (if
the key is in dictionary). If not, it inserts key with a value to the dictionary.
13. max() and min():- Used to find maximum and minimum respectively from
the dictionary.
my_dict = {'x':500, 'y':5874, 'z': 560}
key_max = max(my_dict.keys(), key=(lambda k: my_dict[k]))
key_min = min(my_dict.keys(), key=(lambda k: my_dict[k]))
print('Maximum Value: ',my_dict[key_max])
print('Minimum Value: ',my_dict[key_min])
Maximum Value: 5874
Minimum Value: 500
78
14. clear() :- removes all items from the dictionary.
15. sorted():- The sorted() function returns a sorted list of the specified iterable
object.
dict = {6:'George' ,2:'John' ,1:'Potter' ,9:'Micheal' ,7:'Robert' ,8:'Gayle' }
b = sorted(dict.keys())
print("Sorted keys",b)
c = sorted(dict.items())
print("Sorted Values",c)
1. count the number of times a character appears in a given string using a dictionary :-
#initializing string
test_str = "AMARDEEP"
# printing result
print ("Count of all characters in GeeksforGeeksis : \n" , res)
2. Create a dictionary with names of employees, their salary and access them.
Mydict = { }
while True :
79
name = input("Enter employee name :-")
sl = int(input("Enter employee salary :-"))
Mydict[ name] = sl
user = input("Do you want to quit then enter yes :-")
if user == "yes" :
break
print(Mydict)
Short Answers type questions
Q1. Keys of dictionary must be_________
a. antique
b. unique
c. mutable
d. integers
Q2. We can repeat the values of Key in Dictionary?
a. True
b. False
Q3. Key – value concept is in _______________
a. List
b. String
c. Dictionary
d. Tuple
Q9. Like lists, dictionaries are which mean they can be changed.
80
a. Mutable
b. Immutable
c. Variable
d. None of these
Q11. Which of the following function create a dictionary from sequence of key - value
Pairs.
a. dictionary( )
b. dict( )
c. create( )
d. convert( )
Q1. Parth wants to display the value corresponding to the key “3” in dictionary given
below. As a friend of Parth, help him to find the correct code.
Q4. Get the key of a minimum value from the following dictionary
4) Write a program to convert a number entered by the user into its corresponding
number in words. for example if the input is 876 then the output should be ‘Eight
Seven Six’.
83
9) Write a Python function to count the frequency of elements in a list using a
dictionary.
10) Find error, underline them and rewrite the same after correcting the following
code:-
D1= { }
i=1
Num= input("Enter number of entries: ")
while (i<=Num):
a= get("Enter name: ")
b= input("Enter age:")
D1(a)=b
i= i+1
L= D1.key()
for i in L:
print(i, '\t', D1[i])
ANSWER KEY
1. b 2. a 3 c
1. d
85
2. keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]
res_dict = dict(zip(keys, values))
print(res_dict)
3. print(MyDict['class']['student']['marks']['physics'])
4. print(min(My_dict, key=My_dict.get))
5. count= 4
86
4. num = input("Enter any number: ") #number is stored as string
#numberNames is a dictionary of digits and corresponding
number
#names
numberNames = {0:'Zero',1:'One',2:'Two',3:'Three',4:'Four',\
5:'Five',6:'Six',7:'Seven',8:'Eight',9:'Nine'}
result = ''
for ch in num:
key = int(ch) #converts character to integer
value = numberNames[key]
result = result + ' ' + value
print("The number is:",num)
print("The numberNameis:",result)
87
9. def CountFrequency(my_list): # Function definition
# Creating an empty dictionary
freq = {}
for item in my_list:
if (item in freq):
freq[item] += 1
else:
freq[item] = 1
for key, value in freq.items():
print ("% d : % d"%(key, value))
my_list=[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]
CountFrequency(my_list) # function calling
10. D1= { }
i=1
Num= int (input("Enter number of entries: "))
while (i<=Num):
a= input("Enter name: ")
b= input("Enter age:")
D1[a]=b
i= i+1
L= D1.keys()
for i in L:
print(i, '\t', D1[i])
1. (i) A
(ii) 30
(iii) False
(iv) True
(v) None
(vi) ('a', 30)
88
2. (i) n=int(input("How many student data you want to enter ..."))
Student={}
for i in range(n):
roll_no=int(input("Enter roll no: "))
name=input("Enter name: ")
marks=int(input("Enter marks: "))
Student[roll_no]=[name,marks]
print("{:<10} {:<10} {:<10}".format('Rollno','Name','Marks'))
for k, v in d.items():
Name, num = v
print("{:<10} {:<10} {:<10}".format(k, name, marks))
(ii)
n=int(input("Enter n: "))
d={}
for i in range(n):
roll_no=int(input("Enter roll no: "))
name=input("Enter name: ")
marks=int(input("Enter marks: "))
d[roll_no]=[name,marks]
for k in d:
if(d[k][1]>75):
print(d[k][0])
(iii)
n=int(input("How many student data you want to enter ..."))
Student={}
for i in range(n):
roll_no=int(input("Enter roll no: "))
name=input("Enter name: ")
marks=int(input("Enter marks: "))
Student[roll_no]=[name,marks]
for k, v in list(Student.items()):
if v[1] < 50:
del Student[k]
print("Remaining students: ", Student)
89
Sorting techniques :- Bubble and Insertion Sort
● Bubble sort
● Insertion sort
(i) BUBBLE SORT: Bubble sort is a simple sorting algorithm. It is based on comparisons,
in which each element is compared to its adjacent element and the elements are swapped
if they are not in proper order.
PROGRAM:
OUTPUT:
The sorted list is : [8, 12, 24, 45, 60, 77, 87, 90]
(ii) INSERTION SORT: Sorts the elements by shifting them one by one and inserting the
PROGRAM:
n=len(L)
for j in range(1,n):
temp=L[j]
prev=j‐1
prev=prev‐1
OUTPUT:
Enter the elements: [45, 11, 78, 2, 56, 34, 90, 19]
The sorted list is: [2, 11, 19, 34, 45, 56, 78, 90]
● Library or package
● Module
● Function/Sub Modules
● A module is a file containing python definitions, variables and classes and statement
with .py extension
● A Python package is simply a directory of python modules.
● A library in python is collection of various packages. Conceptually there is no
difference between package and python Library.
● Putting code into modules is useful because of the ability to import the module
functionality.
● Reusability: A module can be used in some other python code. Hence it provides
facility of code reusability
● A module allows us to logically organize our python code.
● Grouping related code into a module makes the code easier to understand and use.
● Categorization: Similar types of attributes can be placed in a single module.
Creation of Module:
A module is simply a python file which contains functions, classes and variables.
91
Let us consider the following example of a module name area.py which contains three
functions name area_circle(r), area_square(s), area_rect(l,b)
import math
def area_circle(r):
return math.pi*r*r
def area_square(s):
return s*s
def area_rect(l,b):
return l*b
2) Using from Statement: -To import some particular Function(s) from module we will use
import statement
OR
To use a function inside a module you have to directly call function if you are importing the
modules using from statement.
92
Example : Let us consider the following code. In this program we import the module with
the help of from statement and directly use the function instead of specifying Module name.
area_rect(5,4)
Importing math module:-In order to use the various constants of mathematics and
operations, we have to import math module in our program.
Example :
import math
pi: - It is a mathematical constant, the ratio of the circumference of a circle to its diameter
(3.14159...)
For example
>>> print ("The value of pi is :",math.pi)
The value of pi is: 3.141592653589793
For example :
>>>print("The value of e is :", math.e)
The value of e is :2.718281828459045
ceil(x): - Returns the smallest integer that is greater than or equal to x.
For example :
>>>print("ans :",math.ceil(7.3))
Output: ans :8
floor(x): - Returns the largest integer that is less than or equal to x.
>>>math.floor(-45.17)
-46
>>>math.floor (100.12)
100
pow(x,y): - It returns the value of xy, where x and y are numeric expressions.
>>> print ("ans :", math.pow (3, 3))
Ans :27.0
>>>math.pow (2, 4)
16.0
93
>>>math.pow (5, 0)
1.0
sqrt(x): - Returns the square root of x.
>>> print ("Squre root of 65=:", math.sqrt (65))
Squre root of 65=:8.06225774829855
>>>math.sqrt (36)
6.0
fabs(x): - Returns the absolute value of x, represented as –
math.fabs (x)
where, x can be any numeric value.
For example,
>>> print (math.fabs (500.23))
500.23
>>> print (math.fabs (-200))
200
cos(x): - Returns the cosine of x in radians.
>>>math.cos(3)
-0.9899924966004454
sin(x): - Returns the sine of x in radians.
>>>math.sin (3)
0.14112000806
tan(x): - Returns the tangent of x in radians.
>>>math.tan (3)
-0.1425465430742778
Random Module: - This module contains functions that are used for generating random
numbers. import statement is the first statement to be given in a program for generating
random numbers:
import random
(1) random():- It is floating point random number generator between 0.0 to 1.0. Here
lower limit is inclusive where as upper limit is less than 1.0. i.e. 0<=N<1 where N is
generated random number.
Example: -
>>>import random
94
>>>n=random.random()
>>>print(n)
0.1738135764235368
(2) randrange():- This method generates an integer between its lower and upper
argument. By default, the lower argument is 0.
Example :-
>>> import random
>>>Number=random.randrange (30)
>>>print(Number)
15
Note: - This line of code shall generate any one random integer number from 0 to 29
excluding upper argument.
(3) randint() : - This method generate random integer number. Both the given range
values are inclusive.
Example :-
>>> import random
>>>Number=random.randint (100,500)
>>>print(Number)
151
Statistical Module: - This module provides functions for calculating mathematical statics
of numeric (real valued) data. There are 3 basic functions under this module.
1. mean()
2. median()
3. mode()
In order to use these functions, we have to import statistics module in our code.
95
2. median(): - The median is the middle number in a group of numbers. If group has odd
numbers of element then it will return the middle position value, otherwise will return the
average of values at mid and mid-1 position.
Example: -
>>> import statistics
>>>L=[10,20,30,40,50,60,70]
>>>print(statistics.median(L))
40
3. mode(): - The mode function returns number that occurs most often within a set of
numbers.
Example:-
>>> import statistics
>>>L=[10,5,30,5,5,60,70]
>>>print(statistics.mode(L))
5
(1 MARK QUESTIONS)
a) 5.0
b) 5
c) 2
d) 4.0
(2 MARKS QUESTIONS)
97
Q10. What would be the output produced by the following code :
import math
import random
print ( math.ceil (random.random()))
Justify your answer.
(3 MARKS QUESTIONS)
Q1. Select the possible output(s) of the following code from the given option. Also,
specify the maximum and minimum value that can be assigned to variable NUM.
import random
cities = [‘Agra’, ‘Delhi’, ‘Chennai’, ‘Bhopal’]
NUM = random.randint(1,2)+1 for city in cities:
for I in range(1,NUM):
print(city, end=‘’)
print(‘\n’)
a) c) Agra
b) Agra Delhi
DelhiDelhi Chennai
ChennaiChennaiChennai Bhopal
BhopalBhopalBhopalBhopal
d) AgraAgra e) ChennaiChennai
DelhiDelhi BhopalBhopal
ChennaiChennai
BhopalBhopal
Q2.What is the utility of Python standard library's math module, random module and
statistics module?
98
Q4. What are docstrings? How are they useful?
Q5. Consider the following code:
import random as r
for I in range(4):
print(100 + r.randint(5,10), end=’ ‘)
Find the suggested output option(s) (i) to (iv). Also, write the least value and highest value
that can be generated by randint().
(i) 102 105 104 105
(ii) 110 103 104 105
(iii) 105 107 105 110
(iv) 110 105 105 110
Q6. Name the python library modules which need to be imported to invoke the following
functions: (i) floor() (ii) randint() (iii) mean()
Q7. In which situation, would you prefer bubble sort over insertion sort?
Q8. Write a python program to calculate mean, median and mode of data stored in the list.
Q9. What happens when Python encounters an import statement in a program? What
would happen if there is one more import statement for the same module, already
imported in the same program?
Q10. What possible output(s) are expected to be displayed on screen at the time of
execution of the program from the following code? Specify the maximum values that can
be assigned to each of the variables first, second and third in the code given.
a) 20#25#25#
b) 30#40#70#
c) 15#60#70#
d) 35#40#60#
Case Study Based Questions
1. Write a python program that takes a number from 1 to 9 and stored inside the variable
“guess_num”. If the user guesses wrong then the prompt appears again and the user
continues to input another number repetitively until the guess is correct. On successful
guess, the user will get a “Well guessed!” message, and the program will exit.
99
2. Write a program to perform insertion sorting on a given list of strings, on the basis of
length of strings. That is, the smallest length string should be the first string in the list
and the largest length string should be the last string in the sorted list.
1. import <modulename>
2. from <module> import <function>
A2.
import math
n=float(input('Enter n='))
ans=math.sqrt(n)
print('Square root of',n,' = ',ans)
A3.
(i) The math module is used for math related functions that work with all number
except complex numbers.
(ii) The Random module is used for different random number generator functions.
A4.
Each python program file is a module which imports other modules like objects and
attributes. A python program folder is a package of modules. A package can have modules
or sub folders.
A5.
Answer: b
100
A6.Advantages of modules are:-
1. Reusability : Working with modules makes the code reusable.
2. Simplicity: Module focuses on a small proportion of the problem, rather than focusing on
the entire problem.
A7.
Ceil: The function 'ceil(x)' in Python returns the smallest integer not less than x i.e., the
next integer on the RHS of the number line. Hence, 'math. ceil(89.7)' will return 90
whereas 'math. floor(89.7)' will return 89.
A8.
import random
print(random.randrange(10))
A9.
In the "from-import" form of import, the imported identifiers (in this case factorial())
become part of the current local namespace and hence their module's names aren't
specified along with the module name. Thus, the statement should be:
A10.
random.random() would generate a number in the range [0.0, 1.0] but math.ceil ( ) will
return ceiling number for this range, which is 1.0 for all the numbers in this range. Thus
the output produced will always be 1.0.
A1. Options b and c are correct. Maximum and Minimum value assigned to NUM are 3 and
2 respectively.
A2.
(i) Math module: The math module is used for math-related functions that work
with all number types except for complex numbers.
(ii) Random module: The random module is used for different random number
generator functions.
(iii) Statistics module:- The statistics module is used statistic-related functions like
mean, mode, median etc.
A3.
Options ii, iii, v and vi are possible outputs
101
A4. A docstring is just a regular Python triple-quoted string that is the first thing in a
function body/a module/ a class. When executing a function body (or a module/class),
the docstring doesn't do anything like comment, but Python stores it as part of the
function documentation. This documentation can later be displayed using the help()
function. So, even though docstrings appear like comments (no execution), they are
different from comments.
A5.
Options iii and iv are possible output(s). Least value and highest value can be
generated by randint() are 5 and 10 respectively.
A6.
(i) floor() – math
(ii) randint()- random
(iii) mean()- statistics
A7.
Bubble sort would be ideal sorting technique for situations where data can be read
only sequentially (e.g., data stored on magnetic tapes). As bubble sort also compare
two adjacent records, it will be suitable for such a situation.
A8.
import statistics as s
a=[4,7,8,2,3,4,5,3,4,5,6,7,10]
print(s.mean(a))
print(s.median(a))
print(s.mode(a))
A9.
When Python encounters an import statement, it does the following:
(i) Code of the imported module is interpreted and executed.
(ii) Defined functions and variables createdin the module are now available to the
program that imported the module.
(iii) For imported module, a new namespace is set up with the same name as that of
the module.
Any duplicate import statement for the same module in the same program is ignored
by Python.
A10.
Option (a) is expected output
Maximum values that can be assigned to the variables first,second and third are 7,7
and 8 respectively.
102
Answers (Case Study based Questions)
A1.
import random
print(target_num)
print('Well guessed!')
A2.
def insertion_sort(arr):
for i in range(1,len(arr)):
key = arr[i]
j = i-1
while j >= 0 and len(key) <len(arr[j]): # comparison on the basis of length
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
return arr
103
Unit III : Society, Law and Ethics
Cyber Crime is defined as a crime in which a computer is the object of the crime (hacking,
phishing, spamming) or is used as a tool to commit an offence (child pornography, hate
crimes). Cybercriminals may use computer technology to access personal information,
business trade secrets or use the internet for exploitative or malicious purposes. Criminals
can also use computers for communication and document or data storage. Criminals who
perform these illegal activities are often referred to as hackers.
A traditional view of hackers is a lone rogue programmer who is highly skilled in coding and
modifying computer software and hardware systems. But this narrow view does not cover
the true technical nature of hacking. Hackers are increasingly growing in sophistication,
using stealthy attack methods designed to go completely unnoticed by cyber security
software and IT teams. They are also highly skilled in creating attack vectors that trick
users into opening malicious attachments or links and freely giving up their sensitive
personal data.
Ransomware is a type of malware that prevents users from accessing their system or
personal files and demands ransom payment in order to regain access. While some people
might think "a virus locked my computer," ransomware would typically be classified as a
different form of malware than a virus. The earliest variants of ransomware were developed
in the late 1980s, and payment was to be sent via snail mail. Today, ransomware authors
order that payment be sent via crypto currency or credit card, and attackers target
individuals, businesses, and organizations of all kinds. Some ransomware authors sell the
service to other cybercriminals, which is known as Ransomware-as-a-Service or RaaS.
Cyber Safety :
Cyber safety is the safe and responsible use of Internet &ICT(Information &
Communication Technology). Cyber safety is about to not only keeping information safe
and secure, but also being responsible with that information, being respectful of other
people online. As per Cyber safety peoples are advised to use good 'netiquette' (internet
etiquettes).
Identity Protection :
Protection against theft of personal information over Cyber Space without consent, usually
for financial gain is known as Identity Protection.
Tips to Prevent Identity Theft
▪ Use strong passwords and PINs & Keep passwords and PINs safe.
▪ Create log-in passwords for all devices.
▪ Beware of phishing scams.
105
▪ Restore old computers to factory settings.
▪ Encrypt your hard drive
▪ Check security when shopping online-check links authenticity which are received from
an unsolicited email.
▪ Take care when posting on social media-Check security settings on social media
accounts, and avoid posting personal information publicly, or publicly "checking in" .
Confidentiality of Information
Allows authorized users to access sensitive and secured data maintains the Confidentiality
of Information.
Tips to Protect Information Confidential
▪ Build strong passwords
▪ Use multifactor authentication- a computer user is granted access only after
successfully presenting 2 or more pieces of evidence.
▪ Masking -The free version of Mask-Me creates an alternate e-mail address whenever
a Web site asks for a user’s e-mail. E-mails from that site can be accessed via a
Mask-Me in-box or forwarded to a user’s regular e-mail account.
▪ Private Browsing & Safe Browsing-Purpose of private browsing is to avoid leaving a
history of one's browsing in the browser history on the computer we are using. Use
updated browser for safe browsing & browse privately.
▪ Encryption-Use https based sites, as HTTPS ensures data security over the network -
mainly public networks like Wi-Fi. HTTP is not encrypted and is vulnerable to
attackers. PGP is a popular program used to encrypt and decrypt email over the
Internet, as well as authenticate messages with digital signatures and encrypted
stored files.
▪ Avoid using public wifi and public computer.
108
QUESTIONS
1 Mark Questions :
(1) Which of the following is not a type of cybercrime?
(i) Data theft (ii) Forgery
(iii) Damage to data and systems
(iv)Installing antivirus for protection.
(2) What is the most important activity in system hacking?
(i) Information gathering (ii)Cracking passwords
(iii) Escalating privileges (iv) Covering tracks
(3) Which is the following is not done by cyber criminals?
(i) Unauthorized account access
(ii)Mass attack using Trojans as botnets.
(iii) Email spooling and spamming
(iv) Report vulnerability in any system.
(4) Which is the name of the IT law that India is having in the Indian legislature?
(i) India’s Technology (IT) Act, 2000
(ii) India’s Digital Information (DIT) Act, 2000
(iii) India’s Information Technology (IT) Act, 2000
(iv) The Information Act ( IA ) , 2000
(5) The full form of Malware is
(i) Malfunctioned software
(ii) Multipurpose software
(iii) Malicious software
(iv) Malfunctioning of security
(6) Which social network is considered the most popular for social media marketing?
(i) Twitter (ii) Facebook (iii) Linkdin (iv) Whats App
(7) Which of the following is an important aspect of creating blogs and posting content?
(i) Using a witty user name
(ii) Posting at least once a month to the blog
(iii) Social Media Optimization
(iv)All of the above
(8) Which of the following is the correct depiction of Digital Marketing?
(i) E-mail Marketing (ii) Social Media Marketing
(iii)Web Marketing (iv)All of the above
(9) Which of the following is not threat?
(i) Virus (ii) Hacker
(iii) Hard disk failure (iv)Operating system
(10) IT Act of the Indian Parliament notified on ___________
(i) 17 January 2001 (ii) 25 October 2002
(iii)17 October 2000 (iv) 25 April 2000
(11) Sakshi’s classmate sent her a message on Facebook “You are a Loser”. Sakshi is a
victim of:
109
(i) Phishing (ii) Eavesdropping
(iii) Cyber bullying (iv) Trolling
(12) What can happen when you give your personal data (email, address, photos you
post…) in exchange for free apps and services?
(i) Nothing can happen. Your data is not allowed to be passed on to anyone
(ii) It isn’t really used, it’s just compulsory to ask for that information
(iii) When giving your email you’re automatically entered in a lottery where you can
win something
(iv) Everything you do online is of value and is used by companies looking to target
their advertising
110
Q.4 What are cookies? How are they used by websites to track you?
Ans: Cookies are small pieces of information websites can store in your browser.
Cookies can be – 1. First Party Cookies- These are the cookies that store your own log in
id, password, and auto fill information etc. 2. Third Party Cookies: These are the cookies
that websites store to know about your search history and web browsing history so as to
place advertisements as per your interests.
Q.5 What is private browsing? Why is it considered a better way of browsing the Internet?
Ans:
• Anonymous browsers allow users to view websites without revealing personal
information of user.
• It can be sued as a tool for governments, journalists and every security conscious
surfers.
• A popular solution to this is- Private Browsing.
• Incognito browsing open up a version of the browser that will not track your activity.
it is particularly useful if you are entering sensitive data like bank details into your
browser.
• Proxy works as a middleman between your computer and the website you want to
access. Now the tracking website will get the IP address of proxy site.
• Virtual Private Network (VPN) this is a method to add security and privacy to private
and public networks, like WiFi hotspots and Internet. It is originally meant for
business employees working offsite to gain access to shared drives or networks.
Q.6 What is confidentiality of information? How do you ensure it?
Ans : Confidentiality of Information ensures that only authorized users get access to
sensitive and protected data. Best practices used to ensure confidentiality are –
• Use of Firewall
• Control browser settings to block Tracking.
• Browse Privately
• Be careful while posting on internet.
• Ensure safe sites while entering crucial information.
Q.7 Raman wanted to gift his brother a football or a wrist watch. So he searched for many
sports items and wrist watches online. But after that every time he goes online, his web
browser shows him advertisements about sports items and wrist watches.
(a) Why is this happening?
(b) How could have Raman avoided them?
(c) How can Raman get rid of this now?
Ans:
(a) This is happening because third party cookies saved his search preferences and now
websites are posting advertisements based on his preferences.
(b) Robin could have avoided this by privately browsing i.e. opening the web browser in
incognito mode before searching for such things.
(c) Now Robin can delete all the previous history and cookies stored on his computer. This
would stop websites posting advertisements.
111
Q.8 What is a virus? What is anti-virus software?
Ans: A computer virus is a malicious program that self-replicates by copying itself to
another program. In other words, the computer virus spreads by itself into other
executable code or documents. The purpose of creating a computer virus is to infect
vulnerable systems, gain admin control and steal user sensitive data. Hackers design
computer viruses with malicious intent and prey on online users by tricking them. Antivirus
software is a program or set of programs that are designed to prevent, search for, detect,
and remove software viruses, and other malicious software like worms, trojans, adware,
and more.
112
Extra Questions :
(1) Describe : (a) Cyber bullying (b) Cyber Stalking
(2) What do you understand by identity theft ?
(3) What measures should one take to avoid and maintain confidentiality of personal
information ?
(4) Nivedita has recently shifted to new city and new school. She does not know many
people in her new city and school. But all of a sudden, someone is posting negative,
demeaning comments on her social networking profile, school site’s forum etc.
She is also getting repeated mails from unknown people. Every time she goes online,
she finds someone chasing her online. (a) What is this happening to Nivedita? (b)
What action should she taken to stop them?
(5) What is data privacy ? Websites that you visit collect what type of information about
you ?
(6) What is antivirus software ?
(7) What is the need for secure password ?
(8) What is online fraud ?
(9) What are intellectual property rights ?
(10) what is digital property ? Give some examples of digital properties.
(11) What are common gender and disability issues faced while teaching / using
computers in class rooms ?
(12) What operations can be carried out for proper E-Waste Process ?
113