0% found this document useful (0 votes)
41 views97 pages

CS Support Material 2024 25 (2)

The document outlines the syllabus for Computer Science for Class XI, covering topics such as computer systems, Python programming, and societal impacts of technology. It includes detailed unit descriptions, practical exercises, and suggested reading materials. Additionally, it provides a breakdown of marks distribution for theory and practical assessments.
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)
41 views97 pages

CS Support Material 2024 25 (2)

The document outlines the syllabus for Computer Science for Class XI, covering topics such as computer systems, Python programming, and societal impacts of technology. It includes detailed unit descriptions, practical exercises, and suggested reading materials. Additionally, it provides a breakdown of marks distribution for theory and practical assessments.
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/ 97

INDEX

UNIT UNIT / CHAPTER NAME PAGE No.


NO.

1 Computer Systems and Organization 8-20

2 Python Basics and Flow of Control 21- 34

2 String 35-44

2 List Manipulation 45- 52

2 Tuples 53 - 61

2 Dictionary 62 - 68

2 Introduction to Python Module 69 - 73

3 Society, Law and Ethics 74 - 99

4 Sample Question Paper Solved 100-131

5 Sample Question Paper Unsolved 110-127

Computer Science (2024-25)


CLASS XI Code No. 083
Unit wise Syllabus

Unit 1: 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, and interpreter),
application software
● Operating System(OS): functions of the operating system, OS user interface
● Boolean logic: NOT, AND, OR, NAND, NOR, XOR, NOT, truth tables and De Morgan’s laws,
Logic circuits
● Number System: Binary, Octal, Decimal and Hexadecimal number system;
conversion between number systems
● Encoding Schemes: ASCII, ISCII, and Unicode (UTF8, UTF32)

4
Unit 2: Computational Thinking and Programming - I
● Introduction to Problem-solving: Steps for Problem-solving (Analyzing the problem,
developing an algorithm, coding, testing, and debugging), representation of algorithms
using flowchart and pseudocode, decomposition
● Familiarization with the basics of Python programming: Introduction to Python,
Features 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, useof 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
operators, augmented assignment operators, identity operators (is, is not), membership
operators (in not in)
● Expressions, statement, type conversion, and input/output: precedence of operators,
expression, evaluation of an expression, type-conversion (explicit and implicit conversion),
accepting data as input from the console and displaying output.
● Errors- syntax errors, logical errors, and run-time errors
● Flow of Control: introduction, use of indentation, sequential flow, conditional and iterative
flow
● Conditional statements: if, if-else, if-elif-else, flowcharts, simple programs: e.g.: absolute
value, sort 3 numbers and divisibility of a number.
● Iterative Statement: for loop, range(), 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, string operations (concatenation, repetition, membership and
slicing), traversing a string using loops, built-in functions/methods–len(), capitalize(),
title(), lower(), upper(), count(), find(), index(), endswith(), startswith(), isalnum(),
isalpha(), isdigit(), islower(), isupper(), isspace(),lstrip(), rstrip(), strip(), replace(), join(),
partition(), split()
● Lists: introduction, indexing, list operations (concatenation, repetition, membership and
slicing), traversing a list using loops, built-in functions/methods–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
and slicing); built-in functions/methods – 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 a
dictionary (adding a new term, modifying an existing item), traversing a dictionary, built-in
functions/methods – len(), dict(), keys(), values(), items(), get(), update(), del, clear(),

5
fromkeys(), copy(), pop(), popitem(), setdefault(), max(), min(), sorted(); 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 3: Society, Law and Ethics
● Digital Footprints
● Digital Society and Netizen: net etiquettes, communication etiquettes, social media
etiquettes
● Data Protection: Intellectual property rights (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,
cyber trolls, cyber bullying
● Cyber safety: safely browsing the web, identity protection, confidentiality
● Malware: viruses, trojans, adware
● E-waste management: proper disposal of used electronic gadgets.
● Information Technology Act (IT Act)
● Technology and society: Gender and disability issues while teaching and using
computers
1. Practical
S.No. Unit Name Marks
(Total=30)
1. Lab Test (12 marks)
Python program (60% logic + 20% documentation + 20% 12
code quality)
2. Report File + Viva (10 marks)
Report file: Minimum 20 Python programs 7
Viva voce 3
3. Project (that uses most of the concepts that have beenlearnt) 8
2. Suggested Practical List of 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 loops:
Pattern-1 Pattern-2 Pattern-3
* 12345 A
** 1234 AB
*** 123 ABC
**** 12 ABCD
***** 1 ABCDE

6
● Write a program to input the value of x and n and print the sum of the followingseries:
⮚ 1 + 𝑥 + 𝑥2 + 𝑥3 + 𝑥4 + ⋯ 𝑥n
⮚ 1 − 𝑥 + 𝑥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.
● 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.
● Create a dictionary with the roll number, name and marks of n students in a class and
display the names of students who have marks above 75.
3. Suggested Reading Material
● NCERT Textbook for Computer Science (Class XI)
● Support Material on CBSE website.

Distribution of Marks

Periods
Unit Unit Name Marks
No. Theory Practical
Computer Systems and
1 Organisation 10 10 10

Computational Thinking and


2 Programming -1 45 80 60

3 Society, Law, and Ethics 15 20 —

Total 70 110 70

7
Unit – 1 (Computer System and Organisation)

Computer System

A computer is an electronic device which consists of hardware and software. Hardware components
describe the physical parts of the computer and software controls hardware and run the operating
system, different programs & applications like Microsoft Windows, Microsoft word, Microsoft Excel
etc.
Below is the block diagram of Computer System

Strengths of Computer:
• A computer is much faster as compared to human beings.
• Computers are more accurate than a human for solving any problem.
• They are immune to tiredness and boredom or fatigue.
• Computers can perform repetitive jobs efficiently.
Weaknesses of Computer:
• Computer cannot take decisions on its own.
• It needs to be told at each and every step to perform any certain tasks.
• The computer doesn’t have human-like feelings.
A computer works on the IPO principle i.e. Input -> Process -> Output.
A computer receives data as input, processes it, stores it, and produces output based on this,
computer uses some components to take input, some components to do processing and some
components to provide output.
Input Device: The devices which are used to input the data and programs in the computer are
known as "Input Devices". Input unit accepts instructions and data from the user and converts

8
these instructions and data in computer acceptable format which are sent to computer system for
processing. Some examples of input devices include keyboard, mouse, scanner, touch screen, etc.
Output Device: Output Device produces the final results of computer into human understandable
form. Output unit accepts the results produced by the computer which are in coded form and it
converts these coded results to human readable form. For example, monitor, projector,
headphone, speaker, printer, etc.
Central Processing Unit (CPU): It is known as the brain of the computer. It has three main
components:
• Control Unit (CU): It controls and guides interpretation, flow and manipulation of data and
information. It sends control signals until the required operations are properly done by ALU
and memory unit (storage unit).
• Arithmetic and Logic Unit (ALU): It performs all the required arithmetic and logical operations
to perform the task.
• Memory Unit (Storage Unit): It comprises of primary and secondary memory units.
Hardware: All the physical components of the computer system are known as hardware e.g.,
keyboard, mouse, monitor, printer, etc.
Software: A set of instructions that directs a computer to perform specific tasks or operations.
Computer software consists of computer programs and libraries.
Software can be classified into three types:
• System Software: This software is mandatory for all computer systems to work. For example:
Operating systems like MS-DOS, Microsoft Windows etc.
• Application Software: This software is made to perform a specific task, For example: WordPad,
MS-Word, etc.
• Utility Software: Software that assists the computer to perform functions like data backup,
virus removal, scanning, defragmenting, etc. For example: Antivirus, Disk defragmenter, etc.
Memory Units
Classification of Computer Memory
A) Primary Memory: It is the internal storage that is used by our computer system to store data and
instructions while processing. It is temporary memory and is volatile. It is directly accessed by
the CPU. It is of two types viz. RAM and ROM.
1. RAM: It is an acronym for Random Access Memory. It is a type of Primary memory and is also
known as read and write memory as it can be used for both purposes.
It can be of the following two types:
(i) SRAM: It is an acronym for Static Random Access Memory. It is a type of memory that
requires a constant power supply to hold the data and information. These are made of flip-
flops.
(ii) DRAM: It is an acronym for Dynamic Random Access Memory. The term dynamic
indicates that the memory is constantly needed to be refreshed otherwise it loses its
contents. It is the most common kind of RAM used in personal computers. These are made
of transistors and capacitors.
2. ROM: It is an acronym for Read Only Memory. It provides non-volatile storage of data. We
can access any memory location of ROM by supplying its address.
B) Secondary Memory: It is also known as external memory or non-volatile memory. It is slower
than main memory. These are used for storing data or information permanently. For example:
hard disk, CD-ROM, DVD etc.

9
1. Compact Disc (CD): It is an optical media that is used for electronically recording, storing and
playing back audio, video, text and other information in digital form.
2. Digital Video Disc (DVD): It is also known as Super Density Disc(SDD) or Digital Versatile
Disc(DVD). In appearance, they are somewhat similar to CDs but they have comparatively
more storage capacities than that of CD.
3. Pen drive: It is a storage device that includes flash memory with an integrated Universal Serial
Bus (USB) interface. These are typically removable and rewritable and physically much smaller
than an optical disc.
4. Blu-ray Disc (BD): It is a digital optical disc data storage format designed to supersede the
DVD format. It is capable of storing high-definition video resolution (1080p). It uses a blue-
violet laser to read and writes data with high precision. Its storage capacity is up to 50 GB.

C) Cache Memory: Cache memory is a very high speed semiconductor memory which can speed up
CPU. It acts as a buffer between the CPU and main memory. It is used to hold those parts of data and
program which are most frequently used by CPU.

Advantages
The advantages of cache memory are as follows:
• Cache memory is faster than main memory.
• It consumes less access time as compared to main memory.
• It stores the program that can be executed within a short period of time.
• It stores data for temporary use.

Disadvantages
The disadvantages of cache memory are as follows:
• Cache memory has limited capacity.
• It is very expensive

The smallest unit is bit, which mean either 0 or 1.


1 bit = 0 or 1
1 Byte = 8 bit
1 Nibble = 4 bit
1 Kilo Byte = 1024 Byte= 210 Byte
1 Mega Byte = 1024 KB= 210 KB

10
1 Gega Byte = 1024 MB= 210 MB
1 Tera Byte = 1024 GB= 210 GB
1 Peta Byte =1024 TB= 210 TB
1 Exa Byte =1024 PB= 210 PB
1 Zetta Byte = 1024 EB= 210 EB
1 Yotta Byte = 1024 ZB= 210 ZB

Input – Output (I/O) Devices


Input Devices
• Input unit is used to accept data and instructions from the user.
• Keyboard is used to type in letters, digits and commands.
• Mouse is a pointing input device.
• Microphone is used to send input to the computer.
• A scanner creates an electronic form of the printed image. Scanner are of three type: Handheld,
Flatbed and Drum.
• A touch screen can detect where on the screen surface you are touching.
• A barcode reader is a handheld device that is used to obtain data contained in a bar code.
• Light pen is a handheld electro optical pointing device which is used for making drawings,
graphics and for menu selection.
Output Devices
• Output unit is responsible for producing the output in user-readable form.
• Monitor displays information in a way similar to that shown on a television screen.
• The picture on a monitor is made up of thousands of tiny coloured dots called pixels.
• CRT (Cathode Ray Tube) contains an electron gun at the back of the glass tube.
• Liquid Crystal is a material used to create each pixel on the screen in LCD.
• TFT (Thin Film Transistor) is the device within each pixel that sets the charge.
• PDP (Plasma Display Panels) are flat panel displays.
• Plasma technology utilises small cells containing electrically charged ionised gases.
• Printer prints information and data from the computer onto a paper.
• Printer are divided into two categories: impact printer and Non-impact printer.
• Speakers receive the sound in form of electric current from the sound card.
• The Plotter is a graphic output device used to create drawings on paper.
Port: It is a connection point of interface between a computer and internal or external devices. Some
common types of ports are - Serial Port, USB Port, Bluetooth, IR port etc.
Serial Port: Serial port is also known as COM Ports (communication ports).These are used to
connect devices such as mouse, modem, etc. In this type of ports, only 1 bit of information can
travel at a time.
Parallel Port: Parallel port is a type of port in which data are sent and received simultaneously over
several parallel channels. It can transfer up to 8 bits of data at a time. It is used to connect
peripheral devices such as printer.
USB Port: USB Port is an acronym for Universal Serial Bus Port. It comes under a serial port and is
used for short distance digital data communication. It allows data transfer between devices with
little electric power.
PS/2 Port: PS/2 Port is a type of port developed by IBM for connecting a mouse or a keyboard to the
computer.

11
Infrared Port: Infrared Port is also known as an IR port. It is a meta port that sends and receives
infrared signals from other infrared-enabled devices.

Software Concept
It represents the set of programs that governs the operations of a computer system and make the
hardware run smoothly.
Types of Software
(i) System Software: These softwares are mandatory for all computer systems to work. For
example: Operating Systems like Windows and language processors like assembler, etc.
(ii) Application Software: These softwares are made to perform a specific task. For example:
WordPad, MS-Word, etc.
(iii) Utility Software: It is used to perform some additional functions which make our computer
safer, secure and work smoothly
UTILITY SOFTWARE
Utility Software is used to perform some additional functions which makes our computer more
safe, secure and work smoothly. Utility software is considered to be a part of system software.
For example, antivirus, disk defragmenter, etc.
(i) Antivirus: it is utility software which detects and removes computer viruses. The antivirus
keeps a watch on the functioning of the computer system.
(ii) Disk Defragmenter: it scans the hard disk for fragmented files and brings all the fragments
together.
(iii) Backup Utility: It is used to create the copy of the complete or partial data stored in a disk or
CD on any other disk. In case the hard disk crashes or some other system failure occurs, the
files can be restored using backup software.
(iv) Compression Utility: It is used to compress large files. Compression is useful because it helps
reduce resources usage and the file transmission on the network becomes easier.
(v) Disk Cleaner: It scans for files that have not been accessed/used since long. Such files might
be occupying huge amount of memory space.
(vi) File Management Tools: It helps the user in storing, indexing, searching and sorting files and
folders on the system. e.g. Windows Explorer.
SYSTEM SOFTWARE:
(i) Operating System (OS): It is a system program that acts as an interface between user and the
machine. It allocates and manages the resources of the computer.
(ii) Language Translators: It is a program used to convert a program written in HLL(High Level
Language) or assembly language to machine language.
(a) Compiler: It is a system program which translates a program written in a high level
language into its equivalent program in machine language.
(b) Interpreter: Interpreter converts a HLL program into equivalent machine language
program one line at a time and executing it, if no error is encountered.
(c) Assembler: Assembler is a system program that converts an assembly language program
into the machine language of the host computer.
(iii) Device Drivers: It is a program that controls a particular type of device that is attached
externally to a computer.
APPLICATION SOFTWARE

12
(i) General Purpose Application Software: A software which is made for the common users for
day to day application and uses. Example: Word Processor, Presentation Tools,
Spreadsheet Packages, Database Management System , Graphics Software.
(ii) Special or Specific-Purpose (Customised Software): those software which have been
developed for a user for task which is very specific to them.
• Customised Software , Payroll Management System, Hotel Management etc.
A programming tool or software development tool is a computer program that software
developers use to create, debug, maintain, or otherwise support other programs and applications.

Operating System (OS)


It is defined as a collection of programs that coordinates the operations of computer hardware and
software. It acts as a bridge or the interface between man and machine.
Functions of an Operating System
• Device management: Operating system ensures the smooth functioning of all the peripheral
devices.
• Processor management: Operating system enables the activities of planning, performing and
monitoring the performance of any process.
• Memory management: It is the act of managing memory i.e., provide required memory for the
process to happen and then save the desired result back in the memory.
• File management: This function of operating system allows the user to create a file, write into
it, open it for reading, close it after reading or writing is over and delete it, if it is not required
any more.
Types of Operating Systems
• Real Time Operating System (RTOS): RTOS is a multi-tasking operating system that aims to
execute real time applications. It is designed to respond to an event within a predetermined
time. These are used to control machinery, scientific instruments and industrial systems.
For example: Windows CE, Linux, etc.
• Multi user operating system: It is the type of operating system that allows many users to take
the advantage of computer’s resources simultaneously.
For example: UNIX, VMS, etc.
• Single user operating system: Single user operating system is designed for one user to
effectively use a computer at a time.
For example: Windows 2007, Windows 10, etc.
• Single tasking operating system: It is an operating system which can run only one program at
a time. For example: Palm
• Multi-tasking operating system: This operating system allows the execution of multiple tasks
at a time.
For example: Windows 2007/2008/2009 /XP, etc.
• Time sharing operating system: It allows the users to share the computer resources
simultaneously.
For example: A mainframe computer that has many users logged on to it.
• Distributed operating system: Distributed operating system uses multiple central processors
to serve multiple real time applications.
User Interface
The feature of a computer system which allows the user to interact with it.

13
There are two prevalent types of user interface:
• Command Line Interface: It requires users to type appropriate instructions into the command
line.
• Graphical User Interface: GUI is the type of interface in which user interacts by using a mouse or
other peripheral to point and click on graphics or icons.
Questions to Solve:
A) Identify the following peripherals as INPUT device or OUTPUT device.
1. Monitor _______
2. Keyboard __________
3. Scanner ___________
4. Laser Printer ____________
5. Mouse ____________
6. Speakers _____________
7. Digital Camera _____________

B) Fill in the blank with the correct answer from the box. Some may be used more than once or not at
all.

1. I connect computers and allow them to talk to each other. ______________________


2. I wake up the computer and remind it what to do. __________________
3. I am the brain of the computer. _________________________
4. Information is stored on my magnetic cylinders. ________________________
5. I hold all of the other circuit boards. _______________________
6. I handle the graphics that are displayed on the monitor. ___________________
7. I am the type of port used by flash drives __________________________

C) Fill in the blanks with the vocabulary words from the box. Use each word only once.

1. ________________________ memory is stored on chips located on the motherboard.


2. _________________________memory is stored on the hard drive.
3. A _______________________can hold information greater than a CD or DVD.
4. A _______________________usually holds up to 650 to 700 MB.
5. A _______________________holds even more information at least 7 GB.
6. The purpose of storage in a computer is to hold ____________________or data.
7. A computer that is easy to operate is called ________________ .
8. ___________________is the most common operating system for PCs.
9. Operating systems are constantly being_________________________ as technology advances.
10. A Graphical User Interface (GUI) uses__________________ to help the user navigate within the
computer system.

Short Answer Type Questions with solution:

14
Q1. Write the full form of ASCII.
Ans: American Standard Code for Information Interchange
Q2. Differentiate between Interpreter and Compiler.
Ans: An interpreter converts HLL program into machine language line by line and simultaneously
executes the converted line. A compiler converts an HLL into machine language in one go.
Q3. What is the difference between RAM and ROM?
Ans:

