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

Class11 CS DataHandling Updated

Python provides built-in data types to store and handle data, including numbers, strings, lists, tuples, and dictionaries. Numbers can be integers, floating point numbers, or complex numbers. Integers are whole numbers without decimals, while floating point numbers have fractional parts. Complex numbers contain real and imaginary components. Strings are sequences of characters that can be indexed forward and backward. Variables in Python refer to objects, which have a type, value, and ID (memory location). Operators perform operations on operands (data).

Uploaded by

tbf06720
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Class11 CS DataHandling Updated

Python provides built-in data types to store and handle data, including numbers, strings, lists, tuples, and dictionaries. Numbers can be integers, floating point numbers, or complex numbers. Integers are whole numbers without decimals, while floating point numbers have fractional parts. Complex numbers contain real and imaginary components. Strings are sequences of characters that can be indexed forward and backward. Variables in Python refer to objects, which have a type, value, and ID (memory location). Operators perform operations on operands (data).

Uploaded by

tbf06720
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 49

Data Handling

Python provides predefined set of data types for


handling the data it uses. Data can be stored in any of
these data types.
Data types
Data can be of many types like character, integer, real ,
string etc.
Numbers without fractions represent integer data.
Numbers with fractions represent real data and true
and false represent Boolean data. Anything enclosed in
quotes represents string data in Python.
Python offers the following built-in code data types .
Numbers string list tuple dictionary.
Numbers
Number data types are used to store numeric values in
Python. Numbers in Python have the following code
data types
i)Integers (signed integers, booleans)
ii)Floating point numbers
iii)Complex numbers
Integers
Integers are whole numbers such as 5, 36, -30, etc.
Integers after presented in Python by a numeric values
with no decimal point. Integers can be positive or
negative example+ 12,- 12,- 15,300 etc.(missing + or -
symbol means it is a positive integer)
There are two types of integers in Python .
Signed integer: It is a normal integer representation of
whole numbers. Integers in Python can be of any
length, it is only limited by the memory available
undefined python provide single data type (int ) store
any Integer whether big or small. It is signed
representation, i.e integers can be positive or negative.
Boolean : These represent truth values False and True.
They behave like 0 and 1 respectively. To get the
Boolean equivalents of 0 or 1 you can type bool(0) or
bool(1), python will return False or True respectively.
Example >>> bool(0)
False
>>> bool (1)
True
>>> str(False)
'False'
Note: The two objects representing the value is False
and True (not false or true) you are the only Boolean
objects in Python.
Floating Point Numbers
A number having fractional part is a floating-point
number. For eg 3.1415 is a floating point number. The
number 12 is an integer but 12.0 is a floating point
number.
Note: In some cases the exception Overflow error is
raised instead of the given number cannot be
represented through available number of bytes.
Fractional numbers can be written in 2 forms.
i) Fractional Form . Eg 3500.78 , -0.006 etc.
ii) Exponent Notation . Eg 3.5E03 0.5E-0.4.
Advantages
1. Floating point variables are used to represent
real numbers which are used for measurable
quantities like distance, area,
Temperature etc.
2. They can represent values between integers.
3. They can represent much greater range of
values.
Disadvantages
Floating-point operations are usually slower
than integer operations.
Note: In Python floating point numbers have a
precision of 15 digits(double precision).
Complex Numbers
Mathematically a complex number is a number of the
form (a + bi ) where i is the imaginary number equal to
square root of -1. Complex number is made up of both
real and imaginary components. In (a + bi ) , a and b
are real numbers and ‘i’ is imaginary.
Python represents complex numbers as a pair
of floating point numbers
Examples
A = 0 + 3.1j
B = 1.5+2j
The above example shows complex number A
has reall component 0 and imaginary
component as 3.1 and in complex number
B ,the real part is 1.5 and imaginary part is 2.
When displaying complex numbers, Python
displays complex numbers in parentheses
when they have a non-zero real part as shown
below.
>>> c = 0 + 4.5 j
>>> d =1.1 + 3.4j
>>> c
4.5 j
>>> d
(1.1 + 3.4j)
>>> print(c)
4.5j
>>> print(d )
(1.1 + 3.4j)
From the above program segment we see that
complex numbers with non zero part are
displayed with parentheses around it but
there is no parentheses around complex
number with real part as 0.
Retrieving stored values
Complex numbers have real part and
imaginary part both which are represented
internally as float values.
Retrieval of the two components using
attribute references can be done as follows
For a complex number z:
z.real gives the real part, z.imag give the
imaginary part as a float not as a complex
value
Example
>>> z = (1+ 2.56j) + (-4-3.56j)
>>>z.real
-3.0
>>>z.imag
-1.0

