0% found this document useful (0 votes)
11 views91 pages

Data Handling

The document provides an overview of Python data types, including numbers, strings, lists, tuples, and dictionaries, along with their characteristics such as mutability and immutability. It explains the differences between mutable types (like lists and dictionaries) and immutable types (like integers and strings), as well as the operators used in Python for various operations. Additionally, it covers the internal workings of variables and objects in Python, including their type, value, and memory address.

Uploaded by

nilesh.ssharma14
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)
11 views91 pages

Data Handling

The document provides an overview of Python data types, including numbers, strings, lists, tuples, and dictionaries, along with their characteristics such as mutability and immutability. It explains the differences between mutable types (like lists and dictionaries) and immutable types (like integers and strings), as well as the operators used in Python for various operations. Additionally, it covers the internal workings of variables and objects in Python, including their type, value, and memory address.

Uploaded by

nilesh.ssharma14
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
You are on page 1/ 91

LEARNING OUTCOMES :

❑ DATATYPES
❑ OPERATORS
❑ MUTABLEAND IMMUTABLE TYPES
❑ EXPRESSION
DATA TYPES
Data type in Python specifies the type of data weare going to store in any variable, the
amount of memoryit will take and type of operation wecan perform on avariable.
Datacanbeofmanytypese.g.character,integer, real, string etc.
Pythonsupportsfollowingdata types:
➢ Numbers ( int, float, complex)
➢ String
➢ List
➢ Tuple
➢ Dictionary
NUMBERS
Fromthe nameit is very clear the Numberdata types are used to store numeric values.
NumbersinPythoncanbeoffollowingtypes:
(i) Integers
a) Integers(signed)
b) Booleans
(ii) Floating point numbers
(iii) ComplexNumbers
INTEGERS
Integersallows tostore wholenumbersonlyandthereis nofractionparts.
Integerscanbepositiveandnegative e.g.100,250,-12,+50
Therearetwointegersin Python:
1) Integers(signed) : it is normalinteger representation of wholenumbers. Integers in
pythoncanbeonanylength,it isonlylimitedbymemory available.InPython3.xint
datatypecanbeusedtostorebigorsmall integervaluewhetherit is+veor –ve.
2) Booleans: it allows to store only two values True and False. The internal value of
booleanvalueTrueandFalseis 1and0resp.Wecanget booleanvaluefrom0and1
usingbool()function.
INTEGERS
>>>bool(1)
True
>>>int(False)
0
>>>str(False)
„False‟ #str() functionis usedtoconvert argumenttostring type.
FLOATING POINT NUMBERS
It allowsto storenumberswithdecimalpoints. Fore.g. 2.14.Thedecimalpoint indicate
thatit isnotanintegerbutafloatvalue.100isanintegerbut100.5 isafloatvalue.In
Previouschapterwehavealreadydiscussedfloatvalues canbeoftype type:
1.FractionalForm: 200.50,0.78,-12.787
2.ExponentForm: it isrepresentedwithmantissaandexponent.For e.g

>>>x= 1.5E2 #means1.5 x 102whichis 150


>>>print(x) #150.0
>>>y=12.78654E04
>>>print(y) #127865.4
FLOATING POINT NUMBERS
Floating point numberare mainly used for storing values like distance, area,
temperature etc. which havea fractional part.
Floating point numbershavetwoadvantage over integers:
✓ they canrepresent values betweentheintegers
✓ they canrepresent amuchgreater rangeof values
Butfloating point numberssuffers from onedisadvantagealso:
✓ Floating point operations are usually slower than integer operations.

In Python floating point numbers represent machine level double


precision floating point numbers i.e. 15 digit precision.
COMPLEX NUMBERS
Python represent complex numbersin the form A+Bj. Torepresent imaginary
numbers,Pythonusesj or J in place of i. Soin Pythonj = and −1. Bothreal
imaginary parts are of typefloat
e.g.
a=0+6j
b=2.5 +3J
>>>a=4+5j
>>>print(a) #(4+5j)
>>>b=0+2j
>>>b #(2j)
COMPLEX NUMBERS
Python allows to retrieve real andimaginary part of complex numberusing
attributes: real andimag
If the complex numberis athen wecanwrite a.real or a.imag
Example
>>>a=1+3.54j
>>>print(a.real) #1.0
>>>print(a.imag) #3.54
STRING
In previous chapter wehave already discussed aboutstring. Let usrecall the things:
1. Stringis acollectionofanyvalid characters in aquotationmarks( „or“ )
2. Eachcharacter ofStringin Pythonis aUnicodecharacter
3.Strings are used to store information like name,address, descriptions. Etc Forexample:
“hello”, „welcome‟,“sales2018”,“[email protected]
STRING
In Python string is asequence of characters andeach character canbe individually access
using index. Frombeginningthe first character in String is at index 0andlast will be
at len-1. Frombackward direction last character will beatindex -1andfirst
character will beat–len.

