Datatypes in Python
Datatypes in Python
❑ 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.
[Link],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 nofraction parts.
Integerscanbepositiveandnegative e.g.100,250,-12,+50
Therearetwointegersin Python:
1) Integers(signed) : it is normalinteger representation of wholenumbers. Integers in
pythoncanbeonanylength,it isonlylimitedbymemory [Link]
datatypecanbeusedtostorebigorsmall integervaluewhetherit is+veor –ve.
2) Booleans: it allows to store only two values True and False. The internal value of
booleanvalueTrueandFalseis [Link] 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. [Link] indicate
thatit isnotanintegerbutafloatvalue.100isanintegerbut100.5 [Link]
Previouschapterwehavealreadydiscussedfloatvalues canbeoftype type:
[Link]: 200.50,0.78,-12.787
[Link]: it [Link] 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). wecanuse the 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 thoselist 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 [Link] 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 [Link]
simplewordschangeable/modifiableandnon-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 [Link] 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
[Link].
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 [Link] 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. Soevery thing 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
supportallarithmeticoperations(behavior).
Everypythonobjecthasthreekeyattributesassociatedwithit:
1. typeof 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 [Link] dependentuponthe systemwhere
it is installed but in mostcases it returns the memorylocation of the object. 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)
JUST A MINUTE…
Whatwill bethe outputof followingcode
>>>x,y=-8,-15
>>>print(x//3)
>>>print(8/-3)
->>>print(8//-3)
JUST A MINUTE…
Whatwill bethe outputof followingcode
>>>x,y=-8,-15
>>>print(x//3) -3
>>>print(8/-3)
->>>print(8//-3)
JUST A MINUTE…
Whatwill bethe outputof followingcode
>>>x,y=-8,-15
>>>print(x//3) -3
>>>print(8/-3)
-2.66665
->>>print(8//-3)
JUST A MINUTE…
Whatwill bethe outputof followingcode
>>>x,y=-8,-15
>>>print(x//3) -3
>>>print(8/-3)
-2.66665
->>>print(8//-3)
--3
JUST A MINUTE…
Whatwill bethe outputof followingcode
>>>-11// 5
>>>-11%5
>>>11%-5
>>>11//-5
JUST A MINUTE…
Whatwill bethe outputof followingcode
>>>-11// 5 -3
>>>-11%5
>>>11%-5
>>>11//-5
JUST A MINUTE…
Whatwill bethe outputof followingcode
>>>-11// 5 -3
>>>-11%5 4
>>>11%-5
>>>11//-5
JUST A MINUTE…
Whatwill bethe outputof followingcode
>>>-11// 5 -3
>>>-11%5 4
>>>11%-5 -4
>>>11//-5
JUST A MINUTE…
Whatwill bethe outputof followingcode
>>>-11// 5 -3
>>>-11%5 4
>>>11%-5 -4
>>>11//-5
-4
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
[Link] 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
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
for more updates visit: [Link]
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
for more updates visit: [Link]
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
for more updates visit: [Link]
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
for more updates visit: [Link]
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
for more updates visit: [Link]
ARITHMETIC EXPRESSION
10+ 20
30%10
RELATIONAL EXPRESSION
X>Y
X<Y<Z
for more updates visit: [Link]
LOGICAL EXPRESSION
aor b
not aandnot b
x>yandy>z
STRING EXPRESSION
>>>“python” + “programming” #pythonprogramming
>>>“python” * 3 #pythonpythonpython
for more updates visit: [Link]
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)
for more updates visit: [Link]
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
for more updates visit: [Link]
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
for more updates visit: [Link]
b) a,b =10,5 c
=b// a
c) a,b =10,5 c
=b%a
for more updates visit: [Link]
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)
for more updates visit: [Link]
OUTPUT?
(10<20)and(20<10)or(5<7)andnot7<10and6<7<8
for more updates visit: [Link]
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
[Link] 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)
for more updates visit: [Link]
importmath
math library contains many functions to perform mathematical operations like finding
squarerootofnumber,logofnumber,trigonometric functionsetc.
for more updates visit: [Link]
(i) 20+/4
(ii) 2(l+b)
(iii) [Link](0,-1)
(iv) [Link](-5)+4/2
for more updates visit: [Link]
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 |
for more updates visit: [Link]
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))
for more updates visit: [Link]
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
for more updates visit: [Link]
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”