Data type Range


Integers And unlimited range
subject to available virtual
memory only.
Boolean Two values True (1) and
False (0) only. An unlimited
range subject to available
virtual memory.

Floating point An unlimited range subject


numbers to available virtual
memory.

Complex Same as floating point


numbers numbers because real and
imaginary parts are
represented as floats

Note : Complex numbers are commonly used in


Electrical Engineering. In the field of electricity, due to
the symbol ‘I’ is
Used to represent current, they use symbol ‘j’
for square root of 1.
Strings
A string data type lets you hold string data i.e
any number of valid characters into a set of
quotation marks.
In Python 3.x each character stored in a string is
a Unicode. Unicode is a system designed to
represent every character from every
language.A string can hold any type of known
characters i.e letters, numbers and special
characters of any known scripted language.
String as a sequence of characters
A Python string is a sequence of characters and
each character can be individually accessed
using its index. Strings in Python as stored as
individual characters in contiguous location with
two way index for each location.
Forward indexing
0 1 2 3 4 5
Name P Y T H O N
-6 -5 -4 -3 -2 -1

Backward indexing

Name[0] = ‘P’ = Name[-6]


Name[1] = ‘Y’ = Name[-5]
Name[2] = ‘T’ = Name[-4]
Name[3] = ‘H’ = Name[-3]
Name[4] = ‘O’ = Name[-2]
Name[5] = ‘N’ = Name[-1]
Note: Python has no separate character data type
which most other programming languages have that
can hold a single character. In Python a character is a
string type only with single character.
Strings in Python a stored by storing each character
separately in contiguous locations. The characters of
the string are given two way indices
0, 1, 2...... In the forward direction and
-1,-2,-3,..... In the backward direction.

Example: Consider a string subject =


"COMPUTERS". It will be stored as

0 1 2 3 4 5 6 7 8
Subject C O M P U T E R S
-9 -8 -7 -6 -5 -4 -3 -2 -1

Thus Subject[0]=’C’ Subject[2]=’m’


