You are on page 1of 113

कें द्रीय विद्यालय क्षेत्रीय कायाालय अहमदाबाद

Kendriya Vidyalaya Sangathan Regional Office, Ahmedabad

Class XI
Computer Science(083)

Based on Latest CBSE Exam Pattern


for the Session 2022-2023

1
OUR PATRON

SMT SHRUTI BHARGAV


Deputy Commissioner,
KVS RO Ahmedabad

SMT VINITA SHARMA


Assistant Commissioner,
KVS RO Ahmedabad

2
SUBJECT CO-ORDINATION BY

SMT SUNITA GUPTA


Principal, KV No 1 AFS Jamnagar

CONTENT TEAM

SMT RAKHI JAIN PGT COMP KV NO.1, AFS, JAMANGAR


SH SATISH MAMNANI PGT COMP KV AFS , SAMANA
SMT RENU BAHETI PGT COMP KV SAC, AHMEDABAD
SMT SONIA CHOUDHARY PGT COMP KV NO.2 AHMEDABAD CANTT
SH RAHUL AWASTHI PGT COMP KV JUNAGADH
SH DHIREN K MESHVANIYA PGT COMP KV JETPUR

3
KENDRIYA VIDYALAYA SANGATHAN, AHMEDABAD REGION
SPLIT-UP OF SYLLABUS
SUB: COMPUTER SCIENCE (083)
CLASS - XI (NEW SYLLABUS)
Session 2022-23
DISTRIBUTION OF MARKS

UNIT UNIT THEORY Periods


NAME MARKS THEORY PRACTICAL

1 Computer System and Organization 10 10 10


2 Programming and Computational 45 80 60
Thinking-1
3 Society, Law and Ethics 15 20 --
TOTAL 70 110 70
MONTH- WISE DISTRIBUTION
Month Topics to be covered Th. Pr.
Unit I: Computer Systems and Organisation 15 10
• Basic computer organisation: Basic Computer Organisation: Introduction to computer
system, hardware, software, input device, output device, CPU, memory (primary, cache
and secondary), units of memory (Bit, Byte, KB, MB, GB, TB, PB)
• Types of software: system software (operating systems, system utilities, device drivers),
programming tools and language translators (assembler, compiler & interpreter),
application software
• Operating system (OS): functions of operating system, OS user interface
• Boolean logic: NOT, AND, OR, NAND, NOR, XOR, truth table, De Morgan’s laws and logic
JULY

circuits
• Number system: Binary, Octal, Decimal and Hexadecimal number system; conversion
between number systems.
• Encoding schemes: ASCII, ISCII and UNICODE (UTF8, UTF32)
Unit II: Computational Thinking and Programming - 1
• Introduction to problem solving: Steps for problem solving (analysing the problem,
developing an algorithm, coding, testing and
debugging). representation of algorithms using flow chart and pseudo code,
decomposition

4
• Familiarization with the basics of Python programming: Introduction to Python, features 15 15
of Python, executing a simple "hello world" program, execution modes: interactive mode
and script mode, Python character set, Python tokens (keyword, identifier, literal,
operator, punctuator), variables, concept of l-value and r-value, use of comments features
of Python, Python Character Set, Token & Identifiers, Keywords, Literals,
Delimiters, Operators.
• Knowledge of data types: number (integer, floating-point, complex), boolean, sequence
(string, list, tuple), none, mapping (dictionary), mutable and immutable data types
• Operators: arithmetic operators, relational operators, logical operators, assignment
operator, augmented assignment operators, identity operators (is, is not), membership
AUGUST
operators (in, not in)

• Expressions, statement, type conversion & input/output: precedence of operators, 20 15


expression, evaluation of expression, python statement, type conversion (explicit &
implicit conversion), accepting data as input from the console and displaying output
SEPT
• Errors: syntax errors, logical errors, runtime errors
• Flow of control: introduction, use of indentation, sequential flow, conditional and
iterative flow control
• Conditional statements: if, if-else, if-elif-else, flowcharts, simple programs:
e.g.: absolute value, sort 3 numbers and divisibility of a number
• Iterative statements: for loop, range function, while loop, flowcharts, break and
continue statements, nested loops, suggested programs:
generating pattern, summation of series, finding the factorial of a positive number
etc
• Strings: introduction, indexing, string operations (concatenation, repetition,
membership & slicing), traversing a string using loops, builtin functions: len(),
capitalize(), title(), lower(), upper(), count(), find(), index(), endswith(), startswith(),
isalnum(), isalpha(), isdigit(), islower(), isupper(), isspace(), lstrip(), rstrip(), strip(),
replace(), join(), partition(), split()

OCT • Lists: introduction, indexing, list operations (concatenation, repetition, membership &
slicing), traversing a list using loops, built-in functions: 15 10
len(), list(), append(), extend(), insert(), count(), index(), remove(),
pop(), reverse(), sort(), sorted(), min(), max(), sum(); nested lists, suggested
programs: finding the maximum, minimum, mean of numeric values stored in a list;
linear search on list of numbers and counting the frequency of elements in a list
• Tuples: introduction, indexing, tuple operations (concatenation, repetition,
membership & slicing), built-in functions: len(), tuple(), count(), index(), sorted(),
min(), max(), sum(); tuple assignment, nested tuple, suggested programs: finding
the minimum, maximum, mean of values stored in a tuple; linear search on a tuple of
numbers, counting the frequency of elements in a tuple

NOV • HALF YEARLY EXAMINATION

• Dictionary: introduction, accessing items in a dictionary using keys, mutability of 15 15


dictionary (adding a new item, modifying an existing item), traversing a dictionary,
built-in functions: len(), dict(), keys(), values(), items(), get(), update(), del(), clear(),
fromkeys(), copy(), pop(), popitem(), setdefault(), max(), min(), count(), sorted(),

5
copy(); suggested programs : count the number of times a character appears in a
given string using a dictionary, create a dictionary with names of employees, their
salary and access them

DEC • Sorting techniques: Bubble and Insertion sort 10 5


• Introduction to Python modules: Importing module using 'import ' and using from
statement, Importing math module (pi, e, sqrt, ceil, floor, pow, fabs, sin, cos, tan);
random module (random, randint, randrange), statistics module (mean, median,
mode)
Unit III: Society, Law and Ethics
• Digital Footprints
• Digital society and Netizen: net etiquettes, communication etiquettes, social media
etiquettes
• Data protection: Intellectual Property Right (copyright, patent, trademark), violation of
IPR (plagiarism, copyright infringement, trademark infringement), open source
softwares and licensing
(Creative Commons, GPL and Apache)
JAN • Cyber-crime: definition, hacking, eavesdropping, phishing and fraud emails, ransomware, 20
preventing cyber crime
• Cyber safety: safely browsing the web, identity protection, confidentiality, cyber trolls
and bullying
• Safely accessing web sites: malware, viruses, trojans, adware
• E-waste management: proper disposal of used electronic gadgets
• Indian Information Technology Act (IT Act)
• Technology & Society: Gender and disability issues while teaching and using computers

FEB • Revision, Project work, Session Ending Practical Examination

PRACTICAL WORK
S.No. UNIT NAME MARKS
1 Lab Test (12 marks)
Python program (60% logic + 20% documentation + 20% code quality) 12
2 Report File + viva (10 marks)
Report file: Minimum 20 Python programs 7
Viva voce (based on the report file) 3
3 Project (that uses most of the concepts that have been learnt) Project 8
may be allotted to group of 2-3 students.

6
Suggested Practical List Python Programming
• Input a welcome message and display it.
• Input two numbers and display the larger / smaller number.
• Input three numbers and display the largest / smallest number.
• Generate the following patterns using nested loop.
Pattern-1 Pattern-2 Pattern-3

* 12345 A
** 1234 AB
*** 123 ABC
**** 12 ABCD
***** 1 ABCDE

• Write a program to input the value of x and n and print the sum of the following series:
 𝟏+𝒙+𝒙𝟐 +𝒙𝟑 …+𝒙𝒏
 𝟏−𝒙+𝒙𝟐 −𝒙𝟑 …+(−𝟏)𝒏𝒙𝒏

 𝒙− 𝒙𝟐 + 𝒙𝟑 − 𝒙𝟒…+(−𝟏)𝒏 𝒙𝒏
𝟐! 𝟑! 𝟒! 𝒏!

 𝒙− 𝒙𝟐 + 𝒙𝟑 − 𝒙𝟒…+(−𝟏)𝒏 𝒙𝒏
𝟐 𝟑 𝟒 𝒏

• 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 of elements, sort in ascending/descending order using Bubble/Insertion sort.
• Input a list/tuple of elements, search for a given element in the list/tuple.
• Input a list of numbers and find the smallest and largest number from the list.
• Create a dictionary with the roll number, name and marks of n students in a class and display the names of
students who have scored marks above 75.

ooOoo

7
CLASS : XI
SUB : Computer Science ( 083 )
Session – 2022-23
Unit I: Computer Systems and Organization

Computer : A computer is an electronic device that can be programmed to accept data


(input), process it and generate result (output). A computer along with additional hardware
and software together is called a computer system.
A computer system primarily comprises a central processing unit (CPU), memory,
input/output devices and storage devices. All these components function together as a
single unit to deliver the desired output. A computer system comes in various forms and
sizes. It can vary from a high-end server to personal desktop, laptop, tablet computer, or a
smart phone.

Memory : A computer system needs memory to store the data and instructions for
processing. Whenever we talk about the ‘memory’ of a computer system, we usually talk
about the main or primary memory. The secondary memory (also called storage device) is
used to store data, instruction sand results permanently for future use.

Software : The sole purpose of a software is to make the computer hardware useful and
operational. A software knows how to make different hardware components of a computer
work and communicate with each other as well as with the end-user. We cannot instruct
the hardware of a computer directly. Software acts as an interface between human users
and the hardware. Depending on the mode of interaction with hardware and functions to be
performed, the software can be broadly classified into three categories viz.
(i) System software, (ii) Programming tools and (iii) Application software.

Operating System : An operating system (OS) can be considered to be are source


manager which manages all the resources of a computer, i.e., its hardware including CPU,
RAM, Disk, Network and other input-output devices. It also controls various application
software and device drivers, manages system security and handles access by different
users. It is the most important system software. Examples of popular OS are Windows,
Linux, Android, Macintosh and so on.
8
Number Systems :
Till now, we have learnt that each key (representing character, special symbol, function
keys, etc.) of the keyboard is internally mapped to an ASCII code following an encoding
scheme. This encoded value is further converted to its equivalent binary representation so
that the computer can understand it. The code for character “A” belongs to the decimal
number system and its equivalent binary value belongs to the binary number system. A
number system is a method to represent (write) numbers. Every number system has a set
of unique characters or literals. The count of these literals is called the radix or base of the
number system. The four different number systems used in the context of computer are
shown in table.

9
Questions No 1 to 10 Short Answer Type Question- 1 Mark
1. CPU has sub components namely Control Unit, registers and __________
2. _________ converts a high level language to machine code & execute it line by line.
3. Write full form of EEPROM.
4. ASCII stands for __________________
5. Storage of 2 KB means the following number of bytes:
6. Name the encoding scheme that could represent characters of all the known languages.
7. Which gate gives high output when odd number of inputs are high ?
8. State both DeMorgan’s Laws.
9. 1 TB = ___________ MB
10. Full form SRAM is ?

Questions ( 11 to 20 ) Short Long Answer Type Question- 2 Marks


11. Write and define different types of software with example.

12. What is Operating System? Write its two functions

13. Convert the following number systems :

(125)10 = ( ? )16 = ( ? )8
14. Write the equivalent Boolean expression for the following logic circuit.

15. Write equivalent character for given ASCII (Ordinal) values:

67 79 86 73 68

16. Draw logic circuit diagram for the following Boolean expression:

𝑌 = 𝑃 𝑄̅ + 𝑅

17. Expand the following terms:

10
(i) GUI (ii) USB (iii) BIT (iv) CD

18. What is UTF-8? Explain.

19. Arrange the following in ascending order of memory capacity:

TB , Byte, KB, Nibble, PB, MB, GB

20. Drive the Boolean expression for the logic circuit shown below:

Questions ( 21 to 30 ) Long Answer Type Question - 3 Marks


21. What is the difference between RAM and ROM ?

22.Convert the following number system.

( 10011111 )2 = ( ? )16 = ( ? )10 = ( ? )8

23. Why are language processors used? List their types and explain.

24. Write De-Morgan’s laws and prove anyone law out of them using truth table.
25. Draw truth table for given Boolean expression:

𝐸 = 𝑋. 𝑌(𝑌. 𝑍 + 𝑍̅)

26. Draw the logic circuit diagram for the expression: X=AB'+B'C'+ABC

27. Write Idempotent law, Distribute law and Absorption law.

28. Functions and diagram of Computer Systems.

29. Advantages and disadvantages of computer.

30. Explain about secondary memory with example.

11
Marking Scheme
1 to 10 Short Answer - 1 Mark
1. ALU
2. Interpreter
3. Electrically Erasable Programmable Read Only Memory.
4. American Standard Code for Information Interchange
5. 2048
6. Unicode
7. XOR
8. (A+B)’=A’.B’ and (A.B)’=A’+B’
9. 1024 X 1024
10. Static Random Access Memory

11 to 20 Short Long Answer - 2 Marks

11. Operating system : It is the interface between user and computer system

Ex : Windows, Linux

Application Software : software intended for a specific task


Ex : MS Office, Photoshop
12. Operating System : It is the interface between user and computer system. It’s
provide suitable platform for other programs.

• Process management

• Memory management
13. (125)10 = ( 7D )16 = ( 175 )8
14. w.x’+y’.z
15. C O V I D
16.

12
17. (i) GUI : Graphical User Interface
(ii) USB : Universal Serial Bus
(iii) BIT : Binary Digit
(iv) CD : Compact Disk

18. UTF-8 is an encoding system which is used in UNICODE system. It is a type of multi-
byte encoding. It can use 1,2,3 or 4 Octets i.e. 8 bits, 16 bits, 24 bits or 32 bits depending
upon the requirement or size of the data.

19. Nibble—Byte—KB---MB---GB---TB---PB
20. C(A+B) + D

21 to 30 Long Answer - 3 Marks

21. Both RAM and ROM are parts of the primary memory
RAM refers to random access memory where both read and write operations can take
place. RAM is a volatile memory; its contents are lost when power is turned off. Types :
SRAM, DRAM.

ROM refers to read only memory where only read operation can take place. The ROM is a
non-volatile memory.
Types : PROM, EPROM, EEPROM

22. ( 10011111 )2 = ( 9F )16 = ( 159 )10 = ( 237 )8

23. Programs written in a high level language are required to be converted into a machine
language. This task is accomplished by the language processor. The types are – Assembler,
Interpreter, Compiler.

Compiler : Converts High Level Language into Low level language in one go.
Interpreter : Converts High level language into low level language line by line
Assembler : Converts Assembly language to machine language.

24. De-Morgan’s Law:


(i) (A + B)’ = A’ . B’
(ii) (A . B)’ = A’ + B’

13
Prove using truth table:
A B A+B (A+B)’ A’ B’ A’.B’
0 0 0 1 1 1 1
0 1 1 0 1 0 0
1 0 1 0 0 1 0
1 1 1 0 0 0 0

25. truth table for given Boolean expression:


𝐸 = 𝑋. 𝑌(𝑌. 𝑍 + 𝑍̅)

X Y Z X.Y Y.Z 𝐙̅ 𝐘. 𝐙 + 𝐙̅ 𝐗. 𝐘(𝐘. 𝐙 + 𝐙̅)


0 0 0 0 0 1 1 0
0 0 1 0 0 0 0 0
0 1 0 0 0 1 1 0
0 1 1 0 1 0 1 0
1 0 0 0 0 1 1 0
1 0 1 0 0 0 0 0
1 1 0 1 0 1 1 1
1 1 1 1 1 0 1 1

26. Draw the logic circuit diagram for the expression: X = AB' + B'C' + ABC

27. Idempotent law : X+X=X, XX=X


Distribute law : X( Y+Z) = XY + XZ
and Absorption law. : X +XY = X , X (X+Y) = X

14
28. There are four main functions of the computer system:
Input: The process of data feeding by the user (Data means raw facts and figures)
Process: The actual work done in computers
Output: The result of user’s task (It can be: On-screen (Soft Copy), On
Paper (Hard Copy) or On Air)
Storage: The process of saving data

29. Advantages of a Computer


Storage: the most significant advantage of a computer is its storage capacity. A
human brain cannot store everything as it tends to forget. Thus, with the help of a
computer, we can get stored information with a touch of a button.
Accuracy: a computer is never wrong. It is we who feed in the wrong information;
thus, if you want 100% accuracy in your work and want to calculate millions of data, a
computer can be beneficial. It gives error-free output without any chances of mistakes.
Easy to understand and easy to use– doing tough calculations becomes very easy
when you know the computer well. The results given by a computer are 100% true, and no
one can doubt its efficiency. Step by step data processing and step-by-step calculations
make one understand things in a much simpler way.
Speed: no one can match up to the speed of a computer. Speed is related to the
quantity of data, and the data is measured with a unit of time. As a computer is a fast
device, it can process data rapidly. The speed of a computer is unmatchable and is
measured in micro and nanoseconds.
Disadvantages of a Computer
Health issues: sitting and working on a chair, sofa, couch for long hours can lead to
health issues—pain in the shoulder, spinal cord pain, lower backache, and a lot more.
Generally, people bend forward and work on the computer. Thus, this leads to a wrong
sitting posture, further leading to health issues like slip discs, sciatica, and more.
Movement of the hands continuously leads to injury in the fingers in the long run.
Wasting time on unnecessary things

15
Higher dependency on electronic gadgets:

