0% found this document useful (0 votes)
16 views13 pages

Datatypes, Operators

Uploaded by

Sandhya Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views13 pages

Datatypes, Operators

Uploaded by

Sandhya Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

5.

7 DAT A TYPE S
-~ ==-
Ever y valu e b e long s to a spec ific da1 a type in Pyth on .
Data type iden tifie s the type of data valu es a [Link] bl ~
can hold and the oper ation s that can b r, perf onnc J on
that data . Figu re 5.6 enlis ts the d ata rype s avai lable
in Pyth on.

Numbe.:-s

lntege r Floati ng Comp lex


Point t_Dictio
_ _r.aries
____,

Boole an

Figur e 5, 6: Diffe rent data types in Pytho n

5.7. 1 Num ber


Num ber data type stor es num eric al valu es only . lt is
furth er class ified into thre e diffe rent type s: int. > =~o a ~-
and com... olex .
Tabl e 5 .2 Num eric data type s

Type / Class Desc ripti on Exam ples


.:: ;it integ er ::1u:nbers - 12. - 3. 0 . 125. 2
.:!ca t real or floati ng poin r numb e rs -2 .04 , 4 .0. 14.:23
cornp.:;,.ex como.. lex numb ers 3 + 4j , 2 - 2j

Boo lean data type (boc l) is a subt ype of inte ger. It


I
is a uniq ue data type , cons istin g of two cons ta:it s , T ~ue
and Fal se . Boo lean True valu e is non- zero , non -nul l
and non -ern pty. Boo lean Fa ls e is the valu e zero .
Let us now try to execu te few statem ents in intera ctive
mode to deter mine the data type of the variab le using
built- in funct ion type () .
Exa ,nple 5.3
>>> nur:il = 18
>>> t y pe ( num l)
<c2.. ass ' i r;t ' >

>>> ni.;m2 = -12 10


>>> type (num2 )
< c l ass 'i nt ' >

>>> varl = True


>>> type( varl)
< c2.a ss 'bee: ' >

>>> floa tl = -1 921 . 9


>> > type (float l )
<c ~ass ' floa t ' >
>>> flo a~2 = - 9.8*1 0**2
>>> pr::.:1 t(float 2 , type(f loat2 ))
-980 . C0080 000CC 00 1 <clas s 'float ' >

> >> v ar2 = - 3+7 . 2 j


