Data Handling IP

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

4 l) ala

~-lc) r1CllinS

Outline
4.1 Introduction
4.2 Data Types
-t.l Introduction 4.3 Mutable and Immutable Types

ln any l.rngunge, there .ue some fundamental s you 4.4 Operators


1wed to know bl'fore you c.in write C'Vl'n the most 4.5 Expressions
l'!cmL•ntary programs. This d1.1pter introduces some 4.6 Working with math Module of
such fundanwntals : tfnfa types, vnrio/1/cs, operators and Python
cxprcssio11s in Python. 4.7 Debugging
Python provi1.ks a predefined set of data types for
handling the d.:1t.1 it USl !S . DatJ can be stored in any of
these d.ita typL'S. This chapter is going to discuss various
types of datJ that you can store in Python. Of course, a
program also needs a means to identify stored data .
So, this chapter shall al so talk about mutable and
immutable variables in Python.

4.2 Data Types


Data can be of mc1ny ty pes e.g., c/,nmclcr, i11tcger, rcnl,
string etc. Any thing enclosed in quotes represents string
data in Python. Numbers without fractions represent
integer data. Numbers with fraction s represent real data
and True and False n~prcsent Boolean data. Since the
data to be deal t with are of m any types, a programming
language must provide ways and faci lities to handle all
types of data.
Before you learn how you can process different types of
data in Python, let us discuss various data-types
supported in Python. In this discussion of data types,
you'll be able to know Python's capabilities to handle a
specific type of data, such as the memory space it
allocates to hold a certain type of data and the range of
values supported for a data type etc. 79

80 IIJl(_;i'l/\/-. ilr. s PPt,r r1r, ,
I ' I;

I:ythlin ol lcr::, Jollu\\111 )-; huill 111 lllll' d.11.1 IYfW..,