Q4. What is a language processor? Write the name of two language processors.
Ans. A language processor is a software program for processing program code to machine code. Ex,
Compiler, Interpreter.
MCQ Type Questions:
Q1. Which smaller unit of CPU directs and coordinates all activities within it and determines the
sequence in which instructions are executed, sending instructions sequence to other smaller unit.
a) CU b) ALU c) Processor d) All of the above
Q2. Which is not Secondary Storage Device?
a) RAM b) ROM c) Cache Memory d) All of the above.
Q3. Which is not Utility Software?
a) MS Office b) Antivirus c) Disk Cleanup d) Compression Tools
Q4. Which is not Language Processor?
a) Assembler b) Compiler c) Interpreter d) Disk Defragmenter
Q5 MICR stands for?
a) Maganetic Ink Character Reader b) Maganetic Ink Code Reader
c) Maganetic Ink Caser Reader d) Maganetic Ink Computer Reader
Q6. When we work on any document on PC, it is stored temporarily in ____ memory
a) RAM b) ROM c) CPU d) CD-ROM
Q7. What do you call a program in execution?
a). Command b) Process c) Task d) Instruction
Q8. Which of the following is not an operating system?
a). Windows b) Linux c) Oracle d) DOS
Q9 Which is not Secondary Storage Device?
a). RAM b) ROM c) Cache Memory d) All of the above
Q10. Which is not Language Processor?
a). Assembler b) Compiler c) Interpreter d) Disk Defragmenter

Long Answer Type Question:


15
Q1. Explain the types of Memory of Computer with example.
Q2. What do you mean by Firmware? Explain the use of BIOS?
Q3. What is computer? Explain the main components of computer system with block diagram ?
Q4. Explain types of Computer based on size and performance with example?
Q5. What is the difference between Multi user Operating System and Multi processing Operating
System.

Q6. What is Operating System? Explain the functions of Operating System?


Q7. What is ROM? Explain about different types of ROM.
Q8. What do you mean by Peripheral Device? Name two Peripheral Devices of Computer?
Q9 Explain following Terms?
(a) Printer
(b) Keyboard
(c) Mouse
(d) Arithmetic Logic unit
Q10. Which of the following is designed to control the operations of a computer?
a) Application Software b) System Software c) Utility Software d) User

BOOLEAN ALGEBRA
It is developed by George Boole in 1854 and deals with binary values and logical operations and
hence is also known as Binary Algebra or Logical Algebra. It helps us in analysing and
simplifying the digital circuits.
Boolean Algebra uses three basic logical operators:-
• NOT operator – It operates on single input and gives complement of the input as output. Thus if
A = 0, then A' =1 and vice versa.
• OR operator – It is a binary operator equivalent to a logical (+) addition. Thus A + B implies A
OR B. This operator gives a true (i.e. 1) if any of the operand is True or 1.
• AND operator – It is a binary operator equivalent to logical (·) multiplication. Thus A · B implies
A AND B. It gives a true (i.e. 1) only if both the operands are True or 1.
A logical variable can take only two values i.e. either a binary 1 or a binary 0. While evaluating
Boolean expression the order of evaluation of logical operators is NOT, AND then OR, Parenthesis
is evaluated first.
Truth Table – It is tabulated form of all the possible input combinations and their respective
outputs. The number of possible input combinations for a Boolean expression is 2n, where n is the
number of input variables. Hence, for a Boolean function F(A,B), number of possible combinations
will be 4 and for a Boolean function F(A,B,C,D) it will be 16.

Basic Rules (Postulates) of Boolean Algebra


• X + 0 = X or 0 +X = X
• X + 1 = 1 or 1 + X = 1
•X.0=0
•X.1=X
De Morgan's theorems
(i) (ii)

16
The dual principle or principle of duality says that the Boolean algebra remains unchanged when the
dual pairs are interchanged. But nothing goes with compliment because compliment is self-dual
operation.
Principle of Duality states that starting with a Boolean relation, another Boolean relation can be
derived by
1. Changing each OR sign (+) to an AND sign (.).
2. Changing each AND sign (.) to an OR sign (+).
3. Replacing each 0 by 1 and each 1 by 0.
Logic circuit, electric circuit whose output depends upon the input in a way that can be expressed
as a function in symbolic logic; it has one or more binary inputs and a single binary output. Logic
circuits that perform particular functions are called logic gates.
• NOT Gate is an inverter circuit that operates on single input. It gives complement of the input as
the output. It is represented by the following symbol.

.
AND Gate gives a high output if both the inputs are high. Algebraically it is represented by a (.) dot.
Its electronic symbol is

OR Gate gives a high input if any one of the inputs is high. Its algebraic symbol is (+) Plus, and
electronically it is represented as

NAND Gate is inverter of AND gate. It gives a High Input if any of the inputs is low. Its symbol is AND
Gate with a small circle at the output implying inversion.

NOR Gate is inverter of OR. Its output is low if any of the inputs is high. Its symbol is OR Gate with a
small circle at the output implying inversion.

XOR Gate gives a high output if odd number of inputs is high. It is used to detect the mismatch of bits.
Its algebraic symbol is ⊕.
XNOR Gate gives a high output when both the inputs are same i.e., either both are high or both are
low.
Tautology: It is an expression or assertion that is always true.
Fallacy: An expression that always yields 0 or false is called Fallacy.
Universal gates – NAND and NOR gates are known as universal gates as any possible circuit can be
built using these two gates.
Questions:
17
Q1. Which is Universal Gate?
a) AND Gate b) OR Gate c) NOR Gate d) NOT Gate
Q2. Which gate returns true if both inputs are similar otherwise false.
a) NAND b) NOR c) XOR d) None of the above
Q3. Which of the following is / are the universal logic gates?
a) OR and NOR b) AND c) NAND and NOR d) NOT
Q4. Write the equivalent Boolean expression for the following Logic circuit.

a) (P+Q’).(Q+R’) b) (P’+Q).(Q+R’) c) (P’+Q’).(Q’+R) d) (P’+Q’).(Q’+R’)


Q5. DE Morgan’s Law states that
a) (AB)’ = A’ + B’ b) (A+B)’ = A’ * B c) (A’+B’) = A’.B’ d) (AB)’ = A’+B

Q6. Draw a Logic Diagram of given Boolean Expression F(X,Y,Z) = ((X’+Y).(X+Y’+Z))’


Q7. Draw Truth Table of given Boolean Expression F(A,B,C) = ((A.B)+C)(A+C)
Q8. Draw the logic circuit diagram for the expression: X=AB'+B'C'+ABC.
Q9. Write the truth table for NOR gate.
Q10. Construct the logic circuit of the given Boolean Expression?
F (A, B, C, D) = (A+B) C + (ABCD)’ + (AB)’+CD

NUMBER SYSTEM AND ENCODING SCHEMES


Number System
A set of values used to represent different quantities is known as number system.
The four most common number systems are:
(1) Decimal Number System: The decimal number system has base or radix 10 because it uses
ten digits from 0 to 9.
(2) Binary Number System: The Base-2 number system is also famously known as the Binary
Number System wherein only two binary digits exist, i.e., 0 and 1.
(3) Octal Number System: Octal number system has only eight (8) digits from 0 to 7. The
base of octal number system is 8, because it has only 8 digits.
(4) Hexadecimal Number System: A Hexadecimal number system has sixteen (16)
alphanumeric values from 0 to 9 and A to F. The base of hexadecimal number system is 16,
because it uses 16 alphanumeric values. Here A is 10, B is 11, C is 12, D is 13, E is 14 and F is 15.

18
Relation between various number systems is given below:

Conversion between Number Systems.

Let's break down each conversion:

1. Binary (Base 2):


○ To convert decimal 76 to binary:
■ Divide 76 by 2:
■ 76 / 2 = 38 remainder 0
■ 38 / 2 = 19 remainder 0
■ 19 / 2 = 9 remainder 1
■ 9 / 2 = 4 remainder 1
■ 4 / 2 = 2 remainder 0
■ 2 / 2 = 1 remainder 0
■ 1 / 2 = 0 remainder 1 (stop here)
○ Reading remainders from bottom to top gives us: 1001100
2. Octal (Base 8):
○ To convert decimal 76 to octal:
■ Divide 76 by 8:
■ 76 / 8 = 9 remainder 4
■ 9 / 8 = 1 remainder 1
■ 1 / 8 = 0 remainder 1 (stop here)
○ Reading remainders from bottom to top gives us: 114
3. Hexadecimal (Base 16):
○ To convert decimal 76 to hexadecimal:
■ Divide 76 by 16:
■ 76 / 16 = 4 remainder 12 (which is C in hexadecimal)
19
■ 4 /16 = 0 reminder 4 (stop here)
■ Reading remainders from bottom to top gives us:
○ Therefore, 76 in hexadecimal is 4C.

Conversion from Decimal to Any Number: Use Division method: Dividing Decimal Number by base
of number in which we have to convert and write down remainder in reverse order.
Any other Number to Decimal Number: Multiply each digit with the positional power of the base
which is converting to decimal.
Conversion from Binary / Octal / Hexadecimal to Binary / Octal / Hexadecimal: use bit
Combination method for Octal – 3 bit and for Hexadecimal – 4 bit Combination.

Method of one’s complement: One complement of a binary number is found by inverting the zero
and one’s without changing the number of digits.
1’s complement of 111001 is 000110

Method of two’s complement: Two’s complement of a binary number is found by adding 1 to its
one’s complement.
Steps:
• At first 2’s complement of the subtrahend is found.
• Then it is added to the minuend.
• If the final carry over of sum is 1 it is dropped and result is positive
• If there is no carry over, the 2’s complement of sum will be the result and it is negative.
e.g 10110 – 11010
2’s complement of 11010 is (00101 + 1)
i.e., 00110
Hence minuend 1 0 1 1 0
2’s complement of subtrahend + 0 0 1 1 0
11100
As there is no carry over, the result of subtraction is negative and is obtained by writing the 2’s
complement of 11100 i.e., (000110 + 1) or 00100
Hence the difference is – 100
Encoding Schemes
Integers may be represented in various ways in computers. These are
(a) Sign and magnitude representation
(b) One’s complement, Two complement
Some of the main computer codes are:
(i) ASCII Code: American Standard Code for Information Interchange. It is a 7-bit code so it has 27
— 128 possible code groups.
(ii) ISCII Code: Indian Standard Code for Information Interchange. It is a 8-bit code so it has 28=
256 possible code groups. It retains all ASCII characters and offers coding for Indian
characters also.
(iii) UNICODE: It is the new universal coding standard being adopted by all newer platforms.
Unicode provides a unique number for every character, no matter what the platform or
program or the language is. Commonly used UNICODE encodings are UTF-8, UTF-16 and UTF-
32. It is a superset of ASCII, and the values 0–128 have the same character as in ASCII.
Questions:
20
Q1. The hexadecimal digits are 1 to 0 and A to _______?
a) E b) F c) G d) D
Q2. ASCII is a _________ bit code and ISCII is a ___________ bit code.
a) 8, 7 b) 7, 8 c) 8, 8 d) 7, 7
Q3. According to the distributive law A (B+C) = __________.
a) ABC b) AB+AC c) A+B+C d) A+BC
Q4. Convert the following: (i)(4A)16=(______)2 (ii) (106)10=(_____)8
Q5. Convert the decimal number 106 to
a) binary and b) octal.
Q6. ASCII uses ____ bits to represent Characters.
a) 5 b) 6 c) 7 d) 8
Q7. How many bits forms a Kilo Byte?
a) 8194 Bits b) 8192 bits c) 4096 bits d) 1024 bits
Q8. Convert the following number in to given numbers:
a) (345.24)10 =( )2 b) (A35.57)16 =( )8
Q9. Convert the following numbers in the given equivalent number system.
a). (234.56)10 = ( )2 b) (1101111.11011)2 = ( )16
Q10. Full form of USB
a) Uniform Service Bus b) Universal Serial Bus c). Universal Sector Buffer d) Universal
Service Bus
Unit – 2 (Computational Thinking and Programming)
Problem and Problem Solving
In computer science, "problem" refers to a task or challenge that requires a solution. The process
of identifying a problem, developing an algorithm, and implementing an algorithm to develop a
computer program is called Problem Solving.
Steps required for solving a problem
● Analyzing the problem
● Developing an Algorithm
● Coding
● Testing and Debugging

Analyzing the Problem


This stage focuses on understanding the problem. If we do not have a clear understanding of the
problem, we may develop a computer program that cannot solve the problem correctly. In this
stage, we figure out the inputs, the outputs and the processing required to convert the input into
the output.
Developing Algorithm
This stage focuses on creating a logical sequence of instructions, called an Algorithm. An algorithm
has a distinct start and end point, as well as a defined number of steps.
Draw a flow-chart to identify whether a number taken as the input from the user is an
even number or an odd number?

Algorithm Flow Chart

21
START
Step 1 → Take an integer number A as
input Step 2 → Divide A by 2, and store the
remainder as r
Step 3 → If r is zero, Display 'Even'
Step 4 → Else Display 'Odd'
STOP

Coding
Coding is the process of creating computer programs.
Testing
Testing is a process to check if an application is working as expected. The main objective of
Testing is to find errors.
Debugging
Debugging is the activity to fix the errors found in the application during the testing phase.
Representation of Algorithms
There are two common methods of representing an algorithm —flowchart and pseudocode.

Pseudocode
● Pseudocode is a way of representing an algorithm in readable and easy language.
● Pseudocode is not an actual program. So, it cannot be executed.
● Some of the frequently used keywords while writing pseudocode are INPUT, COMPUTE, PRINT
IF/ELSE, START, STOP

Advantages of Pseudo-Code:
1. Easily convertible to a Programming Language
2. Easy to understand and read
Write a pseudocode for identifying if a number is even or odd.
INPUT number A
COMPUTE remainder as r = A%2
IF r ==0 PRINT 'Even'
ELSE PRINT 'Odd'

Decomposition
Decomposition is the process of breaking a complex computer problem into smaller parts that are
easily manageable and solvable

Computer Program:

22
A computer program is a set of instructions written in a programming language that can be
executed by the computer to perform and solve a certain task.
Python Programming Language:
Python is an interpreted, high-level programming language. It was developed by Guido van Rossum.
It is user-friendly and is most popular for its easy-to-use syntax and readable code. It is case
sensitive.

Working in Python
i) Install Python on the computer (https://www.python.org/downloads/).
ii) Use Python IDLE (Integrated Development and Learning Environment) for developing python
Programs.

How to Display Data


print( ) function is used to print a message on the screen.

A Simple Hello World Program


print("Hello World")

Modes of working in Python


● Interactive Mode
● Script Mode

Interactive Mode
In Interactive Mode, a python statement is executed in a command-line shell. It provides instant
feedback for each statement while keeping prior statements in memory.

Script Mode
In script mode, the instructions are saved in a file with a '.py' extension and executed from the
beginning of the file. This mode is suitable for creating and running large programs.

Character Set:
A character set is a collection of valid characters that can be recognized by a language. Python
Language recognises the following characters as valid:
23
Letters : A-Z, a-z
Digits : 0-9
Special Symbol : + / @ ! - = <> == etc.
Whitespaces : '\n', '\t' etc.
Tokens
Tokens are the smallest individual units of a program.

Keywords
Keywords are reserved words with special meaning (known to the interpreter). These can not be
used as identifiers in a program.
Example: for, while, else, if
Identifier
A variable, function, class, module, or other objects are identified by a name known as identifier.
Rules for naming an identifier:
1. First character of a variable can be an alphabet (A-Z or a-z) or an underscore(_).
2. Next characters of a variable can be an alphabet (A-Z or a-z), an underscore(_) or a digit.
3. Keywords cannot be used as variables.
4. First character cannot be a digit.
5. Special characters including white spaces are not allowed.

Literals:
Literals are data-items that have a fixed value of a certain data type, such as a number, string,
boolean, or None. They are also known as Constants.

Example :
String literals (Text) : 'Hello World'
Numeric literals (Numbers) : 3.14
Boolean literals (Truth Value) : True/False
None Literal : The None keyword is used to define a null value or absence of a value. None is
different from 0.

Operators and Operands


Operators are symbols (or keywords) that perform various operations on the operands. An operand
is a variable or a literal on which the operation is performed.
Example: 50 + 20
24
Here 50 and 20 are operands, and + is the operator.

Arithmetic Operators : Arithmetic operators perform mathematical operations like addition,


