You are on page 1of 180

XI COMPUTER

SCIENCE
(PYTHON) GUIDE Latest Guide for CBSE
Computer Science (Python)
Class 11th students.
ARCHIT GULIA
B. Tech

Question and Answer Guide


XI Computer Science Guide
Table of Contents

1 Computer overview and its Basics .......................................................................................... 4


1.1 Very Short Answer Type Questions ................................................................................. 4
1.2 Short Answer Type Questions – I [2 mark each].............................................................. 5
1.3 Short Answer Type Questions – II [3 mark each]............................................................. 8
1.4 Long Answer Type Questions [4-5 mark each]................................................................. 8
2 Generations And Evolution Of Computers Quick Review ........................................................ 11
2.1 Very Short Answer Type Questions [1 mark each] ....................................................... 11
2.2 Short Answer Type Questions – I [2 mark each]............................................................ 13
2.3 Short Answer Type Questions – II [3 mark each]........................................................... 16
2.4 Long Answer Type Questions (4-5 marks each) .............................................................. 17
3 Booting............................................................................................................................... 21
3.1 Short Answer Type Questions – I [2 mark each]............................................................ 21
4 Software Basics ................................................................................................................... 21
4.1 Very Short Answer type Questions [1 mark each] .......................................................... 21
4.2 Short Answer type Questions – I [2 mark each] .............................................................. 23
4.3 Short Answer type Questions – II [3 mark each] ............................................................. 25
4.4 Long Answer type Questions [4-5 mark each] ................................................................ 26
5 Number System and Its Conversion ...................................................................................... 27
5.1 Short Answer Type Questions-II.................................................................................... 27
5.2 Long Answer Type Questions (4 marks each] ................................................................. 30
6 Internal Storage Encoding Of Characters............................................................................... 34
6.1 Short Answer Type Questions-II.................................................................................... 34
7 Microprocessor ................................................................................................................... 35
7.1 Very Short Answer Type Questions (1 mark each) .......................................................... 35
7.2 Short Answer Type Questions-II (3 mark each)............................................................... 36
8 Memory Concepts............................................................................................................... 39
8.1 Very Short Answer Type Questions (1 mark each) .......................................................... 39
8.2 Short Answer Type Questions-I (2 mark each)................................................................ 40
8.3 Short Answer Type Questions – II (3 mark each) ............................................................ 41
9 General Concepts Of Programming....................................................................................... 43

https://onlinestudytest.com/
9.1 Very Short Answer Type Questions (1 mark each) .......................................................... 43
9.2 Short Answer Type Questions-I (2 marks each) .............................................................. 44
9.3 Long Answer Type Questions (4 marks each) ................................................................. 45
10 Documentation And Programming Maintenance ............................................................... 46
10.1 Very Short Answer Type Questions (1 mark each) .......................................................... 46
10.2 Short Answer Type Questions-I (2 marks each) .............................................................. 46
10.3 Long Answer Type Questions (4 marks each) ................................................................. 47
11 Problem Solving Methodologies ....................................................................................... 50
11.1 Very Short Answer Type Questions (1 mark each) .......................................................... 50
11.2 Short Answer Type Questions-I (2 marks each) .............................................................. 51
11.3 Long Answer Type Questions (4 marks each) ................................................................. 51
12 Algorithms & Flowcharts.................................................................................................. 53
12.1 Short Answer Type Questions-II (3 marks each) ............................................................. 53
12.2 Short Answer type Questions [2 mark each] ................................................................. 56
12.3 Long Answer type Questions [4 mark each] ................................................................... 57
13 Python Programing.......................................................................................................... 60
13.1 Very Short Answer type Questions [1 mark each] .......................................................... 60
13.2 Short Answer type Questions [2 mark each] ................................................................. 62
13.3 Long Answer type Questions [4 mark each] ................................................................... 65
14 Flow chart and python basic............................................................................................. 72
14.1 Very Short Answer Type Questions (1 marks each)......................................................... 72
14.2 Short Answer Type Questions (2 marks each) ................................................................ 76
14.3 Long Answer Type Questions (5 marks each) ................................................................. 78
15 Python Programming....................................................................................................... 85
15.1 Very Short Answer Type Questions (1 marks each)......................................................... 85
15.2 Short Answer Type Questions (2 marks each) ................................................................ 91
15.3 Long Answer Type Questions (4 marks each) ................................................................102
16 Conditional and Looping Constructs.................................................................................116
16.1 Very Short Answer type Questions [1 mark each] .........................................................116
16.2 Short Answer type Questions [2 mark each] ................................................................119
16.3 Long Answer type Questions [4 mark each] ..................................................................124
17 Strings............................................................................................................................137
17.1 Very Short Answer type Questions [1 mark each] .........................................................137
17.2 Short Answer type Questions [2 mark each] ................................................................140
17.3 Long Answer type Questions [4 mark each] ..................................................................145
18 Lists ...............................................................................................................................153

https://onlinestudytest.com/
18.1 Very Short Answer Type Questions (1 marks each)........................................................153
18.2 Short Answer Type Questions (2 marks each) ...............................................................155
18.3 Long Answer Type Questions (4 marks each) ................................................................159
19 Tuples............................................................................................................................165
19.1 Very Short Answer type Questions [1 mark each] .........................................................165
19.2 Short Answer type Questions [2 mark each] ................................................................165
19.3 Long Answer type Questions [4 mark each] ..................................................................166
20 Dictionaries ....................................................................................................................172
20.1 Short Answer type Questions [2 mark each] ................................................................172
20.2 Long Answer type Questions [4 mark each] ..................................................................173

e-book – all right reserved

Edition: 2021-2022

Archit Gulia, B. Tech

https://onlinestudytest.com/
Super Success Institute, Muzaffarnagar

1 COMPUTER OVERVIEW AND ITS BASICS

1.1 VERY SHORT ANSWER TYPE QUESTIONS

Question 1:
Which part interprets program instructions and initiate control operations ?
Аnswer:
Control unit.

Question 2:
What is primary memory ?
Аnswer:
Primary memory : This is the storage section of computer which is used to store data or instructions
or both for processing purpose.

Question 3:
What is RAM ?
Аnswer:
RAM : RAM stands for Random Access Memory.
This is the main memory of computer used to retain user’s instructions and data for processing
purpose. This is volatile in nature .

Question 4:
What is ROM ?
Аnswer:
ROM : ROM stands for Read Only Memory. ROM applies to semiconductor memory whose contents
cannot be altered, once they have been set. So non-volatile in nature.

Question 5:
What is PROM ?
Аnswer:
PROM : PROM stands for Programmable Read Only Memory. A control memory in which stored
contents can be altered once after they have been set.

Question 6:
What is EPROM ?
Аnswer:
EPROM : EPROM stands for Erasable Programmable Read Only Memory. It can be erased and
programmed with a special type of equipment. If it is exposed to ultraviolet light, it allows data to be
erased and reprogrammed.

https://onlinestudytest.com/
Question 7:
What is EEPROM ?
Аnswer:
EEPROM : EEPROM stands for Electrically Erasable Programmable Read Only Memory. This type of
ROM can be erased and programmed with the help of electric pulse .

Question 8:
Give three examples of both input devices and output devices.
Аnswer:
Input Devices :

Keyboard

Mouse

Scanner
Output Devices :

Monitor

Speaker

Printer

1.2 SHORT ANSWER TYPE QUESTIONS – I [2 MARK EACH ]


Question 1:
Name the components of a computer system.
Аnswer:
The computer system consists of two parts :
Hardware.

Software.
Question 2:
Explain functional components of a computer system.
Аnswer:
A computer system contains many different objects such’ as a CPU, memory, disks, etc.
These all must be connected for the system to function.
Question 3:
Explain volatile and non-volatile memory.
Аnswer:
The memory is which data is lost when power is removed is called volatile memory. The
memory is which data is not lost when power is removed is called non-volatile memory.
Question 4:
What are the basic units of computer ? Give two names of sub-units of CPU and also give

https://onlinestudytest.com/
the functions of each unit
Аnswer:
The computer consists of the following basic units :

Input unit

Central Processing Unit (CPU)


Output unit

Memory unit
The CPU has two sub units :
(A) Control Unit (CU) : Control unit controls the entire operation being carried out.
(B) Arithmetic Logic Unit (ALU) : It performs the
arithmetic and logical operations.
Question 5:
What is data ? What is the output of data processing system ?
Аnswer:
Data is derived from a word ‘datum’ i.e. a fact. Data is a collection of raw facts and figures.
Data processing system is a computer based system which converts data into information.
Question 6:
What is the difference between data and information ?
Аnswer:
Data : Data means facts and figures. Data is unprocessed information. For example :
Siddharth, 40400195, M.
Information : Information means what we get after processing data i.e., processed data. In
other words, information is processed data.
For example :

NAME ROLL NUMBER GENDER

Siddharth 40400195 M

Question 7:
What is the function of memory ? What are the types of it ?
Аnswer:
The memory stores data temporarily or permanently.
Computer memory is of two types :
Primary Memory (Main Memory) : The primary or main memory holds the data and
information during processing. It holds data temporarily, as we switch off computer the
information vanishes.
For example : RAM.

https://onlinestudytest.com/
Secondary Memory : It can store data perma-nently on the computer but it cannot process
data. It is meant for permanent storage of data and information.
For example : CD-ROM, DVD-ROM.
Question 8:
What is a bit ? How bit, byte and nibbles are related to each other ?
Аnswer:
Bit (Binary Digit) : A bit is the smallest elementary unit of memory, which can store one
binary signal either 0 or 1. A group of 8 bits is called a byte. A group of 4 bits is called a
nibble.
Question 9:
What do you mean by Input Unit ? Give the examples of Input Unit.
Аnswer:
Input Unit : An input unit takes the input and converts it into binary form so that it can be
understood by CPU for processing accordingly. For example : Keyboard, Mouse, Joystick,
Scanner, Camera, Magnetic Ink Character Reader (MICR), Bar Code Reader (BCR) etc.
Question 10:
What is the function of CPU in a computer system ?
Аnswer:
The CPU is the control center for a computer. It controls, directs and manages the entire
performance of the computer. The CPU has two different parts which are responsible for
different functions.
Question 11:
What do you understand by IPO cycle ?
Аnswer:
IPO cycle refers to the Input Process Output cycle where every operation undergoes the
phases namely input, process and output.
Question 12:
Differentiate between source program and object program.
Аnswer:
Source Program : A program which is written by the programmer in high level language or in
assembly language, which is to be converted into machine language by the compiler is
known as source program.
Object Program : The source program is converted into machine level instruction for
execution. This converted program (in the machine language) is known as an object
program.
Question 13:
Mention any two limitations or weaknesses of a computer ?
Аnswer:
Any two limitations or weaknesses of a computer system are as follows :

https://onlinestudytest.com/
Lack of intelligence/Lack of decision making power : No doubt, computer is a powerful
machine but cannot decide on its own that what it is supposed to do as a machine. This is a
serious limitation of a computer system and it is an artificially intelligent machine.
Need of special language : A computer can understand only the binary language, in which
the information is represented in terms of only two symbols, namely 0 and 1. This is not the
natural language of human beings and learning of the binary language is not an easy task.

1.3 SHORT ANSWER TYPE QUESTIONS – II [3 MARK EACH ]


Question 1:
Explain Primary Memory Unit.
Аnswer:
Memory Unit stores the data, instructions, intermediate results and output temporarily,
during the processing of data. This memory is also called the main memory or primary
memory of the computer. The input data that is to be processed is brought into the main
memory before processing.
Question 2:
Explain what is a computer and write its advantage.
Or
Define computer. Give it’s characteristics.
Аnswer:
A computer is an electronic device which can perform various operations correctly and fast.
For example data processing, huge calculations etc. Characteristics of computer :
Speed : Its speed is very fast. A modern computer can execute millions of instructions in one
second.

Accuracy : A computer can give accurate results up to 20 to 30 places of decimal.

High storage capacity : A computer can store large amount of data in very small space.
Versatility : A computer c3n do different types of tasks like data processing, graphics, audio
and visual effects.
Repetitive: A computer makes no mistake in repeating anything as many times.

1.4 LONG ANSWER TYPE QUESTIONS [4-5 MARK EACH ]


Question 1:
Explain four characteristics of computer.
Аnswer:
Speed, accuracy, diligence, storage capability and versatility are some of the key
characteristics of a computer. A brief overview of these characteristics are :

https://onlinestudytest.com/
Speed : The computer can process data very fast, at the rate of millions of instructions per
second. Some calculations that would have taken hours and days to complete otherwise,
can be completed in a few seconds using the computer.
Accuracy : Computer provides a high degree of accuracy. For example : the computer can
accurately give the result of division of any two numbers up to 30 decimal places.
Diligence : When used for a longer period of time, the computer does not get tired or
fatigued. It can perform long and complex calculations with the same speed and accuracy
from the start till the end.
Storage Capability : Large volumes of data
and information can be stored in the computer and also retrieved whenever required. A
limited amount of data can be stored temporarily in the primary memory. Secondary
storage devices like DVD and compact disk can store a large amount of data permanently.
Question 2:
Compare human beings with computer.
Or
What is the difference between man and computer ?
Аnswer:
A computer is an electronic device which can process data to give meaningful information
with the help of a set of instructions called ‘Program’.
In computer, following are the advantages as compare to man :

It is faster as compared to human beings

It is more accurate in comparison to human being. “


It can store a huge amount of information that can be retrieved instantly as compared to
the human beings.

It is immune to boredom and tiredness.

It is versatile, can do different types of work with same accuracy and speed.

A computer has following disadvantages :


A computer does not have its own intelligence that a man has.
A computer cannot work without power
(electric or battery)
Question 13:
Expand the following terms :

CPU,

ALU,
VLSI,

https://onlinestudytest.com/
MSI,

LSI,
SSI,

IC,

IPO,

HLL,
MB.

Аnswer:

CPU —> Central Processing Unit

ALU —> Arithmetic Logic Unit


VLSI —> Very Large Scale Integration

MSI —> Medium Scale Integration

LSI —> Large Scale Integration

SSI —> Small Scale Integration


IC —> Integrated Circuits

IPO —> Input Process Output

HLL —> High Level Language


MB —> Mega Byte

https://onlinestudytest.com/
2 GENERATIONS AND EVOLUTION OF COMPUTERS QUICK REVIEW

2.1 VERY SHORT ANSWER TYPE QUESTIONS [1 MARK EACH ]


Question 1:
Write the name of the first calculating device.
Аnswer:
Calculating machine ABACUS is not called a computer, it can almost be called a computer.
Question 2:
Write the name of first device for multiplication.
Аnswer:
Napier’s Bone was a mechanical device built for the purpose of multiplication in 1617 A.D.
by an English mathematician John Napier.
Question 3:
How many generations of computer exist ?
Аnswer:
There are five generations of computer.
Question 4:
What is the time period for first generation of computer ?
Аnswer:
First Generation is from 1940 to 1956 (used Vacuum Tubes).
Question 5:
What is the time period for second generation of computer ?
Аnswer:
Second Generation is from 1956 to 1963 (used Transistors).
Question 6:
What is the time period for third generation of computer ?
Аnswer:
Third Generation is from 1964 to 1971 (used Integrated Circuits).
Question 7:
What is the time period for fourth generation of computer ?
Аnswer:
Fourth Generation is from 1971 to present (used Microprocessors).

https://onlinestudytest.com/
Question 8:
What difference does the 5th generation computer have from other generation computers
?
Аnswer:
Artificial intelligence.
Question 9:
Which computer language is used for artificial intelligence ?
Аnswer:
PROLOG.
Question 10:
The binary system uses powers of_____ ?
Аnswer:
2.
Question 11:
Who is known as the Father of Computers ?
Аnswer:
Charles Babbage is known as the Father of Computers.
Question 12:
Who was the first lady programmer ?
Аnswer:
Lady Ada Lovelace.
Question 13:
In which generation vacuum tubes were used ?
Аnswer:
Vacuum tubes were used in first generation computers.
Question 14:
In which generation transistors were used ?
Аnswer:
Transistors were used in second generation computers.
Question 15:
Who introduced the concept of punched cards ?
Аnswer:
Herman Hollerith introduced the concept of punched cards.
Question 16:
Name the machine developed by Blaise Pascal ?
Аnswer:
The machine developed by Blaise Pascal is Pascaline.
Question 17:
Expand ENIAC.

https://onlinestudytest.com/
Аnswer:
ENIAC stands for Electronic Numerical Integrator And Computer.
Question 18:
Expand EDSAC.
Аnswer:
EDSAC stands for Electronic Delay Storage Automatic Computer.
Question 19:
Expand UNIVAC.
Аnswer:
UNIVAC stands for Universal Automatic computers.
Question 20:
Give two examples of fourth generation computers.
Аnswer:
Two examples of fourth generation computers are home computers and personal
computers.

2.2 SHORT ANSWER TYPE QUESTIONS – I [2 MARK EACH ]


Question 1:
Why is analytical engine often called the pioneer computer ?
Аnswer:
The analytical engine was the first design to introduce the basic architecture of modern
computer i.e., CPU storage area, memory & input/ output device. Therefore, it is called the
pioneer computer.
Question 2:
Name the two machines proposed by Charles Babbage.
Аnswer:
The two machines proposed by Charles Babbage are :

Difference Engine

Analytical Engine.
Question 3:
When and who invented vacuum tubes ?
Аnswer:
Lee Dee Forest invented vacuum tubes in 1906.
Question 4:
Give the – classification of the mechanical calculating devices.
Аnswer:
Mechanical calculating devices can be classified into following categories :
Manual Calculating Devices.

https://onlinestudytest.com/
Semi-automatic Calculating Devices.
Question 5:
Name two manual calculating devices.
Аnswer:
The two manual calculating devices are as follows:

ABACUS
Napier Bones.
Question 6:
Name any two semi-automatic calculating devices.
Аnswer:
Two semi-automatic calculating devices are as follows :

Pascaline.

Difference Engine.
Question 7:
What is ABACUS ? Explain.
Аnswer:
The ABACUS is a mechanical device which has a wooden frame. An ABACUS consists of
beads divided into two parts which are movable on the rods in two parts. The device was
used for doing calculations like addition, multiplication, etc. Chinese have been using
ABACUS for large calculations. This device is still used for calculations in countries like China,
Japan and Russia.
Question 8:
What are the advantages of vacuum tubes ?
Аnswer:
Vacuum tubes have the following advantages :
Vacuum tubes were the only electronic components available during those days which
made possible the invention of electronic digital computers.
These computers were the fastest calculating
devices of that time. They could perform computations in milliseconds.
Question 9:
When were the transistors developed ?
Аnswer:
Transistors were developed during second generation. A transistor is smaller and more

https://onlinestudytest.com/
reliable substitute to the vacuum tubes.

Question 10:
Write a short note on Charles Babbage.
Аnswer:
Charles Babbage was a British mathematician. In 1833, he designed a mechanical computer
known as Analytical Engine. The machine had the ability to handle large amount of data and
process it at a high speed. Charles Babbage is known as the ‘Father of Computers’ because
he introduced the idea of storing and reading information before processing.
Question 11:
Write a short note on Lady Ada Lovelace.
Аnswer:
The Lady Ada Lovelace was the daughter of the famous poet Byron. She is known as the
‘First Lady Computer Programmer’ in computer history. The concept of instructions given to
Analytical Engine in the form of 0’s and l’s was given by her.
Question 12:
Write a short note on Pascal’s Adding Machine.
Аnswer:
In 1692 Blaise Pascal, a Frenchman, invented a calculating machine called Pascaline. The
machine was made up of gears and was used for adding numbers quickly. He was credited
for building the first mechanical calculating machine. The design of his machine was ahead
of its time.
Question 13:
What are the disadvantages of third generation computers ?
Аnswer:
The disadvantages of third generation computers are as follow :

Air conditioning is required in many cases.

Highly sophisticated technology required for manufacturing of IC chips.


Question 14:
What is the main disadvantage of using fourth generation computers ?
Аnswer:
The main disadvantage of using fourth generation
computers is that the highly sophisticated technology required for manufacturing of VLSIC
(Very Large Scale Integration Chip).

https://onlinestudytest.com/
2.3 SHORT ANSWER TYPE QUESTIONS – II [3 MARK EACH ]
Question 1:
Explain the evolution of computing device.
Аnswer:
The computing devices have evolved from simple mechanical machines like ABACUS,
Napier’s Bones, Slide Rule, Pascal’s Adding and Subtraction Machine, Leibniz’s Multiplication
and Dividing Machine, Jacquard Punched Card System, Babbage’s Analytical Engine and
Hallerith’s Tabulating Machine, to the first electronic computer.
Question 2:
Explain first generation computers.
Аnswer:
First generation computers were vacuum tubes based machines. These were large in size,
difficult to operate and instructions were to be written in machine language. Their
computation time was in milliseconds.
Question 3:
Explain second generation computers.
Аnswer:
Second generation computers were transistor based machines. They used the stored
program concept. Programs were written in assembly language. They were smaller in size,
less expensive and required less maintenance than the first j generation computers. The
computation time was j in microseconds.
Question 4:
Explain third generation computers.
Аnswer:
Third generation computers were characterized by the use of IC. They consume less power
and required low maintenance compared to their predecessors. High-level languages were
used for programming. The computation time was in nanoseconds. These computers were
produced commercially.
Question 5:
What do you mean by fourth generation computers ?
Аnswer:
Fourth generation computers used micro-processors which were designed using the LSI and
VLSI technology. The computers became small,
portable, reliable and cheap. The computation time is in Pico-seconds. They became
available both to the home user and for commercial use.
Question 6:
Explain fifth generation computers.
Аnswer:
Fifth generation computers are capable of learning and self-organization. These computers
use SLSI chips and have large memory requirements. They use parallel processing and are
based on Artificial intelligence. The fifth generation computers are still being developing.

https://onlinestudytest.com/
Question 7:
Write the classification of computer based on their sizes and types.
Аnswer:
Computers are broadly classified as micro-computers, mini computers, mainframe
computers, and supercomputers based on their sizes and types.
Question 8:
Explain microcomputers.
Аnswer:
Microcomputers are small, low-cost and standalone machines. Microcomputers include
desktop computers, notebook computers or laptops, netbooks, tablet computer, handheld
computer and smart phones.
Question 9:
Explain mainframe computers.
Аnswer:
Mainframe computers are multi-user, multi-programming and high performance computers.
They have very high speed, very large storage capacity and can handle large workloads.
Mainframe computers are generally used in centralized databases.
Question 10:
What do you mean by supercomputers ?
Аnswer:
Supercomputers are the – most expensive machines, having high processing speed capable
of performing trillions of calculations per second. The speed of a supercomputer is
measured in FLOPS. Super-computers find applications in computing intensive tasks.

2.4 LONG ANSWER TYPE QUESTIONS (4-5 MARKS EACH )


Question 1:
Write features of first generation of computers.
Аnswer:
First generation of computers :
The main component of first generation of computers were vacuum tube.

The size of computers were very big.

Huge consumption of electricity (approx. 60 KW).


It was a giant machine 30 x 50 feet long, weighed 30 tons, containing 20,000 values &
70,000 resistors.
Programming language was machine level. Example : ENIAC, UNIVAC-I, EDSAC etc.
Question 2:
Write features of second generation of computers and give example.
Аnswer:
Second generation of computers :

https://onlinestudytest.com/
The main component of second generation of computers was transistor instead of vacuum
tube.

The size was still big but small in comparison to 1st generation.

Electricity consumption was lower.


They were faster and more reliable in comparison to the computers of 1st generation.

Core memory was developed.


Programming languages used were FORTRAN, COBOL, ALGOL, SNOBOL etc.
Examples : IBM 1401, IBM 1620, IBM 7094, UNIVAC 1108, CDC 1604, CDC 3600.
Question 3:
Write the features of third generation of computers.
Аnswer:
Third generation of computers :
The main component of third generation computers were integrated circuits(IC’s) known as
chips.
More reliable computers, less expensive and faster in comparison to previous generations.
Examples : IBM-360 Series, ICL1900 Series, Honey well Model 316.
Question 4:
Write features of fourth generation of computers.
Аnswer:
Fourth generation of computers :
Main component for this generation computers are VLSIC (Very Large Scale Integrated
Circuits), known as microchips consisting of a packing of about 50000 transistors.

Computer cost reduced up to a great extent.

Faster access facility and processing speed.

Many powerful operating systems were developed.


Multimedia computers are in existence.

Question 5:
What do you mean by super computers ? What was the purpose to develop super
computers ?
Аnswer:
Super Computers : Super computers are the most powerful computers among digital
computers. A super computer consists of several processors running together making them
immensely faster and powerful. These computers are capable of handling ’v 2 amounts of
data for calculation and storage A supercomputer has the capability equal to that of 40,000
microcomputers.

https://onlinestudytest.com/
These computers are mainly used in areas like weather forecasting, nuclear science
research, aerodynamic modeling, meteorology etc.
Examples : CRAY X-MP/14, CDC – 205, ETA GF – 10, NEC SX – 2, PARAM, ANURAG.
PARAM and ANURAG are super computers produced by India and exported to many
European countries.
Question 6:
How can we define computers according to technology ? What are the difference between
them ?
Or
What are the types of computers ? Define them.
Аnswer:
There are three types of computers according to the technology. These are :
(i) Digital Computers
(ii) Analog Computers
(iii) Hybrid Computers
Digital Computers : The computer which works on the digital signals or deals with discrete
digital signals is called digital computer.
Analog Computers : The computer which works on physical analogies or physical quantities
is called analog computer. It is a special purpose computer used to design specific problems.
Hybrid Computers : A computer which has the features of both analog and digital computers
is called hybrid computer.
Question 7:
Write a short note on Herman Hollerith.
Аnswer:
In 1889, Herman Hollerith invented a machine which worked on electricity for the first time.
One machine was used for recording data and the other one was used for doing calculations
on that recorded data. His machine was capable of reading both numbers and letters.
Herman Hollerith introduced the concept of punched cards. Hollerith invented the
tabulating machine that could read Information from punched cards.

Question 8:
What are mainframe computers ? Mention the main characteristics of mainframe
computers ?
Аnswer:
Mainframe computers are very large computers available in different models, capacities and
prices. The main characteristics of mainframe computers are as follows :

Qualified operators and programmers are required for their operation.

They support a wide range of peripherals.

They have large storage capacities.

https://onlinestudytest.com/
They can make the use of a wide variety of software.

These computers are mainly used in large commercial and government organizations.
Question 9:
Discuss the mini computers with their main characteristics.
Аnswer:
Mini computers were introduced in the 1960’s. They have less capacity to manipulate and
store data than mainframe computers.
Some of the main characteristics of mini computers are as follows :

They offer a limited range of peripherals.


Limited software can be used.

There is a facility for direct of ration of the machine by the end user.

Air conditioning is not necessary and is provided in many cases for dust control.

They are widely used for data processing.


Question 10:
What are micro computers ? Mention the characteristics of n microcomputers/personal
computers.
Аnswer:
Micro computers/Personal computers are computers that use one or more
microprocessors, and contain storage and input/output facilities, usually housed within a
single enclosure. These have revolutionized the computer industry because of their size and
cost.
Some of the characteristics of micro-Computers/ Personal computers are as follows :

They are cheap and easy to use.


They have limited input and output capacities.

They have low storage capacity.

Visual Display Unit (VDU) or printer is used to get the output.

https://onlinestudytest.com/
3 BOOTING

3.1 SHORT ANSWER TYPE QUESTIONS – I [2 MARK EACH ]