Forward indexing
0 1 2 3 4 5 6
message W E L C O M E
-7 -6 -5 -4 -3 -2 -1

Backward indexing
STRING
Toaccess individual character of String (Slicing). wecanusethe syntax:
StringName[indexposition]
>>>stream=“Science”
>>>print(stream[0])
S
>>>print(stream[3])
e
>>>print(stream[-1])
e
STRING
Whatwill bethe output:
>>>stream=“Science”

>>>print(stream[5]) #Output1
>>>print(stream[-4]) #Output2
>>>print(stream[-len(stream)]) #Output3
>>>print(stream[8]) #Output4
STRING
Wecannotchangethe individual letters of string byassignment because string in python
is immutable andhenceif wetry to dothis, Python will raise an error “object does
notsupportItemassignment”
>>>name=“Ronaldo”
>>>name[1]=„i‟ #error

Howeverwecanassign string to another string. For e.g


>>>name=“Ronaldo”
>>>name=“Bekham” #noerror
LISTS AND TUPLES
Lists andTuplesare compounddata types i.e. they allows to store multiple values
under onenameof different data types.
Themain difference between Lists andTuplesis List canbe changed/modified i.e.
mutabletypewhereasTuplescannotbechanges or modified i.e. immutable type.
Let ustake this with example:
Lists: Alist in pythonrepresents alist of comma-separated values of any data type
between square brackets.
[10,20,30,40,50]
[„a‟,‟e‟,‟o‟,‟i‟,‟u‟]
[“KV”,208004,97.5]
EXAMPLES -LIST
>>>family=["Mom","Dad","Sis","Bro"]
>>>family
['Mom', 'Dad', 'Sis', 'Bro']
>>>print(family)
['Mom', 'Dad', 'Sis', 'Bro']
>>>Employee=["E001","Naman",50000,10.5]
>>>Employee
['E001', 'Naman', 50000,10.5]
>>>print(Employee)
['E001', 'Naman', 50000, 10.5]
EXAMPLES -LIST
Thevalues stored in List are internally numbered from 0onwards. i.e. first element will beat
position 0andsecondwill beat1andsoon.

>>>Employee=["E001","Naman",50000,10.5]
>>>print(Employee[1])
Naman
>>>Employee[2]=75000
>>>print(Employee)
['E001', 'Naman', 75000, 10.5]
Youcancheckthenumberofitemsin list using len()function
>>>print(len(Employee))
4
TUPLES
Tuplesas those list which cannotbechangedi.e. not modifiable. Tuplesare defined
inside parenthesis and values separated bycomma
Example:
>>>favorites=("Blue","Cricket","Gajar Ka Halwa")
>>>student=(1,"Aman",97.5)
>>>print(favorites)
('Blue', 'Cricket', 'Gajar Ka Halwa')
>>>print(student)
(1, 'Aman',97.5)
TUPLES
LikeList, Tuplesvaluesarealsointernally numberedfrom0andsoon.
>>>print(favorites[1])
Cricket
>>>print(student[2])
97.5

>>> student[2]=99
>>>student[2]=99 #Error, tuple doesnotsupportassignmenti.e. immutable
DICTIONARY
Dictionary is another feature of Python. It is anunordered set of commaseparated
key:value pairs.DictionaryItems aredefinedin CurlyBrackets{ }
Keysdefined in Dictionary cannotbesamei.e. notwokeyscanbesame.
>>>student={'Roll':1,'Name':"Jagga",'Per':91.5}
>>>print(student)
>>>print(student['Per'])
91.5
>>>val={1:100,2:300,4:900} #Keynamecanbestring /numeric
>>>print(val[1])
100
Dictionary is mutable. i.e. Wecanmodifydictionary elements.
>>>val[2]=1000
>>>print(val) #{1: 100, 2: 1000, 4:900}
DATA TYPE SUMMARY

Core Data types

Numbers None Sequences Mappings

Floating
Integers point Complex String Tuple List Dictionary