Subject[-1]=’s’ Subject[-7]=’m’
Since the length of the string variable can be
determined using the function len(< string>), ok
we say that)
1)first character of the string is at index 0 or -
length
2) second character of the string is at index 1 or
or-(length -1)
:
:
Last character of the string is at index(length -1)
or - 1.
Variable internals
Python is an object oriented language. Python calls
every entity that stores any value or any type of data
as an object.
An object is an entity that has certain properties and
that exhibit a certain type of behaviour, for example
integer values are objects they hold whole numbers
only and they have properties, the support all
arithmetic operations (behaviour).
Similar to objects in Python we can say a variable is
also an object that refers to a value.
Every Python object has three key attributes associated
with it
i) the type of an object
The 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= a 4
>>> type(4)
< class ' int'>
>>> type (a)
< class ' int'>
From the above program segment we observe that the
type of integer value 4 is returned as int.
The type of variable ' a' is returned as int, since ' a ' is
referring to an integer value.
ii) the value of an object
It is the data item contained in that object. For a
literal, the value is the literal itself and for a variable
the value is the data item it is currently referencing.
Example
>>> a =4
>>> print (4)
4
>>> print (a)
4
From the above program segment the observe the
value of integer literal 4 is 4.
The value of variable a is 4 as it is currently referencing
two integer value 4.
iii) the id of an object
The id of an object is the memory location of that
object.
Built in function id() returns the id of an object.
Example
>>> id(4)
30899132
>>>a=4
>>> id(a)
30899132.
From the above program segment object 4 is internal
is stored in 30899132.
Variable a is currently referencing the location
30899132 ( same as id(4)). It means that variable is not
a storage location in Python, rather a label pointing to
a value object.
Example 2
>>> id(4)
30899132
>>>a=4
>>>id(a)
30899132
>>>b=5
>>>id(5)
30899148
>>id(b)
30899148
>>>b=b-1
>>>id(b)
30899132
From the above program segment the observed that
variable 'b' is is referring to the value 4.
Notice that id of variable ' b' is the same as id of in
integer 4.
OPERATORS
The symbols that triggered the operation/ action on
data are called operators and the data on which the
operation is being carried out is referred to as
operands.
Example x= a+b * 5-d
In the above expression =,
+,* - are operators and x,a,b,5,d are called as operands.
The types of operators in Python are
i) Arithmetic operators
ii) Relational operators
iii) Identity operators
iv) Logical operators
v) Bitwise operators
Arithmetic operators
Addition + , subtraction -, multiplication * , division/ ,
floor division // , remainder % , exponentiation ** .
Python also provides to unary arithmetic operators
that require only one operand i.e unary + and unary -.
S.N OPERATO USAGE EXAMPLES
o R
1 + Addition: Adds the Eg: i)15+20
values of operands Results in
and results in sum of 35.
two operands. ii)A=2
Python also uses + for A+5
concatenation of Results in 7
strings.
2 - Subtraction: This Eg i)14-3
operator subtracts the Results in
second operand from 11
the first operand. ii) a=9 , b=5
a-b
evaluates
to 4
3 * Multiplication: This Eg i) 4*3
operator multiplies Results in
the values of its 12
operands. ii) a=9 , b=5
Python uses the * a*b
operator as a evaluates
replication operator to 40
when used with
strings.
4 / Division : This Eg
operator divides the i) 4/2
first operand by the =2.0
second operand. ii) 7/2.5
=2.8
5 // Floor Division :This Eg
operator performs i) 100/
floor division. Here / 32
the fractional part is =3
truncated , and only ii) 6.5//
the whole part of 2
result is given as =3.0
output,
(Note: For negative
operands, the result is
rounded down to the
nearest whole
number)
6 % Modulus : This Eg i)
remainder finds the 19 % 6 =1
remainder when 7.2 %3 =1.2
operand1 is divided by 6% 2.5 =1.0
operand2.
7 ** Exponentiation: This Eg i) 4**3
performs the evaluates
exponentiation(power 43 = 64.
) calculation. i.e it ii) 49 **0.5
returns the result of a evaluates
number raised to a 49 0.5 =
power. sqrt(49)= 7

8. + Unary + .This is a Eg
unary operator means A= +10
it works on a single
operand. This
operator is used to
denote a number is
positive.
9. - Unary - . This is a Eg
unary operator means A= -10
it works on a single
operand. This
operator is used to
denote a number is
negative.

Augmented assignment operators


Python has an assignment operator = which assigns the
value specified on the RHS (right hand side) to the
variable/ object on the
LHS( left hand side) of =.
Python also offers augmented assignment arithmetic
operators which combine the arithmetic operator with
the assignment operators.
Example
a=a+b can also be written as a+=b
[COPY THE TABLE FROM PAGE NO. 219]
Operation Description Comment
X+=Y X=X+Y Value of Y I is added to the
value of x and then the
result is assigned to X.
X-=Y X=X-Y Value of Y is subtracted
from X and result is
assigned to X.
X*=Y X=X*Y Value of Y is multiplied to
the value of X and result is
assigned to X.
X/=Y X=X/Y Value of Y is divided by the
value of X and result is
assigned to X.
X**=Y X=X**Y X to the power of Y is
computed and the result is
assigned to X.
X%=Y X=X%Y The value of X Mod Y
(remainder)is a assigned to
X.
Note: This holds good only for immutable types such as
numbers.