30. Secondary Memory : Primary memory has limited storage capacity and
is either volatile (RAM) or read-only (ROM). Thus, a computer system needs auxiliary or
secondary memory to permanently store the data or instructions for future use. The
secondary memory is non-volatile and has larger storage capacity than primary memory. It
is slower and cheaper than the main memory. But, it cannot be accessed directly by the
CPU. Contents of secondary storage need to be first brought into the main memory for the
CPU to access. Examples of secondary memory devices include Hard Disk Drive (HDD),
CD/DVD, Memory Card,
However, these days, there are secondary storage devices like SSD which support very fast
data transfer speed as compared to earlier HDDs. Also, data transfer between computers
have become easier and simple due to the availability of small-sized and portable flash or
pen drives.

16
UNIT – II COMPUTATIONAL THINKING AND PROGRAMMING – 1

Introduction to problem Solving

1 Analyzing the problem


It is important to clearly understand a problem before we begin to find the solution for it. If
we are not clear as to what is to be solved, we may end up developing a program which
may not solve our purpose. Thus, we need to read and analyze the problem statement
carefully in order to list the principal components of the problem and decide the core
functionalities that our solution should have. By analyzing a problem, we would be able to
figure out what are the inputs that our program should accept and the outputs that its
should produce.
2 Developing an Algorithm
It is essential to devise a solution before writing a program code for a given problem. The
solution is represented in natural language and is called an algorithm.
3 Coding
After finalizing the algorithm, we need to convert the algorithm into the format which can
be understood by the computer to generate the desired solution. Different high level
programming languages can be used for writing a program. It is equally important to
record the details of the coding procedures followed and documented the solution. This is
helpful when revisiting the programs at a later stage.
4 Testing and Debugging
The program created should be tested on various parameters. The program should meet
the requirements of the user. It must respond within the expected time. It should generate
correct output for all possible inputs.
In the presence of syntactical errors, no output will be obtained. In case the output
generated is incorrect, then the program should be checked for logical errors, if any.
Software industry follows standardized testing methods like unit or component testing,
integration testing, system testing, and acceptance testing while developing complex
applications. This is to ensure that the software meets all the business and technical
requirements and works as expected. The errors or defects found in the testing phases are
debugged or rectified and the program is again tested. This continues still all the errors are
removed from the program. Once the software application has been developed, tested and
delivered to the user, still problems in terms of functioning can come up and need to be
resolved from time to time. The maintenance of the solution, thus, involves fixing the
problems faced by the user, answering the queries of the user and even serving the
request for addition or modification of features.

An algorithm is defined as a step-by-step procedure designed to perform an operation


which will lead to the desired result, if followed correctly.
• Algorithms have a definite beginning and a definite end, and a finite number of steps.

17
• A good algorithm, which is precise, unique and finite, receives input and produces an
output.
• In order to write effective algorithms we need to identify the input, the process to be
followed and the desired output.
• A flowchart is a type of diagram that represents the algorithm graphically using boxes of
various kinds, in an order connected by arrows.
• An algorithm where all the steps are executed one after the other is said to execute in
sequence.
• Decision making involves selection of one of the alternatives based on outcome of a
condition.
• An algorithm may have a certain set of steps, which are repeating for a finite number of
times, such an algorithm is said to be iterative.
• There can be more than one approach to solve a problem and hence we can have more
than one algorithm for a particular problem.
• The choice of algorithm should be made on the basis of time and space complexity.

INTRODUCTION TO PYTHON

Introduction:
General-purpose Object Oriented Programming language, High-level language Developed in
late 1980 by Guido van Rossum at National Research Institute for Mathematics and
Computer Science in the Netherlands.
It is derived from programming languages such as ABC, Modula 3, small talk, Algol- 68.
It is an Open Source Scripting language. It is Case-sensitive language (Difference between
uppercase and lowercase letters). One of the official languages at Google.

Characteristics of Python:
• Interpreted: Python source code is compiled to byte code as a .py file, and this byte
code can be interpreted by the interpreter.
• Interactive Object Oriented Programming Language
• Easy & Simple
• Portable
• Scalable: Provides improved structure for supporting large programs.
• Integrated
• Expressive Language
Python Interpreter:
Names of some Python interpreters are:
• PyCharm
• Python IDLE
• The Python Bundle
• pyGUI
• Sublime Text etc.

18
There are two modes to use the python interpreter:
i. Interactive Mode
ii. Script Mode

i. Interactive Mode: Without passing python script file to the interpreter, directly
execute code to Python (Command line).
Example:
>>>6+3
Output: 9

Fig: Interactive Mode

Note: >>> is a command the python interpreter uses to indicate that it is ready. The
interactive mode is better when a programmer deals with small pieces of code.

To run a python file on command line:


exec(open(“C:\Python33\python programs\program1.py”).read( ))

ii. Script Mode: In this mode source code is stored in a file with the .py extension
and use the interpreter to execute the contents of the file. To execute the script
by the interpreter, you have to tell the interpreter the name of the file.
Example:
if you have a file name Demo.py , to run the script you have to follow the following
steps:
Step-1: Open the text editor i.e. Notepad
Step-2: Write the python code and save the file with .py file extension. (Default directory is
C:\Python33/Demo.py)
Step-3: Open IDLE ( Python GUI) python shell
Step-4: Click on file menu and select the open option
Step-5: Select the existing python file
Step-6: Now a window of python file will be opened
Step-7: Click on Run menu and the option Run Module.

Very Short Answer Type Questions (1 Marks)

1. A search algorithm takes ____ as an input and returns ____ as an output.


(A) Input, output
(B) Problem, solution
(C) Solution, problem
(D) None of the above
Answer:-- (B)
19
2. Method which uses a list of well defined instructions to complete a task starting from
a given initial state to end state is calls as :
(A) Program
(B) Flowchart
(C) Algorithm
(D) None of the above
Answer :- (C)

3. Flowcharts and algorithms are used for


(A) Better programming
(B) Easy testing and debugging
(C) Efficient coding
(D) All of the above
Answer :-- (D)

4. An algorithm represented in the form of programming language is ____


(A) Flowchart
(B) Pseudo code
(C) Program
(D) None of the above
Answer:--- (C) Program

5. Terminal symbol in flowchart indicates


(A) Processing
(B) End
(C) Input and output
(D) Decision
Answer:--- (B) End

6. Pictorial representation of an algorithm is


(A) Flowchart
(B) Data flow diagram
(C) Algorithm design
(D) Pseudo code
Answer:--- (A) Flowchart

7. The process of drawing a flowchart for an algorithm is called _______


(A) Performance
(B) Evaluation
(C) Algorithmic Representation
(D) Flowcharting
Answer:--- (D) Flowcharting

20
8. The following box denotes?

(A) Decision
(B) Initiation
(C) Initialization
(D) I/O
Answer:--- (A) Decision

9. Who developed the Python language?


(A) Zim Den
(B) Guido van Rossum
(C) NieneStom
(D) Wick van Rossum
(E) Answer:- (B)Guido van Rossum

10. In which year was the Python language developed?


(A) 1995
(B) 1972
(C) 1981
(D) 1989
Answer:- (D) 1989

Q.11 When was Python released?


Q.12 Who developed Python?
Q.13 Which two languages contributed to Python as a Programming Language?
Q.14 Is Python an Object Oriented Language?
Q.15 Python got its name from which show?
Q.16 Which of the following are not valid strings in Python?
(a)”Hello” (b) „Hello‟ (c)”Hello‟ (d) „Hello” (e) {Hello}
Q.17 Write Instructions in python to get the following result:
(Do it in both interactive mode and script mode)
I am a student of KV ONGC Chandkheda
I live in Chandkheda
And I love Chandkheda.

Q.18 What will be the output of the following code: Give reason for your output.
#This is a Sample Code
#to print some lines
#print(“Just like “)
print(“Hello! how are you?”)
print(“Are you from India?”)
21
Short Answer Type Questions (2 Marks)

Q.1 “Python is an interpreted language‟. What does it mean to you?


Q.2 What does a cross platform language mean?
Q.3 Python is a Free and Open Source language. What do you understand bythis feature?
Q.4 In how many ways, can you work in Python?
Q.5 What is the difference between Interactive mode and Script Mode in Python?
Q.6 What are the advantages of Python?
Q.7 What are the limitations of Python?
Q.8 What is None literal in Python?
Q.9 What is the error in following code: x, y =7 ?
Q.10 what will the following code do: a=b=18 ?

Long Answer Type Questions (3 Marks)

Q.1 Find the error in the following code:


(a) temp=90 (b) a=12 (c) print(“x=”x)
Print temp b=a+b
print( a And b)

Q.2 Find the error in the following code:


(a) a, b, c=2, 8, 4 (b) x = 23 (c) else = 21-4
print(a, b, c) 4=x
c, b, a = a, b, c
print(a; b; c)

Q.3 Find the error in the following code:


(a) y = x +5 (b) a=input(“Value: “) (c) print(x = y = 5)
print(x, y) b = a/2
print( a, b)

Q.4 What is the difference between a keyword and an identifier?


Q.5 What are literals in Python? How many types of Literals are allowed in Python?

Long Answer Type Questions (5 Marks)

Q1 Write an algorithm and flowchart that converts the input Celsius degree into its
Equivalent Fahrenheit degree. Use the formula: F = (9/5) *C+32.
Q2 Swapping of 2 variables without using temporary (or 3rd variable).

22
Ans1.

Ans 2

23
Knowledge of Data Types
A variable is like a container that stores values that you can access or change. A variable,
as the name suggest, has been derived from the word ‘vary’ which states that a variable
may vary during the execution of a program.
Through variables, we store the value in computer’s memory. Variable is a named unit of
storage. Every variable has a type and this type defines the format and behavior of the
variable.
Example: x=3
It will automatically assign a value 3 to variable named x, which is an integer.
A variable has three main components:
➢ Identity of the variable
➢ Type of the variable
➢ Value of the variable
A. Identity of the variable: It refers to the variable’s address in the memory. The
address of an object can be checked using the method id().
Syntax: id(object/variable)
Example: >>>x = 10
>>> id(x) Address of
1254668541 memory location
storing value 10

B. Type of the variable: By type, we refer to the data type of a variable. In Python, each
value is an object and has a data type associated with it. Data type of a value refers to the
value it is and the allowable operations on those values. A data type in Python can be
categorized as follows:
1. Number:
Number data type stores numerical values.
NOTE: One of the most distinguished feature of Python is that you don’t really have to
declare a numeric value to define its type. Python can easily differentiate one data type
from another when you write and run your statement.
(a) int(integer): Integer represents whole numbers without any fractional part. They can
be positive or negative and have unlimited size in Python. Example: -6, 468, 0, 4, -43.
(b) float(floating point number): Floating point numbers denote real numbers or
floating point values (i.e., numbers with fractional part). Example: 3.14, 565.34, 0.76, 4.0
(c) Complex Numbers: Complex numbers in Python are made up of pairs of real and
imaginary numbers. They take the form ‘x + yj’ or ‘x + yJ’
Example: (i) >>> x = 2 + 5j
>>>print(x.real, x.imag)
2.0 5.0
(ii) >>> y = 4 – 2j
>>>print(y.real, y.imag)
4.0 -2.0

24
2. str(string):
A string is a sequence of characters that can be a combination of letters, numbers and
special symbols, enclosed within quotation marks, single, double, or triple (‘ ‘ or “ “ or ‘‘‘
’’’). These quotes are not part of the string.
Example: >>> str = “Hello Python”
>>> print(str)
Hello Python
3. bool(Boolean):
Boolean data type represents one of the two possible values, True or False. Any expression
which can be True or False has the data type bool.
Note: A Boolean True value is non-zero, non-null and non-empty.
Example: >>> bool_1 = 6>10
>>> print(bool_1)
False
4. None:
This is a special data type with a single value. It is used to signify the absence of
value/condition evaluating to False in a situation. It is represented by None.
Note: Python doesn’t display anything when we give a command to display the value of a
variable containing value as None. On the other hand, None will be displayed by printing
the value of the variable containing None using print() statement.
Example: >>>val1 = None
>>> val1
>>> print(val1)
None
5. List:
A list is a collection of values or an ordered sequence of values/items. The items in a list
can be of any type such as string, integers, float, objects or even a list.
Elements of a list are enclosed in square brackets [ ], separated by commas.
Example: >>> L = [10, 20, 30, 40, 50]
>>>print( L )
[10, 20, 30, 40, 50]
6. Tuple:
Tuple is an another sequence data type similar to the list. A tuple consists of a number of
values separated by commas. Unlike lists however, tuples are enclosed within parentheses.
Elements in a tuple need not be of the same type, they can be heterogeneous.
Example: >>> T = ( 10, 20, 30, 40, 50 )
>>>print( L )
( 10, 20, 30, 40, 50 )
7. Dictionary:
Python-dictionary is an unordered collection of items where each item is a key-value pair.
We can also refer to a dictionary as a mapping between a set of keys and set of values. The

25
items of a dictionary are enclosed within curly braces and items are separated by commas.
The key value pairs are separated by colon (:).
Example: D = { “Jan” : 31, “Feb” : 28, “Mar” : 31 }

Mutable and Immutable Types


Mutable data types: Data types where the value can be changed in place. Example:
dictionary, sets, lists etc.
Immutable data types: Data types where the values cannot be changed in place.
Example: integer, float, string, tuples etc.

Operators:
Used to perform specific mathematical or logical operations on values. The values that the
operators works on are called operands. Following are the types of operators:
1. Arithmetic Operator
2. Relational Operator
3. Assignment Operator
4. Logical operators
5. Membership Operator
6. Identity Operators
1. Arithmetic Operator
Operator Operation Description Example
+ Addition Adds two numbers >>>n1=5
>>>n2=4
>>>n1+n2
9
- Subtraction Subtract the operand on the right >>>n1=5
from the operand on the left >>>n2=4
>>>n1-n2
1
* Multiplication Multiplies the two values >>>n1=5
>>>n2=4
>>>n1*n2
20
/ Division Divides the operand on the left >>>n1=5
with the operand on the right >>>n2=2
>>>n1/n2
2.5
% Modulus Divides the operand on the left >>>n1=5
with the operand on the right and >>>n2=2
returns the remainder >>>n1%n2
1

26
// Floor Floor division. To find the integer >>>n1=5
Division part of the quotient when one >>>n2=2
number is divided by the other. >>>n1//n2
The result is always the largest 2
integer less than or equal to the
actual quotient.
** Exponent To raise a number to the power of >>>n1=5
another number. >>>n2=2
>>>n1 ** n2
25

2. Relational Operator
Operator Operation Description Example
== Equals to Compares two values. If both >>>n1=2
values are equal then returns True >>>n2=3
else returns False >>>n3=2
>>>n1==n2
False
>>>n1==n3
True

!= Not Equals to Compares two values. If both >>>n1!=n2


values are not equal then returns True
True else returns False >>>n1!=n3
False
> Greater Than If the value of the left operand is >>>n1>n2
greater than operand on the right False
side of operator then returns True >>>n2>n1
else return False True
< Less than If the value of the left operand is >>>n1<n2
smaller than operand on the right True
side of operator then returns True >>>n2<n1
else return False False
>= Greater than or If the value of the left operand is >>>n1>= n2
equal to greater than or equal to operand False
on the right side of operator then >>>n3 >= n1
returns True else return False True
<= Less than or If the value of the left operand is >>>n1<= n2
equal to smaller than operand on the right True
side of operator then returns True >>>n3 <= n1
else return False False

27
3. Assignment Operator

Operator Description Example (x=5, y=10)


= Assigns value from right side operand to left >>>z=x+y
side operand >>>z
15
+= Evaluates R-value and adds it to L-value. The >>>x+=2*y
final result is assigned to L-value. >>>x
25

-= Evaluates R-value and subtract it from L- >>>x-=2*y


value. The final result is assigned to L-value. >>>x
-15

*= Evaluates R-value and multiply it by L-value. >>>x*=2*y


The final result is assigned to L-value. >>>x
100

/= Evaluates R-value and divide the L-value with >>>x/=y


R-value. The final result is assigned to L- >>>x
value. 0.5

%= Evaluates R-value and divide the L-value with >>>x%=4


R-value. The remainder is assigned to L- >>>x
value. 1

//= Evaluates R-value and divide the L-value with >>>x//=4


R-value. The quotient is assigned to L-value. >>>x
1

**= Evaluate R-value and calculate 𝐿 − 𝑣𝑎𝑙𝑢𝑒 𝑅−𝑣𝑎𝑙𝑢𝑒 . >>>x**=4


The final result is assigned to L-value >>>x
625

A shorthand assignment operator (or compound assignment operator or an augmented


operator) is a combination of a binary operation and assignment.
Example : +=, -=, *=, /=, %=, //= and **=

28
4. Logical operators
Operators Description Example
and Combines two conditions and returns >>>n1=10
True if both conditions are True else >>>n2=20
returns False >>>n1==10 and n2==20
True
>>>n1==10 and n2==10
False

or Combines two conditions and returns >>>n1==10 or n2==50


True if any condition is True else returns True
False >>>n1==50 or n2==30
False
not Negates a condition and returns True if >>>not (n1==20)
the condition is False, otherwise returns True
False. >>>not (n1==10)
False

5. Membership Operator
Operators Description Example
in return True if value exists in the >>>L=[1,2,3]
sequence, else false. >>>1 in L
True
>>> 4 in L
False
not in return True if value does not exists in the >>>L=[1,2,3]
sequence, else false. >>>1 not in L
False
>>>4 not in L
True

6. Identity operator
Operator Description Example
is Evaluates to True if the variables on x is y, here result is True if
either side of the operators points to id(x) equals to id(y)
the same object and False otherwise
is not Evaluates to False if the variables on x is not y, here result is
either side of the operators points to True if id(x) is not equals to
the same object and True otherwise id(y)

Precedence of Operators:
The order in which the operators are executed in an expression is called the operator
precedence. Operator precedence of some common operators are given below:
29
Expressions: An expression is a combination of constants, variables and operators which
always evaluates to a value which is also an expression.
Example: x = 3 + 4 –y * 2

