Data Handling

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

Chapter 7

Data Handling
Introduction, Data Types, Mutable and Immutable Types, Operators, Expressions, Introduction to Python
Standard Library Modules, Debugging
DATA TYPES
Data types are used to identify type of data and set of valid operations for it. Python offers the following
built-in core data types:
1. Numbers
2. String
3. List
4. Tuple
5. Dictionary
1. Data Types for Numbers
Python offers the following data types to store and process different types of numeric data:
a. Integers
 Integers (signed). Python provides single data type (int) to store any positive or negative integer
(i.e. whole number), whether big or small.
 Booleans. Subtype of integers, and Boolean values False and True behave like the values 0 and
1, respectively. To get the Boolean equivalent of 0 or 1, you can type bool(0) or bool(1), Python
will return False or True respectively.
b. Floating-Point Numbers. Represent machine-level double precision floating point numbers (15 digit
precision). The range of these numbers is limited by underlying machine architecture subject to
available (virtual) memory.
c. Complex Numbers. Represent complex number in the form A + B j, where 𝑗 = √−1. Complex
numbers are made of two parts: the real part (A) and the imaginary part (B), both are represented
internally as float values.
The Range of Python Numbers
Data type Range

Integers an unlimited range, subject to available (virtual) memory only.

Booleans two values True (1), False (0).

Floating point an unlimited range, subject to available (virtual) memory on underlying machine
numbers architecture.

Complex numbers same as floating point numbers because the real and imaginary parts are represented
as floats.

2. Data Type for Strings


 All strings in Python are sequences of pure Unicode characters.
 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.
 A Python string is a sequence of characters and each character can be individually accessed using its
index. Valid string indices are 0, 1, 2, …, up to length–1 in forward direction, and –1, –2, –3, …, –
length in backward direction.
Example:

String as a Sequence of Characters


 Stored as individual characters in contiguous location.

 Length of string variable can be determined using function


len(<string>)
 To determine length of above shown string name, you may write:
len(name)
which will give you 6, indicating that string name stores six characters.
 Any character in the string can be accessed as:
<stringname>[<index>]
 The index (or subscript) is the numbered position of a letter in the string. In Python, for any string of
length size, the valid indices are:
 0, 1, 2, …, size–1 in the forward direction and
 –1, –2, –3, …, –size in the backward direction
 If you try to access the string name by using:
>>> name[size]
Python will return an error like:
name[size]
IndexError: string index out of range
The reason is that in a string there is no index equal to the length of the string, thus accessing an
element with an invalid index causes an error.
 You cannot change the individual letters of a string in its place by assignment because strings are
immutable and hence item assignment is not supported, i.e.,
>>> name[0]=‘S’
will cause an error like:
name[0]=‘S’
TypeError: ‘str’ object does not support item assignment
 However, you can assign to a string another string or an expression that returns a string using
assignment, e.g., following statement is valid:
name=‘hello’
name=“new”
3. Lists
 A list represents a group of comma–separated values of any datatype enclosed between square
brackets.
Example:
[1, 2, 3, 4, 5]
[‘a’, ‘e’, ‘I’, ‘o’, ‘u’]
[‘Neha’, 102, 79.5]
You can assign a list to a variable, e.g.,
>>> a=[1,2,3,4,5]
>>> a
[1,2,3,4,5]
>>> print(a)
[1,2,3,4,5]
 In list also, the values internally are numbered from 0 (zero) onwards, i.e., first item of the list is
internally numbered as 0, second item of the list as 1, 3 rd item as 2, and so on.
 Values of list are mutable, i.e., changeable – one can change / add / delete a list’s element. To change
the third value in the list a (given above), you may write
>>> a[2]=30
>>> a
[1,2,30,4,5]
4. Tuples
 Tuples are represented as group of comma–separated values of any data type within parentheses.
 Values of tuple are immutable, i.e., non–changeable; one cannot make changes to a tuple.
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’)
5. Set
 A set is a mutable data type which is created like lists, but enclosed within { }.
 It can take values of different types but cannot contain mutable elements and duplicate entries.
 The sets elements are unordered and unindexed.
Example:
Set1 = {1, 2, 3, 4}
6. Dictionaries
 The dictionary is an unordered set of comma–separated key :value pairs, enclosed within { }, with