Relational operators
Relational operators determine the relation among
different operands. Python provides six relational
operators for comparing values. These are also called
as comparison operators.
The six relational operators are
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
Relational operators work on nearly all types of data in
Python such as numbers, strings, list, tuples etc.
They work on the following principles
1) For numeric types, values are compared after
removing trailing zeros after decimal point from a
floating point number(example 6 and 6.0 are treated as
equal)
2) Strings are compared on the basis of lexicographical
ordering (ordering in dictionary).
Capital letters are considered lesser than small letters
i.e 'A' is less than 'a'.
Care should be taken for non printing characters like
space.
Example >>>"Apple" == " Apple"
False
3) Two list and similarly two tuples are equal if they
have same elements in same order.
4) Boolean true is equivalent to 1(numeric 1) and
Boolean false is equivalent to 0(numeric zero) for
comparison purposes.
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 i.e
identity operators compare the memory locations of
the two objects and return True or False accordingly.
is: A is B , returns True if both its operands are
pointing to the same object (i.e both referring to the
same memory location) returns False otherwise.
is not: a is not b , returns True if both its operands are
pointing to different objects (i.e both referring to
different memory locations) returns False otherwise.
Example >>> a=235
>>> b=240
>>> c=235
>>> a is b
False
>>>a is c
True
>>> print (id(a),id(b),id(c))
492124000 492124080 492124000
Now on changing the value of B so that it is not
referring to the same integer object, then the
expression
will return True
>>> b=b-5
>>> a is b
True
>>>print(id(a),id(b),id(c))
492124000 492124000 492124000
Now b is also pointing to the same integer object as’ a’
, i.e all a, b, c reference to the same memory location.
The is not operator is opposite to the is operator. It
returns True when both its operands are not referring
to the same memory address.
Equality (==) and Identity (is) : An important relation
We have seen in previous examples that when two
variables are referring to the same value the is
operator returns True. When the is operator returns
true for two variables, it implicitly means that the
equality operator will also return True.
Expression a is b returns True means that a==b will
also be True
Example
>>> print (a,b )
235 235
>>> a is b
True
>>> a==b
True
The other way round may not be always true i.e in
some cases we find that the operator == returns True,
for some, but is operator returns False.
Example:
>>> s1= ‘ abc’
>>> s2= input(“ Enter a string “)
Enter a string abc
>>> s1== s2
True
>>> s1 is s2
False
>>> s3= ’abc’
>>> s1 is s3
True
The reason behind this behaviour is that there are few
cases where Python creates two different objects even
though both store the same value.
They are
1. Input of Strings from the console
2. Writing integers literals with many digits.
3.Writing floating point and complex literals (very big
integers).

Logical operators
The logical operators are[ OR , AND ,NOT] that refer to
the ways relationships(among values) can be
connected.
Truth value testing: Python Associates with every
value type, some truth value (the truthiness), i.e
Python internally categorises them as true or false.
Any object can be tested for truth value. Python
considers following false ( i.e the truth value as false)
and true.
Values with Truth value as Values with Truth
false value as true.
 None
 False (Boolean value false)
 Zero of any numeric type
(0 ,0.0 ,0j) All other values are
 An Empty sequence (Eg ‘ ‘, considered true
(),[])
(‘ ‘ is empty string,( ) is
empty tuple, [ ] is empty
list)
 Any empty mapping eg
{ }

Note: Boolean values belong only to just one data type,


