0% found this document useful (0 votes)
56 views

XI-IP-Module-DATA HANDLING-2021-22

The document discusses various data types in Python including numbers, strings, lists, tuples, and dictionaries. It provides details on: 1) The core numeric data types in Python are integers, floating point numbers, and complex numbers. Integers can be positive or negative whole numbers while floating point numbers have fractional components. 2) Strings store text data as a sequence of characters and are immutable. Lists and tuples are used to store collections of mixed data types, with lists being mutable and tuples immutable. 3) Dictionaries store data as key-value pairs and are mutable. The document explains how various data types are represented and can be accessed or modified in Python.

Uploaded by

Raju Upadhyay
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)
56 views

XI-IP-Module-DATA HANDLING-2021-22

The document discusses various data types in Python including numbers, strings, lists, tuples, and dictionaries. It provides details on: 1) The core numeric data types in Python are integers, floating point numbers, and complex numbers. Integers can be positive or negative whole numbers while floating point numbers have fractional components. 2) Strings store text data as a sequence of characters and are immutable. Lists and tuples are used to store collections of mixed data types, with lists being mutable and tuples immutable. 3) Dictionaries store data as key-value pairs and are mutable. The document explains how various data types are represented and can be accessed or modified in Python.

Uploaded by

Raju Upadhyay
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/ 40

Class XI- Informatics Practices

Chapter 4 –Data Handling-Module-I


Module I- Data Types
Data Types:
Data can be of many types:
Character, String, integer, real etc.
Anything enclosed in quotes is string, No. without fractions represent int.,with fraction
represent real.
True and false represent Boolean data.

Built in core data types


 Numbers(int, float, string, list, tuple, dictionary)
 String
 List
 Tuple
 Dictionary
Python capabilities to handle the varied data is based on memory space it allocates to
hold a certain type of data and the range of values supported for a data type.

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.

There are two types of integers:


Integers(signed):
Normal integer represented by whole no. Int. in Python 3.x can be of any
length, it is only limited by the memory available.
Boolean

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

Range of Python numbers:


Data Type Range
Integers An unlimited range, subject to available
(virtual) memory only
Booleans Two values true(1) or false(0)
Floating point no. An unlimited range, subject to available
(virtual) memory only on underlying
machine architecture

Complex no. Same as floating point nos. because the


real and imaginary parts are represented
as floats

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

Lets assume that variable name=as stored the value’PYTHON’


Where name[0]=P=name[-6]
Name=[1]=Y=name[-5]…….

1. Strings in python are stored by storing each character separately n contiguous


location.
2. The characters in the strings are given two way indices: forward and backward.

Lets store the word :


Subject=’computers’
Subject[0]=?

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:

Traceback (most recent call last):


File "<pyshell#6>", line 1, in <module>
nam[0]='p'
TypeError: 'str' object does not support item assignment
nam=’informatics’
can be assigned

List and Tuples:


The list and tuples are Python’s compound data types. List can be changed but
Tuples can’t(immutable)

A List in Python represents a list of comma separated values of any datatype


between square brackets.

Examples of List
[1,3,5,6]
[‘a’, ‘e’, ‘o’,]
[‘Amit’,18,99.2]

Assign List to a variable:


a=[10,20,30,40]
b=[‘ram’,18,78]
print(a)
OUTPUT will be:

[10, 20, 30, 40]

print(b)

['ram', 18, 78]

Page 5 of 40
To change first value :
a[0]=100
print(a)
[100, 20, 30, 40]

To change third item:


a[2]=90

print (a)
[100, 20, 90, 40]

The numbers internally are numbered as o,1,2….


Tuples:
Tuples are represented as a list of comma-separated values of any data type within
parentheses for example:
p=(1, 2, 3, 4, 5)
q=(2, 4, 6, 8)
r=(‘a’, ‘e’, ‘i’, ‘o’, ‘u’)
j=(7,3, ’a’, 45, ’we’, ‘s’)

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={‘a’:1, ‘e’:2 , ’i’:3, ‘o’:4,’u’:5 }