(1,') f llJJ/1• G:•J / )/f /11J// tl/"I /

4 .2 .1 Numbers
As it is cleJr b y the n,1 mc, th e N 11111 /1cr d.11"<1 ty pes a rc W-,t d Lo ::, tore num(' ric:
1
VJ I LH', in l'ython.·11 11 ,
Numbe rs in Py thon h.w c fo ll owing corL' da! J ty pl'S :
(1) lntq!,t'r'> . ¢) lntt•gt'r'> (::,ignl'd) ¢) Bool1 ,111-.
(ii) Flo,1ting l\1int Numbvr -. (111) (. om pit•, Numh(' r..,
H ere, we sha ll talk abou t on ly in tegers .-ind flu;iting point number brie fl y. Coverin
g co mpl l'x
nu mbers here is beyond th e scope of the book.

4. 2 . l A Integers
Integers are w hole numbe rs su ch as 5, 39, 1917, 0 etc.
They h ave n o fract ion al pa rts. Intege rs arc represen ted
in Py thon b y n umeric va lu es w ith no d ecim a l poin t.
Integers ca n be positi ve o r nega ti ve, e.g., + 12, - 15, 3000
ype s of Integers in Pytho n

:• Intege rs (s igned)
:• Boolea ns
j
(missing + or - sy mbol m eans it is p ositi ve numbe r) . ~

There are two typ es of integers in Py th on :


(i) Integers (signed) . It is the n orm al intege r1 represen tati on of w h ole number
s. Integers in
Pytlio11 3. x can be of any length, it is onl y limited by the me mory av ail able. U nlike
other
langua ges, Pytlion 3.x provide s single data ty pe (int) to store any int eger, w he th er
big or small.
It is signed represen tation, i.e., the integers can be positive as well as negative.
(ii) Boolean s. These represen t the truth va lu es False and True . The Boolea n ty
p e is a sub type of
plain integers, and Boolean values False and Tru e b ehave like the v alu es O and 1,
respecti vely.
To get the Boolean equivale nt of Oor 1, you can type bool(O) or bool (1), Py thon will
return False
or True respecti vely. See figure below (left side).
r----- ------ , I I NOTE
iI >» bool(0) l I
1 »> str(Fal se)
I
1
I I I
1
I
False 1 1 'False' 1 The str( ) function converts a
I I I
I I I I
value to string.
I I
I I
I
>» bool(l) 1 1 »> str(Tru e)
I
!I
I I
1L. _True l
_ _ _ _ _ _ _ _ _ _ ..,
l_' True' ______ _ i
NOTE
Howeve r, when you convert Boolean values False and True
to a string, the strings 'False' or 'True' are returned , respec- The two objects representing
tively. The str() function convert s a value to string. See figure the values False and True (not
false or true I are the only
above (right side).
Boolean objects in Python.
4.2.1 B Floating Point Numbers
A number having fraction al part is a floating -point number . For example, 3.141
59 is a
floating -point number . The decimal point signals that it is a floating -point number,
not afl
integer. The number 12 is an integer, but 12.0 is a floating -point number .

In some cases, the exception OverflowError is raised instead if the given number cannot be
1. represented through available
number of bytes.
, Chop 1er 4 .. DATA HAN DLING 83

Jn a string, say name, of length ln, the valid indices are 0, 1, 2, ... ln-1. That means, if you try to
give something like :
» > name[ln] NO T E

Python will return an error like : The index (also called subscript
sometimes) is the numbered
name[ln]
position of a letter in the string.
IndexError: string index out of range In Python, indices begin 0
onwards in the forward
The reason is obvious that in string there is no index equal to direction and -1, -2, ... in the
the length of the string, thus accessing an element like this backward direction.
causes an error.
Also, another thing that you must know is that you cannot change the individual letters (called
item assignment) of a string in place by assignment because strings are immutable and hence
item assignment is not supported, i.e.,
name = 'hello' . d' .d .
- - - ,n 1v1 ua11etter ass1g11ment not
name [ 0] = 'p' .---- allowed in Python

will cause an error like :


name [0] = 'p'
TypeError: 'str' object does not support item assignment
NOTE
However, you can assign to a string another string or an
expression that returns a string using assignment, e.g., following Valid string indices are 0, 1,
2 ... upto Jength-1 in forward
statement is valid :
direction and-1, -2, -3 ...
name = 'hello' Strings can be assigned expressions - length in backward direction.
name = "new" . - - - - that give strings.

4.2.3 Lists and Tuples


The lists and tuples are Python's compound data types. We have taken them together in one
section because they are basically the same types with one difference. Lists can be changed /
modified (i.e., mutable) but tuples cannot be changed or modified (i.e., immutable). Let us talk
about these two Python types one by one .
. 4.2.3A Lists
A List in Python represents a list of comma-separated values of any datatype between square
brackets e.g., following are some lists :
[1, 2, 3, 4, 5]
NO T E
['a', 'e·, 'i', 'o', 'u' ]
['Neha', 102, 79. 5 ] Common sequence types
provided by Python include :
Like any othe~ value, you can assign a list to a variable e.g.,
❖ Strings
» > a= (1, 2, 3, 4, 5] # Statement 1 ❖ Lists
>» a ❖ Tuples
[1, 2, 3, 4, 5] ❖ Dictionaries
»> print (a)
[1, 2, 3, 4, 5]
INFORt/iATICS PRACTICES _ ,,

J", lt.111;;•· fir ·,1 v..Jl1w in .i 11 -.l n,Jni1·ly a (g1Vl'n ..ibove), you m ay w rite
o> d[0] • 10 # c.hange 1st item- cons i der statement 1 given earlier
~ )) J
(10, 2, 3, 4 , 5)

·1", h,111i~• · 3rd ih-m, you rnJy writ<•

>» a(2] " 30 # change 3rd i t ern


»> a
(10, 2,30,4, S)

Yuu 1~u1·w·J it ri~ht ; the v.i lues inll'rnally a rc numbe red from O(zero) onwards i.e., first item of
ti 11: li-.t i':I intt•rn.illy nu m bL•red a~ 0, 1-,ccond item of the lis t as 1, 3rd item a s 2 and so on.
Wt• Jr1• no t ).Soin~ furthcr in lb t di-,cu<;,;,ion here. Lists shall be discussed in details in a later
< hJplt·r.

4.2.38 r•Jpl,..,
You c.:in th ink o f T u p lc!:i (prono unced as tu-pp-le, rhyming with NOTE
coupk ) a,;, tho~ lihts which cannot be changed i.e., are not
mo<l ifi.ible. I upl<-. ,HP n·w e',(.'nt<'d a<, group of comma-sep arated Values of type list are mutable
vr1lw , of any dalt.• lyJJC within pan•nthe'>es, e.g., following are I.e., changeable - one can
change/ add/ delete a list's
•,omc tuples:
elements. But the values of type
p tuple are immutable i.e.,
(1,2,3,4, 5)
non-changable ; one cannot
q• (2, 4, 6, 8) make changes to a tuple.
r ('a', 'e', 'i', 'o', 'u')
h= (7 , 8 ' 9 J 'A' , 'B' , 'C)

4 .2 .4 D1< t1<Jnory
NOTE
. I)1ction.iry data type is another feature in Python's hat. The
dtclwnan; i'> an unordered set of comma-sep arated key : value Python data types strings, lists,
tuples, dictionary etc. are all
p..11r-;, within I I, with the requiremen t that within a dictionary,
lterables.
no two keys can be lhe same (i.e., there are unique keys within a
di ctionary)
ITERABLE
for instance, following are som e dictionarie s :
" An iterable is any Python
{'a' : 1 , 'e' : 2, 'i' : 3, 'o' : 4 , 'u' : S} object that can return its
members, one at a time. Since,
you can access elements of
>>> vowe 1 s = { a . 1 , 'e' ·. 2 ,
I ' • '1'' .• 3 , 'o' ·. 4 , ' u' .· 5} strings, lists, tuples and
dictionary one at a time, these
»> vowels['a'] " I/ere 'a ', 'e', 'i ', 'u' and 'u' are the keys of
are all iterables. '1
dictionary vowels; 1. 2. 3, 4, 5 are 1'Ulues fur
1 the~e keys re~pectively.

>>> vowels ['u'] - - - -


5 Specifying key in~ide I J afier dictionary name gives tlze corresponding
11alue from the key : value pair inside dictionary.

Dictionarie s sh all be covered in d e tails in a later chapter.


(',apter 4 D.\ TA HAN DLING 85

FolJmving figure summa rizes the core data types of Python .


Core Data Types

'
Numbers None Sequenc es J,lapptn<; S

~
Integer Floating Complex String Tuple l.Jst Didlooar y
point

Boolean

4.3 Mutable and Immut able Types


le types, in
171e Python data objects can be broadly categorized into hvo - mutable and immutab
sunple words changeable or modifiable and non-modifiable types.
1. Immutable types
. the following
The imm~table types are those that can never change their value in place. In Python
types are. unmuta ble : integru, jlaating point numbers, Booleans, strings, h1p_le<>.
Let us unders tand the concept of immutable types. In
Immuta ble Types
order to unders tand this, consider the code below :
❖ integer~
Sample code 4.1 ❖ floating point numoer s
❖ boolean s
p=S ❖ strings
q =P ❖ tuples
r=S
# will assign 5, 5, 5 to p, q, r
p = 10
r=7
q=r
p, q, r could be
After reading the above code, you can say that values of integer variables
types can
changed effortlessly. Since p, q, r are integer types, you may think that integer
change values.

But hold : It is not the case. Let's see how.


value-objects i.l'.,
You already know that in Python , variable-names are just the references to
are not storage
data values. The variabl e-name s do not store values themselves i.e., they
containers. Recall section 3.5.1 where we briefly talked about it.
processes these
Now consider the Sample code 4.1 given above. Internally, how Python
page and then
assignments is explain ed in Fig. 4.2. Carefully go throug h figure 4.2 on the next
read the following lines.
chan~ing "in
So although it appear s that the value of variable p / q / r is changi ng; values are not
place'' the fact is that the variabl e-name s are instead made to refer to new
immutable integer
y location.)
object. (Changing in place means modify ing the same value in same memor
88
M uta bl e Types

I Ii, 1111111l•h- I\,., . . , lll' 1111• ,I ' \\ 1111 , . \ . il,11 I 111 ,,.. I li ,11 1i~•·cl


,., •.,,,
1>11 l11 11 1,1r11 ·'>
in pl.,"·, )111\ 1111 1·1 1, 1••· .ir,· 111111 ,il•lt · 111 I \ 1111111 1111 " ,1 ' ,11 1
, , , .... ,. 11111 /

'l"\1 d1.111r.1· ,l ll ll' l1il•1 ·r 111 ,I 1, -.1, ) "" 111 ., y W I iii · :


l h i,. I .>. ,l I t, I
u,q 1 I .w
It will m.1\..1• tlw fo,l 11.1111\·ly ('h k ,is IL •Ill, Ii i.
r 'I
: ' " ( hk. • [ .l, 4, t,J I
I I
I I
" " i d( Chk) ~ 1111. nv1m uftm rl11111ol11u ,1 v,1lu11 111
1~019553& tho ll"lt Chk, 11 1 rufuroru n 1r11m1111y
~• • •
>>>Chk [ 1 ] • 40 < • •-\
lld(lr u!II (111!1 10111111110d 111111111 I h t1I
111111111" thu Ll1111111u h,11 t,,k1111 In place
the llat, ore mutnble
>» i d( Chk) J.:: 1
150195536 lI
Lists ,md Didi1>n,1ril'S sh,111 bl' n>Vl'l'l'd l,l ll'r in !Iris hook.

-4 .3 . 1 Voriabl0 lnlcrria ls
Pylhun is .rn ubjL'cl oricnll'd l.10gu.1gL·. Py thon cnlls eve ry c..-ntily th;:it sto res any v;:ilucs or any
ty pe o f d.11.1 .is ,rn obj (•ct.
An object is nn ent ity that has certain properties and that
~-2 l'Xhibil n certni n ty pe of behavio r, e.g., integer values are
1. What is String data type in Python ? objl'Cls - lhl'y hold whole numbers only and they have
2. What are two interndl sulitypes of infi nite prl'rision (properties); they support all arithmetic
String data in Python ? npl'raliuns (behavior).
3. How are st r type strings different from So all d nla or values arc referred to as object in Python.
Unicode strings ? SimilJ rly, we can say tha t a variable is also ;:in object that
4. What are List and Tuple data types of rdcrs lo a vnluc.
Python ?
Every Python object h ;:is three key attributes associated toit :
5. How is a list type different from tuple
data type of Python ?
(i) The type of on object
6. What are Dictionaries in Python ?
7. Identify the types of data from the The type of an object determines the operations that can be
following set of data prrforml'd on the object. Duilt-in function type( ) returns
'Roshan', u'Roshan', False, the type of an object.
'False' I ['R' I 'o' I 's' I 'h' I 'a' I 'n' I]I
Consider th is :
('R', '0' 1 's' 1 'h', 'a' 1 'n'),
{'R': 1 1 ' o': 21 's': 3 1 'h' : 4'a' »> a = 4 .
.----- Typ,· of inr,·1:,·r m lru• 4 1·1
: 5, 'n': 6}, (2.0 - j) 1 >>>type ( 4) r,•tur,1<•cl int i.t'. ,1111•i:,•r

121 12.0, 0.0, 01 3j 1 6 + 2.3j, <c la ss 'i nt' >


T\'P<'
..
uf '''" "', ,.a ·.,,,,.,,,,/\'
/ ill jr,/ l.f'
I I ,.1 ,, .
True, "True" >> > t ype (a) . , - - - - r11t1·K•'' /,,., '"'·" ' a ,s ,
r,j,·rrin/!, to u,r ,r,r,·~•·r 1•i1/w.1
8. What do you understand by mutable <c lass 'i nt' >
and immutable objects ?
-- ~ •"-6I

l
90 INFORMATICS PRACTICE
S - Xi

OpPrdtor<i

Tlw ,1 1,vr.,lil111, bl·ing c.uriL•d out un c.b t,1, are represented by opera tors. TI1e symbols lha
tri~;!~l·r thL· lll'l'r,, lilrn / ,,ct ion on Lfat~1, ,ue called oper~tors. The operations(specific tasks) ar;
n·1'rL'~l'l11l•d by o,,rr,1/1>rs and the ohiects of the opcra t1on(s) are referred to as Operands.
l\lhl,n·-. 111h . . l'( lit 1ipl·1,11lir.., lllmp1i..,t•.., uf thl'"l' types of OPERATORS
l'l'l't,11111 -. ti) \11lhml'lil llJ'l't,11lH.., (11) Rl'l,1t1on,1l opcrntor'> " 3
The symbols that trigger
(111) ldl·nttl, llJ'l't ,1h11.., (1, •) I ug1L ,ll opet ,,tms (u) Bitwise the operation/ action on dat
lll'l't ,llllt.., (,') ~h ml'l'r-.htp llPl'r,,tnr.., are called Operators, and tha;
Out pf tlwsL', we ..,h,111 t,1 lk ,1bout membershi p operators later dataonwhichope rationisbeing
whc.•n ,w t,111-. aliout lists and dictionaries. (Chapter 6 onwards). carried out, i.e., th e objects of
the operation(s) are referred to
Ll'l us di~cuss tlwse opt•r,1 tors in detai l. as Operands.

4 .4. l Arithmetic Operato rs


To Jo ari thnwti c, Python uses arithmeti c operators. Python provides operators for basic
c..1kul.1tions, as given bt'low :

+ .1ddition multiplication II floor division exponentiation


subtr.1ction I division % remainder

Each of these operators is a binary operator i.e., it requires two values (operands) to calculate a
fin,11 answer. Apart from these binary operators, Python provides two unary arithmetic
operators (that require one operand) also, which are unary+, and
unary - .
UNARY OPERATORS

" The operators that act on


4.4.1 A Una ry Operato rs one operand are referred to as
Unary Operators. "

Unary+ Unary -
The operators unary '+' precedes an The operator unary -precedes an operand. The
operand. The operand (the value on operand of the unary - operator must ha:e
which the operator operates) of the unary arithmetic type and the result is the negation of 115
+ operator must have arithmetic type and operand's value. For example,
the result is the value of the argument. if a = 5 then - a means - 5.
For example, if a = 0 then - a means 0
if a = 5 then + a means 5. (there is no quantity known as - O)
if a = 0 then + a means 0. if a = - 4 then - a means 4.
if a = - 4 then + a means - 4. Th.is operator reverses the sign of the operand's vaJue-

81 NAR Y OPERATORS
4.4 . l B Binary Operators on two
" Operators that act up as
Operators that act upon two operands are referred to as Binary operands are referred to
Operators. The operands of a binary operator are distinguishe d Binary Operators. t' ,
as the left or right operand. Together, the operator and its I

operands constitute an expression.


1
Sometimes these can be words too. e.g .. in Python is and is not are also operators.
3
.,
I

INFORMATICS PRAcnqs
1CO
• , • I c,... ·~~ ' Q.--=- r-•:i:-s
.., _..,_ -i - ~ -~ :-- '- ~ i... , t= n- ' c rt>n tM, th.it 6t.1blish relationships amo
1:.,, • ., .....: ' :1 _: ; ~ . , ~ 2.;..,__1ut n:>1 J , 0 ,u r - - . ng tl-
.\ Jl ear ..- r =-~----'-'• ·- ... · • ..
1
~Jt J r5 th~ Boolecm lm;1.::al ope ra to rs (or and ·
yz.1:Je~< Tris s.e~-!i.on t~~s 2.::,,."'ut 1og ~"- l"Ft' l \.. -·
1 1 _
L... • ' , n~
. . _ L, •· , l · .;; (amonl• \·,=tlues) L,m be LOnnected. P) thon pro .·
L'ia t re:er !o t.1 e ,\·ay:- the:-t:> re~.. uon. ur - 0 . _ d d \1d\
i... · · ('" e, rire,-:wns. These .u e or, an , .in not.
• •tm
ll·r--- '1,-..:--i-al
• • ~t '" o· '--
or.orate-rs
t -•
to .::om ~me e,..1:- c r --
t::' -t· . . ·
-~ ~ to •'-e GL~uS, mn ot o~c
· l · al - l . for 1\ ' Ou
OF•era t L1r'--, it is im rn.1rt.mt to kno,v a~
UC'. ore " e p,°'---"txu l.. - o I '
Truth \"alue Testing. t-{>cau::;e in s0me ca~es IosicJ1 L)l-"erators base t 1eir resu ts o n truth Valt
testing.

4.4 .4A Tru7h Value Tes!ing


P..ihon associates ,\iUi e\·ery Yalue ~}-"'€, so me truth ,·alue (th_e trutlzi11c::-::-), i.e., Python intern,ll:;
c~tec--orizes
0
them as tr ?lt' or . f.1J:5<·. AnY• object can be tested tor trnth value. Python conside~
follo,\·ing Yalues Ja!:-e, (i.t?., " i th truth-Yal ue as J:1!:-e) and tr111: :

Values with truth value as false Values with truth value as t~ l


:'\one
FaLcce (Boolean Yalue False)
zero of any numeric type, for e..xample, 0, 0.0, Oj All other values are
considered tnie.
any empty sequence, for example, ", ( ), [ ]
(please note, " is empty string ; () is empty tuple ; and [ ] is empty list)]
any empty mapping, fo r example, II
The result of a relational expression can be Tme or False depending upon the values of its operands and th~
comparison taking place.

Do not confuse behveen Boolean values Tnte, False and truth values (truthiness values) tr11,·
false. Simply put truth-value tests for zero-ness or emptiness of a value. Boolean values belon5
to just one data type, i.e., Boolean type, ·w hereas we can test truthiness for every value object ~ry
Python. But to avoid any confusion, we shall be giving truth values trne and fa lse in small lettel"1
and with a subscript tval, i.e., now on in this chapter true ..... ~11 and I''alse h •11I will be referring Ill
truth-values of an object.

The utility of Truth Value testing v,1ill be dear to you as we are discussing the functioningol
logical operators.

4 .4.4B The or Operator


The or operator combines two expressions, which make its operands. The or operator works~
these ways :
(i) relational expressions as operands . as opr,randi
(11••) numbers or strings or hsts

(i) Relational expressions as operands ,


tl1e,,.
When or operator has its operands as relational expressions (e.g., p > q, j != k, etc.) then
operator performs as per the following principle:

The or operator evaluates to True 1f either of its (relational) operands evaluates to True;
False 1f both operands evaluate to False.
[)-'i(/', d :,J 1 / • •J. 1,..:_ ·.s 101

That i'> ;
Y. y xory
J-i.tl,* False False
F,il¼' Tme True
True False True
True· True True

f ollowi ng ilre some examp les of this or operat ion :


( 4 :.= 4)or( 5 == 8 ) results into True becaus e first expres sion (-t == -!) is Trnt'.

5 > 8 or S < 2 results into False becaus e both express ions 5 > 8 and 5 < 2 are F11/~e.

(ii) tJumb ers / strings / lists as operon ds 5


or ", 3 or 0, de.) tht>n
When or operat or has its operan ds as numbe rs o r strings or li~ts (e.g., 'a'
the or operat or perfor ms as per the follow ing princip le :

That is :
NO T E
X y xory

fal~ t-..l false t-,.,,1 y In general, True and False


represen t the Boolean values
fa)r,,e t, ., true :n:il y
and true and false represent
true~:,! false ro.,J X truth values.

true ,..., truei,,~, X

Examples

Operation Results into Reason

0 or () O first expression (0) has false r."1' he.nee second expression O is returned .

0 or 8 8 first expression (0) has false 1.,,, hence second expression S is returned.

5 or 0.0 5 first express ion (5) has true~,, hence first expression 5 is returned .

'hl'llo' or " 'hello' first expression ('heUo') has true 1:-,,1, hence first expression 'lreUo' is returned

or 'rt ' a' first express ion(") has Jalse1;.,,,1, hence second expression 'a' is returned.
or • first express ion(") has Jalsen:oi' hence second expression " is returned .
d
'a' or 11·' efr>IJ:
_u_ .:.:.:.l'
_ h_e_n_c_e_f ·
i_ r_s_t_e_x_p_ __
re_s_s_io_n '
'a_ _is_re_t_u_n_,e_._ _ _ __
____ ____ __'a_'_ __:___fi_rs_t_e_x:._p_res_s_io_n~('-a.:..') __
_h_as ,r

flow is the truth value determined ? - refer to section 4.4.4A above.

b dt . ed
t Thi!.._typ- of tu · · but whose truth-ness can e e emun
biy qth-on. or nctionmg applies to any value which is not a relational expression
7
102 INFORMATICS PRACTICE
5 I

The or ope rato r will test the sec ond ope d only if the firs t ope ran d is fa lse, oth
ran e rwi se ignore.
eve n if the sec ond ope ran d is log ical 11;
ly wro ng e.g. ,
20 > 10 or "a" + 1 > 1 NO TE

will giv e you resu lt as The or ope rato r will test tht
True seco nd op~ rand only if the fir;i
wit hou t che ckin g the sec ond ope rand f · "" ope rand 1s false, otherwise
whi ch is syn tact ical ly wro ng - you can
o or 1.e., a + 1> 1, ignore it.
not add an inte ger to a
stri ng.
4.4 .4C The and Op era tor
The and ope rato r com bin es two exp ress
ion s, whi ch ma ke its ope ran ds. The
in the se way s : and ope rato r works
(i) rela tion al exp ress ion s as ope ran
ds
(i1) num ber s or stri ngs or list s as
ope ran ds
li) Relatio nal expressions as ope ran ds
Wh en and ope rato r has its ope ran ds as
rela tion al exp ress ion s (e.g., p > q, j !=
ope rato r per form s as per the foll owi ng k, etc.) the n the and
prin cip le :
The and operator evaluates to True if both
of its (rel atw nal) ope rands eva lua te
False if either or both operands evaluat to True;
e to False.
Tha t is:
X y x and y
Fals e Fals e Fals e
Fals e Tru e Fals e
Tru e Fals e Fals e
Tru e Tru e Tru e
Fol low ing are som e exa mpl es of the
and ope rati on :
(4 == 4) and (5 == 8) results into False beca use first expr essi
on (4 == 4) is True but second expression
(5 == 8) evaluates to False.
Both ope rand s hav e to resu lt into True
5 >8 and 5 < 2 in orde r to hav e the final resu lts as Tr11t
resu lts into False because first expressi
8 > 5 and 2 < 5 on : 5 > 8 eval uate s to False.
resu lts into True because both oper ands
: 8 > 5 and 2 < 5 eval uate to Trne
(ii) Nu mb ers / strings / lists as ope ran
ds6
Wh en and ope rato r has its ope ran ds
as num ber s or stri ngs or 1· t ( , , ,,
the and ope rato r per£orm s as per the . etc.) then
foll owm g prin cip le: 1s s e.g., a or , 3 or 0,
In an expression x and Y, iJ first operand
, (1.e., expression x) has ~alse then return fi·rst
ope ran d x as result, otherwi.se return J' tval, .
y.

·
This type of or func tion ing applies
6. to any value wh'ich is
.
not a relation
·
al expression but who se truth -nes s can be deteruu11ed
by Pyth on.
.....,....,,
.
_______________ :,,..,.,..,.,,,,
___:. : c - -====---- -- --
. .u~a:x.:::,,,__
- ~e

103
':hnprer 4 . D.A,TA HAND LING

l11at is :
X y x and y
false trnl fal sC' h•ul X

fa lse 1;,,/ true 1;,,,1 X

tru e ,,..,, fol se 1;,.,, y


true ,-,.., 1 y

XAMP LES

Opera tion Results into Reason

first e:\prl:'ssion (0) has fin l~c hence first expres sion O is return ed .
0 and 0 0 ... h 111I, '

is return ed .
0 and 8 0 first expres sion (0) has fnl~c ""''' hence first expression O
0.0 is return ed .
5 and 0.0 0.0 fi rst expression (5) has /nil' ,.,.,,, hence second C'xpression
sion " is returned
'hello ' and " first l:'xpression ('hello') has h·ue,.,,,,1, heno.> second expres
" is return ed.
" and ' a' first expression (") has fn lsc ,,,.,,, hence first expression
" is return ed.
'' and " firs t expression (" ) has fn lse,,,nl• hence first expression

first expression ('a') has tru ehonl• hence second expression 'j' is return ed.
' a' and 'j' T
.
How tire truth value is determined ? - refer to section 4.4.4A

IMPORTANT
first opera nd is trne, other wise ignor e
The and opera tor will test the second opera nd only if the
it ; even if the secon d opera nd is logically wron g e.g.,
N OTE
10 > 20 and "a" + 10 < 5
will give you result as The and operator will t est the
False second operand only if the first
g- operand is true, otherwise
ignoring the second opera nd comp letely, even if it is wron ignore it.
you cannot add an integ er to a string in Python.

4.4.4D The not Ope rator


ssion or opera nd 1.e., it is a unar y
The Boolean/logical not opera tor, work s on single expre
the truth value of the expression
operator. The logical not opera tor nega tes or reverses
following it i.e., if the expre ssion is Tnte or true tvat, then
not expressio_,r is False, and \·ice versa.
or a string or a list etc. as resul t, the 'not'
· Unlike 'and' and 'or' opera tors that can retur n numb er
operator retur ns alwa ys a Boolean value True or False.
Consider some exam ples belo w: NOT E
not 5 results into False because 5 is non-z ero (i.e., truern11)
Operator not has a lower priority
not 0 results, into Tme because O is zero (i.e., Jalset:"1I )
than non-Boolean operators. so
not -4 results into False becau se - 4 is non zero thus trueh'tJI" not a = b is interpreted as not
results into False becau se the expre ssion 5 > 2 is True. (a = b), and
not (5 > 2) a == not b is a
syntax error.
not (5 > 9) results into True because the expre ssion 5 > 9 is False.
INFORMATICS PRACTICES_]
108

4.5 Exp ress ions


ATO M
·on in Pyth on is any vali d com bina tion of
An expr css1 operators, " An at om is some thing that
literals and variables. An exp rcs~ion is com pos d f iore has a value . Iden tifiers, litera ls,
e ~ one or n the
.
operat ions, w1' th or1erators, llfcrals-, and variables as st rings, lists, tuples, sets,
dicti onaries etc. are all atoms.
cons titue nts of exp ress ions.
Pyth on puts it in this way : a valid com bina
,,
tion of atom s an d
operators form s a Pyth on ex pres sion . In
sim ples t wor ds, ~n
atom is som ethi ng that has a valu e. EXP RES SION
So all of these are a to m s m
Pyth on : idc11tifier s, litera ls and valu es-i1 " An expression in Python 1s
1-enclosu rcs su ch _ as
quo tes ("), pare ntheses, brackets , etc. i.e., any valid combination of
strin gs, tupl es, lists,
dicti onaries, sl'ls etc. oper ators and atoms An
expression is composed of one
The expr essi ons in Pyth on can be of any
type . arithm~t
ic or more oper otion s
expressions, strin g expressions, relational expr
essions, logical
expressio11s, co111po1111d expressions etc.
¢) The type s of oper ator s and ope rand s used in
an exp ress ion d eter min e the exp ress ion type
¢) An expr essi on can be com pou nd
.
exp ress ion too if it invo lves mul tipl e type
e.g., a+ b > C** d or a* b< c* d is a compound s of operators,
expression as it invo lves arithmetic as well as
rrlational as well as logical oper ator s.
Let us talk abo ut thes e one by one .
1. Arithmetic Expressions. Arithmetic
expr essi ons invo lve num bers (inte gers ,
num bers , complex numbers) and arithmetic floating-point
oper ator s.
2. Relational Expressions. An expr essi on hav
ing liter als and /or vari able s of any vali d
rela tion al oper ator s is a relational expr essi on. type and
For example, thes e are vali d rela tion al expr essi
ons:
x>y , y<= z, Z< > X, Z== q, x<y >z,
X== y<> Z
3. Logical Expressions. An expr essi on hav
ing liter als and /or vari able s of any vali d
logi cal ope rato rs is a logical expr essi on. For type and
example, thes e are vali d logi cal exp ress ions
a or b , b and c, a and not b , not c or not :
b
4. Stri ng exp ress ions . Pyth on also prov ides
two strin g ope rato rs+ and *, whe n com bine
strin g ope rand s and inte gers , form strin g d with
expr essi ons.
¢) Wit h ope rato r +, /1,e concatenation
operator, the ope rand s sho uld be of strin g type
¢) Wit h* ope rato r, the replicatio11 oper
only.
ator, the ope rand s sho uld be one strin g and
one integer.
For inst ance , follo win g are som e lega l strin
g exp ress ions :
"and "+ "the n"
# would resu lt into 'and then ' -
con cate nati on
"and " * 2 # would res ult into 'and and ' - rep
lica tion