i.e Boolean type, whereas we can test truthiness for
every value of object in Python. To avoid confusion
truth values true and false are written in lowercase
with the subscript as tval i.e true tval and false tval , will
be referring truth value of objects.
The OR operator
The OR operator combines two expressions, which
make its operands. The OR operator works in these
ways
i) Relational expressions as operands .
ii) Numbers or strings or list as operands.
Relational expressions as Operands
The operator evaluates to true if either of its operands
evaluates to true, false if both operands evaluates to
false.
X Y X or Y
False False False
False True True
True False True
True True True
Numbers/ strings/ list as operands
In an expression X OR Y if 1st operand (i.e expression X)
has false , then return the second operand Y as the
result, otherwise return X.
X Y X or Y
false tval false tval Y
false tval true tval Y
true tval false tval X
true tval true tval X
Example
0 or 8
=8 (first expression is zero has false tval hence second
expression is returned)
5 or 0.0
=5 (expression five has true tval hence first expression
is returned)
AND operator
The AND operator combines two expressions, which
make its operands. The AND operator works in these
ways
i) relational expression as operands
ii) numbers or strings or list as operands.
Relational expressions as operands
The and operator evaluates to true if both of its
relational operations evaluate to true it evaluates to
false if either or both operands evaluate to false.
X Y X and Y
False False False
False True False
True False False
True True True
Numbers/ strings /list as operands
In an expression X and Y, if 1st operand (i.e expression
X) has False tval, then return first operand X as result,
otherwise return Y.
X Y X and Y
false tval false tval X
false tval true tval X
true tval false tval Y
true tval true tval Y
The NOT operator
The Boolean / Logical NOT operator works on a single
expression or operands ,i.e it is a unary operator. The
logical NOT operator negates or reverses the truth
value of the expression following it ,i.e if the
expression is true or true tval , then the NOT expression
is false and false tval.
Unlike the AND and OR operators the NOT operator
returns always a Boolean value True or False.
Chained comparison operators
In Python we can change multiple comparison which
work like shortened version of larger Boolean
expressions
By writing >>> 1<2<3 is equivalent to
>>> 1<2 and 2<3
Bitwise operators
Bitwise operators are used to work on smaller scale-
on binary representation of data.
Bitwise operators are used to change individual bits in
an operand.(refer previous chapter for examples)
Operator Associativity
The order in which the expressions are evaluated
based on the precedence of operators is called as
operator associativity.
Precedence of operators means the ranking of each
operator.
[COPY TABLE FROM TEXT BOOK PAGE NO. 230]

OPERATOR DESCRIPTION

() Parantheses

** Exponentiation

~ Bitwise NOR

+ ,- Positive,Negative,Unary
*,/,//,% Multiplication,Division,Floor division,Remai

+,- Addition , Subtraction

& Bitwise And

OPERATOR DESCRIPTION

^ Bitwise XOR

| Bitwise OR

<,<=,>,>=,==,!=, is , is Comparisions, Identity Operators


not

*,/,//,% Multiplication,Division,Floor division,Rem

not Boolean NOT

and Boolean AND


or Boolean OR
EXPRESSIONS
An expression is a combination of operators and
operands that is interpreted to produce some other
value. In any programming language, an
expression is evaluated as per the precedence of
its operators. So that if there is more than one
operator in an expression, their precedence
decides which operation will be performed first. We
have many different types of expressions in
Python.
A. Constant Expressions: These are the
expressions that have constant values only.
# Constant Expressions
x = 15 + 1.3
print(x)
output: 16.3
B. Arithmetic Expressions: An arithmetic
expression is a combination of numeric values,
operators, and sometimes parenthesis. The result
of this type of expression is also a numeric value.
The operators used in these expressions are
arithmetic operators like addition, subtraction, etc.
Here are some arithmetic operators in Python:

Operator
s Syntax Functioning

+ x+y Addition

– x–y Subtraction
* x*y Multiplication

/ x/y Division

// x // y Quotient

% x%y Remainder
** x ** y Exponentiation
Example:
# Arithmetic Expressions
x = 40
y = 12
add = x + y
sub = x - y
pro = x * y
div = x / y
print(add)
print(sub)
print(pro)
print(div)
Output : 52
28
480
3.3333333333333335
C. Relational Expressions: In these types of
expressions, arithmetic expressions are written on
both sides of relational operator (> , < , >= , <=).
Those arithmetic expressions are evaluated first,
and then compared as per relational operator and
produce a boolean output in the end. These
expressions are also called Boolean expressions.
Example:

# Relational Expressions
a = 21
b = 13
c = 40
d = 37
p = (a + b) >= (c - d)
print(p)

Output: True
D. Logical Expressions: These are kinds of
expressions that result in either True or False. It
basically specifies one or more conditions. For
example, (10 == 9) is a condition if 10 is equal to 9.
As we know it is not correct, so it will return False.
Studying logical expressions, we also come across
some logical operators which can be seen in logical
expressions most often. Here are some logical
operators in Python:

Operato
r Syntax Functioning

It returns true if both P and


P and Q are true otherwise returns
and Q false

It returns true if at least one


or P or Q of P and Q is true

It returns true if condition P


not not P is false.

Example:
P = (10 == 9)
Q = (7 > 5)
# Logical Expressions
R = P and Q
S = P or Q
T = not P
print(R)
print(S)
print(T)

Output
False
True
True
E. Bitwise Expressions: These are the kind of
expressions in which computations are performed
at bit level.
Bitwise AND &
Bitwise OR |
Bitwise left shift <<
Bitwise Right shift >>
Example:

# Bitwise Expressions
a = 12
x = a >> 2
y = a << 1
print(x, y)

Output
3 24
LIST AND TUPLES
List and tuples are Pythons compound data types.
Can be changed / modified (i.e immutable) but
tuples cannot be changed or modified (i.e
immutable).
List: A list in Python represents a list of comma -
separated values of any data type between square
brackets.
Example
[ 1, 2,3,4,5 ]
[ a, e, i ,o, u ]
[ "Riya", 102, 79.5]

Like any other value you can assign a list to a


variable.
Example
>>> a =[ 1,2,3, 4, 5]
>>> a
[ 1, 2, 3, 4, 5]
>>> print (a)
[1, 2, 3, 4, 5]
To change first value in a list namely 'a ' you may
write
>>> a[0]= 10
>>>a
[ 10, 2,3, 4,5]
Change the third item you may write
>>> a[2]= 30
>>>a
[10 ,2, 30,4,5]
The first item of a list is internally numbered as 0,
second as 1 and so on.

TUPLES: This is a list which cannot be changed,i.e


they are not modifiable.
Tuples are represented as group of comma
separated values of any data type within
parenthesis.
Example
p= (1,2,3,4, 5)
Q =(2, 4, 6,8)
R=( 'a', 'e', 'i','o' ,'u')
h= (7, 8, 9, 'a', 'b' ,'c')
Note: values of type list are mutable i.e
changeable, one can change / add / list elements.
But values of type tuple are immutable i.e non
changeable, one cannot make changes to a tuple.
SETS
Sets are similar to list, that can store multiple
values same as in mathematical sets. But Python
sets are different from list.
The differences are
1) are sets are created by specifying comma
separated values enclosed in curly brackets {}
2) sets elements are unordered and unindexed
unlike lists
3) sets do not allow duplicate entries unlike lists
4) sets cannot contain mutable elements.

Consider the example


>>> myset={ 1, 2, 3 ,4 }
>>> print(myset)
{ 1, 2, 3, 4}
# set created by specifying comma separated by
enclosed in curly brackets{}

>>> myset1 ={ 1, 2 , 3, 4, 4}
>>> print(myset1)
{ 1, 2,3, 4}
>>> type (myset)
< class ' set'>
Python data types strings, list, tuples, dictionary
etc are all iterables.
>>>set1={1,2.[3.4]}
set1={1,2,[3,4]} type error: Unhashable type: 'List'

Sets do not allow mutable elements like list. It will


display an error message when we try to add a list
as an element, but it will give no error when we
give a tuple as an element because a tuple is not
mutable.
>>>set1={1,2,(3,4)}
Note: A set cannot contain a mutable element in it.
However a set itself is mutable i.e we can add or
remove elements from it.