Question 1:
What is booting ? What are the types of booting ?
Аnswer:
Booting is the process of restarting a computer or its operating system software. It starts
with switching on the computer and ends when the operating System is loaded in main
memory and the computer is ready to take commands from the user.
Booting is of two types :

Cold booting : When the computer is started after having been switched off.
Warm booting : When the operating system alone is restarted after a system crash or freeze

4 SOFTWARE BASICS

4.1 VERY SHORT ANSWER TYPE QUESTIONS [1 MARK EACH]


Question 1:
Name any two popular word processing software.
Answer:
Two popular word processing software are :

OO-writer

MS-word
Question 2:
Expand OS.
Answer:
OS stands for Operating System.
Question 3:
Name the categories in which the software are classified.
Answer:
Software are classified into following two categories :
System software

https://onlinestudytest.com/
Application software
Question 4:
Name the various categories of system software.
Answer:
System software are divided into following two categories :

Operating system
Language processor
Question 5:
Expand DBMS.
Answer:
DBMS stands for Data Base Management System.
Question 6:
What is the full form of DTE
Answer:
DTP stands for Desk Top Publishing.
Question 7:
Expand IOCS.
Answer:
IOCS stands for Input-Output Control System.
Question 8:
Write the name of the part of machine level instruction, which tells the central processor
what has to be done.
Answer:
Operation code.
Question 9:
A system program that combines the separately compiled modules of a program into a form
suitable for execution.
Answer:
Linking loader.
Question 10:
Which system software does the job of merging the records from two files into one ?
Answer:
Utility program.
Question 11:
A computer cannot “boot” if it does not have the____.
Answer:
Operating system.

https://onlinestudytest.com/
Question 12:
Write the name of the system program that sets up an executable program in the main
memory ready for execution.
Answer:
Loader.
Question 13:
What do you mean by FIFO algorithm ?
Answer:
It means execute first job that is entered first in the queue. It stands for First In First Out
algorithm. 1
Question 11:
What do you mean by bug ?
Answer:
A bug is logical error in a program.

4.2 SHORT ANSWER TYPE QUESTIONS – I [2 MARK EACH ]


Question 1:
Define Software. Give its types.
Answer:
Software represents the set of programs that controls the operation of a computer system
and utilizes hardware.
Software are of two types :

System Software
Application Software.
Question 2:
What is system software ? What are its components ?
Answer:
System Software : The software which controls the internal operations of the computer and
creates an interface with software and hardware is known as system software.
The system softwares can be divided into two categories :
Operating system

Language processors
Question 3:
What do you mean by operating system ?
Answer:
Operating System is a software program which manages the hardware and software

https://onlinestudytest.com/
resources and links them. It creates an interface between hardware and software. It is a
bridge between the hardware and the software.
Question 4:
What do you mean by graphics software ?
Answer:
Graphics software is the application software which can manipulate images, known as
graphics software. The graphics software can incorporate images, text, sound, animation
and video sequence.
Question 5:
Name the various categories of application software.
Answer:
Application software can be divided into following three categories :

Packages

Utilities
Customized Software
Question 6:
Name the major categories of packages.
Answer:
Following are the major categories of packages :

Word processing software

Database management software

Spreadsheets
Desktop publishing software

Graphics, multimedia and presentation applications.


Question 7:
Explain utility program.
Answer:
A program that performs a specific task related to the management of computer functions,
resources, or files as password protection, memory management, virus protection, and file
compression.
Question 8:
Give examples of utility programs.
Answer:
some examples of utility programs are :

Virus scanners

Disk defragmenters

https://onlinestudytest.com/
Encryption utilities

Backup software

4.3 SHORT ANSWER TYPE QUESTIONS – II [3 MARK EACH ]


Question 1:
Explain operating system and utility system software.
Answer:
Operating systems are essential for running a computer. However, as part of the operating
system, there are often other programs which are not essential to the running of the
computer. These are known as utilities. If they were not there, they would not affect the
working of the computer. 3
Question 2:
How does the application software and operating system work together ?
Answer:
When we use a program, it sends commands to the computer. But the computer is just a
heap of nuts and bolts and computer chips. It can’t understand the commands by itself. So
the operating system catches the commands and tells the computer what you want it to do.
Question 3:
What are open source software ? Give its examples.
Answer:
Open source software is that computer software whose source code is made available with
a license in which the copyright holder provides the rights to read, change and distribute the
software for any purpose. For example : Linux, Unix etc.
Question 4:
What are the criteria of software development industry to consider a software as open
source software ?
Answer:
For a software to be considered as open source software it should meet certain criteria,
they are :

It should be available free or at low cost.

Source code must be included.

Everyone should be allowed to edit the source code.


Modified versions can be redistributed.
Question 5:
What are Freeware ? Give its examples.
Answer:
It generally refers to the software which re available for use at no cost or for an optional fee
to avail all the functions of the software. For example : WordPad, Paint, Notepad etc.

https://onlinestudytest.com/
Question 6:
What are Shareware ? Give its examples.
Answer:
It is that software which is made available with
a right to redistribute copies. It is also known as “Try Before You Buy.” For example :
wondershare, Kaspersky antivirus etc.
Question 7:
What are Proprietary Software ? Give its examples.
Answer:
It is a software which is owned by an individual or a company. Their source code is always
kept secret. For example : Microsoft windows, adobe flash player etc.

4.4 LONG ANSWER TYPE QUESTIONS [4-5 MARK EACH ]


Question 1:
What are the functions of a file system ?
Answer:
The major functions of a file system are given below :
It provides file naming freedom to the users and permits controlled sharing of files.

It provides long and short term storage of files.

It provides security against loss of information due to system failure.


It also provides file recovery modules, if required. [1 mark for each point]
Question 2:
Define following with examples :

Word processing packages

Spreadsheet packages
DBMS packages.
What are the functions of a file system ?
Answer:
Word processing packages : It is a software package that processes textual matter created
to a right to redistribute copies. It is also known as “Try Before You Buy.” For example :
wondershare, Kaspersky antivirus etc.
organize an error free document. Some popular word processing packages are Wordstar,
MS- WORD, Word Perfect, Softword etc.
Spreadsheets packages : It is a software package that accepts data in a tabular form i.e., in
rows and columns and allows the user to manipulate, calculate, edit and analyze the data in
the required manner. Some popular spreadsheet packages are, LOTUS 1-2-3, MS-Excel and
Quattro Pro.

https://onlinestudytest.com/
Data base management software (DBMS)
packages : A DBMS package is a software package which manages the different database
with home bulk information in the form of data. It can manage, add, delete and modify the
database. Examples : FoxPro, FOXBase, SYBase, Dbase IV & MS-Access etc.

5 NUMBER SYSTEM AND ITS CONVERSION

5.1 SHORT ANSWER TYPE QUESTIONS-II


Question 1:
Explain octal and hexadecimal number.
Answer:
Octal (base 8) was previously a popular choice for representing digital circuit numbers in a form that
is more compact than binary. Octal is sometimes abbreviated as oct. Octal counting goes as :
0,1, 2, 3,4, 5, 6, 7,10,11,12,13,14,15,16,17,20, 21 and so on.
Hexadecimal (base 16) is currently the most popular choice for representing digital circuit numbers
in a form that is more compact than binary. Hexadecimal numbers are sometimes represented by
preceding the value with ‘Ox’, as in 0x1 B84. Hexadecimal is sometimes abbreviated as hex.
Hexadecimal counting goes :
0,1,2, 3,4,5, 6, 7, 8,9, A, B, C, D, E, F, and so on.

Question 2:
Explain decimal and binary number.
Answer:
Decimal (base 10) is the way most human beings represent numbers. Decimal is sometimes
abbreviated as dec. Decimal counting goes :
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18 and so on.
Binary (base 2) is the natural way most digital circuits represent and manipulate numbers. Binary
numbers are sometimes represented by preceding the value with ‘Ob’, as in Ob1O11. Binary is
sometimes abbreviated as bin.
Binary counting goes as : 0,1,10,11,100,101,110,
111, 1000, 1oo1, 1010,1011, 11oo, 1101, 1110, 1111,10000,10001 and so on. 3

Question 3:
Convert (17.35) 10 to binary form.

https://onlinestudytest.com/
Answer:

Now we have to convert the fractional part, that means the part after decimal:

Question 5:
Convert (39286)10 to octal form.

Answer:

(39286) 10 = (114566) 8

Question 6:
Convert (0.2) 10 to the binary form.

Answer:

(0.2) 10= (0.0011) 2

https://onlinestudytest.com/
Question 7:
Convert (423.03125)10 to octal form.
Answer:

second we convert the fraction part by multiplying fraction part by 8 repeatedly.

Question 8:
Fill the correct entry. 3

Decimal Binary Octal

0 000 0

1 001 1

2 ? 2

3 Oil 3

4 100 4

5 101 5

? 110 6

7 ? ?

Answer:

Decimal Binary Octal

0 000 0

1 001 1

2 010 2

3 Oil 3

https://onlinestudytest.com/
4 100 4

5 101 5

6 110 6

7 111 7

5.2 LONG ANSWER TYPE QUESTIONS (4 MARKS EACH ]


Question 1:
Do as directed :

(a) Convert the Decimal number 781 to its Binary equivalent.


(b) Convert Binary number 101101.001 to its decimal equivalent.
(c) Convert Octal number 321.7 into its Binary equivalent.

Answer:

https://onlinestudytest.com/
Question 2:
Do as directed :

(a) Covert the Hexadecimal number 3BC into its Binary equivalent
(b) Convert the Binary number 10011010.010101 to its Hexadecimal equivalent.
(c) Convert the Decimal number 345 into Octal number.

Answer:

https://onlinestudytest.com/
Question 3:
Do as directed

(a) Convert the Decimal number 736 into Hexadecimal number.


(b) Convert the Octal number 246.45 into Hexadecimal number.
(c) Convert the Hexadecimal number ABF.C into Octal number.
(d) Covert the Octal number 576 to Decimal.
(e) Convert the Hexadecimal number A5C1 to Decimal,

https://onlinestudytest.com/
Answer:

https://onlinestudytest.com/
6 INTERNAL STORAGE ENCODING OF CHARACTERS

6.1 SHORT ANSWER TYPE QUESTIONS-II


Question 1:
What is ASCII ?
Answer:
It is acronym for the American Standard Code for Information Interchange. It is used in most
microcomputers and minicomputers and in many mainframes. It is a 7-bit code so it has 27 = 128
possible code groups. 2

Question 2:
What is ISCII ?
Answer:
It is acronym for Indian Standard Code for Information Interchange. It is a 8-bit code so it has 28 =
256 possible code groups. It retains all ASCII characters and offers codng for Indian characters also. 2

Question 3:
What do you understand by Unicode ?
Answer:
It is the new universal coding standard being adopted all newer platforms. Unicode provides a
unique number for every character, no matter what the platform or program or the language is. 2

Question 4:
Expand the following:

1. ASCII
2. ISCII

Answer:

ASCII: American Standard Code for Information Interchange.

ISCII : Indian Standard Code for Information Interchange.

https://onlinestudytest.com/
7
MICROPROCESSOR

7.1 VERY SHORT ANSWER TYPE QUESTIONS (1 MARK EACH )


Question 1:
What do you mean by registers ?
Answer:
It is a small amount of very fast memory that is built into the CPU. It is very expensive.

Question 2:
What do you mean by bus ?
Answer:
It refers to collection of wires through which data is transmitted from one part of computer to
another.

Question 3:
What is expansion Bus ?
Answer:
External bus is also known as expansion bus. It connects the different external devices peripherals,
expansion slots, input/output ports and drive connections to the rest of the computer.

Question 4:
What is Intel 8085 ?
Answer:
Intel 8085 is a microprocessor that is used in various electronic devices.

Question 5:
What are the three leading microprocessor manufacturing companies ?
Answer:
Intel IBM, Freescale AMD, Microchip MIPS NEC are the three leading companies.
Question 6:
What do you mean by Instruction Set ?
Answer:
The set of instructions that a microprocessor can execute.

Question 7:
What do you understand by Bandwidth ?
Answer:
The number of bits processed in a single instruction.

https://onlinestudytest.com/
Question 8:
Define Clock speed.
Answer:
The clock speed determines how many instructions per second a processor can process. It is given in
megahertz or gigahertz.

Question 9:
Define chip.
Answer:
It is a small piece of semiconducting material on which an integrated circuit is embedded.

Question 10:
What is the role of clock speed in microprocessor ?
Answer:
It is the speed at which microprocessor executes instructions.

7.2 SHORT ANSWER TYPE QUESTIONS-II (3 MARK EACH )


Question 1:
Draw the block diagram of microprocessor.
Answer:
Block diagram of microprocessor

Question 2:
What is microprocessor ? Name its various components.
Answer:
A microprocessor also called CPU is multipurpose, programmable logic device that reads binary
instructions from a storage device called memory, accepts binary data as input and processes data
according to those instructions and provides results as output.
Components of Microprocessor:

1. CPU
2. Bus. 3

https://onlinestudytest.com/
Question 3:
What do you understand by registers ? Give the name of two registers.
Answer:
It is a small amount of very fast memory that is built into the CPU. It is very expensive. Accumulator
and program counter are two registers. 3

Question 4:
Write the characteristics on the basis of which microprocessors are differentiated.
Answer:

1. Instruction Set
2.Bandwidth
3. Clock Speed 3

Question 5:
Expand the following :

RISC

CISC
EPIC

Answer:

RISC : Reduced Instruction Set Computing.

CISC : Complex Instruction Set Computing.

EPIC : Explicitly Parallel Instruction Computing.


[1 mark for each correct answer]

Question 6:
Explain the following :

CISC

RISC

EPIC

Answer:

CISC : It is acronym for Complex Instruction Set computing. The CISC architecture contains a large set
of computer instructions that range from very simple to very complex and specialized.

RISC : It is acronym for Reduced Instructions Set Computing. It has relatively limited number of
instructions. It is designed to perform relatively small number of operations so that it can operate at
higher speed.

EPIC : It is acronym for Explicitly Parallel


Instruction Computing. It refers to architecture in which features are provided to facilitate compiler
enhancements of Instruction Level Parallelism in all programs while keeping hardware complexity
relatively low. [1 mark for each]

https://onlinestudytest.com/
Question 7:
Write RISC Approach.
Answer:
RISC processors only use simple instructions that can be executed within one clock cycle. Thus, the
“MULT” command could be divided into three separate commands: “LOAD,” which moves data from
the memory bank to a register, “PROD,” which finds the product of two operands located within the
registers, and “STORE,” which moves data from a register to the memory banks. In order to perform
the exact series of steps described in the CISC approach, a programmer would need to code four
lines of assembly :
LOAD A, 2 : 3 LOAD B, 5 : 2
PROD A, B STORE 2:3, A

Question 8:
Write CISC Approach.
Answer:
The primary goal of CISC architecture is to complete a task in as few lines of assembly as possible.
This is achieved by building processor hardware that is capable of understanding and executing a
series of operations. For this particular task, a CISC processor would come prepared with a specific
instruction (we’ll call it “MULT”). When executed, this instruction loads the two values into separate
registers, multiplies the operands in the execution unit, and then stores the product in the
appropriate register. Thus, the entire task of multiplying two numbers can be completed with one
instruction : MULT 2:3, 5:2.

Question 9:
Wtite examples of CISC processors.
Answer:
Examples of CISC processors are :

• System/360(excluding the ‘scientific’ Model 44).


• VAX.
• PDP-11.
• Motorola 68000 family
• Intel x86 architecture based processors. 3

Question 10:
Write any four points about RISC.
Answer:
Reduced Instruction Set Computer have :

• Small number of instructions.


• Instruction size constant.
• Bans the indirect addressing mode.
• Retains only those instructions that can be overlapped and made to execute in one machine cycle
or less. 3

https://onlinestudytest.com/
8 MEMORY CONCEPTS

8.1 VERY SHORT ANSWER TYPE QUESTIONS (1 MARK EACH )


Question 1:
Write the full form of CD-ROM.
Answer:
Compact Disk Read Only Memory.

Question 2:
Write the capacity of 3.5 inch floppy disk.
Answer:
1.44 MB.

Question 3:
How many bit for data recording format in most of the modern magnetic tape is needed ?
Answer:
8-bit EBCDIC.

Question 4:
Write the unit of tape speed .
Answer:
Inch per second.

Question 5:
By which reading data is performed in magnetic disk ?
Answer:
Read/write leads.

Question 6:
What do you mean by access time?
Answer:
Seek time + latency time.

Question 7:
What do you mean by seek time ?
Answer:
Time to position the head over proper track.

Question 8:
What do you mean by latency time ?
Answer:
Time to spin the needed data under head.

Question 9:
Hard disk is coated from both the sides by
Answer:
Magnetic metallic oxide.

Question 10:
How many bytes makes 1KB ?

https://onlinestudytest.com/
Answer:
1KB = 1024 bytes.

Question 11:
Write any two advantages of a pen drive.
Answer:
The advantages of a pen drive are :

• Small Size for easy transport


• Affordability.

8.2 SHORT ANSWER TYPE QUESTIONS-I (2 MARK EACH )


Question 1:
What do you mean by CD-ROM ?
Answer:
CD-ROM is a non-volatile optical data storage medium using the same physical format as audio
compact disk, readable by a computer with a CD- ROM drive. The standard 12cm diameter CD- ROM
store about 660 megabytes.

Question 2:
What is Blu-ray ?
Answer:
Blu-ray, also known as Blu-ray Disc (BD), is the name of a new optical disk format that offers more
than five times the storage capacity of traditional DVDs.

Question 3:
Explain RAM.
Answer:
Computer RAM is the best known form of memory your computer uses. Every file or application
opened is placed in RAM. Any information the computer needs or uses becomes part of a
continuous cycle where the CPU requests the data from RAM, processes it and then writes new data
back to the RAM. This can happen millions of times a second. However, this is just for temporary file
storage, so it is deleted when the files or applications are closed.

Question 4:
What do you mean by hard drive ?
Answer:
A hard drive is a form of computer memory that allows you to permanently store data. This is where
all of your permanent files and programs are stored. On computers running with Microsoft windows
the hard drive is often called C-drive. The size of a hard drive is typically measured in gigabytes.

Question 5:
Explain virtual memory.
Answer:
Virtual memory typically comes into place when applications are too large for the RAM to handle.
The operating system uses the hard drive to temporarily store information and take it back when
needed. This is normally a lot slower than actual RAM and can possibly degrade the performance if
used too heavily.

https://onlinestudytest.com/
Question 6:
Where do we use cache memory ?
Answer:
Cache memory is used in between the CPU and the RAM and holds the most frequently used data or
instructions to be processed. There are three different grades of cache.

Question 7:
What do you mean by port ? Write its types also.
Answer:
A port is a connection point or interface between a computer and internal or external devices.
Some common types of ports are :

1. Serial Port.
2. Parallel Port.
3. USB Port.
4. Bluehx th.
5. PS/2 Port.
6. Infrared Port.
7. Firewire Port.

Question 8:
Explain difference between serial and parallel data transfer.
Answer:
Parallel data transfer refers to the type of data transfer in which a group of bits are transferred
simultaneously while serial data transfer refers to the type of data transfer in which a group of data
bits are transferred one bit at a time. So that means that the amount of data transferred serially is
less than the data transferred parallel per second.

Question 9:
What do you mean by PS/2 port ?
Answer:
A type of port developed by IBM for connecting a mouse or keyboard to a PC. The PS/2 port
supports a mini DIN plug containing just 6 pins. Most PCs have a PS/2 port so that the serial port can
be used by another device, such as a modem. The PS/2 port is often called the mouse port.

8.3 SHORT ANSWER TYPE QUESTIONS – II (3 MARK EACH )


Question 1:
Explain 3.5 inch floppy disk.
Answer:
Micro floppy disks (3.5 inch) if it is high density (MF2HD), can store 1.44 MB and if it is low density
(MF2DD), can store 720 KB. Mini Floppy disks (5.25 inch) if it is high density (MD2HD), can store 1.2
MB and low density (MD2DD), stores 360 KB of data.

Question 2:
MICR stands for ?
Answer:
MICR (Magnetic Ink Character Reader) is a kind of scanner that can scan and identify the writing of
magnetic ink. This device is used in banks to verify the signatures in cheques.

https://onlinestudytest.com/
Question 3:
What do you mean by Extended Binary Coded Decimal Interchange Code ?
Answer:
EBCDIC is an 8-bit binary code for larger IBMs primarily mainframes in which each byte represent
one alphanumeric character or two decimal digits. 256 characters can be coded using EBCDIC.

Question 4:
Explain Computer memory.
Answer:
Computer memory are internal storage areas in the computer used to either temporarily or
permanently store data or instructions to be processed. There are four basic types of computer
memory : Cache Memory, RAM, Virtual Memory and Hard Drives. With modern CPU’s running at
speeds of 1 gigahertz or higher, it is hard for computer memory to keep up with the extreme amount
of data being processed. Computer
engineers fixed the problem by “tiring” memory. By using this tiring effect, engineers use a small
amount of more expensive memory and a large amount of low cost memory.

Question 5:
Pen drives are universal. Explain.
Answer:
The design of a pen drive makes it easy to fit almost anywhere. They can store a large amount of
information, sometimes as large as 32 gigabytes. Almost all computers that are designed today have
a USB port that allows for extra drives to be attached to access other information on other computer
hardware accessories.

Question 6:
Expalin Cache Memory.
Answer:
A CPU cache is a cache used by the Central Processing Unit (CPU) of a computer to reduce the
average time to access data from the main memory. The cache is a smaller, faste r memory which
stores copies of the data from frequently used main memory locations. Most CPUs have different
independent caches, including instruction and data caches, where the data cache is usually
organized as a hierarchy of more cache levels (LI, L2, etc.)
When the processor needs to read from or write to a location in main memory, it first checks
whether a copy of that data is in the cache. If so, the processor immediately reads from or writes to
the cache, which is much faster than reading from or writing to main memory.
Most modern desktop and server CPUs have at least three independent caches: an instruction cache
to speed up executable instruction fetch, a data cache to speed up data fetch and store, and a
translation look aside buffer (TLB) used to speed up virtual-to- physical address translation for both
executable instructions and data. The data cache is usually organized as a hierarchy of more cache
levels.

https://onlinestudytest.com/
9
GENERAL CONCEPTS OF PROGRAMMING

9.1 VERY SHORT ANSWER TYPE QUESTIONS (1 MARK EACH )


Question 1:
On which step programming methodology used ?
Answer:
Before writing program.

Question 2:
What do you mean by modular approach ?
Answer:
Breaking of a problem into sub-problems.

Question 3:
Which characteristics of programming methodology refers to the overall readability of the
programme ?
Answer:
Clarity.

Question 4:
Are comments executed ?
Answer:
Comments are not executed

Question 5:
Do comments increase execution time ?
Answer:
No, comments do not increase execution time.

Question 6:
How many types of comments ?
Answer:
Comments are of two types : single line and multiple line.

Question 7:
Why do we use comments ?
Answer:
Comments helps the reader to understand the programme easily.

https://onlinestudytest.com/
Question 8:
Which characteristics refer to insertion of extra blank spaces before declaration ?
Answer:
Indentation

9.2 SHORT ANSWER TYPE QUESTIONS-I (2 MARKS EACH )


Question 1:
Define Clarity of source code.
Answer:
The extent to which inherent language features support source code that is readable and
understandable and that clearly reflects the underlying logical structure of the program.

Question 2:
Explain clarity of expression
Answer: Clarity refers to the overall readability of the program, with emphasis on program logic. It
allows other programmers to follow the program, if the program is written clearly. It also makes the
programmer to grasp his or her own program logic even after a long period of time.

Question 3:
Give an example of clarity of expression.
Answer:
Suppose we wish to write a program to calculate the area of a circle. We require two variables;
radius and area. Instead of writing r and a to represent the radius and area re spectively, we use
radius and area to represent themselves. It increases the readability of program, Similarly, the
constant can be written as pi instead of denoting by p.

Question 4:
Explain types of comments.
Answer:
There are two types of comments in a C+ + program; single line comment and multi-‘line comment.
Single line comment begin with double slash (/ /) and end in the same line. We can write a program
statement and a comment in same line. Whatever written after the / / is ignored by the compiler.

Question 5:
Write any two characteristic of comments.
Answer:
Comments are not executed in a program. Since the compiler ignores comments, there will be no
increase in the file size and execution time.

Question 6:
Write any two purpose of comments.
Answer:

Comments help the reader to understand the program easily.

When a program consists of several functions, comments can be added to each function to indicate
the purpose of the function.

Question 7:
Define identation.
Answer:

https://onlinestudytest.com/
Indentation refers to the insertion of extra blank , spaces before declarations and statements. It
enhances the readability of programs.

9.3 LONG ANSWER TYPE QUESTIONS (4 MARKS EACH )


Question 1:
Define clarity and simplicity of expression with example.
Answer:
Crarity and Simplicity of Expression: In the early days most of the computer programs were written
to carry out difficult and complex calculations. It is not so any more. However, you may still have to
write programs involving complex calculations.
It is advised that if any expression becomes very big or very complex then you must write the same
in two steps rather then doing it in one single step. This will make the expression simple and any
programmer will be more accurate in writing simple expressions.
Simple expressions are also easily readable and can be understood by others without making any
extra efforts. For example, a Statement like :

A = square root((x y/d)+(c+z)2 – (u*v) )/L may be written in two steps as :


A1 = x y/d
A2 = (c+z) 2
A3 = u * v
A = square root(Al + A2 – A3)/L

https://onlinestudytest.com/
10 DOCUMENTATION AND PROGRAMMING MAINTENANCE

10.1 VERY SHORT ANSWER TYPE QUESTIONS (1 MARK EACH )


Question 1:
How many types of documentation are there ?
Answer:

(a) internal documentation


(b) external documentation

Question 2:
Which documents helps in programme maintenance ?
Answer:
internal documentation

Question 3:
Write the alternate name of error.
Answer:
Bugs

Question 4:
What is debugging ?
Answer:
The process of correcting the error.

10.2 SHORT ANSWER TYPE QUESTIONS-I (2 MARKS EACH )


Question 1:
Explain documentation
Answer:
All programs need not to be short and simple. Complex programs can be better understood if
additional information is provided. Documentation is a method of providing useful information
about a program. It consists of written descriptions, specification and development of the program.

Question 2:
Explain programme maintenance.
Answer:
Changes in requirements force to modify existing programs. Program maintenance is the
modification of a program to take care of changing requirements or any errors found after the
program is put to use.

Question 3:
What do you mean by running and debugging of programme.
Answer:

https://onlinestudytest.com/
Running and Debugging Programs : Once a program has been written, it has to be tested for its
correctness. During this process, we may find errors. In computer terminology, errors are known as
bugs, and the process of correcting the errors is known as debugging.

Question 4:
Define syntax error.
Answer:
The grammatical rules of a language are referred to as syntax of that language. If we do not strictly
follow the syntax of programming language at the time of writing a program, syntax errors are
bound to occur.

10.3 LONG ANSWER TYPE QUESTIONS (4 MARKS EACH )


Question 1:
Write the factors on which documentation depend.
Answer:

A program must have meaningful constant and variable names.

A program should include specification of the problem.

The initial lines of comment should contain programmer’s name, date, brief description of the
problem, and the purpose of the program.

Other comments include the input by form and type, output by form and type, data structures used,
main function and other functions used, and assumptions.

The purpose of every function and their inter-relationships must be described with comments.