subtraction, multiplication, division, floor division, exponent and modulus. (+,-,*,/,//,**,%)

Relational Operators:
Relational operators perform comparison between values. An expression having relational operators
evaluates to either True or False. Example >, <, >=, <=, ==, !=

Logical Operators:
These operators are used to combine conditional statements.

Examples:

○ and: True if both the operands are true.


○ or: True if either of the operands is true.
○ not: True if the operand is false (complements the operand).

Assignment Operators: These operators are used to assign values to variables.

Examples:

○ = (Assign): Assigns the value on the right to the variable on the left.
○ +=, -=, *=, /=: These operators combine arithmetic operations with assignment.

Membership Operators:

These operators test for membership in sequences (lists, tuples, strings).

Examples:

○ in: True if value/variable is found in the sequence.


○ not in: True if value/variable is not found in the sequence.

Identity Operators:

These operators compare the memory locations of two objects.

Examples:

○ is: True if the operands are identical (refer to the same object).
○ is not: True if the operands are not identical (do not refer to the same object).

Python Comments
Comments are descriptions about the code. They help other programmers understand the
functionality of the code. Comments are ignored by the Python interpreter.

Variable

25
Variables refer to an object (data items like int, float, list, dictionary etc.) stored in the memory. Value
stored in a variable can be changed during the program execution.
Rules for naming a variable are the same as the rules for naming an Identifier.

Concept of L Value and R Value


In Python, the l-value refers to the left-hand side of an assignment operator, while the r-value refers
to the right-hand side of an assignment operator.

Consider the following assignment statement:


x = 5+2
In the statement above, the l-value is 'x' as it is on the left-hand side of the = operator.
The r-value is 7 as it is on the right-hand side of the = operator

● Knowledge of data types: Number(integer, floating point,complex), boolean, sequence(string, list,


tuple), None, Mapping(dictionary), mutable and immutable data types.

Data Type
Data type represents the type of data a Variable or a Literal is referring to. Each data type has specific
characteristics and operations associated with it. In Python, there are various data types, including
number, string, boolean, list, tuple, and dictionary.

Mutable and Immutable Data Objects


Python variables are memory references. It may be required to change or update the value of an
object referenced by a variable.

Mutable Objects:
Mutable data objects are objects that can be changed after they are created. It is possible to add,
remove, or modify elements within these data types. Example of mutable data types: List, Set and
Dictionary.
Immutable Objects :

26
Objects whose values cannot be changed after they are created are called immutable objects. To
change the value, a new object is created. Example of immutable data types: Number (Integer, Float),
String, and Tuple.

Numeric Data Types (Number)


Python has three numeric data types:
1. Integer
2. Float
3. Complex
Integer
● Numbers with No Fractional Part
● Can be Positive or Negative
● In Python 3, the int type has no max limit. Values can be as large as the available memory
allows.
● Example 100, 0o55 (octal number), 0x68(hexadecimal number)
Float
● Numbers with Fractional Part
● Example 3.14, .314E01
Complex
● Numbers with both real and imaginary components
● A complex number is represented by "x + yj". Example 10 + 9j
Boolean
A boolean data type can assume one of the two possible values : True or False.

Sequence: Sequence is an ordered collection of items or elements which includes several built-in
types as String, List, and Tuple. Values in the sequence are called elements/items. Each element in a
sequence has a unique index.
String:
● A string is an ordered sequence of characters enclosed in single/double/triple quotes.
● Single Line String : Terminates in a single line. Example – 'This is an example of single line'
● Multi Line String : Does not terminate in a single line. A multiline string may be created using
three quotes
List:
27
● List is an ordered sequence data type which can store values of any data type.
● List is mutable.
● List is enclosed in square brackets [ ]
● Example : [ ] is an empty List,
[5, 6.5, True, 'Hello'] is a List having 5, 6.5, True and 'Hello' as four elements.

Tuple:
● Tuple is an ordered sequence which can store values of any data type.
● They are immutable, i.e the items of a Tuple cannot be updated after creation.
● Tuple is enclosed in parenthesis ( )
● Example : t=( ) is an empty Tuple
t=(9,) is a Tuple with 9 as an item
t=(8, 5, 9.5, False) is a Tuple with 8, 5, 9.5, False as four items
Mapping
Mapping is an unordered data type in Python. Currently, there is only one standard mapping data
type in Python called dictionary.
Dictionary:
● Dictionary in Python stores items in the form of key-value pairs
● Syntax is dict_variable = {key1:value1, key2:value2, …, key-n:value-n}
● Items in a dictionary are enclosed in curly brackets { } and are separated by commas
● In a key-value pair, the key is separated from the value using a colon (:)
● To access any value in the dictionary, specify the key as the index using square brackets [ ].
● Example : { } is an empty dictionary,
D = {'name':'Python','version':'3.7.2', 'OS': 'Windows'}
print(D['version']) # shows 3.7.2 as output
Special Data-type: None
The None data type/keyword is used to indicate absence of a value (No value or Missing Value).
Example
>>> myVar = None
>>> print(type(myVar))
<class 'NoneType'>
>>> print(myVar)
None
Operator Precedence(PEMDAS)
PEMDAS stands for Parentheses, Exponents, Multiplication and Division, and Addition and
Subtraction. Let's look at each component:

28
Expression
An expression is combination of operators, operands, literals and parenthesis. An expression
produces a value when evaluated.
Evaluation of Expression
1. Evaluate the expression 50 + 20 * 30
Evaluation:
= 50 + (20 * 30) #precedence of * is more than that of +
= 50 + 600
= 650
2. Evaluate the expression 100 - 20 + 50
Evaluation:
The two operators (–) and (+) have equal precedence and the associativity is from left to right so the
left operator (i.e. -) will be evaluated first.
= (100 – 20) + 50
= 80 + 50
= 130
3. Evaluate the expression 9 + 3 ** 2 * 4 // 3
Evaluation:
= 9 + (3 ** 3) * 4 // 3
= 9 + 27 * 4 // 3 (* and // has left to right associativity)
= 9 + 108 // 3
= 9 + 36
= 45
Type conversion
It is the process of converting the value from one data type into another. Python supports two ways
of Type conversion:
● Implicit conversion
● Explicit conversion
Implicit conversion
This type of conversion is performed by Python Interpreter automatically without the user's
intervention.
Example:
num1 = 20 # num1 is integer
num2 = 30.5 # num2 is float
sum1 = num1 + num2 # sum1 will use float to avoid
# loss of fractional part during addition

29
print(sum1)
print(type(sum1))
Output:
50.5
<class 'float'>

Explicit Conversion:
This type of conversion is performed by the user manually. It is also known as type-casting. Explicit
type-casting is performed using functions such as int( ), float( ), str( ) etc.
Syntax : new_data_type (expression)
Example
num1 = input("Enter a number : ") # takes a string input by default
var1 = int(num1) #converts string to integer
var1 = var1 * 3
print(var)
Output
Enter a number : 2
6
Question 1:
Write the output of the given Python code :
a=0
a+ =2
print (a)
a) 2 b) 4 c) 6
Question 2:
Write the output of the given Python code :
a = 20
if a > = 22:
print(“if”)
elif a >= 21:
print(“elif”)
else:
print(“else”)
a) Else b) else c)elif
Question 3:
Which Operator is used for comparison of values?
a) Logical Operators b) Assignment Operators c) Relational Operators
Question 4:
What will be the output of the following code :
a=1
a, b = a+1, a+1
print(a)
print(b)
a) 2,2 b)4,2 c)2,6
Question 5:

30
Use IDLE to calculate : [CBSE Text Book]
(a) 6 + 4 * 10
(b) (6 + 4) * 10
i) (a) 46 b) 100 ii)a) 100 b)46 iii) a)100 b)100
Question 6:
What will be the output of the following code : [CBSE Text Book]
a = 3 – 4 + 10
b=5*6
c = 7.0/8.0
print(a,b,c, sep=”,”)
i)9,30,0 ii)9,30,1 iii)10,30,0
Question 7:
What will be the output of following code?
X, Y=2,6
X,Y = Y,X+2
print(X,Y)
a) 17 5 b)6 4 c)4 6
Question 8:
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is z)
a) True b)False c)True or False
Question 9:
x = ["apple", "banana"]
print("banana" in x)
a) True b)False c)True or False
Question 10:
What will be the output of following code?
12 & 13
a) 12 b)13 c)12 & 13
Question 11:
Which are correct arithmetical operations?
i) a = 1*2
ii) 2 = 1+1
iii) 5 + 6 = y
iv) Seven = 3 * 4
Question 12:
Which operations result in 8?
i) 65 // 8
ii) 17 % 9
iii) 2 * * 4
iv) 64 * * 0.5
Question 13:
If the value of a = 20 and b = 20, then a+=b will assign ________ to a

31
a) 40 b) 30 c) 20 d) 10
Question 14:
The ____________ operator is used to find out if division of two number yields any remainder
a) / b) + c) % d) //
Question 15:
Which of the following is the relational operator
a. //
b. =
c. ==
d. and

Input and Output in Python


Data Input:
input( ) function is used for getting input from the user. It returns the input as a String data type by
default.
Explicit type casting is required to convert the input string into any other data type if required.
Data Output:
print( ) function is used for displaying output on the screen.
Example-1
num1 = int(input("Enter a Number : ")) # type casting the input from
String to Int
print("The Number is : ", num1)
Example-2
num = int(input("Enter a Number : "))
num_cube = num*num*num
print("The cube is : ",num_cube)

Errors
A programmer can make mistakes while writing a program, and hence, the program may not execute
or may generate wrong output. The process of identifying and removing such mistakes, also known
as bugs or errors, from a program is called debugging.
Errors occurring in programs can be categorised as:
i) Syntax errors.
ii) Logical errors
iii) Runtime errors
Syntax Error
Like other programming languages, Python has its own rules that determine its syntax. The
interpreter interprets the statements only if it is syntactically (as per the rules of Python) correct. If
any syntax error is present, the interpreter shows error message(s) and stops the execution there.
For example, parentheses must be in pairs, so the expression (10 + 12) is syntactically correct,
whereas (7 + 11 is not due to absence of right parenthesis. Such errors need to be removed before
the execution of the program
Some of the Common Syntax Errors are
● Parenthesis Mismatch
● Misspelled keyword

32
● Incorrect Indentation
Logical Error
Logical errors occur when the code runs without any errors, but the output is not as expected. Logical
errors are caused by a problem in the logic of the code.
Example : Average = mark_1 + mark_2 / 2 # incorrect calculation of average marks
Corrected Code : Average = (mark_1 + mark_2 ) / 2
Runtime Error
A runtime error causes abnormal termination of the program during the execution. Runtime error
occurs when the statement is correct syntactically, but the interpreter cannot execute it.
Runtime errors do not appear until after the program starts running or executing.
Example: 'division by zero'
num1 = 5.0
num2 = int(input("num2 = ")) #if the user inputs zero, a runtime error will occur
print(num1/num2)

Flow of Control
Flow of Control refers to the order in which statements are executed in a program.
Sequential Flow
The default control flow in a program is sequential flow, in which statements are executed line-by-
line one after the other in a sequence in which they are written.
Example
x=6
y=7
z=y-x
print(z)
Conditional Flow
Conditional flow refers to execution of certain statements only if a specific condition is met. This is
accomplished by the use of conditional statements such as if, if-else, and if-elif-else.
Example
num = int(input("Enter a number : "))
if(num>5):
print("Number is greater than 5")
else:
print("Number is less than 5")
Output
Enter a number : 55
Number is greater than 5
Iterative Flow
Iteration means 'repetition'.
Iterative flow repeats statements in a block of code. Repetition or looping can be performed a fixed
number of times or until a certain condition is met. This is accomplished through the use of iterative
statements: for and while.
Example-1
name = input("Enter your name : ")
for x in range(5): # range function creates a sequence of integers from 0 to 4

33
print("Hello", name)
Example-2
name = input("Enter your name : ")
i=1
while i<=5:
print("Hello", name)
i +=1
MCQ

1.Which one of the following is a valid Python if statement :


a. if a>=2 : b. if (a >= 2) c. if (a => 22) d. if a >= 22
2.The order of statement execution in the form of top to bottom is known as construct.
a. alternate b. sequence c. flow of data d. flow chart
3.The two membership operators are ..........and ............
a. in, not in b. true , false c.=,== d. none
4.A graphical representation of an algorithm to solve a problem is called ...............
a. flow of data b. barchart c. flow chart d. none
5.What is the logical expression for the following
Either A is greater than B or A is less than C
a. A>B or A<C b. A>B and A<C c . A>Band C d. A>Bor C
6.Which statement will check if a is equal to b?
a. if a = b: b. if a == b: c. if a === c: d. if a == b
7.Consider the given expression:
"Python" or True and "Programming" or not 70
Which of the following will be correct output if the given expression is evaluated ?
(a) True (b) False (c) ‘Python’ (d) ‘Programming’
8.What shape represents a decision in a flowchart ?
(a) A diamond (b) A rectangle (c) An oval (d) A parallelogram
9. To add and assign the value 10 to a variable a we cannot write
(a) a=a+10 (b) a+=10 (c ) a=+10 (d) a=10+10

Very Short Answers


Answer the Following Questions (Very Short Answers)
i. Define Algorithm
ii. What is decomposition?
iii. Why do we need Algorithm?
iv. What is meant by Debugging?
v. Write difference between algorithm and flowchart.
vi. Write the pseudocode to print all multiples of 5 between 10 and 25 (including both 10 and 25).
vii. Write an algorithm to find the greatest among two different numbers
viii. Write a pseudocode to calculate the factorial of a number
ix. Write an algorithm to find greatest among three numbers
x. Is ‘None’ and None same? Explain Why.
Case based:

34
Following is an algorithm for going to school or college. Can you suggest improvements in this to
include other options?
Reach_School_Algorithm
a) Wake up
b) Get ready
c) Take lunch box
d) Take bus
e) Get off the bus
f) Reach school or college
Short Answers
Answer the Following Questions (Short Answers)
1) What is empty statement in Python? What is its need?
2) Write a program to check a character is vowel or not
3) Explain the data types in python
4) Write short notes on types of operators in python with appropriate example
5) Write a program to check whether a years is leap year or not.
6) What is syntax error? Give one example.
7) What is the difference between ‘=’ and ‘==’? Explain with the help of an example.
8) What is the difference between mutable and immutable data types?
9) Differentiate between logical and runtime error?
10)What is the difference between the following operators?
a. * and **
b. = and ==
c. Logical error and runtime error
d. / and //
Long Answers
Answer the Following Questions (Long Answers)
1) What is the difference between a keyword and an identifier?
2) Classify the different types of decision-making statements.
3) Explain briefly constant, variables, expression, keywords and statements available in python.
4) What do you understand by precedence of operators? What is the precedence of arithmetic
operators?
5) What are the three types of flow of control in a program.

STRING
INTRODUCTION
It is a collection of characters (alphabets, digits or special characters including spaces) that is
enclosed in single quotes (‘ ’) or double quotes (‘‘ ’’) or triple quotes (‘‘‘ ’’’).
Ex- 'Hello Students’, "1412” etc.
Strings are immutable, means that the contents of the string cannot be changed after it is created.
INDEXING IN STRING
It is a process in which each character of string has its index or can be accessed using its index. 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 (Forward indexing).
35
There is another way (Backward indexing) for indexing from last character (index = -1) to first
character (index = -length of the string)
STRING OPERATIONS
(1) Concatenation operator (+) – The Concatenation operator adds or concat two strings.
ex: -
>>>Str1= ‘Welcome’
>>>Str2 = ‘ to KVS’
>>>print(Str1+Str2)
’Welcome to KVS’
Concatenation operator works for string objects only. If we try another data type with string it
will produce error.

(2) Replication/repetition operator (*) – The multiplication operator acts as a replication


operator when we have one string and one integer as operands.
ex: - >>>print(’KVS’*3) >>>print(‘3’ *’3’)
‘KVSKVSKVS’ error
(3) Membership Operators: -
IN and NOT IN are two membership operators to find the appearance of a substring inside the
string.

IN- Returns True if a character or a substring NOT IN- Returns True if a character or a
exists in the given string; otherwise, False. substring does not exist in the given string;
ex: - >>>‘N’ in ‘KVS’ otherwise, False

False ex: - >>>‘N’ not in ‘KVS’

>>>‘V’ in ‘KVS’ True

True >>>‘V’ not in ‘KVS’


False

36
(4) String Slicing: - Extracting a subpart from a main string is called slicing. It is done by using a
range of indices.
Syntax - string_name[Start:Stop:Step]
Note: It will return a string from the index start to stop-1.

ex: - >>>Str = ‘Students’ >>>Str[2:5]


>>>Str[0:8] ‘ude’
‘Students’ >>>Str[-6:-2]
>>>Str [ :8] ‘uden’
‘Students’ >>>Str[4:-1]
>>>Str[0:3] ‘ent’
‘Stu’ >>>Str[1:8:2]
’tdns’

(5) Traversing: - Traversing means iterating through the elements of string, one character at a
time.

Example Output

ex: - >>>Str=‘Students’ S*t*u*d*e*n*t*s*


>>> for a in Str:
print(a,’*’, end=‘ ’)

>>>for a in Str: S*
print(a,’*’) t*
u*
d*
e*
n*
t*
s*

BUILT-IN FUNCTIONS/METHODS
Function/Met syntax Description
hod
len( ) len(str) Returns the length of the string
count( ) str.count(sub, start, end) It returns number of times substring str
occurs in the given string.

37
split( ) str.split(“,”) Breaks up a string at the specified separator
and returns a list of substrings
capitalize( ) str.capitalize( ) Converts the first letter of the string in
uppercase
title( ) str.title( ) It returns the string with first letter of every
word in the string in uppercase and rest in
lowercase.
find( ) str.find(sub, start, end) It is used to search the first occurrence of the
substring in the given string.
replace( ) str.replace(old, new) It replaces all the occurrences of the old string
with the new string.
index( ) index(substr, start, end) It also searches the first occurrence and
returns the lowest index of the substring.
lower( ) str.lower( ) It converts the string into lowercase
islower( ) str.islower( ) It returns True if all the letters in the string
are in lowercase otherwise false
upper( ) str.upper( ) It converts the string into uppercase
isupper( ) str.isupper( ) It returns True if all the letters in the string
are in uppercase otherwise false.
isalpha( ) str.isaplha( ) It checks for alphabets in an inputted string
and returns True in string contains only
letters else false.
isalnum( ) str.isanum( ) It returns True if all the characters are
alphanumeric else false.
isdigit( ) str.sidigit( ) It returns True if the string contains only
digits, otherwise false.
lstrip( ) str.istrip(chars) It returns the string after removing the space
str.istrip( ) from the left of the string

rstrip( ) str.restrip(chars) It returns the string after removing the space


str.rstrip( ) from the right of the string

strip( ) str.strip( ) It returns the string after removing the space


from the both side of the string
index( ) str.index(substring) It returnsthe index position of an element or
an item in a string of characters or a list of
items.
startswith( ) string.startswith(substring, It returns True if the string starts with the
start, end) given substring, and False otherwise.

38
partition( ) str.partition(separator) It splits a given string into three parts based
on the first occurrence of a specified
separator. It returns a tuple containing the
three parts: the portion before the separator,
the separator itself, and the portion after the
separator.
join( ) separator.join(iterable) It is used to concatenate elements from an
iterable (like a list or tuple) into a single
string, with a specified separator between
each element.
endswith( ) string.endswith(substring, It returns True if the string ends with the
start, end) given substring, and False otherwise.

MIND MAP OF STRING

39
Multiple Choice Question
Q.1 What is the output of the following code?
example = "snow world"
example[3] = 's'
print (example)
(a) snow (b) snow world (c) Error (d) snos world
Q.2 Which of the following statement will return the last three characters of a string ‘str’?
(a) str[3: ] (b) str[ : 3] (c) str[-3: ] (d) str[ : -3]
Q.3 Find the operator which cannot be used with a string in Python from the following:
(a) + (b) not in (c) * (d) //
Q.4 Which of the following operations on a string will generate an error?
(a) "PYTHON"*3 (b) "PYTHON" + "20" (c)"PYTHON" + 10 (d) "PYTHON" + “LANGUAGE"
Q.5 Which of the following is not a valid string in Python?
(a) “Hello” (b) ‘Hello’ (c) “Hello’ (d) None of the above
Q.6 Which of the following operators is used for concatenation of two strings?
(a) - (b) * (c) + (d) /
Q.7 Which of the following functions will return the total number of characters in a string?
(a) count( ) (b) index( ) (c) len( ) (d) all of these
Q.8 Which of the following function is used for checking whether a string is containing digits only:
(a) isalpha( ) (b) isdigit( ) (c) isalnum( ) (d) None of the above

40
Q.9 What will be the output of above Python code?
str1= “6/4”
print(“str1”)
(a) 1 (b) 6/4 (c) str1 (d) 1.5
Q.10 Which of the following will result in an error?
str1="python"
(a) print(str1[2]) (b) str1[1]="x" (c) print(str1[0:9]) (d) None of these

Competency Based Question


Q.1 What will be the output of the following code
Msg="CompuTer"
Msg1=''
for i in range(0, len(Msg)):
if Msg[i].isupper():
Msg1=Msg1+Msg[i].lower()
elif i%2==0:
Msg1=Msg1+'*'
else:
Msg1=Msg1+Msg[i].upper()
print(Msg1)
Ans. cO*P*t*R
Q.2 What is the output of the following?
print('abcdefcdghcd'.split('cd'))
Ans. ['ab', 'ef', 'gh', '']

Q.3 What is the output of the following?


print('ab cd ef'.title())
Ans Ab Cd Ef
Q.4 Suppose s is “\t\tWorld\n”, what is s.strip() ?
Ans. World
Q.5 Write a program to input a string and calculate the length of the string without using len().
Q.6 Write a program to input a string and print the total number of uppercase and lowercase
letters in a given string.
Q.7 Find the output
str="KVS RO Delhi"
for i in str:
if(i.isupper()==True):
print(i.lower(),end="")
if(i.islower()==True):
41
print(i.upper(), end="")
Ans. kvsrodELHI
Q.8 What is the output of the following?
print('ab12'.isalnum( ))
Ans. True
Q.9 Find the output:
str="PYTHON@LANGUAGE"
print(str[2:12:2])
Ans. TO@AG
Q.10 Find and write the output of the following python code:
x = "abcdef"
i = "a"
while i in x:
print(i, end = " ")
Ans. aaaaaa ---- OR infinite loop
Very short Questions
Q.1 What is a string in Python?
Ans. It is a collection of characters enclosed in ‘ ’ or “ ” or ‘“ ”’ .
Q.2 Write python code to print the string “KVS” 5 times.
Ans. >>>”KVS”*5
Q.3 What is the index value of first character of string in Python?
Ans. 0
Q.4 If A = “Hello” then what will be the value of A[3] ?
Ans. ‘l’
Q.5 Is 555 or ‘555’ same ?
Ans. No
Q.6 Identify valid string literals : ‘marks’’, ‘123’, “L@”, “mark’.
Ans. ‘123’, “L@”
Q.7 How many times is the word “Hi” displayed in the following statement?
s=’python world’
for ch in s[3:8]:
print(‘Hi’ )
Ans. 5 times
Q.8 Suppose word = ‘amazing’, then what will be word[: : -2]?
Ans. ‘giaa’
Q.9 Out of the following operators, which one’s cannot be used with strings?
=, - ,* , /, //, %, >, <> , in, not in, <=
Ans. /, // and %
Q.10 If s= ‘Middleeast’, then what will be the output of s[5:-2].
Ans. ‘eea'

