Data Handling IP
Data Handling IP
Data Handling IP
~-lc) r1CllinS
Outline
4.1 Introduction
4.2 Data Types
-t.l Introduction 4.3 Mutable and Immutable Types
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) . ~
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
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)
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.
'
Numbers None Sequenc es J,lapptn<; S
~
Integer Floating Complex String Tuple l.Jst Didlooar y
point
Boolean
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 /
-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
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.
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
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
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.
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.
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
5 > 8 or S < 2 results into False becaus e both express ions 5 > 8 and 5 < 2 are F11/~e.
That is :
NO T E
X y xory
Examples
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
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
XAMP LES
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.
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
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
~ ' - : ,'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~.
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)
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 :
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
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
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. 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
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
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