Statement:
An instruction which does something e.g. a=4 will assign a value 4 to variable a.

Evaluation of expressions:
The expressions are evaluated based on the precedence and associativity of the operators.

Input and Output:

Input :
To enter values from the user input( ) function is used. It accepts all type of values (either
a number, alphabet or special character) as string.
Syntax : variable = input([prompt])
Example: age=input(“Enter your age”)

30
The input( ) function takes exactly what is typed from the keyboard, converts it into a
string and assign it to a variable on left hand side of the assignment operator(=).

Output :
print() – used to output data to standard output device. The function print() evaluates the
expression before displaying it on screen.
Syntax : print(value)
Example: >>> L = [10, 20, 30, 40, 50]
>>>print( L )
[10, 20, 30, 40, 50]

Data type conversion :


The process of converting the value of one data type to another data type is called type
conversion.
There are two types of type conversions in Python:

1. Implicit Type Conversion : In this, Python automatically converts value from one data
type to another without user involvement.
Example: >>> N1=20 # N1 in integer
>>> N2 = 10.5 # N2 in float
>>> S = N1 + N2 # S will be float
>>> print(S)
output will be 30.5

2. Explicit Type Conversion: In this type of conversion, user converts the data type of an
object to required data type. A predefined functions like int(), float() or str( ) can be used.
Example: >>> N1=10 # N1 is integer
>>> N2=‘30‘ # N2 in string
>>> N3 = int(N2) # N3 will integer (N2 is converted to integer)
>>> print(N3) # 30 will be printed

Debugging :
The process of identifying and removing logical errors and runtime errors is called
debugging. Due to errors in program, it may not execute or generate wrong output. The
errors are of the following types:
1. Syntax Error
2. Logical Error
3. Runtime Error

1. Syntax Error:
Syntax errors are produced by Python when it is translating the source code into byte code.
They usually indicate that there is something wrong with the syntax of the program.

31
Example: Omitting the colon at the end of a for statement yields the somewhat redundant
message SyntaxError: invalid syntax.
Example 1: print(“Hello”) #syntactically correct
Example 2: print(“Hello” #syntax error due to right parenthesis is missing

2) Logical Error:
Logical errors are the most difficult to fix. They occur when the program runs without
crashing, but produces an incorrect result. The error is caused by a mistake in the
program's logic. You won't get an error message, because no syntax or runtime error has
occurred.
Example:
x = 10
y = 20
avg = x + y / 2
print(“Average of x and y = “, avg)
# this will give wrong average as y/2 will be calculated first instead of (x+y)/2.

3) Runtime Error :
Run time errors causes abnormal termination of program while it is executing. It occurs
when statement is correct syntactically, but interpreter cannot execute it.
Eg: a statement having division operation in program, if denominator value is zero then it
will give a runtime error “division by zero”.

Very Short Type Questions


1. What will the data type of the L:
L = {“Tuple” : “List” }
2. What is None data type?
3. What will be datatype of variable ‘c’ after executing following statements?
>>>a,b=5.25,10
>>>c=int(b/a)
4. What will be the output of the following?
X = ‘5’
Y = 10
print(X + Y)
5. What will the data type of bool_1
bool_1 = ‘True’
6. Solve the following expression:
(12+3) * 4 – 6/2
7. What is the difference between True and ‘True’?
8. What is list in Python?
9. What is Tuple in Python?
10. What is dictionary in Python?

32
Short Answer Type Questions :
11. What is debugging?
12. Write all logical operators in Python?
13. What are mutable and immutable data types in Python?
14. Explain the difference between tuple and list.
15. What is type casting and its type?
16. What are shorthand operators? Explain with the help of example.
17. What are identity operators? Explain with the help of an example.
18. How we can take input from user in Python?
19. Find the output of the following code:
X=4
Y=2
X+=Y+2
Y-=X+3
print(X, Y)
20. Convert the following expression into equivalent Python statements:
(i) z = 3abc + 4
𝑥+2
(ii) a = 𝑏−1
Long Answer Type Questions :
21. What do you understand by precedence of operators? What is the precedence of
arithmetic operators?
22. What is the difference between ‘=’ and ‘==’? Explain with the help of an example.
23. What is syntax error? Give one example.
24. What is logical error? Give one example.
25. What is runtime error? Give one example.
26. Solve the following expression:
(i) 12 * (3 % 4) //2 + 6
(ii) 12 % 3 ** 4//5 +6
27. What is type casting? Explain its types with the help of examples.
28. Find the output of the following.
P = 10
Q = 20
P * = Q//3
Q += P + Q ** 2
print(P, Q)
29. Write a program to input temperature in Celsius and convert it into Fahrenheit using
the formula:
F = C * 9 / 5 + 32
30. Write Python expression to represent the following situations:
(i) Add remainder of 8/3 to the product of 8 and 3
(ii) Find the square root of the sum of 8 and 43
(iii) Find the sum of square roots of 8 and 43.
33
Case Based Questions :

31. Ajit a student of class 11 wants to convert the temperature from Celsius to Fahrenheit.
He knows the formula of converting Celsius to Fahrenheit and has written a Python
program for the same. The formula for converting temperature is as follows:
9𝐶
F= +32
5
The program written by him is as follows:
C = input(“Enter temperature in Celsius”) # Line 1
F = 9 * C + 32 / 5 # Line 2
Print(“Temperature in Fahrenheit is = “, F) # Line 3

After running the program, he get an unexpected result. Help him correct the program by
answering the following questions.
(i) There is an error in line 1. Write the correct statement.
(ii) At line 2 Ajit has written wrong conversion of the formula of converting temperature
from Celsius to Fahrenheit. Write the correct code for the same.
(iii) After correcting errors at Line 1 and Line 2, Ajit is still getting error. Correct the error
and write the correct statement.
(iv) What will the output if the user input 37 at statement 1.
(v) Write a Python statement to convert temperature from Fahrenheit to Celsius.

Answers:
A1. Dictionary
A2. This is a special data type with a single value. It is used to signify the absence of
value/condition evaluating to False in a situation. It is represented by None.
A3. integer
A4. Error will be generated as string and integer cannot be added.
A5. String
A6. 57.0
A7. True is a Boolean value and a keyword while ‘True’ is a string value.
A8. A list is a collection of values or an ordered sequence of values/items. The items in a
list can be of any type such as string, integers, float, objects or even a list.
Elements of a list are enclosed in square brackets [ ], separated by commas.
Example: >>> L = [10, 20, 30, 40, 50]
A9. Tuple is another sequence data type similar to the list. A tuple consists of a number of
values separated by commas. Unlike lists however, tuples are enclosed within parentheses.
Elements in a tuple need not be of the same type, they can be heterogeneous.
Example: >>> T = ( 10, 20, 30, 40, 50 )
A10. Python-dictionary is an unordered collection of items where each item is a key-value
pair. We can also refer to a dictionary as a mapping between a set of keys and set of
values. The items of a dictionary are enclosed within curly braces and items are separated
by commas. The key value pairs are separated by colon (:).
34
Example: D = { “Jan” : 31, “Feb” : 28, “Mar” : 31 }
A11. The process of identifying and removing logical errors and runtime errors is called
debugging.
A12. There are three logical operators: and, or, not.
A13. Mutable data types: Data types where the value can be changed in place. Example:
dictionary, sets, lists etc.
Immutable data types: Data types where the values cannot be changed in place. Example:
integer, float, string, tuples etc.
A14. List and tuple are ordered collection of elements. Elements in list are enclosed in
square brackets [] while elements in tuple are enclosed in parentheses (). List is a mutable
data structure while tuple is a immutable data structure.
A15. The process of converting the value of one data type to another data type is called
type conversion or type casting.
There are two types of type conversions in Python:
1. Implicit Type Conversion
2. Explicit Type Conversion
A16. A shorthand assignment operator (or compound assignment operator or an
augmented operator) is a combination of a binary operation and assignment.
Example: +=, -=, *=, /=, %=, //= and **=
A17. Identity operators are used to check whether two variables are pointing to same
memory location or not. There are two identity operators: is and not is.
Operator Description Example
is Evaluates to True if the variables on x is y, here result is True
either side of the operators points to if id(x) equals to id(y)
the same object and False otherwise
is not Evaluates to False if the variables on x is not y, here result is
either side of the operators points to True if id(x) is not equals
the same object and True otherwise to id(y)

A18. To enter values from the user input( ) function used.


It accepts all type of values (either a number, alphabet or special character) as string.
Syntax : variable = input([prompt])
Example: age=input(“Enter your age”)
The input( ) function takes exactly what is typed from the keyboard, converts it into a
string and assign it to a variable on left hand side of the assignment operator(=).
A19. 8 -9
A20. (i) z = 3 * a * b * c + 4
(ii) a = (x + 2 ) / ( b – 1 )
A21. The order in which the operators are executed in an expression is called the operator
precedence. The precedence of Arithmetic operator is as follows:
**
*, /, //, %
+, -
35
A22. = is an assignment operator which is use to assign values to a variable. == is a
comparison operator used to compare two values for equality. If both values are equal it
return True and False otherwise.
A23. Syntax errors are produced by Python when it is translating the source code into byte
code. They usually indicate that there is something wrong with the syntax of the program.
Example: Omitting the colon at the end of a for statement yields the somewhat redundant
message SyntaxError: invalid syntax.
Example 1: print(“Hello”) #syntactically correct
Example 2: print(“Hello” #syntax error due to right parenthesis is missing

A24. Logical errors are the most difficult to fix. They occur when the program runs without
crashing, but produces an incorrect result. The error is caused by a mistake in the
program's logic . You won't get an error message, because no syntax or runtime error has
occurred.
Example:
x = 10
y = 20
avg = x + y / 2
print(“Average of x and y = “, avg)
# this will give wrong average as y/2 will be calculated first.

A25. Run time errors causes abnormal termination of program while it is executing. It
occurs when statement is correct syntactically, but interpreter cannot execute it.
Eg: a statement having division operation in program, if denominator value is zero then it
will give a runtime error “division by zero”
A26. (i) 24
(ii) 8
A27. The process of converting the value of one data type to another data type is called
type conversion.
There are two types of type conversions in Python:
1. Implicit Type Conversion: In this, Python automatically converts value from one data
type to another without user involvement.
Example: >>> N1=20 # N1 in integer
>>> N2 = 10.5 # N2 in float
>>> S = N1 + N2 # S will be float
>>> print(S)
output will be 30.5
2. Explicit Type Conversion: In this type of conversion, user converts the data type of an
object to required data type. A predefined functions like int(), float() or str( ) can be used.
Example: >>> N1=10 # N1 is integer
>>> N2=‘30‘ # N2 in string
>>> N3 = int(N2) # N3 will integer (N2 is converted to integer)

36
>>> print(N3) # 30 will be printed
A28. 60 480
A29. C = float(input(“Enter temperature in Celsius:”))
F = C * 9 / 5 + 32
print(“Temperature in Fahrenheit is =”, F)
A30. (i) 8 % 3 + 8 * 3
(ii) (8+43)**0.5
(iii) 8**0.5 + 43**0.5

A31. (i) C = float(input(“Enter temperature in Celsius”))


(ii) F = C * 9 / 5 + 32
(iii) print(“Temperature in Fahrenheit is =”, F)
(iv) 97.8
(v) (F+32)*5/9

FLOWOFCONTROL:
1. Decision Making and branching (Conditional Statement)
2. Looping or Iteration
3. Jump statements

DECISION MAKING & BRANCHING :

Decision making is about deciding the order of execution of statements based on certain
conditions. Decision structures evaluates multiple expressions which produce TRUE or
FALSE as outcome.
There are three types of conditions in python :
1. If statement
2. if-else statement
3. elif statement

37
1. if statement : It is a simple if statement. When condition is true, then code
which is associated with if statement will execute.
Example:
a=40
b=20
if a>b:
print(“a is greater than b”)
2. if – else statement:
When the condition is true, then code associated with if statement will execute,
otherwise code associated with else statement will execute.
Example:
a=10
b=20
if a>b:
print(“a is greater”)
else:
print(“b is greater”)

3. elif statement: It is short form of else-if statement. If the previous conditions were
not true, then do this condition". It is also known as nested if statement.

Example:
a=input(“Enter first number”)
b=input("Enter Second Number:")
if a>b:
print("a is greater")
elif a==b:
print("both numbers are equal")
else:
print("b is greater")

38
LOOPS IN PYTHON :
Loop: Executes a set of statements repeatedly until a particular condition is satisfied.

There are two types of loops in python:


While
Loops in loop
Python
for loop

1. while loop
2. for loop

1. while loop: With the while loop we can execute a set of statements as long as a
condition is true. It requires to define an indexing variable.
Example: To print table of number 2 :

i=2
while i<=20:
print(i)

i+=2
2. for loop: The for loop iterate over a given sequence (it may be list, tuple or string).

Note: The for loop does not require an indexing variable to set before hand, as the for command
itself allows for this.

primes = [2, 3, 5, 7]
for x in primes:
print(x)
39
The range() function:
It generates a list of numbers, which is generally used to iterate over with for loop. range()
function uses three types of parameters, which are:

• start: Starting number of the sequence.


• stop: Generate numbers upto, but not including last number.
• step: Difference between each number in the sequence.

• Python use range() function in three ways:

a. range(stop)

b. range(start,stop)

c. range(start,stop,step)

Note:
➢ All parameters must be integers.
➢ All parameters can be positive or negative.

a. range(stop): By default, It starts from 0 and increments by 1 and ends upto


stop, but not including stop value.
Example:

For x in range(4):
print(x)

Output:
0
1
2
3

b. range(start,stop) : It starts from the start value and upto stop, but not including
stop value.

Example:
for x in range(2,6):
print(x)

40
Output:
2
3
4
5

c. range(start, stop, step): Third parameter specifies to increment or decrement


the value by adding or subtracting the value.
Example:
for x in range (3,8,2) :

print(x)

Output:
3
5
7

One Mark question and answer


Sr no Question Ans
Q1 Can we write if/else into one line in python? a)
a) Yes
b) No
c) if/else not used in python
d) None of the above

Q2 Which one of the following is a valid Python if statement. a)


a) if a>=2 :
b) if (a >= 2)
c) if (a => 22)
d) if a >= 22

Q3 What keyword would you use to add an alternative condition to c)


an if statement?
a) else if
b) elseif
c) elif
d) None of the above

Q4 What will be the data type of the var in the below code snippet?

var = 10
print(type(var))
var = "Hello" a)
print(type(var))
41
a) int and str
b) int and int
c) str and str
d) float and str
Q5 How is a code block indicated in Python? b)
a) Brackets
b) Indentation
c) Key
d) None of the above
Q6 What will be the output of the following code snippet?

a = [1, 2, 3] d)
a = tuple(a)
a[0] = 2
print(a)

a) [1,2,3]
b) (1,2,3)
c) [2,2,3]
d) error
Q7 What will be the output of the following code snippet? d)

print(type(5 / 2))
print(type(5 // 2))

a) int and int


b) str and str
c) int and float
d) float and int
Q8 What will be the output of the following Python code? d)

x =['ab','cd']
forIin x:
i.upper()
print(x)

a) [‘ab’, ‘cd’]
b) [‘AB’, ‘CD’]
c) [None, None]
d) none of the mentioned

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


i=5 b)
while True:
if i%0O11 == 0:
break
print(i)
42
i += 1

a) 5 6 7 8 9 10
b) 5 6 7 8
c) 5 6
d) error
Q10 What will be the output of the following Python code? c)
i=1
while True:
if i%3 == 0:
break
print(i)
i+=1

a) 1 2
b) 1 2 3
c) error
d) none of the mentioned

Short Answer Type Question -2 marks

Q1) What are loops in python? Name the two types of loop.
Q2) What a range() function does? Give an example.
Q3) What will be the output of the following code?
for i in range(2):
print(i)
for i in range(4,6):
print(i)

Q4) What is the syntax of if-elif statement in Python?


Q5)Write a program to check whether a years is leap year or not.
Q6) Write a program to check a character is vowel or not.
Q7)What will be the output of the following Python code?
list1 = [3, 2, 5, 6, 0, 7, 9]
sum = 0
sum1 = 0
for elem in list1:
if (elem % 2 == 0):
sum = sum + elem
continue
if (elem % 3 == 0):
sum1 = sum1 + elem
print(sum , end=" ")
print(sum1)

43
Q8) Write a program to make the following pattern:

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

Q9) Write the difference between for and while loop?

Q10) Define indentation?

ANSWERS
Ans 1) A loop in Python is a control flow statement that is used to repeatedly execute a
group of statements as long as the condition is satisfied. The two types of loops are for and
While loop.
Ans 2) The Python range() function returns the sequence of the given number between
the given range.
Example:
for i in range(0,10,2):
print(i, end=" ")
print()

Ans3)
0
1
4
5
Ans 4)
Syntax of if-elif-else

if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
Ans 5)
year = int(input('Enter year : '))
if (year%4 == 0 and year%100 != 0) or (year%400 == 0) :
print(year, "is a leap year.")
else :
print(year, "is not a leap year.")
44
Ans 6)
vowels = ['a', 'e', 'i', 'o', 'u']
text = input("Enter a character: ")
if text in vowels:
print("It is a vowel")
else:
print("It is not a vowel")

Ans 7)8 12

Ans 8)
rows = 5
k=0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(end=" ")

while k!=(2*i-1):
print("* ", end="")
k += 1
k=0
print()
Ans 9)
For Loop While Loop
It is used when the number of iterations is It is used when the number of
known. iterations is not known.
In case of no condition, the loop is repeated In case of no condition, an error will
infinite times. be shown.
Initialization is not repeated. Initialization is repeated if carried out
during the stage of checking.
Statement of Iteration is written after Can be written at any place.
running.
Initialization can be in or out of the loop Initialization is always out of the
loop.
The nature of the increment is simple. The nature of the increment is
complex.
Used when initialization is simple. Used when initialization is complex.