Comments are to be inserted in the program wherever necessary for clarity. The purpose of such
comments is not to tell how or why something is done, but what is being done.

Question 2:
Explain program maintenance with reference to organization.
Answer:
Program maintenance is an important duty of programmers. It involves all steps from problem
definition to program preparation. In certain organizations, programmers can do nothing but
maintain the programs.
At the initial stage of computerization, an organization’s programming effort mostly goes into the
development of new applications. As the number of installed programs grows, the programming
effort shifts from program development to program maintenance, in fact, in many organizations,
more than half of the programming effort is on program maintenance. An estimate shows that the
cost of program maintenance is twice larger than that of initial development.

Question 3:
Explain run time error with example.
Answer:
Run-Time Errors : A program’s syntax may be correct- H may be compiled and linked successfully.
But it may not be executed successfully because of run-time errors. Such errors are found at the
time of executing the program.
Let us consider the following program segment

https://onlinestudytest.com/
n = 9;
while (n > 1)
{
n-1
m = m / (n -1);
}

When the value of n becomes 2, the expression a > 1 is true .


Hence, the statement n – decreases the value of n by 1. When the value of n is 1, Ihe divisor is O’
which generates a run-time error. Run-time errors include finding square root of a negative number,
stack overflow, and null pointer assignment.

Question 4:
Explain logical error.
Answer:
A logic error is a defect in the program that causes it to produce an incorrect result, but one that is
not so blatant as to be detectable as a runtime error. (A logic error in one part of the program might
eventually trigger a runtime error in some other part of the program, but those are separate errors.)
An example would be a function that is supposed to return the larger of its two arguments but in
fact returns the smaller:
def larger(m, n):
if (m > n):
return n
return m

Question 5:
Write all steps of program solving methodology. [CBSE Text Book]
Answer:
There are following seven steps of program solving methodology:

Problem Definition: Computer programs are written to solve problems posed by humankind. Prior
to writing a program, one has to understand a description of the problem to solve. This descriptio n
may be very precise or vague, but nevertheless, it is necessary /present. Once programmer is sure of
what the problem entails, he must write down a list of specifications. Specifications are precise
definitons of what the program must do.

Problem Analysis: In this step, the problem has to be fragmented into smaller and manageble parts.
The original problem has to be analyzed and divided into a number of sub-problems as these sub-
problems are easier to solve and their solutions would become the components of the final problem.
Each sub-problem is divided into further smaller ones and this fragmentation has to be continued to
achieve simple solutions. The use of modular programming is to get proper solution.

Designing the Problem : Designing the problem can be expressed in the form of:
(i) Algorithm
(ii) Flowchart
(i) Algorithm: An algorithm is a set of instructions that describe a method for solving a problem. It is
normally given in mixture of computer code and English Language. This is often called “Pseudo code”.
(ii) Flowchart : The algorithm is represented in the form of a diagram with action boxes linked by
lines showing the order in which they are executed. This is known as ‘the flow of control’. It is the
diagrammatic representation of an algorithm.

https://onlinestudytest.com/
Coding : The process of translating the algorithm into syntax of a given language is known as
‘coding’. Since algorithm cannot be executed directly by the computer, it has to be translated into a
programming language.

Program Testing and Debugging : Program testing means running the program, executing all its
instructions and testing the logic by entering sample data in order to check the output. Debugging is
the process of finding and correcting the errors in the program code.

Documentation : The documentation includes the problem definition, design documents, a


description of the test perform, a history of the program development and its different versions and
a user’s manual. Such a manual is designed for a native user and illustrates the preparation of inpu t
data, running the program and obtaining and interpreting the results.

Program Maintenance : It is not directly part of the original implementation process, but needs
special emphasis. All activities that occur after a program operation are part of the program
maintenance. Many large programs have long life span that often exceed the lifetime of the
hardware they run on. Maintenance is an important part of the life cycle of a program.

Question 6:
What is run-time error, logical error and syntax error?
Answer:
Syntax error : The errors which are traced by the compiler during compilation, due to wrong
grammar for the language used in the program, are called syntax errors.
For example, cin<<a; // instead of extraction operator insertion operator is used.
Run time Error : The errors encountered during execution of the program, due to unexpected input
or output are called run-time error.
For example – a=n/0; // division by zero
Logical Error : These errors are encountered when the program does not give the desire d output,
due to wrong logic of the program.
For example : remainder = a+b// instead of using % operator + operator is used.

https://onlinestudytest.com/
11 PROBLEM SOLVING METHODOLOGIES

11.1 VERY SHORT ANSWER TYPE QUESTIONS (1 MARK EACH )


Question 1:
Write the alternate name of infinite loop.
Answer:
endless loop.

Question 2:
Define looping
Answer:
Looping is repeating a s t of instructions until a specific condition is met

Question 3:
Write the difference bets een finite and infinite loop.
Answer:
A finite loop ends itself. An infinite loop will not end without an outside cause.

Question 4:
Is for loop pretest type of loop ?
Answer:
Yes. The second clause (the condition) is evalu-ated before each iteration through a loop.

Question 5:
Can you use one or more loop inside any another while, for or do., while loop ?
Answer:
Yes.

Question 6:
Write the name of loop which executes a sequence of statements multiple times and abbreviates
the code that manages the loop variable.
Answer:
for-loop.

Question 7:
Define Variable.
Answer:
It is the name of space inside computer memory walues can be stored.

https://onlinestudytest.com/
11.2 SHORT ANSWER TYPE QUESTIONS-I (2 MARKS EACH )
Question 1:
Define infinite loop.
Answer:
An infinite loop is a sequence of instructions in a computer program which loops endlessly, either
due to the loop having no terminating condition, having one that can never be met, or one that
causes the loop to start over.

Question 2:
Give an example for infinite loop
Answer:
A simple example of an infinite loop is instructing a computer to keep on adding 0 to 1 until 2 is
reached. This will never happen.

Question 3:
What is a logical operator ?
Answer:
Logical operator is a operator used to combine relational expressions. In C++, there are three types
of logical operators :

(i) Logical AND


(ii) Logical OR
(iii) Logical NOT

Question 4:
What will be the minimum number of inputs for finding a simple interest ?
Answer:
The formula of simple interest is :

So, to find the simple interest we need to input the value of Principal (P), Rate (R) and Time (T) .
Therefore the minimum number of inputs for finding the simple interest is 3 i.e. P R and T.

11.3 LONG ANSWER TYPE QUESTIONS (4 MARKS EACH )


Question 1:
Explain Modular programming.
Answer:

(i) Modular programming is the technique which divides the entire program into smaller modules,
which perform a specific task.
(ii) It can often be used in variety of applications and functions with other components of the
system.
(iii) The order in which the modules are executed by the computer is controlled by the main
program. This describes fully the procedures required in the solution to a problem. The procedures
are written in the order of the machine execution.
(iv) OPP is compatible with the modular programming concept to a large extent. Modular
Programming enables multiple programmers to divide up the work and debing pieces of the
program independently.

https://onlinestudytest.com/
Question 2:
What is the difference between modular programming and structured programming ?
Answer:
Modular programming : It is the act of designing and writing programs as interactions among
functions that each perform a single well defined function & which have minimal side effect
interaction between them. It is heavily procedural. The focus is entirely on writing code (functions).
Data is passive. Any code may access the contents of any data structured passed to it.
Object Oriented programming : it is a programming using “objects”-data structures consisting of
data fields & methods together with their interactions to design applications and computer
programs. Programming techniques may include features such as data abstraction, encapsulation,
messaging, modularity, polymorphism/and inheritance.

Question 3:
Differentiate between top down and bottom up methods of modular programming.
Answer:

Top-Down Method Bottom-up Method

Bottom-up method is just the opposite of top- down m


The principle of top down method dictate that a program
refers to a style of programming in which an application
should be divided into a main module and its related module.
constructed with existing primitives of the programmin
Each module should also be divided into sub modules
language and then gradually more and more complicate
according to software engineering and programming style.
features are added till applications are written. In othe
The division continues till the module consists only of an
initiating the design with simple modules and then fuild
elementary process that is intrinsically understood and
into more complex structures ending at the top is botto
cannot be further subdivided.
method.

Question 4:
What are the advantages of using a modular approach in programming ?
Answer:

It is easy to understand small sections of code in the modular programming.

You can store the code across multiple files.

Modular programming allows collaborative programming. Collaborative programming means more’


than one program
work in one application at the same time.

Duplication of code, is not possible in modular programming. The programmers create a single
procedure for code.

The errors are localized to a subroutine or function and it is easy to find the errors.

The code should be used in multiple applications in modular programming.

The code should be simple and short in modular programming and it is less need to be written.

https://onlinestudytest.com/
12
ALGORITHMS & FLOWCHARTS

12.1 SHORT ANSWER TYPE QUESTIONS-II (3 MARKS EACH )


Question 1:
Explain Algorithm.
Answer:
An algorithm is a step by step instructions required to solve any problem. These instructions are in
user’s language that means they are independent of any programming language. 3

Question 2:
Write some properties of algorithm.
Answer:
Some properties of algorithm are :

An algorithm should terminate after finite number of steps.

An algorithm should be simple so that anyone can understand them properly.

An algorithm should be universal and lead to an unique solution of the problem.

An algorithm should have capability to handle some unexpected situations which may arise during
the solution of a particular problem.

An algorithm should be able to solve all problems of a particular type for which it is designed. [Any
3,1 mark for each correct point]

Question 3:
Write some characteristics of algorithm.
Answer:
Some characteristics of algorithm are :

Each and every instruction should be short and clear.

Each instruction should be such that it can be performed in a finite time.

One or more instructions should not be repeated infinitely.

After performing the instructions the desired result must be obtained. [Any 3,1 mark for each
correct point]

https://onlinestudytest.com/
Question 4:
Write an algorithm to calculate sum of two numbers.
Answer:

Step 1 : Start.
Step 2 : Read A,B.
Step 3: Sum=A+B.
Step 4 : Print Sum.
Step 5 : Stop. 3

Question 5:
Write an algorithm to calculate simple interest.
Answer:

Step 1: Start.
Step 2 : Read RR,T.
Step 3 : SI=(P*R*T)/100.
Step 4 : Print SI
Step 5 : Stop. 3
Question 6:
Write an algorithm to convert temperature from Fahrenheit to Celsius.
Answer:

Step 1: Start.
Step 2 : Read F.
Step 3: C=(5(F-32))/9.
Step 4 : Print C.
Step 5 : Stop. 3

Question 7:
Write an algorithm to calculate area of triangle.
Answer:

Step 1: Start.
Step 2 : Read a,b,c.
Step 3: s=(a+b+c)/2.
Step 4 : Area = (s(s-a)(s-b)(s-c))1/2.
Step 5 : Print Area.
Step 6 : Stop. 3

Question 8:
Write an algorithm that generates the fibbonacci series as:
1,1,2,3, 5,…. N terms.
Answer:
The algorithm as :

Step 1 : Begin.
Step 2 : Read N.
Step 3 : Let a = 1, b = 1 Step 4 : Print a, b.
Step 5 : ctr = 2.
Step 6 : c = a + b.

https://onlinestudytest.com/
Step 7 : a = b.
Step 8 : b = c.
Step 9 : ctr = ctr + 1.
Step 10 : If ctr < N then repeat steps 6 to 9.
Step 11 : Stop. 3

Question 9:
Write an algorithm to compute sum of the square of N numbers.
Answer:
The algorithm as :

Step 1: Read N.
Step 2 : Let ctr = 0, sum = 0.
Step 3 : Read Num.
Step 4 : ctr = ctr + 1.
Step 5 : Compute the square of the number i.e.,
= sqr (Num * Num).
Step 6 : sum = sum * sqr.
Step 7 : If ctr is less than N then repeat steps 3 to 6. Step 8 : Print sum.
Step 9 : End. 3

Question 10:
Write an algorithm for calculating the conversion from rupees to dollars.
Answer:
Algorithm is defined as follows :

Step 1: Start.
Step 2: Read the amount in rupees and conversion rate.
Step 3: Calculate the equivalent amount in dollars using the following formula : amount in dollars =
amount in rupees / conversion rate.
Step 4 : Write the amount in dollars.
Step 5 : Stop. 3

Question 11:
Write an algorithm to find the largest among three numbers.
Answer:
The algorithm is defined as :

Question 1:
Is Python a high-level Language ?
Answer:
Yes, Python is a high-level Language.
Question 2:
Is Python interpreted ?
Answer:
Yes, Python is a interpreted language.
Question 3:
Is Python Object-Oriented Language ?

https://onlinestudytest.com/
Answer:
Yes, Python is a Object-Oriented Language.
Question 4:
How many modes are available in Python ?
Answer:
interactive mode and script mode.
Question 5:
Can Python be easily integrated with C+ + ?
Answer:
Yes, Python can be easily integrated with C + +.
Question 6:
Is Python supports GUI applications?
Answer:
Yes, Python supports GUI applications.
Question 7:
Does Python support automatic garbage collection ?
Answer:
No, Python does not support automatic garbage collection.
Question 8:
Does Python support Hyper Text Markup Language?
Answer:
No, Python does not support Hyper Text Markup Language.
Question 9:
“Python is Scalable”, is this statement true?
Answer:
True.
Question 10:
Can we connect Python to database ?
Answer:
Yes, we can connect with all major commercial databases.

12.2 SHORT ANSWER TYPE QUESTIONS [2 MARK EACH ]


Question 1:
Define Python ?
Answer:
Python is a high-level, interpreted, interactive and object oriented-scripting language.
Question 2:
Why Python is interpreted ?
Answer:

https://onlinestudytest.com/
Python is interpreted because it processed at runtime by the interpreter and you do not
need to compile your program before executing it. This is similar to PERL and PHP.
Question 3:
Is there a tool to help find bugs or perform static analysis ?
Answer:
Yes,
Pychecker is a static analysis tool that finds bugs in Python source code and warns about
code complexity and style.
Pylint is another tool that checks if a module statisfies a coding standards, and also makes it
possible to write plug-ins to add a custom feature.
Question 4:
Who developed Python?
Answer:
Python was developed by Guido van Rossum in the late eighties and early nineties at the
National Research Institute for Mathematics and Computer Science in the Netherlands.
Question 5:
Why Python is Easy-to-learn?
Answer:
Python has relatively few keywords, simple structure, and a clearly defined syntax. This
allows the student to pick up the language in a relatively short period of time.
Question 6:
Write any feature of Python library.
Answer:
Python library is very portable and cross-platform compatible on UNIX, Windows, and
Macintosh.
Question 7:
Write any one similarity between Python and OOPs
Answer:
Python supports most of the OOP concepts like encapsulation, inheritance and
polymorphism.
Question 8:
Is Python compiler language or interpreter language?
Answer:
It is normally interpreted by another computer program. However subsets of the language
can be compiled.

12.3 LONG ANSWER TYPE QUESTIONS [4 MARK EACH ]


Question 1:
What is the Python programming language?

https://onlinestudytest.com/
Answer:
Python is an interpreted, interactive, object- oriented programming language. It is often
compared to Tel, Perl, Scheme or Java.
It is a scripting language like Php or Asp for developing applications. Python is an
interpreted, object-oriented, high-level programming language with dynamic semantics. Its
high-level built in data structures, combined with dynamic typing and dynamic binding,
make it very attractive for Rapid Application Development, as well as for use as a scripting
or glue language to connect existing components together. Python’s simple, easy to learn
syntax emphasizes readability and therefore reduces the cost of program maintena nce.
Python supports modules and packages, which encourages program modularity and code
reuse. The Python interpreter and the extensive standard library are available in source or
binary form without charge for all major platforms, and can be freely distri buted.
Question 2:
What is Python ? State some programming language features of Python.
Answer:
Python is a modern powerful inter-preted language with objects, modules, threads,
exceptions, and automatic memory managements.
Python was introduced to the world in the year 1991 by Guido van Rossum
Salient features of Python are :

Simple & Easy : Python is simple language & easy to learn.

Free/open source : Everybody can use python without purchasing license.

High level language : When coding in Python one need not worry about low-level details.
Portable : Python codes are Machine & platform independent.

Extensible: Python program supports usage of C/ C + + codes.


Embeddable Language : Python code can be embedded within C/C+ + codes & can be used a
scripting language.

Standard Library : Python standard library contains prewritten tools for programming.
Built-in Data Structure : Contains lots of data structure like lists, numbers & dictionaries.
Question 3:
Distinguish Java with Python
Answer:
Java v/s Python :
Python programs run slower than the Java codes, but Python saves much time and space.
Python programs are 3-5 times smaller than Java programs.
Python is a dynamic typed language. Python programmers don’t need to waste time in
declaring variable types as in Java.

https://onlinestudytest.com/
Python is much more easy to learn than Java.
Question 4:
Explain the disadvantages of Python.
Answer:
Disadvantages of Python are :

Python is not the best for memory intensive tasks.


Python is interpreted language and is slow compared to C/C+ + or java.

Python is not a great choice for a high graphic 3D game that takes up a lot of CPU.
Python is evolving continuously with constant evolution there is little substantial
documentation available for the language.
Question 5:
Compare C + + v/s Python.
Answer:
C+ + v/s Python
Comparison is same as that between Java and Python except the program length in python
is 5-10 times shorter than that in C + + .

Python programmers can complete a task in 2 months that takes a year in C + +.


Question 6:
How do we make Python Scripts Executable ?
Answer:
Python scripts can be executed in two ways :
Open the script1.Py in IDE Editor and run the script in the frontmost window of the Python
IDE by hitting the run all button.
Using command prompt by making sure PATH is appropriate directly type script name. > > >
python Script1.Py

https://onlinestudytest.com/
13 PYTHON PROGRAMING

13.1 VERY SHORT ANSWER TYPE QUESTIONS [1 MARK EACH]


Question 1:
What are the two modes in Python ?
Answer:
Interactive Mode Programming and Script Mode Programming.

Question 2:
Write any two Standard Data Types in Python.
Answer:
List and String.

Question 3:
Is List a standard data type ?
Answer:
Yes, List is a standard data type.

Question 4:
Write the kind of Python’s dictionary ?
Answer:
Python’s dictionaries are kind of hash table type.

Question 5:
What is the extension of Python language?
Answer:
All Python files have extension “.py”.

Question 6:
Which mode of Python invoking the interpreter without passing a script file as a parameter ?
Answer:
Interactive Mode Programming.

Question 7:
Which mode of Python invoking the interpreter with a script parameter begins execution of the
script and continues until the script is finished ?
Answer:
Script Mode Programming.

https://onlinestudytest.com/
Question 8:
In which mode of Python, the interpreter is no longer active ?
Answer:
Script Mode Programming.

Question 9:
Do Python variables have to be explicitly declared to reserve memory space ?
Answer:
Yes.

Question 10:
Does Python allows you to assign a single value to several variables simultaneously ?
Answer:
Yes, Python allows you to assign a single value to several variables simultaneously.

Question 11:
Give a example of immutable data type.
Answer:
Tuple.
Question 12:
Which type of values can be store in Number data types.
Answer:
numeric values.

Question 13:
Does Python allow for only double quotes ?
Answer:
No, Python does allow for either pairs of single or double quotes.

Question 14:
Write the name of most versatile Python’s compound data types.
Answer:
Lists.

Question 15:
Which data type consists of a number of values separated by commas ?
Answer:
A tuple

Question 16:
What is IDLE?
Answer:
IDLE (pronounced as Idli) is the most popular Python development environment IDLE is an acronym
of Integrated Develop Environment

Question 17:
Name some commands of Python.
Answer:
Copyright, help, credits.

https://onlinestudytest.com/
13.2 SHORT ANSWER TYPE QUESTIONS [2 MARK EACH]
Question 1:
What is the difference between a keyword and an identifier ?
Answer:
Keyword is a special word that has a special meaning and purpose. Keywords are reserved and are
few. For example : if, else, elif etc.
Identifier is the user-defined name given to a part of a program like variable, object, functions etc.
Identifiers are not reserverd. These are defined by the user but they can have letters, digits and a
symbols underscore. They must begin with either a letter or underscore. For example : chess, _ch,
etc.

Question 2:
What are literals in Python ? How many types of literals are allowed in Python ?
Answer:
Literals mean constants i.e. the data items that never change value during a program run. Python
allow five types of literals :

String literals

Numeric literals

Boolean literals

Special literal (None)

Literal collections like tuples, lists etc.

Question 3:
How many ways are there in Python to represent an integer literal ?
Answer:
Python allows three types of integer literals :

Decimal (base 10) integer literals.

Octal (base 8) integer literals.

Hexadecimal (base 16) integer literals.


For example, decimal 12 will be written as 14 as octal integer and as OXC as hexa decimal integer.
(12) 10 = (14) 8 = (OXC) 16. (as hexa decimal)

Question 4:
How many types of strings are supported in Python ?
Answer:
Python allows two string types :

Single line strings : Strings that are terminated in single line. For example :
str = ‘Oswal Books’

Multiple strings : Strings storing multiple lines of text. For example :


str = ‘Owal \
Books’
or str = ” ” ” Oswal

https://onlinestudytest.com/
Books
”” “

Question 5:
What is “None” literal in Python ?
Answer:
Python has one special literal called ‘None’. The ‘None’ literal is used to indicate something that has
not yet been created. It is also used to indicate the end of lists in Python.

Question 6:
What factors guide the choice of identifiers in Programs ?
Answer:

An identifier must start with a letter or underscore followed by any number of digits or/ and letters.

No special character (other than under-score) should be included in the identifier.

No reserved word or standard identifier should be used.

Upper and lower case letters are different. All characters are significant.

Question 7:
What will be the size of the following constants : “\a”. “\a”, “Manoj\’s”, ‘\”, “XY\ YZ”
Answer:
‘\a’ – size is 1 as there is one character and it is a string literal enclosed in single quotes.
“\a” – size is 1 as there is one character enclosed in double quotes.
“Manoj\’s” – size is 7 because it is a string having 7 characters enclosed in double quotes.
“\” – size is 1. It is a character constant and is containing just one character \”.
“XY\ – size is 4. It is a multiline string create YZ” with \ in the basic string.

Question 8:
What is the difference between a tuple and a list ?
Answer:
A tuple is immutable i.e. cannot be changed. It can be operated on only. But a list is mutable.
Changes can
be done internally to it.
tuple initialization: a = (2,4,5) list initialization: a = [2,4,5]

Question 9:
Write various python modules convert the list to generate the output “one, two, three” ? a = [‘one’,
‘two’, ‘three’]
Answer:
> > > a = [‘one’,’two’,’three’]
>>> ‘,’.join(a)
‘one,two,three’

Question 10:
Is there a tool to help find bugs or perform static analysis?
Answer:
Yes. PyChecker is a static analysis tool that finds bugs in Python source code and warns about code
complexity and style. Pylint is another tool that checks if a module satisfies a coding standard, and
also makes it possible to write plug-ins to add a custom feature.

https://onlinestudytest.com/
Question 11:
What is a tuple ?
Answer:
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.

Question 12:
What is a list?
Answer:
Lists are the most versatile of Python’s compound data types. A list contains items separated by
commas and enclosed within square brackets ([ ]). To some extent, lists are similar to arrays in C.
One difference between them is that all the items belonging to a list can be of different data type.

Question 13:
Explain String data type.
Answer:
Strings in Python are identified as a contiguous set of characters in between quotation marks.
Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the
slice operator ( [ ] and [ : ] ) with indexes starting at 0 in the beginning of the string and working their
way from -1 at the end.

Question 14:
What is a Number data types ?
Answer:
Number data types store numeric values. They are immutable data types, which means that
changing the value of a number data type results in a newly allocated object.

Question 15:
Write the names of all Standard Data Types.
Answer:
(a) Numbers
(b) String
(c) List
(d) Tuple
(e) Dictionary

Question 16:
Write a list comprehension that builds a list of the even numbers from 1 to 10 (inclusive).
Answer:
foo = [x for x in range(l, 11) if (x % 2) = = 0] print foo [2,4,6,8,10]

Question 17:
When do you use list vs. tuple vs. dictionary vs. set?
Answer:
‘List’ is like an array, individual element of list data can be accessed using indexing and can be
manipulated. “Tuples” are similar to list, but there data can be changed once created through the
execution of program. ‘Set’ stores unordered values and have no index. And unlike Tuples and lists,
sets can have no duplicate data. “Dictionary” is similar to what their name is. It consist of pairs of
keys and thier corresponding values.

https://onlinestudytest.com/
Question 18:
Explain the dictionary in Python.
Answer:

Python’s built-in data type is dictionary, which defines one-to-one relationships between keys and
values.

Dictionary is indexed by keys.

Dictionary is similar to association array or hash table of other languages.

Dictionary consist of pairs’-of keys and their corresponding values.

Question 19:
What is PEP 8?
Answer:
PEP 8 is a coding convention(a set of recommendations) to write your Python code in order to make
it more readable and useful for those after you.

Question 20:
Explain how Python is interpreted.
Answer:
Python program runs directly from the source code. Each type Python programs executed code is
required. Python converts source code written by the programmer into intermediate language which
is again translated into the native language/ machine language that is executed. So Python is an
interpreted language.

13.3 LONG ANSWER TYPE QUESTIONS [4 MARK EACH]


Question 1:
How do we share global variables across modules in Python?
Answer:
We can create a config file & store the entire global variable to be shared across modules or script in
it. By simply importing config, the entire global variable defined. It will be available for use in other
modules.
For example we want a, b & c to share between modules.
config.py :
a=0
b=0
c =0
modulel.py:
import config
config.a = 1
config.b = 2
config.c = 3
• print ” a, b & c are : ” , config.a, config.b, config.c

Question 2:
What are the rules for local and global variables in Python?
Answer:
In Python, variables that are only referenced inside a function are implicitly global. If a variable is

https://onlinestudytest.com/
assigned a new value anywhere within the function’s body, it’s assumed to be a local. If a variable is
ever assigned a new value inside the function, the variable is implicitly local, and you need to
explicitly declare it as ‘global’. Though a bit surprising at first, a moment’s consideration explains
this. On one hand, requiring global for assigned variables provides a bar against unintended side -
effects. On the other hand, if global was required for all global references, you will be using global all
the time. You have to declare as global every reference to a builtin function or to a component of an
imported module. This clutter would defeat the usefulness of the global declaration for identifying
side-effect.

Question 3:
What does ‘immutable’ mean ? Which data type in Phython are immutable.
Answer:
An immutable variable change of value will not happen in place. Modifying an immutable variable
will rebuild the same variable. For example,
>>> x= 5
will create a value 5 referenced by
x x —> 5
>>> y = x
This statement will make y refer to 5 of x.
x
5
y
>>> x = x + y
As x being, immutable type, has been rebuild. In the statement expression of RHS will result into
value 10 and when this is assigned to LHS (x), x will rebuild to 10. An Integer data type in python is
immutable.

Question 4:
Does Python support data type conversion ?
Answer:
Yes, Python support data type conversion. To convert between built-in types, programmer simply
use the type name as a function. There are several built-in functions to perform conversion from one
data type to another. These functions return a new object represting the converted value.

Function Description

int (x [, base]) Converts x to an integer, base specifies the base if x is a string.

long [x [, base]) Converts x to a long integer, base specifies the base if x is a string.

float (x) Converts x to a floatingpoint number.

complex (real, [ing]) Creates a complex number.

str (x) Converts object x to a string representation.

repr (x) Converts object x to an expression string.

tuple (x) Converts x to a tuple.

list (x) Converts x to a list.

https://onlinestudytest.com/
chr (x) Convets an integer to a character.

