You are on page 1of 42
31 Data Handling sy oo 34. roducton 32 Data Types 33. Mutable and immutable Types 34 Operas 35 Expressions INTRODUCTION Inany language, there are some Fundamentals ost elementary programs. This chapter int lperators and expressions in Python. sined set of datatypes you need to know before you can write even the oduces some such fundamentals: data tyre, cnriables, Python provides a prede' for handling the data it uses. Data can be stored Fython provides Piypes. This chapter is going to deus various types of daa that You an src Python OF couse, a program also needs a means 10 Geni stored data, his chapter sball lo talk bout mutable ad inmtable vans Python, ‘ye have shown screenshots of Python shell used in i take commands, But in text section, we ing that ths command is So, IMPORTANT : In this chapter and onwards, Spyder IDE (IPython shell) which wses Int]: Prom have given commands with >>> Prompt ‘which is a standard way of teli ven on a Python shell prompt he same way, though [Python shellisan enhance sel. used Al Python shells execute the code in Fae vestes (eg Teron usiversiy) Yow are es 9 Python IDE/shell of your ho vsing Anaconda distribution which installs mann Jong with Python, As Spyder IDE and choice, but we have installed Pyt vais (uch as NumPy, Sy, Pandaand many wa) bution and is very easy 1 use, we Rave Python sels avaiable a5 prt of Anaconda PEO ist IDE and [Python shell inthis book at times. . siven screenshots of Spyder Ga a. 68 3.2 DATA TYPES ‘Anything, eschosed in Data. can be of many types, wharacter, integer ul sty represents string data in Python, Numbers without fractions represent integer data sinc the dal must provide ways and facilities to handle all types of data 7 data in Python, let us discuss various datatypes supported intython inthis cso of datatypes yn abe 2.1 to know Python's capabilities to handle a specific ype ot Pe data, such as the memory space it allocates to hold a Dtunary certain type of data and the range of values supported for a data type ete Python offers following, built-in core data types = (i) Number () Dictionary, iy String (i) List i) Tale 3.2.1 Numbers {As itis clear by the name the Number data types are used to store numeric values in Python, ‘The Numbers in Python have following cone data types (Integers ‘© Integers (signed) © Booleans (ii) Floating-Point Numbers (Gi). Complex Numbers 3.2.1A Integers Integers are whole nur ‘They have no fractional parts, Integers a toes tint in Python by numeric values with no decimal point ntegers (signed) Tntegors can be postive or negative cg, +12,~15,3000— * Boolean (missing » or- symbol means it s postive number. “There are ta types of integers in Python integer represen imbers such as 5, 39, 1917, 0 etc. orypagiof = ne represented yn of whole numbers, Int a i note z= (142.563) + (4 3.564) (3-43) >>> 2.real = 3.0 spb zeimag Hil tit may tam ae The range of numbers represented through Python's numeric data ype sven blow Toe 3:1 The Range of Python Numbers ” | ea ey ss a tu vais Tee (1), False (0) V0 Plating point | an untimited range, subject to available mts | ietuaty'menny ses wedi, meshine 1, hat aze floating. point numbers? architecture ‘hen are they preferred over integers? ‘Same a ating post aumbers because thera | aa ees ae nd imaginary ports ave represented floats. | would Python representa. complex fmber with real part as 3 and 9-2-2 Strings Insgingy pat ar = 25? You already know about strings (as data) in Python. ln this 2. iat wl be the output of following section, we shall be talking about Python's datatype string, =! ‘Astring data type lets you hold string data, e any number a) ‘of valid characters into a set of quotation marks. aps (141.53) InPython 3.x each character stored ina string! print (p) Azcacter, OF in other words, all strings in Python 3x are print (@) Stguenees of pure Unicode charaaers, Unica s 9 system 4. iat abe oe output of follwing designed to represent every character from every anBuBs ony ‘A string can hold any type 792,543.95 OF known characters. i prin (r.real) Tat mates op yon) sme print (r-4mag) {te en of any known ym Ce Why dor Python ses symbol f to scripted language "ent iy pr os compet Fling ate Siring othcoenal!?—tigs Python —- ee abed” , "1234", 'S%% 2 ten ‘a meen min oan no septs cartes nat wih vrei bts cc seg pe enh Comper umes isa Unicode all legal cr, Baba, 7 os 72 COMPUTER SCIENCE WTH PYTHON Sing 5 a Sequence of Characters (Litho string isa sequence of characters and each character canbe individually acs Using its index, Let us understand this Leta fst study the intemal structure or composition of Python tring sit wil form the kay sate leering of various string manipulation concepts. Stings in Python are sora individual characters in contiguous location, with two-way index foreach location Zits individual elements ofa string are the characters contained in it (stored in contigunyy sre locations) and as mentioned the characters of a string are given two-way inder fy each location, ‘et us understand this with the help ofan illustration as given in Fig. 3.1 cc ee om DOO 8543-2 ot Bact Flgue 3.1. Soucte of Ayton Stig From Fig. 3.1 you can infer that {® Strings in Python are stored by storing each character separately in contiguous locatins '& The characters of the strings are given two-way indices 0,1, 2. in the foranard direction and 2.3, sn inthe backward direction, ‘Thus you can access any character as (cindes] e.g, to access the fist character of “tring mame shown in Fig. 3.1, youll write namef0], because the index of ist charsees nt vag ‘may also writename|-6] or the above example, when sting name sstoving "PYTHON Let us consider another string say subject = Computers’. willbe stored se a aa wojer [Clo] m eLe[s = -) 02 ot Thus, subjettO) °C sseet) Waseca! Sibject (-a]~'# —ngect-7jow Set Since length of sting variable canbe determined using function letctringp), we cans th © fitst character ofthe string is at index 0 oF Lng ‘© second character of the string i a index 1 ort 1) ‘© second last character of the string is af index (en «© last character ofthe string is at index (length -1) or -1 oye DATA HARDAIG 7 Iva sting, ay name, of sive someting he "At I the valid indices ane, 1, 2, bn-l. That mean, i you try to Python will turn an error lke The index (ao aed subset ceback (woot recent call Last) somata) 6 the numbered Hite "oyshell¥40>", Line 4, tn exodte postion of erin the stig raeel tn] a In Prthon, ces been war inthe forward Indestrror: stedng index out of range Girecin an 1-2. ne chars recon The ream iv obvious tha in string there sno index equal io Ui length of the string, thus accessing an element like this Also, another thing that you must know is that you cannot change the individual letters of a ‘ring in place by assignment because strings are immutable and hence item assignment is not supported, i, ane hell rane(@) ='p) « tel Pi will cause an error like back (nost recent call last) el1f3)", line, in rane(@) “TypeError: ‘str! object does not support Stem assigment However, you ean assign to srng another sting oan [TSE TENEEN ‘expression that etums a string using assignment. Owing Vad ng dees ae 0.1 Statements valid rae «helt Sing Be asi sin ane ="new" <— ‘re 3.2.3 Lists and Tuples “Thelin and tuples are Pythons compound datatypes: Weave an then together in one section because they are basically the same types with one difference. Lists canbe changed / trodified (-, mutable) but tuples cannot be changed or modified (i, immutable), Let us talk about these two Python types one by one 323A, Lists ‘ist in Python represents ais of comma-separated values of any datatype between square brackets e., following, are some ists (3,2,3,4,5) tae,'s,8, 0) (wena, 102, 79-5] cove Mm coher value, you can assign a lst a variable 8 Dovan[a,2, 3,4, 5) #statenent 2 (1, 2, 3,4, 5) >>> print (a) 1, 2, 3, 4, 5) ite may write To change first value in a list namely a (given above), you May W renent 1 above >>> a (0) =10 ‘change 1st Aten ~ consider statement 1 a (20, 2, 3, 4, 5), To change 3rd item, you may write >>>al2] = 30 # change 3rd item 20, 2, 30, 4, 5] You guessed it right; the values internally are numbered from 0 (zero) onwards fe irstitem of the lst is internally numbered as 0, second item ofthe list as 1, 3rd item as 2 and so on. ‘Weare not gong further in list discussion here. List shal be discussedin detail ina later chapter. 3.2.38 Tuples You san think of Types (pronauna as tu-p-; shyming with coupe) FOP 2s those lists which cannot be changed fe, are not modifiable Tuples are represented as ist of comma-separated values of any Vales of type Ist ae mutable date type within parentheses, ¢.¢,, following are some tuples Jie, changeable ~ one can =(4,2,3,4,5) change /adé/ delete 3. at's P=(4,2,3,4, elements. Bu the voles of type a= (2, 4,6, 8) tuple are immutebie ie, ra (3, '¢, "0,3, U) non-changable one canot n= (7,8, 9,88, 0) Ime changes to 2 tuple Tuples shall be discussed in details in a later chapter. 3.2.4 Dictionary two keys can be the same (le, there are unique keys within a dictionary), For wnetsice, Cara, %:2,23, 024s) vor vowels = a :1,'8 2:3, 24: 5} a N >>> vowels} ~ Hae £0 a W ate bo of toast ; 1.2.5.4 3 ae alan fr ih peti doo vowels('!] + stu] — Speci ey ine {1 fer tionary mame hs the 5 ‘umd ale fo heya Dictionaries shall be covered in details in a ater chapter for 3 OATA HANDLING 75 Following figure summarizes the core data types of Python ore Data Types Sequaroet Maopos tneger Foaling Conon a) Sing Tasty MUTABLE AND IMMUTABLE TYPES “The Python data objects can be broadly categorized into tu ~ mutable and inomutabe types i simple words changeable or modifiable and non-modifiable types. 1. Immutoble types ‘The immutable types are those that can never change ther value in place. In Python, the following, types are immutable: integers ating point number, Boles sings es. Lot us understand the concept of immutable types. In onder to understand this, consider the code below * integers 4 floating point numbers Sample code 3-4 + booleans a strings ae + tuples pes dd give 5, 5,5 p=10 re? an xy that values of integer variables p,q, 7 could be 1 reading the above code, you 2 82 Seatatetae 7 eypes you may tink hatinteger ypescan change changed effortlessly. Since p, 4, rareinteger| values. But hold : It is not the case. Let's see how. +o: earable-aes re just the eres © values Yas aed kaw hat Nes a mae a mk eae aren os theca ane t ae eee re are peed pret a rr explind Fig 32 Carl Boneh FS S.2n the next page and then “ects t Be eae vale of var rs hanging wae 0°11 in Prec. (Changing in pace means mel? the same value in same memory location) COMPUTER SCIENCE YH Pron in place. nly three types are mutable in Python, These a list, dictionaries and ses Dicom To change a member of alist, you may write 3 Sets k= (2,4, 6] chkta} 48 ‘wil make the lst namely Chk as [2, 4,6) 661 ‘So, sonar angg a abe SS) ig, Seca 1 (2: els] = 42 < neem ager tan ple In (63): ic(cnky fs" Mutable objects ae |e Cee}: cme = v8 [68], 158198536 ea): ——) is, ction ot Imai oj Int flo, complek sting. ple Lists and Dictionaries shall be covered later in this book. 3.3.1 Variable lnemals Python is an obj orente language. Python calls every entity Uut stores any vals a ny ‘ype of data as an objet An objets an enity that has certain properties and that exhibit a cerain ype of behavior cg. inger SETAC values ae objec = they old whole mumbersoniyand ape they have infinite precision (properties they support aalve all arithmetic operations (behav. anid So ll data or values are referred to as objet in Python. | Similarly, we can say thata variables also an object thet refers toa value, Every Python object haste key attributes associated to it {The ype of en objet ‘The ype ofan objet determines the operations ths can be perfome on the objet Buln function ype) ets the ype of an ete. Consider tis veard >otype (a) celass'int> © >ootype (a) celass'int> © DATA HANDLING. a 79 Wu) The value of on object isthe date contained in the objec a Cable the value is the dataitems take, “awment you can display vale ‘literal, the value isthe literal itself and for 3 (the variable) is currenily referencing, Using, print ‘of an object. For example, raed pee ae fina 8 Ae >>> print (a) ~ OP sal faa 4 sty ‘few as 4 li) The i of on object ‘The ofan object is generally the memory location af the objet. Although iis implemen taon dependent but in most implementations it returns the memory loston of he bet Buin function 44) reams the i ofan objet, cg 1. at is Sting data type in Python ? 2 Wat ate two internal SUBTYPE Of sarap code 3.2 Sing data i Python ? ae 3. How ae st type strings diferent fom. ; ow ae eng »>» id(@) Te of dn variable hide tinge 30999132 Soe hen pare / hea rene 5. How ig ist type diferent fom tuple 224408) mat ate Dictionaries in Python ? probes ~ ing ger 3 identity the types of ata fom thE 997445) flowing set of data 39899122 b) foshart, uRoshart, False vor sat — vara bit nn fr ie $ false, [Reset 39899120 (#0, 's,'", Oy pobebt fa," 02 2,'s “ 2973600) sont hat th id of aie» Sy: 6), (2-0-3) 39899132 + ae os of ger $ 12, 12.0, 0.0, 8, 3364299" > True, "True* 4. at do you undestand by moa es a >>> id (a) 39899132 SS ~ ‘and immutable objects ? ira is re fei tion T5132 Nace wort Rec ar rae sre et Boh ter en ping ie ‘The id) ofa varableis same as the id) of value itis storing [Now consider this . 80 coms ‘Thus internal change in value of variable b (from to 4) of sample code 3.2 will Be represents 8 shown in Fig. 34 asa a soasorze ' bb Figure 2.4 Memon representation of sample code 3.2. Please note that while storing complex numbers, id's are created differently, so a complex liters! say 2.4) and a complex variable say x having value 2-4) may have different id's DATA TYPES IN PYTHON, MUTABILITY, INTERNALS P, ln . ogress In Python 2 we 1m the Python Shell IDLE or IPython shell of Spyder IDE, type the statements as instructed. Using value 12, create data-item (that contains 12 in i) of following types. Give at least so ‘examples foreach type of data. Check type of each of your examples using type ) function 22g. to check the type of 30. you can type om Python prompt fypet3.). | © Floating point | number Science with Python and fill it there in °r? practically doing it on the comourer ” gop 3: DATA HANDUNG om 81 ja, OPERATORS operations being cased ou Ta onc operon /acie oa St ers by opt The smb sat a are cal operator The operations sk) ae represented By Operatars and the objets of the opeeteng) oe eerie One are r Prses of these types of operators: (9 Arithmetic operators (i) Relational ontore (ii) Kdentity operators (io) Logical operators (0) The symbols that trier the operators (i) Membership operators, nn BW ——opertin/ acon on dt, ae Out ofthese we shall talk about membership operators later on nr eprint ban when we talk about strings, lists, tuples and dictionaries, __ te words too, eg.» in Pythor 3.4.1B Binary Operators Operators that act upon two operands are rele to a+ EISEETICHERS Binary Operators. The operands of 2 binary OPeratOr 3° Operators hat ar distinguished as the left or right operand. Together. the operands ate veterans ‘operator and its operands constitute ar expression. Binary Operators 1. Addition operator + The arithmetic binary operator + adds valu values of its two operands. For example, 4920 resultsin 24 245 (where a= 2) results in 7 a+b (wherea=4,b=6) resultsin 16 For Addition operator + operands may be of mute types Python also offers + as a concatenation operator when use with strings, lists and tuple 1 {functionality for strings will be covered in Chapter 5 - String, Manipulation ; for list, it wily covered in Chapter 7 — List Manipulation 2, Subtraction operator ~ ‘The ~ operator subtracts the second operand from the first. For example, a3 evaluates to 11 ab (wherea=7,b=5) evaluates to 2 x-3 (where x= 1) evaluates to -4 ‘The operands may be of number types 3. Multiplication operator * ‘The * operator multiplies the values of its operands. For example, ana evaluates to 12 1b 4 (where b=6) evaluates to 24 pt2(wherep- 5) evaluates to -10 fa*c(wherea=3,c=5) evaluates to 15, ‘The operands may be of integer or floating point number types. Python also offers * as a replication operator when used with strings. This functionality w in Chapter 5 ~ String Manipulation. 4, Division operator / ‘The / operator in Python 3.x result as a float value, ¢.¢ ides its frst operand by the second operand and als) 4/2 evaluatesto 2.0 100/10 evaluatesto 10.8 712.5 evaluatesto 2.8 100/32 evaluatesto. 3.125 43.5/1.5 evaluatesto 9.8 please note that in older version of Python (2.x), the / operator worked dltterent! or fooean values rue and Fle, recltht Python rally aes values ado (zr) epetve 78"! you? 3). 5 6 nl 31 Wt wl be np rods *Y 83 rloor Division operator // none ln Se greater than, etaona operators work with ney al Pee oF lists, tuples et. Relational operators work oP Rp te ere puma poi rm os on a tbs’ ST 1 operator also works ith tie oP 6 Please note this style of combining | ples Pe after removing trating zeros ater decimal) “fand 4.0 will be treated as equal (fer to 4 only). following pri assignment wath othe i Ss 86 COMPUTER SCIENCE WT Pri, i (onering in dicionay, ‘Ais es than’ Py € Strings are compared on the basis of lexicographic eden Capital eters ae considered lesser than small tr © rote oy bok is teal books : comesponding codes or ordinal Levcographicl ordering simplemente va the comespo . eee cee intade cine) of the characersbeing compared. Thats th aes Si cteS than teense ASTI vee of ter'A (5) ee than 497). You cages ARIAS thancer youself using odlcharacter) function. orth 1 Forte mae eon you ned Bec about nonprinting characters like spaces. ‘Spaces are real characters and they have a O+t{24)= True specific code (ASCII code 32) assigned 0, fag), sacrte! we * then If yu ae comparing two stings thst ea: False appear same to you but they might produce 8 different result ~if they have some spaces [Rests devon rom ansopies rents because he seco te in the beginning ot end of the string mba me See sereenshot on the right. shen eb gcai ‘© Two lists and similarly two tuples are equal if 'N's oral value (65) they have same elements in the same order. ‘© Boolean True is equivalent to 1 (numeric one) and Boolean False to 0 (numeri zeo) or ‘comparison purposes For instance. consider the following relational operations. Given 3 b=13, p= 3.0 ent, d='ge=N: f= "god's g ='God', h ='god, j ='God k L=M1, 2,3], M=[2,4, 6), N=[1, 2,3) On (12,3) P=, 4,6), Q=(1,2.3) Neu 1L What is the function of operat ? What are arithmetic operators ? Give their examples. 2 How ie ‘unary +" operator diferent from ‘operator ? How i nary peter citfeent from ~’ operator? 3. What are binary operators ? Give ‘xamples of aitti binary operator 4. What does the modulus operator do? wit return True will return False Bh me will return False M4" han wl return True tor ale" will return Faise sel" win return True “UL return roe Will retuen False will return True Wat wb the es of 2% 2 an ee mo? “dll retum raise Pelee what wil be there of 5.3 and will return true ow s0//3? will return False meh g ‘ill return true wil: return False wl return true All return True 6 How will you caluate 45° in Python ? eens aa ra 7 maori eats greater than or equal to varable final > ger 3 DATA HARUN mn 5 summarizes the action of these rel ‘able: om) eto Octo in ton lational operators |_# _@_} pee peng peg prog pong Bea 330) | Fale True Thue Fale TruwPale rr (A | False Tue True ae Tre ae a | Fake Fae te Tae te ivpORTANT While using floating-point numbers with relational operators, you shoul keep in mina that fhoating point numbers are approximately presented in-memory in binary foes up t9 the lilowed precision (15 digit precision in ease of Python). This approsimation may ylel Jinexpected results if you are comparing floating-point numbers especialy toe esaty (=) Numbers such a5 1/3 ete, cannot be fully represented as binary ast vies O.AAN.. ee alt represent itn binary some approximation is done interlly. Consider the following code for to understand it Tas Bn aa Fn we va ‘compare 01004 0103 se, fost you 0.38 eh Theresa of exreson 044 04204 (becaute of losin paproxinaton) nit ason ee Fas or ay onan a 1+ 0.1 8 4and 03 Gn [28]: 9.160.160.1 #= 0.9 in (28): print (0.3) a3 uality comparisons as much as you 6 “Thus, you should avoid floating point eq Relational Or ‘The relational operators have a lower p arithmetic operators “That means the expression 5 en expressions Jperators with Arithmetic Operators wecelere than the 1 Gen atin dja He,t wl corso eth elt of faltwing expressions? (aes) > (6-2) ‘expression? Dick ioie; Genk (OY'==/ and no he following (rest Qi jk (a >t ar(>-2 expression 3 Waist wick 1 means the expression Zand nt the expres 2 Mir ib the der of tation loving expressions? ‘tugfrelatona peratorsarecasy to rk wth yt wile (ie >= j-6 (i) s930< 7 **2 working with them, sometimes you get unexpected sully (icy korn womtaviout from Your program, To ava | wou How ae fotoing two ex#P008 Tipe you to know certain tips regarding relational operators Aierent ?(j) ans = 8 (i) ans == & Expression n gical Operators neatier section discussed about rel Shes, is section ahs abut gia ope Jha eet fo the ays these telatonshipe tie hgical per “petators that establish relationships among the ator, the Bolean lgial operators (or, and, not) eta (mong values) canbe connected. Python provides Hes canbe et express, De aad, and ma tote we proce othe cscussion of apical operators, itis impurtat for you to know about ators tis important for you to know a Truth Value Testing because in some cases logal operators base tei sults on truth vale » Val associates with every value type, some truth vale (the rahins) i, Python internally negonizes them as true or fase, Any objet can be tested for truth value. Python considers owing values false, (i, with truth-vale a file) and rue ah with ins Vales with rath vale os tue 4a fesing ample, 0, 00, ‘Atheros ae ‘considered ti. juence, tor example, OL Tsemply sng) sempty tuple and | Sem sO ny empty mapping or example 1) Theol of relational expression canbe Trae o False depending pon the valves fits operands and the | ‘spurs taking, place. ‘vo not confuse between Boolean values True, False and truth values (truthiess values) ta fete simply put uth-vae et for 2ro-nessor emptines of alu. Boolean values belong toast ome datatype, Le, Boolean type whereas we can test truthines for every valve object in Tito Bot to aend any confusion, we shale giving trath vars rac and alse in smal eters iru witha sbserip fel, now n in his chap trae and fal Wil be refering to teuthvalues of an objet. Js we are discusing the functioning of “The utility of Trth Value testing, will be cea to you a8 we are discussing 7 logical operators. 3448 The of Operator The ar operator combines tivo expressions, these ways (0) relational expressions as operands cords atonal expressions (> wich make its operands. The or erator works in i sumbers or strings o ists as operands () Relational expressions 08 oper its operands a5 re owing paniple _ z i either of its (relational) operands evaluates (9 ‘rue: False if both operands That is x y xory False False False False True True True False True True True Tre Following are some examples of this or operation (4e=4) or (S==8) results into True because first expression (4 == 4) is True S>Bors<2 results into False because both expressions 5> 8 and 5 <2 are Fay lil) Numbers / strings / lists as operands? When or operator has its operands as numbers or strings or lists (¢., ‘a’ 0”, 300, et) then the or operator performs as per following principle Jn an expression x ory, if first operand, (ie, expression x) has false, then return second operand y as result, otherwise return x. Thats x Bs fsesy ——faotmy false trate true fey te tne Examples Operation Rests nto Reston Dor 0 0 fit expen (as ae, hence second epson 9 mmc oors § fist expression (hasan henee second expression 8s rue a ..—Llrr-.-— i §sssssr ello'or” lo’ fis expen ht) a it expen et eum =? ‘yi expresion hs any, HS expe etre oe Set expen (has fey, hence cond eps” tue Ey fis expesion (3) has rac. hence fst expire ‘How the truth value is determined ? ~ refer to section 3.4.44 above nistype cr funeoig plo any whist arate geaan tear by Python. ATA HANDLING. The oF operator will test the even if the second operand 20> 180r“a 4154 will give you result as FF True “The oF operator wil test string, 4C The ond Operator in these ways. (0) relational expressions as operands (i) numbers oF strings oF lists as operands | Relotional expressions as operands When and operator has its operands as relational ‘operator performs as per following principle expressions (eg,.p>4,) etc) then the and The and operator evaluates to True if both ofits (1 relational) operands evaluate to True False if either or both operands evaluate to Fal That is x y xandy False False False False True False True False False True ‘Tre True Following are some examples of the and operation a 4) and ( 8) resus into False because fist expression (== 4 is Tue but second epson (5==8) evaluates to False Both operands have to result into Tru inorder to have the final ests as tv 5>8 and 5<2 results into False becuse fist expression 5 >8 evaluates to Fae B > Sand 2 <5 results info True because both operands: $> Sand 2 5 evaluate to Tae (i) Numbers / strings / lists os operands* When and operator has its operands as numbers or strings or lists (e., ‘a oF”, 3.0F0, etc) then the and operator performs as per following principle In an expression x and y, if first operand, (i.e, expression x) has false, then re first operand x as result, otherwise return y, Mhstyeotorfuntionng spre to any vale michs otto expresionbtwhosetth-nesscane oernges ae 4 COMPUTER SCIENCE wa Py xend y Tx a Ab eit poi Fin expression (has fe, Bence ist expression Os retured, Sint expres 9 hi ra Bence second expression 00 is nes ll and fin expen (hl) has ry ence Second expression is etme and oy fist expression (7) has fag hence fis expression“ is eure and * fis expression has file eee fst expression 8 rete wand j 1T__ fst expression (2) has ti, ence second exprstion is ete How the truth value is determined ?~ reer to secon 344 above. IMPORTANT. ‘The and operator wil test the second operand only if the frst operand is true, otherwise gnae It; even ifthe second operand is logically wreng es, 38> 20 anda" +105 Cree will give you result as “Te and operator wil He False second operand ony he ‘ignoring the second operand completely, evenifit is wrong SPAN te, ahr ignoring the second operand completely, evenifitis wrong ore! you cannot add an integer toa string in Pythen, 3.4.4D The not Operator ‘The Boolear/logical not operator, works on single expression or operand is, itis a uns eperator. The logical not operator negates or reverses the truth value of the expres? following iti, ifthe expression is True or tru yay then not expression is False, and vie Unlike ‘and’ and ‘or operators that can etum number ora string or alist ete as resi the’ 0 ‘operator retums always a Boolean value True ar Fatse Consider some examples below not § seul into False because 5s nore ie, ray) not @ ‘esl ino Tue because is zee (ie, fal) pera wet not —4 results nto False beau fm mn Shen ee 48 0 ze0 thus frist ase ree not G > 2) results ilo False because the expression 5>2 is Tre, @ ==) and'4 2 net? rot ( > $) result into Te because the expression 579 ig Fung, MBEENO Le 5 ATA WANDUNG i 9 OPERATORS IN PYTHON of __ Progress In Python 3.2 ening Operators’ concepts. I involves both interactive mode and gf the concepts, it would be better if you frst perform the 1 by script mode practice questions, Science with Python and fil therein Pu? 3.2 undes Chop ¢ ater ¢ Please check the practical component-book - Progvess in Computer , Practically doing it on the computer ) potece V6 LeT Us Revise 1. Wat is the function of logit << oprters 2 Write an expression ivelving 8 logical operator to test if OPerators are the symbols or keywords sometimes) that represent feats are 58 and grade i specific operations lat isthe order of evaluation in the <> Arithmetic operators carryout arithmetic for Python. These ore fslowing expressions | tary + unary yf, Sand 9, (ard or bea? © nary + aves the vol of ts operand, unary changes he sign of (xo y and y m= mt io opera’ vale (ivan decod | Adon operarr+ gives sum o's operand’ vol, ~subracts the 3 What isthe result” of following value of second operand rom the vol of first operand gives the vaptesion: @ >= band (@-+)>¢ if product of ls operands’ value. The operator / divides the fist (a3 boo (a= “perand by second and returns @ flat res performs the floor What fe the snit. of following) Elon, fits the romans sir rai Am oper 7 cxyesions (oto) if Second and + 1s the exponentiation operator, L,I gives base 1 b=7? Teed © power. () heck +2 mate = 00 7 Be bs ccna ae (i ehak = mate =-§ eae ee en ie, lsh, eter en el 0. i) heck =", mate = tone to, reer tan ove 1 on ot el (check meer mate = ny (a) heck or mate (0) mate or check — Bisse opeatrs are lke logical operators but they work on (6 check and not mate individu Bis. (6) check and mate 6) mate and #5 iy operas (is 8) mare the memory mo ajc re Enluate each ofthe above expressions efrncing forall four sets of values «aged operarsparfr conan on if rates 5. entity the order of evaluation in toe eer or wae. These ae Yr ‘anda fatowing expression “pte rela eres! tah vl depends om tir Se5e 702 a3 4and Boolean rest Tae or Fae ee eae rs ath ae deen oi eminent ot 20 4» 62 2 er (such a 0,020 0} and emp sequences (sich —— all others SSS nes en Ween re aoe abe False while a am b i True? ‘honempty oes) have rte ue Data HANDUNG 101 45.1 Evalvcting Expressions inthis section, we shall be discussing how "Smt etna and lope se PYton eats diferent ype of expr Teedina separate ce Bt Sing express mented rh ib 45.14 Evaluating Arithmetic Expressions ‘eal ae familiar with artemene expressions and thir basi evaluation els rm Ralete an expression Le’ se how Pattern ak Evaluating Arithmetic Expressions Toevaluate an arithmetic expression (with operator and operands), Python follows thes rules ‘© Determines the order of evaluation in an expression considering the operator precedence ‘© As per the evaluation order, for each of the sub-expression (generally in the form of cvalue> ¢4., 13% 3) t= Evaluate each of its operands or arguments '= Performs any implicit conversions (eg., promoting int to float or bool to int for arithmetic on mixed types). For implicit conversion rules of Python, read the text given after the rules. = Compute its result based on the operator. 1= Replace the subexpression with the computed result and carry on the expression evaluation, ‘= Repeat till the final result is obtained, Imp ypeconseron Coon An ing yearns cavern poy Egmont ode ea esa expres Tn come a opens pt ee sprang promotion ois ee ps he ng a Peer anu ia come hte Scones ames a ni ~o No conersin 0 Pe i converted to complex ; the other is converted to floating saad are integers sample, which will make tear how Python tral ier the following example essionand then evalatesit Tounderstand his const pesinamised type arthmeticexpr id then evah sees pro ined rithmetc expression. Wat wil be heal rest Example33. Consider the following code coment ‘the final daa ype? integer ches. a integer iad integer fled 102 MPLTER SCIEN t=5.0 1 Floating point number f4=36.0 1 Floating point number As(ch4)/a0 ‘expression 1 B= Fa /80%en/2 expression 2 print (a) Print (a) Solution. As per operator precedence, expression I will be internally evaluated as A= ch + 1/40) int int Wi int Floating pt Step 1 (no conversion here) Step 2 (Ant to Floating 4 Pt conversion floating ot ‘So overall inal datatype for expression will be evaluated as: (ch + 9/ db) + 29/50 (5+ 20/50 2/50 + willbe floating-point number and the expressie Lint to floating point conversion} 70/50 Aata ‘As per operator precedence expression 2 wil be interally evaluat ag (cs9/a) * ony Float Float .-| float int | Anteger to Floating oat BE conversion, integer to Floating Bt conversion float so, final datatype for expresion 2 willbe lating point number 4 aTA HANDUNG 103 -tpeexpresion, expression 2 will be evaluated as (ft bye) 12) = ((960/5.)+ 51/2) no co 0352) a (72+5.0)/2) dealt =(860/2) =360/20 B=180 ‘he output will be integer to floating point conversion] 1a 18.0 ‘The final datatype of expression 1 willbe floating point number and of expression 2, it willbe floating-point number, IMPORTANT In Python, ifthe operator is the division operator (/) the result wil always be a floating point number, even if both the operands are of integer types (an exception tothe rule). Consider following example that illustrates it shanple 44 Consider Below gen expressions what Wi be He ina silt and inal date type? ajb=3,6 — ) a,D=3,6 cable cebi/a ‘Ans, (a) In expression e630 bf cn28 | ' is cn ro (i) Inexpression (9 Inexpression en6//a > I come er c2 1 1 rod corte, 8 od int int rand bah ant ero ag ra we ant You, yourself, can un these expresso (© function, 45.18 Evaluating Relational Expressions All comparison operations in Python have arithmetic operations, All relational exPFess* Tue ot False Further, chained expressions like #< be ‘mathematics ie, comparisons in Python are teeated as a< b and bec (Comparisons) ihe same priority, which is Tower than thatof any Fans (comparisons) yield Boolean values only i eave the interpretation that is conventional in ‘fained arbitrarily, eg. a4) and(qco4> ee ornate) (59) True, simply its st arguments) ok 4 what is type conven (cnc) > etumed as overall result + the second argue! How does Python prior it? (5<2) will not be evaluated at all. rennet (9 © 90 OF (8 6 2), 105 argument (5-3) i False it will now evaluate Hive aor atgunent CO - avd argument (2) adits fsecond arguments) result 8 returned a= overall “e tneapronatin (349) and (82, since ‘True, it will now evaluate ot arguument (<5) is thu cevini argument (82) and Hts (second arguments) result is etumed a overall ome aa Svatuatee ata 5) Hell HoH Jun 8-6 39 and (521, since frst argument (5-3) is Fase, simply its (lst fall result the second argument (5-<2) will not Be tu wil Be He np of following expression (6-6 10) and (10.65) oF (318) and not 8 18 station Habe VS 1 hw te tall expressions equal? por yan ot 2 (eon 9) and (nt 2) ) (0 (y a0 (90t 2) )) 2 ‘yar when would only fst argument sated and when oth ft and ated in vo boerd and not (e 8) Ae dant dee 5 Type casting? 1 om mpc typ conversion ferent magic type enversan ? 5 re runvesion function you wold 2 tn tli be of conversions Yoon to 09 tng 9 fost fat vo tegen 4 ing tages 1 eg wo fot 4 to Bosian ‘1, agar vo compen Example 38 ‘Divide by zero’ is an undefined term. Dividing by zero enuses an error in ay programin imu, but when following expression i evaluated i Pythons Python reported no erro and returned the result as True. Could you tel, why ? (5 618) or (50. 100/8) Solution. In or evaluation firstly Python tests the iat Srumment 1, 5<10 het, which is True. In or evalua. tian Python does not evakuate the second argument if Tae tist argument is True and returns the result of first gument a the result of overall expression So for the given expression, the second argument Ser enion (a. 100) 8 NOT EVALUATED AT ALE- Tio io why, Python reported no error, and simply sitarned True, the result of first argument 3.5.2. Type Costing You have Teart in ealer section that in expression yon paved types Python internally changes the Gata ot some operands so that all operands bows Same ype. This type of conversion is automatic (¢ daa hence known 3s impli Pe convenon iron, however, also supports explicit (Pe Explicit Type Conversion pe conversion is user-defined conversion ‘expression to be of specific type. The jon is also known as Type ‘Anexplicit 9 that forces an ceplict type conversi Casting, library, Python's standard library is a import math Cer than built-in funcions, Python makes ava lection time offers time related function : mo Python's standard liar provides a module namely math for mah umber types excep for complex numbers. In order to work with functions of math module, you need 10 fist impor it your program by gh statement a follows 35 the top lie of your Python script } ( ate nay me cio nln A le a le tring offers functions fr String manipulation and s ‘Then you can use math libary’s functions as math Following table (ble 3.1) list some useful math functions that you can use in your programs “Toe 321 Some Mathematical Function math Module elated feos ht work ny es) [5 [oar [mwa nam J 6. | tog | mat.tog num, tase) a pow | mathpow (base, exp) natural logarithm e aed te the org power ‘The fabst) function returns the absolute value of mum: ‘The floor) function retums the largest integer not greater than ‘The log) function returns the natural logarithm for mum. A domain error occurs if mur is negative and a range error outs if the argument num is zero, The 1ogtO( ) function returns the base 10 logarithm for num ‘A domain error occurs if mut is negative and a range er"or ‘occurs if the argument is ze. The pomt) function eetums is raised to exp power ie. haw ap | Addomain err ours i as -0 | and exp <+0 also if hse 0 and 9 nt integer sathewp 0) gies the vate | E ae FAG (conn Frm) Descpon eT ie | aes oceans 2 [age [matt ram) |The age fancin tu he | math (1.0) ges 90 Lt | [sero a [ep |mathexptarg) ‘The expt) function returns the | math fabs) gives 10 rath fabs(t.) gives 10 | math loor(105 gies 10 mathe} @6-20 | | tmathog(1.0) gies hen legate for 1 sath og 026, 2 will Inga of 03st be De math og10(1.0) gives ba loganthm toe 1 math pow 30.0 3 math pow (40, 20 8 on mn DATA HANDLING. rae 5 punctlon | (General Form) | (enerel Form) ae ol mathsinars rete the | masini) | sine of arg. The value of arg | (val is a number) ba trust be in radlane | (el a rumba sy ow acoso) whe | ee | exif ag he value of (a numb sn tant Ime tan fonction returns the | mathtan) | Lange ofa The value o | el = Smet ng Tim va to (el ba un ve anes adept |The depres) conver angle | mdepes8) wuld ge rom sas edeges. | Tash ve tne | mathsatiants) | Me adn) comersange | mahsaions(7290) would [rosea | Reverso") ann) ema module of Python also makes vallable wo ef constans namely iar which youcani8e 14159. to available precision 718281... to available precision inpi__ gives the mathematical constant mathe gives the mathematical constant roti are examples o valid attic expressions (oer import math sane Caen: ans D=4 eS PH70, 4293. 121051, 225519, y 1624113, 2=231.05 (ip math sin(p/ ) + math.cosla-o) ( mathpow(a/b 35) (io) (mathsqrt ()4)€ (iy x/y + math floor(p* 4/9) (0) (mathceil (p)+a)*€ invalid arithmetic expressions continuation. Following are examples of two operators in ty gasb-2/8 oe sang baw a2 toy mathleg-ay+p/¢ DOM eer econ fgg Example, Write the corresponding Python expressions forte following mathematical expressions © Steed iy 2—y torr eaae lel (io) (cosx/tanx)+* Solution. (i) mathsar ( iy 2-ye mathexp2 EY (iy peg math.powr tio (enath.cos(x)/ mathsan 2) {oath fabs (math.exP2) >) anarbebecr) ‘An expresion composed oon or mor operations. 50 valid combination A PEEET eras ord gy {In thon terms, an exresion legal combination of atoms and operotors. © ‘An om in Pt someting that as 0 vl, Examples of atoms ae variables, Merl, ring, oy Expressions can be orihmetc, relational or logical, comp et Jopes of operators used in a expression determine is type For stance, we of arth operas mg, “arthmetic expression ‘Aithnetic expressions con either be integer expressions or real expressions or complex number operation Imised-mode expressions, ‘An arithmetic expression always results ino number (integer oF floating-point mumber or a complex mane. ‘relational expression always results in¢ Boolean value i, ether True or False; and a logical expression aa ‘int. @ number oF a string oF @ Boolean value, depending upon its operands. Ina mixed-mode expression, different ypes of varabls!constants are converted to one same type. This paces 5 called type conversion. * Type conversion can take place in wo forms: implicit (that is performed by compiler without programmers Jntervention) and explicit (tat is defined by the user) 10 implicit conversion, ll operands are converted up to the type of the largest operand, which s clled ope promotion or coercion, ‘The explicit conversion of an operand to a specific type is called type casting and itis dane using type conversion functions tha is used os ‘ctype conversion function > ( ) 9.10 convert to loa, one may write float () Solved Problems a 1. What are data types ? What are Python's built-in core datatypes ? Solution. The real life data is of many types. So to represent varius types of realli programming languages provide waysand alites to handle thse which aceon Pythons built-in core data types belong to ‘© Numbers (integer, floating-point, complex numbers, Booleans) © String © List © Tuple © Dictionary Which data types of Python handle Numbers ? Solution. Python provides following data types to handle numbers (i) Boolean (9. Integers (ii) Floating:point numbers () Complex numbers ATA HANDUNG m1 so Bo conse op gas on, Bolen vale Tra and Fai ae eat and Pa el ely map ines and. That internally Tues Seen er), When tan ae convert Booka cess yar Meshe angembacaneteaeaaypeaem si dt ype of th wes ge bl 3, 3, 130, “13, “I3*, 240}, 13,(3,13,2) 13.2) sal solution 3 integer a complex number 130 Floating point number ay sting ny Sting 240) complex number B integer Bina) bit @.13.2) Tuple Len(ste2)) |. pata HANDLING wat sweet fee © pw sa i What sth sts (say # and b) when compared using = we! 0 wo 20) and ste(200) (ia) 1 Too obi compare re immutable an mutable types? o three internal key-atebutes of ati two objects ret stom ? What is an e Lis a int i) 20 and inn) and "a" pression ? able anal ma Ww Value-vatab i , Pore alan tan? pi th sap , operator they will al return Tre ive values equal ? Why/why not 2 ap and 200 Cc he difference between implicit type conversion and explicit type aversion? {using fs operator. Why ? bys Trae but why isa b Fa Chen set ~ "Hello, what will be the values of? fo) sel fOL (tet [A] (0) ste F-5) 15 IF you give the following for str = "Hel steal] =" 1h: What wil the result given by the following 2 ype (+3) type (3) type (6™D LYRE LD Coyne IB) NPE lw?) (ste i 1 What ae augmented assignment operators? How are they set 1, Diente between (9557222)"2 awe 5022/2 18, Given the Boolean variables a ¢a8: a= 28, What would following code fragments Evaluate the following Boolean expressions bande bore (o) not band not (@ 0F Wicr @e4 ()"Hallo” > “hello” 21, Write following expressions in (©) nota and Python (ox aam20 MAR? (ose) why docs Fython report ere? False, b= True, ¢= False (ay (oan bor not not (not Bor not 2) a 9 8 result in 7 Given x=3 20 (@) “Hello” — “Hell (xe 7 and > (oe ath ope (a ae feaaiF Ha ower 2. nea) produces error. Why ? 2B. int) produces ersor but followin 24. White expression to convert 2%. bvaluate and Justify (22/1 lean’) +2 or int’) (0 itegee ate 7 % Evaluate: () 22017. - 227 2 oe i false af ‘the val expression hav cs 17 ee) i Boolean vals Maree (2070 sat Nove (0208 8 ing int p en 3752 inezara) (i) Jone (i) THE [ent for sgt) se relum True, Bat Python gives Fae when hsqrt cay ii doesnot return. Why ? a7 int 22097 and justi: and None (0) None and None 28, Evaluate and justify (0) @ 0° None and “or (®) 20° None and on (©) False and 23 (a) 23 and False (© not (1== 1and@ 2) {)) “abc” == “Abc and not (2-== 3 0° 3 == 4) @) False and 1 = 1 or not True or 1 == 1 and False or @ 29, Evaluate the following for each expression that is successfully evaluated, determine it value a for unsicessful expression, state the reason. (@) Lea(*helto") == 25/5 or 20/20 (®) 3.5 or 50/(5 - (3 +2)) (©) 50/(5 - (3+ 2)) oF 3< 5 ( 2+ (2+ Qencer"))) 30. Write an expression that uses exactly 3 arithmetic operators with integer literals and produces resi BIL Ada parentheses tothe following expression to make the order of evaluation more clea. yR4=20 and y%100 120 or y%A00 == 0 Type B : Application Based Questions 1. What is the result produced by ()) bool (0) (i) bool (ste(0)) ? Justify the outcome. 2 What will be the output, if input for both the statements is 5+ 4/2 6 == input ("Value 1:") 6 == int(input ("value 2:")) 3, Following code has an expression with all integer values. Why is the result in floating poi! a,b, c=2,3,6 deasbt esd print(4) 4, What will following code print ? (@a=va beva print (a, b) print ( Print (a is b) 5. What wil be output produced by following code ? Stat eee 8 tate reason for this output. eased en20 f-20 B20 hae+t print(c == 4) print(c is 4) print(g == h) print(e is h) peer ate print(a) print(b) +, What would be the output proxtuced roduced by folk Heong cate ? Why? b,c 20.1 4-03 arbec-d feasbec print(e) print (#) hat will be the output of following Python code? as be7.4 con ans print(a, b) at=24e print(a) beate print(b) What will be the output of following code ? 4 wyn4, 8 z= xlyty print(2) 10, Make change in the expression for = ‘onnat change the operators and order of variables. (Hint. Use a funetion around a sub-expression) ee : re emor even if it has a subexpression with “divide by zor! of previous question so thatthe output produced is zero. You 1, Following expression does not report problem 2 on 10/0 reports this ror? What changes can you make to above expression s0 that Fython rep 12 What is the output produced by fllowing cose 2, b= bool (8), bool (9.0) Gd ste (@), str (0-8) Brint (Len(a), Len(b)) print (Len(e), len(@)? — 1. Givema string s= "1235". Can you write” OFT Sen te pe to produce strings ie, the program should Be : rec an conver 0 tet] as Tre jon that gives sum of al he digits shown isi the the result a5 15 (1920345) [Hint Uses indexes and 1. Predict the output if eis given pat eve beacs print (a == 0) print (a is b) MH bry c= str (a) : d= str (b) print (¢ =» d) Print (c isd) = input ("Enter") print (c == e) print (c ise) 15, Find the errors), (0) name = "Hart print (nane) fname[2] = *R* print (nane) (W) a= bool (@) b= boot (1) print (a print (b false) true) (print (type (int("123"))) Print (type (int(“Hello"))) Print (type (str("123.0"))) pisa.ae Print (type (pi)) print (type ("3.14") Print (type (Float (3.14*))) Print (Cope (Float( "three poin faut) (0) print ("Helo + 2) (print print (*Hello” + "2" Print ¢ Print ("Hello + 2) fell0"/2) fell0" / 2) Type C : Programming Practice/Knowledge based Questions 1 te. Program to obtain principal amount rate of interest and time from user and compute singe interest Nate @ Program to obtain temperatures of 7 days (Monday, Tuesday average temperature of the week. 3. Write a program to obtain x, y, 4 Sunday) and then displ = from user and calculat Write a program that reads a number of 200 seconds are printed as 3 mins and 20 seconds, {Hint use // and % to get minutes and seconds) 5 eit a program that reads from user -() an hour between 1 to 12 and (i) mumber of hours aheod. Program should then print the time after those many hour, og Enter hour between 1-12 : 9 How many hours ahead : a Tine at that tine would be $ Ayrne & Prostam to take year a5 input and check fit isa leap yea oF not 7 Wiite a program to take to numbers and print ifthe fist nuniees ie fully divisible by second oF not te expression : 4x*43y° +9246, seconds and prints it in form ‘mins and seconds, eg. 1 eclock 8, Writ a program to take a 2g nm is 25, the program should prints, 9, Try writing program (similar o should print 321 Write a program to take two inputs fr day, mo na date is. For simplicity, take 30 days for all mont then it should print Day of the year 35 input ber and then print the reversed number. That if the HP Previous one) for three digit number ‘e, if you input 123 1% p,the mth and then calculate which day of the yee Ms ths. For example, if you give input as: Day

You might also like