the requirement that within a dictionary, no two keys can be the same (i.e., there are unique keys
within a dictionary).
Example:

Summary of Core Data Types of Python

Data types strings, lists, tuples, dictionary, etc., are all iterables. An iterable is any Python object that can
return its members, one at a time.
MUTABLE AND IMMUTABLE TYPES
Immutable Types
1. The immutable types are those that can never change their value in place. The following types are
immutable:
integers, floating point numbers, Booleans, strings, tuples.
2. Python frontloads some commonly used values in memory.
3. In immutable types, each variable referring to that value actually store that memory addresses of the
value.
4. Multiple variables / identifiers can refer to a value.
5. Internally, Python keeps count of how many identifiers / variables are referring to a value.
6. Each time you change the value, the variable’s memory address changes.
Example to Illustrate Immutable Types
p=5
q=p
r=5
.
.
.
p = 10
r=7
q=r
Mutable Types
7. Mutability means that in the same memory address, new value can be stored as and when you want.
8. The mutable types are those whose values can be changed in place. The following types are mutable:
lists, dictionaries, and sets.
Example: To change a member of a list, you may write:
chk = [2, 4, 6]
chk [1] = 40
The above statement will make the list namely chk as [2, 40, 6].
>>> chk=[2,4,6]
>>> id(chk)
150195536
Even after changing a value in the list chk, the reference memory address has
>>> chk[1]=40
remained same. That means, the change has taken in place – the lists are
>>> id(chk)
mutable.
150195536
>>> chk
[2,40,6]