unichr (x) Converts an integer to a Unicode character.

diet (x) Creates a disetionary, x must be a sequence of tuples.

set (x) Converts x to a set

Question 5:
How do you make an array in Python?
Answer:
Use a list: [“this”, 1, “is”, “an”, “array”] Lists are equivalent to C or Pascal arrays in their time
complexity. The primary difference is that a Python list can contain objects of many different types.
The array module also provides methods for creating arrays of fixed types with compact
representations, but they are slower to index than lists. Also note that the numeric extensions and
others define array-like structures with various characteristics as well.

Question 6:
How do you make conversion between tuples and lists ?
Answer:
The function tuple (seq) converts any sequence (actually, any.iterable) into a tuple with the same
items in the same order.
For example, tuple([1, 2, 3]) yields (1, 2, 3) and tuple (‘abc’) yields (‘a’, ‘b’, ‘c’). If the argument if a
tuple, it does not make a copy but returns the same object, so it is cheap to call tuple( ) when you
aren’t sure that an object is already a tuple.
The function list(seq) converts any sequence or iterable into a list with the same items in the same
order. For example, list((1, 2, 3)) yields [1, 2, 3] and list (‘abc’) yields [‘a’, ‘b’, ‘c’j. If the argument is a
list, if makes a copy just like se[:j would.

Question 7:
What is the difference between list and tuple ? Give an example .
Answer:
Lists are Python’s general purpose container, often used for collections of similar objects. Lists are
mutable objects that can contain any Python data. Example :
>my list = [ ] # make an Empty list
>my list = [1,1.0+3j, “aperitivo”, true] # make a list containing four entities.
A Tuple is an immutable value (can’t be changed) that can contain any Python data. They are
generally used for small collectioin of data.
Example :
>mytuple = [1, 2, 3, 4) # create a four element tuple.
>mytuple[2] = 4 # Error – tuple can’t be modified. > print mytuple[2], len(mytuple)

Question 8:
What is used to represent Strings in Python ?
Answer:
Using Single Quotes (‘)
You can specify strings using single quotes such as ‘Quote me on this’. All white space i.e. spaces and
tabs are preserved as it is.
Using Double Quotes (”)
Strings in double quotes work exactly the same way as strings in single quotes. An example is

https://onlinestudytest.com/
“What’s your name?”
Using Triple Quotes o(”’ or ” ” “)
You can specify multi-line strings using triple
quotes. You can use single quotes and double
quotes freely within the triple quotes. An example
is
“‘This is a multi-line string. This is the first line. This is the second line.
“What’s your name?,” I asked.
He said “syed saif naqvi.”

Question 9:
Is there a tool help to find bugs or perform static analysis ?
Answer:
Yes, pychecker is a static analysis tool that finds bugs in Python source case and warns about code
complexity and style.
Pylint is another tool that checks if a module satisfies a coding standard, and also make it possible to
write plug-ins to add a custom feature.

Question 10:
Which of the following variable names are invalid ? Justify.
(a) try
(b) 123 Hello
(c) sum
(d) abc@123
Answer:
(a) try : is a keyword can’t be used as an identifier.
(b) 123 Hello : Variable names can’t start with a digit.
(c) abc@123 : Special characters aren’t allowed in variable names.

Question 11:
Name four Python’s basic data types. Why are they called so ?
Answer:
The four basic data types are :

Number

Sequences

Sets

Maps.

These are called so because :

Number data type stores numerical values and is immutable i.e., value of its object cannot be
changed.
These are of 3 types :

Integer and Long

Float/Floatingpoint

Complex

https://onlinestudytest.com/
Sequence is an ordered collection of items, indexed by positive integers, It is a combination of
mutable and non-mutable data types. Three types of sequence data type available in Phyton are
strings, lists and tuples.

Sets in an unordered collection of values of any type, with no duplicate entry. Sets are immutable.
Example S = Set ([1,2,3,4])

Mapping data types are unordered and mutable. Dictonaries falls under mapping.
Example
d = {1 : ‘a’, 2 : Tb’, 3 : ‘c’

Question 12:
Classify the Python data types.
Answer:

Step 1: Read X, Y, Z.
Step 2 : If X > Y continue step 5.
Step 3 : If Y>Z then print “Y is the largest “and continue step 7.
Step 4 : Continue step 6.
Step 5 : If X>Z then print “X is the largest “and continue step 7.
Step 6 : Print “Z is largest”.
Step 7: End. 3

Question 12:
Write an algorithm to print the bigger of any two unique given numbers.
Answer:
The algorithm as :

Step 1: Read two numbers A and B.


Step 2 : Compare A and B.
Step 3 : If A is greater than B then, print A else print B.
Step 4 : Stop. 3

Question 13:
Write an algorithm to input N numbers and find the largest among them.
Answer:
The algorithm as :

https://onlinestudytest.com/
Step 1 : Read N.
Step 2 : Let ctr = 1.
Step 3 : Read Num.
Step 4 : large = Num.
Step 5 : Read next Num.
Step 6 : ctr = ctr + 1.
Step 7 : If (Num > large) then large = Num.
Step 8 : If (ctr < = N) then repeat steps 5 and 6.
Step 9 : Print large.
Step 10 : End. 3

Question 14:
Write an algorithm to compute the sum of odd and even numbers up to N.
Answer:
The algorithm as :

Step 1: Start.
Step 2 : Input N.
Step 3 : sume = 0.
Step 4 : sumo = 0.
Step 5 : ctr = 1.
Step 6 : while (ctr < = N).
If (ctr mod 2 = 0)
sume = sume + ctr
else
sumo = sumo + ctr.
Step 7: Print “sum of even number is” sume.
Step 8 : Print “sum of odd number is” sumo.
Step 9: End.

Question 1:
Draw a flowchart to calculate sum of two numbers
Answer:

https://onlinestudytest.com/
Question 2:
Draw flowchart to convert temperature from Fahrenheit to Celsius.
Answer:

Question 3:
Draw the flowchart to print the largest of any three numbers.
Answer:

Question 4:
Draw the flowchart to print sum of first 100 natural numbers.

https://onlinestudytest.com/
Answer:

14 FLOW CHART AND PYTHON BASIC

14.1 VERY SHORT ANSWER TYPE QUESTIONS (1 MARKS EACH)


Question 1:
Write the output of the given Python code :
a=0
a+ =2
print (a)
Answer:
2

Question 2:
Write the output of the given Python code :

print (3 + 4)
print (3 – 4)
print (3 * 4) print (3/4)
print (3 % 2)
print (3**4) #3 to the fourth power
print (3 // 4) #floor division

https://onlinestudytest.com/
Answer:

7
-1
12
0.75
1
81
0

Question 3:
Write the output of the given Python code :

a = 20
if a > = 22:
print(“if”)
elif a >= 21:
print(“elif”)
else:
print(“else”)

Answer:

else

Question 4:
What is the another name of Comparison Operators?
Answer:
Relational Operators.

Question 5:
Which Operator is used for assigning a value into a variable?
Answer:
Assignment Operators.

Question 6:
Which Operator is used for comparison of values?
Answer:
Logical Operators.

Question 7:
What is the use of “+” operator?
Answer:
The “+” operator adds values on either side of the operator.

Question 8:
What is the use of operator?
Answer:
The operator subtracts right hand operand from left hand operand.

Question 9:
What is the use of “*” operator?

https://onlinestudytest.com/
Answer:
The “*” operator multiplies values on either side of the operator.

Question 10:
What is the use of operator?
Answer:
The 7″ operator divides left hand operand by right hand operand.

Question 11:
What is the use of “%” operator?
Answer:
The “%” operator divides left hand operand by right hand operand and returns remainder.

Question 12:
What is the use of “**” operator?
Answer:
The “**” operator performs exponential (power) calculation on operators.

Question 13:
What is the use of 7/” operator?
Answer:
The 7/” operator results is the quotient in which the digits after the decimal point are removed.

Question 14:
What is the use of “= =” operator?
Answer:
It checks if the value of two operands are equal or not, if yes then condition becomes true.

Question 15:
What is the use of “! =” operator?
Answer:
It checks if the value of two operands are equal or not, if values are not equal then condition
becomes true.

Question 16:
Why do we use ” < > “operator?
Answer:
It checks if the value of two operands are equal or not, if values are not equal then condition
becomes true.

Question 17:
Describe the use of “>” operator?
Answer:
It checks if the value of left operand is greater than the value of right operand, if yes then condition
becomes true.

Question 18:
Why we use “<” operator?
Answer:
The “<” operator checks if the value of left operand is less than the value of right operan d, if yes
then condition becomes true.

https://onlinestudytest.com/
Question 19:
What value has been check by ” > = ” operator?
Answer:
It checks if the value of left operand is greater than or equal to the value of right operand, if yes then
condition becomes true.

Question 20:
Write syntax for “greater than or equal to” operator.
Answer:
a>=b

Question 21:
What value have been check by ” < = ” operator?
Answer:
It checks if the value of left operand is less than or equal to the value of right operand, if yes then
condition becomes true.
Question 22:
Is ” < =” a Assignment operator ?
Answer:
No,”< =” is not assignment operator.

Question 23:
Optimize these statements as a Python programmer.

1 word = ‘word’
2 print word._len_()

Answer:

1 word = ‘word’
2 print len(word)

Question 24:
How many types of operations are supported by the Python language ?
Answer:
Python language supports the following types of operations.

• Arithmetic operations
• Comparison (i.e. Rotational) operations
• Assignment operations
• Logical operations
• Bitwise operations
• Membership operations
• Identity operations.

Question 25:
What will be the output of the following code :

1a=1
2 a, b = a+1, a+1
3 print a
4 print b

https://onlinestudytest.com/
Answer:

2
2

Question 26:
Is there an equivalent of C’s “?:” ternary operator in Python ?
Answer:

No.

14.2 SHORT ANSWER TYPE QUESTIONS (2 MARKS EACH )


Question 1:
What do you mean by Operator precedence?
Answer:
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator.

Question 2:
Assume if A = 60; and B = 13; then find the values of the following :
A&B
A|B
Answer:
Here in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
hence
A&B = 0000 1100 and A|B = 00111101

Question 3:
Assume if A = 60; and B = 13, then find the values of the following.
A ∧ Band ~A
Answer:
Here in binary format they will be as follows :
A = 00111100 B = 0000 1101
hence
A ∧ B = 0011 0001 and ~A = 1100 0011

Question 4:
Explain assigning values to variables in Python.
Answer:
Python variables do not have to be explicitly declared to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to assign
values to variables.

The operand to the left of the = operator is the name of the variable, and the operand to the right of
the = operator is the value stored in the variable.
For example:
# !/usr/bin/python

https://onlinestudytest.com/
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = “John” # A string
print counter
print miles
print name
while running this program, this will produce the following result:
100
1000.0
John

Question 5:
Write the output of the following Python code

a=6
b=7
c = 42
print 1, a = = 6
print 2, a = = 7
print 3, a = = 6 and b = = 7
print 4, a = = 7 and b = = 7
print 5, not a = = 7 and b = = 7
print 6,a==7orb==7
print 7, a==7orb==6
print 8, not (a = = 7 and b = = 6)
print 9, not a = = 7 and b = = 6

Answer:

1 True
2 False
3 True
4 False
5 True
6 True
7 False
8 True
9 False

Question 6:
What do you mean by expression “a = 5” ?
Answer:
This statement assigns the integer value 5 to the variable a. The part at the left of the assignment
operator (=) is known as the 1 value (left value) and the right one as the r value (right value). The l
value has to be a variable whereas the l value can be either a constant, a variable, the result of an
operation or any combination of these.

Question 7:
What do you mean by statement in Python?
Answer:

https://onlinestudytest.com/
A statement is an instruction that the Python interpreter can execute. We have seen two kinds of
statements: print and assignment.
When you type a statement on the command line, Python executes it and displays the result, if there
is one. The result of a print statement is a value. Assignment statements don’t produce a result.

Question 8:
What do you mean by expression in Python ?
Answer:
An expression is a combination of values, variables, and operators. If you type an expression on the
command line, the interpreter evaluates it and displays the result:

Question 9:
Explain Operators and Operands?
Answer:
Operators are special symbols that represent computations like addition and multiplication. The
values the operator uses are called Operands.
Question 10:
Use IDLE to calculate : [CBSE Text Book]
(a) 6 + 4 * 10
(b) (6 + 4) * 10

Answer:

(a) 6 + 40 = 46
(b) 10 * 10 = 100

Question 11:
What will be the output of the following code : [CBSE Text Book]
a = 3 – 4 + 10 b = 5 * 6 c = 7.0/8.0
Answer:
Print “These are the values a, b, c.
These are the values : 9300.0.

14.3 LONG ANSWER TYPE QUESTIONS (5 MARKS EACH )


Question 1:
Write a example of comparison operators.
Answer:
Following example to understand all the comparison operators available in Python programming
language:

# !/usr/bin/python
a = 21
b = 10
c =0
if (a = = b ):
print “Line 1 – a is equal to b”
else:
print “Line 1 – a is not equal to b”
if ( a ! = b ):

https://onlinestudytest.com/
print “Line 2 – a is not equal to b”
else:
print “Line 2 – a is equal to b”
if (a <> b):
print “Line 3 – a is not equal to b”
else:
print “Line 3 – a is equal to b”
if ( a < b ):
print “Line 4 – a is less than b”
else:
print “Line 4 – a is not less than b”
if (a > b ):
print “Line 5 – a is greater than b”
else:
print “Line 5 – a is not greater than b”
a = 5;
b = 20;
if (a < = b):
print “Line 6 – a is either less than or equal to b”
else:
print “Line 6 – a is neither less than nor equal to b”
if (b > = a):
print “Line 7 – b is either greater than or equal to b”
else:
print “Line 7 – b is neither greater than nor equal to b”

When you execute the above program it produces following result:

Line 1 – a is not equal to b


Line 2 – a is not equal to b
Line 3 – a is not equal to b
Line 4 – a is not less than b
Line 5 – a is greater than b
Line 6 – a is either less than or equal to b
Line 7 – b is either greater than or equal to b

Question 2:
Give an example of arithmetic operators.
Answer:
Following example to understand all the arithmetic operators available in Python programming
language:

# !/usr/bin/python
a = 21
b = 10
c =0
c =a+ b
print “Line 1 – Value of c is “, c
c = a -b
print “Line 2 – Value of c is “, c

https://onlinestudytest.com/
c =a* b
print “Line 3 – Value of c is “, c
c = a/b
print “Line 4 – Value of c is “, c
c =a% b
print “Line 5 – Value of c is “, c
a=2
b=3
c = a**b
print “Line 6 – Value of c is “, c
a = 10
b=5
c = a//b
print “Line 7 – Value of c is “, c

When you execute the above program it produces following result:

Line 1 – Value of c is 31
Line 2 – Value of c is 11
Line 3 – Value of c is 210
Line 4 – Value of c is 2
Line 5 – Value of c is 1
Line 6 – Value of c is 8
Line 7 – Value of c is 2

Question 3:
Write a program in Python to explain assignment operators
Answer:
Following example to understand all the assignment operators available in Python programming
language :

# !/usr/bin/python
a = 21
b = 10
c =0

c =a+ b
print “Line 1 – Value of c is “, c

c += a
print “Line 2 – Value of c is “, c

c *= a
print “Line 3 – Value of c is “, c

c/= a
print “Line 4 – Value of c is “, c

c =2
c %= a
print “Line 5 – Value of c is “, e

https://onlinestudytest.com/
c**= a
print “Line 6 – Value of c is “, c

c//= a
print “Line 7 – Value of c is “, c

When you execute the above program it produces following result:

Line 1 – Value of c is 31
Line 2 – Value of c is 52
Line 3 – Value of c is 1092
Line 4 – Value of c is 52
Line 5 – Value of c is 2
Line 6 – Value of c is 2097152
Line 7 – Value of c is 99864

Question 4:
Write source code in Python to explain bitwise operators.
Answer:
Following example to understand all the bitwise operators available in Python programming
language:

# !/usr/bin/python

a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c =0

c = a & b; # 12 = 0000 1100


print “Line 1 – Value of c is “, c

c = a | b; # 61 = 0011 1101
print “Line 2 – Value of c is “, c

c = a ∧ b; # 49 = 0011 0001
print “Line 3 – Value of c is “, c

c = ~a; # -61 = 1100 0011


print “Line 4 – Value of c is “, c

c = a < < 2; #240 = 1111 0000


print “Line 5 – Value of c is “, c

c = a > > 2; # 15 = 00001111


print “Line 6 – Value of c is “, c

When you execute the above program it produces following result:

Line 1 – Value of c is 12
Line 2 – Value of c is 61
Line 3 – Value of c is 49
Line 4 – Value of c is -61
Line 5 – Value of c is 240
Line 6 – Value of c is 15

https://onlinestudytest.com/
Question 5:
Write a program in Python to explain logical operators.
Answer:
Following example to understand all the logical operators available in Python programming
language:

#!/usr/b in/python

a = 10
b = 20
c =0
if (a and b):
print “Line 1 – a and b are true”
else:
print “Line 1 – Either a is not true or b is not true”

if (a or b):
print “Line 2 – Either a is true or b is true or both are true”
else:
print “Line 2 – Neither a is true nor b is true”

a=0
if ( a and b ):
print “Line 3 – a and b are true”
else:
print “Line 3 – Either a is not true or b is not true”

if ( a or b ):
print “Line 4 – Either a is true or b
is true or both are true”
else:
print “Line 4 – Neither a is true nor b is true”
if not( a and b) :
print “Line 5 – a and b are true” else:
print “Line 5 – Either a is not true or b is not true”

When you execute the above program it produces following result:

Line 1 – a and b are true


Line 2 – Either a is true or b is true or both are true
Line 3 – Either a is not true or b is not true
Line 4 – Either a is true or b is true or both are true
Line 5 – a and b are true

Question 6:
Write source in Python code for membership operators.
Answer:
Following example to understand all the membership operators available in Python programming
language :

#!/usr/bin/python
a = 10

https://onlinestudytest.com/
b = 20
list = [1,2,3,4, 5 ];

if ( a in list):
print “Line 1 – a is available in the given list”
else:
print “Line 1 – a is not available in the given list”

if (b not in list):
print “Line 2 – b is not available in the given list”
else:
print “Line 2 – b is available in the given list”

a=2
if ( a in list):
print “Line 3 – a is available in the given list”
else:
print “Line 3 – a is not available in the given list”

When you execute the above program it produces following result:

Line 1 – a is not available in the given list


Line 2 – b is not available in the given list
Line 3 – a is available in the given list

Question 7:
Write source in Python code for identity operators.
Answer:
Following example to understand all the identity operators available in Python programming
language :

# !/usr/bin/py thon

a = 20
b = 20

if (a is b):
print “Line 1 – a and b have same
identity”
else:
print “Line 1 – a and b do not have
same identity”
if (id(a) = = id(b)):
print “Line 2 – a and b have
same identity”
else:
print “Line 2 – a and b do not have same identity”
b = 30
if (a is b ):
print “Line 3 – a and b have same
identity”

https://onlinestudytest.com/
else:
print “Line 3 – a and b do not have same identity”

if (a is not b ):
print “Line 4 – a and b do not have
same identity”
else:

print “Line 4 – a and b have same identity”

When you execute the above program it produces following result:

Line 1 – a and b have same identity


Line 2 – a and b have same identity
Line 3 – a and b do not have same identity
Line 4 – a and b do not have same identity

Question 11:
Give example to understand operator precedence available in Python programming language .
Answer:
Following example to understand operator precedence available in Python programming language :

#!/usr/bin/python

a = 20
b = 10
c = 15
d=5
e =0
e = (a + b)*c/d #(30*15)/5
print “Value of (a + b) * c / d is “, e

e = ((a + b) * c)/d #(30*15)/5


print “Value of ((a + b) * c) / d is “, e

e = (a + b) * (c / d); # (30) * (15/5)


print “Value of (a + b) * (c / d) is “, e

e = a + (b*c)/d; # 20 + (150/5)
print “Value of a + (b * c) / d is “, e

When you execute the above program it produces following result:

Value of (a + b) * c / d is 90
Value of ((a + b) * c) / d is 90
Value of (a + b) * (c / d) is 90
Value of a + (b * c) / d is 50

Question 12:
How are comments written in a program ?
Answer:
As the program gets bigger, it becomes difficult to read it, and to make out what it is doing by just
looking at it. So it is good to add notes to the code, while writing it. These notes are known as
comments. In Python, comment start with ‘#’ symbol. Anything written after # in a line is ignored by

https://onlinestudytest.com/
interpreter, i.e. it will not have any effect on the program.
For example,
# calculating area of a square > > > area = side * * 2
For adding multi-line comment in a program :
(i) Place ‘#’ in front of each line, or,
(ii) Use triple quoted string. They will only work as comment, when they are not being used as
docstring

15 PYTHON PROGRAMMING

15.1 VERY SHORT ANSWER TYPE QUESTIONS (1 MARKS EACH )


Question 1:
What is sys.argv?

https://onlinestudytest.com/
Answer:
A list containing the program name and all the command-line arguments to a program.

Question 2:
What can you do with the eval function?
Answer:
Eval(s) evaluates an expression contained in a string s and returns the resulting object.

Question 3:
What does sys.argv[1:] mean?
Answer:
A list of the command-line arguments.

Question 4:
What type of errors does the exception type NameError correspond to?
Answer:
A variable that is not initialized (defined), perhaps a variable/function that is misspelled.

Question 5:
Why we use ceil(x) function?
Answer:
It returns the ceiling of x as a float, the smallest integer value greater than or equal to x.

Question 6:
Why we use floor(x) function?
Answer:
It returns the floor of x as a float, the largest integer value less than or equal to x.

Question 7:
Explain fabs(x) in python?
Answer:
It returns the absolute value of x.

Question 8:
What value will be return by exp(x) ?
Answer:
Returns e**x.

Question 9:
What value will be return by log10(x) ?
Answer:
Returns the base-10 logarithm of x. This is usually more accurate than log(x,10).

Question 10:
What value will be return by sqrt(x)?
Answer:
Returns the square root of x.

Question 11:
What value will be return by cos(x)?
Answer:
Returns the cosine of x radians.

https://onlinestudytest.com/
Question 12:
Write the output of sin(O)?
Answer:
Returns the zero.

Question 13:
Define tan(x) function in python.
Answer:
Tan(x) function return the tangent of x radians.

Question 14:
Why we use degrees(x) ?
Answer:
It converts angle x from radians to degrees.

Question 15:
What is the advantage of radians(x) ?
Answer:
It converts angle x from degrees to radians.
Question 16:
What value will be return by random() ?
Answer:
Return the next random floating point number in the range (0.0,1.0).

Question 17:
“A module cannot contain a main program”. Is this statement true?
Answer:
False

Question 18:
What gets printed? Assuming python version 2.x print type(l/2)
Answer:
<type’int’>

Question 19:
What is the output of the following code? print type([l,2])
Answer:
< type’list’>

Question 20:
What is the output of the following code? def f(): pass print type(f() )
Answer:
<type’NoneType’>

Question 21:
What should the below code print?
print type(1J)
Answer:
< type’complex’>

https://onlinestudytest.com/
Question 22:
What will be the output of the following code

class c (object):
….def_init_(self):
self.x = 1
C = C()
print C.X
print C.X
print C.X
print C.X

Answer:

All the outputs will be 1, since the value of the objects attribute (X) is never changed .
1
1
1
1
X is now a part of the public members of the class C. Thus it can be accessed directly.

Question 23:
What gets printed with the following code ?

d= lambda p: p * 2
t = lambda p: p * 3
x =2
x = d(x)
x = t(x)
x = d(x)
print x

Answer:

24

Question 24:
What gets printed with the following code ?

x = 4.5
y=2
print x//y

Answer:

2.0

Question 25:
What gets printed with the following code ?
print “hello” ‘world’
Answer:
On one line the text: helloworld

https://onlinestudytest.com/
Question 26:
What gets printed by the code snippet below?
import math
print math.floor(5.5)
Answer:
5.0

Question 27:
What gets printed by the code snippet below?
x = “foo ”
y=2
print x + y
Answer:
An exception is thrown.

Question 28:
What does the following code do?
def a(b, c, d): pass
Answer:
It defines a function, which does nothing.

Question 29:
What do you mean by function?
Answer:
A function is a block of organized, reusable code that is used to perform a single, related action.

Question 30:
Do Python supports built-in functions?
Answer:
Yes, Python gives you many built-in functions like print() etc.

Question 31:
Can First statement of a function be optional?
Answer:
Yes, The first statement of a function can be an optional statement.

Question 32:
Why we use return [expression] in Python?
Answer:
The statement return [expression] exits a function.

Question 33:
Write syntax for function that takes a string as input parameter and prints it on standard screen.
Answer:
def printme (str):
“This prints a passed string into this function”
print str
return

https://onlinestudytest.com/
Question 34:
Why do we define a function?
Answer:

● Decomposing complex problems into simpler pieces.


● Reducing duplication of code.

Question 35:
When we can execute a function?
Answer:
Once the basic structure of a function is finalized, we can execute it

Question 36:
Are all parameters (arguments) in the Python language passed by reference .
Answer:
Yes,All parameters (arguments) in the Python language are passed by reference.

Question 37:
How do we define a function ?
Answer:
Here are simple rules to define a function in Python.

● Function blocks begin with the keyword def followed by the function name and Parentheses ()
● Any input parameters or arguments should be placed within these parentheses.
● The first statement of a function can be an optional statement – the documentation string of the
function or docstaing.
● he code block within every function start with color(:) and is indented.
● The statement return [expression] exits a function, optionally passing back an expression to the
caller. A return statement with no arguments is the same as return none.

Question 38:
What are the various types of para-meters ?
Answer:

Question 39:
What are Required arguments?
Answer:
Required arguments are the arguments passed to a function in correct positional order.

Question 40:
Explain default argument.
Answer:
A default argument is an argument that assumes a default value, if a value is not provided in the
function call.

https://onlinestudytest.com/
Question 41:
Write the syntax of lambda functions?
Answer:
The syntax of lambda functions contains only a single statement, which is as follows:
lambda[arg1 [,arg2, argn]] :expression

Question 42:
What is the use of lambda keyword in Python?
Answer:
You can use the lambda keyword to create small anonymous functions.

Question 43:
Explain return keyword.
Answer:
The statement return [expression] exits a function, optionally passing back an expression to the
caller.
Question 44:
Define scope of a variable.
Answer:
The scope of a variable determines the portion of the program where you can access a particular
identify.

Question 45:
What are two basic scopes of variables in Python?
Answer:
Global variables and Local variables.

Question 46:
What does the following code do? def simpleFunction():
“This is a cool simple function that returns 1”
return 1
print simpleFunction._doc_[10:14]
Answer:
cool

Question 47:
Which variables have local scope?
Answer:
Variables that are defined inside a function body have a local scope.

Question 48:
Which variables have global scope?
Answer:
Variables that are defined outside a function body have a global scope.

15.2 SHORT ANSWER TYPE QUESTIONS (2 MARKS EACH )


Question 1:
What is a Python module ? What is its significance ? .
Answer:

https://onlinestudytest.com/
A ‘module’ is a chunk of python code that exists in its own (.pu) file and is intended to be used by
python code outside iteself. Modules allow one to fundle together code in a form in which it can
easily be used later.
The modules can be ‘imported’ in other programs so the function and other definitions in imported
modules becomes availabe to code that imports them.

Question 2:
“Python has certain functions that you can readily use without having to write any special code.”
What type of functions are these ?
Answer:
The pre-defined functions that are always available for use are known as python’s built-in functions.
For example :
len (), type (), int (), raw-input () etc.

Question 3:
What is the utility of built-in function help () ?
Answer:
Python’s built in function help ( ) is very useful. When it is provided with a program-name or a
module-name or a function-name as an argument, it displays the documentation of the argument as
help. It also displays the docstrings within its passed-argument’s definition. For example :
help (math)
will display the documentation related to module math.

Question 4:
What is the utility of Python standard library’s math module and random module ?
Answer:
Math module is used for math related functions that work with all number types except for complex
numbers, radom module is used for different random number generator functions.

Question 5:
What is raw_input?
Answer:
It is a function which takes a string (e.g., a question) as argument, writes the string to the terminal
window, halts the program and lets the user write in text on the keyboard, and then the text is
returned to the calling code as a string object.

Question 6:
What value will be return by log(x[, base])?
Answer:
With one argument, return the natural logarithm of x (to base e).
With two arguments, return the logarithm of x to the given base, calculated as log(x) log(base)

Question 7:
Define pow(x, y) function in Python ?
Answer:
Return x raised to the power y.. In particular, pow(1.0, x) and pow(x, 0.0) always return 1.0, even
when x is a zero or a NaN. If both x and y are finite, x is negative, and y is not an integer then pow(x,
y) is undefined, and raises ValueError.

Question 8:
Determine what is printed by the following program listinput.py,

https://onlinestudytest.com/
list1 = eval(raw_input(‘Give a list:’))
list2 = eval(raw_input(‘Give another list:’))
print list1 + list2
When the program is running as follows:
Unix/DOS > python listinput.py
Give a list: ‘[1,2]’
Give another list: “[3,4]”
Answer:
[1,2] [3,4]

Question 9:
What will be the output of this program?
a = 20.3
b = ‘Python’
c = ‘”Python”‘
d = 21
print isinstance(a, float),
print isinstance(b, (str, int)),
print isinstance(c, (str, str)),
print isinstance(d, (float, str))
Answer:
True, True, True, False.

Question 10:
Write any Python expression which is a valid input argument to the following program?
input = eval(raw_input(‘Value:’))
print ‘You typed’, value
Answer:
‘one’

Question 11:
Given the program
from scitools.StringFunction import
StringFunction
import sys
formula = sys.argv[1]
f = StringFunction(formula)
print f(2)
Will this input work?
Unix/DOS > python function.py ‘t**2’
Answer:
No, This input will not work

Question 12:
What will happen when you run the following program:
import sys
try:
t = sys.arg[1]
a = sys.arg[2]
except:

https://onlinestudytest.com/
print ‘You must provide TWO
command-line arguments!!!’
sys.exit(1)
s = 0.5*a*t**2
print s
Answer:
The program will always respond with, “You must provide TWO command-line arguments!!!”,
regardless of what you write on the command line

Question 13:
How can you make a module ‘helloworld’ out of these two functions?
def hello():
print ‘Hello,’,

def world(): print ‘World!’


Answer:
Put the functions in a file with name helloworld.
py

Question 14:
Write a program to read the user name using raw_input() and display back on the screen using
print()
Answer:
#!/usr/bin/python
name=raw_input(‘Enter your name :’)
print (“Hi %s, Let us be friends!” % name);

Question 15:
What does the len() function do?
Answer:
It gets the length of the string that you pass to it then returns it as a number. Play with it.

Question 16:
How do you make a higher order function in Python ?
Answer:

● A high order function accepts one or more functions as input and returns a new function.
Sometimes it is required to use function as data.
● To make high order function, one need the import functools module .
● The functools.partial() function is used often for high order function.

Question 17:
What value will be return by “choice(seq)” ?
Answer:
A random item from a list, tuple, or string.

Question 18:
What value will be return by “random()” ?
Answer:
A random float r, such that 0 is less than or equal to r and r is less than 1.

https://onlinestudytest.com/
Question 19:
Give an example of “choice()”
Answer:

The following example shows the usage of choice( ) method.


# !/usr/bin/py thon
import random
print “choice([l, 2, 3, 5, 9]): “,
random.choice([l,2,3,5,9])
print “choice(‘A String*): “,
random.choice(‘A String’)

This will produce the following result choice

([l, 2, 3,5,9]): 2
choice(‘A String’) :n

Question 20:
Give an example of “random()”
Answer:
The following example shows the usage of random() method.

# !/usr/bin/python
import random
# First random number
print “random(): ” ,
random.random() # Second random number print “random(): “,
random.random()
This will produce the following results
random(): 0.281954791393
random(): 0.309090465205

Question 21:
Describe trignometric functions ?
Answer:
Python includes following functions that perform trignometric calculations.

Function Description

acos(x) Return the arc cosine of x, in radians.

asin(x) Return the arc sine of x, in radians.


atan(x) Return the arc tangent of x, in radians.
atan2(y, x) Return atan(y/x), in radians.
cos(x) Return the cosine of x radians.
hypot(x, y) Return the Euclidean norm, sqrt(x*x + y^y).

sin(x)

https://onlinestudytest.com/
tan(x)

degrees(x) Converts angle x from radians to degrees.

radians(x) Converts angle x from degrees to radians.


Question 22:
Describe random functions ?
Answer:
Random numbers are used for fames, simulations, testing, security, and privacy applicatons. Python
includes following functions that are commonly used.

Function Description

choice(seq) A random item from a list, tuple, or string.

randrange ([start,] stop [,Step]) A randomly selected element from range(start, stop, step)

random() A random float, such that 0 is less than or equal to r and r is less than 1

Sets the integer starting value used in generating random numbers. Call this func
seed([x])
before calling any other random module function. Returns None.

shuffle(Ist) Randomizes the items of a list in plae. Returns None.

Uniform(x, y) A random float r, such that x is less than or equal to r and r is less than y

Question 23:
Write a program to swap two numbers.
Answer:
a=5
b=9
def swap(c,d):
return d,c
swap(a,b)

Question 24:
What are the rules to define a function in Python?
Answer:
You can define functions to provide the required functionality. Here are simple rules to define a
function in Python:

(1) Function blocks begin with the keyword def followed by the function name and parentheses (( ))
(2) Any input parameters or arguments should be placed within these parentheses. You can also
define parameters inside these parentheses.
(3) The first statement of a function can be an optional statement-the documentation string of the
function or docstring.
(4) The code block within every function starts with a colon (:) and is indented.
(5) The statement return [expression] exits a function, optionally passing back an expression to the
caller. A return statement with no arguments is the same as return None.

https://onlinestudytest.com/
Question 25:
Give an example for defining a function.
Answer:
def functionname(parameters):
“function_docstring” function_suite
return[expression]

Question 26:
Write a program to illustrate function call.
Answer:
#!/usr/bin/python # Function definition is here
def printme(str): “This prints a passed string into this function”
print tr;
return; # Now you can call printme function printme(“Mohd saif naqvi”) ;
printme(“Chairman of Waltons Technology”)
It produces following result:
Mohd saif naqvi
Chairman of Waltons Technology
Question 27:
Write a program to illustrate “Pass by refe-rence vs value”
Answer:
#!/usr/bin/python # Function definition is here
def changeme(mylist): “This changes a passed list into this function”
mylist.append([l,2,3,4]);
print “Values inside the function: “, mylist
return # Now you can call changeme
function mylist=[10,20,30];
changeme(mylist);
print “Values outside the function: “, mylist
It produce following result:
Values inside the function: [10, 20,30, [1,2,3,4]]
Values outside the function: [10,20, 30, [1,2,3,4]]

Question 28:
Write a program to illustrate “Required arguments”.
Answer:

#!/usr/bin/python
# Function definition is here
def printme (str): “This prints a passed string into this function”
print str;
return;
# Now you can call printme function printme();
It produces following result:
Traceback (most recent call last):
File “test.py”, line 11, in <module>
printme()
TypeError: printme() takes exactly 1 argument (0 given)

https://onlinestudytest.com/
Question 29:
Write a program to illustrate “Keyword arguments”.
Answer:

#!/usr/bin/python
# Function definition is here
def printme(str):”Thisprints a passed string into this function”
print str;
return;
# Now you can call printme function
printme(str=”My string”);
When the above code is executed, it produces following result:
My string

Question 30:
Write a program to illustrate “default argument”.
Answer:

#!/usr/bin/python
# Function definition is here
def printinfo(name,age=35):
“This prints a passed info into this function”
print “Name: “,
name; print “Age “,
age return;
# Now you can call printinfo function
printinfo(age=50,name=”miki”);
printinfo(name=”miki”);

When the above code is executed, it produces following result:

Name: miki
Age 50
Name:miki
Age 35

Question 31:
Write a program to illustrate “variablelength arguments”.
Answer:

#!/usr/bin/python
# Function definition is here
def printinfo(argl,*vartuple):
“This prints a variable passed arguments”
print “Output is:”
print argl for var in vartuple :
print var return;
# Now you can call printinfo function
printinfo(10); printinfo(70,60,50);

When the above code is executed, it produces following result:

https://onlinestudytest.com/
Output is:
10
Output is:
70
60
50

Question 32:
Explain Global vs. Local variables.
Answer:
Variables that are defined inside a function body have a local scope, and those defined outside have
a global scope.
This means that local variables can be accessed only inside the function in which they are declared
whereas global variables can be accessed throughout the program body by all functions. When you
call a function, the variables declared inside it are brought into scope.

Question 33:
Explain anonymous functions.
Answer:
You can use the lambda keyword to create small anonymous functions. These f unctions are called
anonymous because they are not declared in the standard manner by using the def keyword,
lambda functions have their own local namespace and cannot access variables other than those in
their parameter list and those in the global namespace.

Question 34:
Explain Scope of Variables.
Answer:
All variables in a program may not be accessible at all locations in that program. This depends on
where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a particular
identifier. There are two basic scopes of variables in Python :

(1) Global variables


(2) Local variables

Question 35:
What do you mean by module ?
Answer:
A module allows you to logically organize your Python code. Grouping related code into a module
makes the code easier to understand and use. A module is a Python object with arbitarily named
attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions, classes, and
variables. A module can also include runnable code.

Question 36:
What do you mean by globals() and locals () Functions.
Answer:
The globals( ) and locals( ) functions can be used to return-the names in the global and local
namespaces depending on the location from where they are called.
If locals() is called from within a function, it will return all the names that can be accessed locally

https://onlinestudytest.com/
from that function.
If globals() is called from within a function, it will return all the names that can be accesse d globally
from that function .The return type of both these functions is dictionary. Therefore, names can be
extracted using the keys() function

Question 37:
Explain reload)) Function.
Answer:
When the module is imported into a script, the code in the top-level portion of a module is executed
only once.Therefore, if you want to re-execute the top -level code in a module, you can use the
reload() function.
The reload() function imports a previously imported module again. The syntax of the reload))
function is this :
reload (module_name)