>>> pr~nt (va=2 , ~ ype(v ar2))
( - 3+7 . 2j) <c lass ' c ompl ex'>
Varia bles of simpl e data types like ihtege r:s, float,
boole an, etc., hold single value s. But such(variab les are
not usefu l to hold a long list of inform ation, for exam ple,
name s of the mont hs in a year, name s of stude nts in a
class, name s and numb ers in a phone book or the list of
artefa cts in a muse um. For this, Pytho n provi des data
types like tuples , lists , dictio naries and sets.
5.7.2 Sequ ence
A · Pytho n seque,nce is an order ed collec tion of items ,
where each item is index ed by an intege r. The three
types of seque nce data types availa ble in Pytho n are
String s, Lists and Tuple s. We will learn about each of
thern in detail in later chapt ers. A brief introd uctio n to
these data types is as follow s:
(A) Strin g
String is a gr~up of chara cters. These chara cters may be
alpha bets, digits or specia l chara cters includ ing space s .
String value s are enclo sed either in single quota tion
marks (e.g. , 'Hello1 or in double quotati on marks (e.g ..
"Hello"). The quotes are not a part of the string, th ey are
used to mark the beginni ng and end of the string for the
interpre ter. For example ,
>>> strl = ' Hel lo Friend '
>>> str2 = " 452 "
We cannot perform numeri cal operati ons on
strings, even when the string contain s a numeri c
value, as in str2.
(BJ List
List is a sequenc e of items separat ed by comma s and
the items are enclose d in square bracket s [ ).
Exampl e 5.4
#To create a list
> >> l is t l = [ 5 , 3 . 4 , " ~ e w Del h i " , " 2 oc " , .:; :::
#print the elemen ts of t he list lJst l
>>> print(l istl)
[5 , 3.4, ' New De : h i ' , ' 2 Oc ' , 45 ]
(CJ Tuple __
Tuple is a sequenc e of items separat ed by commas and
items are enclose d in parenth esis ().This is unlike list,
where values are enclose d in bracket s [].Once created ,
we cannot change the tuple.

Exa1npl e 5.S
#create a tuple tuple l
>>> tuplel = {10, 2C, "Apple" , 3 .t,, 'a',
#pri rtt tbe element s of the tuple tuplel
<>> :p _r int ( tu p 1 e l )
{l o, ,20, "Apple" , 3.4, 'a')

~
Set is an unorder ed collectio n of items separate d by c01nn1as
and the items are enclosed in curly brackets ( }. A set is
similar to list, except that it cannot have duplicat e entries .
Once created, element s of a set cannot be changed.
Exarripl e 5. 6
#create a se t
>>> setl = {10,20, 3. 14 ,"New De lhi"}
>>> print(t ype (setl))
<class 'set' >
>>> print (s etl)
{ 1 0 , 2 0 , 3 . 1 4 , "N ew Del h. i " }
#duplic ate e lements ar e n ot i n c l ude d i n s e t
>> > se t2 = {: , 2 , 1 , 3}
> >> prir: t(set 2 )
{1 , 2 , 3 }

5 . 7 ._4 None
None is a speci al data type with a singl e value . It is
u s ed to s ignify the absen ce of value in a situa tion. None
supp orts no speci al opera tions , and it is neith er same
as Fa. i se nor O (zero).
Exa mple 5. 7
>> > myVa r = None
> >> pri~t (type (myV ar))
<clas s 'No~e Type ' >
>>> p.:.-ir. t ( rnyV[Link]-)
:-J o ne

5 .7 .5 Mapp ing
Mapp ing is an unord ered data type in Pytho n. Curre ntly,
there is only one stand ard mapp ing data type in Pytho n
calle d dictio nary.
(A) Dicti onar y _
Dictionary in Pyth on holds data items in key-v alue pairs .
Iterns in a dictio nary are encl 'Jsed in curly brack ets { }.
Dicti onari es perm it faste r acces s to data. Every key is
s epara ted from its value using a colon (:) sign. The key
: value pairs of a dictio nary can be acces sed using the
key. The keys are usual ly string s and their value s can
be any data type. In order to acces s any value in the
dictio nary, we have to speci fy its key in squa re brack ets
I l.
Exam ple 5. 8
fr c rea:e a di ct i o nary
>>> die t: = { ' ?rui t ': ' Apple ',
' :.: 1 ir1a.t e ': ' Co~d ', ' Price ( kg)' : 120}
> >> pr i r.t.(d i ctl )
' '?rui t ': ' Appl e', ' Clima t e' : ' Cold ',
' ?=ice (kg) ': 1 20}
>> > prin t (dict l [' Price (kg)' ])
:.. 20

5 . 7 .6 Mutable and Imm utab le Data Type s


,.,,. ·----
Some tim es we may requi re to chan ge- or u'pda te the
valu es of certa in varia bles used in a progr am. Howe ver,
for certajn data types , Pytho n does not allow us to
change the values once a variable of that type has been
created and assigned. values.
Variables whose values can be changed after they
are created and assigned are called mutal)le. Variables
whose values cannot be changed after they are created
and assigned are called immutable. vVhen an attempt is
made to update the value of an immutable variable, the
old variable is destroyed and a new variable is created
by the same name in memory.
Python data types can be classified into mutable and
immutable as shown in Figure 5.7.
· ·•1,
/ Integers ),
· •.. .(·- -Float"·.. -..,)
. '--- ___,,.
·( Boolean ·,:
Immutable ~ ·· ;=~~ --.: ·---~ , Mutable r·······-··---·· .···- ~······•·....\

;. --·,
.
Data Type . - ..., Complex )
,.,-,....._..____ -·-· ----.,
Strinos i
Data Type
,
· -- _.., l
·- ·••
Sets
... . - ;•·
i
· ·•·• •· -- --·-·./

• '-- b /
, .._.... ....... (-Dictionary
- - - - - -~
I

.. - / --·(_ Tuples--) /

.... ¥·-·· ..- -.. -..... »•-- - . .. ..... ... ~--- /

Figure 5. 7: Classification of data types


5 .·7". 7 Deciding l Ts a g e o f Python Data Types
l t is JJrcferred to use lists when \Ve need a simple iterable
collection of data that may go for frequent modifications.
For example, if we store the names of students of a class
in a list, then it is easy to update the list when -s ome
n.e'\v students join or some leave the course. Tuples are
used \vl1en we do not need any change in the data. For
ex arl1ple, names of months in a year. When we need
t1nic1ue ness of elements and to avoid duplicacy it is
p r eferable to use sets, for example, list of artefacts in a
museum. If our data is being constantly modified or we
need a fast lookup based on a custom key or we need
a logical association between the key : value pair, it is
advised to use dictionaries. A mobile phone book is a
good application of dictionary.

5.8 OPERATORS

An operator is used to perform specific mathematical


or logical operation on values. The values that the
operators work on are called operands. For example,
in the expression 1 0 + nu m, the value 1 0, and the
variable ~1 urn are operands and the + (plus) sign is an
operator. Python s·upports several kinds of operators
whose categorisation is briefly explained in this section.
--
5.8. 1 Ari thm etic Ope [Link]~-
Pyth on sup por ts arit bme tic ope rato rs tha t are use
perf orm the four bas ic arit hme tic ope rati ons as wel
mod ular division, floor divi sion and exp one ntia tion .
d to
l as

Tab le 5.3 Arit hme tic Ope rato rs in Pyth on


Ope rato r Ope ratio n Desc ripti on Exa mpl e (Try in Lab)
+ Addi tion Adds the two num eric valu es on >>> n urnl -· :)
eithe r side of the oper ator >>> num2 = 6 .'

>> > num l + num2


This oper ator can also be used to
11
conc aten ate two strin gs on eithe r
side of the oper ator >>> str l = " Hell :, "
>>> s t r 2 = " Indi a "
>>> strl + str 2
' Hel loin dia '
- Subt racti on Subt racts the oper and on the right >>> num l - 5
from the oper and on the left >>> num2 - 6
>> > num l - num2
- J..
* Mult iplic ation Mult iplie s the two valu es on both >>.> num l = 5
side of the oper ator >>> num2 .•. 6
>>> num l * num2
'
30
Repe ats the item on left of the >>> strl = ' Ind ia '
opera tor- if first oper and ., is a >>> s trl ~, 2
strin g aµd seco nd oper and ~ ~ ' In dial ndia '
integ er valu e
I Divi sion Divid es the oper and on the left >>> numl = 8
by the oper and on the right and >>> num2 = 4
retur ns the quot ient >>> num2 I num l
0.5
% Mod ulus Divi des the oper and on the left >>> num l = 13
by the pper and on the right and >>> n um2 = 5
retu rns the rema inde r >> > numl ·!> num2
3
II Floo r Divi sion Divi des the oper and on the left >>> numl = 13
by the oper and on the right and >>> num2 - 4
retur ns the quot ient by remo ving >>> numl I I nurn2
the decim al part. It is some time s 3
also calle d integ er divis ion. >>> num2 / / num1
0
** Expo nent. Perfo rms expo nent ial (power) >>> num l -· 3
calcu latio n on oper ands . That is, >>> num2 = 4
raise the oper and on the left to the >>> num l +" n.u m2
powe r of the oper and on the tight 81

5.8 .2 Rel atio nal Ope rato rs


.--r- -
Rel atio nal ope rato r com pare s the valu es of the ope ra nds
on its eith er side and dete rrni nes the rela tion ship a1no
ng
t hem. Assume the Python variables numl = 1 o, n u m2
-:- 0, n u r.1 3 = 1 0 , s t r 1 = " Good '' , st r2 =
" ~'\f ter~ocn '' for the following examples :
Table 5 .4 Relational operators in Python
Operator Operation Des cription Exa mple (Try in Lab)
Equals to If the valu es of two operands are >>> numl - - nurn2
equal, then the condition is True, False
otherwise it is False >> s t rl - - st r 2
Fa l se
,_ n um2
Not equal to If valu es of two operands are n ot >>> n um l
equal, then condition is True, Tru e
o therwis e it is Fals e >>> s t r l ' == str 2
T r ue
>>> numl ! = n um3
Fals e
Greater than If the value of the left-side operand >>> num l > num2
is greater than the valu e of tl?,'e right- Tru e
side operand, then conditio n is, True, >>> s 't r 1 >' · s ,t r 2
otherwise it is False ,. Tru e .
< Less than If the value of the left-s ide operand >>> num;l < num3
is less th a n the valu e of the right- Fa lse
s ide operand, then condition is True, >> > st r2 < strl
otherwise it is False Tru e
>= Greater than If the value of the left-side operand is >>> n uml >= num2
or equal to greater than or equ al to the value of Tr u e
the right-side operand , then c onditio n >>> n um2 >= num3
is True, o theTW'ise it is False Fa lse
>>> s trl >= s t r2
Tru e
Less than or If the value of the left operand is less > >> num l <= num2
e qual to than or equal to the value of the right Fals e
operand, then is True otherwise it is >>> nu m2 <= num3
False True
>>> s t r l <=- str2
fa l s e

5 .8.3 Assignment Operators


Assignment operator assigns or changes the value of
the variable on its l eft.
Table 5.5 Assignment operat ors in Python

Operator Description Example (Try in Lab)


Assigns value from right-side operand to left- >>> numl = 2
side operand >>> num2 = num l
>>> m.:m2
2
>>> c o ur. try -- ' India '
>>> [Link]
' I :idia'
It adds the value of right -side oper a nd lo the >·> -, : . i; m l
ldt-sid <" ope rnnd a nd os~igns the n ~sult to th e >> ::- r:um2
ldt -s ide ope rand >>> rn.:.ml -+ = num 2
Note: x + =- y is same as x = x + y >>> rwml
12
>.>> r.t..m2
2
>> > st r l = ' He 1J 0 '
>>> st~ 2 = ' I ndia '
> >> s ~rl ~= s~r 2
>> .> s:.~ 1
'He2.:. c i ndia '

It subtracts the value of right-side operand from >>> nt:ml = 1 0


the left-side operand and assigns the result to >>> m.:m2 -= 2
left-side operand >>> :-:1..ml ·· = nurn2
Note: x -= y is same as x = x - y > >"' : L.:m l
8
It multiplies the value of right-side operand >>> ,. t:ml = 2
with the value of left-side operand and assigns >> > n t:m2 = .:,
the result to left-side operand >>> 7: uml " ·- 3
Note: x *= y is same as x = x * y
>> > :n:ml
E
>>>a = ' India '
>>> a + = -:i
>>> a
' I ~d ~aindia : n dia '
/= It divides the value of left-side operand by the >>> ~t.:rr.l = 6
value of right-side operand and assigns the >>> r. um2 = - . . )
result to left-side operand >>> ~t.:ml / = num 2
Note: x / = y is same as x = x / y >>> numl
2 .0
%= It ,p erforms modulus operation usmg two >>> numl = -;
operands and assigns the result tc left-side >>> m:m2 = 3
operand >>> n t.:ml r,;= n um.2
Note: x %= y is same as x = x % y >>'> r.1,ml
1
/ /= It performs floor division using two operands >>> r: url ..c ,

and assigns the res ult to left-side ope rand >>> :-:~m2 = 3
Note: x / / = y is same as x = x / / y >> > r. [Link] 1 /I = n urn2
>>> r. uml
2
**= It performs exponent ial (power) calculatio n on >>> n uml = 2
operators and assigns value to the left-side >>'> num2 -"- 3
operand >> > m: ml * "= m:rn .::
Note: x **= y is same as x = x O y >>> :: u r. l
8
5 .s.4 -~gic ~ (?perators

There are three logical op~r~tors supported by Python.


These operators (a nd , or, not) are to be written in
lower case only. The logical operator evaluates to either
T rue or False based on the logical operands on either
side . Every value is logically either True or Fa 1 s e. By
default, all values are True except None, Fa lse, 0
(zero), empty collections''" , (),[],{}, and few other special
values. So ifwe say n urnl = 10, num2 = -20, then
both numl and num2 are logically True.
Table 5.6 Logical operators in Python

Operator Operation Description Example (Try in Lab)


Logical AJ\JD If both the operands are >>> Tr ue and True
True, then condition True
becomes True >>> numl = 10
>>> num2 = -20
>>> bool (numl -and num2)
True
>>> Tr~e ·and..... ~alse
False ~

> >> num3 = · ()


>>> bool(nurnl and num 3)
False
> >> Fa lse and False
False

Logical OR If any of the two operands >>> Tn.:e or T rue


are True, then condition True
beco mes True >>> Tn.:e or False
True
>>> bool(numl or num3)
•rrue
>>> Fa l se or False
False

Logical NOT Used to reverse the logical >>> numl = 10


state of its operand >>> boo l (numl )
Tru e
>>> not:. numl
> >> bool (numl )
False

5 .8.5 Identity Operators


Identity operators are used to determine whether the
value of a variable is of a certain type or not. Identity
operators can also be used to d etermine whether two
variables are referring to the same obj ect or not . There
are two identity operators.
Table 5. 7 Identity operators in Python
Operator Description Example (Try in Lab)
1S
Evaluates 'I' r ue if the variables on either >> > [Link] = 5
side of the operator point towards the same >>> type(numl ) 1s int
m emory location and False otherwise . True
varl is v a r 2 results to True if id(varl ) is >>> num2 = numl
equal to id(var2 )
>>> i d(numl )
1433 9 20576
>> > i d(nTn2 }
14 339205 7 6
>>> numl :s num2
Tr u e:
is not Evaluates to Fa l se if th e variables on >>> n uml is not numL
either side of the operator point to the same Fa lse
m emory location and True otherv.-[Link]. va r :.
is not v ar 2 results to True if id(var 1) is not
equal to id(var2 )

5.8.6 Membership Op_erators


Membership operators are used to check if a value is a
member of the given sequence or not.
Table 5.8 Membership operators in Python
Operator Description Example (Try in Lab)
m Returns 'I- r u e if the variable/value is found iI_l the >>> a = [l , 2 , 3 }
specified sequence and Fa l se otherwise >>> 2 in a
True
>>> I 1 I in a
Fa l se
not in Returns ':'r ue if the vari~ble/value is not found in >>> a = [ l , 2 , 3~
the specified sequence and False otherwise >> > l C net in a
True
>>> l n -:.1t in a
False
5.9. l Preced ence of Ope rators
- - - -·- - - -- - -- -.- -J
E\·nlua tion of the expres sion is based on preced ence of
o perato rs. When an expres sion contai ns differe nt kinds
o f operat ors, preced ence d e termin es which operat or
s hould be applied first. Higher precedence operat or is
evalua ted before the lower preced ence operato r. Most
of t h e operat ors studied till now [Link] binary operato rs.
Binary operat ors a re operat ors with two operan ds.
The unary operat ors n eed only one operan d, and they
h ave a higher preced en ce than the binary operato rs.
The minus (-) as well as + (plus) operat ors can act as
both unary and binary operat ors, but not is a unary
logical operat or.
-#Dep·.: ~1 is usi1"1g - (minus) as unary o perat o r
\:2 l t.:e = - Cept:-1
/ not is a u~ar y o p er at o r , nega tes True
p:: 1.r.:-. ( not (T::- ue) \

The followi ng table lists preced ence of all operat ors


from hi~ s f. to lowest.
/ ,,.,....- Table 5. 9 Precede nce of all operato rs in Python
./

V Arder of Operato rs Descrip tion


V Precede nce
·/ Exponen tiation (raise to the power)
J **
2 ~ , +, - Complement, unary p lus and unary minus
3 " , . , ~, I I Multiply , divide, modulo and fl oor division
4 +, - Addition and subtract ion
5 <-= , < , > , >-= , ·- - I ! ·= Relation al and Compari son operator s
:_
6 =, '- = , ,' =, _,
' .' - , -= I +=, Assignm ent operator s
·=
i s'
, ?It + =

:s :10:: Identity operator s


7

8 i r. ' nc:: i n Member ship operator s


9 :-J G '.".

10 anci Logical operator s


l l :_-i =-

Note:
a) Pa r en thesis can be used to override the precede nce of
operato rs . The expressi on "vithin () is evaluate d first.
b) For operato rs with equal precede nce, the expressi on is
evaluate d from left to right.

Examp le 5. 9 How will Python evalua te the followi ng


expres sion?
2(, ., JQ I ~ (1
Solution:
= 20 + ( 30 * 40 ) #Step 1
#precedence of * is more than that of +
= 20 + 1200 #Step 2
= 1220 #Step 3
Example 5. 1O How will Python evaluate the followin!:
expression?
20 - 30 + 40
Solution:
The two operators (-)and(+) have equal precedence.
Thus, the first operator, i.e., subtraction is applied
before the second operator, i.e., addition (left to right).
= (20 - 30} + 40 #Step 1
= -1 0 + 4 0 #Step 2
= 30 #Step 3
Example 5.11 How will Python evaluate the follo\ving
expression?
(20 + 30) ~ 40
Solution:
= (20 + 301 . *•. 4~,. # Step 1
·. _# using parenthesisO, we have forced precedence
of+ to be more than tlia~ of *
= so * 4 o # Step 2
= 2000 # Step 3

Example 5. 12 How will the fallowing expression be


evaluated in Python?
15 . 0 I 4 + (8 + 3 . 0)
Solution:
= 15.0 I 4 + (8.0 + 3.0) #Step 1
= 15.0 I 4.0 + 11.0 #Step 2
= 3.75 + 11.0 #Step 3
= 14.75 #Step 4
5.10 STATEMENT
J = I -

!n Python, a statement is a unit of code that the Python


interpreter can execute.
Example 5.13
>>> X = 4 #assi g nment stateme nt
>>>c ube= x ** 3 t assi0nme n t statement
>>> print (x , c ube ) #p rint s ta teme n t
4 64

You might also like