EXA MPLE
the Jollo wi11g code ?
EXAMPLE
the following code ?
m
What will be the output produced by :::::-:-:=:-::-- ...-- -- -- -- -- -- --
Wltat will be tlte output produced bY

· t(2* 'No ' +3* ' 1 ' )


pr1n · prin t (11 + 3)
prin t(2 * ('N o'+ 3*' 1 ')) prin t ( 11 + 3
I I I I )

SOL UTION NONO! ! ! SOLUTI ON 14


NO!! !NO !!! 113
C.,.1c'er .J ['-H .\ H-\NOLING 109

4. 5. 1 Eva luatin g Express io ns


differ ent types of expressions :
In _th is s~ction, ~,·e shall be discussing how Pytho n evalu.ites
an thmet1c, rela honal and logical expressions.

4.5. l A Eva luatin g Arith metic Express ions


expression. Let's see how Pytho n
Pytho n has certai n set of rules that help it evalu a te an
evalu ates them.

Evalua ti ng Arithm etic Expressions


nds), Pytho n follows these rules:
To e\·alu ate an arithm etic expre ssion (with opera tor and opera
¢) Deten nines the order of eva luati on in an expre
ssion considering the opera tor prece d ence.
¢) As per the evalu ation order, for each of the sub-ex
pression (gene rally in the form of <value>
<operatorx value > e.g., 13% 3)
• Evaluate each of its opera nds or argum ents.
ii Perfo rms any implicit conversions (e.g.,
promoting int to float or bool to int for arithmetic
the text given after the rules.
on mixed types). For implicit conversion rules of Python, read
a Comp ute its result based on the operator.
on the expression evaluation.
u Replace the subexpression with the computed result and carry
• Repeat tiJI the final result is obtained.
rsion is a conve rsion perfo rmed by
Impli cit type conve rsion (Coercion). An implicit type conve
it conve rsion is applie d gener ally
the comp iler witho ut progr amme r's interv ention . An implic
(mixed mode expre ssion) , so as
when ever differ ing data types are interm ixed in an expression
not to lose inform ation .
nds up to the type of the larges t
In a mixed arithm etic expre ssion , Pytho n conve rts all opera
is like op1 opera tor op2 (e.g.,
opera nd (type prom otion ). In its simpl est form, an expre ssion
the following coercions are
x/y or p ** a). Here, if both argum ents are stand ard nume ric types,
applied :
to comp lex;
¢) Ifeither argum ent is a comp lex numb er, the other is conve rted
¢) Otherwise, if either argum ent is a floating point numb
er, the other is converted to floating point ;