42
Short Questions
Q.1 Write a python code to give this output :

H # Ans. s='HELLO'
E # for x in s:
L # print(x,'#')
L #
0 #

Q.2 What is a string slice? How is it useful?


Ans. String Slice is a part of a string containing some contiguous characters from the string. It is
accessed from the string by providing a range in“[ ]” brackets i.e. S1[n:m]. Python returns all the
characters at indices n, n+1, n+2. . n-1 e.g. S= ”Barabanki” S[4:7]will return ‘ban’.
Q.3 WAP to print the following pattern without using any nested loop.

# Ans. N=5
## for I in range(1,N+1):
### print(“#”*I)
####
#####

Q.4 Which functions would you chose to use to remove leading and trailing white spaces from a
given string?
Ans. Python String strip( ) function will remove leading and trailing white spaces. If you want to
remove only leading or trailing spaces, use lstrip() or rstrip() function instead.
Q.5 Find the value stored in C at the end of this code snippet:
str="Darjeeling Tea has a strong flavour"
C=0
for i in str:
if i in 'aeiouAEIOU':
C += 1
print(C)
Ans. 12
Q.6 (A) Assertion: str1=”Hello” and str2=”World” then print(str1*3) will give error
(R) Reason : * replicates the string hence correct output will be HelloHelloHello
Ans. A is false and R is correct.
Q.7 Using string replication techniques print the following pattern using any loop.
Hello
43
Hello Hello
Hello Hello Hello
Ans. for a in range(1,4):
print("hello " * a)
Q.8 What is the difference between partition( ) and split( ) function in Python ?
Ans. partition( ) – it partitions the string on the first occurrence of substring.
ex:- s='hello all'
s.partition('a') => ('hello ', 'a', 'll')
s.partition(‘all’) => ('hello ', 'all', ‘ ‘)
split( ) – it returns a list of strings as splitted. ex:- s='hello all'
s.split( ) => [‘hello’, ‘all’ ]
Q.9 What is the concatenation operator in Python ?
Ans. Concatenation operator ( +) –The concatenation operator adds or concat two strings. ex:-
s1=‘Welcome’
s2 = ‘All’
print(s1+s2)
=>Output :- WelcomeAll
Q.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 )

Long Question
Q.1 Write a program to calculate digits and letters in a string.
Ans string=input("Enter string:")
count1=0
count2=0
for i in string:
if(i.isdigit()):
count1=count1+1
elif(i.isalpha()):
count2=count2+1
print("The number of digits is:",count1)
print("The number of characters is:",count2)
Q.2 Write a program to count a specific character in a string.
Ans. string=input("Enter string:")
count=0
ch=input("Enter character you want to count-- ")
count=string.count(ch)
print("The count of ",ch,"in string is ",count)
Q.3 Consider the following string country:
country= "Great India"
What will be the output of the following string operations(Any Four):-

44
(a) print(country[0:len(country)]) Ans. (a)Great India
(b) print(country[-7:-1]) (b)t Indi
(c) print(country[::2]) (c)GetIda
(d) print(country[len(country)-1]) (d)a
(e) print(2*country) (e)Great IndiaGreat India
(f) print(country[:3] + country[3:]) (f)Great India
Q.4 Find Output:
my_string = 'Jhunjhunu' Ans. Jhu
print(my_string[:3]) J@H@U@N@J@H@U@N@U@
for i in range(len(my_string)): Jhunjhunu
print(my_string[i].upper(),end="@") Njh
print()
print (my_string)
print (my_string[3:6])
Q.5 Write a Python Program to input a string to check whether it is a Palindrome string or not. (A
Palindrome string is that which is same from both ends like – NITIN, MALAYALAM, PULLUP)
Ans. s=input("Enter a word :")
print ("You entered :", s)
length=len(s)
rev=""
for i in range (-1,-length-1,-1):
rev=rev+s[i]
if s==rev:
print ("Yes, palindrome")
else:
print ("Not a palindrome")
Case Study based question
Q.1 Ravee is developing a program to greet users based on their input. It takes a name as input
and returns a greeting message in the format "Hello, [name]!".
Ans. user_name = input("Enter your name: ")
print(“Hello”,user_name,”!”)
Q.2 Gorank is tasked with processing a file name and extracting the file extension. Program takes
a file name as input and return the output of its extension.
Ans. file_name = input("enter the file name with extension: ")
if '.' in file_name:
print("The file extension of", file_name, "is", file_name.split('.')[-1])
else:
print("No extension found")

45
LIST
INTRODUCTION
Lists are used to store multiple items in a single variable. Lists are enclosed in square brackets and
the elements of the list are separated by commas. List is a mutable data type, means that the contents
of the list can be changed after it is created.
ex: - L = [12, 23, ‘A’, “45”]
L1 = [ ] # L1 is a blank list
L2 = list( ) # list( ) function is used to create list L2
L3 = [1,2,3,4,5] # L3 is an integer list
L4 = ["ABC", 15, False, 25.5, "male"] # L4 is a list with mix data types
L5 = [‘a’, [2,4,’b’], 56] # L5 is a nested list
INDEXING IN LIST
It is a process in which each element of a list has its index or can be accessed using its index. The first
element of the list has index 0, the next has index 1, and so on. The index of the last element will be
the length of the minus one (Forward indexing).

There is another way (Backward indexing) for indexing from last element (index = -1) to first
element (index = -length of the list)
LIST OPERATIONS
(1) Concatenation (+ Operator): Python allows us to join two or more lists using + operator.
ex: - >>> l1 = [1,3,5,7,9]
>>> l2 = [2,4,6,8,10]
>>> l3 = [‘abc’, “qwe”]
>>>l1 + l2 + l3 # + operator
[1,3,5,7,9,2,4,6,8,10, ‘abc’, “qwe”]
(2) Repetition/ Replication Operator (* operator): Python allows us to replicate a list using
repetition operator depicted by symbol ‘*’.
ex: - >>> str1 = ['Help']
>>> str1 * 4
[' Help ', ' Help ', ' Help’, '' Help’']
(3) Membership (IN/ NOT IN operator) :

Like strings, the membership operators IN checks, if NOT IN operator returns True if the
the element is present in the list then returns True, element is not present in the list, else it

46
else returns False. returns False.
ex: - >>>‘N’ in [‘K’, ‘V’, ‘S’ ] ex: - >>>‘N’ not in [‘K’, ‘V’, ‘S’ ]
False True
>>>‘V’ in [‘K’, ‘V’, ‘S’ ] >>>‘V’ not in [‘K’, ‘V’, ‘S’ ]
True False

List Slicing: - Like strings, the slicing operation can also be applied to lists. List elements can be
accessed in subparts.
Syntax- list_name[start:stop:step]
L = [2,7,9,10,13,15,17,19,23,25]
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]
(4) Traversing: - Traversing means iterating through the elements of a list, one element at a time.
ex: - >>>L1 = [1,2,3,4] 1
>>>for a in L1: 2
print(a) 3
4

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

ex: - >>>L = [1,2,3,4,5] [1,2,11,4,22]


>>>L[2] = 11
>>>L[-1] = 22
>>>print (L)

(6) List Comparisons: - The relational operators >, >=, <, <=, ==, != can be applied for comparison
between two lists results will come in True or False. The following rules are observed:

47
(a) For equality (==) operator: - Equality evaluates 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.
(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

ex: - >>>print( [1,2,3] == [1,2,3]) >>>print( [1,2,8,9] >= [1,9])


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

List Functions :-
Function Syntax Description
list( ) list(sequence) It returns a list created from the passed
arguments, which should be a sequence type
(string, list, tuple etc.). if no argument is passed, it
will create an empty list.
append( ) list.append(items) It adds a single item to the end of the list.
extend( ) list1.extend(list2) It adds one list at the end of another list.
insert( ) list.insert(index_no, value) It adds an element at a specified index
reverse( ) list.reverse( ) It reverses the order of the elements in a list.
index( ) list.index(item) It returns the index of first matched item from the
list.
len( ) len(list) Returns the length of the list i.e. number of
elements in a list
sort( ) list.sort( ) This function sorts the items of the list.
clear( ) list.clear( ) It removes all the elements from the list.
count( ) list.count(element) It counts how many times an element has
occurred in a list and returns it.
sorted( ) sorted(sequence,reverse= It returns a newly created sorted list; it does not
False) change in the original list.
pop( ) list.pop(index) It removes the element from the specified index
and also returns the element which was removed.
remove( ) list.remove(value) It is used when we know the element to be
deleted, not the index of the element.

48
max( ) max(list) Returns the element with the maximum value
from the list.
min( ) min(list) Returns the element with the minimum value
from the list
sum( ) sum(list) It returns the sum of elements of the list.
max( ) max(list) Returns the element with the maximum value
from the list.
min( ) min(list) Returns the element with the minimum value
from the list
sum( ) sum(list) It returns the sum of elements of the list.
MIND MAP OF LIST

Multiple Choice Question


Q.1 The data type list is an ordered sequence which is made up of one or more elements.
(a) Mutable (b) Immutable (c) Both a and b (d) None of the above
Q.2 Which statement from the list below will create a new list?
(a) new_l = [1, 2, 3, 4] (b) new_l = list() (c) Both a and b (d) None of the above
Q.3 What will be the output of the following python code
new_list = [‘P’,’y’,’t’,’h’,’o’,’n’]
print(len(new_list))
(a) 6 (b) 7 (c) 8 (d) 9
Q.4 We can access each element of the list or traverse a list using.
(a) for loop (b) while loop (c) Both a and b (d) None of the above
Q.5 What will be the output of the following python code?
new_list = “1234”
print(list(new_list))
(a) [‘1’, ‘2’, ‘3’, ‘4’] (b) (‘1’, ‘2’, ‘3’, ‘4’) (c) {‘1’, ‘2’, ‘3’, ‘4’} (d) None of the above
Q.6 Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1] ?
(a) Error (b) None (c) 25 (d) 2
49
Q.7 Suppose list1 is [1, 3, 2], What is list1 * 2 ?
(a) [2, 6, 4] (b) [1, 3, 2, 1, 3] (c) [1, 3, 2, 1, 3, 2] (d) [1, 3, 2, 3, 2, 1]
Q.8 Write the output of the following code :
list(“welcome”)
(A) [‘w’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’] (B) (‘w’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’) (C) [‘welcome’] (D) None
Q.9 Write the output of the following code :
L=list(“abcdefgh”)
print(L[4 : -2])
(a) [‘e’ , ‘f’] (b) [‘d’, ’e’ , ‘f’ ] (c) (def) (d) Error
Q.10 Write the output of the following code :
>>>L=[1,2,3,4,5,[6,7,8]]
>>>print(L[5])
(a) [6, 7, 8] (b) 6, 7, 8 (c) Error (d) 6
ANSWERS OF MCQ
(1) a, (2) c, (3) a, (4) c, (5) a, (6) c, (7) c, (8) a, (9) a, (10) a
Competency Based Question
Q.1 Differentiate between append () and extend ()
Q.2 Differentiate between List and string.
Q.3 Write a program to increment the elements of a list with a number?
Q.4 WAP to calculate the mean of the given list of numbers.
Q.5 Write a program to print list having numbers less than 20.
Q.6 What will be the output of the following program?
l=[6,12,18,24,30]
for i in l:
for j in range(1,i%4):
print(j,'#',end='')
print( )
Q.7 Write a program that reverses a list of integers.
Q.8 Write a program to find the number of times an element occurs in the list.
Q.9 Write a program to find the largest and smallest number in a list.
Q.10 Write a program to check if a number is present in the list or not. If the number is present,
print the position of the number. Print an appropriate message if the number is not present in
the list.
Very short Questions
Q.1 Suppose a list is L=[2, 33, "KVS", 14, 25], what is L[-3]?
Ans. “KVS”
Q.2 Given a list L=[1, 2, [“COMPUTER”, “SCIENCE”], “IS”, “TUPLE”]
What will be the value of L[- 3][1].
Ans. “SCIENCE”
Q.3 A = [ ] and A = list( ) will produce the same result.
Ans True
Q.4 Lists once created cannot be changed.
Ans. False
50
Q.5 To sort a list, sort( ) and sorted( ), both can be used.
Ans. True
Q.6 Write the difference between list pop() method and remove() method.
Q.7 What do you understand by mutability?

Q.8 What are nested lists?


Ans. A list can have an element in it, which itself is a list. Such a list is called nested list.e.g.
L=[1,2,3,4,[5,6,7],8]
Q.9 myList = [1,2,3,4,5,6,7,8,9,10]
del myList[3:]
print(myList)
Ans. [1,2,3]
Q.10 Find out the errors and write the correct code :
a=[5, 6, 3, 4, 1]
b=a* ”3”
c=a+b
Ans. b=a*3
Short Questions
Q.1 What will be the output of the following code?
L=[3, 5, 1, 10, 2]
L.append(55)
print(L)
Ans. [3, 5, 1, 10, 2, 55]
Q.2 What is the output of the following code?
a={1:"A",2:"B",3:"C"}
for i,j in a.items( ):
print(i,j,end=" ")
Q.3 How is the pop( ) function different from remove( ) function working with lists in python ?
Explain with examples.

Ans. pop() function removes the last The remove() method


value and returns the same. removes the first matching
>>>l=[10,20,30,20] value from the list.

>>>l.pop() >>>l.remove(20)

20

Q.4 What is the output when the following code is executed ?


>>>names = ['Amir', 'Bear', 'Charlton', 'Daman']
>>>print(names[-1][-1])
Ans. n
Q.5 Compare lists with strings. How are they similar and how are they different?

51
Ans. The similarity between Lists and Strings in Python is that both are sequences. The differences
between them are that firstly, Lists are mutable but Strings are immutable. Secondly, elements
of a list can be of different types whereas a String only contains characters that are all of
String type.
Q.6 Write a program to accept a list of numbers and find the sum of all the numbers in the list.
Q.7 WAP to search for an element in a given list of numbers.
Q.8 WAP to find the minimum element from a list of elements along with its index in the list.
Q.9 What will be the output of the following program:
l=[10,20,30,40,50,60]
for i in range(len(l)):
if(i%2==0):
print(l[i],end='#')
else:
print(l[i],end='@')
Q.10 What will be the output of following program:
odd = [1, 9]
odd.insert(1,3)
print(odd)
odd[2:2] = [5, 7]
print(odd)
Long Question
Q.1 Write a program that takes any two lists L and M of the same size and adds their elements
together to form a new list N whose elements are sums of the corresponding elements in L and M. For
instance, if L = [3, 1, 4] and M = [1, 5, 9], then N should equal [4,6,13].
Q.2 Write a Python program to input 10 numbers to store in the list and print the third largest
number. For example, if the entered numbers in the list are List are 36, 25, 14, - 951, 75, - 85,
654, 88, 9521, 657, then output will be The third largest number is : 654

Q.3 Take a list of 10 elements. Split it into middle and store the elements in two different lists.
E.g.- INITIAL list : 5 10 6 12 3 25 66 44 1 90 After splitting : 5 10 6 12 3
25 66 44 1 90
Q.4 Find and write the output of the following Python code :

x= [1, 2, [3, "KVS", 4], "KV"] Ans.


print(x[0]) 1
print(x[2]) [3, 'KVS', 4]
print(x[-1]) KV
print(x[0:1]) [1]
print(2 in x) True

52
print(x[0]==8) False
print(len(x)) 4
x.extend([12,32,4])
print(len(x)) 7

Q.5 Consider the following list L=[13,18,20,10,18,23] 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
Q.6 Guddu is building a program to process student average marks. It takes marks of five subjects
and calculates the average marks.
Ans. student_marks = eval(input(" Enter marks of five subject in a list (Max. is 100): "))
total_marks=sum(student_marks)
avg_marks= total_marks/5
print("Average marks is: ", avg_marks)

53
TUPLE
INTRODUCTION
A tuple is a collection which is ordered and immutable (We cannot change elements of a tuple in
place). Elements of a tuple are enclosed in parenthesis (round brackets) and are separated by
commas. Tuples can store a sequence of values belonging to any type. Tuples allows duplicate
members.
Ex:- T1 = ( ) # Empty Tuple
T2 = (4,5,6) # Tuple of integers
T3 = (1.5,4,9) # Tuple of numbers
T4 = (‘x’, ‘y’, ‘z’) # Tuple of characters
T5 = (‘a’,1.5,’KVS’,45) # Tuple of mixed values
T6 = (‘KVS’, ‘NVS’, ‘EMRS’) # Tuple of strings
>>>t2 = (10,) # Single element tuple
Note:- comma is necessary in single value tuples. Without a comma it will be a value, not a tuple.
>>>t3=(10,20,30,40,50) # Long tuple
>>>t4=(6,(4,5),9,7) # Nested Tuple
● tuple( ) function is used to create a tuple from other sequences.
● Indexing of tuple is similar to indexing of list.
● Difference between List and Tuple
S. No. List Tuple
01 Elements are enclosed in square brackets Elements are enclosed in parenthesis
i.e. [ ] i.e. ( )
02 It is mutable data type It is immutable data type
03 Iterating through a list is slower as Iterating through a tuple is faster as
compared to tuple compared to list

TRAVERSING A TUPLE
Traversing a tuple means accessing and processing each element of it. A tuple can be traversed using
a loop.
Ex:- >>> T1=(2,4,6,8,10) Output: 2
>>> for a in T1: 4
print(a) 6
8
10
ACCESSING TUPLES
Elements of a tuple can be accessed using Indexing and Slicing, same as in string and list.
if T1= (‘C’, ‘O’, ‘M’, ‘P’, ‘U’, ‘T’, ‘E’, ‘R’):

54
Elements C 0 M P U T E R
+ index Value 0 1 2 3 4 5 6 7
- Index Value -8 -7 -6 -5 -4 -3 -2 -1

>>> T1[2] #WILL ACCESS ‘M’


>>> T1[-3] #WILL ACCESS ‘T’
>>> T1[1:7:1] #WILL ACCESS ‘OMPUTE’