Question 38:
What are docstrings ? How are they useful ?
Answer:
A docstring is just a regular python triple- quoted string that is the first thing in a function body or a
module or a class. When executing a function body the docstring does not do anything like
comments, but Python stores it as part of the function documentation. This documentation can later
be displayed using help)) function. So even though docstrings appear like comments but these are
different from comments.

Question 39:
Find the error
def minus (total, decrement)
output = total – decrement
return output
Answer:
The function’s header has colon missing at the end.
So add colon (:) at end of header line.
Thus, the correct code is

def minus (total, decrement)


output = total – decrement
return output

Question 40:
What would be the output produced by the following code :
import math
import random
print math=ceil (random.random)))
Answer:
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.

https://onlinestudytest.com/
Question 41:
Find the error(s) in the following code and correct them:

def describe intelligent life form ():

height = raw_input (“Enter the height”)

raw_input (“Is it correct ?”)

weight = raw_input (“Enter the weight”)

favorite-game = raw_input (“Enter favorite game”)

print “your height”, height, ‘and weight’, weight

print “and your favorite game is”, favorite- game, ‘.’

Answer:
Here, function name contains spaces. But function name should be a valid Python identifier with no
spaces in between. And here, no variable is defined to obtain value being input. Lines 4 and 6 are
badly indented; being part of same function, those should be at the same indentation level as that of
lines 2, 3, 5 and 7. And also, variable favourite-game is an invalid identifier as it contains a hyphen,
but it should have been an underscore.

Question 42:
Write a function that:

(i) Asks the user to input a diameter of circle in inches.


(ii) Sets a variable called radius to one half of that number.
(iii) Calculate the area of circle.
(iv) Print the area of circle with appropriate unit.
(v) Return this same amount as the output of the function.

Answer:

def area_circle ():


import math
diameter=float (raw_input (“Enter the diameter in Inches))
radius = diameter 12
area_circle_inches = (math.pi) * (radius * * 2)
print “The area of circle, area_circle_ inches
return (area_circle_inches)

Question 43:
What would be the output of the follow-ing ? Explain. [CBSE Text Book]
def fl(): n = 44 def f2 (): n = 77
print “value of n”, n () print “value of n”, n
Answer:
value of n
Name Error : name ‘n’ is not defined.

https://onlinestudytest.com/
15.3 LONG ANSWER TYPE QUESTIONS (4 MARKS EACH )
Question 1:
Explain Comments in Python.
Answer:
Comments in Python :
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to
the physical line end are part of the comment, and the Python interpreter ignores them.

# !/usr/bin/python
# First comment
print
“Hello, Python!”
;
# second comment
This will produce following result:
Hello, Python!
A comment may be on the same line after a
statement or expression:
name
=
“Madisetti”
# This is again comment
You can comment multiple lines as follows :
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.

Question 2:
What are the various types of functions available in Python ?
Answer:

Built-in functions are those that are built into Python and can be accessed by a programmer, e.g.
raw_input, len(s),
A module is a file containing Python defintions and statements. We need to import modules to use
any of its functions or variables in our code.
e.g. import math
value = math.sqrt (64).
User-defined functions are created by the programmer.
e.g. def area (side):
a = side * side
return a

https://onlinestudytest.com/
Question 3:
Explain the term ‘Module’.
Answer:
Module : A module is a file containing Python definitions and statements. Standard library of Python
is extended as modules to a programmer. Definitions from the module can be used within the code
of a program. To use these modules in the program, a programmer needs to import the module.
There are many ways to import a module in program :
(i) Import
(ii) from
(i) Import: It is simplest and most common way to use modules in our code. Its syntax is :
> > > import module name 1 [, module name 2,………. ]
Example,
> > > import math
> > > value = math.sqrt (25)
(ii) From : It is used to get a specific function in the code instead of the complete module file .
If we know before hand which functions, we will be needing, then we may use ‘from’. For modulus
having large number of functions, it is recommended to use ‘from’ instead of import. Its syntax is
> > > from module name import function name 1 [, function name 2, ……….]
Example,
> > > from math import sqrt
> > > value = math . sqrt (36)

Question 4:
Explain ceil(x) in python.
Answer:
ceil(x)
Description : The method ceil( ) returns ceiling value of x-the smallest integer not less than x.
Syntax:
Following is the syntax for ceil()
method import math
math.ceil(x)
Note: This function is not accessible directly so we need to import math module and then we need
to call this function using math static object.
Parameters : x—This is a numeric expression.
Return Value : This method returns smallest integer not less than x .
Example:

# !/usr/bin/py thon
import math # This will import math module
print “math.ceil(-45.17):”,
math.ceil(-45.17)
print “math.ceil(100.12):”,
math.ceil(100.12)
print “math.ceil(100.72):”,
math.ceil(100.72)
print “math.ceil(119L):”,
math.ceil(119L)
print “math.ceil(math.pi):”,
math.ceil(math.pi),

https://onlinestudytest.com/
This will produce the following result
math.ceil(-45.17) :-45.0
math.ceil(100.12): 101.0
math.ceil(100.72): 101.0
math.ceil(119L): 119.0
math.ceil(math.pi): 4.0

Question 5:
Explain exp(x) in python with example.
Answer:
Description : The method exp( ) returns exponential of x : ex.
Example:
Syntax: Following is the syntax for exp() method
import math
math.exp(x)
Note: This function is not accessible directly so w e need to import math module and then we need
to call this function using math static object.
Parameters : x—This is a numeric expression.
Return Value: This method returns exponential of x: ex.
Example: The following example shows the usage of exp() method

# !/usr/bin/py thon
import math # This will import math module
print “math.exp(-45.17): “,
math.exp(-45.17)
print “math.exp(100.12):”,
math.exp(100.12)
print “math.exp(100.72):”,
math.exp(100.72)
print “math.exp(119L):”,
math.exp(119L)
print “math.exp(math.pi):”,
math.exp(math.pi),

This will produce the following result

math.exp(-45.17): 2.41500621326e-20
math.exp(100.12): 3.03084361407e+43
math.exp(100.72): 5.52255713025e+43
math.exp(119L): 4.7978133273e+51
math.exp(math.pi): 23.1406926328

Question 6:
Explain floor(x) in Python with example.
Answer:
The method floor() returns floor of x – the largest integer not greater than x.
Syntax: Following is the syntax for floor() method
import math
math.floor(x)
Note: This function is not accessible directly so we need to import math module and then we need

https://onlinestudytest.com/
to call this function using math static object.
Parameters : x — This is a numeric expression.
Return Value: This method returns largest integer not greater than x.
Example: The following example shows the usage of floor() method.

# !/usr/bin/python
import math # This will import math module
print “math.floor(-45.17): “,
math.floor(-45.17)
print “math.floor(100.12): “,
math.floor(100.12)
print “math.floor(100.72): “,
math.floor(100.72)
print “math.floor(119L):”,
math.floor(119L)
print “math.floor(math.pi):”,
math.floor(math.pi)

This will produce the following result:

math.floor(-45.17) :-46.0
math.floor(100.12): 100.0
math.floor(100.72): 100.0
math.floor(119L): 119.0
math.floor(math.pi): 3.0

Question 7:
Explain log(x) in Python with example.
Answer:
Description : The method log( ) returns natural logarithm of x, for x > 0.
Syntax : Following is the syntax for log() method
import math
math.log(x)
Note: This function is not accessible directly so we need to import math module and then we need
to call this function using math static object.
Parameters : x — This is a numeric expression.
Return Value: This method returns natural logarithm of x, for x > 0.
Example: The following example shows the usage of log() method.

# !/usr/bin/python
import math # This will import
math module
print “math.log(100.12): ” ,
math.log(100.12)
print “math.log(100.72): “,
math.log(100.72)
print “math.log(119L):”,
math.log(119L)
print “math.log(math.pi):”,
math.log(math.pi)

https://onlinestudytest.com/
This will produce the following result:

math.log(100.12): 4.60636946656
math.log(100.72): 4.61234438974
math.log(119L): 4.77912349311
math.log(math.pi): 1.14472988585

Question 8:
Explain loglO(x) in Python with example.
Answer:
Description: The method logl0() returns base -10 logarithm of x for x > 0.
Syntax: Following is the syntax for logl0() method
import math
math.log10(x)
Note: This function is not accessible directly so we need to import math module and then we need
to call this function using math static object.
Parameters : x — This is a numeric expression.
Return Value : This method returns base -10 logarithm of x for x > 0.
Example: The following example shows the usage of log10() method.

# !/usr/bin/python
import math # This will import math module
print “math.logl0(100.12): “,
math.logl0(100.12)
print “math.logl0(100.72):”,
math.logl0(100.72)
print “math.loglO(119L):”,
math.log10(119L)
print “math.loglO(math.pi):”,
math.log10(math.pi)

This will produce the following result:

math.logl0(100.12): 2.00052084094
math.logl0(100.72): 2.0031157171
math.log10(119L): 2.07554696139
math.loglO(math.pi): 0.497149872694

Question 9:
Explain pow(x, y) in python with example.
Answer:
Description : The method pow() returns returns
the value of x to the power of y.
Syntax: Following is the syntax for pow() method
import math
math.pow(x,y)
Note : This function is not accessible directly so we need to import math module and then we need
to call this function using math static object.
Parameters : x—This is a numeric expression, y—This is also a numeric expression.

https://onlinestudytest.com/
Return Value : This method returns value of x to the power of y.
Example: The following example shows the usage of pow() method.

# !/usr/bin/python
import math # This will import math module
print “math.pow(100, 2): “,
math.pow(100,2)
print “math.pow(100,-2): “,
math.pow(100,-2)
print “math.pow(2,4): “,
math.pow(2,4)
print “math.pow(3, 0): “,
math.pow(3,0)

This will produce the following result:

math.pow(100, 2) :10000.0
math.pow(100,-2): O.OOOl
math.pow(2, 4): 16.0 math.pow(3,0): 1.0
Question 10:
Describe sqrt(x) in Python with example.
Answer:
Description : The method sqrt( ) returns the square root of x for x > 0.
Syntax: Following is the syntax for sqrt() method
import math
math.sqrt(x)
Note: This function is not accessible directly so we need to import math module and then we need
to call this function using math static object.
Parameters: x —This is a numeric expression.
Return Value : This method returns square root of x for x > 0.
Example: The following example shows the usage of sqrt() method.

# !/usr/bin/python
import math # This will import math module
print “math.sqrt(100): “, math.sqrt(100)
print “math.sqrt(7): “, math.sqrt(7)
print “math.sqrt(math.pi): “, math.sqrt(math.pi)

This will produce the following result:

math.sqrt(100): 10.0
math.sqrt(7): 2.64575131106
math.sqrt(math.pi): 1.77245385091

Question 11:
Describe Random numbers function in Python with example .
Answer:
Description : The method random( ) returns a random float r, such that 0 is less than or equal to r
and r is less than 1.
Syntax: Following is the syntax for

https://onlinestudytest.com/
random() method
random()
Note : This function is not accessible directly so we need to import random module and then we
need to call this function using random static object.
Parameters: NA
Return Value : This method returns a random float r, such that 0 is less than or equal to r and r is
less than 1.
Example: The following example shows the usage of random() method.

#!/usr/bin/python
import random # First random number
print “random(): “,
random.random() # Second random number
print “random(): “,
random.random()

This will produce the following result:

random(): 0.281954791393
random(): 0.309090465205

Question 12:
Explain cos() in Python.
Answer:
Description: The method cos() returns the cosine of x radi Answer:
Syntax : Following is the syntax for cos() method
cos(x)
Note: This function is not accessible directly so we need to import math module and then we need
to call this function using math static object.
Parameters : x—This must be a numeric value.
Return Value : This method returns a numeric value between-1 and 1 which represents the cosine of
the angle.
Example: The following example shows the usage of cos() method

# !/usr/bin/python
import math
print “cos(3):”,
math.cos(3)
print “cos(-3):”,
math.cos(-3)
print “cos(0):”,
math.cos(0)
print “cos(math.pi):”,
math.cos(math.pi)
print “cos(2*math.pi):”,
math.cos(2*math.pi)

This will produce the following result:

cos(3) >0.9899924966
cos(-3) >0.9899924966

https://onlinestudytest.com/
cos(0): 1.0
cos(math.pi) >1.0
cos(2*math.pi): 1.0

Question 13:
What are Generator Functions ?
Answer:
A generator function or generator method is one which contains a yield expression. When a
generator function is called it returns an iterator. Values are extracted from the iterator one at a
time by calling its_next_( ) method. At each call to_next_( ) the generator function’s yield
expression’s value (None if none is specified) is returned. If the generator function finishes or
executes return a Stop Iteration exception is raised.
Generators provide an elegant way to write simple and efficient code for functions that return a list
of elements. Based on the yield directive, they allow you to pause a function and return an
intermediate result. The function saves its execution context and can be resumed later if necessary.

Question 14:
Define functions with example.
Answer:
A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provides better modularity for your application and a high degree of code reusing.As you
already know, Python gives you many built-in functions like
print( ) etc. but you can also create your own functions. These functions are called user – defined
functions.
Syntax:
def functionname(parameters):
“function_docstring”
function_suite return[expression]
By default, parameters have a positional behavior, and you need to inform them in the same order
that they were defined.
Example:
Here is the simplest form of a Python function. This function takes a string as input parameter and
prints it on standard screen.
def printme(str):
“This prints a passed string into this function”
print str
return

Question 15:
Define functions calling with example.
Answer:
Defining a function only gives it a specific name, specifies the parameters that are to be included in
the function, and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from another
function or directly from the Python prompt. Following is the example to call printme( ) function:

# !/usr/bin/py thon
# Function definition
def printme(str):
“This prints a passed string into this function”

https://onlinestudytest.com/
print str;
return;
# Now you can call printme function
printme (“I’m first call to user defined function!”);
printme (“Again second call to the same function”);

This will produce the following result:

I’m first call to user defined function!


Again second call to the same function

Question 16:
How are arguments passed – by reference or by value ?
Answer:
In Python everything is an object and all variables hold references to objects. The values of these
references are to the functions. As a result you can not change the value of the reference but you
can modify the object if it is mutable. Remember, numbers, strings and tuples are immutable, list
and diets are mutable.

Question 17:
How can we pass optional or keyword parameters from one function to another in Python ?
Answer:
Gather the arguments using the * and ** specifiers in the function’s parameter list. It gives us
positional arguments as a tuple and the keyword arguments as a dictionary. Then we can pass these
arguments while calling another function by using

# and **
def funl (a, *tup, ** keyword.Arg):
keyword Argj’width’j = ‘23.3c’
fun2 (a, *tup, **keywordArg)