¢) No conve rsion if both opera nds are intege rs.

make it clear.
To understand this, consider the following example, which will
will be the final result
EXAMPLE Consider the following code containing mixed arithmetic expression. Wlial

alld the final data type ?


ch = 5 # integ er
i =2 # integ er
fl = 4 # integ er
db= 5.0 # float ing point number
fd = 36.0 # float ing point number
A= (ch+ i) / db # expre ssion 1
i

B = fd /db • ch /2 # expre ssion 2


print (A)
print (B)
- - -- -- ----•=·-=-=-- --======-- -- -- --
113

5 < 10 here, which is True . In or


:~ ,-~ '-' \ .:: ,•.l~:'-' n. fi ~ ~ly ~ihL) n k~ t:- tht' fi r'3t ,1rgu mt•nt, i.e.,
11 d~~•:- n'-'lt t'\' ,1Ju,1 te the St'cond argum ent if lhe first argum ent
is True and
t"\ .i: ~:.;~ :,::,, l\t.. '-':l _
, t . tl . .
:--,:::..r._, L~t.' rv:-~il ~ l)t t·r:-t• · • -:-um'- n ,1:- 1e rt•sult of ove r.:ill expres swn.
1r,~

~ ' - : ,'r :...~'-' ,;:, l ' ~ e , r~\:':-~ iL)n, th L' ~t.'L"\mJ ,1rgumen t expres
sion (50 < 100/0) is NOT EVAL UATE D
ed True, the result of first
..\ T .-\ l... L Tiut 1-=- why, I\thL' n rt> ported no error, and simply return
. 1:-:=:.:~~c·:1~.