OPERATORS IN TUPLE
Operation Name Description Example
Concatenation (+) Joining of two or more tuples is >>>t1 = (1, 2, 3)
called concatenation >>>t2 = (8, 9, 11)
Python allows us to join tuples >>>t1+t2
using concatenation operator (+) OUTPUT :
(1, 2, 3, 8, 9, 11)
(#concatenates two tuples)
>>>t1 = (1, 2, 3)
>>>t2 = (8, 9, 11)
>>>t3 = t1+t2
(#Created new tuple)
OUTPUT :
(1, 2, 3, 8, 9, 11)
Concatenation operator can also
be used for extending an
existing tuple.
>>>t1 = (1, 2, 3)
>>>t1 = t1 + (7,8,9)
>>>t1
It is used to repeat elements of a
>>>h1 = (‘H’ , ‘M’) >>>h1 * 3 (‘H’
Repetition (*) tuple. Repetition operation is
, ‘M’, ‘H’ , ‘M’, ‘H’ , ‘M’)
denoted by Symbol (*)
Membership The ‘in’ operator checks the >>>h1 = (‘H’ , ‘M’)
presence of element in tuple. If >>>’H’ in h1
the element is present it returns True
True, else it returns False. >>>’m’ not in h1
55
The not in operator returns True True
if the element is not present in
the tuple, else it returns False.
Slicing It is used to extract one or more >>>t1 = (1, 2, 3, 7, 8, 9)
elements from the tuple. Like >>>t1[2:4]
string and list, slicing can be (3, 7)
applied to tuples also. >>>t1 =(10, 20, 30, 40, 50,
60, 70, 80)
>>>t1[2 : 7]
(30, 40, 50, 60, 70)
>>>t1[ : 5]
(10, 20, 30, 40, 50)
>>>t1[: : -1]
(80, 70, 60, 50, 40, 30, 20, 10)

Tuple Methods and Built-in Functions

Method Name Description Example

>>>t1 =(10,20,30,40,50, 60, 70,


This method returns the length of 80)
len( ) tuple or the number of elements in
the tuple. >>>len(t1)
8
>>>t1 = tuple()
>>>type(t1)
<class ‘tuple’>

This function creates an empty tuple >>>t1 = tuple(‘python’) #string


tuple( ) or creates a tuple if a sequence is >>>t1
passed as argument. (‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)

>>>t1 = tuple([1,2,3]) #list


>>>t2
(1, 2, 3)

56
>>>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”)
>>>t1.index(‘n’)
This function returns the index of the 8
index( ) first occurrence of the element in the
given tuple. >>>t1=tuple(“tuples in python”)
>>>t1.index(‘f’)
ValueError: tuple.index(x): x not in tuple
>>>t1 = (‘t’, ‘u’, ‘p’, ‘l’, ‘e’, ‘s’)
This element takes tuple as an >>>sorted(t1)
argument and returns a sorted list.
sorted( ) [‘e’, ‘l’, ‘p’, ‘s’, ‘t’, ‘u’]
This function does not make any
change in the original tuple. >>>t1
(‘t’, ‘u’, ‘p’, ‘l’, ‘e’, ‘s’)
>>>t1 = (3, 8, 4, 10, 1)
>>>min(t1)
This function returns the minimum or 1
min( )
smallest element of the tuple. >>>t1 = (‘t’, ‘u’, ‘p’, ‘l’, ‘e’, ‘s’)
>>>min(t1)
‘e’
>>>t1 = (3, 8, 4, 10, 1)
>>>max(t1)
This function returns the maximum 10
max( )
or largest element of the tuple. >>>t1 = (‘t’, ‘u’, ‘p’, ‘l’, ‘e’, ‘s’)
>>>max(t1)
‘u’
>>>t1 = (3, 8, 4, 10, 1)
This function returns the sum of the
sum( ) >>>sum(t1)
elements of the tuple.
26

57
MIND MAP OF TUPLE

Multiple Choice Question


Q.1 What type of error is returned by following code :
a=(“Amit”, “Sumit”,”Ashish”,”Sumanta”)
print(a.index(“Suman”))
(a) Syntax Error (b) Value Error (c) Type Error (d) Name Error
Q.2 What is the length of the given tuple? >>> t1=(1,2,(3,4,5))
(a) 1 (b) 2 (c) 3 (d) 4
Q.3 Which of the following statements will return an error. T1 is a tuple.
(a) T1 + (23) (b) T1 + [3] (c) Both (a) & (b) (d) None
Q.4 What is the output of following code?
>>> t1=(1,2,(3,4,5,2))
>>> print(len(t1[2]))
(a) 1 (b) 2 (c) 3 (d) 4
Q.5 Which of the following is not a tuple?
(a) P = 1,2,3,4,5 (b) Q = (‘a’, ‘b’, ‘c’) (c) R = (1, 2, 3, 4) (d) None
Q.6 Which of the following is/are features of tuple?
(a) Tuple is immutable (b) Tuple is a sequence data type.
(c) In tuple, elements are enclosed in Parenthesis (d) All of the above
Q.7 Which of the following is not a function of tuple?
(a) update( ) (b) min( ) (c) max( ) (d) count( )
58
Q.8 Which of the following is/are features of tuple?
(a) Tuple is immutable (b) Tuple is a sequence data type.
(c) In tuples, elements are enclosed in Parenthesis. (d) All of the above
Q.9 Which of the following is a tuple with a single element?
(a) t = (1,) (b) t = 1, (c) Both (a) & (b) (d). None of the above
Q.10 Rahul wants to delete all the elements from the tuple t, which statement he should use
(a) del t (b)clear() (iii) t.remove() (iv) None of these

ANSWERS OF MCQ
(1) b, (2) c, (3) c, (4) c, (5) a, (6) d, (7) a, (8) d, (9) c, (10) a
Competency Based Question
Q.1 Discuss the utility and significance of Tuples, briefly.
Ans. It is a type of array. It plays a very important role in python. In python it is an immutable type
of container which stores any kind of data types. It is short in memory size in comparison to
lists.
Q.2 Lists and Tuples are ordered. Explain.
Ans. Lists and Tuples are ordered sequences as each element has a fixed position.
Q.3 Write the output of the following.
a=(23,34,65,20,5)
print(a[0]+a.index(5))
Ans. 27
Q.4 Create a tuple names as given here:
names = ('JAI', 'RAM', 'MAMTA', 'KAPIL', 'DINESH', 'ROHIT') Write proper code for getting:
('MAMTA', 'KAPIL', 'DINESH')
Ans. print(names [2 : 5 ])
Q.5 T1=(1,2) & T2=(“KV”,)
print(T2*2)
Ans. (‘KV’,’KV’)
Q.6 T1=(45,67,98)
T1=T1+(1,2,3)
print(T1)
Ans. (45,67,98,1,2,3)
Q.7 Consider the following tuple and write the code in python for the following statements:
T1=(12,3,45,’Hockey’,’Anil’,(‘a’,’b’))
(a) Display the first element of ‘T1’ (b) Display the last element of ‘T1’
(c) Display ‘T1’ in reverse order. (d) Display ‘Anil’ from tuple ‘T1’
(e) Display ‘b’ from tuple
59
Ans. (a) print(T1[0]) (b) print(T1[-1]) (c) print(T1[ : :-1]) (d) print(T1[4])
(e) print(T1[5][1])
Q.8 What is unpacking Tuple?
Ans. 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
the same as the number of elements in the tuple.
Q.9 What are nested tuples?
Ans A tuple containing another tuple in it as a member is called a nested tuple, e.g., the tuple
shown below is a nested tuple:
Employees = (4580,'Rahul', (82,67,75,89,90)) # nested tuple
Q.10 for i in tuple(“KVS”):
print(i+i)
Ans. KK
VV
SS
Very short Questions
Q.1 T1=(“Hockey”, “Cricket”, ‘Football’)
print(max(T1))
print(min(T1))
Ans. Hockey
Cricket
Q.2 What will be the output of the following Python Code?
tp = (5,)
tp1 = tp * 2
print(len(tp1))
Ans. 2
Q.3 Type Error occurs while statement 2 is running. Give reason. How can it be corrected?
>>> tuple1 = (5) #statement 1
>>> len(tuple1) #statement 2
Ans. Because tuple1 is an integer not a tuple. So, we cannot find the length of the integer. If you
want to make tuple then you should write ( 5, )
Q.4 How to create an empty tuple? Also create a single element tuple.
Ans. t=( ) or t=tuple( ) single element tuple: t=(10,)
Q.5 Write a program that inputs two tuples and creates a third, that contains all elements of the
first followed by all elements of the second.
60
Ans. tup1 = eval(input("Enter First tuple :-"))
tup2 = eval(input("Enter second tuple :-"))
tup3 = tup1 + tup2
print(tup3)
Q.6 T1=('A',['B','D'],'C')
T1[1][1]='C'
print(T1)
Ans. ('A', ['B', 'C'], 'C')
Q.7 What is the difference between a List and a Tuple?
Ans.
List Tuple
Elements are enclosed in square brackets i.e. [ ] Elements are enclosed in parenthesis i.e. ( )
It is mutable data type It is immutable data type
Iterating through a list is slower as compared Iterating through a tuple is faster as
to tuple compared to list

Q.8 Which error is returned by the following code:


T = (10,20,30,40,50,60,70)
print(T[20])
Ans. Index Error : tuple index out of range
Q.9 Write a statement to print 30 from the given tuple.
T=(“Seven”,[1,2,3],(20,30,40),”eight”)
Ans. print(T[2][1])
Q.10 Write a program to create a tuple and find sum of its alternate elements?
Ans. T = (10,23,30,65,70)
sum = 0
for a in T[0:5:2]:
sum = sum + a
print(sum)
Long Question
Q.1 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.
Ans. tup= ()
while True :

61
n = int(input("Enter a number :- "))
tup += (n,)
ch = input("To quit enter y/Y =")
if ch == "y" or ch=="Y":
print(tup)
print("Max :-",max( tup ))
print("Min :-",min( tup ))
break
Q.2 Write a program to count vowels in a tuple?
Ans. T = tuple(input("Enter Name :"))
print(T)
v=0
for ch in T:
if ch in ['a','e','i','o','u']:
v=v+1
print("No. of vowels : ",v)
Q.3 What will be stored in variables a, b, c, d, e, f, g, h after following statements?

perc = (88, 85, 80, 88, 83, 86) Ans.


a = perc[2:2] ()
b = perc[2:] (80, 88, 83, 86)
c = perc[:2] (88, 85)
d = perc[:-2] (88, 85, 80, 88)
e = perc[-2] 83
f = perc[2:-2] (80, 88)
g = perc[-2:2] ()
h = perc[:] (88, 85, 80, 88, 83, 86)

Case Study based question


Q.1 Ram tried to create tuple t=(1,2,3) and wanted to change the value using t[1]=10 it showed
error, Why.
Ans. Due to Immutable data type he cannot change
Q.2 Laxman write some code >>>T1=(10) #STM1 and >>>len(T1) #STM2 when he executes
statements which error will occur and how he corrects it.
Ans. Type error will occur, corrected code will be T1=(10,)

62
Dictionary
Dictionary in Python is an unordered collection of data, used to store data values along with the keys.
Dictionary holds the key : value pair. We can also refer to a dictionary as a mapping between a set of
keys and a set of values. Each key-value pair in a Dictionary is separated by a colon (:). E.g.
dict={ “a": “alpha", “o": “omega", “g": ”gamma” }

CHARACTERISTICS OF PYTHON DICTIONARY:


1. The combination of Key and Value is called Key-Value Pair.
2. Keys and their values are separated by colon(:)
3. Different Key-Value pairs are separated by comma(,).
4. Keys are unique for each Value.
5. Keys of dictionary must be of immutable type like string, number etc.

# Creating an empty Dictionary Output


Dict = {} Empty Dictionary:
print("Empty Dictionary: ") {}
print(Dict)

# Creating a Dictionary with Integer Keys Dictionary with the use of Integer
Dict = {1: ‘AAA', 2: ‘BBB', 3: ‘CCC'} Keys:
print("\nDictionary with the use of Integer Keys: ") {1: ‘AAA', 2: ‘BBB', 3: ‘CCC'}
print(Dict)

# Creating a Dictionary with Mixed keys Dictionary with the use of Mixed
Dict = {'Name': ‘Govind', 1: [10, 11, 12, 13]} Keys:
print("\nDictionary with the use of Mixed Keys: ") {'Name': 'Govind', 1: [10, 11, 12, 13]}
print(Dict)

# Creating a Dictionary with dict() method Dictionary with the use of dict():
D=dict({1: 'AAA', 2: 'BBB', 3:'CCC'}) {1: 'AAA', 2: 'BBB', 3: 'CCC'}
print("\nDictionary with the use of dict(): ") Dictionary with each item as a pair:
print(D) {1: 'AAA', 2: 'BBB'}

# Adding elements one at a time Dictionary after adding 3 elements:


Dict={} {0: 'Govind', 2: ‘Prasad', 3: ‘Arya’}
Dict[0] = ‘Govind'
Dict[2] = ‘Prasad'
Dict[3] = ‘Arya’
print("\nDictionary after adding 3 elements: ")
print(Dict)
Dictionary after adding set of values:
# Adding set of values {0: 'Govind', 2: ‘Prasad', 3: ‘Arya’ , 'V':
# to a single Key (1, 2,)}
Dict['V'] = 1, 2
63
print("\nDictionary after adding set of values: ")
print(Dict) Updated dictionary:
{0: 'Govind', 2: ‘Prasad', 3: ‘Arya’ , 'V':
# Updating existing Key's Value (3, 4,)}
Dict[‘V’] = 3,4
print("\nUpdated dictionary: ")
print(Dict)
# Creating a Dictionary
D = {1: ‘Prasad', 'name': ‘Govind', 3: ‘Arya'}

# accessing a element using key Output


print("Accessing a element using key:") Accessing a element using key:
print(D['name']) Govind

# accessing a element using key Accessing a element using key:


print("Accessing a element using key:") Prasad
print(D[1])

# accessing a element using get() method Accessing a element using get:


print("Accessing a element using get:") Arya
print(D.get(3))
D={1:'AAA', 2:'BBB', 3:'CCC'} Output
print("\n all key names in the dictionary, one by one:") all key names in the dictionary, one by
for i in D: one:
print(i, end=' ') 123

print("\n all values in the dictionary, one by one:") all values in the dictionary, one by one:
for i in D: AAA BBB CCC
print(D[i], end=' ')

print("\n all keys in the dictionary using keys() all keys in the dictionary using keys()
method:") method:
for i in D.keys(): 123
print(i, end=' ')

print("\n all values in the dictionary using values() all values in the dictionary using
method:") values() method:
for i in D.values(): AAA BBB CCC
print(i, end=' ')

print("\n all keys and values in the dictionary using all keys and values in the dictionary
items()method:") using items()method:
for k, v in D.items(): 1 AAA 2 BBB 3 CCC
print(k, v, end=' ')

64
Built-in functions in dictionary:-

Function Example with output

len():- Returns the length of the D={1:'AAA', 2:'BBB', 3:'CCC'}


dictionary print('Length', '=',len(D))
Output:- Length= 3

dict() :- dict() function creates a D = dict(name = "Aman", age = 36, country = "India")
dictionary. print(D)
Output:-{'name': 'Aman', 'age': 36, 'country': 'India'}

keys():- returns all the available keys D = dict(name = "Aman", age = 36, country = "India")
print(D.keys())
Output: dict_keys(['name', 'age', 'country'])

values()-returns all the available D = dict(name = "Aman", age = 36, country = "India")
values print(D.values( ))
Output:dict_values(['Aman', 36, 'India'])

items():- returns key:value pair as D={1:'AAA', 2:'BBB', 3:'CCC'}


object for k, v in D.items():
print(k, v, end=’#')
Output: 1 AAA # 2 BBB # 3 CCC

get(): returns the value of the item D={1:'AAA', 2:'BBB', 3:'CCC'}


with specified key print(D.get(2))
Output: BBB

update():- inserts the specified items D={1:'AAA', 2:'BBB', 3:'CCC'}


to the dictionary D.update({4:’DDD’})
print(D)
Output : {1: 'AAA', 2: 'BBB', 3: 'CCC',4:’DDD’}

del() – used to delete the key:value D={1:'AAA', 2:'BBB', 3:'CCC', 4:’DDD’ }


pair D.del(2)
print(D)
Output : {1: 'AAA', 3: 'CCC',4:’DDD’}

clear() – removes all elements from D={1:'AAA', 2:'BBB', 3:'CCC'}


the dictionary D.clear()
print(D)
Output : {}

fromKeys() : creates a new dictionary D=(1,2,3)


from the given sequence of elements print(dict.fromkeys(D,None))
with a value provided by the user. Output : {1: None, 3: None,4:None}

copy() : to make a copy of the D={1:'AAA', 2:'BBB', 3:'CCC'}


dictionary D1=D.copy()
print(D1)
Output : {1: 'AAA', 3: 'CCC',4:’DDD’}

65
pop() : method removes the specified D={1:'AAA', 2:'BBB', 3:'CCC'}
item from the dictionary and return print(D.pop(2))
the corresponding value Output : ’BBB’

popitem() : Remove the last item from D={1:'AAA', 2:'BBB', 3:'CCC'}


the dictionary print(D.popitem())
Output : 3: ’CCC’

setdefault() : This method inserts a new D={1:'AAA', 2:'BBB', 3:'CCC'}


key: value pair only if the key does not print(D.setdefault(4,200))
exist and If the key already exists, it returns Output : 200
the current value in both cases. D now is {1: 'AAA', 2: 'BBB', 3: 'CCC', 4: 200}

max() : returns the maximum key D={1:'AAA', 2:'BBB', 3:'CCC'}


value print(max(D))
Output : 3

min() : returns the minimum key value D={1:'AAA', 2:'BBB', 3:'CCC'}


print(min(D))
Output : 1

sorted(): returns the dictionary in D={10:'AAA', 2:'BBB', 3:'CCC'}


sorted order on keys/values print(sorted(D.items()))
print(sorted(D.values()))
Output :[(2, 'BBB'), (3, 'CCC'), (10, 'AAA')]
['AAA', 'BBB', 'CCC']

MIND MAP

MCQ
1. What is the syntax to create an empty dictionary in Python?
a) dict = {}
b) dict = []
c) dict = ()
d) dict = None
Answer: a) dict = {}
66
2. Which method is used to add a new key-value pair to a dictionary?
a) append()
b) update()
c) insert()
d) add()
Answer: b) update()

3. How do you access the value of a key in a dictionary?


a) dict[key]
b) dict.key
c) dict.get(key)
d) dict[key][ ]
Answer: a) dict[key]

4. What happens if you try to access a key that doesn't exist in a dictionary?
a) It returns None
b) It raises a KeyError
c) It returns an empty string
d) It returns 0
Answer: b) It raises a KeyError

5. Which method is used to remove a key-value pair from a dictionary?


a) pop()
b) remove()
c) delete()
d) clear()
Answer: a) pop()

6. How do you iterate over the key-value pairs of a dictionary?


a) for key in dict:
b) for key, value in dict.items():
c) for key, value in dict:
d) for key in dict.keys():
Answer: b) for key, value in dict.items():

7. What is the output of dict.keys()?


a) A list of keys
b) A list of values
c) A list of key-value pairs
d) A dictionary
Answer: a) A list of keys

8. Which method is used to add new key value pair if not exists ?
a) get()
b) setdefault()
c) add()
d) insert()
Answer: a) setdefault()

9. How do you merge two dictionaries?


67
a) dict1 + dict2
b) dict1.update(dict2)
c) dict1.merge(dict2)
d) dict1.extend(dict2)
Answer: b) dict1.update(dict2)

10. What is the output of dict.clear()?