Question 18:
How to generate random numbers in Python ?
Answer:
The standard module random implements a radom number generator. *’
There are also many other in this module, such as :
uniform(a, b) returns a floating point number in the range [a, b].
randint(a, b) returns a random integer number in the range [a, bj.
random() returns a floating point number in the range [0,1].
Following code snippet show usage of all the different functions, evertime it is executed .
import random
i = random.randint (1, 99) # i randomly initialized by integer between range 1 and 99.
j = random randient (1,99) # j randomly initialized by float between range 1 and 99.
k = random.random() # k randomly initialized by float between range 0 and 1

Print (“i.”, i)
Print (“j.”,j)
Print (“k.”, k)
_______________
Output:
(‘i:’, 64)

https://onlinestudytest.com/
(‘j:’ 701.85008797642115)
(‘k:’: 0.18173593240301023)
Output:
(‘i:’,83)
(‘j:’,56.817584548210945)
(‘k:’; 0.9946957743038618)

Question 19:
Explain “The returnStatement” with example.
Answer:
The statement return [expression] exits a function, optionally passing back an expression to the
caller. A return statement with no arguments is the same as return None .
All the above examples are not returning any value, but if you like you can return a value from a
function as follows :

#!/usr/bin/py thon
# Function definition is here
def sum(arg1,arg2):
# Add both the parameters and return them.
” total=arg1+arg2
print “Inside the function : “,
total
return total;
# Now you can call sum function total=sum(10,20);
print “Outside the function total

This will produce the following result:

Inside the function : 30


Outside the function : 30

Question 20:
Explain Namespaces and Scoping.
Answer:
Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names
(keys) and their corres-ponding objects (values).
A Python statement can access variables in a local namespace and in the global namespace. If a local
and a global variable have the same name, the local variable shadows the global variable. Each
function has its own local namespace. Class methods follow the same scoping rule as ordinary
functions. Python makes educated guesses on whether variables are local or global. It assumes that
any variable assigned a value in a function is local.
Therefore, in order to assign a value to a global variable within a function, you must first use the
global statement.The statement global VarName tells Python that VarName is a global variable .
Python stops searching the local namespace for the variable.

Question 21:
How does a user can share global variables across modules ?
Answer:
The canonical way to share information across modules within a single program is to create a special
module (called config or cfg). Just import the config module in all modules of application. The

https://onlinestudytest.com/
module then becomes available as a global name. Because there is only one instance of each
module, any change made to the module object get reflected everywhere. For example,

config. py:
x=0
mod.py:
import config
config.x=1
main.py :
import config
import mod
print config.x

Question 22:
In analog to the example, write a script that asks users for the temperature in F and prints the
temperature in C.
Answer:

# Program to convert temperature from F into C.


> > > fahrenheit = input (“Entry the temperature
in F : “)
> > > centigrade = (fahrenheit – 32) 8 5/9.0
> > > print “The equivalent temperature in centigrade is”, centigrade
> > > print

Question 23:
Define a function ‘Subtract Number (x, y)’ which takes in two numbers and returns the different of
the two.
Answer:

# Python function which returns the difference of two numbers


> > > a = input (“Enter the first number :”)
> > > b = input (“Enter the second number :”) def Subtract Number (a, b) :
> > > print “Subtraction = %d – %d” % (a, b)
> > > return a – b

Question 24:
Write a program that takes a number and calculate and display the log, square, sin and cosine of it.
Answer:

# Program to display the various values of a number import math


> > > number = input (“Enter the number :”)
> > > print “Number is”, number
> > > print “Log value of number is” math.log (number)
> > > print “Square of number is”, math.pow (number, 2)
> > > print “Sin value of number is”, math.sin (number)
> > > print “Cosine value of number is”, math.cos (number)

Question 25:
Write a tic-tac-toe program in python. [CBSE Text Book]
Answer:

https://onlinestudytest.com/
# tic-tac-toe program
import random def drawboard (board):
# This function is used to print the board
print (‘ | | ‘)
print (‘ ‘ + board [7] + ‘ j ‘ + board [8]
+ ‘ | ‘ + board [9]) print (‘| | ‘)
print (‘ ‘)
print (‘| | ‘)
print (‘ ‘ + board [4] + ‘ | ‘ + board [5]
+ ‘ | ‘ + board [6]) print (‘| | ‘)
print (‘ ‘)
Print (‘ | | ‘)
print (‘ ‘ + board [1] + ‘ | ‘ + board [2]
+ ‘ | ‘ + board [3]) print (‘| | ‘)
def input player letter ():
# This function is used to display the user typed letter
Letter = ”
while not (letter = = ‘X’ or letter = = ‘O’):
print (‘Do you want to be X or O ?’)
letter = input () .upper ()
if letter = ‘X’ return [‘X’, ‘O’]
else:
return [‘O’, ‘X’] def whogoesFirst ():
# This function is used to randomly choose
the player
if random . randint (0,1) = = 0 : return ‘Computer’ else:
return ‘Player’ def Play Again ():
# This function is used when player wants play again print
(‘Do you want to play again ? (Yes or no)’) return input (), lower ().startswith (‘y’) def makeMove
(board, letter, move): board[move] = letter def is Winner (bo, le) :
# This function returns true when plays has
won return

(60[7] = = le and 60[8] = = le and 60[9] = = le) or


(60[4] = = le and 60[5] = = le and 60[6] = = le) or
(60[1 ] = = le and 60[2] = = le and 60[3] = = le) or
(60[7] = = le and 60[4] = = le and 60[1] = = le) or
(60[8] = = le and 60[5] = = le and 60[2] = = le) or
(60[9] = = le and 60[6] = = le and 60[3] = = le) or
(60[7] = = le and 60[5] = = le and 60[3] = = le) or
(60[9] = = le and 60[5] = = le and 60[1] = = le) or

def getBoardcopy(board):
# This function make a duplicate of the board dupeBoard = [ ]
for i in board :
dupeBoard.append(i)
return depeBoard
def isSpaceFree (board, move):
# This function returns Ttue if the passed

https://onlinestudytest.com/
move is free return boardfmove] = = ‘ ‘ def getPlayerMove(board):
# This function is used to take player’s move
move = ‘ ‘
while move not in’12345678 9’.split () or
not is spaceFree (board, int(move)):
print (‘What is your next move ? (1-9)’)
move = input () return int(move)
def chooseRandomMoveFromList(board,
movelist):
# This function returns a valid move from the passed list possible Moves = [ ]
for i in moveList:
if is SpaceFree (board, i):
possibleMOves.append(i)
if len(possibleMoves)! = 0 :
return random.choice (possibleMoves)
else:
return – None
def getComputerMove (board, computerletter):
# This function returns the computer’s letter
if computer letter = = ‘X’:
player letter = ‘O’
else:
player letter = ‘X’
for i in range (1,10):
copy = getBoardCopy (board)
if isSpaceFree (copy, i):
makeMove (copy, computerletter, i)
if is Winner (copy, computerletter):
return i
for i in range (1,10):
copy = getBoard Copy (board)
if isSpaceFree (copy, i):
makeMove (copy, player letter, i)
if is Winner (copy, player letter):
return i
move = chooseRandomMoveFromList (board, [1, 3, 7, 9])
if move ! = None :
return move
if isSpaceFree (board, 5):
return 5
return ChooseRandomMoveFromList (board, [2,4,6,8])
def is BoardFull (board):
# This function returns true if all space on board has been taken
for i in range (1,10):
if isSpaceFree (board, i):
return False
return True
print (“Welcome to Tic-Tac-Toe !”)

https://onlinestudytest.com/
while True:
the Board = [” * 10
playerletter, computerletter = input
playerletter()
turn = whoGoesFirst()
print (‘The’ + turn + ‘will go first.’)
gamelsPlaying = True
while gemelsPlaying:
if turn = = ‘player’:
drawBoard (theBoard)
move = getPlayerMove (theBoard)
makeMove (theBoard, playerletter, move)
if is Winner (theBoard, playletter):
drawBoard (theBoard)
print (‘Hooray ! You have won !’)
gamelsPlaying = False
esle:
if is BoardFull (theBoard):
drawBoard (theBoard)
print (‘The game is a tie.”)
break
else:
turn = ‘computer’
else:
move=getCompterMove (theBoard, Computerletter)
makeMove (theBoard, computer letter, move)
if is Winner (theBoard, computerletter): drawBoard (theBoard)
print(‘The computer has beaten you!’) gamelsPlaying = False
else:
if isBoardFull (theBoard):
drawBoard (theBoard)
print (‘The game is a tie !’)
break
else:
turn = ‘player’ if not play Again():
break

https://onlinestudytest.com/
16 CONDITIONAL AND LOOPING CONSTRUCTS

16.1 VERY SHORT ANSWER TYPE QUESTIONS [1 MARK EACH]


Question 1:
Why do we use ‘break’ statement ?
Answer:
The ‘break’ statement can be used to terminate the loop.

Question 2:
What gets printed with the following code ?
x = True
y = False
z = False
if x or y and z :
print “yes”
else:
print “no
Answer:
Yes

Question 3:
What gets printed with the following code ?
x = True
y = False
z = False
if not x or y :
print 1
elif not x or not y and z:
print 2
elif not x or y or not y and x:
print 3
else:
print 4

https://onlinestudytest.com/
Answer:
3

Question 4:
What gets printed with given code ?
f = None
for i in range (5):
with open(“data.txt”, “w”) as f:
if i > 2:
break
print f.closed
Answer:
True

Question 5:
Which numbers are printed?
for i in range(2):
print i
for i in range(4,6):
print i
Answer:
0,1,4, 5

Question 6:
What gets printed?
import re
sum = 0
pattern = ‘back’
if re.match(pattern, ‘backup.txt’):
sum + = 1
if re.match(pattern, ‘text.back’):
sum + = 2
if re.search(pattern, ‘backup.txt’):
sum + = 4
if re.search(pattern, ‘text.back’):
sum + = 8
print sum
Answer:
13

Question 7:
Write the syntax of an ’if statement1 in Python programming language
Answer:
if expression :
statement(s)
Question 8:
Write the syntax of an if…..else statement in Python programming language
Answer:
if expression:

https://onlinestudytest.com/
statement(s)
else:
statement(s)

Question 9:
Write the output
#!/usr/bin/python
var =100
if(var==100):
print “Value of expression is 100”
print “Good bye!
Answer:
Value of expression is 100
Good bye

Question 10:
Define while loops.
Answer:
A while loop statement in Python programming language repeatedly execute s a target statement as
long as a given condition is true.

Question 11:
Write the syntax of a while loop.
Answer:
The syntax of a while loop in Python programming language is :
while expression :
statement(s)

Question 12:
What happened when the condition of while loop becomes false ?
Answer:
When the condition becomes false, program control passes to the line immediately following the
loop.

Question 13:
Write the syntax of a for loop.
Answer:
The syntax of a for loop look is as follows:
for iterating_var in sequence :
statements(s)

Question 14:
What do you mean by “continue statement” ?
Answer:
It causes the loop to skip the remainder of its body and immediately retest its condition prior to
reiterating.

Question 15:
What do you mean by “pass statement” ?
Answer:

https://onlinestudytest.com/
The pass statement in Python is used when a statement is required syntactically but you do not want
any command or code to execute.

Question 16:
Write the syntax of “break” statement.
Answer:
The syntax for a break statement in Python is as follows : break

Question 17:
Does Python support “switch” statements?
Answer:
No, Python does not currently support switch or case statements as in other languages.

16.2 SHORT ANSWER TYPE QUESTIONS [2 MARK EACH]


Question 1:
What is a statement ? What is the significance of an empty statement ?
Answer:
A statement is an instruction given to the computer to perform any kind of action.
An empty statement is useful in situations where the code requires a statement but does not require
logic. To fill these two requirements simultaneously, empty statement is used. Python offers ‘pass’
statement as an empty statement.

Question 2:
What is the difference between determinable loop and non-determinable loop ?
Answer:
The ‘for loop’ can be labelled as ‘determinable
Ans. Value of expression is 100 Good bye!
loop’ as number of its iterations can be determined before-hand as the size of the sequence, it is
operating upon.
The ‘while loop’ can be ‘non-determined loop’ as its number of iterations cannot be determined
before-hand. Its iterations depend upon the result of a test-condition, which cannot be determined
before-hand.

Question 3:
What are the two types of else clause in Python ? Ans. The two types of Python else clauses are :
Answer:
(i) else in an if statement
(ii) else in a loop statement
The else clause of an if statement is executed when the condition of the if statement results into
false.
The else clause of a loop is executed when the loop is terminating normally i.e. when its test -
condition has gone false for a while loop or when the for loop has executed the last value in
sequence.

Question 4:
Explain nested if…. else.
Answer:
There may be a situation when you want to check for another condition after a condition resolves to

https://onlinestudytest.com/
true. In such a situation, you can use the nested if construct. In a nested if construct, you can have
an if…elif…else construct inside another if…elif… else construct

Question 5:
Write the syntax of a for loop and also given an example.
Answer:
The syntax of a for loop looks as follows : for iterating_var in sequence: statements(s)
Example : for i in range (4):
print i
output : 0 1 2 3

Question 6:
What do you mean by “for loop” ?
Answer:
A for loop is à Python statement which repeats a group of statements a specified number of times.
You can use any object (such as strings, arrays, lists, tuples, diet and so on) in a for loop in Python.
Question 7:
Explain If…else statements
Answer:
If…else statements
An else statement can be combined with an if statement. An else statement contains the block of
code that executes if the conditional expression in the if statement resolves to 0 or a false value .
The else statement is an optional statement and there could be at most only one else statement
following if
Syntax:
The syntax of the if…else statement is :
if expression :
statement(s)
else:
statement(s)

Question 8:
What do you mean by decision making ?
Answer:
Structures require that the programmer specify one or more conditions to be evaluated or tested by
the program, along with a statement or statements to be executed if the condition is determined to
be- true, and optionally, other statements to be executed if the condition is determined to be false.

Question 9:
Create a function addNumbers(x) that takes a number as an argument and adds all the integers
between 1 and the number (inclusive) and returns the total number.
Answer:
def add Numbers (num):
total = 0
i =1
while i< = num:
total + = i
i+ = 1
return total

https://onlinestudytest.com/
Question 10:
Create a function addNumbers(start, end) that adds all the integers between the start and end value
(inclusive) and returns the total sum.
Answer:
def addNumbers(start, end):
total = 0
i = start
while start < = end:
total + = start
start + = 1
return total

Question 11:
Create a function countPages(x) that takes the number of pages of a book as an argument and
counts the number of times the digit ‘1’ appears in the page number.
Answer:
def countPages(num):
total = 0
i =1
while i<=num:
page_no = str(i)
total + = page_no.count(‘1’)
i+ = l
return total

Question 12:
Which of the following does not produce the same output?

https://onlinestudytest.com/
Answer:
All give the same output.

Question 13:
Create a function factorial(x) that takes an integer and returns the product of all the positive integers
less than or equal to n.
Answer:
def factorial(num):
product =1
i = num
while i > 0:
product *=i
i-=l
return product

Question 14:
Create a function doubleFactorial(n) that takes an odd integer and returns the product of all odd
values upto the value n (where n=2k-l).
Answer:
def doubleFactorial(num):
product = 1
i =0
k=0
while k <num:
k = 2*i+l
product * = k
i += 1
return product

Question 15:
Create a function that computes the approximation of pi, based on the number of iterations
specified, pi can be computed by 4*(l-l/3+l/5-l/7+l/9-…).

https://onlinestudytest.com/
Answer:
def piApprox(num):
i =1
pi = 0
while i<=num:
#set ‘while’ termination condition
pi +=((4/float(2*i-l)n-l)**(i+l))
#compute the ith term of the series
i+=l # update i
return pi

Question 16:
What gets printed?
country_counter = {}
def addone(country):
if country in country_counter:
country_counter[country] + = 1
else:
country_counter[country] = 1
addone(‘China’)
addone(‘Japan’)
addone(‘china’)
print len(country_counter)
Answer:
3

Question 17:
What gets printed?
namesl = [‘Amir’, ‘Barry’, ‘Chales’, ‘Dao’]
if ‘amir’ in namesl:
print 1
else:
print 2
Answer:
2

Question 18:
What gets printed?
x =0
y=l
a = cmp(x,y)
if a < x:
print “a”
elif a = = x:
print “b”
else:
print “c”
Answer:
a

https://onlinestudytest.com/
Question 19:
What gets printed ?
x =1
y = “2”
z=3
sum = 0
for i in (x,y,z):
if isinstance(i, int):
sum + = i
print sum
Answer:
4

16.3 LONG ANSWER TYPE QUESTIONS [4 MARK EACH]


Question 1:
Explain Flow Diagram of “for loop”
Answer:
If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is
assigned to the iterating variable iterating_var. Next, the statements bloc is executed. Each item in
the list is assigned t iterating_var, and the statements(s) block is executed until the entire sequence
is exhausted.

Question 2:
Write an example to illustrates the combination of an else statement with a for statement
Answer:

https://onlinestudytest.com/
The following example illustrates the combination of an else statement with a for statement that
searches for prime numbers from 10 through 20.
# !/usr/bin/python
for num in range(10,20):
#to iterate between 10 to 20
for i in range(2,num):
#to iterate on the factors of the number
if num%i == 0:
#to determine the first factor
j=num/i
#to calculate the second factor
print ‘%d equals %d * %d’ % (num,i,j)
break
#to move to the next number, the
#first for
else:
# else part of the loop
print num, ‘is a prime number’
When the above code is executed, it produces following result :
10 equals 2*5
11 is a prime number
12 equals 2*6
13 is a prime number
14 equals 2*7
15 equals 3*5
16 equals 2*8
17 is a prime number
18 equals 2*9
19 is a prime number

Question 3:
Write a program to explain “for loop”
Answer:
#!/usr/bin/python
for letter in ‘Python’: # First Example
print ‘Current Letter :’, letter
fruits = [‘banana’, ‘apple’, ‘mango’]
for fruit in fruits: # Second Example
print ‘Current fruit :’, fruit
print “Good bye!”
When the above code is executed, it produces following result:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana

https://onlinestudytest.com/
Current fruit : apple
Current fruit : mango
Good bye!

Question 4:
Create a function that takes in a positive integer and return a list of prime numbers. A prime number
is only divisible by 1 and itself.
Answer:
def primeNumbers(num):
primes = [ ]
i =2
# iterates through range from 2 to
num(inclusive)
while i< =num:
# add ‘while’ condition
k=2
is Prime = True
# check if prime number
while k<i: # add’while’condition
if i%k==0:
isPrime = False
k+ = l # update k
if isPrime = =True:
primes.append(i)
i+ = l # update i
return primes

Question 5:
Create a function that takes in a positive number and return 2 integers such that the number is
between the squares of the 2 integers. It returns the same integer twice if the number is a square of
an integer.
Answer:
import math
def sqApprox(num):
i =0
minsq = 0 # set lower bound
maxsq = math.ceil(num’l’num)
# set upper bound
while i< maxsq :
# set ‘while’ termination condition
if i*i< =num and i>minsq:
# complete inequality condition
minsq = i
if i*i> =num and i<maxsq:
# complete inequality condition
maxsq = i
i+=l
# update i so that ‘while’ will terminate
return (minsq, maxsq)

https://onlinestudytest.com/
Question 6:
Write a function estimatePi( ) to estimate and return the value of pi based on the formula found by
an Indian Mathematician Srinivasa Ramanujan. It should use a while loop to compute the terms of
the summation until the last term is smaller than le-15. The formula for estimating pi is given below :

where k! is the factorial of k.


Answer:
import math
def factorial(n):
if n = = 0:
return 1
else:
return n * factorial(n-l)

def series_term(k):
a=factorial(4*k)
b=(1103+26390*k)
c=factoriall(k)
d=c**4
e=396**(4*k)
return float(a’fb)/(d’l’e)

def estimatePi():
k=0
final=0
while True:
term = series_term(k)
final + = term
k+=l
if term < 1.0e-15:
break
f=2*math.sqrt(2)/9801
pi = 1.0/(final * f)
return pi

Question 7:
Given a positive integer, write a function that computes the prime factors that can be multplied
together to get back the same integer.
Answer:
def primeFactorization(num):
factors = [ ]
lastresult = num
# 1 is a special case
if num == 1:
return [ ]
while True:
if lastresult == 1:

https://onlinestudytest.com/
break
c =2
while True:
if lastresult % c = = 0:
break
c += 1
factors.append(c)
lastresult/= c
return factors

Question 8:
The smallest common multiple of two or more numbers is called the lowest common multiple (LCM).
Given a list of integers, find the lowest common multiple.
Answer:
def LCM(nums):
nums.sort()
biggest=nums[-l]
multiplier=1
while sum([(multiplier’|,biggest)%num for num in nums])!=0:
multiplier + = 1
return biggest*multiplier

Question 9:
Write a program to explain “if statement”
Answer:
# !/usr/bin/python
var1=100
if var1:
print “1-Got a true expression Value”
print var1
else:
print ” 1-Got a false expression value”
print var1 var2=0
if var2 :
print “2-Got a true expression value”
print var2
else :
print “2-Got a false expression value”
print var2
print “Good bye!”
When the above code is executed, it produces following result:
1- Got a true expression value 100
2- Got a false expression value 0
Good bye!

Question 10:
Explain “elif statement” with example.
Answer:
elif statement : The elif statement allows you to check multiple expressions for truth value and

https://onlinestudytest.com/
execute a block of code as soon as one of the conditions evaluates to true. Like the else, the elif
statement is optional. However, unlike else , for which there can be at most one statement, there
can be an arbitrary number of elif statements following an if
The syntax of the if…elif statement is
If expression1 :
statement (s)
elif expression2 :
statement(s)
elif expression3 :
statement(s)
else:
statement(s)
Example
# !/usr/bin/py thon
var=100
if var = = 200 :
print “1-Got a true expression value”
print var
elif var==150:
print “2-Got a true expression value”
print var2
elif var ==100:
print “3-Got a true expression value”
print var
else:
print “4-Got a false expression value”
print var
print “Good bye!”
when the above code is executed, it produces the following output :
3- Got a true expression value
100
Good bye !

Question 11:
Explain nested if—–else statement
Answer:
There may be a situation when you want to check for another condition after a condition resolves to
true. In such a situation, you can use the nested if construct. In a nested if construct, you can have
an if…elif…else construct inside another if…elif… else construct.
Syntax:
The syntax of the nested if…elif…else construct may be:
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else

https://onlinestudytest.com/
statement(s)
elif expression4: statement(s) else:
statement(s)
Example:
# !/usr/bin/python if var < 200:
print “Expression value is less than 200”
if var==150:
print “=150”
elif var = =100:
print “=100”
elif var ==50:
print “=50”
elif var < 50 :
print “Expression value is less than 50”
else :
print “Could not find true expression”

Question 12:
Explain while loop in Python programming language.
Answer:
The syntax of a while loop in Python programming language is
while expression :
statement(s)
Here statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any nonzero value. The loop iterates while the condition is true .
When the condition becomes false, program control passes to the line immediately following the
loop. In Python, all the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python uses indentation
as its method of grouping statements.
Example
# !/usr/bin/python
count=0
while (count < 9):
print ‘The count is:’,count
count=count +1
print “Good bye!”
OUTPUT
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!

https://onlinestudytest.com/
Question 13:
Explain loops in Python language with diagram.
Answer:
There may be a situation when you need to execute a block of code several number of times. In
general statements are executed sequentially: The first statement in a function is executed first,
followed by the second,and so on. Programming languages provide various control structures that
allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general from of a loop statement in most of the programming languages

Python programming language provides


following types of loop to handle looping requirements.
while loop : Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.
for loop : Execute a sequence of statements multiple times and abbreviates the code that manages
the loop variable.
nested loops : You can use one or more loop inside any another while, for or do..while loop.

Question 14:
Explain Decision making structure with diagram.
Answer:
Decision making structures require that the programmer specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the condition
is determined to be false.
Following is the general from of a typical decision making structure found in most of the

https://onlinestudytest.com/
programming languages :

Python programming language assumes any non-zero and non null values as true and if it is either
zero or null then it is assumed as false value.
Python programming language provides follo-wing types of decision making statements.

Statement Description

if statements An if statement consists of a boolean expression followed by one or more statements

if…else An if statement can be followed by an optional else statement,which executes when the boolean
statements expression is false

nested if
You can use one if or else if statement inside another if or else if statement(s)
statement

Question 15:
Write a function to print the Fibonacci Series upto input limit
Answer:
def fibonacci (num)
if (num = = 0):
return 0
elif (num = = 1):
return 1
else :
return fibonacci (num-1) + fibonacci

https://onlinestudytest.com/
(num-2)
cal = input (“Enter the input limit”)
print fibonacci (val)

Question 16:
Print all multiples of 13 that are smaller than 100. Use the range function in the following manner :
range (start, end, step) where ‘Start’ is the starting value of the counter, ‘end’ is the end value and
‘step’ is the amount by which the counter is increased each time.
Answer:
# program to print multiples of 13 smaller than 100 for counter in range (13,100,13) :
print counter

Question 17:
Write a program using while loop that asks the user for a number, and prints a countdown from that
number to zero.
Answer:
num = input (“Enter the number”)
while (num > = 1) :
print (“num = “, num)
num – num-1
print (“Finish”)

Question 18:
Using random module, Simulate tossing a coin N times.
Answer:
N = input (“Number of tossing a coin”) from random import choice
heads = 0
tails = 0
coin = [‘head’, ‘tail’]
for n in range (N) :
toss = choice (coin)
if toss = ‘head’ :
heads = heads + 1
if toss = = ‘tail’ :
tails = tails + 1
print (‘Heads:’, heads)
print (‘Tails:’, tails)

Question 19:
Write a program using a for loop, that calculates exponentials. Your program should ask for base and
exp. value from user.
Answer:
x = input (“Enter a base number”)
y = input (“Enter a exp. number”)
if y > 0 :
for x in range (y) :
x =x * x
else
for x in range (y) :

https://onlinestudytest.com/
x = 1/x * x
print x

Question 20:
Following code is meant to be an interactive grade calculation script that converts from a percentage
into a letter grade :
90 and above is A+,
80-90 is A,
60-80 is A-,
and everything below is fail.
Write the program to display grade of a user ?
Answer:
grade = input (“Enter the grade percentage”) if grade > = 90 :
print “Grade is A+” if 80 < = grade < 90 : print “Grade is A” elsif 60 < = grade : print “Grade is A -” else
grade < 60 :
print “You are fail”

Question 21:
Write a Python script to read an integer > 1000 and reverse the number.
Answer:
num = int (raw_input(“Enter an integer > 1000 : “))
tnum = num
reverse = 0
while tnum :
digit = tnum %10
tnum = tnum /10
reverse = reverse * 10 + digit
print “Reverse of”, num, “is”, reverse

Question 22:
Write a Python script to generate divisors of a number.
Answer:
num = int (raw_input (“Enter an integer:”))
mid = num/2
print “The divisors of”, num, “are:”
for a in range (2, mid +1):
if num %a = = 0:
print a,
else:
print”End”

Question 23:
Write a Python script that display first ten Mersenne numbers. Mersenne number are in the form of
2n-l.
Answer:
def Mersenne (n):
return 2**n-1
print “First ten Mersenne numbers are :”
for a in range (1,11):
print Mersenne (a)

https://onlinestudytest.com/
Question 24:
Write a Python script that display 20 Mersenne Prime Numbers ?
Answer:
def Mersenne (n):
return 2** n-1
def test prime (n):
mid = n/2 + 1
for t in range (2, mid):
if n%t = = 0:
return false
else :
return true
print “20 Mersenne Prime Numbers are :”
for a in range (1,21):
number = Mersenne (a)
prime = test prime (number)
if prime :
print number, “Prime”
else :
print number

Question 25:
Write a Python script to find sum of the series :
s = 1 + x + x2 + x3 + …. + xn
Answer:
x = float (raw_input (“Enter value of x :”)
n = int (raw_input (“Enter value of n :”))
s=0
for a in range (n + 1) :
s + = x**a
print “Sum of series”, s

Question 26:
Write Python script to print the following pattern:

Answer:
for a in range (3,10,2) :
for b in range (1, a, 2):
print b,
print

Question 27:
Write Python script to print the following pattern

https://onlinestudytest.com/
Answer:
n=1
for a in range (5) :
print n
n = n *10 + 1

Question 28:
Write Python script to calculate sum of following series :
s = (1) + (1+2) + (1+2+3) +…+ (1+2+3+…+n)
Answer:
sum 0
n = int (raw_input (“Enter the value of n :”)]
for a in range (2, n+2):
term = 0
for b in range (1,1):
term + = b
print “Term”, (a-1), “:”,term
sum + = term
print “Sum of”, n, “term is”, sum

Question 29:
Write a Python program to check if a given number is an Armstrong number.
Answer:
sum = 0
n = int (raw_input (“Enter number”)
n1 = n
while (n > 0):
a = n%10
sum = sum + (a * a * a)
n = n/10
if (sum ==n1):
print n, “is an Armstrong number”
else:
print n, “is not an Armstrong number”

https://onlinestudytest.com/
17 STRINGS

17.1 VERY SHORT ANSWER TYPE QUESTIONS [1 MARK EACH]


Question 1:
Explain capitalize( ) method in Python.
Answer:
The method capitalize( ) returns a copy of the string with only its first character capitalized.

Question 2:
Write the syntax for capitalize( ) method.
Answer:
Following is the syntax for capitalize( ) method : str.capitalize( )

Question 3:
What value will be returned by center (width, fillchar) method in Python.
Answer:
The method center( ) returns centered in a string of length width. Padding is done using the
specified fillchar.

Question 4:
What are the two parameters of center( ) method.
Answer:
width — This is the total width of the string,
fillchar — This is the filler character

Question 5:
Describe the count(str, beg=0,end= len(string))
Answer:
The method count( ) returns the number of occurrences of substring sub in the range [start, e nd].

Question 6:
Describe the decode (encoding=’UTF8′, errors=’ strict’ )
Answer:
The method decode( ) decodes the string using the codec registered for encoding.

Question 7:
What do you n .an by encode(encoding= ‘UTF- 8,errors=’strict’)
Answer:
The method encode( ) returns an encoded version of the string. Default encoding is the current
default string encoding.

Question 8:
What do you mean by endswith(suffix, beg=0, end=len(string))
Answer:
The method endswith( ) returns True if the string ends with the specified suffix, otherwise return
False

Question 9:
Write the the syntax for find( ) method
Answer:

https://onlinestudytest.com/
Following is the syntax for find( ) method :
str.find(str, beg=0 end=len(string))

Question 10:
Write the output of the following code.
# !/usr/bin/py thon
str1 = “this is string example… ,wow!!!”;\
str2 = “exam”;
print strl.find(str2);
print strl.find(str2,10);
print strl.find(str2, 40);
Answer:
15 15 -1

Question 11:
Write the syntax for isalnum( ) method.
Answer:
Following is the syntax for isalnum( )
method :
str.isalnum( )

Question 12:
Write the output of the following code.
# !/usr/bin/python
str = “this2009”; # No space in this string print str.isalnum( );
str = “this is string example….wow!!!”;
print str.isalnum( );
Answer:
True False

Question 13:
Write the syntax for isalpha( ) method.
Answer:
Following is the syntax for isalpha( ) method :
str.isalpha( )

Question 14:
Write the output of the following code.
# !/usr/bin/python
str = “this”; # No space & digit in this string print str.isalpha( );
str = “this is string example….wow!!!”; print str.isalpha( );
Answer:
True False

Question 15:
Describe the isdigit( ) method
Answer:
The method isdigit( ) checks whether the string consists of digits only

Question 16:
Why we use islower( ) method in python?

https://onlinestudytest.com/
Answer:
The method islower( ) checks whether all the case-based characters (letters) of the string are
lowercase

Question 17:
Describe the isspace( ) method
Answer:
The method isspace( ) checks whether the string consists of whitespace.

Question 18:
Write the output of the following code.
#!/usr/bin/python
str = ” “;
print str.isspace( );
str = “This is string example….wow!!!”;
print str.isspace( );
Answer:
True
False

Question 19:
Write the output of the following code.
#!/usr/bin/python
str = “this is string example….wow!!!”;
print str.ljust(50, ‘0’);
Answer:
This is string example
…wow!!!000000000000000000

Question 20:
Write the output of the following code.
# !/usr/bin/python
str = “Waltons Technology….wow!!!”;
print “str.upper() : “str.upper()
Answer:
str.upper() : Waltons Technology ….WOW!!!

Question 21:
Rectify the error (if any) in the given statements.
>>>str = “Hello World”
>>>str[5] = ‘p’
Answer:
Strings are immutable. So convert to 2.
list > > >s = list (str)’p’)
>>s [5]=’p’

Question 22:
Give the output of the following state-ments :
>>>str = ‘Honesty is the best policy”
>>>str.replace (‘o’.’*’)

https://onlinestudytest.com/
Answer:
H*nesty is the best p*licy.

17.2 SHORT ANSWER TYPE QUESTIONS [2 MARK EACH]


Question 1:
What do you mean by string in Python ?
Answer:
Strings are amongst the most popular types in Python. We can create them simply by characters in
quotes. Python treats single quotes the same as double quotes.
Creating strings is as simple as assigning a value to a variable. For example :
var1 = ‘Waltons Technology!’
var2 = “Python Programming”

Question 2:
What is indexing in context to Python strings ? J Why is it also called two-way indexing ?
Answer:
In Python strings, each individual character is ! given a location number, called “index” and this
process is called “indexing”. Python allocates indices in two directions :

in forward direction, the indexes are numbered as 0,1, 2, length-1.

in backward direction, the indexes are numbered as -1, -2, -3,…. length.
This is known as “two-way indexing”.

Question 3:
What is a string slice ? How is it useful ?
Answer:
A sub-part or a slice of a string, say s, can be obtained using s[n : m] where n and m are integers.
Python returns all the characters at indices n, n+1, n+2,…. m-1.
For example,
‘Oswaal Books’ [1 : 4] will give ‘swa’

Question 4:
How you can “update” an existing string ?
Answer:
You can “update” an existing string by (re) assigning a variable to another string.
The new value can be related to its previous value or to a completely different string altogether.
Following is a simple example :
# !/usr/bin/python
var1 = ‘Hello World!’
print”Updated String:-“,var i[:6] + ‘Python’

Question 5:
Describe Triple Quotes in Python.
Answer:
Python’s triple quotes comes to the rescue by allowing strings to span multiple lines, including
verbatim NEWLINEs, TABs, and any other special characters. The syntax for triple quotes consists of
three consecutive single or double quotes.
# !/usr/bin/py thon
para str = “””this is a long string that is made up of several lines and non-printable characters such as

https://onlinestudytest.com/
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like this within the brackets [ \n ], or just a
NEWLINE within the variable assignment will also show up.
”” ”
print para_str;

Question 6:
Define raw string with example.
Answer:
Raw strings don’t treat the backslash as a special character at all. Every character you put into a raw
string stays in the way you wrote it :
# !/usr/bin/python
print ‘C:\\nowhere’
When the above code is executed, it produces the following result :
C:\nowhere
Now let’s make use of raw string. We would put expression in r’expression’ as follows :
# !/usr/bin/python
print r’C:\\nowhere’
When the above code is executed, it produces the following result :
C:\\nowhere

Question 7:
Explain Unicode String with example.
Answer:
Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are stored as 16-
bit Unicode. This allows for a more varied set of characters, including special characters from most
languages in the world.
Example…….
#!/usr/bin/python
print u’Hello, world!’

Question 8:
Describe isdecimal( ) with example.
Answer:
The method isdecimal( ) checks whether the string consists of only decimal characters. This method
is present only on Unicode objects.
Note : To define a string as Unicode, one simply prefixes a ‘u’ to the opening quotation mark of the
assignment.
Below is the example.
Syntax :
Following is the syntax for isdecimal( ) method :
str.isdecimal( )

Question 9:
Explain zfill (width) with Syntax and Return Value
Answer:
The method zfill( ) pads string on the left with zeros to fill width.
Syntax : str.zfill(width)
Parameters: This is final width of the string. This is the width which we would get after filling zeros.
Return Value: This method returns padded string

https://onlinestudytest.com/
Question 10:
Write the output of the following code
# !/usr/bin/python
str = “this is string example….wow!!!”;
print str.zfill(40);
print str.zfill(50);
Answer:
On compiling and running the above program, this will produce the following result :
OOOOOOOOthis is string example….wow!!! 000000000000000000this is string example…. wow!!!

Question 11:
Write the output of the following code
# !/usr/bin/python
from string import maketrAns. # Required to call maketrAns. function.
intab = “aeiou” outtab = “12345”
trantab = maketrAns.(intab, outtab) str = “this is string example….wow!!!”; print
str.trAns.late(trantab, ‘xm’);
Answer:
The given code will produce following result :
th3s 3s str3ng 21pl2….w4w!M

Question 12:
Describe the following method trans.late(table, deletechars=””)
Answer:
The method translate( ) returns a copy of the string in which all characters have been translated
using table (constructed with the maketrans( ) function in the string module), optionally deleting all
characters found in the string deletechars.

Question 13:
Give an example of title( ) in Python
Answer:
The following example shows the usage of title( ) method
# !/usr/bin/python
str = “this is string example….wow!!!”;
print str.title( );
On compile and run the above program, this will produce the following result :
This Is String Example….Wow!!!

Question 14:
Give an example of swapcase( ) in Python
Answer:
The following example shows the usage of swapcase( ) method.
# !/usr/bin/py thon
str = “this is string example….wow!!!”;
print str.swapcase( );
str = “THIS IS STRING EXAMPLE….WOW!!!”;
print str.swapcase( );
This will produce the following result :
THIS IS STRING EXAMPLE….WOW!!!
this is string example….wow!!!

https://onlinestudytest.com/
Question 15:
Define strip ([chars]) with its syntax
Answer:
The method strip( ) returns a copy of the string in which all chars have been stripped from the
beginning and the end of the string (default whitespace characters) .
Syntax: str.strip([chars]);

Question 16:
Explain Parameters of str.startswith(str, beg=0,end=len( string) );
Answer:
str — This is the string to be checked.
beg — This is the optional parameter to set start index of the matching boundary.
end — This is the optional parameter to set end index of the matching boundary.

Question 17:
Explain Parameters of str.rjust(width[, fillchar])
Answer:
width — This is the string length in total after padding.
fillchar — This is the filler character, default is a space.

Question 18:
Write the output of the given Python code # !/usr/bin/python
str = “this is really a string example…. wow!!!”;
str = “is”;
print str.rfind(str);
print str.rfind(str, 0,10);
print str.rfind(str, 10, 0);
print str.find(str);
print str.find(str, 0,10);
print str.find(str, 10, 0);
Answer:
Above code will produce the following result :
5
5
-1
2
2
-1

Question 19:
Write the output of the given code #!/usr/bin/python
str = “this-is-real-string-example….wow!!!”;
print “Min character: ” + min(str);
str = “this-is-a-string-example….wow!!!”;
print “Min character: ” + min(str);
Answer:
Min character: !
Min character: !

https://onlinestudytest.com/
Question 20:
Write the output of the given code #!/usr/bin/python
str = “this is really a string example….wow!!!”;
print “Max character: ” + max(str);
str = “this is a string example….wow!!!”;
print “Max character: ” + max(str);
Answer:
Output
Max character: y
Max character: x

Question 21:
Describe the function maketrans( )
Answer:
The method maketrans( ) returns a translation table that maps each character in the intab string into
the character at the same position in the outtab string. Then this table is passed to the translate( )
function.
Syntax : str.maketrans(intab, outtab]);
Question 22:
Write the output of the following code
#!/usr/bin/py thon
str = ” this is string example….wow!!! “; print str.lstrip( );
str = “88888888this is string example….wow!!!8888888”;
print str.lstrip(‘8’);
Answer:
Output
this is string example….wow!!!
this is string example..,.wow!!!8888888

Question 23:
Study the given script
defmetasearch( ):
import re
p=re.compile(‘sing+’)
searchl=re.search(p,’ Some singers sing well’)
if searchl:
match=searchl.group( )
index=searchl.start( )
lindex=search 1 ,end( )
print “matched”, match, “at index”, index ,”ending at”, lindex
else:
print “No match found”
metasearch( )
What will be the output of the above script if search( ) from the re module is replaced by match ( ) of
the re module. Justify your answer
Answer:
The output would be “N match found”
Justification : re.search( ) rill attempt the pattern throughout the string, i ntil it finds a match.

https://onlinestudytest.com/
re.match( ) on the other hand, only attempts the pattern at the very start of the string.
Example :
>>>re.match(“d”, “abcdef’) # No match
>>>re.search(“d”, “abcdef’) # Match

Question 24:
What will be the output of the script mentioned below? Justify your answer, def find) ):
import re
p=re.compile(‘ sing+’)
searchl=p.findall(‘Some singer sing well’)
print searchl
Answer:
Output : [‘sing’, ‘sing’]
Justification : fmdall( ) finds all occurences of the given substring with metacharacter.