Variable Internals
Since Python is an object oriented language, it 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 behavior, e.g.,
integers are objects – they hold whole numbers only and they have infinite precision (properties); they
support all arithmetic operations (behavior).
A variable is also an object that refers to a value. Python objects have three key attributes associated to it:
1. The type of an object: The type determines the operations that can be performed on the object. Built-in
function type() returns the type of an object.
>>> a=4
>>> type(4)
<class ‘int’>
>>> type(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 it is currently referencing. Using print statement you
can display value of an object.
>>> a=4
>>> print(4)
4
>>> print(a)
4
3. The id of an object: The id is the memory location of that object. Built-in function id() returns the
memory location of an object.
>>> id(4)
30899132
>>> a=4
>>> id(a)
30899132
The id() of a variable is same as the id() of value it is storing.

OPERATORS
Operators perform some computation / action when applied to variables and other objects in an expression.
The data on which operation is being carried out, i.e., the variables or objects are referred to as operands.
The operators of Python are:
1. Arithmetic Operators (+, –, *, /, %, **, //): Each of these operators is a binary operator, i.e., it requires
two operands to perform the operation. Python also provides two unary arithmetic operators (that require
one operand), which are unary + and unary –.

Symbol Name Example Result Comment


6+5 11
+ Addition Adds values of its two operands.
5+6 11
6–5 1
– Subtraction Subtracts the value of right operand from left operand.
5–6 –1
5*6 30
* Multiplication Multiplies the values of its two operands.
6*5 30
Divides the value of left operand with the value of
/ Division 60 / 5 12.0
right operand and returns the result as a float value.
Modulus or 60 % 5 0
% Divides the two operands and returns the remainder.
Remainder 6%5 1
Divides and truncates the fractional part from the
// Floor division 7.2 // 2 3.0
result.
Exponentiation
** 2.5 ** 3 15.625 Returns base raised to power exponent (i.e., 2.53).
(Power)
Python also offers + as a concatenation operator when used with strings, lists and tuples. Similarly, *
can be used as a replication operator when used with strings.
Negative Number Arithmetic in Python:
>>> 5//-3 -2 -2
-2 -3 5 3 -5
>>> -5//3 6 ¤ -6
-2 -1 1
>>> -7%4 -2 -2
1 4 -7 -4 7
>>> 7%-4 -8 ¤ 8
-1 1 -1
Augmented Assignment Operators: These operators combine the impact of an arithmetic operator with
an assignment operator (i.e., =).
Operation Description Comment
x+=y x=x+y Value of y added to the value of x and then result assigned to x.
x-=y x=x-y Value of y subtracted from the value of x and then result assigned to x.
x*=y x=x*y Value of y multiplied to value of x and then result assigned to x.
x/=y x=x/y Value of y divides value of x and then result assigned to x.
x//=y x=x//y Value of y does floor division to value of x and then result assigned to x.
x**=y x=x**y xy computed and then result assigned to x.
x%=y x=x%y Value of y divides value of x and then remainder assigned to x.
Augmented assignment holds only for immutable types. For iterable mutables such as lists, it doesn’t
hold (i.e., for lists x+=y is not equal to x=x+y). Augmented assignment operators also work with
bitwise operators.
2. Relational or Comparison Operators (<, >, <=, >=, ==, !=): Python provides the relational operators for
comparing values. If the comparison is true, the relational expression results into the Boolean value True
and to Boolean value False, if the comparison is false. Relational operators work with all types of data
such as numbers, strings, lists, tuples, etc.
 For numeric types, the values are compared after removing trailing zeros after decimal point from a
floating-point number.
Example: Numbers 4 and 4.0 will be treated as equal.
It is not recommended to use == operator to compare two floating-point numbers. The reason is that
floating-point numbers are stored with some precision limit and result in some rounding off, hence
will not yield the correct result. Consider the following code:
>>> 0.1 + 0.1 + 0.1 == 0.3
False
>>> print (0.1 + 0.1 + 0.1)
0.30000000000000004
Thus, you should avoid floating-point equality comparisons as much as you can.
 Strings are compared on the basis of lexicographical ordering (i.e., dictionary ordering).
Lexicographical ordering is implemented via the corresponding codes or ordinal values (e.g., ASCII
or Unicode) of the characters being compared.
Example: Character ‘A’ is less than ‘a’ because ASCII value of ‘A’ (i.e., 65) is less than ‘a’ (i.e., 97).
The ordinal code of a character can be determined using ord(<character>) function (e.g.,
ord(‘A’)).
 Two lists and similarly two tuples are equal if they have same elements in the same order.
 Boolean True is equivalent to 1 and Boolean False to 0 for comparison purposes.
Examples:
P Q P < Q P <= Q P == Q P > Q P >= Q P != Q
3 3.0 False True True False True False
6 4 False False False True True True
‘A’ ‘A’ False True True False True False
‘a’ ‘A’ False False False True True True
“God” < “Godhouse” will return True. Both match up to the letter ‘d’ but ‘God’ is shorter than
‘Godhouse’ so it comes first in the dictionary.
“god” < “Godhouse” will return False. The length of the strings does not matter here. Lower case ‘g’ is
greater than upper case ‘G’.
A very common mistake is to use the assignment operator = in place of the equality operator ==. For
instance, the expression:
value1==3
tests whether value1 is equal to 3. The expression has the value True if the comparison is true;
otherwise, it is False. But the expression
value1=3
assigns 3 to value1; no comparison takes place.
3. Identity operators (is, is not): The identity operators compare the memory locations of two objects
and return True or False accordingly. The id() function is used to determine the memory location.
Operator Usage Description
Returns True is both its operands are pointing to same object (i.e., both
is a is b
referring to same memory location), returns False otherwise.
Returns True is both its operands are pointing to different objects (i.e.,
is not a is not b
both referring to different memory location), returns False otherwise.
Consider the following 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
The ids of a, b and c tell that a and c are referring to same object (their memory addresses are same),
but b is referring to a different object as its memory address is different from the other two.
Equality (==) and Identity (is): When the is operator returns True for two variables, it implicitly
means that the equality operator will also return True. There are some cases where you will find that
the two objects are having just the same value, i.e., == operator returns True for them but the is
operator returns False. Consider the following code:
>>> s1 = ‘abc’
>>> s2 = input(“Enter a string: ”)
Enter a string: abc
>>> s1 == s2
True
>>> s1 is s2
False
The strings s1 and s2 although have the same value ‘abc’ in them, and the == operator also returns
True for s1 == s2, but the is operator returns False for s1 is s2.
The reason behind this behavior is that there are a few cases as shown below where Python creates two
different objects even though both store the same value.
 Input of strings from the console.
 Writing integers literals with many digits (very big integers).
 Writing floating-point and complex literals.
4. Logical operators (and, or, not): These operators refer to the ways the relationships (among values)
can be connected. The results of logical operators are based on truth value testing.
Truth Value Testing: Python associates with every value type, some truth value (the truthiness), i.e.,
Python internally categorizes them as true or false. Any object can be tested for truth value.
Values with truth value as false Values with truth value as true
None
False (Boolean value False)
Zero of any numeric type, e.g., 0, 0.0, 0j
All other values are considered true.
Any empty sequence, e.g., '', (), []
('' is empty string; () is empty tuple; and [] is empty list)
Any empty mapping, e.g., {}
The result of a relational expression can be True or False depending upon the values of its operands
and the comparison taking place.
Boolean values belong to just one data type, i.e., Boolean type, whereas we can test truthfulness (i.e.,
zero or empty) for every value object in Python.
The or Operator: The or operator combines two expressions, which make its operands.
a) Relational expressions as operands: The or operator evaluates to True if either of its (relational)
operands evaluates to True; False if both operands evaluate to False.
b) Numbers / strings / lists as operands: In an expression x or y, if first operand (i.e., expression x)
has falsetval (i.e., false truthvalue), then return second operand y as result, otherwise return x.
Examples:
Results
Operation Reason
into
0 or 0 0 1st expression (0) has falsetval, thus 2nd expression 0 is returned.
0 or 8 8 1st expression (0) has falsetval, thus 2nd expression 8 is returned.
5 or 0.0 5 1st expression (5) has truetval, thus 1st expression 5 is returned.
1st expression ('hello') has truetval, thus 1st expression 'hello'
'hello' or '' 'hello'
is returned.
'' or 'a' 'a' 1st expression ('') has falsetval, thus 2nd expression 'a' is returned.
'' or '' '' 1st expression ('') has falsetval, thus 2nd expression '' is returned.
'a' or 'j' 'a' 1st expression ('a') has truetval, thus 1st expression 'a' is returned.
The and Operator: The and operator combines two expressions, which make its operands.
c) Relational expressions as operands: The and operator evaluates to True if both of its (relational)
operands evaluates to True; False if either or both operands evaluate to False.
d) Numbers / strings / lists as operands: In an expression x and y, if first operand (i.e., expression x)
has falsetval (i.e., false truthvalue), then return first operand x as result, otherwise return y.
Examples:
Results
Operation Reason
into
0 and 0 0 1st expression (0) has falsetval, thus 1st expression 0 is returned.
0 and 8 0 1st expression (0) has falsetval, thus 1st expression 8 is returned.
5 and 0.0 0.0 1st expression (5) has truetval, thus 2nd expression 0.0 is returned.
1st expression ('hello') has truetval, thus 2nd expression '' is
'hello' and '' ''
returned.
'' and 'a' '' 1st expression ('') has falsetval, thus 1st expression '' is returned.
'' and '' '' 1st expression ('') has falsetval, thus 1st expression '' is returned.
'a' and 'j' 'j' 1st expression ('a') has truetval, thus 2nd expression 'j' is returned.
The not Operator: The not operator works on single expression or operand, i.e., it is a unary operator.
This operator negates or reverses the truth value of the expression following it, i.e., if the expression is
True or truetval, then not expression is False, and vice versa. The not operator always returns a
Boolean value True or False.
Examples:
not 5 Results into False because 5 is non-zero (i.e., truetval).
not 0 Results into True because 0 is zero (i.e., falsetval).
not -4 Results into False because -4 is non-zero (i.e., truetval).
not (5 > 2) Results into False because the expression 5 > 2 is True.
not (5 > 9) Results into True because the expression 5 > 9 is False.
The following table summarizes the logical operators.
Operation Result Notes
If x is falsetval, then return y or only evaluates the second argument if the first one is
x or y
as result, else x falsetval.
If x is falsetval, then return x and only evaluates the second argument if the first one is
x and y
as result, else y truetval.
If x is falsetval, then return
not x not has a lower priority than non-Boolean operators.
True as result, else False
Chained Comparison Operators: You can chain multiple comparisons which are like shortened version of
larger Boolean expressions. For example,
>>> 1 < 2 < 3 >>> 1 < 2 and 2 < 3
is equivalent to
True True
The expression 1 < 2 will be first evaluated and if and only if it is True, then only the next chained
expression 2 < 3 will be evaluated.
5. Bitwise operators (&, |, ^): These operators work on binary representation of data. Bitwise operators are
used to change individual bits in an operand.
The AND operator &: When its operands are numbers, the & operation performs the bitwise AND
function on each parallel pair of bits in each operand. The AND function sets the resulting bit to 1 if the
corresponding bit in both operands is 1; 0 otherwise.
Example:
13 & 12 0000 1101 >>> bin (13)
0000 1100 '0b1101'
0000 1100 >>> bin (12)
'0b1100'
>>> 13 & 12
12
>>> bin (13 & 12)
'0b1100'
The inclusive OR operator |: When both of its operands are numbers, the | operation performs the
inclusive OR operation. The inclusive OR means that if either of the two bits is 1, the result is 1; 0
otherwise.
Example:
13 | 12 0000 1101 >>> bin (13)
0000 1100 '0b1101'
0000 1101 >>> bin (12)
'0b1100'
>>> 13 | 12
13
>>> bin (13 | 12)
'0b1101'
The eXclusive OR (XOR) operator ^: Exclusive OR means that if the two operand bits are different, the
result is 1; otherwise the result is 0.
Example:
13 ^ 12 0000 1101 >>> bin (13)
0000 1100 '0b1101'
0000 0001 >>> bin (12)
'0b1100'
>>> 13 ^ 12
1
>>> bin (13 ^ 12)
'0b1'
The complement operator ~: This operator inverts the value of each bit of the operand. If the operand bit
is 1, the result is 0, and if the operand bit is 0, the result is 1.
Example:
~12 0000 1100 >>> bin (12)
1111 0011 '0b1100'
= -(0000 1101) >>> ~12
In the result of ~12 (i.e., 1111 0011), the leftmost bit [i.e., the most -13
significant bit (MSB)] represents the sign bit. If the sign bit is 1, it represents a >>> bin (13)
negative number, and hence 2’s complement is used to find the decimal '0b1101'
equivalent. 2’s complement can be determined by finding the 1’s complement >>> bin (~12)
(i.e., complementing the individual bits) and then adding 1 to it. '-0b1101'
In the above example, the 2’s complement of 1111 0011 is 0000 1100 + 1 = -(0000 1101).
The – (i.e., minus) sign is because it represents a negative number.
Operator Precedence Table
Operator Description
() Parentheses (grouping)
** Exponentiation
~ x Bitwise NOR
+x, –x Positive, negative (unary +, –)
*, /, //, % Multiplication, division, floor division, remainder
+, – Addition, Subtraction
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
<, <=, >, >=, <>, !=, ==, is, is not Comparisons (Relational operators), identity operators
not x Boolean NOT
and Boolean AND
or Boolean OR
Operator Associativity: Associativity is the order in which an expression having multiple operators of same
precedence is evaluated. Almost all the operators have left–to–right associativity except exponentiation
(**), which has right–to–left associativity.
In case if an expression has multiple operators with left–to–right associativity and of same precedence, the
operator on the left is evaluated first and then the operator on its right and so on.
Example:
>>> 7*8/5//2
5.0
>>> (((7*8)/5)//2)
5.0
An expression having multiple ** operators is evaluated from right to left, i.e., 2**3**2 will be evaluated
as 2**(3**2) and not as (2**3)**2.
Example:
>>> 2**3**2
512
>>> 2**(3**2)
512
>>> (2**3)**2
64

EXPRESSIONS
An expression is any valid combination of operators, literals and variables. The expressions can be of any
type:
1. Arithmetic expression – An expression having literals and / or variables of numeric type and arithmetic
operators.
Example: 2 + 5 ** 3, –8 * 6 / 5
2. Relational expression – An expression having literals and / or variables of any valid type and relational
operators.
Example: x > y, y <= z, z != x, z == q, x < y > z, x == y != z
3. Logical expression – An expression having literals and / or variables of any valid type and logical
operators.
Example: a or b, b and c, a and not b, not c or not b
4. String expression – An expression involving string operands, integers and string operators + and *.
Example: “and” + “then” # would result in ‘andthen’ – concatenation
“and” * 2 # would result in ‘andand’ – replication
Evaluating Arithmetic Operations
The following are the rules to evaluate an arithmetic expression:
1. Determine the order of evaluation in an expression considering the operator precedence.
2. As per the evaluation order, for each of the sub-expression (generally of the form
<value><operator><value>, e.g., 13 % 3):
 Evaluate each of its operands.
 Perform any implicit conversions (e.g., promoting int to float, or bool to int, for arithmetic on mixed
types).
 Compute its result based on the operator.
 Replace the subexpression with the computed result and carry on the expression evaluation.
 Repeat till the final result is obtained.
In a mixed arithmetic expression, Python converts all operands up to the type of the largest operand (type
promotion).
In an expression of the simplest type op1 operator op2 (e.g., x / y), if both operands are standard numeric
types, the following implicit type conversions (Coercions), i.e., conversions performed by the compiler
without programmer’s intervention, are applied:
1. If either operand is a complex number, the other is converted to complex;
2. Otherwise, if either operand is a floating point number, the other is converted to floating point;
3. No conversion if both operands are integers, except for division (/) operator. For a division operation, the
evaluated value will be of floating point type.
Evaluating Relational Operations
1. All relational operations have the same priority, and lower than that of any arithmetic operations.
2. All relational expressions yield Boolean values only, i.e., True or False.
3. Chained expressions such as a < b < c is internally treated as a < b and b < c.
Evaluating Logical Operations
1. The precedence of logical operators is lower than the arithmetic operators, and hence arithmetic
subexpression (if any) is evaluated first and then logical operators are applied.
Example: 25 / 5 or 2.0 + 20 / 10 will be evaluated as 5.0 or 4.0 = 5.0
2. The precedence of logical operators among themselves is not, and, or. So, the expression
a or b and not c will be evaluated as (a or (b and (not c))).
Similarly, the expression
p and q or not r will be evaluated as ((p and q) or (not r)).
3. While evaluating or operation, Python evaluates the second argument only if the first one is False.
Similarly, for and operation, the second argument is evaluated only if the first one is True.
Examples:
Find the final result and data type for the expressions given below.
1) a, b = 3, 6 2) a, b = 3, 6 3) a, b = 3, 6.0
c=b/a c = b // a c=b%a

