Data Handling
Data Handling
❑ 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
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
>>>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
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)
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
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.
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
>>>(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*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
>>>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
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
(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”