17.3 LONG ANSWER TYPE QUESTIONS [4 MARK EACH ]


Question 1:
What is the concept of immutable strings ?
Answer:
Strings are immutable means that the contents of string cannot be chrnged after it is created.
For example :
>>> str = ‘Meney’
>>> str [3] = ‘h’
Type Error : ‘str’ object not support item assignment Python does not allow to change a character in
a string. So an attempt to replace ‘e’ in the string by ‘h’ displays a Type Error.

Question 2:
What do you understand by traversing a string ? Ans. Traversing a string means accessing all the
elements of the string one after the other by using the subscript. A string can be traversed using for
loop or while loop.
For example :
A = ‘Python’
i =0
while i < lenn (A) :
print A[i]
i =i + 1
Output :
P
y
t
h
o
n

Question 3:
Write a program to check whether the string is a palindrome or not.
Answer:
def palindrom ( ) :
str = input (“Enter the string”)

https://onlinestudytest.com/
l = len (str)
P= l– 1
inex = 0
while (index < p) :
if (str[index] = = str [p]):
index = index + 1
p = p-1
else :
print “String is not a palindrom” break
else :
print “String is a palindrom”

Question 4:
Write a program to count number of ‘s’ in the string ‘successor’.
Answer:
def letcount ( ) :
word = ‘successor’
count = 0
for letter in word :
if letter = = ‘s’ :
count = count + 1
print (count)

Question 5:
Write a program to determine if the given word is present in the string.
Answer:
def wsearch ( ) :
imprt re
word = ‘good’
search1 = re.search (word, ‘I am a good person’)
if search1 :
position = search1.start ( )
print “matched”, word, “at position”, position
else :
print “No match found”

Question 6:
Input a string “Green Revolution”. Write a script to print the string in reverse .
Answer:
def reverseorder(list 1) :
relist = [ ]
i = len (list 1) -1
while i > = 0 :
relist.append (list [i])
i = 1 -1
return relist

Question 7:
Write a program to print the pyramid ?
Answer:

https://onlinestudytest.com/
num = eval (raw_input (“Enter an integer from 1 to 5:”))
if num < 6 :
for i in range (1, num + 1):
for j in range (num-i, 0,-1):
print (” “)
for j in range (i, 0, -1):
print (j)
for j in range (2, i+1):
print (j)
print (” “)
else :
print (“The number entered is greater than 5”)
Output :

Question 8:
Write the syntax of isdecimal( ) and give suitable example
Answer:
The method isdecimal( ) checks whether the string consists of only decimal characters.
This method are present only on Unicode objects. Below is the example .
Syntax
str.isdecimal( )
Example
# !/usr/bin/python
str = u”this2009″;
print str.isdecimal( );
str = u”23443434″;
print str.isdecimal( );
This will produce the following result :
False
True

Question 9:
Write the output of the following python code #!/usr/bin/python
str = “Line1-a b c d e f\nLine2- a b
c\n\nLine4- a b c d”;
print str.splitlines( );
print str.splitlines(O);
print str.splitlines(3);
print str.splitlines(4);
print str.splitlines(5);
Answer:

https://onlinestudytest.com/
Output
[‘Linel-a b c d e f’, ‘Line2- a b c’, “, ‘Line4- abed’]
[‘Linel-a b c d e f’, ‘Line2- a b c’, “, ‘Line4- abed’]
[‘Linel-a b c d e f\ri, ‘Line2- a b c\ri, ‘\n’, ‘Line4- a b c d’]
[‘Linel-a b c d e f\n’, ‘Line2- a b c\ri, ‘\ri, ‘Line4- a b c d’]
[‘Linel-a b c d e f\ri, ‘Line2- a b c\ri, ‘\n’, ‘Line4- a bed’]

Question 10:
Define split( ) with suitable example.
Answer:
The method split( ) returns a list of all the words in the string, using str as the separator (splits on all
whitespace if left unspecified), optionally limiting the number of splits to num.
Syntax
str.split(str=””, num=string.count(str)).
Parameters
str — This is any delimeter, by default it is space.
num — This is number of lines to be made.
Example
# !/usr/bin/python
str = “Linel-abcdef \nLine2-abc \nLine4-abcd”;
print str.split( ); print str.split(‘ 1 );
OUTPUT
[‘Linel-abcdef’, ‘Line2-abc’, ‘Line4-abcd’]
[‘Linel-abcdef’, ‘\nLine2-abc \nLine4-abcd’]

Question 11:
Explain replace(old, new [, max])
Answer:
The method replace( ) returns a copy of the string in which the occurrences of old have been
replaced with new, optionally restricting the number of replacements to max .
Syntax
str.replace(old, new[, max])
Parameters –
old — This is old substring to be replaced.
new — This is new substring, which would replace old substring.
max — If this optional argument max is given, only the first count occurrences are
replaced.
Example
# !/usr/bin/python
str = “this is string example….wow!!! this is really string”;
print str.replace(“is”, “was”); print str.replace(“is”, “was”, 3);
OUTPUT
thwas was string example….wow!!! thwas was really string
thwas was string example….wow!!! thwas is really string

Question 12:
Describe index(str, beg=0, end=len(string)) with example
Answer:
The method index( ) determines if string str occurs in string or in a substring of string if starting

https://onlinestudytest.com/
indexbeg and ending index end are given. This method is same as find( ), but raises an exception if
sub is not found.
Syntax
str.index(str, beg=0 end=len(string))
Example
# !/usr/bin/python
str = “this is string example….wow!!!”;
str = “exam”;
print str.index(str);
print str.index(str, 10);
print str.index(str, 40);
OUTPUT
15
15
Traceback (most recent call last):
File “test.py”, line 8, in
print str.index(str, 40);
ValueError: substring not found
shell returned 1

Question 13:
Explain expandtabs(tabsize=8) with example
Answer:
The method expandtabs( ) returns a copy of the string in which tab characters ie. ‘ \t’ have been
expanded using spaces, optionally using the given tabsize (default 8).
Syntax
Following is the syntax for expandtabs( ) method : str.expandtabs(tabsize=8)
Example
#!/usr/bin/python
str = “this is\tstring example….wow!!!”;
print “Original string: ” + str;
print “Defualt exapanded tab: ” +
str.expandtabs( );
print “Double exapanded tab: ” + str.
expandtabs(16);
OUTPUT
Original string: this is string example….wow!!! Defualt exapanded tab: this is string example….
wow!!!
Double exapanded tab: this is string example…. wow!!!

Question 14:
Write Python script that takes a string with multiple words and then capitalizes the first letter of
each word and forms a new string out of it.
Answer:
string = raw_input (“Enter a string :”)
length = len (string)
a=0
end – length
string 2 = ” # empty string

https://onlinestudytest.com/
while a < length
if a == 0
string 2 += string [0].upper()
a += 1
elif (string [a] = = ‘ ‘ and string [a+1) !=”) :
string 2 + = string [a]
string 2 + = string [a+l].upper( )
a+=2
else :
string 2 + = string [a]
a+=1
print “Original string :”, string
print “Converted string :”, string2

Question 15:
Write a program that reads a string and display the longest substring of the given string having just
the consonants.
Answer:
string = raw_input (“Enter a string :”)
length = len (string)
max length = 0
max sub = ‘ ‘
sub = ‘ ‘
lensub = 0
for a in range (length) :
if string [a] in aeiou ‘or string [a] in’AEIOU’:
if lensub > maxlength :
maxsub = sub
maxlength – lensub
sub = ‘ ‘
lensub 0
else :
sub += string[a]
lensub = len(sub)
a+=1
print “Maximum length consonent
substring is :”, maxsub,
print “with”, maxlength, “characters”

Question 16:
Write a program that reads email id of a person in the form of a string and ensures that it belongs to
domain @gmail.com.
Answer:
email = raw_input (“Enter email ID :”)
domain = “@gmail.com”
lendo = len(domain)
lenm = len(email)
sub = email [lenm – lendo:]
if sub = = domain :

https://onlinestudytest.com/
if lendo ! = lenm :
print “It is a valid email ID”
else :
print “It is an invalid email ID”
else :
print “It’s domain is different”

Question 17:
Write a program that reads a string and then prints a string that capitalizes every other letter in the
string.
Answer:
string = raw_input (“Enter a string:”)
length = len (string)
string2 = ” ”
for a in range (0, length, 2):
string 2 + – string [a]
if a < (length-1):
string 2+ = string [a+1],upper()
print “Original string is”, string
print “Converted string is”, string2

Question 18:
Consider the string str=”Global Warming” Write statements in Python to implement the followin g
(a) To display the last four characters.
(b) To display the substring starting from index 4 and ending at index 8.
(c) To check whether string has alphanu-meric characters or not
(d) To trim the last four characters from the string.
(e) To trim the first four characters from the string.
(f) To display the starting index for the substring „ WaD.
(g) To change the case of the given string.
(h) To check if the string is in title case.
(i) To replace all the occurrences of letter „aD in the string with „*?
Answer:
(a) print str[-4:]
(b) print str[4:8]
(c) str.isalnum( )
(d) str[:-4]
(g) str.swapcase( )
(h) str.istitle( )
(i) str.replace(‘a’,’*’)

https://onlinestudytest.com/
Output screenshot :

https://onlinestudytest.com/
18
LISTS

18.1 VERY SHORT ANSWER TYPE QUESTIONS (1 MARKS EACH )


Question 1:
How many types of built-in types of sequences in Python.
Answer:
Python has six built-in types of sequences.

Question 2:
Write the output of the given Python code.

# !/user/bin/python
list1 = [‘physics’, ‘chemistry’, 1997, 2000];
list2 = [1,2,3,4,5,6, 7];
print “list1[0]”, list1[0]

Answer:

list1[0]: physics

Question 3:
Write the output of the given Python code.

# !/user/bin/python
listl = [‘physics’, ‘chemistry’, 1997,2000];
list2 = [1,2, 3,4,5, 6, 7];
print “list2[l:5[ :”, list2[l:5]

Answer:

list2[1:5[: [2,3,4,5]

Question 4:
How can we remove list element ?
Answer:
To remove a list element, you can use either the del statement or the remove]) method

Question 5:
Why we use cmp(listl, list2) in Python?
Answer:
It compares elements of both lists.

Question 6:
What is the use of len(list)) in Python?
Answer:
It gives the total length of the list.

Question 7:
Describe max(list) method.

https://onlinestudytest.com/
Answer:
It returns item from the list with max value.

Question 8:
Describe min(list) method.
Answer:
It returns item from the list with min value.

Question 9:
What is the use of list(seq) in Python ?
Answer:
It converts a tuple into list.

Question 10:
What do you mean by list.append(obj)
Answer:
Appends object obj to list

Question 11:
What do you mean by list.count(obj)
Answer:
Returns count how many times obj occurs in list

Question 12:
Explain list.extend(seq)
Answer:
Appends the contents of seq to list.

Question 13:
Is list.reverse() method return a value?
Answer:
This method does not return any value but reverse the given object from the list

Question 14:
Which method is used to sort objects of list.
Answer:
sort ()

Question 15:
Which function is used to reverse objects of list in place.
Answer:
list.reverse ()

Question 16:
Which function is use for removing object obj from list.
Answer:
list.remove(obj)

Question 17:
Which function is use for returning the lowest index in list that obj appears.
Answer:
List index (obj).

https://onlinestudytest.com/
18.2 SHORT ANSWER TYPE QUESTIONS (2 MARKS EACH )
Question 1:
Define list in Python.
Answer:
The list is a most versatile datatype available in Python which can be written as a list of comma-
separated values (items) between square brackets. Good thing about a list is that items in a list need
not all have the same type. Creating a list is as simple as putting different comma-separated values
between square brackets.
For example :
list1 = [‘physics’, ‘chemistry’, 1997,2000];
list2 = [1,2, 3,4, 5];
list3 = ’[‘a”, “b”, “c”, “d”];

Question 2:
Give an example to access values in lists.
Answer:
To access value in lists, use the square brackets for slicking along with the index or indices to obtain
value available at that index. Following is a simple example :

# !/user/bin/python
list1 = [‘physics’, ‘chemistry’, 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7];
print “list1 [0]:”,
list1 [0] print “list2[1 :5]:”, list2[1:5]

When the above code is executed, it produces the following result:

list1 [0]: physics


list2[1:5] : [2, 3, 4, 5]

Question 3:
Give an example to update single or multiple elements of lists
Answer:
You can update single or multiple elements of lists by giving the slice on the left-hand side of the
assignment operator, and you can add elements in a list with the append( ) method. Following is a
simple example:

# !/user/bin/python
listl = [‘physics’, ‘chemistry’, 1997, 2000];
print “Value available at index 2 :”
print list[2];
list[2] = 2001;
print “New value available at index 2 :”
print list [2];
Note: append)) method is discussed in subsequent section.

When the above code is executed, it produces the following result:

https://onlinestudytest.com/
Value available at index 2 :
1997
New value available at index 2 :
2001

Question 4:
Give an example to remove list element.
Answer:
To remove a list element, you can use either I the del statement if you know exactly which ‘
element(s) you are deleting or the remove I ( ) method if you do not know. Following is a simple
example:

# !/user/bin/python
list1 = [‘physics’, ‘chemistry’, 1997, 2000];
print list1;
del list1 [2];
print “After deleting value at index 2 :”
print list1;

When the above code is executed, it produces the following result:

[‘physics’, ‘chemistry’, 1997, 2000];


After deleting value at index 2;
[‘physics’, ‘chemistry’, 2000]

Question 5:
Describe list() with its syntax.
Answer:
The method list() takes sequence types and converts them to lists. It is used to convert a given tuple
into list.
Syntax
Following is the syntax for list() method :
list (seq)

Question 6:
Write the output of the given Python code :

#!/user/bin/python
list1, list2 = [123, ‘xyz’], [456, ‘abc’]
print cmpt(list1, list2);
print cmp(list2, list1);
list3 = list2 + [786];
print cmp(list2, list3)

Answer:

This will produce the following result:


-1
1
-1

https://onlinestudytest.com/
Question 7:
Write the output of the given Python code :

#!/user/bin/python
aList = [123, ‘xyz’, ‘zara’, ‘abc’, 123];
bList = [2009, ‘manni’];
aList.extend (bList)
print “Extended List :”, aList;

Answer:

This will produce the following result:


Extended List : [123, ‘xyz’, ‘zara’, ‘abc’, 123, 2009, ‘manni’]

Question 8:
Write the output of the given python code :

# ! ‘user/bin’pvthon
aList1 = [123, ‘xvz’, zara’, abc’];
print “Index for xyz : ” aList. index) ‘xyz’);
print “Index for zara :”, aList. index(‘zara’);

Answer:

This will produce the following result:


Index for xyz : 1 Index for xxx : 2

Question 9:
Write the output of the given python code :
# !/user/bin/python
aList = [123, ‘xyz’, ‘zara’, ‘abc’];
aList.insert (3,2009) print “Final List:”, aList
Answer:
Output:
Final List: [123, ‘xyz’, ‘zara’, 2009, ‘abc’]

Question 10:
Write the output of the given python code :

#!/user/bin/python
aList1 = [123, ‘xyz’, ‘zara’, ‘abc’];
aList.insert (3,2009) print “Final Lista List

Answer:

Output:
Final List: [123, ‘xyz’, ’zara1, 2009,’abc1’]

Question 11:
Write the output of the given python code :

# !/user/bin/python
aList1 = [123, ‘xyz’, ‘zara’, ‘abc’];

https://onlinestudytest.com/
print “A List:”, aList.pop()
print “B List:”, aList.pop(2)

Answer:

Output:
A List: abc B List: zara

Question 12:
Write the output of the following code [CBSE Text Book]

A = [2, 4, 6, 8,10]
L = len (A)
S=o
for I in range (1, L, 2):
S + = A[I]
print “Sum=”, S

Answer:
Sum = 12
Justification:
A[1] = 4 step size = 2
A[3] = 8
S = 4 + 8 = 12

Question 13:
How are lists different from strings when both are sequences ?
Answer:
The lists and strings are different in following ways :