TYP E CAS T ING


\ r.,n e lt.> ,1mt in an t.' ,1rlier sectio n th.it in expres sion with
\.)J

The explicit conversion of an


r.~!'\ni t:~'s. ~ ·th'---.n intt> m.1. lly changt•s tht> data type of some "
operand to a specific type is
'-'~'r,1:1Js ~l th.1t all o per,.m'-is h,n·t> the sa me data ty pe. This called type casting.
ty-~ '-"'i C\.1flH' rsion is a u tL--.m..:i tic, i.e., impl iLi t and hence known
as irr:2 licit ty°F"' conn' rs ion. Pytho n, howev er, also suppo rts
t''\.f:iG f t;~ C()n\"t'l"5 iL'ln.

Explic it Type Conversion


=--= - ~~ An e,plic it type conve rsion is user-d efined conve rsion that
~ 4.7 torces an expres sion to be of specif ic type. The explic it type
conve rsion is also know n as Type Casting.
I. !,_-e t::e ~0'.'..Jwmg expressions equal ?
i\:_.- -,;':y not ? Type casting in Pytho n is perfor med by <type >() functi on of
x or y and not z appro priate data type, in the follow ing mann er :
(x or y) a nd (not z) ) <datat ype> (expr ession )
, .,, or (y and (not z ) ) )
2. S:a:e w::e.:1 wo.:!d only fast argument
where <datat ype> is the data type to which you want to
!le en' ..:.ated and when both first and type-c ast your expres sion.
sec:;rd ar:;:iner.ts are e'-'aluated m For t?.rample, if ·we have (a = 3 and b = 5.0), then
fa:~or...""g expressions if a =5, b = 10,
c- 5 ==~ int(b )
(1j 1:; > C a.,d C > d
·will cast the data-t ype of the expre ssion as int.
(lz)., = b or C<= d
Simila rly,
,. 'c~c <=a and not (c<a)
11v) !J < ti and d<a d = float (a)
l What is Type casting ?
will assign value 3.0 to d becau se float(a) cast the
4. Ho'if is i.i:plicit type conversion different
expre ssion' s value to float type and then assign ed it to d.
from explicit type conversion ?
5 Wme conversion function you would
:!Se for fol:owmg type of conversions. NOT E
(:l Boolean to string
·, integer to float In Implicit type conversion, the datatypes of all operands are
(m'I float to integer promot ed to the largest datatype automatically, whereas in
explicit type conversion, the datatype of an expression is
stnng to mteger
explicitly forced th rough a datatype conversion fun ction.
v rtring to float
"' stnng to Boolean
mtege1 to complex
0, ,Ji.J'<"' 4 · DAT ..\ HANDLING 115
(i •iii) · c;it' <
' dog' (ix) 'Cat' < 'dog'
(x) 5 > 2 .ind lO > 11 (xi) 5 > 2 or 10 > 11
;"
t SOLUTION
Expressions (i), (ii), (iv), (vi), (v iii) to (xi) will yield a Boolean result.

EXAMPLE I Writ I.' Boolean expressions in Python for these conditions:


(i) x is a foctor of y (that is, x divides evenly into y)
(ii) nge is at least 18 and stn te equals 'Goa'
(ii,) the string name is not 'Nim ra'

SOLUTION
(i) X % y= 0
(ii) age >= 18 and sta te = ' Goa'
(iii) name != ' Nimra'

EXAMPLE EU Vvlzich of the following code fragments may result into data loss ?
(a) a= 17 (c) e = 29/5
b = float(a) f = float(e)

(b) C = 27. 97832 (d) g = 29/5


d=int(c) h = int(g)
SOLUTION
Code fragments (b) and (d) may result into data loss as conversion from float data type (c and g
are float values) is taking place into int datatype (d and hare int values).

4.6 Working with math Module of Python

Other than the built-in functions, Python makes available many more functions through
modules in its standard library. Python's standard library is a collection of many modules for
different functionalities, e.g., module time offers time related functions ; module string offers
functions for string manipulation and so on.
Python's standard library provides a module namely math for math related functions that work
with all number types except for complex numbers.
In order to work with functions of math module, you need to first import it to your program by
giving statement as follows as the top line of your Python script :

import math

Then you can use math library's fun ctions as math.<function-name>. Conventionally (not a
syntactical requ · t) • . d
zremen , you s1wuld give import statements at the top of the program co e.
Following table (T bl
a e 4.6) lists some useful math functions that you can use in your
programs.
--- ---- ---- ------:- - ~-~----
Cf-apter 4 : DATA HJ\NDLING 117
th
The ma module of Python also makes a\'ailable two useful constants namely pi and e, ·which
you can use as :

math.pi gives the mathematical constant n = 3.1-11592 .. ., to available precision.


math.e gives the mathematical constant e = 2.718281 ... , to available precision.

Follo,,·in g are example s of Yalid arithmeti c expressio ns (after import math statemen t) :

Given : n= 3, b= 4, c =5, p=7.0, q=9.3, r =l0.51, x =25.519, y=l0-24. 113, .:=231 .05

(i) math.po w(a / ii, 3.5) (ii) math.sin (p / q) + m ath.cos(a - c)


(iii) x I y + math.flo or(p * a / b) (hi) (math.sq rt (b) * a) - c (v) (rna th.ceil (p) +a)* c

Followin g are example s of invalid arithmeti c expressio ns :


(i) x + * r two operators in continuation.
(iz) q(a+b -::: / 4 ) operator missing between q and a.
(iii) math.pow(O, -1) Domain error because if base = O then exp should not be <= 0.
(iv) math.log (-3) + p I q Domain error because Joo-arithm
0
of a neo-ative
0
number is not possible.

EXAMPLE \\"rift• tht' co~re:;.pond111g P11tho11 e.1.presszo11s for the following mathematical expressions ·

'"') p + q- -
(Ill
(r+s)4
li'
0

(COS.l tanx)- x
SOLUTION
(1) math sqrt (.i * a + b * b + c* c) (ii) 2- y* ma th.exp(2• y) + 4* y
(iiz) p - q, math.pov.'((r + s), -!) (h,) (math.co s (x) I math.tan (x)) + x

(v) math.fabs (math.ex p(2) -x)

EXAMPLE The radius of a sphere is 7.5 metres. Write Python script to calculate ifs area and volume. (Area of
3
a sphere = rrr1 Volume of a sphere = -1;cr )
SOLUTION
import math
r = 7 .5
area= math.pi * r * r
volume= 4 *math.p i• math.pow (r, 3}
print("R adius of the sphere: ", r, "metres" )
print (nAreao fthesph ere: ", area, "units square")
print( "Volume of the sphere : ", volume, "uni ts cube")

Output :
Rd.1
a us of the sphere 7.5 metres
Area of the sphere : 176.71458676442586 units square
Volume of the sphere 5301.437602932776 units cube
- ---- --
118
(' l Ill I l , \ , I N l"
-l .7 m ug_gmg
J'IC'I l'~' ,,f l,h 1t111s tht• plac 11 ()I
l'IIL' , ., u~1• of error
\ <" I, 11f1~ ! '1 1' \ , Hi 1

Python.
·
Before we • I t ' ( Illllljll
tal k ,lbL)ll t d.:-bussms · L':--, I·1 1,
· . 11 11 1,,,,·t.mt t )r \" L)ll tL , \...t1.in- tlw l'ITor-;, l' IT, ir
l . .
" I 1
·· t t 11 l
types, what c-.1u:-t'S t11t'm d e. ::'IL\ d u :-- 1rs -' "•' ' ' L L ·
1 1 1t •rr ,r-.. 1t1d L
''\ L'L
'nl1Lll l" .
r

4.7.1 Erro•s 1 11 c P,~ ~


An errnr, ~l1nwt1nw, l,1lkd '.1 bu\.'.. i-.. .1 m th111~ 111 tlH' l L1dt'l1 1,1t pn·\ L'lll-.. " prng r.1m frum
compiling and rnnntn\.'.. LL11TLYlh.
There ilfl' bruadh //rrt't' I\ w,; Pl L'ITL)J,: l - tl/1/ 11/1' /1111, · ,·11 111, 11//1 / 1111,· t'//(l/s .ind /11_'\lltlf di'fll ~.

