Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
47 views
62 pages
Data Handling
computer
Uploaded by
najiyashirin7
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save Data Handling (1) For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
47 views
62 pages
Data Handling
computer
Uploaded by
najiyashirin7
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Carousel Previous
Carousel Next
Download
Save
Save Data Handling (1) For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 62
Search
Fullscreen
81 Data Handling sa wo ce 41 Introduction 85 Expressions 8.6. Introduction to Python Standard 82 Data Types 83. Mutable and Immutable Types 97 Library Maauies: 84 Operators 7 Debugging INTRODUCTION Inany language, there are some fundamentals you eed to know before you can write even the most elementary programs. This chapter introduces some such fundamentals ; data types, variables, operators and expressions in Python. Python provides a predefined set of data types for handling the data it uses. Data can be stored in any of these data types. This chapter is going 1° discuss various types of data that you can store in Python. Of course, a program also rneedis a means So, this chapter shall also talk about mut able variables in Python. variou to identify stored data able and immut: DATA TYPES 1 integer, real, stying es. AnytRING enclosed in quotes rout ractions represent integer da Numbers ine and Fase represent Boolean data, Since the data to be amming language must provide ways ancl oelites Data can be of many types ¢g. characte! represents string data in Python. Numbers with fractions represent real data and dealt with are of many types: @ PTOB! handle all types of dala Tet us discuss various ple to Kroww Python's space it allocates to hold a ata in Python, cess different types ot & . f vs, you'll be al Before you learn how you can pr data-types supported in Python. In this discussion of at type capabilities t e ific type of data, such as the mentery 0 handle a specific type ° Ee epee certain type of data and the range ‘of values suppent® ie Wee!v COMPUTER SCIENCE WT Pg, 7 204 j wailtein core data types | Python offers following built Ole (0) Dictionary. i : “Gy Numbers i String (HD HS ! 8.2.1 Numbers the name the Number data types are used to store rumeric values iy PY rar by the na i Nt sere in Python have following core data types The Num! y (Integers . © Integers (signed) © Booleans (i) Floating-Point Numbers (iii) Complex Numbers 8.2.1A Integers | / Integers are whole numbers such as 5, 39, 1917, 0 ie Tpes of integers in yeh, en They have no factional paris. Integers are represented faite ython by numeric values with no decimal poi ine danglcs 15, 3000 Booleans \ Integers can be positive or negative, ¢g., +12, - 15, (missing + or~ symbol means it is positive number). ee ‘There are two types of integers in Python : (i) Integers (signed). It is the normal integer? representation of whole numbers, Integers in Python 3.x can be of any length, itis only limited by the memory available. Untke othe, languages, Python 3.x provides single data type (in) to store any integer, whether big or smal, Itis signed representation, i, the integers can be pasitive as well as negative. (@) Booleans. These represent the truth values False and True. The Boolean type is a subtype of Plain integers, andl Boolean values Faise and True behave like the values 0 and 1, respectively To get the Boolean equivalent of 0 or 1, you can type bool) or boo! (1), Python will return False or True respectively. See figure below (left side). i: - [>>> str(False) The str{ } function convers 2 ease" str( ) function converts Value to string. H | | >>> str(True) | "True* However, when you convert Boolean values False and Tre \o a string, the strings ‘False’ or ‘True’ are returned, Tespec- The two objects representing Bvely. The ste) function converts a value to string. See figure the values False and True (rot * of, above (right side), false or true} are the only 8.2.1B Floating Point Numbers a enNam “ zone having factional rae e floating-point number, For example, 3.14159 is @ integer Then eee, The decimal point signals that it ig floating-point number, not an Ber The number 12 is an integer, but 12.0 is a floating-point number. 1 1 Te sore cases, the exception Overlowtiror 5 raised inst the e nf ‘urmber of bytes, m nee5 4 eo Literals/Values’ discussion in chapter 6 wat » that fractional mums 6 | “ mer “etn ym (Norntdl Decinia! Notation) es, 3500.7 en Ap esponent Notation «.s., 3.50075E03, 0.58.04, 1.4793 men 7 he rooting point variables represent real number: nea ; S, which are used tor m, ance are temperature ete. and typically have a fr Sasurable Hloating point numbers have too advantages over hee pat metic : @ They can represent values between the integers _ They can represent a much greater range of values, put floating-point numbers sufer from one disadvantage aso: «6 Floating-point operations are usually slower than integer operations. ip Python, floating point numbers represent machine-level double precision floating point numbers? (15 digit precision) ‘The range of these numbers is limited by underlying ma nine In Python, the Fi ! hon, the aati pain architecture subject to available (virtual) memory numbers hese a : rezleen ot digits (double-precision), 4 a2Ic Complex Numbers Python isa versatile language that offers you a numeric type to represent Conley Numb r Complex Numbers ? Hey, don't you know about Complex mombers Un Tseu Youaze going rudy about Complex rucmbers in class XI Mathematics book Well if you don’t iow ating spout complex numbers, then for you to get started, { am giving below brief cearstactc of Complex numbers and then we shall talk about Pyton’s representation of Complex numbers es 1 Mathematically, @ complex number is 2 number of the form ‘A+ Bi where iis the imaginary number, equal tothe square root 1. what are the builtin core data types of of -Li.e., (=I Python ? 2, What do you mean by Numeric types ? How many numeric date types does A complex number is made up of both real and imaginary components, In complex umber A+B4, A and B ate rea Python provide ? umbers ané iis imaginary. If we have a complex cumber 2 4h. What willbe the data types of wherez=a- bithena would bs de real componen: and b oul following two variables ? represent the imaginary companent of eal compare of A= 2147483647 7d + Bis 4 and the imopinary component would be 3 BoA 1 (int, Carefully look the values they a soi, You afr woe complex numbers inthe form A = Bi where is Balenaemne 0 eeaninary number, equaito ue squace rect of 4. What are Boolean numbers ? Why ave me at they considered 2s a type of integers i" Python ? jumbets: the savings in processer ecsion floating point numbers 2 spy the overhead of using objects in PEN. sochere 2. Asper Python docartentation, “Python does nor support single Pl mune" and memory usage that are usually the reason for using oe ol {sno reason to complicate the language With (2 Kinuls otCOMPUTER Science 4H By, we oy cra 206 7” ‘ bers in Python . ws Complex Nu nts complex numbers in the form A~Bji That is. to represeny i. ' Python repristiijces j (or J) in place of traditional 7. So in Python og, { re iain sen and bare storing two complex numbers in Python «eg following examples 1 43.3) ba2.5423 ‘The above complex number @ has real component as 0 and vepinary component as 3.1 ; in complex number b, the real | aie Lg and imaginary part is 2. When you display complex Python reoteens fab , Python displays complex numbers in parentheses numbers 3s 2 me nak s following 0ine numbers, ig hhave a nonzero real part as shown in when they o examples. used tn omolex numbers are qute commonly ws In the field of electricity, however, because the symbol is used to represent current, they use the symbol j for the square root of Htectrico! Engineering 1 Python acheres to this convention Ps. 1. What are floating point numbers ? When are they preferred over integers ? 2 What ate complex numbers ? How would Python represent 2 camplex number with zeel part as 3 and imaginary part as — 2.5 7 3. What will be the output of following code ? i gz ps (141.54) print (p) print (q) 4. What will be the output of following code? 12,543.95 print (r-real) print (r. imag) 5. Why does Python wses symbol f to represent imaginary part of a comple hurnber instead of the conventional i? Hint, Refer note above, >>> €= 044.55 >> d= 43.45 re | 4.53 | pod (1143.45) >>> print (c) nan at ida as parentheses sa serprint f oo Bu 0 parent around ceg smbe th rtp (1,143.43) Unlike Python’s other numeric types, complex numbersage + a composite quantity macle of two parts : the rea! par and the imaginary part, both of which are represented intemal as float values (floating point humbers). You can retrieve the two components using attribute references. For a complex number z : © zateal gives the real part © zimag gives the imaginary part as a float, not as a complex value. For example, >>> 2= (142,569) + (-4-3.56)) >a (3-3) {wl display real par of compe: >>> zonealarm 3.0 j wll display imaginary pare of xin 2992 edmag, t ecbers 4.08 \ The real and imaginary parts of a complex number #
01 name | He \ me . acwward Indexing figure 8.1 Structure of @ python Sting programming 4 st othet i jaractel no 3. Python has no separate eharacter dataty?e wtih meu single character, m Python, a character isa string (¥P? only, ig is a sequence of characters and each character can be position of Python st uation concepts. Striny acters contained in it (stored 1 gj the characters of a string are given (WONTE index tor lustration as given in Fig. 81 anguages have ~ that €a8 a, ie,, any number of valid All Python (3.x) strings store Unicode characters mn individually accessed ngs as it will form the basis gs in Python are stored. as index for each location. in contiguous y hold 3 singlea %& COMPUTER SCIENCE 3 Fey 208 . that : 8.1 you can infer . From ; i es 7 Python are stored by storing. each character separately in contiguous set i S : ‘The characters of the strings are given tWo-way indices ee O12, win the forward direction and 1, -2,-3, in the backward direction men[cindex] ¢g., 10 access the first an access any character as
), we can say tha. © first character of the string is at index 0 or —length © second character of the stzing is at index 1 or —lengtlt-1) © second last character of the string is at index (length ~2) or -2 © last character of the string is at index (length -1) or -1 Inastring, say name, of length In, the valid indices are 0, 1, 2, hi. That means, if you try to give something like The index (also called subscript >>> name[In] sometimes) is the numbereg _ Position of a letter i the string Python will return an error like : In Python, indices begin 6 men ‘onwards in the forward direction in] and -1, ~2, .. im the backward IndexError: string index out of range direction. The reason is obvious thal in string there is no index equal to the length of the string, thus accessing an clement like this causes an error. Also, another thing that you must know is that you cannot change the individual letters of bs string in place by assignment because strings are i - . $ gs are immutable and 5 . supported, ie, le and hence item assignment isnot rane ="neLlo! adidoal individual leer assignment no Mane[@) =f ¢—————~ toad tone will cause an error like : nane(@) TypeError: ‘str object does not support item assignmentchoptr 8 : DATA HANDLING However, you can assign to a strin a expression that retums a string using a statement is valid : 1 another string or an ssignment, eg,, following Vali string indices are 0, 4 Sings cot be ssid e Sache et fhar eve stones essen “inroads ~ length in backward direction, 8.2.3 Lists and Tuples The lists and tuples are Python's com z ‘ pound data types. We hav. section because they are basically the same types with one difige eee gene one modified (ie, mutable) but tuples cannot be changed or modified (ra, ines ees about these two Python types one by one. Se emanate Lance 8.2.34 Lists A ffeemces oe A List in Python represents a list of comma-se ; brackets eg., following are some lists 1,2.3,4,5) (ae, 0,0] ['Neha’, 102, 79.5) arated values of any datatype between square Like any other value, you can assign a list to a variable eg., >>> a=([1, 2, 3,4, 5] ‘# Statement 1 aoa (1, 2,3, 4,5] >>> print (a) (1, 2, 3,4, 5] To change first value in a list namely a (given above), you may write >>> a[@]=10 # change Ist item - consider statement 1 above >a [19, 2, 3, 4,5] To change 3rd item, you may write >>> a[2] = 38 # change 3rd item >a [10, 2, 30, 4, 5] You guessed it right ; the values internally are numbered from 0 (zero) onwards i. first item of the list is internally numbered as 0, second item of the list as 1, Sed item as 2 and so on. Weare not going further in ist discussion here. Lists shall be discussed in details in a later chapter: 8.2.38 Tuples You can think of Tuples (pronounced as tu-pp-e, rhyming with couple) those lists which cannot be changed ie, are not modifiable, Tuples are represented as group of commur separated values of any date type within parentheses, e.,, following are some tuples p=(1, 2, 3,4, 5) pe (males ay oe i = one can change /add/ delete a hst's: he (7,8,9,'8 8,0) elements. But the values of type tuple are, notable ie, son-cnangeable one CNet s iscussed in details in a later chapter: Tuples shall be discussed i ence nochCOMPUTER SCIENCE yy ITH py 210 in Yi ets / 8 eas gre also similar to lists that can store multiple values same as in mathematica oe sets are little different from lists. se, ‘These differences are : 9 Sets are created by specifying comma separated values enclosed in curly by, © Sets’ elements are unordered and unindexed unlike lists. ackets | © Sets do not allow duplicate entries unlike lists. © Sets cannot contain mutable elements. Consider below given example which is creating a set of values. >oompset = (1,2, 8,4} eae pig coma aed tg >>> print(myset) enclosed in curly brackets ¢ ). {1, 2, 3, 4) myset1={1, 2, 3, 4, 4 mrmneete th Sets do not allow duplicate eis, Sec. treed the >>> print(myset2) ery 4s you ea Se tha 4 upoars ony ace ee {1, 2,3, 4} though you gave 4 Ove while ereoting "a >>> type(myset)
>>> set1={1, 2, (3, 4]} ee nukonsrntanea us? 7 See hat alo mate oes a Hits. See i gave ero when we ta wa File "
", line 1, in cmodule> 4 fist as element, but it une ery net set1=(2, 2, [3,4)} <———— Tegel ee TypeError : unhashable type : ‘list’ >>> seta = {1, 2, (3, 4)} . —_ A set cannot contain a mutable element in it. However, a set itself ti i Python data types st is mutable, i, we can add or remove items from it ees lists, tuples, dictionary et. are all iterables, 8.2.5 Dictionary Dictionary data type is another feature in Python’s hat. The dictionary is an unordered set of comma-separated key : value pairs, within | |, with the requirement that within a dictionary, ro two keys can be the same (ie, there are unique keys within a dictionary). For instance, following are some dictionaries : fa: 53,01 4,'U: 5} ig BS Oa UESY ‘An iterable is any Python object that can ret i members, one at 2 tie >>> vowels = (1a! 1, >>> vowels[‘a'] Hee, 15 and are the keys of dictionary vowels 1,2, 3.4, 5 are values for these keys respectively, : Since, you can acess b strings, fst, Dep vowels(U] + spect key ide {J ote dcionary vane gis he semen con axetil 5 corresponding value from te key : value pair ssi tuples and dictionary one a dictionary ° time, these are all erables. Dictionaries shall be covered in details in «later chapter, —Chopter 8: DATA HANDLING ing fi 21 Following figure summarize: ® the core data types of Python, Core Data Types —_— _ Numbers ai T — None 8 — eruences apengs r —| = ring — | Imeger Floating Complex al | Fan Wings Tweet etry Boolean 8.3. MUTABLE AND IMMUTABLE TYPES Tre Python data objects can be broadly categorized into hu ~ mutable and inwmutable types, in simple words changeable or modifiable and non-modifiable type: 1. Immutable types The immutable types are those that can never change their value in place. In Python, the following types are immutable : integers, floating point numbers, Booleans, strings, tuples. Let us understand the concept of immutable types. In order to understand this, consider the code below : rneiltsbte Tyee! | + integers Sample code 8.1 + floating point numbers ous | booleans ase | strings a | tuples | : twill gives, 5,5 a P=10 qer After reading the above code, you can say that values of integer variables p, q, r could be changed effortlessly. Since p,q, r are integer types, you may think that integer types can change values. But hold : It is not the case, Let's see how. You already know that in Python, variable-names are just the references to value-objects i., data values. The variable-names donot store values themselves ie, they are not storage containers, Recall section 7.5.1 where we briefly talked about it. Now consider the Sample code 8.1 given above. Internally, how Python processes these assignments is explained in Fig. 82. Carefully go through figure 6.2 on the next page and then read the following lines. So although it appears that the value of variable p//q/ ris chany place” the fact is that the variable-names are instead made to rete inate object, (Changing in place means modifying the same value in saute meNOY NS alues are not changing “in gin, ¢ to new immutable integera COMPUTER ScENCE wy 212 ri it statements are executed : @ Initially thgse three sta . nn? All variabies having same value reference the seme vue a-P ec eo eal ference sate ere res Internally Python keeps a count of how TT _ manyrvarables are refering to value a — | obec 208 224 bff -\— par Figure 8.2 22 orl Feel? Ge Te te] q | mummy 5 6 47 V8 y You can check/confirm it yourself using id( ). The id( ) returns the memo: FY address ty which a variable is referencing, >>>q=p >on Note thei) is rturing same een, sda oF >>> ia(5) vate. nich Please note that everythings an abet 1457662208 Tears at hese ae in Python, be it data items, any Ian tcereeing he #28 value, strings, umber, data, ype, >>> id(p) { variables and so forth, This 1s because 1457662208 | Python is an object oriented language 1 and it creates ang teats eventing at >>> id(q) ! an object. The id{ ) function when you 1457662208 | use on any date value or variable, ‘ returns the urigue identty ofthe obec, rridcr) which is its assigned memory adress 1457652208! ! Please note, memory addresses depend on your operating system and will vary in different sessions, © When the next set of statements execute, ie,, \ a-r | tose | J ansacuiyinnuits then these variable names are made to point to different in acton integer objects. That is, now their memory addresses that eye they reference will change. The original memory address of p we that was having value 5 will be the same with the same value ORGY ie, 5 but p will no longer reference it. Same is for other Sean variables, ‘OR Code Reece nechopter 6 : DATA HANDLING 213 This count raf sdenglS COUN reflects that current MlersWvanables ae refering to is val Figure 8.3, | | o> tar i same. memory adres new i . | ‘ale canbe stored aad hen ! i | , i i | | i | |oosqer ! | i soo tana) corre i | (ieee enn ' 1457662288 | ‘variables p,q and rhave changed, I ow iss 1 ‘evar scan conn jee (Conon te oa ort eae f 555 4407) | wasreco2i0 i | >> 4d¢q) 1 1457662240 | Mutabliy mesns atin the i 1 1457662240 (id te ycon aed oe peal. saacae ae { 1457662208 pameuiem i Now vaable Chas reference memory address same as nial reference memory address of varable p when ithas value 8. ‘Compare Istings given above por t= | >>> da(t) 1 1457662208 L. Thus, it is clear that variable names are stored as references to a value-object. Each time you change the value, the variable’s reference memory address changes. Variables (of certain types) are NOT LIKE storage containers i, with fixed memory address where value changes every time. Hence they are IMMUTABLE.COMPUTER SCIENCE WHT prac n 4 Mutable Type; Lists i ose whose values can be changed ] Dictionaries Sets ay j 214 ki 4 2, Mutable types : wu yes are ths Ie re Only see typesare mutable in Python, These are ists, dictionaries and sets. To change a member of a list, you may write | Chk = [2, 4, 6] chk (2. It will make the list namely Chk as [2, 40, 6]. >>> id (chk) 150195536 gy >>> Chk[1] = 48 >>> da(chk) s*" 150195536 | 8.3.1 Variable Internals type of data as an object. 1. What is String data type in Python ? | 2 What are two inteinal subtypes of | String data in Python ? 3. How ae str type strings different from Unicode strings 7 4. What are List and Tuple data types of Python 7 5. How is a list type different from tuple data type of Python ? 6. What aze Dictionaries in Python ? 7 entity the types of data from the following set of data ‘Roshan’, w'Roshar', False, ‘False’, [0's ‘W, ‘a', Wi], CR,‘ "8, "HY, “2, “nt, (REL O52 8:3, N saat 25, 99:6), (2.6-3), 22, 12.0, 0.9, @, 35, 642.34, True, “True” What do you understand by mutable and immutable objects ? ‘See, even aller changing a value in thelist Chk, its reference memory acdress has remained same, That ‘means the change has taken in place| = the lists are mutable Lists and Dictionaries shall be covered later in this book Python is an object oriented language. Python calls every entity that stores any values or any An object is an entity that has certain properties and that exhibit a certain type of behavior, e.g., integer values are objects - they hold whole numbers only and they have infinite precision (properties); they support all arithmetic operations (behavior). So all data or values are referred to as object in Python. Similarly, we can say that a variable is also an object that refers to a value. Every Python object has three key attributes associated toil: () The type of on object The type of an object determines the operations that can be performed on the object, Built-in function type( ) returns the type of an object. Consider this : roasd >>> type (4)
; ocak pe of variable ais abo mt 2 YR ee sitcunah
‘song 0 an meer atu retursed in ie. imagerchovler 8 : DATA HANDLING fi) The valve of an object Itis the data-item contained in the obj literal, the value is the literal veil ed oe variable the value is the data-item it (the variable) is currently referencing. Using print statement you can display value of an object, For example, pase reine) of ger Berat 4 >>> print (a) 4 {ii) The id of an object The id of an object is generally the memory location of the object. Although id is imple mentation dependent but in most implemen- tations it returns the memory location of the object. Built-in function id( returns the id of an object, ¢., value of vale ais 4s curently referencing eget, vatue 4. = yo 1d(4) Object 4 i amterally stored 3899132 a location 30899152 aay Variable ais curren referencing >>> id (a) location 30899152 (Notice same 39899132 Sis) Real that surat hat a storage location Python eS Tie pe ke abject! ‘The id() of a variable is same as the id() of value it is storing. Now consider this : Sample code The id's of value 4 and yop 3d(@) are a ae aeego132 ‘of 4 is sume as the location parasd 10 which variable a is >>> ida) refering to 36899132 a >>>. B= 5 4 ———— variable b is curently having >>> id(s) value 5, i.2. referring 10 >>> id(b) 30899120 ‘Variable B witl wow refer 1o >>> b=b-1 value ses1s2-—— eae >» Sones EXAMPLE Bf What te output of the following code ? SOLUTION EXAMPLE BE In the previous example, Why did the 215 ‘Thus internal change in v: Gao (fom 5 to 4) of sample represented as shown in Fig 84. ‘alue of variable & code 82 will be ame 32890132 bes 38099120 bebea (eye) Figure 8.4 Memory representation of sample code 8.2 Please note that while storing complex numbers, id’s are created differently, so a complex literal say 2.4j and a complex variable say x having value 2.4j may have different id’s, nseti = (11, 12, 13, 13) print(nset2) (11, 12, 13} code not print the output exactly as the input ? SOLUTION This is because the sets ignore the duplicate values. Since the input contained a duplicate value 13, the set nsetl ignored it and hence the output is different from the input. EXAMPLE Eq How are following vo variables created using | | different from one another ? vi={ 11, 12, 13, 14}, v2= (1:42, 13:14) SOLUTION Variable V1 is a set and V2 is a dictionary as it contains key-value pairs. We can confirm it by checking the types of V1 and V2 as: >>> VE= (11, 12, 13, 14) poo V2 = (11:12, 13:14} >>> type(VL)
>>> type(V2)
Dara TyPES, MUTABILITY INTERNALS Progessln Pron 8.1 —————— oP In the Python IDE of your choice pope’ COMPUTER SciENCE y 216 AT Bet rm 8.4 OPERATORS ‘The operations being carried out on data, are tepresented by operators, The — trigger the operation / action on data, are called operators. The operations(sneciig po represented by Operators and the objects of the operation(s) are re sks fed (0.35 Oporang he Python’s sich set of operators comprises of these types of i operators : (i) Arithmetic operators (i) Relational operators (ii) Identity operators (ie) Logical operators (v) Bitwise The srmbat that van operators (vi) Membership operators. called Operators oS ut)” Out of these, we shall talk about membership operators later an which opera Bul when we talk about strings, lists, tuples and dictionaries. carried out 12, the ang (Chapter 10 onwards). the operations) are eins 4 tehereayg! * 25 Operands vl Let us discuss these operators in detail. Beran | =| 8.4.1 Arithmetic Operators To do arithmetic, Python uses arithmetic operators. Python provides operators for bag calculations, as given below = ic + addition + multiplication // subtraction 1 division % floor division ** exponentiation temainder Each of these operators is a binary operator i.,, it requires two values (operands) to calculatey final answer. Apart from these binary operators, Python provides two unary arithmetic | operators (that require one operand) also, which are unary +, and unary — The Operators tht 3 cn | operand are refered to a Unary Operators. 8.4.1A Unory Operators Unary + Unary — ‘The operators unary ‘#’ precedes an operand. The operand (the value on which the operator operates) of the unary + operator must have arithmetic type and the result is the value of the argument. For example, The operator unary ~ precedes an operand. The operand of the unary — operator must have arithmetic type and the result is the negation ofits operands value. For example, ifa=5 then -ameans -5. ifa=0 then —ameans0 (there is no quantity known as - 0) —4 then —a means 4. ifa=5 then +a means 5. ifa-O then +a means 0. ifa ifa=~4 then +a means ~ 4. This operator reverses the sign of the operands value J 8.4.18 Binary Operators Operators that act upon two operands are referred to as Binary . ors son Operators. The operands of a binary operator are distinguished persian rm ered as the left or right operand. Together, the operator and its rewards mr operands constitute an expression. 4. Sometimes these can be words too, eg., in Python is and is nat are also operators.yore 8: DATA HANDING 1, Addilion operator + The arithmetic binary operator + adds v values of its two operands. For exampie 4420 results i in 24 a+5 (where a= 2) results in 7 a+b (where a=4,b=6) results in 19 For Addition operator + operands may be of rmuoiber types®. Python also offers * as a concatenation operator win used with strings. lists arc tuples. Tis fue tionality for strings will be covered in Chapter 10 ~ String Manipulation ; for lists, it will be covered in Chapter 12 — List Manipulation, 2, Subtraction operator — The ~ operator subtracts the second operand from the first. For example, 14-3 evaluates to 11 a-b (where a=7, b=5) evaluates to 2 x-3(wherex= -1) evaluates to —4 The operands may be of number types. 3, Multipliction operator * “The * operator multiplies the values of its operands, For example, 3t4 b*4 (where b evaluates to 12 ) evaluates to 24 p*2(wherep= -5) evaluates to 10 ac (where a=3, ¢=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 flanctionality will be covered in Chapter 10 String, Manipulation 4, Division operaior / The [ operator in Python 3.x divides its first operand by the second operand and always returns the result as a float value, ¢.g., 4/2 evaluatesto 2.0 190/18 evaluatesto = -10.@ 2.8 evaluatesto 2.8 100/32 evaluatesto 3-125 13.5/1,5 evaluatesto 9-0 Please note that in older version of Python (2.%), the / operator worked differently. 5, ForBootean values frue and False, recall that Python inte! you2 :). nally takes values 1 and 0 (zero) respectively so True J will give 27 5 Foot Division operator // on also offers another divisio er division opera which performs the floor division Te lowe Siete i the dissin in which oly the whole i ‘of the result is given in the outou fractional pact is truncated maranatte Tounderstand this, consider the third example of division given in division operator. ie, a-15.9, 6=3, a/b evaluates to5.3. Now if you change the division operator /, with floor division operator //in above expression, ie, 1a=15.9, 6-3, ofa wilt evaluate 195.8 a Fc ug OS educate Consider some more examples: 03 ducuded 100//32 evaluates to 3 feus's's 7/73 evaluates to 2 6.5/2 evaluateste 3.0 ‘The operands may be of number types. Modulus operator % The operator finds the modulus (ie, remainder but pronounced as mo-du-l0) ofits first operand relative to the second, That is, it produces the remainder of dividing the first operand by the second operand, For example, 19 %6 evaluates to, since 6 goes into 19 ‘three tines with a rerainder 1. Similarly, 7.2%3 will yield 1.2 6%2.5 will yield 1.0 ‘The operands may be of munber types. Exponentiction operator ‘The exponentiation operator ™ performs exponen- tiation (power) calculation, ie, it retums the result of a number raised to a power (exponent). For exaniple, 4° 3 evaluates to 64 (4°) a**b(a=7, b=4) evaluates to 2401 (a te. 7*)- 190.5 (x=49.0) evaluates to 7.2. (x°%, tee, Vx, 1.6.5 49) 27.009 1° 0.3 evaluates to 2.68814413570761. (27.005°} ‘The operands may be of number types.4 2eplitation , +> comping bith Hae atk spend we Mahyntd Avr OS Computen scence 232 Pies Sea Th Pay c EXAMPLE EB) Win i be the output produced by EXAMPLE EBM Why is the ong cae the following code ? print (21+ 3) "Bore print ('11" +3) SOLUTION xex-d The problem is with line 2 of givg because an integer cannot be sayy string value, thus Python will give. + Sxexez prine('x:", x) “yt? Ys © Yat, SOLUTION "poeErr:canonlyconatente se (0% Ie gg, xi dy: 82: 10 EXAMPLE Which of the following expan EXAMPLE Eat wi be the output produced by it yet an integer type vniw as ts cute the following code ? Hoan, mag, “™ 7 5*2 wy sme print(14//a, 1024, 14/4) * Oe oe ‘ (5/2 eH 312 SOLUTION (wii) 5% 2 (eit) 5420 3235 (50720) 5-2 LUTION EXAMPLE BQ) What will be the output produced by SOLU (ic (on wan Expressions (i), (ii), (vi), (vii) will yield i ‘he following code ? ; Pi 2 Fielel integer pumas watHiply by ating type result print(2*'Not + 3ttity ieustll ome print(2* (‘No 33*"!")) EXAMPLE BED Considering the expressions fomn ~ 3 Ln SOLUTION No alow (1 f Car stirs eorihe | the previous example, which expressions will yield « nono!!! > Mono lt — Muipied floating point result ? No! LINO! SOLUTION Expressions (0), (vif), (éx) will yield a floatin . EXAMPLE EX) What will be the output produced by rR on ” * point result the following cade ? fyed tite print (type(1+3)) EXAMPLE wi Considering the expressions giver it print (type(1+3.8)) the previous example 12, which expressions will get 7 bat String result ? 1 SOLUTION SOLUTION
:
2 Expressions (ii), (io) will yield a String result EXAMPLE QD iat wil be the output produced by | EXAMPLE FED consiering the expressions iu ine iting eet the previous example 10, which expressions will rl into an Error and why ? print (12 +3) SOLUTION print (*11' + '3") Expression (x) will result into error because th SOLUTION minus operator is not a valid operator ft P a , string and integer values. , 1B 2 lilo a ge mry og MW at wee Win ae Way aaa . asf , = Chopter 8: DATA HANDLING Operator Associotivity 231 | Ble expressio he operates gore SSIOM 25 you have leamt above, there snot any problem as Python will evatuare ree yon Peon have different pene what the expression coma ee aera the operator with higher precmdente fri bat an _ In that case, associativity helps detcemine the octe, n ihe some precedence ? Associativity is the order in which an ian is evaluated. Almost all the operators have lefty (74), which has rightto left associativity. That mon precedence, other than **, in same expression then the operator on its right and so on ans, in case of multiple le operators with sam the operator onthe etic exami ser For example, multiplication operator (*), di , division operator (/) and floor divisi have the same precedence, So, if we have an expression having these opersines ames ee then the same-precedence-operators will be evaluated in left-toright orden en neOUsY For example, foporatrs 2 eis from the son's evaluation that clears marks dius onder of evaluations ‘An expression having multiple ** operators is evaluated from right to left, ie, | 23°" 4 will be evaluated as 2** (3 *4) and NOT AS (2"3)*4 Consider following example See the default order of evaluation (first expresion) r, 1 MATCHES with sie second expression where pom ste gee 2 t pareitheses are added us per right tk associativity onder 19683 lind NOT LIKE third expression that has parenieses om lefto-righ onder, because espomentaton (*) has right-to-left associaiity po 34 (344 2) 19683 expression having multiple operators of same precedence, is evaluated. All operators are left associative except ‘exponentiation (right associative) >>> (3** 3) 72 729 |
You might also like
CHAPTER 3 - New
PDF
No ratings yet
CHAPTER 3 - New
15 pages
Basic Data Types in Python - Real Python
PDF
No ratings yet
Basic Data Types in Python - Real Python
15 pages
Chapter-8 Data Handling
PDF
No ratings yet
Chapter-8 Data Handling
69 pages
Tokens and Data Types Notes
PDF
No ratings yet
Tokens and Data Types Notes
11 pages
11 Unit1chapter03datahandling 180823043256
PDF
No ratings yet
11 Unit1chapter03datahandling 180823043256
92 pages
95% SIMILAR To DH1 But Go Through For Important Info
PDF
No ratings yet
95% SIMILAR To DH1 But Go Through For Important Info
107 pages
Lab 1 - Introduction, Classes, Function
PDF
No ratings yet
Lab 1 - Introduction, Classes, Function
20 pages
Lecture 3
PDF
No ratings yet
Lecture 3
21 pages
Data Types
PDF
No ratings yet
Data Types
30 pages
F-Basic To Expert Python (11 Session) (CodeWithKolin)
PDF
No ratings yet
F-Basic To Expert Python (11 Session) (CodeWithKolin)
17 pages
Class 03 Data Types (Int, Bool, Float, String)
PDF
No ratings yet
Class 03 Data Types (Int, Bool, Float, String)
18 pages
Decision Making Tools Lecture No - 03
PDF
No ratings yet
Decision Making Tools Lecture No - 03
14 pages
07 BasicDataTypes
PDF
No ratings yet
07 BasicDataTypes
19 pages
10 Lecture Data Types in Python SS
PDF
No ratings yet
10 Lecture Data Types in Python SS
17 pages
Chap2 - Types, Operators & Expressions
PDF
No ratings yet
Chap2 - Types, Operators & Expressions
70 pages
Aim: Programming in Python
PDF
No ratings yet
Aim: Programming in Python
8 pages
1.python Introduction
PDF
No ratings yet
1.python Introduction
23 pages
Everything in Python Is An Object.: Unning Cripts
PDF
No ratings yet
Everything in Python Is An Object.: Unning Cripts
11 pages
Week 3 MAK
PDF
No ratings yet
Week 3 MAK
31 pages
Part 4 B
PDF
No ratings yet
Part 4 B
11 pages
Basic Data Types in Python
PDF
No ratings yet
Basic Data Types in Python
8 pages
WWW W3schools Com Python Python Numbers Asp
PDF
No ratings yet
WWW W3schools Com Python Python Numbers Asp
8 pages
Numbers
PDF
No ratings yet
Numbers
10 pages
Class11 CS DataHandling Updated
PDF
No ratings yet
Class11 CS DataHandling Updated
49 pages
1 A Number
PDF
No ratings yet
1 A Number
3 pages
XI-IP-Module-DATA HANDLING-2021-22
PDF
No ratings yet
XI-IP-Module-DATA HANDLING-2021-22
40 pages
Python 4
PDF
No ratings yet
Python 4
3 pages
CHAPTER - 7 Data Handling - Data Types
PDF
No ratings yet
CHAPTER - 7 Data Handling - Data Types
5 pages
05-Number Data Type
PDF
No ratings yet
05-Number Data Type
2 pages
Datatypes in Python
PDF
No ratings yet
Datatypes in Python
6 pages
13
PDF
No ratings yet
13
1 page
Python - 1 Year - Unit-2-1
PDF
No ratings yet
Python - 1 Year - Unit-2-1
118 pages
Python - Numbers: Var1 1 Var2 10
PDF
No ratings yet
Python - Numbers: Var1 1 Var2 10
6 pages
Class 6 Float Complex Bool
PDF
No ratings yet
Class 6 Float Complex Bool
3 pages
DATA HANDLING in Python
PDF
No ratings yet
DATA HANDLING in Python
18 pages
Data Types
PDF
No ratings yet
Data Types
29 pages
Data Types
PDF
No ratings yet
Data Types
19 pages
13.numbers in Python
PDF
No ratings yet
13.numbers in Python
8 pages
Built in Datatypes
PDF
No ratings yet
Built in Datatypes
36 pages
Numbers in Python
PDF
No ratings yet
Numbers in Python
19 pages
Lesson 5
PDF
No ratings yet
Lesson 5
7 pages
(FA3) - Joseph, Daniel - Casting Booleans
PDF
No ratings yet
(FA3) - Joseph, Daniel - Casting Booleans
6 pages
Python Data Types
PDF
No ratings yet
Python Data Types
21 pages
Python - 1 Year - Unit-2
PDF
No ratings yet
Python - 1 Year - Unit-2
116 pages
L2 - Introduction To Python
PDF
No ratings yet
L2 - Introduction To Python
97 pages
Unit 2
PDF
No ratings yet
Unit 2
16 pages
Q. Explain Various Data Type in Python With The Help of Diagram
PDF
No ratings yet
Q. Explain Various Data Type in Python With The Help of Diagram
80 pages
Python Lesson 3
PDF
No ratings yet
Python Lesson 3
5 pages
Basic Data Types in Python Real Python
PDF
No ratings yet
Basic Data Types in Python Real Python
15 pages
A2 Python Numbers
PDF
No ratings yet
A2 Python Numbers
6 pages
Python M2 2
PDF
No ratings yet
Python M2 2
33 pages
Python Data Types
PDF
No ratings yet
Python Data Types
9 pages
Datatypes
PDF
No ratings yet
Datatypes
4 pages
Python PDF
PDF
No ratings yet
Python PDF
7 pages
Python Objects: After Reading This Chapter, The Reader Will Be Able To
PDF
No ratings yet
Python Objects: After Reading This Chapter, The Reader Will Be Able To
21 pages
Python
PDF
No ratings yet
Python
73 pages
Basic Data Types in Python - Ipynb - Colaboratory
PDF
No ratings yet
Basic Data Types in Python - Ipynb - Colaboratory
5 pages
Python
PDF
No ratings yet
Python
30 pages