(a) The lists are mutable sequences while strings are immutable.
(b) Strings store single type of elements, all characters while lists can store e lements belonging to
different types.
(c) In consecutive locations, strings store the individual characters while list stores the references of
its elements.

Question 14:
Write a program to calculate and display the sum of all the odd numbers in the list.
Answer:

pos = 0
sum = 0
while pos < len (L):
if L[pos] %2 = = 1 :
sum = sum + L [pos]
pos = pos + 1
print sum

Question 15:
Define a function overlapping ( ) that takes two lists and returns True if they have at least one
member in common, False otherwise.
Answer:

https://onlinestudytest.com/
def overlapping (a, b):
11 = len (a)
12 = len (b)
for i in range (11):
for j in range (12):
if a[i] == b[j] :
return True
else
return False

Question 16:
Write a program to find all duplicates in a list. [CBSE Text Book]
Answer:

a =[1,2,3,2,1,5,6,5,5,5]
d={ }
for elem in a:
if elem in
d: d[elem] + = 1
else:
d[elem] = 1
print elem
print [x for x, y in d.items() if y > 1],
print “have duplicates”
print d

Output screenshot:

[1,2,5] have duplicates


{1:2,2: 2,3:1,5:4, 6: 1}

18.3 LONG ANSWER TYPE QUESTIONS (4 MARKS EACH )


Question 1:
What is string in Python and how can we access values in list.
Answer:
The most basic data structure in Python is the sequence. Each element of a sequence is assigned a
number – its position or index. The first index is zero, the second index is one, and so forth. Python
has six built -in types of sequences, but the most common ones are lists and tuples.
There are certain things you can do with all sequence types. These operations include indexing,
slicing, adding, multiplying, and checking for membership. In addition, Python has built-in functions
for finding the length of a sequence and for finding its largest and smallest elements .
Python Lists:
The list is a most versatile datatype available in Python which can be written as a list of comma-
seprated values (items) between brackets. Good thing about a list is that items in a list need not all
have the same type.
Creating a list is as simple as putting different comma-separated values between square brackets.
For example:

https://onlinestudytest.com/
list1 = [‘physics’, ‘chemistry’, 1997,2000];
list2 = [1, 2, 3,4,5];
list3 = [“a”, “b”, ”c”, “d”];
Like string indices, list indices start at 0, and lists can be sliced, concatenated and so on.

Accessing Values in Lists :

To access values in lists, use the square brackets for slicing along with the index or indices to obtain
value available at that index. Following is a simple example :

# !/user/bin/python
list = [‘physics’, ‘chemistry’, 1997,2000];
list2 = [1,2, 3,4,5,6, 7];
print “list1 [0]:”, list1 [0]
print “list2[1:5]:”, list2[1:5]
list 2[1:5]: [2, 3, 4, 5]

Question 2:
How can we update and delete list in python.
Answer:

Updating Lists:
You can update single or multiple elements of lists by giving the slice on the left-hand side of the
assignment operator, and you can add to elements in a list with the append() method. Following is a
simple example:

# !/user/bin/python
list = [‘physics’, ‘chemistry’, 1997, 2000];
print “Value available at index 2 :”
print list[2];
list [2] = 2001;
print “New value available at index 2 :”
print list [2];

When the above code is executed it produces the following result:

Value available at index 2 :


1997
New value available at index 2 :
2001
Delete List Elements:
To remove a list element, you can use either the del statement if you know exactly which element(s)
you are deleting of the remove() method if you do not know.
Following is a simple example :

# !/user/bin/python
list1 = [‘physics’, ‘chemistry’, 1997, 2000];
print list1; del list1 [2];
print “After deleting value at index 2:”
print list1;

When the above code is executed, it produces the following result:

https://onlinestudytest.com/
[‘physics’, ‘chemistry’, 1997, 2001]
After deleting value at index 2 :
[‘physics’, ‘chemistry’, 2000]

Question 3:
Write a program to input any two matrices and print sum of matrices.
Answer:

import random
m1 = input (“Enter total number of rows in the first matrix”)
n1 = input (“Enter total number of columns in the first matrix”)
a = [[random.random() for row in range(m1) for col in range (n1)]
for i in range (m1)
for j in range (n1):
a[i][j] = input()
m2 = input (“Enter total number of rows in the second matrix”)
n2 = input (“Enter total number of columns in the second matrix”)
b = [[random.random () for row in range (m2)] for col in range (n2)]
for i in range (m2):
for j in rnage (n2):
b [i][j] = input ()
c = [[random.random () for row in range (ml)] for col in range (n1) ]
if ((m1 = m2) and (n1 = = b)):
print “Output is”
for i in range (m1):
for j in range (n1)]
c[i][j] = a[i][j] + b[i][j]
print c[i][j], ‘it’,
print
else :
print “Matrix addition is not possible”

Question 4:
Write a program to input any two matrices and print product of matrices.
Answer:

import random
m1 = input (“Enter number of rows in first matrix”)
n1 = input (“Enter number of columns in first matrix”)
a = [[random.random () for row in range (m1)] for col in range (n1) ]
for i in range (m1):
for j in range (n1):
a[i][j] = input ()
m2 = input (“Enter the number of rows in the second matrix”)
n2 = input (“Enter the number of columns in the second matrix”)
b = [[random.random () for row in range (m2)] for cal in range (n2) ]
for i in range (m2):
for j in range (n2):
b[i][j] = input ()
c = [[random.random () for row in range (ml)] for col in range (n2)]

https://onlinestudytest.com/
if (n1 = = m2):
for i in range (m1):
for j in range (n2):
c[i][j] = 0 for kin range (n1):
c[i][j] + = a[i][k]*b[k][j]
print c[i][j], ‘\t’,
print
else:
print “Multiplication is not possible”

Question 5:
Write a program to input any matrix and print both diagonal values of the matrix.
Answer:

Import random
m = input (“Enter the number of rows”)
n = input (“Enter the number of columns”)
a = [[random.random () for row in range (m)] for cal in mange (n) ]
if i in range (m):
for j in range (n):
a[i][j] = input ()
print “First diagonal”
for i in range (m):
print a[i][j], ‘\t’
k= m–1
print “second diagonal”
for j in range (m):
print a[j][k], ‘\t’
k- = 1
else:
print “Diagonal values are not possible”

Question 6:
Write a program to input n x m matrix and find the sum of all numbers.
Answer:

def summat (a, m, n):


s=0
for i in range (m):
for j in range (n):
s + = a[i][j]
return s

Question 7:
Write a program to perform various list operations after displaying menu.
Answer:

ch = 0
list = []
while true :

https://onlinestudytest.com/
print “List Menu”
print “1. Adding”
print “2.Modify”
print “3.Delete”
print “4.Sort list”
print “5.Display list”
print “6.Exit”
ch = int (raw_input (“Enter your choice :”)) if ch = = 1 :
print “1.Add element”
print “2.Add a List”
ch1 = int (raw_input
(“Enter choice 1 or 2:”))
if chi = = 1:
item = int
(raw_input (“Enter element:”))
pos = int (raw_input
(“Enter position to add : “))
list.insert (pos, item)
elif chi = = 2 :
list2 = eval (raw_input (“Enter list:”))
list.extend (lst2)
else:
print “Valid choices are 1 or 2”
print “Successfully added” elif ch = = 2 :
pos = int (raw_input
(“Enter position :”))
intem = int (raw_input
(“Enter new value :”))
old = list[pos]
list[.pos] = item
print old, ‘modified with vlaue”, item elif ch = = 3:
print “1.Delete element by position”
print “2.Delete element by value”
ch1 = int (raw_input (“Enter you choice 1 or 2’))
if chi = = 1:
pos = int (raw_input (“Enter position :”))
item = list.pop (pos)
print item, “deleted”
elif ch1 = = 2:
item = int (raw_input (“Enter element:”))
pos = list.remove (item)
print “Succcessfully delted”
else :
print “Valid choices are 1 or 2”
elif ch = = 4 :
print “l.Ascending”
print “2.Descending”
chi = int (raw input (“Enter choice 1 or 2”))

https://onlinestudytest.com/
if chi = = 1:
list. sot () elif ch1 = = 2:
list.sort (reverse = True)
else :

print “Valid choices are 1 or 2”

elif ch = = 5:
print list elif ch = = 6:
break
else :
print “valid choice 1 to 6”

Question 8:
Write a program to pass any list and to arrange all numbers in descending order.
Answer:

def arrange (1, n)


for i in range (n – 1):
for j in range (n – i – 1):
if l[j] > l[j +1] :
temp = l[j]
l[j] = l[j+l]
l[j+l] = temp

Question 9:
Write the output for the following codes. [CBSE Text Book]

A= (10:1000,20:2000,30:3000,40:4000, 50:5000}
print A.items()
print A.keys()
print A.values()

Answer:

[(40, 4000), (10, 1000), (20, 2000), (50, 5000), (30, 3000)]
[40,10, 20, 50, 30]
[4000,1000, 2000,5000,3000]

https://onlinestudytest.com/
19
TUPLES

19.1 VERY SHORT ANSWER TYPE QUESTIONS [1 MARK EACH ]


Question 1:
What is a tuple ?
Answer:
Tuple is a sequence of immutable Python objects

Question 2:
Can we remove individual tuple elements ?
Answer:
No, we cannot remove individual tuple elements.

Question 3:
Which function is use for comparing elements of both tuples.
Answer:
cmp(tuplel, tuple2)

Question 4:
Which function gives the total length of the tuple.
Answer:
len(tuple)

Question 5:
Which function returns item from the tuple with max value.
Answer:
max(tuple)

19.2 SHORT ANSWER TYPE QUESTIONS [2 MARK EACH ]


Question 1:
What is tuple ?
Answer:
Tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists .
The only difference is that tuples can’t be changed i.e.,tuples are immutable and tuples use
parentheses and lists use square brackets. Creating a tuple is as simple as putt ing different comma-
separated values and optionally you can put these comma-separated values between parentheses
also.
For example :
tup1 = (‘physics’, ‘chemistry’, 1997, 2000);
tup2 = (1,2, 3,4, 5);
tup3 = “a”, “b”, “c”, “d”;

Question 2:
Write the output of the given python code :

https://onlinestudytest.com/
#!/user/bin/python
tup1 = (12, 34.56);
tup2 = (‘abc’, ‘xyz’);
#Following action is not valid for tuples
#tup1 [0] = 100;
#So let’s create a new tuple as follows
tup3 = tup1 + tup2;
print tup3;
Answer:
Output :
(12,34.56, ’abc’, ‘xyz’)

Question 3:
Write the output of the given python code :
# !/user/bin/python
tuple1, tuple2 = (123, ‘xyz’), (456, ‘abc’)
print cmp (tuple1, tuple2) ;
print cmp (tuple2, tuple1) ;
tuple3 = tuple2 + (786,);
print cmp (tuple2, tuple3)
Answer:
Output :
-1
1
-1

Question 4:
Write the output of the given python code :
#!/user/bin/python
tuple1, tuple2 = (123, ‘xyz’, ‘zara’, ‘abc’), (456, 700, 200)
print “min value element : “, min (tuple1);
print “min value element : “, min (tuple2);
Answer:
Output :
min value element : 123
min value element : 200

19.3 LONG ANSWER TYPE QUESTIONS [4 MARK EACH ]


Question 1:
What is tuple in Python and how can we access values in tuples ?
Answer:
Tuple is a sequence of immutable Python object. Tuples are sequences, just like lists. The only
difference is that tuples can’t be changed i.e.,tuples are immutable and tuples use parentheses and
lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values and optionally you can put
these comma -separated values between parentheses also.
For example :
tup1 = (‘physics’, ‘chemistry1,1997,2000) ;

https://onlinestudytest.com/
tup2 = (1, 2, 3, 4, 5);
tup3 = “a”, “b”, “c”, “d”;
The empty tuple is written as two parentheses containing nothing :
tup1 = ( ) ;
To write a tuple containing a single value you have to include a comma, even though there is only
one
tup1 = (50,);
Like string indices, tuple indices start at 0, and tuples can be sliced, concatenated and so on.
Accessing Values in Tuples :
To access value in tuple, use the square brackets for slicing along with the index or indices to obtain
value available at that index.
Following is a simple example :
# !/user/bin/python
tup1 = (‘physics’, ‘chemistry’, 1997,2000);
tup2 = (1, 2, 3,4,5,6, 7);
print “tup1[0]”, tup1[0]
print “tup2[1:5]:”, tup2[1:5]
When the above code is executed, it produces the following result :
tup1[0] : physics
tup2[1:5]: [2, 3,4,5]

Question 2:
How we update and delete tuples ?
Answer:
Updating Tuples :
Tuples are immutable which means you cannot update them or change values of tuple elements. But
we are able to take portions of an existing tuples to create a new tuples as follows. Following is a
simple example :
#!/user/bin/python
tup1 =(12,34.56);
tup2 = (‘abc’, ‘xyz’);
#Following action is not valid for tuples
#tup1[0] = 100;
#So lets create a new tuple as follows :
tup3 = tup1 + tup2;
print tup3;
When the above code is executed, it produces the following result :
(12,34.56, ‘abc’, ‘xyz’)
Delete Tuple Elements :
Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting
together another tuple with the undesired elements discarded.
To explicity remove an entire tuple, just use the del statement. Following is a simple example :
#!/user/bin/python
tup = (‘physics’, ‘chemistry’, 1997,2000);
print tup;
del tup;
print “After deleting tup:”
print tup;

https://onlinestudytest.com/
This will produce following result. Note an exception raised, there is because after del tup tuple does
not exist any more :
(‘physics’, ‘chemistry’, 1997,2000)
After deleting tup :
Traceback (most recent call last) :
Fill “test.py”, line 9, in < modulo>
print tup;
Name Error : name ‘tup’ is not defined

Question 3:
Explain cmp(tuplel, tuple2) with example.
Answer:
cmp(tuple1, tuple2)
Despription :
The method cmp( ) compares elements of two tuples.
Syntax :
Following is the syntax for cmp( ) method :
cmp (tuplel, tuple2)
Parameters :

tuple 1 – This is the first tuple to be compared

tuple 2 – This is the second tuple to be compared


Return Value :
If elements are of the same type, perform the compare and return the result. If elements are
different types, check to see if they are numbers.

If numbers, perform numeric conversion if necessary and compare.

If either element is a number, then the other element is “larger” (numbers are “smallest”).

Otherwise, types are sorted alphabetically by name.

If we reached the end of one of the tuples, the longer tuple is “larger”. If we exhaust both tuples and
share the same data, the result is a tie, meaning that 0 is returned.
Example :
The following example shows the usage of cmp( ) method
#!/user/bin/python
tuple1, tuple2 = (123, ‘xyz’), (456, ‘abc’)
print cmp(tuple1, tuple2);
print cmp(tuple1, tuple1);
tuple3 = tuple2 + (786,);
print cmp (tuple2, tuple3)
Let us compile and run the above program, this will produce the following result :
-1
1
-1

Question 4:
Explain tuple(seq) function of the python also give example.
Answer:

https://onlinestudytest.com/
tuple(seq)
Description :
The method tuple( ) is used to convert list into a tuple.
Syntax :
Following is the syntax for tuple( ) method :
tuple (seq)
Parameters :
• seq – This is a list to be converted into tuple. Return Value :
This method returns the tuple.
Example :
The following example shows the usage of tupe( ) method.
# !/user/bin/python
aList = [123, ‘xyz’, ‘zara’, ‘abc’];
aTuple = tuple (aList)
print “Tuple elements :”,aTuple
Let us compile and run the above program, this will produce the followin’, result :
Tuple elements : (123, ‘xyz’, ‘zara’, ‘abc’)

Question 5:
Write a program to input ‘n’ numbers and store it in tuple.
Answer:
t = tuple ( )
n = input (“Enter any number”)
print “Enter all numbers one after other”
for i in range (n) :
a = input (“Enter number”)
t = t+(a, )
print “Output is”
print t

Question 6:
Write a program to input any two tuples and interchange the tupel values.
Answer:
t1 = tuple( )
n = input(“Total number of values m first tuple”) for i in range (n) :
a = input(“Enter elements”)
t2 = t2 + (a, )
print “First tuple”
print t1
print “Second tuple”
print t2
t1, t2 = t2, t1
print “After swapping”
print “First tuple”
print t1
print “Second tuple”
print t2

https://onlinestudytest.com/
Question 7:
Write a program to input ‘n’ numbers and separate the tuple in the following manner.
Example
T=(10,20,30,40,50,60)
Tl=(10,30,50)
T2=(20,40,60)
Answer:
t=tuple( )
n=input(” Enter number of values:”)
for i in range(n):
a=input(“enter elements”)
t=t+(a,)
t1=t2=tuple( )
for i in t:
if i%2 == 0:
t2= t2 + (i,)
else:
tl=tl+(i,)
print “First Tuple”
print t1
print “Second Tuple”
print t2
Output:
Enter number of values: 10
enter elements 1
enter elements 9
enter elements 8
enter elements 5
enter elements 2
enter elements 3
enter elements 6
enter elements 4
enter elements 7
enter elements 10
First Tuple (1, 9, 5, 3, 7)
Second Tuple (8,2,6,4,10)

Question 8:
Write a program to input ‘n’ employees’ salary and find minimum & maximum salary among ‘n’
employees.
Answer:
t=tuple( )
n=input(“Enter total number of employees”)
for i in range(n):
a=input(“enter salary of employee:”)
t=t+(a,)
print “maximum salary=”,max(t)
print “minimum salary=”,min(t)

https://onlinestudytest.com/
Output :
Enter total number of employees 3
enter salary of employee: 7800
enter salary of employee: 8934
enter salary of employee:
6544 maximum salary = 8934
minimum salary = 6544

https://onlinestudytest.com/
20
DICTIONARIES

20.1 SHORT ANSWER TYPE QUESTIONS [2 MARK EACH ]


Question 1:
How are dictionaries different from lists ?
Answer:
The dictionary is similar to lists in the sense that it is also a collection of data-items just like lists but
it is different form lists in the sense that lists are sequential collections and dictionarie s are non-
sequential collections. In lists, where there is an order associated with the data items because they
act as storage units for other objects or variables created. Dictionaries are different from lists and
tuples because the group of objects they hold are not in any particular order, but rather each object
has its own unique name, commonly known as a key.

Question 2:
When are dictionaries more useful than lists ?
Answer:
Dictionaries can be much more useful than lists. For example : suppose we wanted to store all our
friend’s cell phone numbers. We could create a list of pairs (phone number, name), but once this list
becomes long enough searching this list for a specific phone number will get time consuming. Better
would be if we could index the list by our friend’s name. This is precisely what a dictionary does.

Question 3:
Write a program to print the worker’s informations (Name age, salary) in records format.
Answer:
Employees = {‘Rohan’ : {‘age’ : 20, ‘salary’ : 10000}, ‘Mohan’ : {‘age’ : 30, ‘salary’ : 15000}}
for key in Employees :
print “Employee”, key + ‘:’
print ‘Age :’ + str (Employees [key] [‘age’]
print ‘Salary :’ + str (Employees [key] [‘salary’])

Question 4:
What is a key-value pair with reference to Python dictionary ?
Answer:
A dictionary is a mapping between a set of indices (which are called keys) and a set of values. Each
key maps a value. The association of a key and a value is called a key-value pair.

Question 5:
What are the characteristics of Python Dictionaries ?
Answer:
The 3 main characteristics of a dictionary are :

Dictionaries are Unordered : The dictionary elements (key-value pairs) are not in ordered form.

https://onlinestudytest.com/
Dictionary Keys are Case Sensitive : The same key name but with different case are treated as
different keys in Python dictionaries.

No duplicate key is allowed : When duplicate keys encountered during assignment, the last
assignment wins.

Keys must be immutable : We can use strings, numbers or tuples as dictionary keys but something
like [‘key’] is not allowed.

20.2 LONG ANSWER TYPE QUESTIONS [4 MARK EACH ]


Question 1:
Explain cmp(dict1, dict2) with example.
Answer:
Description
The method cmp( ) compares two dictionaries
based on key and values.
Syntax
Following is the syntax for cmp( ) method :
cmp(dict1, dict2)
Parameters
• dict1 – This is the first dictionary to be compared with dict2.
• dict2 – This is the second dictionary to be compared with dict1.
Return value :
This method returns 10 if both dictionaries are equal, – 1 if dictl < dict2 and 1 if dictl > dict2.
Example :
The following example shows the usage of comp( ) method.
# !/user/bin/python
dict1 = {‘Name’ : ‘Zara’, ‘Age’ : 7};
dict2 = {‘Name1 : ‘Mahnaz’, ‘Age’ : 27};
dict3 = {‘Name’ : ‘Abid’, ‘Age’ : 27);
dict4 = {‘Name’ : ‘Zara’, ‘Age’ : 7};
print “Return Value : %d”, % cmp (dict1, dict2)
print “Return Value : %d”, % cmp (dict2, dict3)
print “Return Value : %d”, % cmp (dictl, dict4)
Let us compile and run the above program, this will produce the following result :
Return Value : – 1 .
Return Value : 1
Return Value : 0

Question 2:
Explain str(dict) with example.
Answer:
Description
The method str( ) produces a printable string representation of a dictionary.
Syntax
Following is the syntax for str( ) method :
str(dict)
Parameters
• diet – This is the dictionary.

https://onlinestudytest.com/
Return Value
This method returns string representation.
Example :
The following examples shows the usage of str() method.
# !/user/bin/python
diet = {‘Name’ :’Zara’, ‘Age’ : 7);
print “Equivalent String : %s” %str (dict)
Let us compile and run the above program, this will produce the following result :
Equivalent String : {‘Age’ : 7, ‘Name’ : ‘Zara’}

Question 3:
Describe dict.fromkeys( ) with example.
Answer:
dict.fromkeys( )
The method fromkeys( ) creates a new dictionary with keys from seq and values set to v alue.
Syntax
Following is the syntax for fromkeys( ) method :
dict.fromkeys{seq[,value])}
Parameters :
• seq – This is the list of values which would be used be used for dictionary keys preparation .
• value – This is optional, if provided then value would be set to this value.
Return Value
This method returns the list.
Example :
The following example shows the usage of fromkeys( ) method.
#!/user/bin/python
seq = {‘name’, ‘age’, ’sex’)
diet = dict.from keys(seq)
print “New Dictionary : %s” % str(dict)
dict = dict.from keys(seq, 10)
print “New Dictionary : %s” % str(dict)
Let us compile and run the above program, this will produce the following result :
New Dictionary : {‘age’ : None, ‘name’ : None, ‘sex’: None}
New Dictionary : {‘age’ : 10, ‘name’ : 10, ‘sex’ : 10}

Question 4:
Write a program to input total number of sections and class teacher’s name in 11th class and display
all information on the output screen.
Answer:
class xi = diet ( )
n = input (“Enter total number of section in xi class”)
i =1
while i < = n :
a = raw_input (“enter section”)
b = raw input (“enter class teacher name”)
classxi[a] = b
i =i + 1
print “Class”, “\t”, “Section”,
\t„, “Teacher Name”

https://onlinestudytest.com/
for i in classxi :
print “XI”, “\t”, i, “\t”, class xi[i]

Question 5:
Write a Python program to input ‘n’ names and phone numbers to store it in a dictionary and to
input any name and to print the phone number of the particular name .
Answer:
phonebook = dict( )
n = input (“Enter total number of friends”)
i =1
while i<=n :
a = raw_input (“Enter name”)
b = raw_input (“Enter phone number”)
phonebook [a] = b
i =i + 1
name = raw_input (“Enter name”)
f =0
l = phonebook.keys( )
for i in l :
if (comp (i, name) = = 0) :
print “Phone number =”, phonebook[i]
f =1
if (f = = 0):
print “Given name not exist”

Question 6:
Write a Python program to input ‘n’names and phone numbers to store it in a dictionary and to
search and print the phone number of that particular name.
Answer:
phonebook=dict( )
n=input(” Enter total number of friends to create a telephone book”)
i=l
while i<=n:
a=raw_input(“enter name”)
b=raw_input(“enter phone number”)
phonebook[a]=b
i=i+l
name=raw_input(“enter friend’s name to search for”)
f=0
l=phonebook.keys( )
for i in l:
if(cmp(i,name) == 0):
print “Phone number= “,phonebook[i]
f=l
if (f==0):
print “Given name not exist”
Output:
Enter total number of friends to create a telephone
book 5

https://onlinestudytest.com/
enter name Ramu
enter phone number 9842311111
enter name Raju
enter phone number 9842309564
enter name Sarita
enter phone number 9842398765
enter name Sowmya
enter phone number 9842399922
enter name Karan
enter phone number 9842366554
enter friend’s name to search for Sarita
Phone number = 9842398765

Question 7:
Write the code to input any 5 years and the population of any city and print it on the screen .
Answer:
city=dict( )
n=5
i=l
while i<=n:
a=raw_input(” enter city name”)
b=raw_input(“enter population”)
city[a] =b
i=i+l
print city
Output :
enter city name Chennai
enter population 3400000
enter city name Mumbai
enter population 8900000
enter city name Bangalore
enter population 98700
enter city name Calicut
enter population 560000
enter city name Hyderabad
enter population 900000
{‘Bangalore’: ‘ 98700’/ Hyderabad’: ‘ 900000’, ‘ Chennai’: ‘ 3400000’, ‘ Mumbai’: ‘ 8900000’, ‘
Calicut’: ‘ 560000’}

Question 8:
Write a code to create customer’s list with their number & name and delete any particular customer
using his /her number.
Answer:
customer=dict( )
n=input(” Enter total number of customers”)
i=l
while i<=n:
a=raw_input(“enter customer name”)
b=raw_input(“enter customer number”)

https://onlinestudytest.com/
customer[a]=b
i=i+l
name=raw_input(” enter customer name to delete”)
del customer[name]
l=customer.keys( )
print “Customer Information”
print “Name”/\t’/’number”
for i in 1:
print i/\t’,customer[i]
Output :
Enter total number of customers 5
enter customer name Rohan
enter customer number 123678
enter customer name Ranjish
enter customer number 123677
enter customer name Suraj
enter customer number 123899
enter customer name Damu
enter customer number 123777
enter customer name Dhariya
enter customer number .123885
enter customer name to delete Suraj
Customer Information
Name number
Rohan 123678
Dhariya 123885
Ranjish 123677
Damu 123777

Question 9:
Find errors from the following codes:
c=dict( )
n=input(Enter total number) i=l
while i<=n
a=raw_input(“enter place”)
b=raw_input(” enter number”)
c(a)=b
i=i+l
print “place”,”\t”/’number”
for i in c:
print i,”\t”,cla[i]
Answer:
c=dict()
n=input(“Enter total number” )
i=l
while i<=n:
a=raw_input(“enter place”)
b=raw_input(“enter number”)

https://onlinestudytest.com/
c[a]=b
i=i+l
print “place”,”\t”/”number”
for i in c:
print i.”\t”.c[il

Computer science XI class

Unit 1 : Computer Fundamentals

1. Computer overview and its Basics


2. Software Concepts
3. Data Representation
4. Microprocessor and Memory Concepts

https://onlinestudytest.com/
Unit 2 : Programming Methodology

5. Programming Methodology
6. Algorithms and Flowcharts

Unit 3 : Introduction to Python

7. Introduction to Python
8. Getting Started with Python
9. Operators in Python
10. Functions
11. Conditional and looping Constructs

Unit 4 : Programming with Python

12. Strings
13. Lists, Dictionaries and Tuples

https://onlinestudytest.com/

You might also like