Ans 10)
Indentation is basically the leading white space character added at the beginning of
statements to indicate a block of code.
Example:

if (a>b):
45
a=a+b #block1
b=b+c #block1
c=c*9 #block1
else:
a=a+1 #block2

Long Answer Type Question – 3 Marks

Q1) What is the difference between else and elif construct of if statement?
Q2) Find the output of the following program segments:
I. a = 10
while a > 2:
print (a)
a -= 2

II. for i in range (20, 30, 2):


print (i)

III. var = 7
while var > 0:
print (“current variable value: ” , var)
var = var – 1
if var == 3:
break
else:
if var == 6:
var = var – 1
continue
print (“Good bye!”)

Q 3) Sort 5 numbers (69 , 52, 2, 33, 96) in ascending order


Q 4) What will be the output of the following python code?
str1 = “learn python”
str2 = “”
str3 = “”
for x in str1:
if (x==”r” or x == “n” or x ==”p”):
str2 +=x
pass

if ( x==”r” or x==”e” or x==”a”):


str3 += x
print(str2,end=””)
print(str3)

46
Q5) Write a Python program to find the factorial of a positive number
Q6) What are the four elements of a while loop in Python?
Q7) What are endless loops ? Why do such loops occur? Give example.
Q8) Draw flowchart for displaying first 10 odd numbers.
Q9) What is a flowchart? How is it useful?
Q10) What is empty statement in Python? What is its need?

Answers

Ans 1) ‘else’ is used along with ‘if’ to define the alternative path if the condition
mentioned in the ‘if’ statement is incorrect. This means that only one statement
can be evaluated using if else statement.
If more than one statements need to be evaluated, ‘elif’ construct is used.
There is no limit on the number of ‘elif’ construct which should be used in a statement.
However, the conditions mentioned in each ‘elif’
construct should be mutually exclusive i.e. if one of the conditions in elif is correct,
it stops and doesn’t evaluate the rest.

Ans 2) i) 10

ii) 20
22
24
26
28
iii) current variable value : 7
current variable value : 5
Good bye !
current variable value : 4

Ans 3)

NumList = []
Number = int(input("Please enter the Total Number of List Elements: "))
for i in range(1, Number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
NumList.append(value)
NumList.sort()
print("Element After Sorting List in Ascending Order is : ", NumList)
47
Ans 4) rnpnear

Ans5) def factorial(n):


if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input a number to compute the factiorial : "))
print(factorial(n))

Ans6)The four elements of a while loop in Python are:

1. Initialization Expressions — It initializes the loop control variable and it is given outside the
while loop before the beginning of the loop.
2. Test Expression — If its truth value is true then the loop-body gets executed otherwise not.
3. The Body of the Loop — It is the set of statements that are executed repeatedly in loop.
4. Update Expressions — It updates the value of loop control variable and it is given inside the
while loop.

Ans 7)Endless loops are loops which don’t terminate for the condition never

becomes False. They occur because the variable in the condition is not

being updated correctly.

e.g.

k=5
while K > 0:
pass

while k > 0:
k += 1

Ans 8)
48
Ans 9)A flowchart is a pictorial representation of an algorithm. It uses boxes of different
shapes to represent different types of instructions. These boxes are connected with arrow
marks to indicate the flow of operations. It helps in:

1. Communication — The pictorial representation of the flowchart provides better


communication. It is easier for the programmer to explain the logic of a program.
2. Effective Analysis — It is a very useful technique, as flowchart is a pictorial
representation that helps the programmer to analyze the problem in detail.

Ans 10)In Python, an empty statement is pass statement. Its syntax is:

pass
When pass statement is encountered, Python does nothing and moves to next statement in the flow
of control. It is needed in those instances where the syntax of the language requires the presence
of a statement but where the logic of the program does not.

Explanation of output: 3 is starting value, 8 is stop value and 2 is step value. First
print 3 and increase it by 2, that is 5, again increase is by 2, that is 7. The output can’t
exceed stop-1 value that is 8 here. So, the output is 3,5,8.

Difference between range( ) and xrange():


S.
No. range( ) xrange()

Returns the generator object that can be used


1 Returns the list of numbers
to display numbers only by looping
The variable storing the range takes more
2 Variable storing the range takes less memory
memory
All the operations that can be applied on operations associated to list cannot be
3
the list can be used on it applied on it
4 Slow implementation Faster implementation
JUMP STATEMENTS:
There are two jump statements in python:
1. break
2. continue

1. break statement : With the break statement we can stop the loop even if it is true.
49
Example:
Inwhileloop in forloop
i=1 languages = ["java", "python", "c++"]
while forxin languages:
i<6:print(i) if x ==
ifi==3: "python":break
break print(x)
i+= 1
Output: Output:
1 java
2
3

Note: If the break statement appears in a nested loop, then it will terminate the very loop it is
in i.e. if the break statement is inside the inner loop then it will terminate the inner loop only
and the outer loop will continue as it is.

TOPIC -STRING

INTRODUCTION –
It is a collection of characters.
It is represented using single quotes or double quotes.
Ex:- ‘Hello’ or “Hello”

INDEXING –
String indexing in Python is zero-based: the first character in the string has index 0, the
next has index 1, and so on. The index of the last character will be the length of the string
minus one.
Ex:-
INDEX ->
0 1 2can be
The individual characters 3 accessed
4 5 6by index as follows:
>>> S="WELCOME"
>>>S[0]
'W'
>>>S[5]
'M'

STRING OPERATIONS –
a) Concatenation operator ( +) – The Concatenation operator adds or concat two strings.
ex:- s1=‘Welcome’
s2 = ‘All’
print(s1+s2)

50
=>Output :- WelcomeAll

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


operator when we have one string and one integer as
operands.

ex:- print(3 *’hi’) => hihihi


print(‘3’ *’3’) => error

c) Membership Operators :-
i) in
ex:- ‘a’ in ‘hello’ => False
‘e’ in ‘hello’ => True

# it returns either True/False

ii) not in
ex:- ‘a’ not in ‘hello’ => True
‘e’ not in ‘hello’ => False

# it returns either True/False


STRING SLICES-
String slice is a part of a string containing some contiguous characters from the string.
(With start and stop position)
Syntax:- s[m:n]

If s is a string, it will start from index m and will go till n-1.


Ex:-s = ‘welcome’

Positive Index 0 1 2 3 4 5 6

Negative Index -7 -6 -5 -4 -3 -2 -1

s [0:7] => ‘welcome’


s [ :7] => ‘welcome’
s[0:3] => ‘wel’
s [2:5] => ‘lco’
s[-6:-2] => ‘elco’
s[4:-1] => ‘om’

51
(String slicing With start, stop and step)
Ex:-s = ‘welcome’
s[m : n : o]
It will start with index m to n-1 printing every oth character.
Note#if no value is given for m, by default it will take it as 0
if no value is given for n, by default it will take it as length -1
if no value is given for o, by default it will take it as 1
Ex:-s [0 :6 :2] => ‘wlo’
It will print every 2nd character from index 0 to 5
Ex:-s [2 :6 :3] => ‘lm’
It will print every 3rd character from index 2 to 5
Ex:-s[2::] =>'lcome'
It will print every character from index 2 to n-1(5)

TRAVERSING A STRING –
Traversing means iterating through the elements of string, one character at a time.
Ex:-s=‘hello’
for x in s :
print(x,’*’,end=‘’)

Output :- h*e*l*l*o*

What if we remove end=‘ ’ ?


Ex:- s=‘hello’
for x in s :
print(x,’*’)
Output :- h*
e*
l*
l*
o*
BUILTIN FUNCTIONS –
General form to use string function :-

<string object>.<function name >( )

len( ) – It gives length of the string


ex:- s= ‘hello’
len(s) => 5

capitalize( ) - It capitalize first character of the string.


ex:- ‘hello’.capitalize( )
or s.capitalize( ) => ‘Hello’

52
title( ) – It return title case string.(capitalizes first character)
ex:- s='hello all'
s.title( ) => Hello All

lower( ) - it converts all the characters in the string in lowercase.


ex:- s = ‘HEllo’
s.lower( ) => ‘hello’

upper( ) - it converts all the characters in the string in uppercase.


ex:- s = ‘Hello’
s.upper( ) => ‘HELLO’

count(<char>) - it returns the total count of a given element in a string.


ex:- s = ‘Hello’
s.count(‘l’ ) => 2

find(sub[,start[,end]] ) - it returns the lowest index in the string where the


substring is found.
ex:- s = ‘hello how are you’
sub = ‘are’
s.find(sub) => 10
s.find(sub,12,16) => -1

# if the substring is not found in the range, it returns -1.

index(<char>) - it returns the index of a given element in a string.


ex:-s = ‘Hello’
s.index(‘e’ ) => 1

endswith(<char>) – It returns True if the string ends with the specified value,
otherwise False.
ex :- s = ‘Hello’
s.endswith('o') =>True
s.endswith('a') =>False

startswith(<char>) – It returns True if the string starts with the specified value,
otherwise False.
ex:- s = ‘Hello’
s.startswith('H') =>True
s.startswith('h') =>False #case sensitive

isalnum( ) - it returns true if the characters in the string are alphanumeric.


ex:- s = ‘hello123’
53
s.isalnum( ) => True
s = ‘hello’
s.isalnum( ) => True
s = ‘123’
s.isalnum( ) => True

isalpha( ) - it returns true if all the characters in the string are alphabets.
ex:- s = ‘hello’
s.isalpha( ) => True

isdigit( ) - it returns True if all the characters in the string are digits.
ex:- s = ‘123’
s.isdigit( ) => True

islower( ) - it returns True if all the characters in the string are in lowercase.
ex:- s = ‘Hello’
s.islower( ) => False

isupper( ) - it returns True if all the characters in the string are in uppercase.
ex:- s = ‘HELLO’
s.isupper( ) => True

isspace( ) - it returns true if all the characters in the string are space.
ex:- s = ‘ ’
s.isspace( ) => True

lstrip(<char> ) - it remove the leading characters.(from left hand side).


ex:- s = ‘Hello’
s.lstrip(‘H’ ) => ‘ello’
ex:- s = ‘ Hello’
s.lstrip( ) => ‘Hello’

rstrip(<char> ) - it remove the trailing characters. (from right hand side)


ex:- s = ‘Hello’
s.rstrip(‘o’ ) => ‘Hell’
ex:- s = ‘ Hello ’
s.rstrip( ) => ‘ Hello’

strip(<char>) – it removes specific character from leading and trailing position.


ex:- s='a nice gala'
s.strip('a') => ‘ nice gal’

replace( ) – it returns the string with replaced sub strings.


54
ex:- s='hello all'
s.replace(‘all’, ‘everybody’ ) => hello everybody

join( ) – It joins all items into one string.


ex:- s='Hello'
'*'.join(s) =>'H*e*l*l*o'
s.join('88') =>'8hello8'
s.join('888') =>'8hello8hello8'

partition( ) – it partition the string on first occurrence of substring.


ex:- s='hello all'
s.partition('a') => ('hello ', 'a', 'll')
s.partition(‘all’) => ('hello ', 'all', ‘ ‘)

split( ) – it returns list of strings as separate words.


ex:- s='hello all'
s.split( ) => [‘hello’, ‘all’ ]
---------------

QUESTIONS
VERY SHORT ANSWER TYPE QUESTIONS [1 mark]
1. What is a string in Python ?
Ans. It is a collection of characters enclosed in ‘ ‘ or “ “.
2. Identify valid string literals : ‘marks’’, ‘mark’, “mark”, “mark’.
Ans. ‘mark’, “mark”
3. What is the index value of first character of string in Python ?
Ans. 0
4. If A = “Hello” then what will be the value of A[1] ?
Ans. ‘e’
5. If s = ‘Delhi’, then what will be the output of s.isalpha( ) ?
Ans. True
6. If X[m:n:o] is used for string slicing in Python, what is the default
Value of o if no value is provided ?
Ans. 1
7. What does find ( ) function of string returnsif the substring is not found in the range?
Ans. -1.
8. If output of A.isspace( ) is True, what could be the reason for the same ?
And. It means, all the characters of string are space only.
9. If s= ‘hello’, find the value of len(s).
55
Ans. 5
10. Is 123 or ‘123’ same ?
Ans. No. 123 is a number & ‘123’ is a string.

SHORT ANSWER TYPE QUESTIONS [2 marks ]


1. What is a string in Python ?
Ans. It is a collection of characters. It is enclosed in single quotes ( ‘ ‘ ) or double quotes
(“ “ ). Ending and starting quotes must be same.
Ex : ‘Work’, “Hi”
2. Identify valid string literals : ‘marks’’, ‘123’, “L*”, “mark’.
Ans. ‘123’, “L*”
3. What do you mean by string traversing in Python ?
Ans. Traversing means iterating through the elements of string, one character at a time.
Ex:- s=‘hello’
for x in s :
print(x,’*’,end=‘’)

Output :- h*e*l*l*o*

4. If s= ‘Delhi’, then what will be the output of


i) s.islower( ) & ii) s.lower()?
Ans. i) False, ii) ‘delhi’
5. If X = ‘COMPUTER’, then what will be the output of the following?
i) X[2:4:2] ii) X[::]
Ans. i) ‘m’ ii) ‘COMPUTER’
6. If a=”WORLD”, then what will be the output of the following?
i) a.capitalize() ii) a.title()
Ans. i) ‘World’ ii) ‘Word’
7. What is the difference between partition( ) and split( ) function in Python ?
Ans. partition( ) – it partition the string on first occurrence of substring.
ex:- s='hello all'
s.partition('a') => ('hello ', 'a', 'll')
s.partition(‘all’) => ('hello ', 'all', ‘ ‘)

split( ) – it returns list of strings as splitted.


ex:- s='hello all'
s.split( ) => [‘hello’, ‘all’ ]

8. What is the purpose of index( ) ?


Ans. index(<char>) - it returns the index of a given element in a string.
ex:- s = ‘Hello’

56
s.index(‘e’ ) it will return => 1

9. What is 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

10. What will be the output of the following :


i) a=1 ii) a=’1’
b=2 b=’2’
print(a+b) print(a+b)
Ans. i) 3
ii) 12

LONG ANSWER TYPE QUESTIONS [3 marks ]

1. Define the following :


a) Concatenation operator b) Replication operator
Ans. a) Concatenation operator ( +) –
The Concatenation operator adds or concat two strings.
ex:- s1=‘Welcome’
s2 = ‘All’
print(s1+s2)

=>Output :- WelcomeAll

b) Replication/repetition operator (*) –


The multiplication operator acts as a replication operator when we have one string and
one integer as operands.
ex:- print(3 *’hi’) =>hihihi
print(‘3’ *’3’) => error

2. Differentiate between lstrip( ), rstrip( ) and strip using example.


Ans. lstrip(<char> ) - it remove the leading characters.(from LHS)
ex:- s = ‘Hello’
s.lstrip(‘H’ ) => ‘ello’

rstrip(<char> ) - it remove the trailing characters. (from RHS)


ex:- s = ‘Hello’
57
s.rstrip(‘o’ ) => ‘Hell’
strip(<char>) – it removes specific character from leading and trailing position.
ex:- s='a nice gala'
s.strip('a') => ‘ nice gal’
3. What would Python return when following expressions are evaluated?
Given a=”hello”, b = 15, c = 20, d = “12”
a) str(b) + str(c)
b) d + 10
c) d*3
Ans. a) 1520 b) error c) 121212

4. If s= ‘Middleeast’, then what will be the output of :


a) s[4:7]
b) s[::2]
c) s[5:-2]
Ans. a) ‘lee’ b) ‘mdles’ c) ‘eea'

5. If X = ‘COMPUTER’ and Y = ‘SCIENCE’ then what will be the output of the following?
a) ‘a’ not in X b) X +Y c) Y.replace(‘I’, ‘#’)
Ans. a) True b) ‘COMPUTERSCIENCE’ c) ‘SC#ENCE’
6. If a=”Skylight”, then what will be the output of the following?
a) a.startswith(‘s’) b)a.islower() c) a.endswith(‘t’)
Ans. a) False b) False c) True
7. Write a python code to give this output :
H #
E #
L #
L #
0 #

Ans. s='HELLO'
for x in s:
print(x,'#')

8. Program to concatenate two strings and convert every character in lowercase .


Ans. s1=input("Enter first string")
s2=input("Enter second string")
print("First string", s1)
print("Second string",s2)
s=s1+s2
print("String after concatenation -",s)
58
print("New string in lowercase-",s.lower( ))

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

output : - Enter string:Hello how are you


Enter character you want to count-- h
The count of h in string is 1

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 )

Output : - Enter any string – python


New string- nythop

VERY LONG ANSWER TYPE QUESTIONS [5 marks ]

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
count2=count2+1
print("The number of digits is:",count1)
print("The number of characters is:",count2)

2. If s= “Computer”, then what will be the output of the following :


a) s.upper()
b) s.lstrip('com')
c) s.endswith('t')
d) s.find('c',1,6)
e) s.count(‘u’)

59
Ans. a) ‘COMPUTER’
b) ‘puter’
c) False
d) -1
e) 1

continue statement : With the continue statement we can stop the current
iteration, and continue with the next iteration.

Example:
inwhileloop in forloop
i=0 languages = ["java", "python", "c++"]
while forxin languages:
i<6:i+= 1 if x ==
if i == "python":continue
3:contin print(x)
ue
print(i)
Output: Output:
1 java
2 c++
4
5
6

Loop else statement:


The else statement of a python loop executes when the loop terminates normally. The else
statement of the loop will not execute when the break statement terminates the loop.
The else clause of a loop appears at the same indentation as that of the loop keyword while or
for.
Syntax:
forloop whileloop

for <variable> in while <test