Ans. Ans. Ans.


c=6/3 c=6/3 c = 6.0 % 3
c = 2.0 c=2 c = 0.0

/ always gives floating pt. result

4) (5 < 10) and (10 < 5) or (3 < 18) and not 8 < 18
Ans. (True and False) or (True and (not True))
= False or (True and False) = False or False = False
Type Casting (Explicit Type Conversion)
A user-defined conversion that forces an expression to be of specific type.
Syntax: <data-type> (expression)
where <data-type> is the data type to which you want to type cast your expression.
For example, if we have (a = 3 and b = 5.0), then
int (b)
will type cast the data-type of the float expression b = 5.0 as int.
Python Data Conversion Functions:
S. Conversion Conversion
Examples
No. From To Function
int(7.8) will give 7
Any number-convertible
(floating-point number to integer conversion)
1 type, e.g., a float, a string Integer int()
int('34') will give 34
having digits
(string to integer conversion)
float(7) will give 7.0
Any number-convertible Floating-
(integer to floating-point number conversion)
2 type, e.g., a float, a string point float()
float('34') will give 34.0
having digits number
(string to floating-point number conversion)
S. Conversion Conversion
Examples
No. From To Function
complex(7) will give 7+0j
(1 argument – integer to complex number
Complex conversion)
3 Numbers complex()
number complex(3,2) will give 3+2j
(2 arguments – integer to complex number
conversion)
str(3)will give '3'
(integer to string conversion)
str(5.78) will give '5.78'
(floating-point number to string conversion)
str(0o17) will give '15'
4 Number Booleans String str()
(octal number to string conversion)
str(1+2j) will give '(1+2j)'
(complex number to string conversion)
str(True) will give 'True'
(Boolean to string conversion)
bool(0)will give False
bool(0.0)will give False
bool(1) will give True
bool(3) will give True
bool('') will give False
5 Any type Boolean bool()
bool('a') will give True
bool('hello') will give True
With bool(), non-zero & non-empty values
of any type will give True and rest (i.e., zero,
empty values) will give False.