Dictionary
A dictionary in Python is an an ordered set of
comma separated key: Value pairs, within{} , with
the requirement that within a dictionary no two
keys can be the same(i.e there are unique keys
within a dictionary)
Examples
>>> vowels={'a':1, 'e':2, 'i':3, 'o':4 , 'u':5 }
>>> vowels ['a']
1
In the above code segment a, e , i, o,u are keys of
the dictionary vowels, 1, 2,3,4,5 you are values of
these keys respectively. Specifying the keys inside[]
after the dictionary name gives the corresponding
value from the key: Value pair inside the
dictionary.
MUTABLE AND IMMUTABLE TYPES
Python data objects can be broadly categorised
into mutable and immutable types(changeable for
modifiable and non modifiable types)
Immutable types
The imitable types are those data objects which
can never change their value in place. Following
types are immutable: Integers, floating point
numbers, Boolean, strings, tuples.
Example
P=5
Q=P
R=5
All variables having same value reference, the
same value object, i.e P,Q,R will all reference the
same integer objects.
Your teach integer value is an immutable object.
>>>P=5
>>>Q=P
>>>R=5
>>>id(5)
1457662208
>>>id(P)
1457662208
>>>id(Q)
1457662208
>>>id(R)
1457662208
We notice had id () is returning same memory
address for values 5,P,Q,R which means all these
are referencing the same.

Example 2
P=10
R=7
Q=R
Here the variable names are made to point to
integer objects. Hence their memory addresses
that they reference will change.

>>>P=10
>>>R=7
>>Q=R
>>>id(10)
1457662288
>>>id(P)
1457662288

>>>id(7)
1457662240
>>>id(Q)
1457662240
>>>id(R)
1457662240
>>>id(5)
1457662208
On assigning 5 to any other variable
>>>t=5
>>>id(t)
1457662208
Hence it is clear that variable names are stored as
references to a value object. Time when we change
the value, reference memory addresses changes.
Variables (of certain types) are NOT LIKE are
storage containers i.e with fixed memory address
where value changes every time. Hence they are
immutable.
MUTABLE TYPES
The mutable types are those whose values can be
changed in place.
There are only three mutable types in Python -
lists, dictionaries and sets.
To change any member in a list you may write as
chk=[2,4,6]
chk[1]=40
This will make the change in chk as [2,40,6]
>>>chk=[2,4,6]
>>>id(chk)
150595536
>>>chk[1]=40
>>>id(chk)
150595536
From the above program segment we see that even
after changing a value in the list chk , its reference
memory address has remained the same. That
means the change has taken place- the lists are
mutable.

Python Standard Modules


Math module [COPY TABLE FROM PAGE
N0.242]
Function Prototype Description
ceil() math.ceil() Rounds a
number up to
the nearest
integer
sqrt() math.sqrt() Returns the
square root of
a number
degrees() math.degrees() Converts an
angle from
radians to
degrees
exp() math.exp() Returns E
raised to the
power of x
fabs() math.fabs() Returns the
absolute value
of a number
factorial() math.factorial() Returns the
factorial of a
number
floor() math.floor() Rounds a
number down
to the nearest
integer
fmod() math.fmod() Returns the
remainder of
x/y
gcd() math.gcd() Returns the
greatest
common
divisor of two
integers
log() math.log() Returns the
natural
logarithm of a
number, or
the logarithm
of number to
radians() math.radians() Converts a
degree value
into radians
log10() math.log10() Returns the
base-10
logarithm of x.
pow() math.pow() Returns the
value of x to
the power of y
sin() math.sin() Returns the
sine of a
number
cos() math.cos() Returns the
cosine of a
number
tan() math.tan() Returns the
tangent of a
number

Writing equivalent Python Expression


1)A2 +B2 +2AB
Solution: A*A +B*B+2*A*B
2)√B2 -4AC
Solution : math.sqrt(B*B -4*A*C)

3 ) q/(r+s)5
Solution: q/math.pow((r+s),5)