<sequence>:statement-1 condition>:state
statement-2 ment-
. 1statement-2
. .
else: .
statement(s) else:
statement(s)

60
Nested Loop:
A loop inside another loop is known as nested loop.
Syntax:
for<variable-name>in<sequence>:
for <variable-name> in
<sequence>:statement(s)
statement(s)

Example:
for i in range(1,4):
for j in range(1,i):
print("*", end=" ")
print("")
Programs related to Conditional, looping and jump statements
1. Write a program to check a number whether it is even or odd.
num=int (input("Enter the number:"))
if num%2==0:
print(num, " is even number")else:
print (num, "is odd number")

2. Write a program in python to check a number whether it is prime or not.


num=int(input("Enter the number:"))
for i in range(2,num):
if num%i == 0:
print(num, "is not prime number")
break;
else:
print(num, "is prime number")

3. Write a program to check a year whether it is leap year or not.


year=int(input("Enter the year:"))
if year%100==0 and year%400==0:
print("It is a leap year")
elif year%4==0:
print("It is a leap year")
else:
print("It is not leap year")
61
4. Write a program in python to convert °C to °F and vice versa.
a=int(input("Press 1 for C to F \n Press 2 for F to C \n"))
if a==1:
c=float(input("Enter the temperature in degree celcius:"))
f=(9/5)*c+32
print(c, "Celcius = ",f," Fahrenheit")
elif a==2:
f=float(input("Enter the temperature in Fahrenheit:"))
c=(f-32)*5/9
print(f, "Fahrenheit=", c, "Celcius")
else:
print("You entered wrong choice")

5. Write a program to check a number whether it is palindrome or not.


num=int(input("Enter a number : "))
n=num
res=0
while num>0:
rem=num%10
res=rem+res*10
num=num//10
if res==n:
print("Number is Palindrome")
else:
print("Number is not Palindrome")

6. A number is Armstrong number or not.


num=input("Enter a number : ")
length=len(num)
n=int(num)num=nsum=0whilen>0:
rem=n%10
sum=sum+rem**length
n=n//10
if num==sum:

print(num, "is armstrong number")

else:
print(num, "is not Armstrong number")

62
7. To check whether the number is perfect number or not
num=int(input("Enter a number : "))
sum=0
for i in range(1,num):
if(num%i==0):
sum=sum+i
if num==sum:
print(num, "is perfect number")
else:
print(num, "is not perfect number")

8. Write a program to print Fibonacci series.


n=int(input("How many numbers : "))
first=0
second=1
i=3
print(first, second, end=" ")
while i<=n:
third=first+second
print(third, end=" ")
first=second
second=third
i=i+1

9. To print a pattern using nested loops


for i in range(1,5): 1
for j in range(1,i+1): 1 2
1 2 3
print(j,"",end="")
1 2 3 4
print('\n')

63
List & Tuple
List :
Introduction :Lists are used to store multiple items in a single variable.

Elements of a list are put in square brackets separated by comma.

#Create a List:

a = [ ]# a blank list
My_list=list() # creating a list using list() function
b=[1,2,3,4,5] # here b is a integer list
thislist = ["apple", "banana", "cherry"] # list of fruits
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
Mix_List = ["abc", 34, True, 40, "male"] # list with mix data types
Indexing :List items are indexed, the first item has index [0], the second item has
index [1] etc.

>>> list3 = [100,23.5,'Hello']


>>> print(list3)
[100, 23.5, 'Hello']

#list4 is the list of lists called nested list


>>> list4 =[['Physics',101],['Chemistry',202],['Maths',303]]
>>> print(list4)
[['Physics', 101], ['Chemistry', 202],['Maths', 303]]

Python has a set of built-in methods that you can use on lists :

Sl Method Description
1. append() Adds an element at the end of the list
2. clear() Removes all the elements from the list
3. copy() Returns a copy of the list
4. count() Returns the number of elements with the specified value
5. extend() Add the elements of a list (or any iterable), to the end of
the current list
6. index() Returns the index of the first element with the specified value
7. insert() Adds an element at the specified position
8. pop() Removes the element at the specified position
9. remove() Removes the first item with the specified value
10. reverse() Reverses the order of the list
11. sort() Sorts the list

>>> # Practical on List Data types


>>> list1= [1,2,3,4,5,6]
>>> list2=['abc','def','xyz'] # here we declare two list
>>> list1.append(7) # to add 7 in the list1
64
>>> list1
[1, 2, 3, 4, 5, 6, 7]
>>> list2
['abc', 'def', 'xyz']
>>> list2.clear() # to clear all the elements of the list2 and make it empty
>>> list2
[]
>>> copy_list1=list1.copy() # here list1 copy
>>> list1
[1, 2, 3, 4, 5, 6, 7]
>>> copy_list1
[1, 2, 3, 4, 5, 6, 7]
>>> list1.count(1)
1
>>> t1=(8,9,10)
>>> list1=list1.extend(t1)
>>> list1
>>> list1
>>> list1=[1,2,3]
>>> list1
[1, 2, 3]
>>> list1.extend(t1)
>>> list1
[1, 2, 3, 8, 9, 10]
>>> # 7. insert() Adds an element at the specified position
>>> list1=[10,20,30,40,50]
>>> list1
[10, 20, 30, 40, 50]
>>> list1.insert(0,5) # to insert value 5 at index no 0
>>> list1
[5, 10, 20, 30, 40, 50]
>>> list1.insert(-1,60) # to insert value 60 at index no -1 (at last)
>>> list1
[5, 10, 20, 30, 40, 60, 50]
>>> # pop() Removes the element at the specified position
>>>list1.pop(0) # to Removes the element at the 0 index position
5
>>> list1
[10, 20, 30, 40, 60, 50]
>>>list1.pop(3) # to Removes the element at the 3 index position
40
>>> list1
[10, 20, 30, 60, 50]
>>> #remove() Removes the first item with the specified value
>>> list1.remove(30)
>>> list1
[10, 20, 60, 50]
>>> #reverse() Reverses the order of the list
>>> list1.reverse()
65
>>> list1
[50, 60, 20, 10]
>>> # sort() Sorts the list
>>> list1.sort()
>>> list1
[10, 20, 50, 60]

Nested list :
A list in a another list is called nested list :-
i.e. - list1 =[10,20,30, [40,50],60] # here value 40 & 50 are in nested list

Important Questions :-
01. Differentiate between
1.1 List and string
1.2 append() and extend() list methods
1.3 pop() and remove()
1.4 mutable and non mutable data types
1.5 reverse() and sort() method

Q2 Find the output:-


2.1 myList = [1,2,3,4,5,6,7,8,9,10]
del myList[3:]
print(myList)
2.2 myList = [1,2,3,4,5,6,7,8,9,10]
del myList[:5]
print(myList)
2.3myList = [1,2,3,4,5,6,7,8,9,10]
del myList[::2]
print(myList)
2.4

Q 3. The record of a student (Name, Roll No., Marks in five subjects and percentage of
marks) is stored in the following Record = ['Raman','A-36',[56,98,99,72,69], 78.8]
Write Python statements to retrieve the following information from the list stRecord.
a) Percentage of the student
b) Marks in the fifth subject
c) Maximum marks of the student
d) Roll no. of the student
e) Change the name of the student from ‘Raman’ to ‘Raghav’

Q 4 Write a program to find the number of times an element occurs in the list.
Q 5. Write a program to read a list of n integers and find their median.

66
Tuples:
Introduction :A tuple is an ordered sequence of elements of different data types, such as integer,
float, string, list or even a tuple. Elements of a tuple are enclosed in parenthesis (round brackets)
and are separated by commas.

for example :
>>> a = (1, ‘a’, 7, 6.5) # a is the tuple of mixed data type
>>> b = (2, 4, 6, 8, 10) # b is a tuple of only integers
>>> c = (“English”, “Hindi”, “Math”, “Science”) # c is a tuple of only string
>>> d = (2, 4, 7, [4, 5, 6]) # d is a tuple with list as an element

Incorrect way of assigning a Correct way of assigning a


single element single element

>>> a = (2) >>> a = (2,)

Verification : Verification :

>>> type(a) >>> type(a)


<class ‘int’> <class ‘tuple’>
Accessing Elements in a Tuple :
Elements of a tuple can be accessed in the same way as a list or string using indexing and slicing.
for example
>>> a = (‘C’ , ‘ O’ , ‘M’ , ‘P’ , ‘U’ , ‘T’ , ‘E’ , ‘R’)
ELEMENTS C O M P U T E R

POSITIVE INDEX VALUE 0 1 2 3 4 5 6 7

NEGATIVE INDEX VALUE -8 -7 -6 -5 -4 -3 -2 -1

Tuples in Python :
>>>a[4] # Output is U (fifth element of tuple)
>>>a[7] # Output is R (Eighth element of tuple)
>>>a[-1] # Output is R (last element of tuple or first element from right)
>>>a[9] # Output is IndexError: tuple index out of range
Tuple is Immutable :
Tuple is an immutable data type. It means that the elements of a tuple cannot be changed
after it has been created. for example :
>>> a = (‘C’ , ‘ O’ , ‘M’ , ‘P’ , ‘U’ , ‘T’ , ‘E’ , ‘R’)
>>>a[2] = ‘S’
TypeError: ‘tuple’ object does not support item assignment.

Difference between List and Tuple :


LIST TUPLE

67
It is mutable data type. It is an immutable data type.

Elements are enclosed in Square brackets ie[ ] Elements are enclosed in Parenthesis. ie( )

Iterating through a list is slower as compared Iterating through a tuple is faster as compared
to a tuple to a list

Tuples in Python

Tuple Operations : Various operations of tuple are done by various operators like
Operation
Description Example
Name

>>>t1 = (1, 2, 3)
>>>t2 = (8, 9, 11)
>>>t1+t2

OUTPUT :
(1, 2, 3, 8, 9, 11)
(#concatenates two tuples)

>>>t1 = (1, 2, 3)
Joining of two or more tuples is >>>t2 = (8, 9, 11)
called concatenation >>>t3 = t1+t2
(#Created new tuple)
Concatenation (+)
OUTPUT :
Python allows us to join tuples (1, 2, 3, 8, 9, 11)
using concatenation operator (+).
Concatenation operator can also
be used for extending an
existing tuple.
>>>t1 = (1, 2, 3)
>>>t1 = t1 + (7,8,9)
>>>t1

OUTPUT :
(1, 2, 3, 7, 8, 9)

It is used to repeat elements of a


>>>h1 = (‘H’ , ‘M’)
tuple.
Repetition (*) >>>h1 * 3
Repetition operation is denoted (‘H’ , ‘M’, ‘H’ , ‘M’, ‘H’ , ‘M’)
by Symbol (*).

The ‘in’ operator checks the


presence of element in tuple. If >>>h1 = (‘H’ , ‘M’)
the element is present it returns >>>’H’ in h1
True
Membership True, else it returns False.
>>>’m’ not in h1
The not in operator returns True True
if the element is not present in
68
the tuple, else it returns False.

>>>t1 = (1, 2, 3, 7, 8, 9)
>>>t1[2:4]
(3, 7)

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


It is used to extract one or more 60, 70, 80)
elements from the tuple. Like >>>t1[2 : 7]
Slicing
string and list, slicing can be (30, 40, 50, 60, 70)
applied to tuples also.
>>>t1[ : 5]
(10, 20, 30, 40, 50)

>>>t1[: : -1]
(80, 70, 60, 50, 40, 30, 20, 10)

Tuple Methods and Built-in Functions :


Method
Description Example
Name

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


This method returns the length of
80)
len( ) tuple or the number of elements in
>>>len(t1)
the tuple. 8

>>>t1 = tuple()
>>>type(t1)
<class ‘tuple’>

>>>t1 = tuple(‘python’) #string


>>>t1
This function creates an empty tuple (‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
tuple( ) or creates a tuple if a sequence is
passed as argument. >>>t1 = tuple([1,2,3]) #list
>>>t2
(1, 2, 3)

>>>t1 = tuple(range(7))
>>>t1
(0, 1, 2, 3, 4, 5, 6)

>>>t1=tuple(“tuples in python”)
This function returns the frequency
count( ) >>>t1.count(‘p’)
of an element in the tuple. 2

>>>t1=tuple(“tuples in python”)
This function returns the index of the >>>t1.index(‘n’)
index( ) first occurrence of the element in the 8
given tuple.
>>>t1=tuple(“tuples in python”)
69
>>>t1.index(‘f’)
ValueError: tuple.index(x): x not
in tuple

>>>t1 = (‘t’, ‘u’, ‘p’, ‘l’, ‘e’, ‘s’)


This element takes tuple as an >>>sorted(t1)
argument and returns a sorted list. [‘e’, ‘l’, ‘p’, ‘s’, ‘t’, ‘u’]
sorted()
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)
1
This function returns minimum or
min()
smallest element of the tuple. >>>t1 = (‘t’, ‘u’, ‘p’, ‘l’, ‘e’, ‘s’)
>>>min(t1)
‘e’

>>>t1 = (3, 8, 4, 10, 1)


>>>max(t1)
10
This function returns maximum or
max( )
largest element of the tuple. >>>t1 = (‘t’, ‘u’, ‘p’, ‘l’, ‘e’, ‘s’)
>>>max(t1)
‘u’

>>>t1 = (3, 8, 4, 10, 1)


This function returns sum of the
sum( ) >>>sum(t1)
elements of the tuple. 26

Tuple Assignment :

It allows a tuple of variables on the left side of the assignment operator to be assigned
respective values from a tuple on the right side. The number of variables on the left
should be same as the number of elements in the tuple. for example---
>>>(n1,n2) = (5,9)
>>>print(n1)
5
print(n2)
9
>>>(a,b,c,d) = (5,6,8) #values on left side and right side are not equal
ValueError: not enough values to unpack

Nested Tuples :

A tuple inside another tuple is called a nested tuple. In nested tuples we can access the
elements in the same way of nested list. for example
>>>t1 = ((“Amit”, 90), (“Sumit”, 75), (“Ravi”, 80))
>>>t1[0]
(‘Amit’, 90)
70
>>>t1[1]
(‘Sumit’, 75)
>>>t1[1][1]
75
Important Questions & Answers
1. Which of the following is a Python tuple?
a) [1, 2, 3]
b) (1, 2, 3)
c) {1, 2, 3}
d) {}

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


a) print(t[3])
b) t[3] = 45
c) print(max(t))
d) print(len(t))
3. What will be the output of the following Python code?
>>>t=(1,2,4,3)
>>>t[1:-1]
a) [2, 3, 9]
b) [1, 2, 4, 3, 8, 9]
c) [1, 4, 8]
d) (1, 4, 8)

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


>>>t =(1, 2)
>>>2* t
a) (1, 2, 1, 2)
b) [1, 2, 1, 2]
c) (1, 1, 2, 2)
d) [1, 1, 2, 2]
5. What is the data type of (1)?
a) Tuple
b) Integer
c) List
d) Both tuple and integer

6. If a=(1,2,3,4), a[1:-1] is _________


a) Error, tuple slicing doesn’t exist
b) [2,3]
c) (2,3,4)
d) (2,3)

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


>>> a=(1,2)
71
>>> b=(3,4)
>>> c=a+b
>>> c
a) (4,6)
b) (1,2,3,4)
c) Error as tuples are immutable
d) None
8. What will be the output of the following Python code?
>>>a,b=6,7
>>>a,b=b,a
>>>a,b
a) (6,7)
b) Invalid syntax
c) (7,6)
d) Nothing is printed

9. Tuples are mutable


a) True
b) False

10. x =(3) and y =(3,) both are same


a) True
b) False

Short Answer Questions:- ( 2 Marks)


Find the Output of the followings (I to ix)
Consider the following tuples, tuple1 and tuple2:
tuple1 = (23,1,45,67,45,9,55,45)
tuple2 = (100,200)
Find the output of the following statements:

i. print(tuple1.index(45))
ii. print(tuple1.count(45))
iii. print(tuple1 + tuple2)
iv. print(len(tuple2))
v. print(max(tuple1))
vi print(min(tuple1))
vii. print(sum(tuple2))
viii. print ( sorted ( tuple1) )
print(tuple1)
ix. s=("Cbse Exam 2020-2021")
print(s)
r=""
for i in s:
if i.isupper()== False:

72
r+=i.lower()
elifi.islower()== False:
r+=i.upper()
else:
r=r+i print(r)

X.TypeError occurs while statement 2 is running. Give reason.


How can it be corrected?
>>> tuple1 = (5) #statement 1
>>>len(tuple1) #statement 2

3 Marks Questions
1 Write a program to read email IDs of n number of students and store them
in a tuple. Create two new tuples, one to store only the usernames from the
email IDs and second to store domain names from the email ids. Print all
three tuples at the end of the program.
[Hint: You may use the function split()]
2 Write a program to input names of n students and store them in a tuple.
Also, input a name from the user and find if this student is present in the
tuple or not. We can accomplish these by:
(a) writing a user defined function (b) using the built-in function
3 Write a program to swap two numbers without using a temporary variable.
4 This is a program to create a nested tuple to store roll number, name and
marks of students
5 Write a program to input n numbers from the user. Store these numbers in
a tuple. Print the maximum and minimum number from this tuple.
6 Explain tuple methods with suitable examples.
7 Explain tuple slicing with suitable examples
8 Write a program to find the minimum, maximum, mean of values stored in
a tuple .
9 WAP to perform linear search on a tuple of numbers, counting the
frequency of elements in a tuple.
10 WAP to perform linear search on a tuple of numbers, counting the
frequency of elements in a tuple.

73
Dictionary
Dictionary :- Python Dictionary is used to store the data in a key-value pair format.
-Python Dictionaries are unordered collection.
- Dictionaries are mutable means values in a dictionary can be changed using
its key.
- Keys are unique. - Enclosed within brace { }

Creating the dictionary:-The dictionary can be created by using multiple key-value pairs
enclosed with the curly brackets {}, and each key is separated from its value by the colon (:)