vowels[‘a’]
1

vowels[‘u’]
5

Mutable and Immutable types

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

Now you may think integer types can change values.


We already studies that in Python , variable names are just the references to value
objects i.e data values.
The variable names do not store values themselves, ie. They are not storage containers.

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.

When the next set of statements execute:


p=10
r=7
q=r
then these variable names are made to point to different integer objects. That is now their
memory addresses that they refrence will change.
>>> p=10
>>> r=7
>>> q=r
Now check…..
>>> id(10)
1447744704

>>> id(p)
1447744704

>>> id(7)
1447744656

>>> id(q)
1447744656

>>> id(r)
1447744656

>>> id(2)
1447744576

Now if you assign 2 to any other variable:


t=2
>>> id(t)
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).

Every python object has three key attributes:


1. The type of an Object:
Built in function type () returns the type of an object.
a=5
type(5)
<class 'int'>

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.

Python’s rich set of operators comprises of these types of operators


(i) Arithmetic Operators
(ii) Relational Operators
(iii) Identity Operators

Page 10 of 40
(iv) Logical Operators
(v) Bitwise operators
(vi) Membership Operators

Arithmetic Operators:
+ Addition
- Subtraction
* Multiplication
/ Division

// Floor division
% Remainder
** Exponentiation

Each of these operators is a binary operators i.e. it requires two values(operands) to


calculate a final answer.

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.

If a=5 then -a means -5


If a=0 then - a means 0
If a=-4 then a means 4
This operator reverses the sign of the operands value.
Binary Operators
Operators that act upon two operands. The operands of a binary operators are
distinguished as the left or right operand. Together the operator and its operands
constitute an expression.

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

For addition operator + operator may be of no. type.


2. Subtrstion Operator
Subtract the second operand from first.
14-3 results as 11
a-b results as 2
x-3 (where x=-1) results as -4

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

Q1. What will be the output produced by the following code:


a,b,c,d=9.2, 2.0, 4, 21
print(a/4)
print(a//4)
print(b**c)
print(d//b)
print(a%c)

Negative Number Arithmetic in Python


Page 13 of 40
Arithmetic operations are straight forward even with negative numbers,
especially with non division opertions:
-5 + 3 will give you 2
-5 – 3 will give you -8
-5 * 3 will give -15
-5** 3 will give – 125

But when it comes to division and related operators(/, //, %) it evaluates in


the following manner.
5//-3
-2

-5//3
-2

-7/4
-1.75

-7//4
-2

-7%4
1

7%-4
-1

7//-4
-2

Augmented assignment operator


An augmented assignment is generally used to replace a statement where
an operator takes a variable as one of its arguments and then assigns the result
back to the same variable. A simple example is x += 1 which is expanded to x =
x + (1)
It combine the impact of an arithmetic operator with an assignment operators.
a=10

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

Augmented assignment does not violate mutability.

Relational operator:

Used to compare values

Operator Meaning Exampl e

Greater that - True if left operand is greater than the


> x>y
right

Page 15 of 40
< Less that - True if left operand is less than the right x<y

== Equal to - True if both operands are equal x == y

!= Not equal to - True if operands are not equal x != y

Greater than or equal to - True if left operand is greater


>= x >= y
than or equal to the right

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

2. Strings are compared on the basis of lexicographical ordering (ordering in


dictionary)
Capital letters are considered lesser than small letters: ‘A’ is less than ‘a’;
book is not equal to books

Lexicographical ordering is implemented via ordinal values(ASCII or


UNICODE) just by ord(‘A’) or ord(‘a’). That’s the reason A is less than a.
Similarly nonprinting characters like spaces. Spaces are real characters and
they have a specific code (ASCII 32) assigned to them. If you campare might
produce different result –if they have some spaces in the beginning or end.
'Class'>' Class'
True
'Class'>'Class'
False

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:

While using floating-point numbers, the relational operator (==) does


not produce correct output, this is due to the internal precision errors in
rounding up floating-point numbers.

0.1+0.1+0.1==0.3

False

print(0.1+0.1+0.1)

0.30000000000000004

print(0.3)

0.3

This is because floating point approximation.

Relational operators with arithmetical opertaors

RO is having lower precedence than AO:

a=2

>>> c=3

>>> a+5>c-1

Page 17 of 40
True Expression 1

(a+5)>(c-1) Expression 2 returning same output

True

>>> a+(5>c)-2 Expression 3 is different

Note: Do not confuse with = and ==

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

is a is b Returns true if both the


operands are pointing the
same object(means
refereeing the same memory
location) otherwise False

is a is not b Returns true if both the


not operands are pointing the
different object(means
refereeing the same

Page 18 of 40
memory location)
otherwise False

EQUALITY(==) AND IDENTITY (is) –Important Relation

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

But is operator return False for i is j

ALSO

k=3.5

l=float(input("enter a value"))

enter a value3.5

k==l

True

Page 20 of 40
k is l

False-----The variable k,i both store float value 3.5.

But k==i returns True K is I returns false

Reasons:

There are few cases where python creates two different objects that
both store the same value. These are:

 Input of strings from the console


 Writing integer literals with many digits(very big integers)
 Writing floating point and complex numbers

LOGICAL OPERATORS:

Operator Meaning Example

And True if both the operands are true x and y

Or True if either of the operands is true x or y


True if operand is false
Not not x
(complements the operand)
Truth value testing:

Python Truth Value Testing

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

2. No. or list or strings as operands


0 or 0
0
0 or 8
8
5 or 0.0
5
'hello' or 'hello'
'hello'

The OR operator will test the second operand only if the first operand is
false

20>10 or "a" +1>1

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.

The not operator:

Operator not has a lower priority than non-Boolean operators. It works


on single expression. And reverse or negates the truth values of the
expression.

Example 1.

not a==b ------is interpreted as

not(a==b), and

a== not b --------is a syntax error.

More examples:

x = True

y = False

print('x and y is',x and y)

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

not(5>9)----True expression 5>9 is false

Chained Comparison Operators:

Example 1

1<2<3—----Chained version of Boolean expression

True

1<2 and 2<3

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

**^ Exponentiation (raise to the power)

~+- Complement, unary plus and minus (method names


for the last two are +@ and -@)

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction

>> << Right and left bitwise shift

& Bitwise 'AND'td>

^| Bitwise exclusive `OR' and regular `OR'

Page 25 of 40
<= < > >= Comparison operators

<> == != Equality operators

= %= /= //= -= += Assignment operators


*= **=

is is not Identity operators

in not in Membership operators

not or and Logical operators

Operator precedence affects how an expression is evaluated.


For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first multiplies 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom.
Example

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); # (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 ?

Q. Identify the order of evaluation in the following expression : 4 * 5 + 7 * 2 – 8 % 3 + 4

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

(a or(b and (not c)))

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"

print("Data type of num_int:",type(num_int))


print("Data type of num_str before Type Casting:",type(num_str))

num_str = int(num_str)
Page 32 of 40
print("Data type of num_str after Type Casting:",type(num_str))

num_sum = num_int + num_str

print("Sum of num_int and num_str:",num_sum)


print("Data type of the sum:",type(num_sum))

Output:
Data type of num_int: <class 'int'>
Data type of num_str before Type Casting: <class 'str'>

Data type of num_str after Type Casting: <class 'int'>

Sum of num_int and num_str: 579


Data type of the sum: <class 'int'>

Key Points to Remember


1. Type Conversion is the conversion of object from one data type to another data type.

2. Implicit Type Conversion is automatically performed by the Python interpreter.

3. Python avoids the loss of data in Implicit Type Conversion.

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]'

6 string, tuple, List list() list('Mary') # list of


set, dictionary characters in 'Mary'
→ list ['M', 'a', 'r', 'y']
>>> list((1,2,3,4)) # (1,2,3,4)
is a tuple
[1, 2, 3, 4]
[1, 2, 3]

7 string, list, set tuple tuple() tuple('Mary')


→ tuple ('M', 'a', 'r', 'y')
>>> tuple([1,2,3,4]) # [ ] for
list, ( ) for tuple
(1, 2, 3, 4)

8 Any type Boolean bool() bool(0) =False


bool(1)=True
bool(3)=True
bool(‘’)=False
bool(‘a’)=True
bool(‘helo’)=True
Page 34 of 40
Non-zero or empty type will
return true
And rest will give False

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.

Function Description Example

It returns the smallest integer greater


ceil(n) math.ceil(4.2) returns 5
than or equal to n.
factorial(n) It returns the factorial of value n math.factorial(4) returns 24
It returns the largest integer less than
floor(n) math.floor(4.2) returns 4
or equal to n
It returns the remainder when n is
fmod(x, y) math.fmod(10.5,2) returns 0.5
divided by y
exp(n) It returns e**n math.exp(1) return 2.718281828459045

log2(n) It returns the base-2 logarithm of n math.log2(4) return 2.0


math.log10(4) returns
log10(n) It returns the base-10 logarithm of n
0.6020599913279624
pow(n, y) It returns n raised to the power y math.pow(2,3) returns 8.0

sqrt(n) It returns the square root of n math.sqrt(100) returns 10.0


math.cos(100)
cos(n) It returns the cosine of n
returns 0.8623188722876839
math.sin(100)
sin(n) It returns the sine of n
returns -0.5063656411097588
math.tan(100)
tan(n) It returns the tangent of n
returns -0.5872139151569291

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

(i) Syntax errors


When the rules of a programming language are misused, that is when a
grammatical rule of python is violated. For example:
x < - y* z
if x=(x*y)
These two statements will result in syntax error as’<-‘ is not an assignment
operator and = is the assignment operator, not a relational operator.
Also if is block statement which requires :.
So the correct statement will be:
x=y*z
if x==(x*y)
Page 36 of 40
(ii) Semantic errors
It occurs when statements are not meaningful. For instance ‘Sita plays guitar’
is syntactically and semantically correct. But the statement Guita plays Sita is
syntactically correct because grammar is correct but semantically incorrect.
Similarly there are semantic rules of a programming language , violation of
which results in semantic errors.
x*y=z
2. Logical errors
Even if you do not encounter any error during compile time and run time, and
program does not provide the correct result. This is because of the programmer’s
mistaken analysis of the problem they are trying to solve. Such errors are logical
errors.
For instance incorrectly implemented algorithm, use of a variable before its
initialization, or unmarked end of a loop, wrong parameters passed etc. Sometimes
logical errors are treated as a sub category of run time errors.
3. Run Time errors
Errors that occur during the execution of a program. These are harder to detect,
some stop the execution which is then called program crashed or abnormally
terminated.
Most run time errors are easy to identify as they stops the execution when
encountered like infinite loop, wrong value (entered other than required) input.
Python usually takes care of such errors by terminating the program, but a program
that crashes whenever it detects an error condition is not desirable.

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

Some built in Exception


Exception Name Description
EOF Error When one of built in functions input() hits end of file
condition without reading any data.
IO Error When an I/O operation (such as print(), open() or method
of a file object is ) fails for an I/O related reasons eg. “file
not found” or “disk full”.
Name Error Raised when an identifier name is not found
Index error Raised when the index of a sequence is out of range. For
example String[4] will raise legal indexes for a string
length 4 are 0,1,2,3
Type Error Raised when a function or operation is applied to an
object of incorrect type. Compute a square root of string
value
Value Error Raised when a function gets an argument of correct type
but improper value.int(‘z10”)
Zero Divisional error Raised when the second operand of division or modulo
operation is zero.
Overflow error Raised when the result of an arithmetic operation is too
large to be represented.
Key error Raised when a key is not found in a dictionary

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

You might also like