a) An empty dictionary
b) A dictionary with one key-value pair
c) A dictionary with all keys removed
d) A dictionary with all values removed
Answer: a) An empty dictionary

COMPETENCY BASED QUESTIONS


1. Write a Python function to count the frequency of each word in a given string and store the result
in a dictionary.
e.g.
Input: "Hello world, hello python"
Output: {"Hello": 2, "world": 1, "python": 1}

2. Create a dictionary to store student information, including name, age, and grade. Write a function
to add a new student and another function to retrieve a student's information by name.

3. Given a dictionary of student grades, write a function to calculate the average grade for each
student and return the result in a new dictionary.
Input: {"John": [80, 70, 90], "Jane": [90, 80, 70]}
Output: {"John": 80.0, "Jane": 80.0}

4. Write a function to merge two dictionaries and return the result.


Input: dict1 = {"a": 1, "b": 2}, dict2 = {"c": 3, "d": 4}
Output: {"a": 1, "b": 2, "c": 3, "d": 4}

5. Create a dictionary to store book information, including title, author, and price. Write a function to
find the average price of books by a specific author.
6. Given a dictionary of employee data, write a function to find the highest salary and return the
employee's name and salary.
Input: {"John": 50000, "Jane": 60000, "Bob": 70000}
Output: ("Bob", 70000)

7. Write a function to remove duplicate values from a dictionary and return the result.
Input: {"a": 1, "b": 2, "c": 1, "d": 3}
Output: {"a": 1, "b": 2, "d": 3}

8. Create a dictionary to store city information, including name, population, and country.
9. With respect to Q. 8 , Write a function to find cities with a population greater than a given
threshold.
10. Write a small project using the concept learnt so far.

VERY SHORT QUESTIONS


1. What is the syntax to create an empty dictionary? - {} or dict()
2. How do you add a key-value pair to a dictionary? - dict[key] = value
68
3. How do you access a value in a dictionary? - dict[key]
4. What happens if you try to access a non-existent key? - KeyError
5. How do you remove a key-value pair from a dictionary? - del dict[key] or dict.pop(key)
6. What is the output of dict.keys()? - A list of keys
7. How do you merge two dictionaries? - dict1.update(dict2)
8. What is the output of dict.get(key, default)? - The value if key exists, otherwise default
9. How do you iterate over key-value pairs in a dictionary? - for key, value in dict.items():
10. What is the output of dict.clear()? - An empty dictionary

VERY LONG QUESTIONS


1. Write a Python program to create a dictionary that stores the names of students as keys and their
respective grades as values. The program should also calculate the average grade of all students.

2. Develop a Python program that utilizes a dictionary to store the details of employees in a company,
including their names, ages, and salaries. The program should also calculate the total salary
expenditure.

3. Create a Python dictionary that stores the names of cities as keys and their respective populations
as values. Write a program that includes functions to find the city with the highest population.

4. Design a Python program that employs a dictionary to store the details of books in a library,
including their titles, authors, and publication years. The program should also find books by a specific
author.

5. Write a Python program that utilizes a dictionary to store the details of customers in an e-
commerce platform, including their names, addresses, and order histories. The program should find
the customer with the highest total order value.

6. Develop a Python program that uses a dictionary to store the details of courses in an online
learning platform, including their titles, descriptions, and prices. The program should find courses by
a specific title.

7. Create a Python dictionary that stores the names of countries as keys and their respective capitals
as values. Write a program that finds the capital of a specific country, calculate the number of
countries in the dictionary, and add a new country to the dictionary.

8. Design a Python program that employs a dictionary to store the details of patients in a hospital,
including their names, ages, and medical records. The program should find patients by a specific age
range.

9. Write a Python program that utilizes a dictionary to store the details of products in an inventory
management system, including their names, quantities, and prices. The program should update the
quantity of a product.

10. Develop a Python program that uses a dictionary to store the details of flights in an airline
management system, including their numbers, departure times, and arrival times. The program
should find flights based on its number, and add a new flight to the dictionary.

69
Modules in Python
A module is simply a python file where statements,

classes, Objects, functions, constants and variables are defined. The file name is the module name
with .py extension. Definitions from a module can be imported into other modules. It is a kind of code
library.

We can use the module we created, by using the import statement.

How to import modules in Python?

Python module can be accessed in any of following ways.

1. Python import statement


import math
print(“2 to the power 3 is ", math.pow(2,3))
Just similar to math ,user defined module can be accessed using import statement
2. Import with renaming
import math as mt
print(“2 to the power 3 is ", mt.pow(2,3))
3. Python from...import statement
from math import pow
print(“2 to the power 3 is ", pow(2,3))
4. Import all names
from math import *
print(“2 to the power 3 is ", pow(2,3))

Functions of math module:


To work with the functions of the math module, we must import the math module
in the program.
import math

S. No. Function Description Example

Returns the square root of >>>math.sqrt(49)


1 sqrt( ) a number 7.0

>>>math.ceil(81.3)
2 ceil( ) Returns the upper integer 82

>>>math.floor(81.3)
3 floor( ) Returns the lower integer 81

Calculate the power >>>math.pow(2,3)


4 pow( ) of a number 8.0

5 fabs( ) Returns the absolute value of a >>>math.fabs(-5.6)


number 5.6

70
>>>math.sin(90)
6 sin( ) Returns the sine of a number 0.89399

>>>math.cos(90)
7 cos() Returns the cosine of a number -0.448073

>>>math.tan(90)
8 tan() Returns the tangent of a number
-1.995200

Functions of random module:

To work with the functions of a random module, we must import a random module in the
program.

import random

S. No. Function Description Example

1 random () It returns a random float >>>random.random()


x, such that 0 ≤ x<1 ><1
0.281954791393

2 randint(a, b) It returns a int x between >>>random.randint(1,10)


a & b such that a ≤ x ≤ b
5

3 Randrange ([start,] It returns a random item >>>random.randrange(100,1000,3)


stop [,step]) from the given range upto 150
stop-1.

Functions of statistics module:

To work with the functions of the statistics module, we must import the statistics module in the
program.

import statistics

S. No. Function Description Example

1 mean ( ) It returns mean of a list of numbers >>> print(statistics.mean([1, 3, 5, 7, 9,


11]))
6

2 median() It returns the median (middle value) of >>> print(statistics.median([1, 3, 5, 7,


the given data set 9, 11, 13]))
7

71
3 mode() It returns the mode (central tendency) >>> print(statistics.mode([1, 3, 3, 3, 5,
of the given numeric or nominal data 7, 7, 9]))
set. 3

MINDMAP

MCQ

1
Study the following program and select the possible output(s) from the options (i) to (iv)
following it. Also, write the maximum and the minimum values that can be assigned to the
variable Y.
import random
X=random.random()
Y=random.randint(1,4)
print(int(X),”:”,Y+int(X))
i) 0 : 0 ii) 1 : 6 iii) 2 : 4 iv) 0 : 3
2 Observe the following program and answer the questions that follow:

import random
X=3
N=random.randint(1,X)
for i in range(N):
print (i,”#”,i+1)

72
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
3
What possible outputs(s) are expected to be displayed on screen at the time of execution of
the program from the following code? Also specify the maximum values that can be
assigned to each of the variables FROM and TO.

import random
AR=[20,30,40,50,60,70];
FROM=random.randint(1,3)
TO=random.randint(2,4)
for K in range(FROM,TO+1):
print (AR[K],end=”# “)

(i) 10#40#70# (ii) 30#40#50# (iii)50#60#70# (iv) 40#50#70#


4
What possible outputs(s) are expected to be displayed on screen at the time of execution of
the program from the following code? Also specify the maximum values that can be
assigned to each of the variables START and END. 2

import random
SCORE=[20,40,10,30,15];
START=random.randint(1,3)
END=random.randint(2,4)
for I in range(START,END+1):
print(SCORE[I],"&")
(i) 10&40&20& (ii) 10&30&15& (iii) 40&10&30& (iv) 20&40&10&
5 What are the possible outcome(s) executed from the following code? Also specify the
maximum and minimum values that can be assigned to variable N.

import random
PLAY=[40,50,10,20]"EAST","WEST","NORTH","SOUTH";
ROUND=random.randint(2,3)
for J in range(ROUND,1,–1):
print PLAY[J],”:”
(i) 20:10: (ii) 20:10:50: (iii) 20: (iv) 40:50:20:
6
What possible output(s) are expected to be displayed on screen at the time of execution of
the program from the following code ? Also specify the maximum values that can be
assigned to each of the variables BEGIN and LAST. 2
import random

73
POINTS=[20,40,10,30,15]
POINTS=[30,50,20,40,45]
BEGIN=random.randint(1,3)
LAST=random.randint(2,4)
for C in range(BEGIN,LAST+1):
print POINTS[C],"#"

(i) 20#50#30# (ii) 20#40#45# (iii) 50#20#40# (iv) 30#50#20#

Very Short Answers

1 Predict the output:


from math import *
x=12
y=10 * sqrt(pow(x,2))
2 Identify the errors and correct them:
Import math
Y=36
S=sqrt(Y)
Print(S)
3 Predict the output:
import math
num=14.14
print(math.ceil(num))
print(math.floor(num))
4 Predict the output: (What are the maximum and minimum possible values?)
import random
print(random.random(5))
5 Predict the output:
li=[1,2,3,4,5,6,7,8,9,10]
from statistics import *
print(mean(li))
print(median(li))
6 Identify the errors and correct them:
li=[1,2,3,4,5,6,7,8,9,10]
from statistics import *
print(li.mean())
print(statistics.median(li))
7 Predict the output: (What are the possible values?)
import random
print(random.randint(5,10))
8 Predict the output: (What are the possible values?)
import random
print(random.randrange(10,20,2))
9 Write program to find square root of a function using math module
10 Predict the output:
li=[1,2,3,4,4,4,4,4,4,5,5,5,5,5,6,7,8,8,8,8,9,10]
from statistics import *
print(mode(li))

74
Unit III: Society, Law, and Ethics
Digital footprints

Digital footprints are the traces of data that individuals leave behind while using the internet. These
footprints can be categorized into two main types: active and passive.

Types of Digital Footprints

1. Active Digital Footprints:


o Social Media Posts: Updates, photos, and comments on platforms like Facebook,
Instagram, and Twitter.
o Emails: Sent and received emails.
o Online Forms: Information filled out on online forms, surveys, or registrations.
o Blog Posts and Comments: Content published on blogs or comments left on various
websites.
o Online Purchases: Information about items bought online, including reviews and
feedback.
2. Passive Digital Footprints:
o Browsing History: Records of websites visited, even if not actively interacting with
them.
o IP Addresses: Data associated with the IP addresses that identify devices on the
internet.
o Cookies: Small files stored on devices by websites to track user behavior and
preferences.
o Location Data: Information on where a device has been, often collected through apps
and services.

Importance and Implications

● Privacy Concerns: Digital footprints can reveal personal information, leading to privacy
breaches if not managed properly.
● Security Risks: Hackers can exploit digital footprints to gain unauthorized access to personal
and financial data.
● Personal Branding: Online presence, including professional networks and personal posts,
contributes to one's personal brand.
● Data Analytics: Businesses use digital footprints to analyse consumer behaviour and
preferences for targeted marketing.

75
Managing Digital Footprints

1. Privacy Settings: Regularly update privacy settings on social media and other platforms to
control what information is shared publicly.
2. Clear Browsing Data: Frequently clear cookies and browsing history to minimize passive
footprints.
3. Use Strong Passwords: Implement strong, unique passwords for different accounts to
protect against unauthorized access.
4. Be Mindful of Sharing: Think twice before posting personal information online and avoid
oversharing.
5. Use Encryption: Use encrypted communication methods for sensitive information to enhance
security.

Digital Society and Netizen: net etiquettes, communication etiquettes, social media etiquettes

Netiquette Netiquette refers to the correct or acceptable way of communicating on the internet. Key
principles include:

1. Be Respectful: Treat others with respect, regardless of differences in opinions or beliefs.


2. Avoid Trolling: Do not post inflammatory or offensive comments to provoke others.
3. Respect Privacy: Do not share personal information of others without their consent.
4. Use Appropriate Language: Avoid using foul or abusive language.
5. Be Constructive: Provide constructive feedback and engage in meaningful discussions.

Communication Etiquettes

Communication etiquette involves proper conduct when communicating via digital means,
including email, instant messaging, and video calls. Important guidelines are:

1. Clear and Concise Messages: Keep messages clear and to the point.
2. Professional Tone: Maintain a professional tone, especially in work-related communications.
3. Timely Responses: Respond to messages in a timely manner to maintain effective
communication.
4. Proper Formatting: Use proper grammar, spelling, and formatting.
5. Subject Lines: Use relevant subject lines in emails to indicate the content of the message.

Social Media Etiquettes Social media etiquette encompasses the proper way of interacting on
platforms like Facebook, Twitter, Instagram, and LinkedIn. Key practices include:
76
1. Respectful Interaction: Engage respectfully with others, avoiding arguments and personal
attacks.
2. Think Before Posting: Consider the potential impact and permanence of posts before
sharing.
3. Credit Sources: Always credit original sources when sharing content created by others.
4. Be Authentic: Maintain authenticity and honesty in your posts and interactions.
5. Avoid Spamming: Do not flood timelines or feeds with excessive posts, tags, or messages.

Data protection

Data protection encompasses various aspects of safeguarding information and respecting intellectual
property rights (IPR). Understanding the different types of IPR, recognizing violations, and
comprehending open-source software and licensing are crucial in the digital age.

Intellectual Property Rights (IPR)

Intellectual property rights are legal rights that protect creations of the mind. These include:

1. Copyright:
o Definition: Protects original works of authorship such as literature, music, and art.
o Duration: Generally lasts for the lifetime of the author plus 70 years.
o Rights Granted: Exclusive rights to reproduce, distribute, perform, display, or license
the work.
2. Patent:
o Definition: Protects new inventions or discoveries.
o Duration: Typically lasts for 20 years from the filing date.
o Rights Granted: Exclusive rights to make, use, sell, and import the invention.
3. Trademark:
o Definition: Protects symbols, names, and slogans used to identify goods or services.
o Duration: Can last indefinitely, as long as the trademark is in use and properly
renewed.
o Rights Granted: Exclusive rights to use the mark in commerce and to prevent others
from using similar marks that could cause confusion.

Violation of IPR

Violations of intellectual property rights include:

77
1. Plagiarism:
o Definition: The act of using someone else's work or ideas without proper attribution.
o Implications: Academic and professional consequences, legal penalties, and
reputational damage.
2. Copyright Infringement:
o Definition: Unauthorized use of copyrighted material.
o Examples: Copying and distributing music, movies, books, or software without
permission.
o Penalties: Legal action, fines, and potential imprisonment.
3. Trademark Infringement:
o Definition: Unauthorized use of a trademark that causes confusion about the origin of
goods or services.
o Examples: Using a similar logo or brand name to mislead consumers.
o Penalties: Legal action, financial damages, and injunctions against further use.

Open-Source Software and Licensing

Open-source software is software with source code that anyone can inspect, modify, and enhance.
Key open-source licenses include:

1. Creative Commons (CC):


o Purpose: Provides a variety of licenses that creators can use to specify permissions for
their works.
o Types: Ranges from the most permissive (CC BY) to the most restrictive (CC BY-NC-
ND).
2. General Public License (GPL):
o Purpose: Ensures that software remains free and open, requiring any derivative works
to also be distributed under the same license.
o Key Feature: Copyleft provision, which mandates that modifications and derived
works must be open source under the GPL.
3. Apache License:
o Purpose: Provides a permissive license allowing users to use the software for any
purpose, distribute it, modify it, and distribute modified versions.
o Key Feature: Does not require derivative works to be open source, allowing for
incorporation into proprietary projects.

Cyber Crime:

Cyber crime encompasses illegal activities conducted via the internet or other computer networks.
These crimes exploit vulnerabilities in digital systems and can cause significant harm to individuals,
organizations, and society at large. Key types of cyber crime include hacking, eavesdropping,
phishing, ransomware, cyber trolling, and cyber bullying.

78
Cyber Crime:

● Definition: Illegal activities conducted using computers, networks, or the internet.


● Impact: Can lead to financial loss, data breaches, identity theft, and emotional distress.

Types of Cyber Crime

1. Hacking:
o Definition: Unauthorized access to computer systems or networks.
o Methods: Exploiting vulnerabilities, using malware, or brute force attacks.
o Consequences: Data theft, system damage, and loss of privacy.
2. Eavesdropping:
o Definition: Intercepting private communications without permission.
o Methods: Man-in-the-middle attacks, network sniffing.
o Consequences: Exposure of sensitive information, loss of confidentiality.

3. Phishing and Fraud Emails:


o Definition: Fraudulent attempts to obtain sensitive information by masquerading as a
trustworthy entity.
o Methods: Fake emails, websites, or messages that prompt recipients to provide
personal information.
o Consequences: Identity theft, financial loss, and unauthorized access to accounts.
4. Ransomware:
o Definition: Malware that encrypts a victim's data and demands payment for the
decryption key.
o Methods: Phishing emails, malicious downloads, exploit kits.
o Consequences: Data loss, financial extortion, and operational disruptions.
5. Cyber Trolls:
o Definition: Individuals who deliberately provoke or harass others online to elicit
emotional responses.
o Methods: Posting inflammatory, off-topic, or offensive comments.
o Consequences: Disruption of online communities, psychological distress.
6. Cyber Bullying:
o Definition: The use of digital communication tools to bully, harass, or intimidate
someone.
o Methods: Social media harassment, threatening messages, spreading rumors.
o Consequences: Emotional trauma, mental health issues, and, in severe cases, suicidal
thoughts.
79
Cyber Safety

Cyber safety involves practices and measures to protect oneself and one's information while using
the internet. It includes safely browsing the web, protecting your identity, and maintaining the
confidentiality of your data.

Safely Browsing the Web

1. Use Secure Connections:


o HTTPS: Always check that websites use HTTPS instead of HTTP. The 'S' stands for
secure, meaning that the data sent between your browser and the website is
encrypted.
o VPN: Use a Virtual Private Network (VPN) to encrypt your internet connection,
especially when using public Wi-Fi. This prevents attackers from eavesdropping on
your online activities.
2. Avoid Suspicious Websites:
o Check URLs: Be cautious of URLs that look unusual or unfamiliar. Cybercriminals often
use slightly altered URLs to trick users into visiting malicious sites.
o Security Indicators: Look for a padlock icon in the address bar and verify the site’s
certificate to ensure it’s legitimate.
3. Use Safe Browsing Tools:
o Browser Extensions: Install extensions that block ads, trackers, and malicious sites.
Examples include uBlock Origin and Privacy Badger.
o Antivirus Software: Use reputable antivirus software that provides real-time
protection against malware and phishing attempts.
4. Regularly Update Software:
o Browsers and OS: Keep your web browser and operating system up to date to protect
against security vulnerabilities.
o Plugins: Update plugins like Java and Flash or disable them if not needed, as they can
be exploited by attackers.
5. Be Cautious with Downloads:
o Sources: Download software and files only from trusted sources. Avoid pirated
software, as it can contain malware.
o Scans: Use antivirus software to scan files before opening them.

80
Identity Protection

1. Use Strong Passwords:


o Complexity: Create passwords that are at least 12 characters long and include a mix of
letters, numbers, and special characters.
o Uniqueness: Avoid reusing passwords across different accounts. Use unique
passwords for each account.
2. Enable Two-Factor Authentication (2FA):
o Extra Security: Enable 2FA on all accounts that offer it. This adds an extra layer of
security by requiring a second form of verification, such as a code sent to your phone.
o Methods: Use authentication apps like Google Authenticator or Authy instead of SMS-
based 2FA for better security.
3. Be Wary of Phishing Scams:
o Emails and Links: Be cautious of emails or messages asking for personal information
or containing suspicious links. Verify the sender’s email address and look for signs of
phishing.
o Attachments: Do not open attachments from unknown sources.
4. Monitor Personal Information:
o Credit Reports: Regularly check your credit reports for any suspicious activity.
o Account Activity: Monitor your bank and online accounts for unauthorized
transactions.

Confidentiality

1. Data Encryption:
o Storage: Encrypt sensitive data stored on your devices. Tools like BitLocker
(Windows) or FileVault (Mac) can encrypt your hard drive.
o Communication: Use encrypted communication tools for sending sensitive
information. Apps like Signal and WhatsApp offer end-to-end encryption.
2. Secure Backups:
o Regular Backups: Regularly back up important data to an external drive or cloud
service. Ensure that backups are encrypted and stored securely.
o Offsite Storage: Consider using an offsite location for storing backups to protect
against physical threats like theft or fire.
3. Access Controls:
o Permissions: Restrict access to sensitive information based on user roles. Ensure that
only authorized individuals have access to certain data.
o Authentication: Use strong authentication methods for accessing sensitive systems
and data.
4. Secure Disposal:
o Data Wiping: Use secure methods to erase data from devices before disposal. Simply
deleting files is not enough; use tools that perform a complete wipe of the storage.
o Physical Destruction: For highly sensitive information, consider physically destroying
storage media to ensure data cannot be recovered.

Malware

Malware, short for malicious software, is any software intentionally designed to cause damage to a
computer, server, client, or computer network. Malware can steal, encrypt, or delete data, alter or
hijack core computing functions, and spy on computer activity without the user's knowledge or
permission.
81
1. Viruses

Definition: A computer virus is a type of malware that attaches itself to a legitimate program or file
and spreads to other programs and files on the same system, eventually affecting other systems.

Characteristics:

● Replication: Viruses can replicate themselves and spread to other programs and files when
the infected program or file is executed.
● Activation: Often, viruses lay dormant until the infected file is run or a specific condition is
met.
● Payload: They can carry a payload that performs malicious actions like corrupting data,
logging keystrokes, or even creating backdoors.

Prevention and Protection:

● Antivirus Software: Regularly update and run antivirus software to detect and remove
viruses.
● Avoid Suspicious Links and Downloads: Be cautious when opening email attachments or
downloading files from unknown sources.
● System Updates: Keep your operating system and applications up-to-date to protect against
known vulnerabilities.

2. Trojans

Definition: A Trojan horse, or Trojan, is a type of malware that disguises itself as legitimate software.
Users are typically tricked into loading and executing Trojans on their systems.

Characteristics:

● Deception: Trojans appear as harmless or useful software but perform malicious activities
once installed.
● Variety of Malicious Actions: They can create backdoors, steal information, or download
additional malware.

82
● No Self-Replication: Unlike viruses and worms, Trojans do not replicate themselves but rely
on social engineering to spread.

Types of Trojans:

● Backdoor Trojans: Allow remote control over the infected system.


● Downloader Trojans: Download and install other malicious software.
● Spyware Trojans: Monitor user activities and steal sensitive information.
● Banking Trojans: Target online banking credentials and financial information.

Prevention and Protection:

● Download from Trusted Sources: Only download software from reputable and official
sources.
● Be Wary of Unexpected Emails: Avoid downloading or opening attachments from unknown
or unexpected email sources.
● Security Software: Use comprehensive security software that can detect and block Trojans.

3. Adware

Definition: Adware is a type of malware that automatically delivers advertisements to the user’s
device. It is often bundled with free software and installed without the user's knowledge or consent.

Characteristics:

● Pop-Up Ads: Generates frequent and intrusive advertisements, often in the form of pop-up
windows.
● User Tracking: Adware can track the user’s browsing habits and send this data back to
advertisers.
● Performance Impact: Can slow down system performance and use up bandwidth.

Types of Adware:

● Legitimate Adware: Comes with user consent, often bundled with freeware or shareware,
and can usually be removed by uninstalling the associated software.
● Potentially Unwanted Programs (PUPs): Adware that is installed without explicit user
consent and is often more difficult to remove.

Prevention and Protection:

● Adblockers: Use browser extensions that block ads and pop-ups.


● Careful Installation: Pay attention to installation prompts and opt out of installing additional
software that you do not need.
● Anti-Adware Tools: Use security software that can detect and remove adware.

E-waste management:
E-waste, or electronic waste, refers to discarded electronic appliances and devices. With the rapid
pace of technological advancement, the accumulation of e-waste has become a significant
environmental issue. Proper e-waste management is essential to mitigate its harmful effects on the
environment and human health.
83
Importance of Proper E-Waste Management

1. Environmental Protection: E-waste contains hazardous materials such as lead, mercury,


cadmium, and brominated flame retardants, which can contaminate soil and water if not
disposed of properly.
2. Resource Conservation: Many electronic devices contain valuable materials like gold, silver,
copper, and rare earth elements. Proper recycling can recover these materials and reduce the
need for mining new resources.
3. Health Protection: Improper disposal and informal recycling processes can expose workers
and the public to toxic substances, leading to health issues like respiratory problems, skin
diseases, and neurological damage.

Steps for Proper E-Waste Management

1. Reduce, Reuse, and Recycle:


o Reduce: Minimize e-waste generation by buying only what you need, choosing durable
products, and avoiding unnecessary upgrades.
o Reuse: Extend the life of your electronic devices by repairing them, donating them to
others, or selling them.
o Recycle: Ensure that old and non-functional devices are recycled properly through
authorized e-waste recycling programs.
2. Identify E-Waste:
o Common E-Waste Items: Computers, laptops, mobile phones, tablets, televisions,
printers, refrigerators, and other household appliances.
o Batteries and Accessories: Include batteries, chargers, earphones, and other
electronic accessories in your e-waste disposal plans.
3. Responsible Disposal:
o Certified E-Waste Recyclers: Use certified e-waste recycling services to ensure that
the devices are dismantled and recycled in an environmentally friendly manner.
o Manufacturer Take-Back Programs: Many electronics manufacturers offer take-back
programs to recycle their products. Check with the manufacturer or retailer for such
programs.
o Municipal Collection Programs: Participate in local government e-waste collection
events or drop-off programs.
4. Data Security:
84
Data Wiping: Before disposing of or recycling electronic devices, ensure that all
o
personal data is securely erased. Use software tools to wipe data from hard drives,
phones, and other storage devices.
o Physical Destruction: For highly sensitive data, consider physically destroying the
storage media to prevent data recovery.
5. Regulations and Guidelines:
o Follow Local Laws: Adhere to local, state, and national regulations regarding e-waste
disposal and recycling.
o Stay Informed: Keep updated with guidelines and best practices for e-waste
management from reputable sources such as environmental organizations and
government agencies.

E-Waste Recycling Process

collection & Recovery &


Sorting & Shredding & Disposable of
transportati
Dismantling Seperation Refinement residual waste
on

1. Collection and Transportation:


o E-waste is collected from various sources, including households, businesses, and
institutions, and transported to recycling facilities.
2. Sorting and Dismantling:
o Devices are manually sorted and dismantled into various components, such as plastics,
metals, circuit boards, and glass.
3. Shredding and Separation:
o The dismantled components are further shredded into smaller pieces and separated
using techniques like magnetic separation (for ferrous metals), eddy current
separation (for non-ferrous metals), and flotation (for plastics).
4. Recovery and Refinement:
o Precious metals and other valuable materials are extracted and refined using chemical
and electrochemical processes.

5. Disposal of Residual Waste:


o Non-recyclable and hazardous materials are disposed of in compliance with
environmental regulations to minimize environmental impact.

Information Technology Act (IT Act)

The Information Technology Act (IT Act), enacted in 2000 in India, is a comprehensive legal
framework to address the issues related to cybercrime and electronic commerce. Here are the basic
points of the IT Act:

1. Objective

● Primary Purpose: To provide legal recognition for transactions carried out by means of
electronic data interchange and other means of electronic communication, commonly referred
to as "e-commerce".
● Cybercrime: To address the emerging legal issues related to online activities, cybercrime, and
digital signatures.

85
2. Key Provisions

● Legal Recognition of Electronic Documents: Provides legal recognition to electronic


documents, thus facilitating electronic governance.
● Digital Signatures: Legal recognition of digital signatures for the authentication of electronic
records.
● Certifying Authorities: Establishes a framework for the accreditation of certifying
authorities, who issue digital certificates.
● Electronic Contracts: Recognition of electronic contracts, making them legally enforceable.

3. Offenses and Penalties

● Unauthorized Access: Penalties for gaining unauthorized access to computer systems,


including hacking.
● Data Theft: Punishments for stealing data stored in a computer, such as copying or extracting
data without permission.
● Virus Attacks: Penalties for introducing viruses, worms, or other malicious software into
computer systems.
● Identity Theft: Penalties for identity theft and fraud involving the use of digital identities.
● Cyber Terrorism: Stringent penalties for cyber terrorism activities.

4. Adjudication and Regulation

● Cyber Appellate Tribunal: Establishment of a Cyber Appellate Tribunal to handle appeals


against orders from adjudicating officers related to contraventions under the Act.
● Regulation of Certifying Authorities: Guidelines for the regulation and functioning of
certifying authorities who issue digital signatures.
● Appointment of Adjudicating Officers: Appointment of adjudicating officers to handle
disputes and grievances related to the provisions of the IT Act.

5. Amendments and Updates

● IT (Amendment) Act, 2008: Significant amendments to address evolving cyber threats,


including:
o Child Pornography: Prohibition of child pornography and punishments for related
offenses.
o Phishing and Spam: Provisions to combat phishing attacks and spamming.
o Data Protection: Introduction of data protection measures, including safeguards for
sensitive personal information.

6. E-Governance and E-Commerce

● Electronic Governance: Promotion of electronic governance and the use of digital signatures
for government transactions.
● E-Commerce: Legal recognition and facilitation of electronic commerce, making online
business transactions legally binding.

7. Liability of Intermediaries

86
● Intermediary Guidelines: Defines the roles and responsibilities of intermediaries (e.g., ISPs,
web hosts) in managing and removing unlawful content.
● Safe Harbor Provisions: Provides safe harbor protection to intermediaries, limiting their
liability for third-party content under certain conditions.

8. Miscellaneous Provisions

● Privacy Protection: Provisions to safeguard the privacy of individuals and data protection
requirements.
● Computer Resource Tampering: Penalties for tampering with computer resources,
including data alteration and system interference.
● Confidentiality: Obligations on maintaining the confidentiality and security of electronic
records and digital signatures.

Technology and society: Gender and disability issues while teaching and using computers

Technology plays a pivotal role in modern society, impacting various facets of life, including
education and accessibility for different demographics such as gender and individuals with
disabilities. Here’s an exploration of how technology interacts with these issues in teaching and
computer use:

Gender Issues:

Gender
Issues

Access & Gender Bias Empowermen Safe &


Participatio in t& Inclusive
n technology opportunities spaces

Digital Representaoi Algorithmic Education Skill Entreprenu Cyber Digital


Divide n Bias Bias Development ership Security Literacy

Disability Issues

Disability
Issues

Accessibilty Inclusive Empowerment & Policy &


Challenges Education independence Advocacy

Accessible
Adaptive Universal Assistive Social Employment Legal
Design Technologies
Learning
Inclusion
Advocacy
Technologies material opportunities Protections

87
Multiple choice questions

1) Which of the following best describes a digital footprint?

A. The physical trails left behind by someone on the internet


B. The environmental impact of digital devices
C. The collection of all the traces and activities someone leaves online
D. The programming languages used in digital technology

2) What can contribute to your digital footprint?

