2.Data Handling
2.Data Handling
OUTCOMES :
DATA TYPES
OPERATORS
MUTABLE AND IMMUTABLE TYPES
EXPRESSION
DATA
TYPES
Data type in Python specifies the type of data we are going to
store in any variable, the amount of memory it will take and
type of operation we can perform on a variable. Data can be
of many types e.g. character, integer, real, string etc.
Python supports following data types:
Numbers ( int, float, complex)
String
List
Tuple
Dictionary
NUMBER
S
From the name it is very clear the Number data types are used
to store numeric values. Numbers in Python can be of
(i) following
Integers types:
a) Integers(signed)
b) Booleans
(ii Floating point
) numbers
(iii Complex Numbers
)
INTEGER
S
Integers allows to store whole numbers only and there is no
fraction parts.
Integers can be positive and negative e.g. 100, 250, -12, +50
There are two integers in Python:
1) Integers(signed) : it is normal integer representation of whole
numbers. Integers in python can be on any length, it is only
limited by memory available. In Python 3.x int data type can
be used to store big or small integer value whether it is
+ve or – ve.
2) Booleans: it allows to store only two values True and False. The
internal value of boolean value True and False is 1 and 0
resp. We can get boolean value from 0 and 1 using
bool() function.
INTEGER
S
>>>boo
l(1) True
>>>int(F
alse) 0
>>>str(Fal
se) # str() function is used to convert
„False‟ argument to string type.
FLOATING POINT
NUMBERS
It allows to store numbers with decimal points. For e.g. 2.14. The
decimal point indicate that it is not an integer but a float
value. 100 is an integer but 100.5 is a float value. In Previous
chapter we have already discussed float values can be of
type type:
1. Fractional Form : 200.50, 0.78, -12.787
2.
>>>xExponent it means
= 1.5E2 Form : # is represented
1.5 x 102with mantissa and
exponent. For e.g which is 150
>>>print(x)
>>>y=12.7865 # 150.0
4E04 #
>>>print(y) 127865.
4
FLOATING POINT
NUMBERS
Floating point number are mainly used for storing values like
distance, area, temperature etc. which have a fractional
part.
Floating point numbers have two advantage over integers:
they can represent values between the integers
they can represent a much greater range of values
But floating point numbers suffers from one disadvantage also:
Floating point operations are usually slower than integer
operations.
Backward
indexing
STRIN
G
To access individual character of String (Slicing). we can
use the syntax:
StringName[index position]
>>>stream=“Science”
>>>print(strea
m[0]) S
>>>print(strea
m[3]) e
>>>print(strea
m[-1]) e
STRIN
G
What will be the
output:
>>>stream=“Science”
>>>print(stream[5]) #Outpu
>>>print(stream[-4]) t1
>>>print(stream[- #Outpu
len(stream)]) t2
>>>print(stream[8]) #Outpu
t3
#Outpu
t4
STRIN
G
We cannot change the individual letters of string by assignment
because string in python is immutable and hence if we try to
do this, Python will raise an error “object does not support
Item assignment”
>>>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]
You can check the number of items in list using len() function
>>> print(len(Employee))
4
TUPLE
S
Tuples as those list which cannot be changed i.e. not
modifiable. Tuples are defined inside parenthesis and
values separated by comma
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)
TUPLE
S
Like List, Tuples values are also internally numbered from 0 and so
on.
>>>
print(favorites[1]
) Cricket
>>>
print(student[2])
97.5
>>> student[2]=99
>>> student[2]=99 # Error, tuple does not support assignment
i.e. immutable
DICTIONA
Dictionary is another feature of Python. It is an unordered set of
RY
comma separated
key:value pairs. Dictionary Items are defined in Curly
Brackets { }
Keys defined in Dictionary cannot be same i.e. no two keys can be
same.
>>> student={'Roll':1,'Name':"Jagga",'Per':91.5}
>>>print(student)
>>> # Key name can be string /
>>> print(student['Per'])
val={1:100,2:300,4:90 numeric
91.5
0}
>>> print(val[1])
Dictionary is mutable. i.e. We can modify dictionary
100
elements.
>>>val[2]=1000
>>>print(val) # {1: 100, 2: 1000, 4: 900}
DATA TYPE
SUMMARY
Core Data
types
Boolea
n
MUTABLE AND IMMUTABLE
TYPES
Python data object can be broadly categorized into two types –
mutable and immutable types. In simple words
changeable/modifiable and non-modifiable types.
1. Immutable types: are those that can never change their value in
place. In python following types are immutable: integers, float,
Boolean, strings, tuples
Sample Code:
a = 10
c= # will give output
b =15a 10,10,30
From this code, you can say the value of integer a, b,c
a= could be changed effortlessly, but this is not the case.
20 Let us understand what was done behind the
b= scene
40
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 memory allocation. Let us
understand the case.
valu
e
10 15 20 21 40 55
addres 250 27 28 284 290 312
s 2 0
>>> a=10
a=
>>> b=a
10
>>> c=15
b=a
>>>
c=
print(id(a))
15 a b c
1757402304
>>>
Python provides id() function to print(id(b))
get theaddress to which value 1757402304
memory
>>>
/variable is
print(id(c))
IMMUTABLE TYPES
Now let us understand the changes done to a = 20
variable a, b,c b = 40
c=b
valu
e
10 15 20 21 40 55
addres 250 272 280 284 290 312
272 284
s
>>> a=20
>>> b=40
>>> c=b
>>>
a b print(id(a))
c 1757402464
>>>
Python provides id() function to print(id(b))
get the memory address to which 1757402784
value /variable referring
is >>>
print(id(c))
IMMUTABLE
TYPES
From the previous code it is clear that variable names are stored
references to a value-object. Each time we change the value the
variable‟s reference memory address changes. So it will not store
new value in same memory location that‟s why Integer, float,
Booleans, strings and tuples are immutable.
Variables (of certain type) are NOT LIKE storage containers i.e. with fixed
memory address where value changes every time. Hence they are
immutable
MUTABLE
TYPE
Mutable means in same memory address, new value can be stored
as and when it is required. Python provides following mutable
types:
1. Lists
2. Dictionaries
3. Sets (using List)
Examples:
>>> See, even if
employee=["E001","Rama","Sales",6700 we change
0] the value, its
reference
>>> print(id(employee)) memory
71593896 address has
>>> employee[3]=75000 remained
>>> print(id(employee)) same
71593896
>>>
VARIABLE
INTERNALS
Python is an object oriented language. So every thing in python is
an object. 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 support all arithmetic operations (behavior).
Every python object has three key attributes associated with it:
1. type of object
2. value of an object
3. id of an object
TYPE OF AN
OBJECT
type of an object determines the operations that can be performed
on the object.
Built – in function type() returns the type of an object
Example:
>>> a=100
>>> type(a)
<class 'int'>
>>> type(100)
<class 'int'>
>>> name="Jaques"
>>> type(name)
<class 'str'>
VALUE OF AN
OBJECT
The data items stored in the object is a value of object. The
value stored in an object is a literals. We can using print() to
get the value of an object
Example:
>>> a=100
>>> print(a)
100
>>> name="Kallis"
>>> print(name)
Kallis
>>>
ID OF AN
OBJECT
It is the memory address of any object. Although id is dependent
upon the system where it is installed but in most cases it
returns the memory location of the object. Built in function
id() returns the id of an object
Example:
>>> a=5
>>> id(5)
1911018608
>>> print(id(a))
1911018608
>>>
OPERATOR
S
are symbol that perform specific operation when applied on
variables.
look atTake
the a (Operator)
expression:
10 + 25
(Operands)
Suppose you want to check A is greater than B and C, you can write
using chain of
condition like:
B<=A>=C
BITWISE OPERATORS
Python provides another category of operators – Bitwise
operators. Similar to logical operators except it works on
binary representation of actual data not on its decimal
value. Operations
Operators 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
compliment used to invert all of the
bits of the operand
EXAMPLES -
&
>>> a =
10
>>> b = #
12
0b101
>>>
bin(a) 0
>>> #0b110
bin(b) 0 #8
>>> a & #
b 0b100
>>> bin(a 0
& b)
EXAMPLES -
|
>>> a =
10
>>> b = #
12
0b101
>>>
bin(a) 0
>>> #0b110
bin(b) 0 #8
>>> a | b #
>>> bin(a 0b111
& b) 0
EXAMPLES -
^
>>> a =
10
>>> b = #
12
0b101
>>>
bin(a) 0
>>> #0b110
bin(b) 0 #6
>>> a ^ #
b 0b011
>>> bin(a 0
& b)
EXAMPLES -
~
>>> a
= 10
>>> b #
= 12
0b101
>>>
bin(a) 0
>>> #0b110
0 is#
First the binary of a i.e. 10
bin(b) - now using ~ operator it will
1010,
>>> invert all the bits so bits
11 will be 0101 , Now Python will find
2‟s compliment of bits as : 1011 and result will be -ve
~a
Reason
:-
OPERATOR
PRECEDENCE
Operators Description Associativity
() Parenthesis Left-to-right
** Exponent Right-to-left
~x Bitwise compliment Left-to-right
RELATIONAL
EXPRESSION
X>Y
X<Y<Z
LOGICAL
EXPRESSION
a or b
not a and
not b x>y
and y>z
STRING
EXPRESSION
>>> “python” + #pythonprogram
“programming” ming
>>> “python” * 3 #pythonpythonpy
thon
EVALUATING EXPRESSION -
ARITHMETIC
Executed based on the operator precedence and associativity
Implicit conversion takes place if mixed type is used in
expression
b)
a,b =
10,5 c
= b // a
c)
a,b =
10,5 c
=b%
EVALUATING EXPRESSION -
RELATIONAL
Executed based on the operator precedence and
associativity
All relational expression yield Boolean value True,
False
for chained comparison like – x<y<z is equivalent
to x<y and y<z
(i) a,b,c = (ii) a,b,c = 42,
OUTPUT?
20,42,42 20,20
If inputs are
print(a<
b)
print(b<
=c)
print(a>
b<=c)
EVALUATING EXPRESSION -
LOGICAL
Executed based on the operator precedence and
associativity
Executed in the order of not, and , or
Logical operators are short-circuit
operators
OUTPUT?
(10<20) and (20<10) or (5<7) and not 7<10
and 6<7<8
TYPE
CASTING
We have learnt in earlier section that in an expression with mixed
types, 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
An explicit type conversion is user-defined conversion that forces
an expression to be of specific type. This type of explicit
conversion is also known as Type Casting.
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 any number “))
d = float(a) # if a is of int type then it will be
converted to float
OUTPUT
(i) int(17.8) #7
(ii) int(“20”) # 20
(iii float(17) # 17.0
) complex(1 # 17
(iv 7) + 0j
)
complex( #2+
(v)
2,7) 7j #
(vi
str(13)
(viii)bool(0
) „13‟
)str(0o19) #
(vi
(ix)
i) bool(„ „17‟
a‟) #
False
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 except for complex
numbers
To use standard math library we have to import the library in
our python program using import statement
import math
(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
𝑎2 + 𝑏 2
FOLLOWING MATHEMATICAL EXPRESSION
+ 𝑐2
(i)
(ii) 2 – ye𝑞2y +
4y P 𝑟 + 4
(iii)
x) + x
(v) | e2 – x |
JUST A
MINUTE…
(i) What are data types? What are python built-
(ii) in datatypes Which data type of python
(iii handles Numbers?
)
Why Boolean considered a subtype
(iv
of integer? Identify the data types
)
(v)What is the difference between mutable and immutable
of the values:
data type? Give name of one data type belonging to each
5, 5j, 10.6, „100‟, “100”, 2+4j,
category
[10,20,30], (“a”,”b”,”c”),
(vi)What{1:100,2:200}
is the difference in output of the following ?
print(len(str(19//4)))
print(len(str(19/4))
JUST A
MINUTE…
(vii) What will be the output produced
by these? 12/4 14//14 14%4 14.0/4 14.0%
14.0//4
(viii) Given 4
two variable NM is bound to string “Malala”
(NM=“Malala”). What will be the output produced by following
two statement if the input given is “Malala”? Why?
MM = input(“Enter name :”)
Enter name : Malala
(a) NM == MM (b) NM is MM
JUST A
MINUTE…
(ix)What will be the output of following code? Why
(i)25 or len(25)
(ii)len(25) or 25
(x)What will be the output if input for both
statement is 6 + 8 / 2 10 == input(“Enter
value 1:”)
10==int(input(“Enter value 2:”)
(xi)WAP to take two input DAY and MONTH and then calculate
which day of the year the given date is. For simplicity take
month of 30 days for all. For e.g. if the DAY is 5 and MONTH is
3 then output should be “Day of year is : 65”