XI-IP-Module-DATA HANDLING-2021-22
XI-IP-Module-DATA HANDLING-2021-22
Numbers:
The no. in Python have following core data types:
(i) Integers
Integers(signed)
Booleans
(ii) Floating point no.
(iii) Complex no.
(i) Integers
Whole nos as 5,56,78 etc.
They no fractional part.
Represented by numeric values with no decimal point
Int. can +ve or –ve.
Page 1 of 40
Represent truth values .This is the sub type of plain integers.
bool(0) or bool(1)…..python will return true or false.
(ii) Floating point no.
A no. having fractional part is considered as floating no.31245.45
There are two types:
(a) Fractional form: Normal decimal notation 234.34, 0.2223
(b) Exponent notation: 23.45E05, 01.234E34. Typically used for measuring
quantities like distance, area, temperature,
Floating point no. have two advantages:
They can represent values between the integers
They can represent a much greater range of values
But there is one disadvantage also
Floating point no. usually slower than integer operations .
In python floating point no. represent machine level double precision floating point
no.(15 digit precision. The range of these no. is limited by underlying machine
architecture subject to available (virtual ) memory.
Complex No.
A complex no. is in the form A+B i where i is the imaginary no., equal to the square root
of -1 .
A complex no. is made up of both real and imaginary components. In complex no. A+Bi,
A and B are real no. and i is imaginary.
If we have a complex no. z, where z=a+bi then a would be the real component and b
would represent the imaginary component of z,eg. Real component of z=4+3 i is 4 and
the imaginary component would be 3.
a= 0+3.1j
b=1.5+2j
print(a)
3.1j
print(b)
(1.5+2j)
The above example a has real component as 0 and imaginary component as 3.1; in
complex no. b , the real part is 1.5 and imaginary part is 2.
Python displays complex in parenthesis when they have non zero real part.
c=0+4.5j
d=1.1+3.4j
c
output:
Page 2 of 40
4.5j
print(d)
Output:
(1.1+3.4j)
Unlike Python other numeric types, complex no. are a composite quantity made of two
parts: the real part and the imaginary part, both of which are represented internally as
float values.
You can retrieve the two components using attribute refrences.
z.real gives the real part
z.imag gives the imaginary part as a float, not as a complex value.
Example:
z=(1+2.56j)+(-4 -3.56j)
a
Output:
(-3-1j)
z.real
will display real part of complex no. z
-3.0
z.imag
will display imaginary part of complex no.
-1.0
Page 3 of 40
Strings:
All Python 3.x strings store Unicode characters. Unicode is a system designed to
represent every character letters, no. any special characters of any known script language.
String as a sequence of characters:
Where each character can be individually accessed using its index.
String in Python are stored as individual characters in contiguous location, with two way
index for each location.
0 1 2 3 4 5 FORWARD INDEXING
P Y T H O N
-6 -5 -4 -3 -2 -1
BACKWARD INDEXING
Note: The index also called subscript ,which is the numbered position of a letter
in a string. In Python indices begins from 0.
And in backward -1.
nam='hello'
nam
Output:
'hello'
Page 4 of 40
nam[0]='p'
After executing this will show an error, because it can not change individual letters
of a string by assignment because strings are immutable and hence item
assignment is not supported:
Examples of List
[1,3,5,6]
[‘a’, ‘e’, ‘o’,]
[‘Amit’,18,99.2]
print(b)
Page 5 of 40
To change first value :
a[0]=100
print(a)
[100, 20, 30, 40]
print (a)
[100, 20, 90, 40]
Note: Value of type list are mutable i.e. changeable—one can change/add/delete a list of
elements. But the values of type tuple are immutable means non changeable.
Dictionary:
The Dictionary is an unordered set of comma separated Key: Value pairs within a
dictionary. No two
vowels[‘u’]
5
Page 6 of 40
The Python data objects can be broadly categorized into two-mutable and immutable
types.
1. Immutable types:
The immutable types are those that can never change their value in place.
In Python following types are immutable:
Integers
Floating point no.
Booleans
Strings
Tuples
p=2
q=p
r=2
p=10
r=7
q=r
Initially these three variable p=2, q=p and r=2 having same values reference ,the same
values objects ie. p,q,r will all reference same integer objects.
You can check it by finding its memory address.
Using id() function.
p=2
q=p
r=2
>>> id(2)
1447744576
For p…..
>>> id(p)
1447744576
For q…….
id(q)
1447744576
For r……
Page 7 of 40
>>> id(r)
1447744576
So although it appears that the value of p,q,r is changing but actually it is not changing.
Note: Please remember that memory address depend on your OS.
>>> id(p)
1447744704
>>> id(7)
1447744656
>>> id(q)
1447744656
>>> id(r)
1447744656
>>> id(2)
1447744576
Page 8 of 40
Now variable t has reference memory address same as initial memory address of variable
p when it was value 2.
Mutable types :
The mutable types are those whose values can not be changed in place . Only three
types are mutable in Python. These are: lists, dictionaries and sets.
c1=[2,4,6]
c1[1]=40
c1=[2,4,6]
>>> id(c1)
38624472
1[1]=100
>>> id(c1)
38624472
See even after changing the values in the list c1,its reference memory address has
remained same. That means the change has taken in place. List are mutable .
Variable Internals:
Python calls every entity that stores any values or any type of data as an object.
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).
typr(a)
<class 'int'>
2. The value of an object:
It is the data item contained in the object. For a literal, the value is the literal itself
and for a variable the value is the data item.
x=10
Page 9 of 40
print(10)
10
print(x)
10
Will also return 10.
3. The id of an object
It s the memory location of the object.
id(10)
1423955136
>>> id(x)
1423955136
>>> a=4
>>> id(4) The id of value 4 and variable a are same
1423955040 ,since the memory location of 4 is same as
>>> id(a) the location to which variable a is referring
1423955040 to.
>>> b=5
>>> id(b)
1423955056
>>> id(5)
1423955056
Now notice that the id of variable b is same
>>> b=b-1
>>> id(b) as id of integer 4
1423955040
Operators:
The symbols that trigger the operations/action on data, are called operators. The
operations(specific tasks ) are represented by Operators and the objects of the operations
are referred to as Operands.
Page 10 of 40
(iv) Logical Operators
(v) Bitwise operators
(vi) Membership Operators
Arithmetic Operators:
+ Addition
- Subtraction
* Multiplication
/ Division
// Floor division
% Remainder
** Exponentiation
Python provides two binary arithmetic operators (that require one operand).Unary +
and Unary -.
Unary Operators
Unary +
If a=5 then +a means 5
If a=0 then + a means 0
If a=-4 then +a means -4
Unary –
The result is the negation of its operand’s value.
1. Addition Operator
Page 11 of 40
4+20 results in 24
a+5(if a=5) results in 10
a+b(a=5,b=3) results in 8
3. Multiplaction operator
3*5 results in 15
b*4 (where b=4) results in 16
p*2(where p=-5) results in -10
a*c(a=5,c=2) results in10
4. Division Operator
The / operator in Python divides its first operand and always returns the result
as float value
4/2 results in 2.0
100/10 results in 10.0
7/2.5 results in 2.8
99/12 results in 8.25
18.12/12.23 results in 1.4816026165167622
5. Floor Division
In this the division in which only the whole part of the result is given in the
output and fractional part is truncated.
a=14.2, b=3
a/b
4.733333333333333
a//b
4.0
Examples:
99//32
Page 12 of 40
7//3
2
4.56//12
0.0
6.5//2
3.0
6. Modulus operator:
Produces the remainder of dividing the forst operand by the second operand.
Example:
7 5.2%2
1.2000000000000002
7%3.2
0.5999999999999996
6%2.5
1.0
7. Exponentiation operator:
Calculates the no. raised to a power
Example:
2**3 23
8
a**b(where a=2,b=4)
16
-5//3
-2
-7/4
-1.75
-7//4
-2
-7%4
1
7%-4
-1
7//-4
-2
Page 14 of 40
b=5
a=a+b
Can be expressed:
a+=b
or
a=a+1
a+=1
OPERATIONS DESCRIPTION
x+=y x=x+y Value of Y added to the value
of x
x-=y x=x-y
x*=y X=x*y
x/=y x=x/y
x//=y x=x//y
x**=y x=x**y xy computed and then result
assigned to x
x%=y x=x%y
Relational operator:
Page 15 of 40
< Less that - True if left operand is less than the right x<y
Relational operators work with nearly all types of data, such as no. strings, list, tuples etc.
It works on following principles:
1.For Numeric types: The values are compared after removing the trailing zeros.
For example:
4 and 4.0
Will be treated as equal
Page 16 of 40
3. Two lists and similarly two tuples are equal if they have same elements in the
same order.
4. Boolean True is equivalent to 1 and Boolean false to 0 for comparison purpose.
Important:
0.1+0.1+0.1==0.3
False
print(0.1+0.1+0.1)
0.30000000000000004
print(0.3)
0.3
a=2
>>> c=3
>>> a+5>c-1
Page 17 of 40
True Expression 1
True
IDENTITY OPERATORS
There are two identity operators in Python is and is not. The identity operators are used
to check if both the operands reference the same object memory, the identity operators
compare the memory locations of two objects and return true or false accordingly.
Operator Description
usuage
Page 18 of 40
memory location)
otherwise False
When “is” operator returns true for two variables, it implicitly means
that the equality operator will also return true.
a=235
b=235
print(a,b)
235 235
a is b
True
a==b
True
But it is not always true. That means there are some cases where you
will find that two objects are having just the same value,== operator
returns true for them but is operator return false
s1='abc'
s2=input("enter a string")
Page 19 of 40
enter a string: abc
s1==s2
True
s1 is s2
False
SIMILARLY
i=2+3.5j
j=2+3.5j
i is j
False:--------Objects i and j are the same complex no. with same value
ALSO
k=3.5
l=float(input("enter a value"))
enter a value3.5
k==l
True
Page 20 of 40
k is l
Reasons:
There are few cases where python creates two different objects that
both store the same value. These are:
LOGICAL OPERATORS:
Any object can be tested for truth value, for using if or while condition or as operand of
the Boolean operations below.
Page 21 of 40
The value of a constant is False, when it is False, or None.
When a variable contains different values like 0, 0.0, Fraction(0, 1), Decimal(0), 0j, then it
signifies the False Value.
The empty sequence '', [ ], (), { }, set(0), range(0), Truth value of these elements are False.
The OR operator
Combines two expression
1.Relational expression as operands
2. No. or list or strings as operands
(5==5) or(5==8)
True-------Because first expression is true
>>> 5>8 or 5<2
False------Bothe expressions are false
The OR operator will test the second operand only if the first operand is
false
True
Page 22 of 40
The AND operator
Combines two expressions which , which makes it operands.
1.Relational expression as operands
2. No. or list or strings as operands
(5==5) and (4==8)
False-----First expression is true but sec
The and operator will test the second operand only if the first operand
is true.
Example 1.
not(a==b), and
More examples:
x = True
y = False
print('x or y is',x or y)
Page 23 of 40
print('not x is',not x)
1. x and y
False
2. x or y
True
3.not x
False
Example 1
True
True
Exampl 2
Page 24 of 40
11<13>12-----shorter version of 11<13 and 13>12.
True
Operator Precedence:
The following table lists all operators from highest precedence to lowest.
Operator Description
Page 25 of 40
<= < > >= Comparison operators
a = 20
b = 10
c = 15
d=5
e=0
Page 26 of 40
e = (a + b) * c / d #( 30 * 15 ) / 5
print "Value of (a + b) * c / d is ", e
e = ((a + b) * c) / d # (30 * 15 ) / 5
print "Value of ((a + b) * c) / d is ", e
e = a + (b * c) / d; # 20 + (150/5)
print "Value of a + (b * c) / d is ", e
When you execute the above program, it produces the following result –
Value of (a + b) * c / d is 90
Value of ((a + b) * c) / d is 90
Value of (a + b) * (c / d) is 90
Value of a + (b * c) / d is 50
Operator Associativity
Associativity is the order in which an expression is evaluated that has
multiple operators of the same precedence. Almost all the operators have left-to-
right associativity. For example, multiplication and floor division have the same
precedence.
Almost all operators except the exponent (**) support the left-to-right associativity.
Example:
print(4 * 7 % 3)
1
Page 27 of 40
# Testing left-right associativity
print(2 * (10 % 5))
0
In Python, the only operator which has right-to-left associativity in Python is the exponent
(**) operator.
Q1.a, b ,d =3,5,6
a>b or b<=d ?
a> b< c> d ?
Expression:
An expression in Python is any valid combination of opertors, literals and variables.It is
composed of one or more operations, with opertors, literals and variables .
An atom is something that has a value. ... are all atoms. An expression is any valid
combination of operators, literals and variables. In other words a valid combination of
atoms and operators forms a python expression.
The type of operator and operands used in an expression determine expression type
1. Arithmetic expression
2. Relational expression
3. Logical
4. String Expression
‘and’+’then’
‘hello’*2
Page 28 of 40
Evaluating Expression:
1. Arithmetic :By considering operator precedence.
2. Performs any implicit conversion(eg. Promoting int to float, or bool to int) by
following certain rules.
3. Compute the result based on the operator.
4. Replace the sub expression with the compound result
5. Repeat till the final result is obtained.
Implicit Type Conversion(Coercion):
A conversion performed without programmers intervention. It is applied whenever
differing data types are intermixed in an expression ,so as not to lose the data.
Python converts (in mixed artithmetic expression) all operands upto the type of the largest
operand(type promotion).
It is applied:
1. If either argument is a complex no. then the other is converted to complex
Example Q:
ch=5
i=2
f1=4
db=5.0
fd=36.0
a=(ch+i)/db-----------------Expression-1
b=fd/db*ch/2--------------Expression 2
print(a)
1.4
print(b)
18.0
As per operator precedence:
Page 29 of 40
a=(ch+i)/db -----------------Expression-1
| | |
int int float
b=fd/db*ch/2--------------Expression 2
float float int
Important: In python if the operator is the division result will always be a floating point.
Even if both the operands are of integer types
Example:
a,b=3,6
c=b/a
2.0
a,b=3,6
c=b//a
c
2
c=b%a
c
0
Evaluating Relational Expressions(Comparisons)
All comparison operations have the same priority,which is lower than that of any
arithmetic operations.. It yield Boolean values:
Example 1
a,b,c=10,23,23
print (a<b)
Page 30 of 40
True
print(b<=c)
True
print(a<b<=c)
True
Example-2
a,b,c=23,10,10
print (a<b)
False
print(b<=c)
True
>>> print(a<b<=c)
False
Evaluating Logical Expression:
Precedence of logical operator is lower than the arithmetic operator:
25/5 0r 2.0 +20/10 will be evaluated as 5 or 4.0
Similarly not,and ,or
(a or(b and (not c)))
a,b,c=2,3,4
2
Python minimizes internal work:
In OR only evaluates the second expression, if first is false
Page 31 of 40
In AND only evaluates the second expression, if first one is true.
What will be the output:
(5>10) and (10<5) or (3<18) and not 8<18
False
DIVIDED BY ZERO:
(5<10) or (50<100/0)
Return true because first argument is tested as true
Type Casting
The process of converting the value of one data type (integer, string, float, etc.) to
another data type is called type conversion.
Explicit Type Conversion
In Explicit Type Conversion, users convert the data type of an object to required data
type.Its a user defined conversion that forces an expression to be of specific type. Also
known as Type Casting.
a=3,b=5.0
int(b)
will cast the data type as per expression –int
d=float(a)
d
3.0
Example:
num_int = 123
num_str = "456"
num_str = int(num_str)
Page 32 of 40
print("Data type of num_str after Type Casting:",type(num_str))
Output:
Data type of num_int: <class 'int'>
Data type of num_str before Type Casting: <class 'str'>
4. Explicit Type Conversion is also called Type Casting, the data types of objects are
converted using predefined functions by the user.
5. In Type Casting, loss of data may occur as we enforce the object to a specific data type.
Table:
S. No. Conversion Conversion Examples
From To Function
1 Any no-float, int int() int(7.8)=7
string int(’46’)=46
Page 33 of 40
2 Any no-float, floating float() float(7)=7.0
string point float(‘24’)=24.0
3 numbers Complex complex() complex(7)=7+0j(one
no argument)
comple(3,2)=3+2j
4 No. booleans string str( ) str(3)=’3’
str(5.78)=’5.78’
str(0o17)=’15’(convertin octal
no to string-string converts
the equivalent decimal no. to
string:0o17=15
str(1+2j)= '(1+2j)'
str(True)=’True’
5 integer, float, String str() str(3.141592)
list, tuple, '3.141592'
dictionary → >>> str([1,2,3,4])
string '[1, 2, 3, 4]'
Math module
It is a standard module in Python. To use mathematical functions of this module,we have
to import the module using import math.
Page 35 of 40
pi It is pi value (3.14159...) It is (3.14159...)
It is mathematical constant e
e It is (2.71828...)
(2.71828...)
Debugging
Debugging refers to the process of locating the place of error, cause of error and correcting
the code accordingly. An error causing disruption in program’s running or in producing
right ouput, is ‘program bug’.
Errors in a Program
There are broadly three types of errors:
Compile-Time Errors, Run Time, Logical Errors
1. Compile Time Errors
When a program compiles, its source code is checked for whether it follows the
programming language’s rules or not.
Its further subdivided into two categories:
Syntax error, Semantic error
EXCEPTIONS
Errors and exceptions are similar but different terms. While error represents , any bug in
the code that disrupts running of the program or causes improper output, an Exception
refersto any irregular situation occurring during execution/run time , which you have no
control on. Errors in the program can be fixed by making corrections in the code, fixing
exceptions is not that simple.
Difference between Errors and Exceptions:
Page 37 of 40
Entering wrong pin no. or account no. is error
Not that much amount in account is an exception
ATM machine is struck is also an exception
Exercise:
Page 38 of 40
1. What are Boolean numbers ? Why are they considered as a type of integers in
Python ?
2. What will be the data types of following two variables ?3
3. What are the built-in core data types of Python ?
4. What are complex numbers ? How would Python represent a complex number with
real part as 3 and imaginary part as – 2.5 ?
5. What are floating point numbers ? When are they preferred over integers ?
6. What will be the output of following code ?
7. Why does Python uses symbol j to represent imaginary part of a complex number
instead of the conventional i ?
8. What .will be the output of following code ?
9. What is String data type in Python ?
10. How are str type strings different from Unicode strings ?
11. What are List and Tuple data types of Python ?
12. What are Dictionaries in Python ?
13. What do you understand by mutable and immutable objects?
14. How is a list type different from tuple data type of Python ?
15. How is ‘unary + ‘ operator different from ‘+’ operator ? How is ‘unary – ‘ operator
different from ‘-‘ operator ?
16. What is the function of operators ? What are arithmetic operators ? Give their
examples.
17. What does the modulus operator % do ? What will be the result of 7.2 % 2.1 and 8 %
3?
18. What are binary operators ? Give examples of arithmetic binary operators.
19. What will be the result of 5.0/3 and 5.0//3 ?
20. Write an expression that uses a relational operator to return True if the variable total
is greater than or equal to variable final.
21. How will you calculate 4 .5^5 in Python ?
22. How are following two expressions different ? (i) ans = 8 (ii) ans == 8
23. What is the result of following expression : a >= b and (a + b) > a if (i) a = 3, b = 0 (ii)
a = 7, b = 7 ?
24. What is the function of logical operators ? Write an expression involving a logical
operator to test if marks are 55 and grade is ‘ B’.
25. If a = 15.5, b = 15.5 then why is a is b is False while a == b is True ?
26. Write a program to obtain temperatures of 7 days (Monday, Tuesday … Sunday)
and then display average temperature of the week.
Page 39 of 40
Page 40 of 40