# Creating an empty Dictionary


Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary with dict() method
Dict = dict({1: 'Java', 2: 'T', 3:'Point'})
print("\nCreate Dictionary by using dict(): ")
print(Dict)

Accessing items in a dictionary using keys:- The elements are accessed through the
keys defined in the key:value pairs

Syntax:-<dictionary-name>[<key>]

Mydict = {'Name': 'Raj', 'Age': 15, 'Class': 12, 'Totalmarks':450}

Mydict['Name']

Output:- Raj

Accessing Keys or Values Simultaneously

Mydict = {'Name': 'Raj', 'Age': 15, 'Class': 12, 'Totalmarks':450}

print(Mydict.keys())

print(Mydict.values())

Adding and updating dictionary elements

my_dict = {'name': 'Jack', 'age': 26}

# update value

74
my_dict['age'] = 27

print(my_dict)

# add item

my_dict['address'] = 'Downtown'

print(my_dict)

Output:-

{'name': 'Jack', 'age': 27}


{'name': 'Jack', 'age': 27, 'address': 'Downtown'}

get() method:-

Mydict = {'Name': 'Raj', 'Age': 15, 'Class': 12, 'Totalmarks':450}

print(Mydict.get('Age'))

Output:---- 15

Traversing a dictionary:- Traversal means accessing a d processing each elements:-

Mydict = {'Name': 'Raj', 'Age': 15, 'Class': 12, 'Totalmarks':450}

for k, v in Mydict.items():

print (k, '----', v)

Output:---

Name ---- Raj


Age ---- 15
Class ---- 12
Totalmarks ---- 450

Built-in functions in dictionary:-

1. len():- Returns the length of the dictionary

Mydict = {'Name': 'Raj', 'Age': 15, 'Class': 12, 'Totalmarks':450}


print('Length', '=',len(Mydict))
Output:- Length= 4

75
2. dict() :- dict() function creates a dictionary.

x = dict(name = "John", age = 36, country = "Norway")


print(x)

{'name': 'John', 'age': 36, 'country': 'Norway'}

3. keys():- returns all the available keys

x=dict(name="Yug",age=37,country="India")
print(x.keys())

dict_keys(['name', 'age', 'country'])

4. values()-returns all the available values


x=dict(name="Yug",age=37,country="India")
print(x.values())
dict_values(['Yug', 37, 'India'])
5. get():- The get() method returns the value of the item with the specified key.
Mydict = {'Name': 'Raj', 'Age': 15, 'Class': 12, 'Totalmarks':450}
print(Mydict.get('Class'))
print(Mydict['Name'])

12
Raj
6. update():- updates the dictionary with the elements from another dictionary object
or from an iterable of key/value pairs.

mydict = {'Africa':200,'australia':300,'England':400}
print("Country Name: ",mydict)
mydict.update({'China':500})
print("updated country name: ",mydict)
Country Name: {'Africa': 200, 'australia': 300, 'England': 400}
updated country name: {'Africa': 200, 'australia': 300, 'England': 400, 'China':
500}

76
7. del() :- The del keyword can be used to in-place delete the key that is present in
the dictionary in Python.
# Initializing dictionary
test_dict = {"Arushi": 22, "Mani": 21, "Haritha": 21}

# Printing dictionary before removal


print("The dictionary before performing remove is : ", test_dict)

# Using del to remove a dict


# removes Mani
del test_dict['Mani']

# Printing dictionary after removal


print("The dictionary after remove is : ", test_dict)

The dictionary before performing remove is : {'Arushi': 22, 'Mani': 21, 'Haritha':
21}
The dictionary after remove is : {'Arushi': 22, 'Haritha': 21}

8. pop() method removes the specified item from the dictionary and return the
corresponding value.
Mydict = {'Name': 'Raj', 'Age': 15, 'Class': 12, 'Totalmarks':450}
Mydict.pop('Name')
'Raj'

9. popitem():- The popitem() method removes the item that was last inserted into the
dictionary.
Mydict = {'Name': 'Raj', 'Age': 15, 'Class': 12, 'Totalmarks':450}
K= Mydict.popitem()
print("Last item of dictionary = ", K)

Last item of dictionary = ('Totalmarks', 450)

10. fromkeys():- The dict.fromkeys() method creates a new dictionary from the
given iterable (string, list, set, tuple) as keys and with the specified value.

77
Syntax:
dictionary.fromkeys(sequence, value)

keys = ('Mumbai','Bangalore','Chicago','New York')


value = 'city'
dictionary = dict.fromkeys(keys, value)
print(dictionary)

{'Chicago': 'city', 'Mumbai': 'city', 'New York': 'city', 'Bangalore': 'city'}

11. copy() :- copy() method returns a copy (shallow copy) of the dictionary.
original = {'Name': 'Raj', 'Age': 15, 'Class': 12, 'Totalmarks':450}
new = original.copy()
print('Orignal: ', original)
print('New: ', new)
12. setdefault():- The setdefault() method returns the value of a key (if
the key is in dictionary). If not, it inserts key with a value to the dictionary.

romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5 }


value = romanNums.setdefault('I')
print("The return value is: ", value)
value = romanNums.setdefault('VI')
print("The return value is: ",value)
print("Updated dictionary: ",romanNums)

The return value is: 1


The return value is: None
Updated dictionary: {'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5, 'VI': None}

13. max() and min():- Used to find maximum and minimum respectively from
the dictionary.
my_dict = {'x':500, 'y':5874, 'z': 560}
key_max = max(my_dict.keys(), key=(lambda k: my_dict[k]))
key_min = min(my_dict.keys(), key=(lambda k: my_dict[k]))
print('Maximum Value: ',my_dict[key_max])
print('Minimum Value: ',my_dict[key_min])
Maximum Value: 5874
Minimum Value: 500
78
14. clear() :- removes all items from the dictionary.

Mydict = {'Name': 'Raj', 'Age': 15, 'Class': 12, 'Totalmarks':450}


Mydict.clear()
print(Mydict)
{}

15. sorted():- The sorted() function returns a sorted list of the specified iterable
object.
dict = {6:'George' ,2:'John' ,1:'Potter' ,9:'Micheal' ,7:'Robert' ,8:'Gayle' }
b = sorted(dict.keys())
print("Sorted keys",b)
c = sorted(dict.items())
print("Sorted Values",c)

Sorted keys [1, 2, 6, 7, 8, 9]


Sorted Values [(1, 'Potter'), (2, 'John'), (6, 'George'), (7, 'Robert'), (8, 'Gayle'),
(9, 'Micheal')]

Write programs using dictionary :

1. count the number of times a character appears in a given string using a dictionary :-

#initializing string
test_str = "AMARDEEP"

# using dict.get() to get count


# of each element in string
res = {}

for keys in test_str:


res[keys] = res.get(keys, 0) + 1

# printing result
print ("Count of all characters in GeeksforGeeksis : \n" , res)

2. Create a dictionary with names of employees, their salary and access them.
Mydict = { }
while True :

79
name = input("Enter employee name :-")
sl = int(input("Enter employee salary :-"))
Mydict[ name] = sl
user = input("Do you want to quit then enter yes :-")
if user == "yes" :
break
print(Mydict)
Short Answers type questions
Q1. Keys of dictionary must be_________
a. antique
b. unique
c. mutable
d. integers
Q2. We can repeat the values of Key in Dictionary?
a. True
b. False
Q3. Key – value concept is in _______________
a. List
b. String
c. Dictionary
d. Tuple

Q4. What type of error is returned by the following code :


a={'a' : "Apple", 'b' : "Banana" , 'c' : "Cat"}
print(a[1])

Q5. Write the two ways to construct an empty dictionary.


Q6. Write the output of following code:
sales = {'Audi':45, 'BMW':32, 'Ferrari':12}
for x in sales:
print(x)

Q7. Suppose a dictionary days is declared as:


days={1:"Sun", 2:"Mon", 3:"Wed"}
Write a statement in Python to change Wed to Tue.
Q8. _______ is used to remove all items form a particular dictionary.

Q9. Like lists, dictionaries are which mean they can be changed.
80
a. Mutable
b. Immutable
c. Variable
d. None of these

Q10. What will be the output:-


d1= {‘rohit’:56,”Raina”:99}
print(“Raina” in d1)

Q11. Which of the following function create a dictionary from sequence of key - value
Pairs.
a. dictionary( )
b. dict( )
c. create( )
d. convert( )

Short Answer Type Questions

Q1. Parth wants to display the value corresponding to the key “3” in dictionary given
below. As a friend of Parth, help him to find the correct code.

D={1: ‘Amit’, 2: ‘Suman’, 3: ‘Ravi’, 4: ‘Anuj’}


a. print(D.get(3))
b. print(D[3])
c. Both of the above
d. None of the above
Q2. Write Python code to convert following two list into one dictionary :-
keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]
Q3. Print the value of key ‘physics’ from the following dictionary
MyDict = {
"class": {
"student": {
"name": "Mike",
"marks": {
81
"physics": 70,
"history": 80
}
}
}
}

Q4. Get the key of a minimum value from the following dictionary

My_dict = {'Physics': 82,'Math': 65,'CS': 75}


Q5.Find the output of the following python code:-
a = {}
a[1] = 1
a['1'] = 2
a[1]= a[1]+1
count = 0
for i in a:
count += a[i]
print("count=", count)
Q6. What is the output of the following of code?
a = {i: i*i*i for i in range(6)}
print (a)
Q7. What will be output of following python program :-
dict = {(3,4,8):4,(5,6,9):3}
print(dict)
print('output:',dict[5,6,9])
Q8. Find the output of the following code:-
dictlang = {'c#': 6, 'GO': 89, 'Python': 4,'Rust':10}
cpydict = dictlang.copy()
print(cpydict)
Q9. Find the output of the following code:-
fruitsDict = {
'Apple': 100,
'Orange': 200,
'Banana': 400,
'pomegranate':600 }
if 'Apple' in fruitsDict:
82
del fruitsDict['Apple']
print('Dict after deleting key =',fruitsDict)
Q10. Create a dictionary ‘ODD’ of odd numbers between1 and 10, where the key is the
decimal number and the value is the corresponding number in words.

Long Answer type questions

1) Answer the following question on the given dictionary


Employee= {'Name': 'Aman', 'Salary': 10000, 'Gender': 'Male'}
(i) Add a new key(‘City) with value “Jaipur” in Employeedictionary
(ii) Display all the keys of the Employee dictionary
(iii) Write code to delete all the items of the Employee dictionary
2) What are the differences between dictionary and list ?
3) Consider the following dictionary capitals
capitals = { "Maharashtra": "mumbai",
"Delhi" : "New Delhi",
"Uttar pradesh":"Lucknow",
"Tamil Nadu ": " Chennai"}
Find the output of the following statements:-
(i) print(capitals.get("Tamil Nadu"))
(ii) print(capitals.keys())
(iii) print("Delhi" in capitals)

4) Write a program to convert a number entered by the user into its corresponding
number in words. for example if the input is 876 then the output should be ‘Eight
Seven Six’.

5) Python Program to Multiply All the Items in a Dictionary.

6) Write a Python program to print all unique values in a dictionary.


Sample Data : [{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"},
{"VII":"S005"}, {"V":"S009"},{"VIII":"S007"}]
Expected Output : Unique Values: {'S005', 'S002', 'S007', 'S001', 'S009'}

7) Write a program to create a dictionary namely Mydict with 10 keys 0 to 9, each


having value as 20. Update the first and last values by adding 100 to each of them.

8) Write a python function to print sum of all items in a dictionary.

83
9) Write a Python function to count the frequency of elements in a list using a
dictionary.
10) Find error, underline them and rewrite the same after correcting the following
code:-
D1= { }
i=1
Num= input("Enter number of entries: ")
while (i<=Num):
a= get("Enter name: ")
b= input("Enter age:")
D1(a)=b
i= i+1
L= D1.key()
for i in L:
print(i, '\t', D1[i])

Case based questions

1. Mohan is student who is learning python programming. Mohan is unable to find


out the output of the following python program. Help the Mohan by finding output
of the following :-
Mydict= {'A':10,'B':20,'a':30, 'D':40}
Val_A= ''
for i in Mydict:
if (i>Val_A):
Val_A= i
Val_B= Mydict[i]
print(Val_A) # Line1
print(Val_B) # Line2
print(20 in Mydict) # Line3
print('D' in Mydict) # Line4
Mylist= list(Mydict.items())
Mylist.sort() # Line5
84
print(Mylist[-1]) # Line6

(i)What output does Line1 produce ?


(ii) What output does Line2 produce ?
(iii)What output does Line3 produce ?
(iv)What output does Line4 produce ?
(v) What is the return value form the list sort() function (line5)
(vi) What output does Line6 produce ?
2. Mr. Rajesh Kumar is a teacher in a school. He is doing his work manually . As a
python learner solve the problems of Rajesh Kumar by python programs:-
(i) Create a dictionary student which ask Student roll number, Name and Marks
of students and display them in tabular format.
(ii) Display the names of those students who have secured marks more than 75.
(iii) Delete those students who have secured less than 50 marks

ANSWER KEY

Q. No. Answers Q. No. Answers Q. No. Answers

Short Answers type questions

1. b 2. a 3 c

4. Key Error 5. (i) Use of 6. Audi


{} symbol BMW
(ii) dict() Ferrari
function
7. Days[3] 8. clear() 9. a
=”Tue”
10. True 11. b

Short Answer Type Questions

1. d

85
2. keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]
res_dict = dict(zip(keys, values))
print(res_dict)
3. print(MyDict['class']['student']['marks']['physics'])

4. print(min(My_dict, key=My_dict.get))

5. count= 4