[SOLVE Q.NO 21 FROM PAGE 264]

Using random module


Python has a module namely random that
provides random number generator . A
random number in simple words means a
number generated by chance i.e randomly.
To use random number generator in your
Python program you first need to import
module random using any import command.
import random
The three most common random number
generator functions in random module are
random () : It returns or random floating
point number N in the range[0.0, 1.0]. Notice
that the number generated with random() will
always be less than 1.0(only Lower range limit
is inclusive). It generates a floating point
number.

randint (a,b) : It returns a random integer N


in the range(a,b) i.e a<= N<= b
( both range limits inclusive). It generates an
integer.
Using randrange() function
i) random.randrange(<stop value>)
>>> random.randrange(56)
25
ii) random.randrange(<start>,<stop value>)
>>> random.randrange(12,56)
35
iii) random.randrange(< start>,< stop>,<
step>) : It returns Random numbers from
range Start... Stop with step value.
The following code will generate a random
number in the range 11 to 45 , with a step
value 4. That means the possible random
numbers generated could be one of the values
11, 15,19,23,27,31,35,39,43.
>>> random.randrange(11,45,4)
15
>>> random.randrange(11,45,4)
35
>>> random.randrange(11,45,4)
39
Using the statistic module
The statistics module in the Python standard
library provides many statistics functions such
as mean(), median(), mode() etc. In order to use
these functions in the program you need to
first import Python statistics module by giving
one of the following statements
import statistics
OR
From statistics import mean, median, mode

You can then use this functions As given


below
statistics.mean(<seq>) : It returns the average
value of the set/ sequence of values passed.
statistics.median(<seq>) : It returns the
middle value of the set/ sequence of values
passed.
Statistics.mode(<seq>) : It returns the most
often repeated value of the set/ sequence of
values passed.
Example
>>> import statistics
>>> seq=[5 ,6 ,7,5,6,5 ,5,9,11,12,23,5]
>>> statistics.mean(seq)
8.25
>>> statistics.median(seq)
9.0
>>> statistics.mode(seq)
5
Type casting
Conversion of one data type to another data type
explicitly is called as type casting.

General Form of Type Casting


<datatype>(variable/Expression)

Example : a=9 ,b=5.0

int(b) will cast the data-type of expression as int.

d=float(a) will assign value 9.0 to d.

Debugging
Debugging refers to the process of locating the
place of error, cause of error and correcting
the code accordingly.
An error is also called as a bug and it is
anything in the code that prevents a program
from compiling and running correctly.
The different types of errors are Compile time
error and Run runtime errors and Logical
errors
Errors that occur during compile time are
compile-time errors .The two types of which
fall under this category are Syntax errors and
Semantic errors.
Syntax errors: Syntax errors occur when rules
of a programming language are misused i.e
when a grammatical rule of Python is violated.
Example :
Print(x)
Marks 1=85
Semantic error: Semantics refers to the set of
rules which give the meaning to a statement. A
statement may be grammatically correct but
there are semantic rules of programming
language and violation of such rules is called
as a semantical error.
Example X*Y= Z.

Runtime errors: The errors that occur during


the execution of the program are called as
runtime errors. It is difficult to detect such
errors since some errors stop the execution of
the program which is called abnormal
termination of the program.
An example for a runtime error is an infinite
loop or a situation where a wrong value is
inputted.
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. Hence the program should be
robust so as to recover and continue following
and error.

Logical error: Sometimes we do not encounter


any error during compile time,
but the program does not provide the correct
result. This is because the programmer does
not analyse the problem properly which he is
trying to solve and it results in errors and
such errors are called as logical errors.

Debugging using code tracing


The most common technique to debug the
error is to find the point of error and origin of
error. This is often done by printing the values
of every intermediate result and of all values.
For this purpose code tracing is one of the
most commonly used technique. Code tracing
means executing the code one line at a time
and watching its impact on variables. One way
of code tracing is using dry run.

****************************************************
**********************

You might also like