4. 7. l A Compde-T me_ErrmJ
Errors that occur durin, Cl1mpilL•-tmw, ,Hl' rompik-tmw l'rrL' l)· \,Yhcn cl prugr,1m compiks, its
source code is checked for whether it follow s the prngr.1mming bng u,1gL' S ruk·s nr nL)t. 1

Two types o errors fall into tlw calL'gory ol compik-tinw L'rrors.


l. S ntox Errors

Syntax errors occur when the rul es..oLa programming langu.ugc SYNTAX

are misused r.e., when a grammatirnl rule of P;11Jon j<; , ·iol.11L'd . " Syntax re fers to form al rules
For example, observe the following two statements : governing the con structi on of
valid statements in a language
X <- Y * Z
if X = (X * Y)
,,
Toes; ~':'o statem~nts will result in syntax errors as '<-' is not an assignment operator in Python
and .= 1s the assignment operator, not a relational ope-rator Al
. so, 1· f 1·s a bl oc k statemen,t 1·1
requires a colon (:) at the end of it, which is missing abov1:.•.
Therefore, the correct statements will be as follow s :
X=Y*Z
if X == (X * Y) :
NOTE
One should always try to get the syntax right the first ti· "
me, as a
syntax error wastes computing time and money, as well as Pyth on's indentation errors
programmer' s time and it is preventable. (wrong Indenta tion) are syntax
errors.
2 . Semantics_& .rors
Semantics Errors occur when statements ..nc n.oLme.m.in f F . ,s·ta
. ,. . I
plays Guitar 1s syntachcally and semantically correct as it~ hu · ·or instance. ' the statement nt
1