A. Browsing websites
B. Posting on social media
C. Sending emails
D. All of the above

3) Which of the following actions can help you manage and reduce your digital footprint?

A. Regularly clearing your browser history and cookies


B. Using strong, unique passwords for different accounts
C. Adjusting privacy settings on social media platforms
D. All of the above

4) Which of the following is considered good netiquette when participating in an online


discussion?

A. Using all caps to emphasize your points


B. Respecting others' opinions and responding politely
C. Posting off-topic comments
D. Ignoring other participants' contributions

5) What should you do if you receive an email that appears to be a phishing attempt?

A. Forward it to all your contacts


B. Click on any links to verify if they are safe
C. Delete the email and report it to your email provider
D. Reply to the email asking for more information

6) When composing an email, which of the following practices is considered appropriate


netiquette?

A. Using informal language regardless of the recipient


B. Keeping your message clear and concise
C. Ignoring spelling and grammar errors
D. Using vague subject lines

7) What is the primary purpose of data protection laws?

A. To prevent data from being stored


B. To ensure the free flow of data
C. To safeguard personal information from unauthorized access or disclosure
88
D. To make data publicly available

8) Which of the following is a key principle of the General Data Protection Regulation (GDPR)?

A. Data must be processed unlawfully


B. Data can be collected without any specific purpose
C. Individuals have the right to access and control their personal data
D. Personal data must be stored indefinitely

9) Which practice helps protect data when sharing it electronically?

A. Sending data over unencrypted email


B. Using strong passwords and encryption
C. Sharing passwords with others
D. Keeping default security settings

10) Which of the following is an example of phishing?

A. Installing antivirus software


B. Sending emails that appear to be from a legitimate source to steal personal information
C. Developing a new software application
D. Creating a strong password

11) Which type of cyber-crime involves taking control of someone’s computer to use it for
sending spam or launching attacks?

A. Identity theft
B. Hacking
C. Ransomware
D. Botnet

12) What is the primary goal of ransomware?

A. To steal personal information for identity theft


B. To encrypt the victim's data and demand payment for the decryption key
C. To create backup copies of data
D. To monitor internet usage

13) Which of the following is a good practice to ensure cyber safety when using public Wi-Fi?

A. Accessing sensitive accounts, such as online banking


B. Using a VPN (Virtual Private Network)
C. Disabling firewall protection
D. Sharing personal information freely

14) What is two-factor authentication (2FA)?

A. A method of logging into accounts using two different passwords


B. A security process in which the user provides two different authentication factors to verify
themselves
C. A way to create a backup of your data
89
D. A method of encrypting files on your computer

15) Which of the following actions can help protect against malware infections?

A. Clicking on unknown links in emails


B. Regularly updating your software and operating system
C. Downloading files from untrusted sources
D. Disabling antivirus software

16) Which of the following best describes malware?

A. Software designed to protect your computer from viruses


B. Malicious software intended to damage or disable computers and computer systems
C. A type of hardware that speeds up your computer
D. An operating system feature

17) What type of malware disguises itself as legitimate software but performs malicious
activities?

A. Virus
B. Trojan Horse
C. Worm
D. Spyware

18) Which type of malware replicates itself in order to spread to other computers?

A. Adware
B. Spyware
C. Worm
D. Ransomware

19) What is the primary goal of e-waste management?

A. To increase the production of electronic devices


B. To dispose of electronic waste in landfills
C. To recycle and properly dispose of electronic waste to minimize environmental impact
D. To store electronic waste indefinitely

20) Which of the following is a common practice in e-waste recycling?

A. Burning electronic devices to retrieve metals


B. Disposing of electronic waste in household trash bins
C. Dismantling electronic devices to recover valuable materials
D. Using electronic devices as landfill cover

21) What is a significant environmental concern associated with improper e-waste disposal?

A. Increase in the production of new electronics


B. Contamination of soil and water with toxic substances
C. Decrease in electronic device prices
D. Improvement in landfill efficiency
90
22) Which of the following is a primary objective of the Information Technology Act, 2000?

A. To regulate the use of mobile phones


B. To provide legal recognition for electronic transactions
C. To establish guidelines for television broadcasting
D. To manage public libraries

23) Which of the following is considered a cybercrime under the Information Technology Act,
2000?

A. Unauthorized access to computer systems


B. Physical theft of hardware
C. Traditional forms of fraud
D. Plagiarism in academic writing

24) Which of the following is an important consideration regarding gender and computer use
in education?

A. Providing equal access to computer labs for all students


B. Restricting computer use based on gender preferences
C. Limiting girls' access to programming courses
D. Allowing only boys to use advanced software tools

25) In the context of disability issues, which technology feature is essential for enhancing
accessibility when using computers?

A. Monochrome displays
B. Voice recognition software
C. Limited keyboard functionality
D. Older operating system versions

Answers:

1) C. The collection of all the traces and activities someone leaves online
2) D. All of the above
3) D. All of the above
4) B. Respecting others' opinions and responding politely
5) C. Delete the email and report it to your email provider
6) B. Keeping your message clear and concise
7) C.To safeguard personal information from unauthorized access or disclosure
8) C. Individuals have the right to access and control their personal data
9) B. Using strong passwords and encryption
10) B. Sending emails that appear to be from a legitimate source to steal personal information
11) D. Botnet
12) B. To encrypt the victim's data and demand payment for the decryption key
13) B. Using a VPN (Virtual Private Network)
14) B. A security process in which the user provides two different authentication factors to
verify themselves
15) B. Regularly updating your software and operating system
16) B. Malicious software intended to damage or disable computers and computer systems
17) B. Trojan Horse
91
18) C. Worm
19) C. To recycle and properly dispose of electronic waste to minimize environmental impact
20) C. Dismantling electronic devices to recover valuable materials
21) B. Contamination of soil and water with toxic substances
22) B. To provide legal recognition for electronic transactions
23) A. Unauthorized access to computer systems
24) A. Providing equal access to computer labs for all students
25) B. Voice recognition software

Competency Based Questions