6. {0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

7. {(3, 4, 8): 4, (5, 6, 9): 3}


output: 3

8. {'c#': 6, 'GO': 89, 'Python': 4, 'Rust': 10}

9. Dict after deleting key = {'Orange': 200, 'Banana': 400,


'pomegranate': 600}

10. ODD = {1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}


print(ODD)

Long Answer type questions

1. (i) Employee['City']= "Jaipur"


print(Employee)
(ii) Employee.keys()
(iii) Employee.clear()
2. 1. List is an ordered set of elements. But, a dictionary is a data
structure that is used for matching one element (Key) with
another (Value).
2. The index values can be used to access a particular element.
But, in dictionary key represents index. Remember that, key may
be a number of a string. 3. Lists are used to look up a value
whereas a dictionary is used to take one value and look up
another value.
3. (I) None
(ii)dict_keys(['Maharashtra', 'Delhi', 'Uttar pradesh', 'Tamil Nadu '
(iii) True

86
4. num = input("Enter any number: ") #number is stored as string
#numberNames is a dictionary of digits and corresponding
number
#names
numberNames = {0:'Zero',1:'One',2:'Two',3:'Three',4:'Four',\
5:'Five',6:'Six',7:'Seven',8:'Eight',9:'Nine'}
result = ''
for ch in num:
key = int(ch) #converts character to integer
value = numberNames[key]
result = result + ' ' + value
print("The number is:",num)
print("The numberNameis:",result)

5. My_dict = {'A':10, 'B':20, 'C':30}


Multiply= 1
for i in My_dict:
Multiply= Multiply*My_dict[i]
print(Multiply)
6. L = [{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI":
"S005"}, {"VII":"S005"}, {"V":"S009"},{"VIII":"S007"}]
print("Original List: ",L)
u_value = set( val for dic in L for val in dic.values())
print("Unique Values: ",u_value)
7. Mydict= dict.fromkeys(range(10), 20)
Mydict[0]+=20
Mydict[9]+= 20
print(Mydict)
8. # Function to print sum
def ReturnSum(myDict):
list = []
for i in myDict:
list.append(myDict[i])
final = sum(list)
return final
dict = {'a': 100, 'b': 200, 'c': 300}
print("Sum :", ReturnSum(dict))

87
9. def CountFrequency(my_list): # Function definition
# Creating an empty dictionary
freq = {}
for item in my_list:
if (item in freq):
freq[item] += 1
else:
freq[item] = 1
for key, value in freq.items():
print ("% d : % d"%(key, value))

my_list=[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]
CountFrequency(my_list) # function calling

10. D1= { }
i=1
Num= int (input("Enter number of entries: "))
while (i<=Num):
a= input("Enter name: ")
b= input("Enter age:")
D1[a]=b
i= i+1
L= D1.keys()
for i in L:
print(i, '\t', D1[i])

Case based questions

1. (i) A
(ii) 30
(iii) False
(iv) True
(v) None
(vi) ('a', 30)

88
2. (i) n=int(input("How many student data you want to enter ..."))
Student={}
for i in range(n):
roll_no=int(input("Enter roll no: "))
name=input("Enter name: ")
marks=int(input("Enter marks: "))
Student[roll_no]=[name,marks]
print("{:<10} {:<10} {:<10}".format('Rollno','Name','Marks'))
for k, v in d.items():
Name, num = v
print("{:<10} {:<10} {:<10}".format(k, name, marks))

(ii)
n=int(input("Enter n: "))
d={}
for i in range(n):
roll_no=int(input("Enter roll no: "))
name=input("Enter name: ")
marks=int(input("Enter marks: "))
d[roll_no]=[name,marks]
for k in d:
if(d[k][1]>75):
print(d[k][0])

(iii)
n=int(input("How many student data you want to enter ..."))
Student={}
for i in range(n):
roll_no=int(input("Enter roll no: "))
name=input("Enter name: ")
marks=int(input("Enter marks: "))
Student[roll_no]=[name,marks]
for k, v in list(Student.items()):
if v[1] < 50:
del Student[k]
print("Remaining students: ", Student)

89
Sorting techniques :- Bubble and Insertion Sort

Sorting :- Sorting refers to arranging data in a particular format. Sorting algorithm


specifies the way to arrange data in a particular order. Most common orders are in
numerical or lexicographical order.
To arrange the elements in ascending or descending order. There are many sorting
techniques. Here we shall discuss two sorting techniques:

● Bubble sort
● Insertion sort

(i) BUBBLE SORT: Bubble sort is a simple sorting algorithm. It is based on comparisons,
in which each element is compared to its adjacent element and the elements are swapped
if they are not in proper order.

PROGRAM:

L=eval(input("Enter the elements:"))


n=len(L)
for p in range(0,n‐1):
for i in range(0,n‐1):
if L[i]>L[i+1]:
L[i], L[i+1] = L[i+1],L[i]
print("The sorted list is : ", L)

OUTPUT:

Enter the elements:[60, 24, 8, 90, 45, 87, 12, 77]

The sorted list is : [8, 12, 24, 45, 60, 77, 87, 90]

(ii) INSERTION SORT: Sorts the elements by shifting them one by one and inserting the

element at right position.

PROGRAM:

L=eval(input("Enter the elements: "))

n=len(L)

for j in range(1,n):

temp=L[j]

prev=j‐1

while prev>=0 and L[prev]>temp: # comparison the elements


90
L[prev+1]=L[prev] # shift the element forward

prev=prev‐1

L[prev+1]=temp #inserting the element at proper position

print("The sorted list is :",L)

OUTPUT:

Enter the elements: [45, 11, 78, 2, 56, 34, 90, 19]

The sorted list is: [2, 11, 19, 34, 45, 56, 78, 90]

Introduction to Python Modules: - A python program consists of three main


components

● Library or package
● Module
● Function/Sub Modules

RELATIONSHIP BETWEEN A MODULE, PACKAGE AND LIBRARY IN PYTHON

● A module is a file containing python definitions, variables and classes and statement
with .py extension
● A Python package is simply a directory of python modules.
● A library in python is collection of various packages. Conceptually there is no
difference between package and python Library.

Advantages of Python Modules

● Putting code into modules is useful because of the ability to import the module
functionality.
● Reusability: A module can be used in some other python code. Hence it provides
facility of code reusability
● A module allows us to logically organize our python code.
● Grouping related code into a module makes the code easier to understand and use.
● Categorization: Similar types of attributes can be placed in a single module.

Creation of Module:

The following point must be noted before creating a module.

1. A module name should always end with .py extension


2. We will not able to import module if it does not end with .py
3. A module name must not be a Python keyword

A module is simply a python file which contains functions, classes and variables.

91
Let us consider the following example of a module name area.py which contains three
functions name area_circle(r), area_square(s), area_rect(l,b)

import math

def area_circle(r):

return math.pi*r*r

def area_square(s):

return s*s

def area_rect(l,b):

return l*b

importing Modules: There are two ways to import a module(s) :

1) Using import statement: we can import single as well as multiple modules

1.1 For importing Single module

Syntax: import modulename

1.2 For importing Multiple modules

Syntax: import modulename1, modulename2, modulename3

To Use function inside module

Syntax modulename.function name

2) Using from Statement: -To import some particular Function(s) from module we will use
import statement

2.1 To import Particular Function

Syntax: From <module name> import <write name of Function(s)>

OR

From <module name> import *

(This statement will import all the functions from modules)

To use a function inside a module you have to directly call function if you are importing the
modules using from statement.

92
Example : Let us consider the following code. In this program we import the module with
the help of from statement and directly use the function instead of specifying Module name.

from area.py import area_rect

area_rect(5,4)

Importing math module:-In order to use the various constants of mathematics and
operations, we have to import math module in our program.

Example :
import math

Let us discuss commonly-used constants and functions in math module.

pi: - It is a mathematical constant, the ratio of the circumference of a circle to its diameter
(3.14159...)

For example
>>> print ("The value of pi is :",math.pi)
The value of pi is: 3.141592653589793

e: - It is a mathematical constant that returns e raised to the power x, where e=2.718281.


It is the base of natural logarithms. It is also called Euler's number.

For example :
>>>print("The value of e is :", math.e)
The value of e is :2.718281828459045
ceil(x): - Returns the smallest integer that is greater than or equal to x.
For example :
>>>print("ans :",math.ceil(7.3))
Output: ans :8
floor(x): - Returns the largest integer that is less than or equal to x.
>>>math.floor(-45.17)
-46
>>>math.floor (100.12)
100
pow(x,y): - It returns the value of xy, where x and y are numeric expressions.
>>> print ("ans :", math.pow (3, 3))
Ans :27.0
>>>math.pow (2, 4)
16.0
93
>>>math.pow (5, 0)
1.0
sqrt(x): - Returns the square root of x.
>>> print ("Squre root of 65=:", math.sqrt (65))
Squre root of 65=:8.06225774829855
>>>math.sqrt (36)
6.0
fabs(x): - Returns the absolute value of x, represented as –
math.fabs (x)
where, x can be any numeric value.
For example,
>>> print (math.fabs (500.23))
500.23
>>> print (math.fabs (-200))
200
cos(x): - Returns the cosine of x in radians.
>>>math.cos(3)
-0.9899924966004454
sin(x): - Returns the sine of x in radians.
>>>math.sin (3)
0.14112000806
tan(x): - Returns the tangent of x in radians.
>>>math.tan (3)
-0.1425465430742778

Random Module: - This module contains functions that are used for generating random
numbers. import statement is the first statement to be given in a program for generating
random numbers:

import random

The various functions associated with this module are as follows: -

(1) random():- It is floating point random number generator between 0.0 to 1.0. Here
lower limit is inclusive where as upper limit is less than 1.0. i.e. 0<=N<1 where N is
generated random number.

Example: -

>>>import random
94
>>>n=random.random()
>>>print(n)

0.1738135764235368

(2) randrange():- This method generates an integer between its lower and upper
argument. By default, the lower argument is 0.

Example :-
>>> import random
>>>Number=random.randrange (30)
>>>print(Number)
15

Note: - This line of code shall generate any one random integer number from 0 to 29
excluding upper argument.

(3) randint() : - This method generate random integer number. Both the given range
values are inclusive.

Example :-
>>> import random
>>>Number=random.randint (100,500)
>>>print(Number)
151

Statistical Module: - This module provides functions for calculating mathematical statics
of numeric (real valued) data. There are 3 basic functions under this module.

1. mean()
2. median()
3. mode()

In order to use these functions, we have to import statistics module in our code.

1. mean(): - It calculate the average of all given numbers.


Example: -
>>> import statistics
>>>L=[1,2,3,4,5,6]
>>>print(statistics.mean(L))
3.5Note: - 3.5 is the average of all numbers in the list

95
2. median(): - The median is the middle number in a group of numbers. If group has odd
numbers of element then it will return the middle position value, otherwise will return the
average of values at mid and mid-1 position.

Example: -
>>> import statistics
>>>L=[10,20,30,40,50,60,70]
>>>print(statistics.median(L))
40

3. mode(): - The mode function returns number that occurs most often within a set of
numbers.

Example:-
>>> import statistics
>>>L=[10,5,30,5,5,60,70]
>>>print(statistics.mode(L))
5

(1 MARK QUESTIONS)

Q1. Which of these definitions correctly describe a module?


a) Denoted by triple quotes for providing the specifications of certain program elements.
b) Design and implementation of specific functionality to be incorporated into a program
c) Defines the specifications of how it is to be used.
d) Any program that reuses code.

Q2. If a,b,c=3,4,1 then what will be the value of math.sqrt(b)*a-c

a) 5.0
b) 5
c) 2
d) 4.0

Q3. What is displayed on executing print(math.fabs(-3.4))?


a) -3.4 b) 3.4 c) 3 d) -3
Q4. What is the file extension of python module file?
Q5. Which of the following is not an advantage of using modules?
a)Provides a means of reuse of program code
b)Provides a means of dividing up tasks
c)Provides a means of reducing the size of the program
d)Provides a means of testing individual parts of the program
96
Q6. Which operator is used in the python to import all modules from packages?
(a) . operator (b) * operator
(c) ‐> symbol (d) , operator
Q7. In python which is the correct method to load a module math?
(a) include math (b) import math
(c) #include<math.h> (d) using math
Q8. Which is the correct command to load just the tempc method from a module called
usable?
(a) import usable,tempc (b) Import tempc from usable
(c) from usable import tempc (d) import tempc
Q9. Which of the following can not be returned by random.randrange(4)
a) 0
b) 3
c) 2.3
d) None of the mentioned
Q10. What does random.seed(3) return?
a) True
b) None
c) 3
d) 1

(2 MARKS QUESTIONS)

Q1. Write two forms of import statement.


Q2. Write a python program to calculate the square root of given number n.
Q3. What is the utility of Python standard library's math module and random module?
Q4. Define 'module' and 'package'.
Q5.Which of the following is the same as math.exp(p)? Also give the explanation.
a) e ** p b) math.e ** p
c) p ** e d) p ** math.e
Q6. List any two advantages of modules?
Q7. How is math.ceil (89.7) different from math.floor (89.7)?
Q8. Write a Python program to generate a random number between 0 and 9.
Q9.What is the problem in the following piece of code?
from math import factorial
print (math.factorial (5))

97
Q10. What would be the output produced by the following code :
import math
import random
print ( math.ceil (random.random()))
Justify your answer.

(3 MARKS QUESTIONS)

Q1. Select the possible output(s) of the following code from the given option. Also,
specify the maximum and minimum value that can be assigned to variable NUM.
import random
cities = [‘Agra’, ‘Delhi’, ‘Chennai’, ‘Bhopal’]
NUM = random.randint(1,2)+1 for city in cities:
for I in range(1,NUM):
print(city, end=‘’)
print(‘\n’)
a) c) Agra
b) Agra Delhi
DelhiDelhi Chennai
ChennaiChennaiChennai Bhopal
BhopalBhopalBhopalBhopal
d) AgraAgra e) ChennaiChennai
DelhiDelhi BhopalBhopal
ChennaiChennai
BhopalBhopal

Q2.What is the utility of Python standard library's math module, random module and
statistics module?

Q3. Consider the following code:


import math
import random
print(str(int(math.pow( random.randint (2,4),2) )), end = ‘ ’)
print(str( int ( math.pow(random.randint(2,4), 2))) , end = ‘ ’)
print( str ( int (math.pow( random .randint (2,4),2))))
What would be possible outputs out of the given six choices?
(i) 2 3 4
(ii) 9 4 4
(iii) 16 16 16
(iv) 2 4 9
(v) 4 9 4
(vi) 4 4 4

98
Q4. What are docstrings? How are they useful?
Q5. Consider the following code:

import random as r
for I in range(4):
print(100 + r.randint(5,10), end=’ ‘)

Find the suggested output option(s) (i) to (iv). Also, write the least value and highest value
that can be generated by randint().
(i) 102 105 104 105
(ii) 110 103 104 105
(iii) 105 107 105 110
(iv) 110 105 105 110

Q6. Name the python library modules which need to be imported to invoke the following
functions: (i) floor() (ii) randint() (iii) mean()

Q7. In which situation, would you prefer bubble sort over insertion sort?

Q8. Write a python program to calculate mean, median and mode of data stored in the list.

Q9. What happens when Python encounters an import statement in a program? What
would happen if there is one more import statement for the same module, already
imported in the same program?

Q10. What possible output(s) are expected to be displayed on screen at the time of
execution of the program from the following code? Specify the maximum values that can
be assigned to each of the variables first, second and third in the code given.

from random import randint


LST=[5,10,15,20,25,30,35,40,45,50,60,70]
first = randint(3,8) – 1
second = randint(4,9) – 2
third = randint(6,11) – 3
print(LST[first],"#", LST[second],"#", LST[third],"#")

a) 20#25#25#
b) 30#40#70#
c) 15#60#70#
d) 35#40#60#
Case Study Based Questions

1. Write a python program that takes a number from 1 to 9 and stored inside the variable
“guess_num”. If the user guesses wrong then the prompt appears again and the user
continues to input another number repetitively until the guess is correct. On successful
guess, the user will get a “Well guessed!” message, and the program will exit.
99
2. Write a program to perform insertion sorting on a given list of strings, on the basis of
length of strings. That is, the smallest length string should be the first string in the list
and the largest length string should be the last string in the sorted list.

Answers (1 Mark Questions)


A1 :-b) Design and implementation of specific functionality to be incorporated into a
program
A2. :- a) 5.0
A3. :- b) 3.4
A4. The file extension of python module file is .py
A5. Answer: c
A6. * operator.
A7. import math
A8. C) from usable import tempc
A9. C) 2.3
A10. b) None
Answers (2 Marks Questions)

A1. There are two forms of import statements:

1. import <modulename>
2. from <module> import <function>

A2.

import math
n=float(input('Enter n='))
ans=math.sqrt(n)
print('Square root of',n,' = ',ans)
A3.
(i) The math module is used for math related functions that work with all number
except complex numbers.
(ii) The Random module is used for different random number generator functions.
A4.
Each python program file is a module which imports other modules like objects and
attributes. A python program folder is a package of modules. A package can have modules
or sub folders.
A5.

Answer: b

EXPLANATION: math.e is the constant defined in the math module.

100
A6.Advantages of modules are:-
1. Reusability : Working with modules makes the code reusable.
2. Simplicity: Module focuses on a small proportion of the problem, rather than focusing on
the entire problem.

A7.

Ceil: The function 'ceil(x)' in Python returns the smallest integer not less than x i.e., the
next integer on the RHS of the number line. Hence, 'math. ceil(89.7)' will return 90
whereas 'math. floor(89.7)' will return 89.

A8.
import random

print(random.randrange(10))

A9.

In the "from-import" form of import, the imported identifiers (in this case factorial())
become part of the current local namespace and hence their module's names aren't
specified along with the module name. Thus, the statement should be:

print (factorial (5))

A10.

The output would be : 1.0

random.random() would generate a number in the range [0.0, 1.0] but math.ceil ( ) will
return ceiling number for this range, which is 1.0 for all the numbers in this range. Thus
the output produced will always be 1.0.

Answers (3 Marks Questions)

A1. Options b and c are correct. Maximum and Minimum value assigned to NUM are 3 and
2 respectively.
A2.
(i) Math module: The math module is used for math-related functions that work
with all number types except for complex numbers.
(ii) Random module: The random module is used for different random number
generator functions.
(iii) Statistics module:- The statistics module is used statistic-related functions like
mean, mode, median etc.
A3.
Options ii, iii, v and vi are possible outputs

101
A4. A docstring is just a regular Python triple-quoted string that is the first thing in a
function body/a module/ a class. When executing a function body (or a module/class),
the docstring doesn't do anything like comment, but Python stores it as part of the
function documentation. This documentation can later be displayed using the help()
function. So, even though docstrings appear like comments (no execution), they are
different from comments.

A5.

Options iii and iv are possible output(s). Least value and highest value can be
generated by randint() are 5 and 10 respectively.
A6.
(i) floor() – math
(ii) randint()- random
(iii) mean()- statistics
A7.

Bubble sort would be ideal sorting technique for situations where data can be read
only sequentially (e.g., data stored on magnetic tapes). As bubble sort also compare
two adjacent records, it will be suitable for such a situation.

A8.
import statistics as s
a=[4,7,8,2,3,4,5,3,4,5,6,7,10]
print(s.mean(a))
print(s.median(a))
print(s.mode(a))

A9.
When Python encounters an import statement, it does the following:
(i) Code of the imported module is interpreted and executed.
(ii) Defined functions and variables createdin the module are now available to the
program that imported the module.
(iii) For imported module, a new namespace is set up with the same name as that of
the module.

Any duplicate import statement for the same module in the same program is ignored
by Python.

A10.
Option (a) is expected output
Maximum values that can be assigned to the variables first,second and third are 7,7
and 8 respectively.

102
Answers (Case Study based Questions)
A1.
import random

target_num, guess_num = random.randint(1, 10), 0

while target_num != guess_num:

guess_num = int(input("Guess a number between 1 and 10 \ until you get it right:"))

print(target_num)

target_num = random.randint(1, 10)

print('Congratulation both target and guess numbers are same',target_num,guess_num)

print('Well guessed!')

A2.
def insertion_sort(arr):
for i in range(1,len(arr)):
key = arr[i]
j = i-1
while j >= 0 and len(key) <len(arr[j]): # comparison on the basis of length
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
return arr

l = input("Enter a list of strings : ").split() # split() splits the input on whitespace


print(insertion_sort(l))

103
Unit III : Society, Law and Ethics

• Cyber Crime : Definition, Hacking, Eavesdropping, Phishing and Fraud Emails,


Ransomware, Preventing Cyber Crime
• Cyber Safety : Safely browsing the web, Identity Protection, Confidentiality, Cyber Trolls
and Bullying
• Safely Accessing Web Sites : Malware, Viruses, Trojans, Adware
• E-waste Management : Proper Disposal of Used Electronic Gadgets
• Indian Information Technology Act (IT Act)
• Technology & Society: Gender and Disability issues while Teaching and using Computers

Cyber Crime is defined as a crime in which a computer is the object of the crime (hacking,
phishing, spamming) or is used as a tool to commit an offence (child pornography, hate
crimes). Cybercriminals may use computer technology to access personal information,
business trade secrets or use the internet for exploitative or malicious purposes. Criminals
can also use computers for communication and document or data storage. Criminals who
perform these illegal activities are often referred to as hackers.

1. Cyber Trolls 2. Cyber Bullying 3. Cyber Stalking

Hacking:Hacking refers to the misuse of devices like computers, smartphones, tablets,


and networks to cause damage to or corrupt systems, gather information on users, steal
data and documents, or disrupt data-related activity.

A traditional view of hackers is a lone rogue programmer who is highly skilled in coding and
modifying computer software and hardware systems. But this narrow view does not cover
the true technical nature of hacking. Hackers are increasingly growing in sophistication,
using stealthy attack methods designed to go completely unnoticed by cyber security
software and IT teams. They are also highly skilled in creating attack vectors that trick
users into opening malicious attachments or links and freely giving up their sensitive
personal data.