. , . . as some meaning but the stateme


' Guitar plays Sita 1s syntachcally correct (as the grammar is
correct) but semantically incorrect . Similarly, there are SEMANTI CS
sem an tics rules of a programming language, violation of which " Semantics refers to the ~et
results in semantical errors. of rul es whi ch give the meaning
of a sta t emen t . tf
Chapter 4 . DATA HANDLING 119

will result in a semantica l error as an expression cannot be on the left side of an assignment
statement.
4 .7.1 B Log,cal Errors
Sometimt''>, even if yo u don't encounter any ('rror during compile-time and run-time, your
progra_m does not provide th e correct result. This is because of the programmer's mistaken
~nalysis of ~he problem they are trying to solve. Such errors are logical errors. For instance, an
incorrectly implemented algorithm, or use of a variable before its ini tialization, or unmarked
end fo r a loop, or wrong parameters passed are often the hardes t to prevent and to locate. These
must be handled carefully. Sometimes logical errors are treated as a subcategory of run-time
errors.
4. 7. 1C Run-Time Errors
Errors that oc.eur during the execution of a program are run-time errors. These are harder to
detect errors. Some run-time errors stop the execution of the program which is then called
program "crashed " or " abnormally terminated".
Most run-time errors are easy to identi fy because program halts when it encounters them e.g.,
an infinite loop or wrong value (of different data type other than required ) is input.
Normally, programming languages incorporate checks for run-time errors, so does Python.
However, Python usually takes care of such errors by terminating the program, but a program
that crashes whenever it detects an error condition is not desirable.
Exceptions
Errors and exceptions are similar but different terms. While error represents, any bug in the
code that disrupts running of the program or causes improper output, an Exception refers to any
irregular situation occurring during execution/run-time, which you have no control on.
Errors in a program can be fixed by making corrections in the code, fi xing exceptions is not that
simple.
Let us try to understand the difference between an error and exception with the help of real life
example. For instance, if you operate an A TM then
¢) entering wrong account'number or wrong pin number is an ERROR.
¢) 'not that much amount in account' is an EXCEPTION.
¢) 'A TM machine struck' is also an EXCEPTION.