Q 1) Describe a situation where you had to manage your digital footprint. What steps did you take,
and what was the outcome?
Answer: In college, I realized that my social media presence could impact job prospects. I reviewed
my profiles, adjusted privacy settings, and removed any unprofessional content. Additionally, I
started sharing industry-relevant articles and my own projects. As a result, I noticed a more positive
response from recruiters during interviews.
Q 2) Give an example of how you maintained netiquette during a heated online discussion.
Answer: During an online class debate, a disagreement arose about a controversial topic. I ensured I
responded respectfully by acknowledging the other person's points before presenting my arguments
with evidence. This approach kept the discussion productive and helped maintain a respectful tone in
the class forum.
Q 3) Have you ever dealt with a cyber troll? How did you handle the situation?
Answer: Yes, I managed a community forum where a user began posting inflammatory comments. I
addressed the issue by enforcing the community guidelines, warning the user, and eventually
banning them after repeated offenses. This action maintained a positive environment for other users.
Q 4) Can you describe an instance where you implemented data protection measures in a project?
Answer: In my previous job, I led a project to handle customer data. I ensured we used encryption
for sensitive information, implemented access controls, and conducted regular audits. These
measures helped protect our data from breaches, and we successfully passed an external security
audit.
Q 5) How did you respond to a potential cyber crime threat in your organization?
Answer: When our company received a phishing email targeting employees, I immediately informed
the IT department and communicated the threat to all staff. We conducted a training session on
recognizing phishing attempts, which significantly reduced the number of successful phishing
incidents.
Q 6) What strategies have you used to promote cyber safety awareness?
Answer: I organized a series of workshops covering topics like password security, recognizing
phishing, and safe browsing habits. Additionally, I created an intranet page with resources and tips
on cyber safety, which helped increase employee awareness and reduce security incidents.
Q 7) Describe a time when you had to deal with a malware infection. What was your approach?
Answer: Our office network was once infected with malware, causing several computers to
malfunction. I isolated the affected systems, ran antivirus scans to remove the malware, and restored
data from backups. Post-incident, we updated our security software and implemented stricter email
filtering to prevent future attacks.
Q 8) How have you contributed to e-waste management in your organization?
92
Answer: I initiated an e-waste recycling program where employees could safely dispose of old
electronics. We partnered with a certified e-waste recycler and organized quarterly collection drives.
This initiative not only reduced our environmental footprint but also raised awareness about e-waste
management.
Q 9) Can you provide an example of how you ensured compliance with the IT Act in a project?
Answer: While developing an e-commerce platform, I ensured our data collection practices complied
with the IT Act by obtaining user consent and securely storing data. We also implemented measures
to protect against cyber crimes, such as encryption and regular security audits, which helped us
maintain compliance and protect user data.
Q 10) How have you adapted your teaching methods to accommodate students with disabilities?
Answer: In my computer classes, I used screen readers for visually impaired students and provided
keyboard shortcuts for those with motor disabilities. I also ensured that all course materials were
accessible and offered one-on-one support to address individual needs. These adaptations helped all
students fully participate and succeed in the course.
Very Short Answer Questions

Q 1) What is a digital footprint?


Answer: A digital footprint is the trail of data one leaves online through activities like social media
posts and website visits.
Q 2) Why is netiquette important?
Answer: Netiquette ensures respectful and effective communication online.
Q 3) Who are cyber trolls?
Answer: Cyber trolls are individuals who provoke or harass others online to cause disruption.
Q 4) What is the purpose of data protection?
Answer: Data protection safeguards personal and sensitive information from unauthorized access
and breaches.
Q 5) What is phishing?
Answer: Phishing is a cyber crime where attackers deceive individuals into providing sensitive
information.
Q 6) How can you enhance cyber safety?
Answer: Enhance cyber safety by using strong passwords and enabling two-factor authentication.
Q 7) What is malware?
Answer: Malware is malicious software designed to harm or exploit computer systems.
Q 8) Why is proper e-waste disposal important?
Answer: Proper e-waste disposal prevents environmental pollution and health hazards.
Q 9) What does the IT Act regulate?
Answer: The IT Act regulates electronic commerce, cyber crimes, and digital signatures in India.
Q 10) How can educators support students with disabilities in computer classes?
Answer: Educators can support students with disabilities by providing accessible technologies and
personalized accommodations.

93
Short Answer Questions:

Q 1: How can individuals manage their digital footprints effectively?

Answer: Individuals can manage their digital footprints by being mindful of what they share online,
using privacy settings on social media platforms, regularly reviewing and deleting unnecessary data,
and considering the long-term implications of their online activities on their digital reputation.

Q 2: What are the potential consequences of leaving a large digital footprint?

Answer: A large digital footprint can lead to privacy concerns, identity theft, targeted advertising, and
reputational damage. Employers, universities, and even individuals may use digital footprints to form
opinions or make decisions about someone, highlighting the importance of managing online presence
carefully.

Q 3: Why is it important to avoid spreading misinformation or rumours online?

Answer: Spreading misinformation or rumours online can harm reputations, create confusion, and
contribute to societal distrust. Adhering to net etiquette involves verifying information before
sharing it and promoting constructive dialogue rather than spreading falsehoods.

Q 4: How can netiquette contribute to a positive online community?

Answer: Netiquette fosters respectful communication, encourages active listening, and promotes
empathy online. By following netiquette guidelines, individuals contribute to a supportive and
inclusive online environment where diverse opinions can be shared respectfully.

Q 5: What are cyber trolls, and how do they impact online communities?

Answer: Cyber trolls are individuals who deliberately provoke or harass others online through
inflammatory comments, insults, or disruptive behaviour. They can create toxic environments,
discourage healthy discourse, and even cause psychological harm to their targets.

Q 6: How can online platforms mitigate the impact of cyber trolls?

Answer: Online platforms can mitigate the impact of cyber trolls by implementing strict community
guidelines, encouraging positive interactions, providing reporting and blocking tools, and fostering a
culture where respectful communication is valued and rewarded.

Q 7: What are some best practices for organizations to ensure data protection?

Answer: Organizations can ensure data protection by implementing encryption for sensitive data,
conducting regular security audits, training employees on data security protocols, obtaining user
consent for data collection, and complying with data protection regulations such as GDPR or CCPA.

Q 8: How can individuals protect their data while using public Wi-Fi networks?

Answer: Individuals can protect their data on public Wi-Fi networks by using virtual private
networks (VPNs), ensuring websites use HTTPS encryption, avoiding accessing sensitive information,
and turning off sharing settings on their devices.

94
Q 9: What are the steps individuals should take if they become victims of cyber crime?

Answer: If individuals become victims of cyber crime, they should report the incident to law
enforcement or cyber crime authorities, preserve evidence such as screenshots or email
communications, notify their bank or financial institutions if financial fraud is involved, and take
steps to secure their accounts and devices.

Q 10: How can businesses prevent cyber crimes like ransomware attacks?

Answer: Businesses can prevent ransomware attacks by regularly backing up data, educating
employees about phishing and suspicious links, updating software and security patches promptly,
implementing strong access controls, and considering cyber insurance to mitigate financial losses.

Q 11: What are the common signs that indicate a device may be infected with malware?

Answer: Common signs of malware infection include slow performance, unexpected pop-up
windows, changes in browser settings, unusual network activity, and unauthorized access to
personal information. Prompt action is essential to mitigate further damage.

Q 12: How can parents ensure their children practice cyber safety while using the internet?

Answer: Parents can ensure their children practice cyber safety by setting parental controls on
devices and internet browsers, discussing safe online behaviour and potential risks, monitoring their
children's online activities, and encouraging open communication about any concerns or incidents.

Q 13: What are the main sources of malware distribution?

Answer: Malware can be distributed through malicious websites, infected email attachments,
software downloads from untrusted sources, removable storage devices like USB drives, and
compromised advertisements (malvertising) on legitimate websites.

Q 14: How does ransomware differ from other types of malware?

Answer: Ransomware is a type of malware that encrypts a victim's files or locks them out of their
device until a ransom is paid. Unlike other malware that may aim to steal data or disrupt operations,
ransomware directly extorts money from victims in exchange for restoring access to their files or
devices.

Q 15: Why is improper disposal of e-waste harmful to the environment?

Answer: Improper disposal of e-waste can lead to toxic substances such as lead, mercury, and
cadmium leaching into soil and water sources, posing health risks to humans and wildlife. Recycling
e-waste responsibly helps recover valuable materials and reduces environmental pollution.

Q 16: How can consumers contribute to responsible e-waste management?

Answer: Consumers can contribute to responsible e-waste management by recycling old electronics
through certified e-waste recycling programs, donating functional devices to charity or
refurbishment programs, and advocating for sustainable practices among manufacturers and
policymakers.

95
Q 17: What are the key provisions of the Information Technology Act related to cyber crime
and electronic signatures?

Answer: The Information Technology Act includes provisions for defining cyber crimes, specifying
penalties for offenses such as hacking and data theft, facilitating electronic commerce through legal
recognition of electronic records and digital signatures, and establishing adjudicating authorities for
cyber disputes.

Q 18: How does the IT Act support electronic governance in India?

Answer: The IT Act promotes electronic governance by enabling the government to issue
notifications, licenses, and permits electronically, recognizing electronic documents and digital
signatures as legally valid, and ensuring secure electronic transactions through digital certificates
and encryption standards.

Q 19: Why is it important to address gender stereotypes in technology education?

Answer: Addressing gender stereotypes in technology education promotes inclusivity, encourages


more girls and women to pursue careers in STEM fields, and fosters diverse perspectives in
innovation and problem-solving.

Q 20: How can educators accommodate students with disabilities in computer-based learning
environments?

Answer: Educators can accommodate students with disabilities by providing accessible digital
resources and technologies, using assistive technologies such as screen readers and speech
recognition software, ensuring physical accessibility to computer labs and devices, and offering
personalized support and accommodations based on individual needs.

Long Questions

Q 1) In today's digital age, maintaining a positive digital footprint is crucial for personal and
professional success. Can you discuss the steps one should take to audit and manage their
digital footprint effectively, and provide examples of the potential impacts of a poorly
managed digital footprint on career opportunities?

Answer: To audit and manage a digital footprint effectively, individuals should start by searching
their name on search engines to identify publicly available information. This includes social media
profiles, blogs, articles, and any other online activity. Reviewing and cleaning up social media profiles
is essential; this involves deleting or privatizing old posts that may be inappropriate or
unprofessional. Setting strict privacy settings on social media platforms to control who can view
personal information is also crucial.

Individuals should consider what they share online, ensuring it's positive and professional. Creating
and maintaining a LinkedIn profile and other professional networking sites can enhance one's digital
footprint. Additionally, contributing positively to online communities, such as forums related to one's
field, and publishing professional content, such as blog posts or articles, can further build a positive
online presence.

A poorly managed digital footprint can significantly impact career opportunities. For example,
unprofessional or controversial posts can deter potential employers who often search candidates'
96
online presence before making hiring decisions. Negative or inappropriate content can damage one's
reputation, leading to missed job opportunities or professional relationships. Conversely, a well-
managed digital footprint can enhance credibility and present one as a knowledgeable and
responsible individual, leading to better career prospects and professional networking opportunities.

Q 2) Cyber trolling can significantly impact individuals and online communities. Explain the
psychological effects of cyber trolling on victims and discuss effective strategies that
individuals and online platforms can implement to combat cyber trolling.

Answer: Cyber trolling involves sending hostile, offensive, or inflammatory messages to provoke or
harass individuals online. The psychological effects on victims can be severe, including stress,
anxiety, depression, and decreased self-esteem. Victims may also experience feelings of isolation and
helplessness, impacting their personal and professional lives.

To combat cyber trolling, individuals can use several strategies. First, they should avoid engaging
with trolls, as responding can escalate the situation. Instead, they can use blocking and reporting
features on social media platforms to remove and report trolls. Maintaining a support network of
friends and family can provide emotional support and advice.

Online platforms play a crucial role in addressing cyber trolling. Implementing strict community
guidelines that prohibit abusive behavior is essential. Platforms can use automated tools to detect
and filter out offensive content and provide users with easy ways to report harassment. Ensuring
timely and appropriate actions against reported trolls, such as account suspension or banning, can
deter such behavior. Educating users about the impact of cyber trolling and promoting a positive
online culture can further help in creating a safer online environment.

Q 3) Cyber crime is a growing threat to individuals and organizations. Describe the various
types of cyber crimes and discuss a high-profile cyber crime case, detailing the attack method,
impact, and the response by the affected organization.

Answer: Cyber crimes encompass a range of illegal activities conducted through digital means.
Common types include phishing (fraudulent attempts to obtain sensitive information), hacking
(unauthorized access to computer systems), ransomware (encrypting data and demanding payment
for its release), identity theft (stealing personal information to commit fraud), and DDoS attacks
(disrupting services by overwhelming servers with traffic).

A high-profile cyber crime case is the 2017 Equifax data breach. Attackers exploited a vulnerability in
the company's web application to access sensitive data, including Social Security numbers, birth
dates, and addresses of approximately 147 million individuals. The impact was significant, leading to
identity theft and financial fraud risks for affected individuals. Equifax's response included offering
free credit monitoring services to victims, investing in improved security measures, and facing legal
and financial repercussions, including fines and settlements. The case highlighted the importance of
timely security updates and robust data protection practices.

Q 4) In the context of increasing cyber threats, discuss the importance of cyber safety
education for individuals and organizations. Provide examples of effective cyber safety
practices that can be adopted to protect against online threats.

Answer: Cyber safety education is crucial for raising awareness about online threats and promoting
safe behaviors to protect personal and organizational data. Educated individuals are less likely to fall

97
victim to phishing scams, malware, and other cyber attacks, while organizations can enhance their
overall security posture.

Effective cyber safety practices include using strong, unique passwords for different accounts and
enabling two-factor authentication to add an extra layer of security. Regularly updating software and
operating systems to patch vulnerabilities is essential. Individuals should be cautious about sharing
personal information online and verify the legitimacy of websites and emails before providing
sensitive data.

For organizations, implementing comprehensive cybersecurity policies, conducting regular security


audits, and providing ongoing training to employees on recognizing and responding to cyber threats
are effective practices. Additionally, using advanced security technologies such as firewalls, intrusion
detection systems, and endpoint protection can help safeguard against cyber attacks.

Q 5) Malware poses a significant risk to computer systems and data integrity. Explain the
different types of malware and describe a real-world example of a malware attack, including
how it was detected, the damage caused, and the remediation steps taken.

Answer: Malware includes various malicious software types, such as viruses (self-replicating
programs that infect files), worms (self-replicating programs that spread across networks),
ransomware (encrypts data and demands ransom), spyware (secretly monitors user activity), and
trojans (disguised as legitimate software to gain access).

A real-world example is the WannaCry ransomware attack in 2017. It exploited a vulnerability in


Windows operating systems, spreading rapidly and encrypting files on infected computers. The
attack caused widespread disruption, affecting hospitals, businesses, and government agencies
worldwide. Detection occurred through reports of encrypted files and ransom demands.

The damage included significant operational disruptions, data loss, and financial losses due to
ransom payments and recovery efforts. Remediation steps involved applying security patches to
close the exploited vulnerability, restoring data from backups, and implementing improved
cybersecurity measures to prevent future attacks. The attack underscored the importance of timely
software updates and robust data backup practices.

Case Study Questions

Q 1) Sarah is a college student who regularly posts updates about her personal life on social
media. Recently, she discovered that potential employers have been viewing her social media
profiles during job interviews. How can Sarah manage her digital footprint to enhance her
professional image?

Answer: Sarah can manage her digital footprint by adjusting her privacy settings on social media
platforms to limit who can view her posts. She should also review and delete any content that may be
perceived negatively by employers. Additionally, she can create a professional online presence by
sharing relevant achievements and interests related to her career goals, which can overshadow less
professional content.

Q 2) Tom is participating in an online discussion forum where he disagrees with another


member's viewpoint. How should Tom express his disagreement respectfully and contribute
positively to the discussion?

98
Answer: Tom should express his disagreement respectfully by focusing on the content of the
discussion rather than attacking the person's character. He can start by acknowledging the valid
points made by the other member before presenting his counterarguments with supporting evidence
or examples. It's important for Tom to use polite language, avoid personal attacks, and be open to
considering different perspectives to maintain a constructive dialogue.

Q 3) Emma runs a popular blog where she frequently receives derogatory comments and
personal attacks from anonymous users. How can Emma effectively deal with cyber trolls
while maintaining a positive online presence?

Answer: Emma can effectively deal with cyber trolls by implementing comment moderation on her
blog to filter out offensive or inappropriate comments. She should establish clear community
guidelines that discourage trolling behavior and encourage constructive feedback. Emma can also
empower her audience to report abusive comments and consider blocking persistent offenders to
maintain a safe and supportive online environment.

Q 4) Mark works for a financial services company that recently experienced a data breach
compromising customer information. How should Mark and his company respond to mitigate
the impact of the breach and ensure data protection in the future?

Answer: Mark and his company should respond to the data breach by immediately notifying affected
customers and regulatory authorities as required by data protection laws. They should conduct a
thorough investigation to determine the cause of the breach and implement enhanced security
measures such as encryption, multi-factor authentication, and regular security audits. Mark should
also provide affected customers with support and resources to protect their identities and financial
information.

Q 5) Laura's online banking account was hacked, and unauthorized transactions were made
using her credit card information. How should Laura respond to this cyber crime incident to
minimize financial loss and prevent future attacks?

Answer: Laura should respond to the cyber crime incident by immediately contacting her bank to
report the unauthorized transactions and freeze her account if necessary. She should also change her
online banking passwords and monitor her financial statements for any further suspicious activity.
Laura should file a police report and keep records of all communications with her bank and law
enforcement for documentation purposes. To prevent future attacks, she should enable two-factor
authentication on her accounts and remain vigilant about phishing scams and malware threats.

Q 6) James received an email with an attachment from an unknown sender claiming to be a


job offer. How should James handle this situation to ensure his cyber safety?

Answer: James should handle the situation by not opening the email attachment or clicking on any
links within the email, as it could potentially contain malware or phishing attempts. He should delete
the email immediately and mark it as spam. James should verify job offers through official channels
or directly contact the company's HR department using verified contact information to confirm the
legitimacy of the email. Practicing caution and skepticism with unsolicited emails can help James
protect his personal information and avoid falling victim to cyber threats.

Q 7) Maria's computer suddenly started running slower than usual, and she noticed
unexpected pop-up windows appearing on her screen. What steps should Maria take to
identify and remove malware from her computer?
99
Answer: Maria should first disconnect her computer from the internet to prevent further damage and
then run a full system scan using reputable antivirus software. She should follow the software's
instructions to quarantine or remove any detected malware. Maria should also update her operating
system and software applications to their latest versions, as updates often include security patches
that can protect against known vulnerabilities exploited by malware. Regularly backing up important
files can help Maria recover her data in case of a malware attack.

Q 8) David's company recently upgraded its office computers and is unsure how to
responsibly dispose of the old equipment. What steps should David take to ensure proper e-
waste management?

Answer: David should ensure proper e-waste management by partnering with certified e-waste
recycling vendors that adhere to environmental regulations and ethical recycling practices. He
should inquire about the vendor's recycling processes to ensure that electronic components are
properly dismantled, recycled, or disposed of in an environmentally friendly manner. David can also
explore options for refurbishing or donating functional equipment to charitable organizations or
schools, promoting sustainability and reducing electronic waste generation.

Q 9) Sarah operates an e-commerce website that collects customer data for processing orders.
What legal obligations does Sarah have under the Information Technology Act regarding data
protection and privacy?

Answer: Sarah has legal obligations under the Information Technology Act to protect customer data
by implementing reasonable security practices and procedures to safeguard sensitive information
from unauthorized access, disclosure, or misuse. She should obtain customer consent before
collecting personal data and clearly communicate her privacy policy detailing how customer
information will be used, stored, and protected. Sarah should also comply with data breach
notification requirements and cooperate with law enforcement authorities in case of cyber crime
incidents involving customer data.

Q 10) In a computer science class, Sarah notices that female students are less likely to
participate actively in coding exercises compared to male students. How can Sarah address
gender stereotypes and encourage equal participation among all students?

Answer: Sarah can address gender stereotypes by promoting an inclusive learning environment
where all students feel valued and encouraged to participate. She can incorporate diverse examples
and role models in her teaching materials to demonstrate that computer science is accessible and
relevant to everyone, regardless of gender. Sarah should actively encourage female students to share
their ideas and collaborate with peers, provide constructive feedback, and recognize their
achievements to boost confidence and engagement. By fostering a supportive classroom culture that
celebrates diversity and inclusivity, Sarah can help bridge gender gaps and empower all students to
succeed in computer science education.
**********************

100

You might also like