Type Casting Issues: Assigning a value to a type with a greater range (e.g., from int to float) poses no
problem. However, assigning a value of larger data type to a smaller data type (e.g., from float to int)
may result in losing some precision.
Floating-point type to integer type conversion results in loss of fractional part. Original value may be out of
range for target type, in which case result is undefined.

INTRODUCTION TO PYTHON STANDARD LIBRARY MODULES


Other than built-in functions, standard library also provides some modules having functionality for
specialized actions. A Python module is a file which contains some variables and constants, some functions,
objects, etc. defined in it, which can be used in other Python programs.
In order to use a module, you need to first import the module in a program and then you can use the module
functions, variables, constants and other objects in your program file.

Working with math Module of Python


1. Python’s standard library provides a module namely math for mathematical related functions that work
with all number types except complex numbers.
2. To work with math module functions, you need to first import it to your program by typing the
following statement as the top line of your Python Script:
import math
Then you can use any math library’s function as
math.<function-name>
Some Mathematical Functions in math Module
S. Function Prototype Description Example
No. (General Form)
1 ceil math.ceil (num) The ceil( ) function returns the math.ceil (1.03) gives 2.0
smallest integer not less than math.ceil (–1.03) gives –1.0
num.
2 sqrt math.sqrt (num) The sqrt( ) function returns the math.sqrt (81.0) gives 9.0
square root of num. If num< 0,
domain error occurs.
3 exp math.exp (arg) The exp( ) function returns the math.exp (2.0) gives the
natural logarithm e raised to value of e2
the arg power.
4 fabs math.fabs (num) The fabs( ) function returns the math.fabs (1.0) gives 1.0
absolute vaue of num. math.fabs (–1.0) gives 1.0
5 floor math.floor (num) The floor( ) function returns the math.floor (1.03) gives 1.0
largest integer not greater than math.floor (–1.03) gives –2.0
num.
6 log math.log (num, [base]) The log( ) function returns the math.log (1.0) gives the
natural logarithm for num. A natural logarithm for 1.0
domain error occurs if num is math.log (1024, 2) will give
negative and a range error logarithm of 1024 to the base
occurs if the argument num is 2
zero.
7 log10 math.log10 (num) The log10 ( ) function returns math.log10 (1.0) gives base 10
the base 10 logarithm for num. A logarithm for 1.0
domain error occurs if num is
negative and a range error
occurs if the argument is zero.
8 pow math.pow (base, exp) The pow( ) function returns base math.pow (3.0, 0) gives value
raised to exp power, i.e., baseexp. of 30.
A domain error occurs if base = math.pow (4.0, 2.0) gives
0 and exp<= 0; also if base< 0 value of 42.
and exp is not integer.
9 sin math.sin (arg) The sin( ) function returns the math.sin (val)
sine of arg. The value of arg (val is an number)
must be in radians.
10 cos math.cos (arg) The cos( ) function returns the math.cos (val)
cosine of arg. The value of arg (val is an number)
must be in radians.
11 tan math.tan (arg) The tan( ) function returns the math.tan (val)
tangent of arg. The value of arg (val is an number)
must be in radians.
12 degrees math.degrees (x) The degrees( ) function converts math.degrees (3.14) would
angle x from radians to degrees. give 179.91
13 radians math.radians (x) The radians( ) function converts math.radians (179.91) would
angle x from degrees to radians. give 3.14
The math module of Python also makes available two useful constants namely pi and e:
math.pi gives the mathematical constant  = 3.141592… to available precision.
math.e gives the mathematical constant e = 2.718281… to available precision.
Using random Module
Python has a module namely random that provides random-number generators. To use random number
generators, you need to import random module.
import random
Three most common random number generator functions in random module are:
random() It returns a random floating-point number N in the range 0.0 ≤ N < 1.0
randint(a,b) It returns a random integer N in the range (a, b), i.e., a ≤ N ≤ b
randrange
(<start>,<stop>,<step>) It returns random numbers from range start … stop with step value.
Examples:
1. To generate a random floating-point number between 0.0 to 1.0, simply use random():
>>> import random
>>> print(random.random())
0.022353193431
2. To generate a random floating-point number between lower to upper using random():
a. Multiply random() with difference of upper limit with lower limit, i.e., (upper – lower)
b. Add it to lower limit
For example, the following code generates floating-point random numbers between 15 and 35
>>> import random # need not rewrite this command, if random module already imported.
>>> print(random.random()*(35–15)+15)
28.3071872734
3. To generate a random integer number in range 15 to 35 using randint():
>>> print(random.randint(15,35))
16
4. To generate a random number in the range 0 to 45 using randrange():
>>> random.randrange(45)
13
5. To generate a random number in the range 11 to 45 using randrange():
>>> random.randrange(11,45)
25
6. To generate a random number in the range 11 to 45 with a step value 4 using randrange():
>>> random.randrange(11,45,4)
15
The possible random numbers that may be generated by the above code will be one of the values
11,15,19,23,27,31,35,39,43.
Using the statistics Module
The statistics module of Python provides many statistics functions such as mean(), medium(),
mode(), etc. In order to use these functions in your program, you need to import statistics module.
import statistics # import full statistics module
or
from statistics import mean,median,mode # import only 3 functions from statistics module
You can use these functions as given below:
(i) statistics.mean(<seq>) It returns the average value of the set / sequence of values passed.
It returns the middle value of the given set / sequence of values
(ii) statistics.median(<seq>)
when arranged in order.
It returns the most often repeated value of the set / sequence of
(iii) statistics.mode(<seq>)
values passed.
Examples:
>>> import statistics
>>> seq=[5,6,7,5,6,5,5,9,11,12,23,5]
>>> statistics.mean(seq)
8.25
>>> statistics.median(seq)
6.0
>>> statistics.mode(seq)
5
DEBUGGING
Debugging refers to the process of locating the place of error, cause of error, and correcting the code
accordingly. An error, sometimes called ‘a bug’, is anything that prevents a program from compiling and
running correctly.
Types of Errors
Compile–Time Errors
When a program compiles, its source code is checked for whether it follows the programming language’s
rules or not. Errors that occur during compile–time are called compile–time errors.
1. Syntax Errors
Syntax errors occur when rules of a programming language are misused, i.e., when a grammatical rule of
Python is violated. For example, consider the following statements:
X<-Y*Z
if X=(X*Y)
These two statements will result in syntax errors as ‘<-’ is not an assignment operator in Python and ‘=’
is the assignment operator, not a relational operator. Also, if is a block statement, it requires a colon (:)
at the end of it, which is missing above. Therefore, the correct statements will be as follows:
X=Y*Z
if X==(X*Y):
2. Semantics Errors
Semantics refers to the set of rules which give the meaning of a statement. Violation of these rules results
in semantical errors. For example, the statement
X*Y=Z
will result in a semantical error as an expression cannot come on the left side of an assignment
statement.
Logical Errors
Logical errors are not encountered during compile time and run-time. The program with logical errors does
not provide the correct result. Logical errors are because of the programmer’s mistaken analysis of the
problem. For instance, an incorrectly implemented algorithm, or use of a variable before its initialization, or
unmarked end for a loop, or wrong parameters passed are often very hard to prevent and to locate. Logical
errors must be handled carefully. Logical errors are also treated as a subcategory of run-time errors.
Run–Time Errors
Errors that occur during the execution of a program are run-time errors. Some run-time errors stop the
execution of the program which is then called program “crashed” or “abnormally terminated”.
Exceptions:
An exception refers to any irregular situation occurring during execution / run-time, which you have no
control on. 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. Therefore, a program should recover and continue
following an error. Some built-in exceptions in Python are shown below:
Exception Name Description
Raised when one of the built-in functions (input()) hits an end-of-file (EOF)
EOFError
condition without reading any data.
Raised when an I/O operation such as a print(), open(), or a method of a file
IOError
object) fails for an I/O related reason, e.g., “file not found” or “disk full”.
NameError Raised when an identifier name is not found.
IndexError Raised when a sequence subscript or index is out of range.
Raised when an import statement fails to find the module definition or when a
ImportError
from … import fails to find a name that is to be imported.
Exception Name Description
Raised when an operation or function is applied to an object or inappropriate type,
TypeError
e.g. if you try to compute a square-root of a string value.
Raised when a built-in operation or function receives an argument with an
ValueError
inappropriate value, e.g., int('z10') will raise ValueError.
ZeroDivisionError Raised when the second argument of a division or modulo operation is zero.
OverflowError Raised when the result of an arithmetic operation is too large to be represented.
KeyError Raised when a dictionary key is not found in the set of existing keys.

Debugging using Code Tracing


Most common technique to debug an 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. Common useful technique for
debugging is code tracing. Code tracing means executing code one line at a time and watching its impact on
variables. One way of code tracing is using dry run. Code tracing can also be done by debugging tools
available in software form.

You might also like