So you can think of Exceptions in a program as a situation that occurs during runtime and you
have no control on it e.g., you write a code that opens a data file and displays its contents on
screen. This program's code is syntactically correct and
NOTE
logically correct too. But when you run this program, the
file that you are opening, does not exist on disk - this
While Error is a bug in the code that
will cause an EXCEPTION. So the program has no errors causes irregular output or stops a
but an exception occurred. Some common exceptions program from executing, an Exception
that may occur during a Python program's execution are is an irregular unexpected situation
being listed in the table below. occurring during execution on which
programmer has no control.
124 INFORMATICS PRA.CTICES
X;

n a F ttt
1. \\'l,q f ,1n· ~~·1 ~ 'C~ -, \\'l,11 ,rep , H1l1n ' ... i,,,,i, 11 1 re ◄
1 (t' ' j, 't"'t '' ?
sou., T O"l Toe real life dat a is of
man y typ es. So to rt'p rese nt v,1ri~m
pro gra mm ing lang uag es pro Yid e way s typ es of rt'.11-lifo d.ita,
s and facilities to han dll' thes e, \-Vh1ch are
kno wn as data typt>s.
Pyt hon ' s buil t-in cor e dat a typ es belo
ng to :
:r Num ber s (int ege r, floa ting -po int,
com plex numbC'rs, Boolc.:ms)
== Stri ng ..: List
Tup le Dic tion an
2. Which data types of Pytlio11 l1n11dlc Num
bers ?
SOL UTIO N .
Pyt hon pro vid es foll owi ng data type
s to han dle num bers
(z) Inte ger s (ii) Boo lean (iii) Flo atin g-p oin t num ber s
(iv) Com plex num ber s
3. W11y is Boolea11 c011sidercd a subtype
of integers ?
SOL UTIO N . Boo lean valu es
True and False inte rnal ly ma p to inte ger
con side red equ al to 1 and False equ al s 1 and 0. Tha t is, inte rnal ly True is
to O (zero). Wh en 1 and O are con ver
boo l() func tion , they retu rn True and ted to Boo lean through
False. Tha t is w hy Boolean s are trea ted
as a sub typ e of integers.
4. Identify tlze data types of t11e valu
es given below :
3, 3j, 13.0, '13' , "13", 2 +Oj , 13, [3,
13, 2], (3, 13, 2)
SO LUT ION .

3 integer
3j com plex num ber
13.0 Floating-point num ber
'13' strin g
"13 " String
2+0 ; com plex num ber
13 integer
(3, 13, 2) List
(3, 13, 2) Tuple
5. What do you understand by term 'immutab
le' ?
SOL UTIO N . lmm uta~ le mea
ns unc han gea ble. In Pyt hon , imm utab
can not b~ ch~ ged m plac~. Wh ene ver le typ es are tho se who se values
one assi gns a new valu e to a var iabl e
typ e, van able s reference 1s cha nge d refe rrin g to immutable
and the pre vio us valu e is left unc han
X = 3 ged . e.g.,
X = 5

x~ :} valu e 3 is untouched and x is mad


to refer to new value.
e
6. What will be the output of t11e following
?
pri nt (le n(s tr(1 7// 4)) )
pri nt (le n(s tr(1 7/4 )))
SOL UTIO N . 1
3
bec aus e
and
len (str (17 //4) )
= len (str (4) ) len (str (l7 /4) )
= len( '4') = len (str (4. 0))
= len ('4. 0')
= 1
= 3

You might also like