Boolean
MUTABLE AND IMMUTABLE TYPES
Python data object canbebroadly categorized into twotypes –mutable andimmutable types.In
simplewordschangeable/modifiable andnon-modifiable types.
1. Immutabletypes: are those that cannever changetheir value in place. In python following
typesareimmutable: integers,float, Boolean,strings, tuples
SampleCode:
a= 10
b= a
c =15 #will give output 10,10,30
a=20 From thiscode,youcansaythevalueofintegera,b,c couldbechanged
b=40 effortlessly, but this is notthe case.Let usunderstandwhatwasdone
behindthescene
c =b
IMMUTABLE TYPES
Note: In python each value in memory is assigned a memory address. So each time a new
variable is pointing to that value they will be assigned the same address and no new
memoryallocation.Letusunderstandthecase.

value
10 15 20 21 40 55
address 250 272 280 284 290 312
>>> a=10
a=10
>>> b=a
b= a c
>>> c=15
=15
>>> print(id(a))
1757402304
a b c
>>> print(id(b))
1757402304
Python provides id() function to get the >>> print(id(c))
1757402384
memory address to which value /variable is
IMMUTABLE TYPES
Nowlet usunderstandthe changesdoneto variable a,b,c a=20
b=40
c= b

value
10 15 20 21 40 55
address 250 280 290 312
272 284
>>> a=20
>>> b=40
>>> c=b
>>> print(id(a))
a b 1757402464
c >>> print(id(b))
1757402784
Python provides id() function to get the >>> print(id(c))
memory address to which value /variable is 1757402784
referring
IMMUTABLE TYPES
Fromthe previous code it is clear that variable namesare stored references to a value-object.
Eachtimewechangethevaluethevariable‟sreferencememory addresschanges.Soit will
not store new value in same memory location that‟s why Integer, float, Booleans, strings
andtuplesareimmutable.
Variables (of certain type) are NOT LIKE storage containers i.e. with fixed memory address
wherevaluechangesevery time. Hencetheyare immutable
MUTABLE TYPE
Mutable meansin samememoryaddress, newvalue canbestored asandwhenit is required.
Python provides following mutabletypes:
1. Lists
2. Dictionaries
3. Sets
Examples:(using List)
>>>employee=["E001","Rama","Sales",67000] See, even if we
change the value,
>>>print(id(employee))
its reference
71593896 memory address
>>>employee[3]=75000 has remained
>>>print(id(employee)) same
71593896
>>>
VARIABLE INTERNALS
Pythonis anobject oriented language. Soeverything in pythonis anobject. An object is
any identifiable entity that have some characteristics/properties and behavior. Like
integer values are object – they hold whole numbers only(characteristics) and they
supportall arithmeticoperations(behavior).

Everypythonobjecthasthreekeyattributesassociatedwithit:
1. type of object
2. value of an object
3. id of an object
TYPE OF AN OBJECT
type of anobject determines the operations that canbeperformed onthe object.
Built –in functiontype()returnsthetypeofanobject
Example:
>>>a=100
>>>type(a)
<class'int'>
>>>type(100)
<class'int'>
>>>name="Jaques"
>>>type(name)
<class'str'>
VALUE OF AN OBJECT
Thedata items stored in the object is avalue of object. Thevalue stored in an objectis a
literals. Wecanusingprint() togetthevalueofanobject
Example:
>>>a=100
>>>print(a)
100
>>>name="Kallis"
>>>print(name)
Kallis
>>>
ID OF AN OBJECT
It is thememoryaddressofanyobject.Althoughidis dependentuponthe systemwhere
it is installed but in mostcasesit returns the memorylocation of theobject. Built in
functionid()returnstheidofanobject
Example:
>>>a=5
>>>id(5)
1911018608
>>>print(id(a))
1911018608
>>>
OPERATORS
are symbolthat perform specific operation whenapplied onvariables. Takea
look at the expression: (Operator)

10 + 25 (Operands)

Abovestatement is anexpression (combination of operator and operands)

i.e. operator operates on operand. some operator requires two


operandandsomerequires onlyoneoperandto operate
TYPES OF OPERATORS -ARITHMETIC
BinaryOperators:arethoseoperators thatrequiretwooperandtooperateupon.
Following are someBinaryoperators:

Operator Action
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder
** Exponent
// Floor division
TYPES OF OPERATORS -ARITHMETIC
UnaryOperatorsTheyrequire only oneoperand to operate like unary+and– Fore.g.
>>>a=5
>>>print(+a)
5
>>>print(-a)
-5
>>>
EXAMPLE – BINARY ARITHMETIC OPERATOR
>>>num1=20
>>>num2=7
>>>val =num1%num2
>>>print(val)
6
>>>val = 2**4
>>>print(val)
16
EXAMPLE – BINARY ARITHMETIC OPERATOR
>>>val =num1/ num2
>>>print(val)
2.857142857142857
>>>val =num1// num2
>>>print(val)
2
JUST A MINUTE…
Whatwill bethe output of following code

>>>a,b,c,d =13.2,20,50.0,49
>>>print(a/4)
>>>print(a//4)
>>>print(20**3)
>>>print(b**3)
>>>print(c//6)
>>>print(d%5)
>>>print(d%100)
TYPES OF OPERATORS –AUGMENTED
ASSIGNMENT OPERATORS
It perform operation with LHSandRHSandresult will beassignedto LSH

Operator Action Example


+= RHS added to LHS and result assigned to LHS x+=5 means x=x+5
-= RHS minus to LHS and result assigned to LHS x-=5 means x=x-5
*= RHS multiply to LHS and result assigned to LHS x*=5 means x=x*5
/= LHS divided by RHS and result assigned to x/=5 means x=x/5
LHS(FLOAT)
%= LHS divided by RHS and remainder assigned to LHS x%=5 means x=x%5
**= RHS power to LHS and result assigned to LHS x**=5 meansx=x**5
//= LHS divided by RHS and result assigned to LHS (INT) x//=5 means x=x//5
TYPES OF OPERATORS –RELATIONAL OPERATOR
Are used to comparetwo values andreturn the result as Trueor Falsedepending uponthe
result of comparison
Operator Action Example
< Less than 50<45 returns False, 40<60 returnsTrue
> Greater than 50>45 returns True, 40>60 returns False
<= Less than or equal to 50<=50 returns True, 80<=70 returnsFalse
>= Greater than or equal to 40>=40 returns True, 40>=90 returns False
== Equal to 80==80 returns True, 60==80 returnsFalse
!= Not equal to 45!=90 returns True, 80!=80 returns False
FEW POINTS TO REMEMBER -COMPARISONS
✓ For numeric types, the values are compared after removing trailing zeros after decimal
pointfromfloatingpointnumber.Forexample6and6.0willbetreated asequal.
✓ Capitalletters(ASCIIcode65-90)areconsideredaslessthansmallletters (ASCIIcode97-
122).
✓ >>>‟Hello‟<„hello‟ #willgiveresult true
✓ In string be careful while comparison, because special characters are also assigned to
someASCIIcode.LikeASCIIcodeofspaceis 32,Enteris 13.
✓ >>>‟Hello‟==„Hello‟#false,becausethereisspacebeforeHinsecondstring
✓ Like other programming language, In Python also we have to be very careful while
comparing floating value because it maygives you unexpected result. So it is suggested
nottouseequalitytestingwithfloating values.
COMPARISON WITH FLOATING VALUES
>>>0.1 +0.1+ 0.1 ==0.3
Will return False
How?
Let uscheckthe value of0.1+0.1+0.1
>>>print(0.1+0.1+0.1)
Output:- 0.30000000000000004
That‟swhy0.1 +0.1+ 0.1 ==0.3 is False
Reason: In python floating numbersare approximately presented in memory in binary form
up to the allowed precision 15 digit. This approximation mayyield unexpected result if
youarecomparingfloatingvalueusing equality
RELATIONAL OPERATOR WITH ARITHMETICOPERATORS

Relational operator have lower priority than arithmetic operators, So if any arithmetic
operator is involved with relational operator then first arithmetic operation will be
solvedthencomparison.
Forexample
>>>a,b,c= 10,20,30
>>>a+10> b-10
Result: True
HereComparisonwillbe20>10
WHAT IS THEDIFFERENCE?
If thevalueofais 100, Whatis thedifference betweenthebelow2statements
Statement 1: >>>a== 60
Statement 2: >>>a= 60
IDENTITY OPERATOR
These operators are used to checkif both object are pointing to samememory address
or not.

Operator Usage Description


is a is b Return True, if both operands are pointing to
same memory location, otherwise False
is not a is not b Return True, if both operands are not pointing
to same memory location, otherwise False
EXAMPLE OF IDENTITY OPERATORS
>>>a= 10
>>>b= 10
>>>c = 20
>>>ais b #True #
>>>ais c False #
>>>ais not c True
>>>c -=10
>>>ais c #True
EQUALITY(==) VS IDENTITY(IS)
Whenwecomparetwo variables pointing to samevalue, then both Equality (==) and
identity (is) will return True.
>>>a,b =10, 10
>>>a==b #True
>>>ais b #True

But in few cases, whentwo variables are pointing to samevalue ==will return Trueand
is will return False
EXAMPLE
>>>s1=„kvoef‟
>>>s2=input(„EnteranyString‟)
Enter anyString: kvoef
>>>s1==s2 #True #
>>>s1 is s2 False
>>>s3=„kvoef‟
>>>s1is s3 #True
FEW CASES-PYTHON CREATES TWODIFFERENT
OBJECT THAT STORE THE SAME VALUE
❑ Input of String from the console
❑ Dealing with large integer value
❑ Dealing with floating point andcomplexliterals
LOGICAL VALUE – ASSOCIATION WITH OTHER TYPE
In pythonevery value is associated with Booleanvalue Trueor False. Let us Seewhich
values are True andFalse

False values True values


None
False All other values are
considered as true
Zero (0)
Empty Sequence “ “, [], (),{}
LOGICAL OPERATORS

Python supports 3logical operators : and, or,not

or operator : it combines2expressions, whichmakeits operand.Theor


operator works in 2 ways:
(i) Relational expression as operand
(ii) Numbers or string or lists asoperand
RELATIONAL EXPRESSION AS OPERANDS
When relational expression is used as operand then or operator return True if any
expressionis True.If bothareFalsethenonly or operatorwill return False.

>>>(5>6) or (6>5) #True #


>>>(4==4) or (7==9) True #
>>>(6!=6) or (7>100 False
NUMBERS/STRINGS AS OPERANDS
When numbers/strings are used as operand then output will be based on the internal
Booleanvalueofnumber/string.TheresultwillnotbetheTrueor Falsebutthevalue
usedwith or.Howeverinternalvalueofresult willbe Trueor False.

>>>(0) or (0) #0
>>>(0) or (10) #10
>>>(4) or (0.0) #4 >>> 20>10 or 8/0 >5
>>>„kv‟or „‟ #kv >>> 20<10 or 8/0 >5
>>>(9) or (7) #9
>>>„abc‟or „xyz‟ #abc
andoperators: it combines 2expressions, which makeits operand. Theand operator
works in 2 ways:
(i) Relational expression as operand
(ii) Numbers or string or lists as operand
RELATIONAL EXPRESSION AS OPERANDS
When relational expression is used as operand then and operator return True if both
expressionsareTrue.If anyexpressionis Falsethen andoperator will returnFalse.

>>>(8>6) and (6>5) #True #


>>>(4==4) and (7==9) False #
>>>(7!=6) and (10+10>18) True
NUMBERS/STRINGS AS OPERANDS
When numbers/strings are used as operand then output will be based on the internal
Booleanvalueofnumber/string.TheresultwillnotbetheTrueor False,butthevalue
usedwith and.Howeverinternalvalueofresultwill be Trueor False.

>>>(0) and (0) #0


>>>(0) and (10) #0
>>>(4) and (0.0) #0 >>> 20<10 and 8/0 >5
>>>„kv‟and „‟ # „‟ >>> 20>10 or 8/0 >5
>>>(9) and (7) #7
>>>„abc‟and „xyz‟ #xyz
CHAINED COMPARISON
Python can chain multiple comparisons which are like shortened version of larger Boolean
expressions.Inpythonratherthanwriting10<20and20<30,youcan evenwrite10<20<30,
whichis chainedversionof10<20and20<30.
Supposeyouwanttocheckageisgreaterthanorequalto13andlessthanor
equalto19thenyoucanwriteusingchainofconditionlike:
13<=age<=19

Supposeyouwantto checkAisgreater thanBandC,youcanwrite usingchainof


conditionlike:
B<=A>=C
BITWISE OPERATORS
Python provides another category of operators –Bitwise operators. Similar to logical
operators exceptit works onbinary representation of actual data not onits decimal
value.
Operators Operations Use Description
& Bitwise and Op1 & Op2 It compares two bits and generate
a result of 1 if both bits are 1;
otherwise it return 0
| Bitwise or Op1 | Op2 It compares two bits and generate
a result of 1 if any bits are 1;
otherwise it return 0
^ Bitwise xor Op1 ^ Op2 It compares two bits and generate
a result of 1 if either bit is 1;
otherwise if both Operand are 1 or
0 it will return False
~ Bitwise ~Op1 The Compliment operator is used
compliment to invert all of the bits of the
operand
EXAMPLES -&
>>>a= 10
>>>b= 12
>>>bin(a) # 0b1010
>>>bin(b) #0b1100 #
>>>a& b 8
>>>bin(a & b) #0b1000
EXAMPLES -|
>>>a= 10
>>>b= 12
>>>bin(a) # 0b1010
>>>bin(b) #0b1100 #
>>>a| b 8
>>>bin(a & b) #0b1110
EXAMPLES -^
>>>a= 10
>>>b= 12
>>>bin(a) # 0b1010
>>>bin(b) #0b1100 #
>>>a^ b 6
>>>bin(a & b) #0b0110
EXAMPLES -~
>>>a= 10
>>>b= 12
>>>bin(a) # 0b1010
>>>bin(b) #0b1100 #
>>>~a -11
Reason:-
First the binary of ai.e. 10is 1010,nowusing ~operator it will invert all the bits so bits
will be0101, NowPython will find 2‟scompliment of bits as: 1011 andresult will be
-ve
OPERATOR PRECEDENCE
Operators Description Associativity
() Parenthesis Left-to-right
** Exponent Right-to-left
~x Bitwise compliment Left-to-right

+x, -x Positive or negative Left-to-right


*, /, / / , % Arithmetic operator Left-to-right
+, - Add, Sub Left-to-right
& Bitwise & Left-to-right
^ Bitwise XOR Left-to-right
| Bitwise OR Left-to-right
<,<=,>,>=,<>,!=,==, is, is not Comparison & Identity Left-to-right
not x Boolean Not Left-to-right
and Boolean AND Left-to-right
or Boolean OR Left-to-right
ASSOCIATIVITY OF OPERATORS
It is the order in which anexpression havingmultiple operators of same precedenceis
evaluated. Almost all operators have left-to-right associativity exceptexponential
operator whichhas right-to-left associativity.
For example if anexpression contains multiplication, division andmodulus then
they will beevaluated from left to right. Takealook onexample:
>>>8* 9/11//2
>>>(((8*9) / 11)//2)
>>>8* ((9/11)//2)
>>>8* (40/ (11//2))
ASSOCIATIVITY OF OPERATORS
It is the order in which anexpression havingmultiple operators of same precedenceis
evaluated. Almost all operators haveleft-to-right associativity exceptexponential
operator whichhasright-to-left associativity.
For example if anexpression contains multiplication, division andmodulus then
they will beevaluated from left to right. Takealook onexample:
>>>8* 9/11//2 3.0

>>>(((8*9) / 11)// 2)
>>>8* ((9/11)//2)
>>>8* (40/ (11//2))
ASSOCIATIVITY OF OPERATORS
It is the order in which anexpression havingmultiple operators of same precedenceis
evaluated. Almost all operators haveleft-to-right associativity exceptexponential
operator whichhasright-to-left associativity.
For example if anexpression contains multiplication, division andmodulus then
they will beevaluated from left to right. Takealook onexample:
>>>8* 9/11//2 3.0

>>>(((8*9) / 11)// 2) 3.0


>>>8* ((9/11)//2)
>>>8* (40/ (11//2))
ASSOCIATIVITY OF OPERATORS
It is the order in which anexpression havingmultiple operators of same precedenceis
evaluated. Almost all operators haveleft-to-right associativity exceptexponential
operator whichhasright-to-left associativity.
For example if anexpression contains multiplication, division andmodulus then
they will beevaluated from left to right. Takealook onexample:
>>>8* 9/11//2 3.0

>>>(((8*9) / 11)// 2) 3.0


>>>8* ((9/11)//2) 0.0
>>>8* (40/ (11//2))
ASSOCIATIVITY OF OPERATORS
It is the order in which anexpression havingmultiple operators of same precedenceis
evaluated. Almost all operators haveleft-to-right associativity exceptexponential
operator whichhasright-to-left associativity.
For example if anexpression contains multiplication, division andmodulus then
they will beevaluated from left to right. Takealook onexample:
>>>8* 9/11//2 3.0

>>>(((8*9) / 11)// 2) 3.0


>>>8* ((9/11)//2) 0.0
>>>8* (40/ (11//2)) 64.0
ASSOCIATIVITY OF OPERATORS
Anexpression havingmultiple ** operator is evaluated from right to left. i.e. 3** 4
** 2will beevaluatedas3** (4** 2)not(3**4)** 2
Guessthe output
>>>3** 4** 2
>>>3** (4 ** 2)
>>>(3**4) ** 2
ASSOCIATIVITY OF OPERATORS
Anexpression havingmultiple ** operator is evaluated from right to left. i.e. 3** 4
** 2will beevaluatedas3** (4** 2)not(3**4)** 2
Guessthe output
>>>3** 4** 2 43046721

>>>3** (4 ** 2)
>>>(3**4) ** 2
ASSOCIATIVITY OF OPERATORS
Anexpression havingmultiple ** operator is evaluated from right to left. i.e. 3** 4
** 2will beevaluatedas3** (4** 2)not(3**4)** 2
Guessthe output
>>>3** 4** 2 43046721

>>>3** (4 ** 2) 43046721
>>>(3**4) ** 2
ASSOCIATIVITY OF OPERATORS
Anexpression havingmultiple ** operator is evaluated from right to left. i.e. 3** 4
** 2will beevaluatedas3** (4** 2)not(3**4)** 2
Guessthe output
>>>3** 4** 2 43046721

>>>3** (4 ** 2) 43046721
>>>(3**4) ** 2
6561
EXPRESSION
Wehave already discussed onexpression that is acombinationof operators, literals
andvariables (operand).
TheexpressioninPythoncanbeofanytype:
1) Arithmetic expressions
2) Stringexpressions
3) Relational expressions
4) Logicalexpressions
5) Compoundexpressions
ARITHMETIC EXPRESSION
10+ 20
30%10

RELATIONAL EXPRESSION
X>Y
X<Y<Z
LOGICAL EXPRESSION
aor b
not aandnot b
x>yandy>z

STRING EXPRESSION
>>>“python” + “programming” #pythonprogramming
>>>“python” * 3 #pythonpythonpython
EVALUATING EXPRESSION -ARITHMETIC
❑ Executedbasedontheoperatorprecedenceandassociativity
❑ Implicit conversion takes place if mixed type is used in expression

IMPLICIT CONVERSION (COERCION)


An implicit conversion is a conversion performed by the interpreter without
programmer‟s intervention. It is applied generally whenever differing types are
intermixedin anexpression, soasnottoloseinformation.
The rule is very simple, Python convert all operands up to the type of the largest
operand(typepromotion)
IMPLICIT CONVERSION (COERCION)
If both arguments are standard numeric types, the following coercions are
applied:
➢ If either argumentis acomplex number,the other is converted to complex
➢ Otherwise, if either aargumentis afloating number,the other is converted to
floating point
➢ Noconversion if both operand areintegers
EXAMPLE – OUTPUT?
n1=10
n2=5
n4=10.0
n5=41.0
A=(n1+n2)/n4
B=n5/n4* n1/2
print(A) print(B)
EXAMPLE – OUTPUT?
n1=10
n2=5
n4=10.0
n5=41.0
A=(n1+n2)/n4
B=n5/n4* n1/2
print(A) print(B) 1.5
EXAMPLE – OUTPUT?
n1=10
n2=5
n4=10.0
n5=41.0
A=(n1+n2)/n4
B=n5/n4* n1/2
print(A) print(B) 1.5

20.5
FIND THE OUTPUT?
a) a,b =10,5
c =b / a

b) a,b =10,5 c
=b// a

c) a,b =10,5 c
=b%a
EVALUATING EXPRESSION -RELATIONAL
❑ Executedbasedontheoperatorprecedenceandassociativity
❑ All relational expression yield Booleanvalue True, False
❑ forchainedcomparisonlike –x<y<zis equivalenttox<yandy<z

OUTPUT?
If inputsare
(i) a,b,c =20,42,42 (ii) a,b,c =42, 20,20
print(a<b)
print(b<=c)
print(a>b<=c)
EVALUATING EXPRESSION -LOGICAL
❑ Executedbasedonthe operator precedenceandassociativity
❑ Executedin the order of not, and, or
❑ Logical operatorsare short-circuit operators

OUTPUT?
(10<20)and(20<10)or(5<7)andnot7<10and6<7<8
TYPE CASTING
Wehavelearntinearliersectionthatinanexpressionwithmixedtypes,Python internally
changes the type of some operands so that all operands have same data type. This
type of conversion is automatic i.e. implicit conversion without programmer‟s
intervention
Anexplicit typeconversion is user-defined conversion that forces an expressionto beof
specifictype.Thistypeofexplicitconversionisalso knownasTypeCasting.
Remember, in case of input() with numeric type, whatever input is given to
input() is of string type and to use it as a number we have to convert it
to integer using int() function. It is an explicit conversion or Type
Casting.
Syntax:- datatype(expression)
TYPE CASTING -EXAMPLES
>>>num1=int(input(“Enter anynumber “))
d=float(a) #if ais of int type then it will beconverted to float
OUTPUT
(i) int(17.8) #7
(ii) int(“20”) #20
(iii) float(17) #17.0
(iv) complex(17) #17+0j
(v) complex(2,7) #2+7j #
(vi) str(13) „13‟
(vii) str(0o19) #„17‟
(viii) bool(0) #False
(ix) bool(„a‟) #True
MATH MODULE OF PYTON
Other than build-in function, Python provides many more function through modules in
standard library. Python provides math library that works with all numeric types
exceptforcomplexnumbers
Tousestandard mathlibrary wehave to import the library in our python programusing
import statement

importmath

math library contains many functions to perform mathematical operations like finding
squarerootofnumber,logofnumber,trigonometric functionsetc.
SOME MATHEMATICAL FUNCTION
S.No Function Prototype Description Example
1 ceil() math.ceil(num) It returns the number math.ceil(2.3
rounded to next integer ) Ans- 3
2 floor() math.floor(num) It returns the number math.floor(2.3
rounded to previous integer ) Ans- 2
3 fabs() math.fabs(num) Returns the absolute value math.fabs(-
i.e. number without sign 4) Ans – 4
4 pow() math.pow(b,e) Return the value of (b)e math.pow(2.3)
Ans- 8
5 sqrt() math.sqrt(num) It returns the square root of math.sqrt(144
number ) Ans- 12
6 sin() math.sin(num) Returns the sin value of math.sin(math
number . radian(90))
Ans- 1.0
7 exp() math.exp(num) Returns natural logarithm e math.exp(2)
raised to the num Ans- 7.3890..
SOME MATHEMATICAL FUNCTION
ThemathmoduleofPythonalsocontains twousefulconstant piande

math.pi gives youthe value of constant π= 3.141592…


math.e givesyouthevalueofconstant e=2.718281
So, while writing anyformula whichuses the constant pi youcanuse math.pi, like
area =math.pi* radius* radius
VALID ARITHMETIC EXPRESSION USING MATH
LIBRARY
(i) math.pow(8/4,2)
(ii) math.sqrt(4*4+2*2+3*3)
(iii) 2+math.ceil(7.03)

INVALID ARITHMETIC EXPRESSION

(i) 20+/4
(ii) 2(l+b)
(iii) math.pow(0,-1)
(iv) math.log(-5)+4/2
WRITE THE CORRESPONDING PYTHON EXPRESSION FOR THE
FOLLOWING MATHEMATICALEXPRESSION

(i) 𝑎 2 + 𝑏2 + 𝑐2
(ii) 2–ye2y+ 4y

(iii) P+ 4
𝑟+ 𝑠
(iv) (cos x / tan x) + x
(v) | e2–x |
JUST A MINUTE…
(i) Whatare data types?Whatare pythonbuilt-in datatypes
(ii) Whichdata type of pythonhandlesNumbers?
(iii) WhyBooleanconsideredasubtypeof integer?
(iv) Identify the data types of the values:
5, 5j, 10.6, „100‟,“100”, 2+4j, [10,20,30], (“a”,”b”,”c”), {1:100,2:200}
(v)Whatis the difference between mutable andimmutable data type? Give nameof
onedatatypebelongingtoeachcategory
(vi) Whatis the difference in output of the following?
print(len(str(19//4)))
print(len(str(19/4))
JUST A MINUTE…
(vii) Whatwill bethe output producedbythese?
12/4 14//14 14%4 14.0/4 14.0//4 14.0%4
(viii) Given two variable NMis boundto string “Malala” (NM=“Malala”). Whatwill bethe
output producedbyfollowing two statement if the input given is “Malala”?Why?
MM=input(“Enter name:”)
Enter name: Malala
(a) NM==MM (b) NMisMM
JUST A MINUTE…
(ix) Whatwill bethe output of following code? Why
(i) 25or len(25)
(ii) len(25) or 25
(x) Whatwill bethe output if input for both statement is 6+8/ 2 10==
input(“Enter value 1:”)
10==int(input(“Enter value 2:”)
(xi)WAPto take two input DAYandMONTHandthen calculate whichdayof the year the
given date is. For simplicity take monthof 30daysfor all. For e.g. if the DAYis 5and
MONTHis 3then output shouldbe“Day of year is : 65”

You might also like