Eavesdropping is the unauthorized real-time interception of a private communication,


such as a phone call, instant message, videoconference or fax transmission. The
term eavesdrop derives from the practice of actually standing under the eaves of a house,
listening to conversations inside.

Phishing are fraudulent attempts by cybercriminals to obtain private information.


For e.g. : A message prompt your personal information by pretending that bank/mail
service provider is updating its website. There are various phishing techniques used by
attackers: o Embedding a link in an email to redirect to an unsecure website that requests
sensitive information o Installing a Trojan via a malicious email attachment o Spoofing the
sender’s address in an email to appear as a reputable source and request sensitive
information o Attempting to obtain information over the phone by impersonating a known
company vendor.
104
Phishing is an attempt to acquire sensitive information such as usernames, passwords and
credit card details (and sometimes, indirectly, money) by masquerading as a trustworthy
entity in an electronic communication. Phishing is typically carried out by email spoofing or
instant messaging and it often directs the users to enter personal information at a fake
website, the look and feel of which is identical to the legitimate one, the only difference
being the URL of the website in question.

Ransomware is a type of malware that prevents users from accessing their system or
personal files and demands ransom payment in order to regain access. While some people
might think "a virus locked my computer," ransomware would typically be classified as a
different form of malware than a virus. The earliest variants of ransomware were developed
in the late 1980s, and payment was to be sent via snail mail. Today, ransomware authors
order that payment be sent via crypto currency or credit card, and attackers target
individuals, businesses, and organizations of all kinds. Some ransomware authors sell the
service to other cybercriminals, which is known as Ransomware-as-a-Service or RaaS.

Cyber Safety :
Cyber safety is the safe and responsible use of Internet &ICT(Information &
Communication Technology). Cyber safety is about to not only keeping information safe
and secure, but also being responsible with that information, being respectful of other
people online. As per Cyber safety peoples are advised to use good 'netiquette' (internet
etiquettes).

Safely Browsing the Web :


Viruses and malware spread, easily and quickly through websites/web browsing. Through
clicking over the links found on web pages or in email mistakenly our computer may be
infected. An infected computer can run slow, barrage us with pop-ups, download other
programs without our permission, or allow our sensitive personal information to others.
Tips for Safe Web Browsing :
▪ Common sense (never respond to spam & disclose personal information).
▪ Use an antivirus & Firewall-It provide real time malware protection.
▪ Create strong passwords
▪ Mind your downloads - Be sure to review all pre-checked boxes prompted at
download & un-check any extra applications which we don’t want to install.

Identity Protection :
Protection against theft of personal information over Cyber Space without consent, usually
for financial gain is known as Identity Protection.
Tips to Prevent Identity Theft
▪ Use strong passwords and PINs & Keep passwords and PINs safe.
▪ Create log-in passwords for all devices.
▪ Beware of phishing scams.

105
▪ Restore old computers to factory settings.
▪ Encrypt your hard drive
▪ Check security when shopping online-check links authenticity which are received from
an unsolicited email.
▪ Take care when posting on social media-Check security settings on social media
accounts, and avoid posting personal information publicly, or publicly "checking in" .
Confidentiality of Information
Allows authorized users to access sensitive and secured data maintains the Confidentiality
of Information.
Tips to Protect Information Confidential
▪ Build strong passwords
▪ Use multifactor authentication- a computer user is granted access only after
successfully presenting 2 or more pieces of evidence.
▪ Masking -The free version of Mask-Me creates an alternate e-mail address whenever
a Web site asks for a user’s e-mail. E-mails from that site can be accessed via a
Mask-Me in-box or forwarded to a user’s regular e-mail account.
▪ Private Browsing & Safe Browsing-Purpose of private browsing is to avoid leaving a
history of one's browsing in the browser history on the computer we are using. Use
updated browser for safe browsing & browse privately.
▪ Encryption-Use https based sites, as HTTPS ensures data security over the network -
mainly public networks like Wi-Fi. HTTP is not encrypted and is vulnerable to
attackers. PGP is a popular program used to encrypt and decrypt email over the
Internet, as well as authenticate messages with digital signatures and encrypted
stored files.
▪ Avoid using public wifi and public computer.

Cyber trolls & Cyber bullying :


Cyber trolling is internet slang for a person who intentionally starts arguments or upsets
others by posting inflammatory remarks. The sole purpose of trolling is angering people.
Purpose – to entertain, to argument, to upset victim, to get attention
Cyber bullying: Saying and/or doing mean things to the person online. It is a harm inflicted
through using the Internet, ICT devices, or mobile phones. Purpose – to get revenge, to
harass & threat, to humiliate
Cyber stalking: Doing research on every aspect of the person’s life.
Cyber harassment: Continuously contacting the person online, even though they don’t want
you to.

Safely accessing web sites: malware, viruses, trojans, adware :


Safely accessing web sites
How to prevent/remove Adware/malware :
▪ Uninstall the malicious programs from Windows
▪ Use antivirus program for malware and unwanted programs
▪ Reset the browser settings to their original defaults
▪ Scan for malicious programs antivirus/antimalware program
106
How to prevent/remove Virus :
▪ Beware of Fake Download Buttons
▪ Use a Secure Browser
▪ Avoid Public Torrent Sites
▪ Don’t Open Email Attachments Forwarded to You
▪ Don’t Use Your PC’s Admin Account
▪ Scan All New Files and Disks
How to prevent/remove Trojan :
▪ Never open unsolicited emails from unknown senders
▪ Avoid downloading and installing programs unless you fully trust publisher
▪ Use firewall software
▪ Use a fully updated antivirus program
Malware : Malware could be computer viruses, worms, Trojan horses, dishonest spyware,
and malicious .
Computer Virus: It is a small piece of software that can spread from one infected
computer to another. It can corrupt, steal, or delete data on your computer/hard drive.
Trojan Horse: can do anything from record your passwords by logging keystrokes (known
as a keylogger) to hijacking your webcam to watch and record your every move.
Computer Worm:A computer worm is a software program that can copy itself from one
computer to another, without human interaction. Spam: unwanted messages in your email
inbox.
Phishing: Phishing are fraudulent attempts by cybercriminals to obtain private
information. For e.g. a message prompt your personal information by pretending that
bank/mail service provider is updating its website.
Spyware: spyware is used to spy on their victims. An e.g. is key logger software that
records a victim’s every keystroke on his or her keyboard.
Adware : unwanted ads shown while surfing internet.
Eavesdropping : is the act of intercepting communications between two points.
E-waste Management: proper disposal of used electronic gadgets
Whenever an electronic device covers up its working life, or becomes non-usable due to
technological advancements or becomes non-functional, it is not used anymore and comes
under the category of e-waste or electronic waste. As the technology is changing day by
day, more and more electronic devices are becoming non-functional and turning into e-
waste. Managing such non-functional electronic devices is termed as e-waste management.
Proper disposal of used electronic gadgets E-waste is a growing problem for us in India. As
an 132 cr strong economy, we produce e- waste in large quantities. It is very important to
dispose off waste in a pragmatic manner.
Ways to dispose off e-waste :
1. Give Back to Your Electronic Companies and Drop Off Points
2. Visit Civic Institutions
3. Donating Your Outdated Technology
4. Sell Off Your Outdated Technology
5. Give Your Electronic Waste to a Certified E-Waste Recycler
107
Indian Information Technology Act (IT Act)
12.9 INFORMATION TECHNOLOGY ACT, 2000 The Information Technology Act, 2000 (also
known as ITA-2000, or the IT Act) is an Act of the Indian Parliament (No. 21 of 2000)
notified on 17 October, 2000. It is the primary law in India dealing with cybercrime and
electronic commerce. The original Act contained 94 sections, divided into 13 chapters and 4
schedules. The laws apply to the whole of India. Persons of other nationalities can also be
indicted under the law if the crime involves a computer or network located in India. The IT
Act is a set of recent legal enactments, currently existing in India, which provide legal
support to computer users against cybercrime. The cyber police works as a detector to
discover cybercrimes. They have the authority in respect of all the offences committed
under TITA (The Information Technology Act, 2000), Central Act No. 21 of 2000, or crimes
related to Intellectual Property Rights. The cyber laws in India and the provisions for legal
action and punishment have been explained in a nutshell in Fig. 12.8.
IT Act, 2000 - Amendments A major amendment was made to the IT Act in 2008. It
introduced Section 66A which penalized sending of “offensive messages”. It also introduced
Section 69, which gave authorities the power of “interception or monitoring or decryption of
any information through any computer resource”. Amendments also contained penalties for
child pornography, cyber terrorism and voyeurism. The Act was passed in December 2008
and came into force in October 2009.
Technology &Society: Gender and disability issues while teaching and using
computers
While there is recognition of the potential of information and communication technologies
(ICT) as a tool for the promotion of gender equality and empowerment of women, a
“gender divide” has also been identified, reflected in the lower number of women accessing
and using ICT as compared to men. Unless this gender divide is specifically addressed,
there is a risk that ICT may exacerbate existing inequalities between women and men and
create new forms of inequality. If, however, the gender dimensions of ICT—in terms of
access and use, capacity building opportunities, employment and potential for
empowerment—are explicitly identified and addressed, ICT can be a powerful catalyst for
political and social empowerment of women, and for promotion of gender equality.
Disability Issues
Disability Issues Clinical categories of cognitive disabilities include autism and Down
syndrome. Less-severe cognitive conditions include the sub-category of so-called learning
disabilities, such as dyslexia (reading) and dyscalculia (mathematics). The functional
disability perspective ignores the medical and behavioral causes of cognitive disabilities and
focuses instead on the abilities and challenges the person with a cognitive disability faces.
Functional cognitive disabilities may involve difficulties or deficits involving:
• Problem-solving • Attention • Memory • Math comprehension • Visual comprehension •
Reading • Linguistic (speech) • Verbal comprehension
The following list shows the benefits that access to ICTs can bring to people within the wide
spectrum of learning disabilities.
These include: • Improved writing• Multimedia• Sensory stimulation.

108
QUESTIONS
1 Mark Questions :
(1) Which of the following is not a type of cybercrime?
(i) Data theft (ii) Forgery
(iii) Damage to data and systems
(iv)Installing antivirus for protection.
(2) What is the most important activity in system hacking?
(i) Information gathering (ii)Cracking passwords
(iii) Escalating privileges (iv) Covering tracks
(3) Which is the following is not done by cyber criminals?
(i) Unauthorized account access
(ii)Mass attack using Trojans as botnets.
(iii) Email spooling and spamming
(iv) Report vulnerability in any system.
(4) Which is the name of the IT law that India is having in the Indian legislature?
(i) India’s Technology (IT) Act, 2000
(ii) India’s Digital Information (DIT) Act, 2000
(iii) India’s Information Technology (IT) Act, 2000
(iv) The Information Act ( IA ) , 2000
(5) The full form of Malware is
(i) Malfunctioned software
(ii) Multipurpose software
(iii) Malicious software
(iv) Malfunctioning of security
(6) Which social network is considered the most popular for social media marketing?
(i) Twitter (ii) Facebook (iii) Linkdin (iv) Whats App
(7) Which of the following is an important aspect of creating blogs and posting content?
(i) Using a witty user name
(ii) Posting at least once a month to the blog
(iii) Social Media Optimization
(iv)All of the above
(8) Which of the following is the correct depiction of Digital Marketing?
(i) E-mail Marketing (ii) Social Media Marketing
(iii)Web Marketing (iv)All of the above
(9) Which of the following is not threat?
(i) Virus (ii) Hacker
(iii) Hard disk failure (iv)Operating system
(10) IT Act of the Indian Parliament notified on ___________
(i) 17 January 2001 (ii) 25 October 2002
(iii)17 October 2000 (iv) 25 April 2000

(11) Sakshi’s classmate sent her a message on Facebook “You are a Loser”. Sakshi is a
victim of:
109
(i) Phishing (ii) Eavesdropping
(iii) Cyber bullying (iv) Trolling
(12) What can happen when you give your personal data (email, address, photos you
post…) in exchange for free apps and services?
(i) Nothing can happen. Your data is not allowed to be passed on to anyone
(ii) It isn’t really used, it’s just compulsory to ask for that information
(iii) When giving your email you’re automatically entered in a lottery where you can
win something
(iv) Everything you do online is of value and is used by companies looking to target
their advertising

2/3 Marks Questions :

Q.1 What is cyber safety?


Ans: Using internet with care and responsibility is called Cyber Safety so that we can keep
our personal information safe.

Q.2 What should you do to protect your identity on Internet?


Ans: The things we can do to protect our identity on Internet.
• Most common solution to this is Private browsing or Anonymous browsing.
• Confidentiality of information.
• Appropriate usage of social networking sites.

Q.3 How do websites track you online?


Ans: Whenever you visit a website, your web browser may reveal your location via your
device‘s IP address.
• It can also provide your search and browsing history etc. which may be used by third
parties, like advertisers or criminals.
• This way website track you. Tracking is generally used by advertising networks to
build up details profiles for pinpoint ad targeting.
• This information is compiled through your web usage patterns, and which websites
generally use for tracking you.
This generally includes-
• IP Address
• Cookies and tracking scripts etc.
• HTTP Referrer
• Super Cookies
• User Agent

110
Q.4 What are cookies? How are they used by websites to track you?
Ans: Cookies are small pieces of information websites can store in your browser.
Cookies can be – 1. First Party Cookies- These are the cookies that store your own log in
id, password, and auto fill information etc. 2. Third Party Cookies: These are the cookies
that websites store to know about your search history and web browsing history so as to
place advertisements as per your interests.

Q.5 What is private browsing? Why is it considered a better way of browsing the Internet?
Ans:
• Anonymous browsers allow users to view websites without revealing personal
information of user.
• It can be sued as a tool for governments, journalists and every security conscious
surfers.
• A popular solution to this is- Private Browsing.
• Incognito browsing open up a version of the browser that will not track your activity.
it is particularly useful if you are entering sensitive data like bank details into your
browser.
• Proxy works as a middleman between your computer and the website you want to
access. Now the tracking website will get the IP address of proxy site.
• Virtual Private Network (VPN) this is a method to add security and privacy to private
and public networks, like WiFi hotspots and Internet. It is originally meant for
business employees working offsite to gain access to shared drives or networks.
Q.6 What is confidentiality of information? How do you ensure it?
Ans : Confidentiality of Information ensures that only authorized users get access to
sensitive and protected data. Best practices used to ensure confidentiality are –
• Use of Firewall
• Control browser settings to block Tracking.
• Browse Privately
• Be careful while posting on internet.
• Ensure safe sites while entering crucial information.
Q.7 Raman wanted to gift his brother a football or a wrist watch. So he searched for many
sports items and wrist watches online. But after that every time he goes online, his web
browser shows him advertisements about sports items and wrist watches.
(a) Why is this happening?
(b) How could have Raman avoided them?
(c) How can Raman get rid of this now?
Ans:
(a) This is happening because third party cookies saved his search preferences and now
websites are posting advertisements based on his preferences.
(b) Robin could have avoided this by privately browsing i.e. opening the web browser in
incognito mode before searching for such things.
(c) Now Robin can delete all the previous history and cookies stored on his computer. This
would stop websites posting advertisements.
111
Q.8 What is a virus? What is anti-virus software?
Ans: A computer virus is a malicious program that self-replicates by copying itself to
another program. In other words, the computer virus spreads by itself into other
executable code or documents. The purpose of creating a computer virus is to infect
vulnerable systems, gain admin control and steal user sensitive data. Hackers design
computer viruses with malicious intent and prey on online users by tricking them. Antivirus
software is a program or set of programs that are designed to prevent, search for, detect,
and remove software viruses, and other malicious software like worms, trojans, adware,
and more.

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


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

Q.10 What type damages can be caused by viruses to your computer?


Ans: Damages caused by Viruses:
• Damage or Delete files.
• Slow down your computer.
• Invade your email programs

Q.11 What is a spam? Why has it become a big Internet issue?


Ans: Spam email is a form of commercial advertising which is economically viable because
email is a very cost-effective medium for the sender. If just a fraction of the recipients of a
spam message purchase the advertised product, the spammers are making money and the
spam problem is perpetuated.

Q.12 What do you understand by PC intrusion?


Ans: Intrusion - Computer Definition. To compromise a computer system by breaking the
security of such a system or causing it to enter into an insecure state. The act of
intruding—or gaining unauthorized access to a system—typically leaves traces that can be
discovered by intrusion detection systems.

Q.13 What is the need for secure passwords?


Ans: A password that is difficult to detect by both humans and computer programs,
effectively protecting data from unauthorized access. A strong password consists of at least
six characters (and the more characters, the stronger the password) that are a combination
of letters, numbers and symbols (@, #, $, %, etc.) if allowed. Passwords are typically case
sensitive, so a strong password contains letters in both uppercase and lowercase. Strong
passwords also do not contain words that can be found in a dictionary

112
Extra Questions :
(1) Describe : (a) Cyber bullying (b) Cyber Stalking
(2) What do you understand by identity theft ?
(3) What measures should one take to avoid and maintain confidentiality of personal
information ?
(4) Nivedita has recently shifted to new city and new school. She does not know many
people in her new city and school. But all of a sudden, someone is posting negative,
demeaning comments on her social networking profile, school site’s forum etc.
She is also getting repeated mails from unknown people. Every time she goes online,
she finds someone chasing her online. (a) What is this happening to Nivedita? (b)
What action should she taken to stop them?
(5) What is data privacy ? Websites that you visit collect what type of information about
you ?
(6) What is antivirus software ?
(7) What is the need for secure password ?
(8) What is online fraud ?
(9) What are intellectual property rights ?
(10) what is digital property ? Give some examples of digital properties.
(11) What are common gender and disability issues faced while teaching / using
computers in class rooms ?
(12) What operations can be carried out for proper E-Waste Process ?

113

You might also like