Class XI Python Material - String
Class XI Python Material - String
Software are the logical components of the computer system. They are intangible in
nature (i.e. one cannot touch software). Software is the set of programs or instructions.
it helps in maintaining the computer system and performing the various tasks with the
computer system
Both hardware and software together make the computer system function.
Input Devices:
Devices that help user to give input to a computer are called Input Devices.
8
Name of input Image of Input Device Purpose of use
device
Keyboard Basic input device for key entry
9
Digital Camera to obtain photographs or video.
Output Devices : Devices, which display the result of processing are known as Output
Devices.
Examples:
10
CENTRAL PROCESSING UNIT (CPU)
CPU is called brain of the computer. It is also known as processor. It is responsible for
carrying out all activities in a computer. It is further divided into three parts:
• Arithmetic Logic Unit (ALU): This unit is responsible for arithmetic
calculations and comparison.
• Control Unit (CU): This unit is responsible for flow of data and instructions
between different units of computer. It decides whether data should go to ALU,
registers, memory unit, secondary storage or output unit.
• Registers: They are memory cells inside CPU to store data temporarily. They are
mainly used to store frequently used data.
MEMORY UNIT
Memory unit is used to store data and instructions. It stores data in machine language
i.e. in the form of 0 and 1. The binary digits 0 and 1 are known as bits.
PRIMARY MEMORY: Memory unit is also termed as primary memory. It consists of
three parts:
• RAM (Random Access Memory)
• ROM (Read Only Memory)
• Cache Memory
RAM (Random Access Memory): It is used to store data and instructions temporarily.
It retains data in it as long as the power is on. All the contents of RAM get cleared if
power supply is turned off.
Types of RAM:
• DYNAMIC RAM: It consists of capacitors and transistors. It uses electric charge
to store the data.
• STATIC RAM: It consists of flip-flops. It stores data in binary form. It has faster
access time compared to dynamic RAM.
ROM (Read Only Memory) : ROM stands for Read Only Memory. Data is permanently
stored in ROM. it contains instructions needed to start up the computer and load
operating system into RAM.
Types of ROM:
• PROM (Programmable Read Only Memory) : It can be programmed once.
• EPROM (Erasable Programmable Read Only Memory): It can be erased by
keeping ROM chip using Ultraviolet light. It can be reprogrammed..
• EEPROM (Electrically Erasable Read Only Memory): It can be erased by
electrical signal. It can also be reprogrammed.
CACHE MEMORY:
It is special memory used to compensate the speed difference between CPU (very fast)
and RAM (very slow). It stores the copies of frequently used data from RAM. Hence it
reduces the time required to access data from primary memory.
11
1 GB (Gigabyte) = 1024 MB
1 TB (Terabyte) = 1024 GB
1 PB (Petabyte) = 1024 TB
1 EB (Exabyte) = 1024 PB
1 ZB (Zettabyte) = 1024 EB
SECONDARY STORAGE UNIT:
Secondary storage unit is used to store data permanently. It consists of different types
of storage devices. Most commonly used storage devices are:
1) Hard Disk: It is the most commonly used storage device to store data on a
computer. It consists of multiple magnetic plates and heads to read and write
data. Magnetic plates are further divided into tracks and sectors to store data.
Maximum capacity of hard disk is 15TB.
2) Compact Disk (CD): it is an optical disk to store data. it have a storage capacity
of 700 MB. There are three types of CDs:
➢ CD-ROM (Compact Disk Read Only Memory): These are pre-recorded CDs
provided by manufacturers. Example: CDs containing softwares, games,
ebooks etc.
➢ CD-R (Compact Disk Recordable): Data can be recorded on these CDs only
once.
➢ CD-RW (Compact Disk Rewritable): These types of CDs can be erased and
recorded multiple times.
3) Digital Versatile Disk (DVD): it is an optical disk to store data and have a
storage capacity of upto 17 GB. There are three types of DVDs:
➢ DVD-ROM (Digital Versatile Disk – Read Only Memory): These are
prerecorded DVDs provided by manufacturers. Example: DVDs containing
movies etc.
➢ DVD-R (Digital Versatile Disk – Recordable): Data can be recorded on these
DVDs only once.
➢ DVD-RW (Digital Versatile Disk – Rewritable):These types of DVDs can be
erased and recorded multiple times.
4) Blu Ray Disk: it is optical disk that can store HD (High Definition) videos and
data. They can store up-to 128 GB of data.
5) Pen Drive : It is also called Flash memory. It is a solid state memory that can
store more than 128GB of data.
TYPES OF SOFTWARE:
Software is defined as a collection of programs which are used for different purposes.
Utility Software :
These softwares are used to take backup, remove outdated file, recover data and other
tasks that assist in smooth operation of computer.
Examples : Anti-Virus , Disk Defragmentation, Disk Clean, Backup, etc.
Device Driver: A device driver is a particular form of software application that allows
one hardware device to interact with another hardware device .A device driver may also
be called a software driver. Example connecting a PC to a printer.
➢ Process Management:- The operating system takes care of the allotment of CPU
time to different processes. it can create and delete processes. It also provides
mechanism for communication among processes. This deals with management of
the Central Processing Unit (CPU). This is known as scheduling.
➢ Memory Management:- The CPU and the I/O devices interact with the memory.
When a program needs to be executed it is loaded onto the main memory till the
execution is complete. Thereafter that memory space is freed and is available for
other programs. The common memory management techniques used by the
operating system are Partitioning and Virtual Memory. Operating System
allocates and de-allocates memory to different softwares.
➢ File Management:- It manages storage, retrieval, naming, sharing, and
protection of files. It also manages the files, folders and directory systems on a
computer. The file manager of the operating system helps to create, edit, copy,
allocate memory to the file.
13
➢ Device Management: The Operating System communicates with hardware
and the attached devices and maintains a balance between them and the CPU.
This is all the more important because the CPU processing speed is much higher
than that of I/O devices. It is responsible allocation and de-allocation of the
hardware devices to different programs. In order to optimize the CPU time, the
operating system employs two techniques - Buffering and Spooling.
➢ I/O System Management: It takes care of allocation and de-allocation of
Input/Output devices to different programs.
14
• SOLARIS is registered as compliant with Single UNIX Specification. It is quite
scalable and is used on virtual machines.
Computers are designed to work internally with numbers. In order to handle characters,
we need to choose a number for each character. The ability of a computer system to
understand signals or letters depends on its character set
The complete set of characters / symbols are called alphanumeric codes. The complete
alphanumeric code typically includes −
➢ 26 upper case letters (A-Z)
➢ 26 lower case letters (a-z)
➢ 10 digits (0-9)
➢ 7 punctuation marks
➢ 20 to 40 special characters
Following are some forms of character set or encoding schemes:
15
➢ ASCII
➢ ISCII
➢ UNICODE
ASCII Code: (American Standard Code for Information Interchange) most of the micro
computers, mini computers and some mainframe computers use this code.
ASCII code has two versions - ASCII – 7 and ASCII – 8.
➢ ASCII – 7 code use 7 bits for one signal or character. By this, 27 = 128 , different
characters can be used.
➢ ASCII – 8 code use 8 bits for one signal or character. By this, 28 = 256 , different
characters can be used.
ISCII: it stands for Indian Script Code for Information Interchange for Indian languages.
In order to facilitate the use of Indian languages on Computers, a common standard for
coding Indian scripts called ISCII was developed in India.
It is an 8-bit code representation for Indian languages which means it can represent
28=256 characters. It retains all 128 ASCII codes and uses rest of the codes 128 for
additional Indian language character set. Additional codes have been assigned in the
upper region (160– 255) for the ‘aksharas’ of the language. These codes are used for ten
Indian scripts - Devnagari, Punjabi, Gujarati, Oriya, Bengali, Assamese, Telugu, Kannada,
Malayalam and Tamil.
UNICODE: (UNIVERSAL CODE)
This is Universal Character Set which represents a signal or a character in a group of 32
bit. It has the capability to include signals and characters from all scripts of all languages
of world.
The Unicode Standard is the universal character encoding standard for written
characters and text. Each character or symbol is assigned a unique numeric value,
largely within the framework of ASCII. Earlier, each script had its own encoding system,
which could conflict with each other.
The purpose of Unicode is to −
provide a unique number for every character,
no matter what the platform,
no matter what the program,
no matter what the language.
Unicode characters are represented in one of three encoding forms:
➢ an 8-bit form (UTF-8)
➢ a 16-bit form (UTF-16)
➢ a 32-bit form (UTF32)
EXERCISES
(Multiple Choice Questions)
1. The physical and tangible components of the computer are termed as:
a) Hardware b) software c) firmware d) None
4. A computer program that converts an entire program into machine language is called-
a) Interpreter b) Compiler c) Linker d) Assembler
16
6. Which of the following are two main components of CPU?
a) ALU & MU b) ALU & CU c) I/O d) None
Answers
1 2 3 4 5 6 7 8 9 10
A A C B A B C A C A
Q. 4. What is a bit ? How bit, byte and nibbles are related to each other?
Ans. : 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.
❖ Micro Computers: These are also known as Personal Computers. These type of
digital computer uses a microprocessor (a CPU on a single chip) and include both
desktops and laptops. These computers can work on small volume of data, are
very versatile and can handle variety of applications. These computers are being
used as work stations, CAD, multimedia and advertising applications. Small
portable computers such as PDAs (Personal Digital Assistants) and tablets with
wireless computing technology are increasingly becoming popular.
❖ Main Frames: These computers are large and very powerful computers with
very high memory capacity. These can process huge databases such as census at
extremely fast rate. They are suitable for big organizations, banks, industries etc.
and can support hundreds of users simultaneously on the network.
❖ Super Computers: These are fastest and very expensive computers. They can
execute billions of instructions per second. These are multiprocessor, parallel
systems suitable for specialized complex scientific applications involving huge
amounts of mathematical applications such as weather forecasting.
18
Q. 4 Distinguish between internal and external memory.
Ans :-
Internal memory External memory
20
NUMBER SYSTEM:
Each number system has a base also called a Radix. A decimal number system is a
system of base 10; binary is a system of base 2; octal is a system of base 8; and
hexadecimal is a system of base 16.
S.No. Number System Base Symbols or digits used
1 Binary 2 0,1
2 Octal 8 0,1,2,3,4,5,6,7
3 Decimal 10 0,1,2,3,4,5,6,7,8,9
4 Hexadecimal 16 0,1,2,3,4,5,6,7,8,9, A, B, C, D, E, F
where A = 10; B = 11; C = 12; D = 13; E = 14; F = 15
CONVERTING A NUMBER FROM ONE BASE TO ANOTHER
DECIMAL TO BINARY
Method to convert a Decimal number into its Binary equivalent
1. Divide the decimal number by 2.
2. Take the remainder and record it on the side.
3. Divide the quotient by 2.
4. REPEAT UNTIL the decimal number cannot be divided further.
5. Record the remainders in reverse order and you get the resultant binary number.
Example:
Convert the Decimal number 125 into its Binary equivalent.
Number Method Quotient Remainder
125 Divide
125/2 62 1
62/2 31 0
31/2 15 1
15/2 7 1
7/2 3 1
3/2 1 1
1/2 0 1
Answer: (1111101)2
CONVERTING DECIMAL FRACTION TO BINARY
Example:
Convert (0.75)10 to binary
➢ Multiply the given fraction by 2.
➢ Keep the integer in the product as it is and multiply the new fraction in the
product by
➢ Continue the process till the required number of decimal places or till you get
zero in the fraction part.
➢ Record the integers in the products from top to bottom.
Given fraction 0.75
➢ Multiply 0.75 by 2 =1.50
➢ Multiply 0.50 by 2 = 1.00
➢ Reading the integers from top to bottom
0.75 in decimal number system is 0.11 in binary number system.
Example:
Convert the Decimal number 125 into its Octal equivalent.
125 / 8 = 15 5
15 / 8 =1 7
1 / 8 =0 1
Answer: (175)8
Converting Decimal fraction to Octal
Example
Convert (0.75)10 to Octal
➢ Multiply the given fraction by 8.
➢ Keep the integer in the product as it is and multiply the new fraction in the
product by 8.
➢ Continue the process and read the integers in the products from top to bottom.
Given fraction 0.75
Multiply 0.75 by 8 6.00
Reading the integers from top to bottom 0.75 in decimal number system is 0.6 in octal
number system.
Example:
Convert the Hexadecimal number AB to its Decimal equivalent.
=A x161 + B x 160
=10 x 161 + 11 x 160
=160+11 = (171)10
Hexadecimal fraction to decimal Conversion
Example:
Convert (1E.8C)16 to decimal
1 E 8 C
= (1 x 16 )+ (14 x 16 )+ (8 x 16-1)+ (12 x 16-2)
1 0
= 16 + 14 + 0.5 + 0.04688
= (30.54688)10
We take a binary number in groups of 4 and use the appropriate hexadecimal digit in it’s
place. We begin at the rightmost 4 bits. If we are not able to form a group of four, insert
23
0s to the left until we get all groups of 4 bits each. Write the hexadecimal equivalent of
each group. Repeat the steps until all groups have been converted.
Example:
Convert the binary number 1000101 to its Hexadecimal equivalent.
0100 0101 (Note that we needed to insert a 0 to the left of 100.)
4 5
Answer: (45)16
In case of a fractional binary number form groups of four bits on each side of decimal
point. Then replace each group by its corresponding hexadecimal number.
Example:
Convert (11100.1010)2 to hexadecimal equivalent.
0001 1100 . 1010
1 C . A
Answer : (1C.A)16
HEXADECIMAL TO BINARY CONVERSION:
0 0000 0 0
1 0001 1 1
2 0010 2 2
3 0011 3 3
4 0100 4 4
5 0101 5 5
6 0110 6 6
7 0111 7 7
8 1000 10 8
9 1001 11 9
10 1010 12 A
11 1011 13 B
12 1100 14 C
13 1101 15 D
14 1110 16 E
15 1111 17 F
Exercises
(Multiple Choice Questions)
1. An organized way of representing numbers is called:
a) Character System b) Number system c) Integer system d) None
2. How graphics are represented by the computer?
a) Unicode b) ASCII c) Bitmap d) Binary
Answer :
1 2 3 4 5 6 7 8 9 10
B C B C C D B A B B
25
(Short Anwser Type Questions):
23 0 21 0 (1010)2=(10)10
(b)
1 1 1 0 1 0
25 24 23 0 22 0 (111010)2=(60)10
(c)
1 0 1 0 1 1 1 1 1
28 0 26 0 24 23 22 21 1 (101011111)2=(351)10
4 D D
(10011011101)2=(4DD)16
26
BOOLEAN ALGEBRA
INTRODUCTION:-
Boolean algebra was developed by English Mathematician George Boole. It is described
as algebra of logic or algebra of two values i.e True or False.
The term logic means a statement having binary decisions i.e True/Yes or False/No.
APPLICATION OF BOOLEAN ALGEBRA:-
It is used to perform the logical operations in digital computer. In digital computer True
represent by ‘1’ (high volt) and False represent by ‘0’ (low volt). Logical operations are
performed by logical operators. The fundamental logical operators are:
1. AND (conjunction)
2. OR (disjunction)
3. NOT (negation/complement)
AND operator: It performs logical multiplication and denoted by (.) dot.
X Y X.Y
0 0 0
0 1 0
1 0 0
1 1 1
OR operator: It performs logical addition and denoted by (+) plus.
X Y X+Y
0 0 0
0 1 1
1 0 1
1 1 1
NOT operator: It performs logical negation and denoted by (-) bar or single quote ( ‘ ).
It operates on single variable.
X X’ ( ‘ means complement of x)
0 1
1 0
Truth Table
Truth table is a table that contains all possible values of logical variables/statements in
a Boolean expression.
No. of possible combination = 2n, where n=number of variables used in a Boolean
expression. The truth table for XY + Z is as follows:
Dec X Y Z XY XY+Z
0 0 0 0 0 0
1 0 0 1 0 1
2 0 1 0 0 0
3 0 1 1 0 1
4 1 0 0 0 0
5 1 0 1 0 1
6 1 1 0 1 1
7 1 1 1 1 1
TAUTOLOGY & FALLACY:
➢ If the output of Boolean expression is always True or 1 is called
Tautology.
➢ If the output of Boolean expression is always False or 0 is called Fallacy.
27
Logic Gate:
A gate is a digital circuit which operates on one or more signals and produce single
output. Gates are digital circuits because the input and output signals are denoted by
either 1(high voltage) or 0(low voltage).
There are three basic gates:
AND gate : The AND gate is an electronic circuit that gives a high output (1) only if
all its inputs are high. AND gate takes two or more input signals and produces only
one output signal.
0 0 0
0 1 0
1 0 0
1 1 1
0 1 1
1 0 1
1 1 1
NOT gate: The NOT gate is an electronic circuit that gives a high output (1) if its
input is low. NOT gate takes only one input signal and produce only one output
signal. The output of NOT gate is complement of its input. It is also called inverter.
Input Output
A A’
0 1
NAND, NOR XOR, XNOR GATES
NAND gate :
The NAND gate or “Not AND” gate is the combination of two basic logic gates, the AND
gate and the NOT gate connected in series. The NAND gate and NOR gate can be called
the universal gates since the combination of these gates can be used to accomplish any
of the basic operations. Hence, NAND gate and NOR gate combination can produce an
inverter, an OR gate or an AND gate.
28
The output of a NAND gate is high when either of the inputs is high or if both the inputs
are low. In other words, the output is always high and goes low only when both the
inputs are high. The logic NAND function is given by the Boolean expression:
Truth Table
Logical Circuit X Y Z
0 0 1
Logical expression: 0 1 1
X
1 0 1
Z Z = ~(X & Y) 1 1 0
nand(Z,X,Y)
Y
NOR gate: The NOR gate is a digital logic gate that implements logical NOR. A HIGH
output (1) results if both the inputs to the gate are LOW (0); if one or both input is HIGH
(1), a LOW output (0) results. NOR is the result of the negation of the OR operator. The
NOR gate is one of the universal gates. A NOR gate combines an OR gate and a NOT gate.
XOR gate : The Exclusive-OR gate or XOR gate is achieved by combining standard logic
gates together. XOR gate is used extensively in error detection circuits, computational
logic comparators and arithmetic logic circuits. The Exclusive OR gate gives an output
only if its two inputs are dissimilar, namely if one of them is high (one) and the other is
low (zero).
Truth Table
Logical Circuit X Y Z
Logical expression 0 0 0
Z=X^Y 0 1 1
X xor(Z,X,Y) 1 0 1
Z 1 1 0
Y
De Morgan's Theorem:
‘De Morgan’ was one of the Cambridge mathematicians. He recognized that the nature of
algebra is purely symbolic. He was very much aware of the possibility that some
algebras differ from ordinary algebra.
We use De Morgan’s theorems to solve the expressions of Boolean algebra. It is a very
powerful tool used in digital design. De Morgan’s theorems can be used when we want
to prove that the NAND gate is equal to the OR gate that has inverted inputs and the
NOR gate is equal to the AND gate that has inverted inputs. To reduce the expressions
that have large bars, we must first break up these bars.
DeMorgan’s First Theorem:
DeMorgan’s First theorem proves that when two (or more) input variables
are AND’ed and negated, they are equivalent to the OR of the complements of the
individual variables. Thus the equivalent of the NAND function will be a negative-OR
function, proving that
30
We can also show that using logic gates
and again we can show this operation using the following truth table.
31
EXERCISES
(Multiple Choice Question)
1. When the result of any Boolean statement is always 1 is known as ___________.
a) True
b) Tautology
c) Fallacy
d) False
2. When the result of any Boolean statement is always 0 is known as ______________.
a) True
b) Tautology
c) Fallacy
d) False
3. The logical operations can be carried out by which of the following?
a) Values and Variables
b) Functions and Laws
c) Operators and Operands
d) None of these
4. To denote NOT operation which of the following symbols is used?
a) bar
b) dot
c) plus
d) asterisk
5. The dot symbol is used to represent which of the following operation?
a) AND
b) OR
c) NOT
d) NAND
6. Which of the following are logical statements:
a) The Indian cricket team is a world champion in 2011.
b) The NOT function can be operated on more than one Boolean function.
c) Both a & b.
d) None of the above
7. Which of the following gate is also known as an inverter
a) AND
b) OR
c) NOT
d) NAND
8. Which of the following gate returns a true result if both inputs are true otherwise
false.
a) AND
b) OR
c) NOT
d) None of the above
9. Which gate can be written like A & B
a) AND
b) OR
c) NOT
d) XOR
10. Which gate returns true if both inputs are similar otherwise false.
a) NAND
b) NOR
c) XOR
d) None of the above
32
Answers:
1 2 3 4 5 6 7 8 9 10
B C C A A C C A A C
X+X’ X.X’
X X’ X.X’
X X’ X + X’
0 1 0
0 1 1
1 0 0
1 0 1
33
Unit II: Computational Thinking and Programming – 1
Introduction to problem solving:
Problem solving is the process in which we identify a problem, developing an algorithm
for the identified problem and finally implementing the algorithm to develop a
computer program.
Steps for problem solving –
Problem solving starts with the identification of the problem and ends with a complete
solution in terms of a program or software. Key steps required for solving a problem
using a computer are-
i. Analysing the problem- we need to read and analyse the problem statement to solve
the problem and decide the core functionalities that our solution should have.
ii. Developing an Algorithm -It is essential to device a solution before writing a
program code for a given problem. Algorithm is a set of exact steps which when
followed ,solve the problem or accomplish the required task. For a given problem, more
than one algorithm is possible and we have to select the most suitable solution.
iii. Coding- convert the algorithm into the format which can be understood by the
computer to generate the desired solution. Different high level programming languages
can be used for writing a program.
iv. Testing and Debugging- The program created should be tested on various
parameters. The program should meet the requirements of the user. It must respond
within the expected time. It should generate correct output for all possible inputs.
Program should be checked for errors, if any.
Algorithm -A sequence of steps to accomplish the task. Such a finite sequence of steps
required to get the desired output is called an algorithm. It will lead to the desired result
in a finite amount of time, if followed correctly. Algorithm has a definite beginning and a
definite end, and consists of a finite number of steps.
Characteristics of a good algorithm are-
• Precision — the steps are precisely stated or defined.
• Uniqueness - results of each step are uniquely defined and only depend on the input
and the result of the preceding steps.
• Finiteness — the algorithm always stops after a finite number of steps.
• Input — the algorithm receives some input.
• Output — the algorithm produces some output.
Flowchart -A flowchart is a pictorial representation of an algorithm. We use boxes,
diamonds and other shapes, connected by arrows in flow chart.
Pseudocode-A pseudocode is a way of representing an algorithm. It is considered as a
non-formal language that helps programmers to write algorithm. It is intended for
human reading and cannot be executed directly by the computer. No specific standard
for writing a pseudocode exists. By writing the pseudocode the programmer safeguards
against leaving out any important step. Besides, for non-programmers, actual programs
are difficult to read and understand, but pseudocode helps them to review the steps to
confirm that the proposed implementation is going to achieve the desire output.
34
Basics of Python programming:
Introduction to Python -Python is a general-purpose Object Oriented Programming
language, High-level language Developed in late 1980 by Guido van Rossum at National
Research Institute for Mathematics and Computer Science in the Netherlands. It is an
Open Source Scripting language and is Case-sensitive language .
Features of Python
• Python is a high level language. It is a free and open source language.
• It is an interpreted language, as Python programs are executed by an interpreter.
• Python programs are easy to understand as they have a clearly defined syntax and
relatively simple structure.
• Python is case-sensitive. For example, NUMBER and number are not same in Python.
• Python is portable and platform independent, means it can run on various operating
systems and hardware platforms.
• Python has a rich library of predefined functions.
• Python is also helpful in web development. Many popular web services and
applications are built using Python.
• Python uses indentation for blocks and nested blocks
There are two ways to use the Python interpreter:
a) Interactive mode b) Script mode
36
% Modulus Divides the operand on >>>a=10
the left with the >>>b=3
operand on the right >>>a%b
and returns the 1
remainder
// Floor Division Floor division. To >>>a=10
find the integer part >>>b=6
of the quotient when >>>a/b
one number is 1
divided by the other.
The result is always
the largest integer
less than or equal to
the actual quotient.
** Exponent To raise a number to >>>a=2
the power of another >>>b=3
number. >>>a**
b
8
Relational Operator
Operator Operation Description Example
== Equals to Compares two values. If both are equal >>>x=5
returns true else returns False >>>y=4
>>>z=4
>>>x==y
False
>>>y==z
True
!= Not Equals to Compares two values. If both are not >>>x!=y
equal returns true else returns False True
>>>y!=z
False
> Greater Than If the value of the left operand is greater >>>y>x
than operand on the rightside of False
operator then returns true else return >>>x>z
False True
< Less than If the value of the left operand is smaller >>>y<z
than operand on the rightside of True
operator then returns True >>>x<y
else return False False
>= Greater than or If the value of the left operand is greater >>>z>= y
equal to than or equal to operand on the right True
side of operator then >>> y>= x
returns True else return False False
<= Less than or If the value of the left operand is smaller >>>x<= y
equal to than operand on the rightside of False
operator then returns true else return >>>z <= x
False True
37
Logical operators
Operators Description Example
And Combines two conditions and returnsTrue if >>>a=6
both conditions are True else returns False >>>b=5
>>>a==6 and b==5
True
>>>a1==10 and b==5
False
Or Combines two conditions and returns True if any >>>a==6 or b==0
condition is True else returnsFalse True
>>>a==0 or b==4
False
Not Negates a condition and returns True if the >>>not (a==0)
condition is False, otherwise returns False. True
>>>not (b==5)
False
Assignment Operator
Operator Description Example (x=2,
y=5)
= Assigns value from right side operand to left side >>>z=x+y
operand >>>z
7
+= It adds the value of right-side operand to the >>>x+=2
left-side operand and assigns the result to the
>>>x
left-side operand
4
38
**= It performs exponential (power) calculation on >>>x**=3
operators and assigns value to the left-side
>>>x
operand 8
Identity operator
Operator Description Example
Is Evaluates True if the variables on either side >>> num1 = 5
of the operator point towards the same >>> type(num1) is int
memory location and False otherwise. var1 True
is var2 results to True if id(var1) is equal to >>> num2 = num1
id(var2) >>> id(num1)
1433920576
>>> id(num2)
1433920576
>>> num1 is num2
True
is not Evaluates to False if the variables on either >>> num1 is not num2
side of the operator point to the same False
memory location and True otherwise. var1
is not var2 results to True if id(var1) is not
equal to id(var2)
6. Membership Operator
Operators Description Example
In It return True in case value exists in >>>N=[5,7,1]
sequence, otherwise false. >>>1 in N
True
>>> 4 in N
False
not in return True if value does not exists in the >>>N=[4,8,7]
sequence, else false. >>>4 not in L
False
>>> 0 not in L
True
Precedence of Operators:
The order in which the operators are executed in an expression is called the operator
precedence. Operator precedence of some common operators are given below:
39
Comments- Comments are used to add a remark or a note in the source code. they
are not executed by interpreter. They are added with the purpose of making the source
code easier for humans to understand. In Python, a comment starts with # (hash sign).
Everything following the # till the end of that line is treated as a comment.
Data Types-
Data Type specifies which type of value a variable can store. type () function is used to
determine a variable's type in Python. Data type in Python can be categorized as
follows:
1. Number: Number data type stores numerical values. A feature Python is that there
is no need to declare a numeric value to define its type. Python can easily
differentiate one data typefrom another when you write and run your statement.
(a) int(integer): Integer represents whole numbers without any fractional part. They
can be positive or negative and have unlimited size in Python. Example: -6, 468, 0, 4, -
43.
(b) float(floating point number): Floating point numbers denote real numbers or
floating point values (i.e., numbers with fractional part). Example: 3.14, 565.34, 0.76, 4.0
(c)Complex Numbers: Complex numbers in Python are made up of pairs of real and
imaginary numbers. They take the form ‘x + yj’ or ‘x + yJ’ Example:
a = complex(50) # convert 50 to a real part val and zero imaginary part
b=complex(87,54) #convert 87 with real part and 54 as imaginary part
print(b)
Output :-
(5+0j)
(101+23j)
2. str(string):A string is a sequence of characters that can be a combination of letters,
numbers and special symbols, enclosed within quotation marks, single, double, or
triple (‘ ‘ or “ “ or ‘‘‘’’’). These quotes are not part of the string.
3. Boolean: Boolean data type represents one of the two possible values, True or False.
Any expressionwhich can be True or False has the data type bool.
4. None: This is a special data type with a single value. It is used to signify the absence
of value/condition evaluating to False in a situation. It is represented by None.
5. List: A list is a collection of values or an ordered sequence of values/items. The
items in a listcan be of any type such as string, integers, float, objects or even a list.
Elements of a list are enclosed in square brackets [ ], separated by commas.
Example: >>> A = [6,8,2,9,100]
>>>print( A )
[6,8,2,9,100]
6.Tuple: Tuple is another sequence data type similar to the list. A tuple consists of a
number of values separated by commas. Unlike lists however, tuples are enclosed
within parentheses. Elements in a tuple need not be of the same type, they can be
heterogeneous.
Example: >>> T = ( 80,40,25, 30, 50 )
>>>print( L )
( 80,40,25, 30, 50)
40
7.Dictionary: -Python-dictionary is an unordered collection of items where each item
is a key-value pair. We can also refer to a dictionary as a mapping between a set of keys
and set of values. The items of a dictionary are enclosed within curly braces and items
are separated by commas.The key value pairs are separated by colon (:).
Example: Dict = { “Hindi” : 96, “English” : 88, “Maths” : 91 }
Statement- In Python, a statement is a unit of code that the Python interpreter can
execute. For example
a=50
x=sum(4,5)
input/output - input() function is used for taking the user input. The input()
function prompts the user to enter data. It accepts all user input as string.
name = input("Enter your name: ")
print() function is used to output data to the screen. It evaluates the expression before
displaying it on the screen. The print() outputs a complete line and then moves to the
next line for subsequent output. The syntax for print() is:
print(value [, ..., sep = ' ', end = '\n'])
print( "Bikaner")
Type Conversion: It is the process of converting the value of one data type to
another.
41
Debugging- The process of identifying and removing errors or mistakes from a
program is called debugging and the mistakes known as errors. Errors can be
categorized as:
i) Syntax errors
ii) Logical errors
iii) Runtime errors
1. Syntax Error:
If a statement is not written as per syntax/ rules of python, syntax errors are there and
interpreter shows error message(s) and stops the execution there. Example 1:
print(“India) #syntax error as right double quote is missing
Example 2: Print(“Hello”) #syntax error due to P is capital
2. Logical Error:
Logical errors are the most difficult to find and fix. These types of error is caused due to
wrong logic. No syntax error /error message will be there.
Example:
x=5
y = 10
m=x+y
print (“Multiplication of x and y = “, m) # results wrong as used + instead of *
3.Runtime Error:
A runtime error causes abnormal termination of program while it is executing. In this
error statement is correct syntactically, but the interpreter cannot execute it. Runtime
errors do not appear until after the program starts running or executing. For example, a
statement having division operation in program, if denominator value is zero then it
will give a runtime error “division by zero”.
42
Flow of Control
The order of execution of the statements in a program is known as flow of control.
Control statements are used to control the flow of execution depending upon the
specified condition/logic. There are three types of control /flow statements-
1. Sequential flow
2. Conditional Flow
3. Iterative flow
Sequential flow- It is the concept, where Python executes one statement after another
from beginning to the end of the program.
Conditional / Decision making statement-Decision making statement used to control
the flow of execution of program depending upon condition. Following conditional
statements available in python -
• if statement
• if-else statement
• if-elif- else statement
• Nested if statement
if statement-In this it checks the condition and execute the statement if the condition is
true and do nothing if the condition is false.
Syntax:
if condition:
Statements
Example-
x=1
if(x==1 ):
print(“x is one”)
if-else statement-if with else is used to test the condition and if the condition is True it
perform /execute true block otherwise false block.
Syntax:
if condition:
Statements #True Block
else:
Statements # False block
Example-
num = int(input("Enter a number= "))
if (num%2==0):
print("even number ")
else:
print("odd number")
if-elif- else statement-In this variant of if multiple chain of condition is to be checked.
Each elif must be followed by condition: and then statement for it. After every elif we
can give else which will be executed if all the condition evaluates to false
Syntax:
if condition:
Statements
elif condition:
Statements
elif condition:
Statements
else:
Statement
43
Nested if statement- In nested type of “if” we use if within another if as a statement of
it. Mostly used in a situation where we want different else for each condition. Syntax:
if condition1:
if condition2:
statements
else:
statements
elif condition3:
statements
else:
statements
Example:
num = float (input ("Enter a number: "))
if num>= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
for loop- This loop is used to iterate over a range of values or a sequence. The for loop
is executed for each of the items in the range. These values can be either numeric, or,
they can be elements of a data type like a string, list, or tuple.
Syntax:
for val in sequence:
statements #body of loop
Example-1
city=["Bikaner","Jodhpur,"Jaipur","Sikar"]
for i in city:
print(i)
Usage of Range()-
It is used to create a list containing a sequence of integers from the given start value up
to stop value (excluding stop value), with a difference of the given step value. The range
() is a built-in function in Python. Syntax of range () function is:
range([start], stop[, step])
Example-2
x=1
while (x < 3):
print('inside while loop value of x is ',x)
x=x+1
else:
print('inside else value of x is ', x)
Jump Statements- These statements are used to transfer the program's flow from one
location to another. There are two types of jump statements -.
1. break
2. continue
Break- The break statement terminates the current loop and resumes execution of the
statement following that loop.
Example-
for I in range(1,100):
if i == 10:
break
print(i) # the code will print only 1 to 9
Continue- The continue statement skips the current execution of loop and jump for
next execution of the loop.
Example-
for I in range(1,100):
if i == 10:
continue
print(i) # the code will print 1 to 99 without 10
pass -This statement does nothing but can be used if no action in a statement.
for i in range (1,100):
if(i >=50):
pass
else:
print(i)
45
==================================================================
Exercises
(MCQ type Question 1 Marks)
1. Who developed Python Programming Language?
a) Wick van Rossum b) Rasmus Lerdorf
c) Guido van Rossum d) Niene Stom
Answer: c
2. Which of the following is the correct extension of the Python file?
a) .python b) .pys
c) .py d) .p
Answer: c
3 What will be the value of the following Python expression?
1 + 10 % 4
a) 3 b) 2
c) 11 d) 1
Answer: a
4. Which of the following character is used to give single-line comments in Python?
a) @ b) #
c) ! d) /*
Answer: b
5. Which one of the following is not a keyword in Python language?
a) for b) evals
c) while d) false
Answer: d
6. What will be the output of the following Python program?
i=1
while i < 5:
i += 1
print(i)
a) 5 b) 0
c) 1 d) none of the mentioned
Answer:a
7. run tyme error in a code means:
(a)You have not used correct logic.
(b) There was error while running the program.
(c) There is an error with your typing and code structure
(d) None of above.
Answer: b
8. Which of the following is not a core data type in Python programming?
a) Tuples b) Lists
c) Class d) Dictionary
Answer: c
9. What will be the output of the following Python code?
x = 'abcd'
for i in x:
print(i.upper())
a) a B C D b) a b c d
c) error d) A B C D
Answer: d
10.What will be the output of the following Python statement?
>>>"a"+"bc"
a) bc b) abc
c) a d) bca
Answer: b
46
(VSA type Question 2 Marks)
1. What are data types? How are they 2. What are immutable and mutable
important? types? List immutable and mutable
Answer = representation of many types types of python.
of data in by provided facilities is called Answer = immutable type :- those
data type . types whose value never change is
Example = integer, string , list etc. known as immutable type.
They are play very important role in Example = integer , string , Boolean,
programming because without any tuples , e.c.t
data of program , program can cause Mutable type: - those type whose value
error , so program needed data can be change is known as mutable
type.Example = list, dictionary, set
3. What are tokens in Python? How 4. What will the result given by the
many types of tokens are allowed in following ?
python? Exemplify your answer. (a)type(6+3)
Answer =Token are smallest individual (b)type(6-3)
unit in a program. (c)type(6*3)
Type of tokens (d)type(6/3)
keywords : False, True, for, while (e)type(6//3)
identifiers : a, A, lst, dic (f)type(6%3)
literal : “python”, 5, 9, ‘class11’ Answer =
operator : +, -, /, *, **, %, // (a)int (b)int (c)int
punctuators :&, ^, ?, #, @, ! (d)float (e)int (f)int
5. What are variables? How are they 6. In Python, strings are immutable
important for a program? while lists are mutable. What is the
Answer =Variable is a label that can difference?
used in process of program. it can Answer =(i) In consecutive locations,
contain numeric values, character, strings store the individual characters
string is called variable. while list stores the references of its
Variable play very important role in elements
programming because they enable (ii) Strings store single type of
programmers to write flexible elements - all characters while lists can
programs. without variable we can not sore elements belonging to different
enter the data directly in the program. types.
47
(Short answer type Question 2 Marks)
Q-1 Rewrite the following code Q-2 Find the output of the following code
fragments using for loop: segments:
i = 10 x = 40
while (i > 0) : y=x+1
print (i) x = 20, y + x
i -= 3 print (x, y)
Answer = Answer =
for i in range (10,0,-3): Output:
print (i) (20, 81) 41
Q-3 What will be the output Q-4 What will be the output produced by
produced by following code following code?
fragment (s)? (a)
X = 10 >>> str(print()) + "One"
X = X + 10 (b)
X=X-5 >>> str(print("hello")) + "One"
print (X) Answer =
X, Y = X- 2, 22 (a)
print (X, Y) 'NoneOne'
answer= (b)
5 hello
13 22 'NoneOne'
Q-5 Rewrite the following code Q-6 Find the output of the following code
fragment that saves on the number segments:
of comparisons: var = 7
if (a == 0) : while var > 0:
print ("Zero") print ('Current variable value: ', var)
if (a == 1) : var = var -1
print("One") if var == 3:
if (a == 2) : break
print ("Two") else:
if (a == 3) : if var == 6:
print ("Three") var = var -1
Answer = continue
if (a == 0) : print ("Good bye!")
print ("Zero") Answer :-
elif (a == 1) : Current variable value: 7
print("One") Current variable value: 5
elif (a == 2) : Good bye!
print ("Two") Current variable value: 4
elif (a == 3) :
print ("Three")
Q-7 How is break statement different Q-8 Find out the error(s) in following code
from continue? fragments:
Answer = a, b, c = 2, 8, 9
Break :- A break statement skips the print (a, b, c)
rest of the loop and jumps over to thec, b, a = a, b, c
statement following the loop. print (a; b; c)
answer=
Continue :- The continue statement a, b, c = 2, 8, 9
skips the rest of the loop statements print (a, b, c)
48
and causes the next iteration of the c, b, a = a, b, c
loop to take place. print (a, b, c)
Q-9 What is the purpose of range() Q-10 Write Pseudo code to calculate area of
function? Give one example. circle.
Answer :-It is used to create a list Answer:-
containing a sequence of integers t = input "Enter Radius of circle "
from the given start value up to stop Area = pi * r * r
value (excluding stop value), with a Display Area
difference of the given step value.
Example :-
for i in range(100) :
It will run from 0 to 99.
Q-11Find the output of the following Q-12 Find the output of the following code
code segments: segments:
a = 110 i = 0; sum = 0
while a > 100: while i < 9:
print(a) if i % 4 == 0:
a -= 2 sum = sum + i
Answer :- i=i+2
110 print (sum)
108 Answer :-
106 0
104 0
102 4
4
12
Q-13 Find the output of the following Q-14 Find the output of the following code
code segments: segments:
country = 'INDIA' for i in range(20,30,2):
for i in country: print(i)
print (i)
Answer :-
Answer :- 20
I 22
N 24
D 26
I 28
A
Q-15 Find the output of the following Q-16 What will be output produced by
code segments: following code? State reason.
for x in range(1,4): a=5-4-3
for y in range(2,5): b = 3 ** 2 ** 3
if x * y > 10: print(a)
break print(b)
print (x * y) Answer =
Answer :- Line 1:
2 a = -2
3 Line 2:
4 b = 3 ** 2 ** 3
4 = 3 ** 8
6 So for:
8 b = 6561
6
49
9
Q-17 Draw flow chart to calculate Q-18 Write algorithm to calculate simple
simple interest. interest.
Answer :-
1. Start
2. Input principal
3. Input rate
4. Input time
5. Simple interest principal * rate * time
6. Print simple interest
7. Stop
50
STRING IN PYTHON
Basics of String:
• Strings are immutable means that the contents of the string cannot be changed
after it is created. At the same memory address, the new value cannot be stored.
Python does not allow the programmer to change a character in a string.
Example:
>>>str='jaipur'
>>>str[0]='J'
TypeError: 'str' object does not support item assignment
As shown in the above ex
ample, str has the value “jaipur”. An attempt to replace ‘j’ in the string by
‟J‟ displays a TypeError.
• Each character has its index or can be accessed using its index.
• String in python has two-way index for each location. (0, 1, 2, ……. In the forward
direction and -1, -2, -3, …….. in the backward direction.)
Example:
0 1 2 3 4 5 6
T E A C H E R
-7 -6 -5 -4 -3 -2 -1
• The index of string in forward direction starts from 0 and in backward direction
starts from -1.
• The size of string is total number of characters present in the string. (If there are
n characters in the string, then last index in forward direction would be n-1 and
last index in backward direction would be –n.)
• String are stored each character in contiguous location.
• The character assignment is not supported in string because strings are
immutable.
Example:
>>>s=”TEACHER”
>>>s[1]
‘E’ # returns index 1 position
>>>s[-4]
‘C’ #returns index -4 position
51
s=”TEACHER” s=”TEACHER”
for ch in s : for i in range(len(s)):
print(ch) print(s[i])
String Operators:
A). String concatenation Operator: Concatenation means to join two values. In
Python, + symbol is used to concatenate the strings.
>>>name="Jay"
>>>msg="Hello "
>>>print(msg+name)
'Hello Jay' #concatenated string
Note: You cannot concate numbers and strings as operands with + operator.
Example:
>>>7+’4’ # unsupported operand type(s) for +: 'int' and 'str'
It is invalid and generates an error.
B). String repetition Operator: It is also known as String replication operator.
Replication can be performed by using * operator between the string. It will repeat the
string n times, where n is the integer providedple:
>>>s="Ha"
>>> s*3
'HaHaHa' #Replication
Note:You cannot have strings as n=both the operands with * operator.
Example:
>>>”Ha” * “Ha” # can't multiply sequence by non-int of type 'str'
It is invalid and generates an error.
C). Membership Operators: In and not in are two membership operators to find the
appearance of a substring inside the string.in – Returns True if a character or a substring
exists in the given string; otherwise, False
not in - Returns True if a character or a substring does not exist in the given string;
otherwise, False
Example: >>> "T" in "TEACHER"
True
>>> "ea" in "TEACHER "
False
>>>"CH" not in "TEACHER "
False
D). Comparison Operators: These operators compare two strings character by
character according to their ASCII value. ASCII Values can be finding out by given
functions.
Characters ASCII (Ordinal) Value
‘0’ to ‘9’ 48 to 57
‘A’ to ‘Z’ 65 to 90
‘a’ to ‘z’ 97 to 122
Function Description
ord(<character>) Returns ordinal value of a
character
chr(<value>) Returns the corresponding
character
52
Example:
>>> 'abc'>'abcD'
False
>>> 'ABC'<'abc'
True
>>> 'abcd'>'aBcD'
True
>>> 'aBcD'<='abCd'
True
>>> ord('b')
98
>>> chr(65)
'A'
Slicing in Strings: Extracting a subpart from a main string is called slicing .It is done
by using a range of indices.
Syntax:
>>>string-name[start:stop:step]
Note: it will return a string from the index start to stop-1.
Example:
>>> s="TEACHER"
0 1 2 3 4 5 6
T E A C H E R
-7 -6 -5 -4 -3 -2 -1
>>> s[2:6:1]
'ACHE'
>>> s[6:1:-1]
'REHCA'
>>> s[0:10:2]
'TAHR'
>>> s[-8:-3:1]
'TEAC
>>> s[ : 6 : 1] # Missing index at start is considered as 0.
'TEACHE'
>>> s[2 : :2] # Missing index at stop is considered as last index.
'AHR'
>>> s[3:6: ] # Missing index at step is considered as 1.
'CHE'
>>> s[ : :-1]
'REHCAET'
>>> s[2: :]+s[ :2 :]
'ACHERTE'
>>> s[1: 5:-1]
‘‘
53
S. Function Description Example
No.
1 len( ) Returns the length of a string >>>print(len(str))
14
2 capitalize( ) Returns the copy of the string with its >>> s1.capitalize()
first character capitalized and the rest 'Hello365'
of the letters are in lowercased.
3 find(sub,start,en Returns the index of the first >>>s2.find("thon",1,7)
d) occurence of a substring in the given 3
string (case-sensitive). If the >>> str.find("ruct",8,13)
substring is not found it returns -1. -1
4 isalnum( ) Returns True if all characters in the >>>s1.isalnum( )
string are alphanumeric (either True
alphabets or numbers). If not, it >>>s2.isalnum( )
returns False. True
>>>s3.isalnum( )
True
>>>s4.isalnum( )
False
>>>s5.isalnum( )
False
5 isalpha( ) Returns True if all characters in the >>>s1.isalpha( )
string arealphabetic. False otherwise. False
>>>s2.isalpha( )
True
>>>s3.isalpha( )
False
>>>s4.isalpha( )
False
>>>s5.isalpha( )
False
6 isdigit( ) Returns True if all the characters in >>>s1.isdigit( )
the string aredigits. False otherwise. False
>>>s2.isdigit( )
False
>>>s3.isdigit( )
True
>>>s4.isdigit( )
False
>>>s5.isdigit( )
False
7 islower( ) Returns True if all the characters in >>> s1.islower()
the string arelowercase. False True
otherwise. >>> s2.islower()
True
>>> s3.islower()
False
>>> s4.islower()
False
>>> s5.islower()
True
54
8 isupper( ) Returns True if all the characters in
>>> s1.isupper()
the string areuppercase. False False
otherwise. >>> s2.isupper()
False
>>> s3.isupper()
False
>>> s4.isupper()
False
>>> s5.isupper()
False
9 isspace( ) Returns True if there are only whitespace
>>> " ".isspace()
characters in the string. False
True
>>> "".isspace()
False
10 lower( ) Converts a string in lowercase >>> "HeLlo".lower()
characters. 'hello'
11 upper( ) Converts a string in uppercase >>> "hello".upper()
characters. 'HELLO'
12 lstrip( ) Returns a string after removing >>> str="data structure"
the leading characters. (Left side). >>> str.lstrip('dat')
if used without any argument, it ' structure'
removes theleading whitespaces. >>> str.lstrip('data')'
structure'
>>> str.lstrip('at')
'data structure'
>>> str.lstrip('adt')
' structure'
>>> str.lstrip('tad')
' structure'
13 rstrip( ) Returns a string after removing the >>> str.rstrip('eur')
trailingcharacters. (Right side). 'data struct'
if used without any argument, it >>> str.rstrip('rut')
removes thetrailing whitespaces. 'data structure'
>>> str.rstrip('tucers')'data
'
14 split( ) Splits the string from the specified >>> str="Data Structure"
separator and returns a list object >>> str.split( )
with string elements. ['Data', 'Structure']
1 Mark Questions
Q.No Question Answer
1. print the string “India” 10 times. >>>”india”*10
2. What is the output of the following code False
>>>‘a’ in “computer”
3. What is the output of the following code ‘cmue’
Strg=”computer”
print(Strg[ 0: 8 : 2]
4. What is the output of the following? “India”
print('INDIA'.capitalize())
5. Which of the following is not valid string (iii) “Hello’
in Python?
55
(i) “Hello” (ii) ‘Hello’
(iii) “Hello’ (iv) None of the above
6. Suppose word = ‘amazing’, the what will ‘giaa’
be word[: : -2]?
2 Mark Questions
Sr. Question Answer
1. If you give the following for str1=”Hello” String is immutable data type.So it
why does python report error str1[2]=’p’ does not support item assignment
2. Identify the output of the following Vidya
Python statements.
x="Vidyalaya"
y="Vidya"
if(y in x):
print(y)
3. Look at the code sequence and select the kvsrojAIPUR
correct output
str="KVS RO Jaipur"
for i in str:
if(i.isupper()==True):
print(i.lower(),end="")
if(i.islower()==True):
print(i.upper(), end="")
4. Find the correct output of the following -1
>>>str="The planet earth looks like a
blue marble from outer space"
>>>print(str.find('marble',50))
5. Find the value stored in ctr at the end of 12
this code snippet:
mystr="Darjeeling Tea has a strong
flavour"
ctr=0
for i in mystr:
if i in 'aeiouAEIOU':
ctr += 1
print(ctr)
3 Mark Questions
Sr. Question Answer
1. Write a Python program to input a line of line=input ("Enter a line of text :")
text and a character from user to print ch=input ("Enter a character to
the frequency of the character in the line. search ")
For example k=line.count(ch)
Line entered is : this is a golden pen print ("Frequency is :",k)
The character to search : e
Then output is : Frequency is 2
2. Write a Python Program to input a string s=input("Enter a word :")
to check whether it is a Palindrome string print ("You entered :", s)
or not. (A Palindrome string is that which length=len(s)
is same from both ends like – NITIN, rev=""
MALAYALAM, PULLUP) for i in range (-1,-length-1,-1):
rev=rev+s[i]
if s==rev:
print ("Yes, palindrome")
56
else:
print ("Not a palindrome")
3. Using string replication techniques print for a in range(1,4):
the following pattern using any loop. print("hello " * a)
Hello
Hello Hello
Hello Hello Hello
4 Mark Questions
Sr. Question Answer
1. Find Output: Jhu
my_string = 'Jhunjhunu' J@H@U@N@J@H@U@N@U@
print(my_string[:3]) Jhunjhunu
for i in range(len(my_string)): Njh
print(my_string[i].upper(),end="@")
print()
print (my_string)
print (my_string[3:6])
2. Consider the following string mySubject: Computer Science
mySubject = "Computer Science" Scienc
What will be the output of the following Cmue cec
string operations : e
print(mySubject[0:len(mySubject)]) Computer ScienceComputer Science
print(mySubject[-7:-1]) eniSrtpo
print(mySubject[::2])
print(mySubject[len(mySubject)-1])
print(2*mySubject)
print(mySubject[::-2])
3. Consider the following string country: a)Great India
country= "Great India" b)t Indi
What will be the output of the following c)GetIda
string operations(Any Four):- d)a
a) print(country[0:len(country)]) e)Great IndiaGreat India
b) print(country[-7:-1]) f)Great India
c) print(country[::2])
d) print(country[len(country)-1])
e) print(2*country)
f) print(country[:3] + country[3:])
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
57