Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

Chapter-8 Data Handling

Uploaded by

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

Chapter-8 Data Handling

Uploaded by

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

Data

Handling
In i s ChaPter

8.5 Expressions
8.1 Introduction
8.6 Introduction to Python Standard
8.2 Data Types Library Modules
8.3 Mutable and Immutable Types 8.7 Debugging
8.4 Operators

8.1 INTRODUCTION
In any language, there are some fundamentals you need to know before you can write even the
most elementary programs. This chapter introduces some such fundamentals : data types,
variables, operators and expressions in Python.

Python provides a predefined set of data types for handling the data it uses. Data can be stored
n any of these data types. This chapter is going to discuss various types of data that you can
store in Python. Of course, a program also needs a means to identify stored data.
So, this chapter shall also talk about mutable and immutable variables in Python.

8.2 DATA TYPES


Data can be of many types e.g., character, integer, real, string etc. Anything enclosed in quotes
represents string data in Python. Numbers without fractions represent integer data. Numbers
Boolean data. Since the data to be
with fractions represent real data and True and False represent
dealt with are of many types,
a programming language must provide ways and facilities to
handle all types of data.
Be of data in Python, let us discuss various
Ore you learn how you process different ypes
can

in Python. In this discussion of


data types, you'll be able to know Python's
ta-types supported
capabilities to handle a specific type of data, such as the memory space it allocates to hold a
ce type of data and the range of values supported for a data type etc.

203
204 cOMPUTER SCIENCE WITH
PYTHON. X

Python offers following built-in core data types :

() Numbers (i) String (ii) List (iv) Tuple (o) Dictionary.


8.2.1 Numbers
As it is clear by the name the Number data types are used to store numeric values in Pvthon
The Numbers in Python have following core data types:

) Integers
Integers (signed) Booleans
ii) Floating-Point Numbers (ii) Complex Numbers

8.2.1A Integers
Integers are whole numbers such as 5, 39, 1917, 0 etc. Types of Integers in Python
They have no fractional parts. Integers are represented
in Python by numeric values with no decimal point. Integers (signed)
Integers can be positive or negative, e.g., + 12, - 15, 3000 Booleans
(missing+ or-symbol means it is positive number).

There are two types of integers in Python


(i) Integers (signed). It is the normal integer' representation of whole numbers. Integers in
Python 3.x can be of any length, it is only limited by the memory available. Unlike other
languages, Python 3.x provides single data type (int) to store any integer, whether big or smal.
It is signed representation, i.e., the integers can be positive as well as negative.
(i) Booleans. These represent the truth values False and True: The Boolean type is a subtype of
plain integers, and Boolean values False arnd 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. See figure below (left side).

>» bool(e) str(False) The str) function converts a


False 'False'
value to string.

> bool(1) >str(True)


True 'True

However, when you convert Boolean values False and True


to a string, the strings False' or "True' are returned, Ihe two objects
representing
respec the values False and True (
ot
tively. The str() function converts a value to string. See figure ony
the
above (right side). talse ortrue) are
Boolean objects in Python.
8.2.1B Floating Point Numbers
is a
A number having
fractional part is a floating-point number. For example,
3.1s not
floating-point number. The decimal point signals that it is a floating-point numbe
integer. The number 12 is an integer, but 12.0 is a floating-point number.
u g h a v a i l a b l e

1. In some cases, the exception OverflowError is raised instead if the given number cannot be represented t
number of bytes.
HANDLING
205
DATA
ter 8:
be Written in
Values discussion in chapter 6) that fractional numbers can
all (from Literals/
twotorms
etc.
a Fractional Fornm (Normal Decimal Notation) e.g., 3500.75, 0.00005, 147.9101

Exponent Notation e-g., 3.50075E03, 0.5E-04, 1.479101 E02 etc.


like
variables represent real numbers, which are used for measurable quantities
Eloating point
distance, area, temperature etc. and typically have a fractional part.

Floating-point numbers
have two advantages overintegers
can represent values between the integers.
They
They can represent a much greater range of values.
sutfer from disadvantage also:
Butfloating-point numbers
one

Floating-point operations are usually slower than integer operations.

In Python, floating point numbers represent


machine-level NOTE
double precision floating point numbers (15 digit precision). In Python, the Floating point
machine
The range of these numbers is limited by underlying numbers have precision of 15

architecture subject to available (virtual) memory. digits (double-precision).

8.2.1C Complex Numbers


a numeric type to represent Comnplex
Numbers also.
Python is a versatile language that offers you to
about Complex numbers ? Uhh, I see. You a r e going
Complex Numbers ? Hey, don't you know
Mathematics book. Well, if you don't know anything
study about Complex numbers in class XI I am giving below brief introduction of
about complex numbers, then for you to get started,
about Python's representation of Complex numbers.
Complex numbers and then we shall talk
C h e c k P o i n t

Mathematically, complex number is a number of the form


a
8.1
A +Biwhere i is the imaginary number, equal to the square root
1. What are the built-in core data types of of-1 i.e., v-1.
Python A complex number is made up of both real and imaginary
2. What do you mean by Numeric types? number A +Bi, A and B are real
How many numeric data types do0es components. In complex
numbers and i is imaginary. If we have a complex number z,
Python provide ?
would be the real component and b would
3. What will be the data types of
where za+bithen a
of real component of
following two variables? represent the imaginary component z, e.g.,
and the imaginary component would be 3.
A 2147483647 z =4 +3i is 4
BA + 1
(Hint. Carefully look the values they NOTE
are storing. You can refer to range or
A complex number is in the form A +Bi where i is
Python number table.)
the imaginary number, equal to the square root of
What are Boolean numbers ? Why are -1 i.e., -1, that is i' =-1
ney considered as a type of integers in
Python?
floating point numbers; the savings in processor
andm on
documentation, "Python does not support single-precision of using objects in Python, so there
these is dwarfed by the overhead
s na usage that are usually the reason for using
*Compicate the language with two kinds of floating point numbers".
cOMPUTER SCIENCE WITH PYTHON
X
206

Complex Python
Numbers in That is, to represent imao
complex numbers in the form A+Bj. naginary
Consider
Python represents of traditional i. So in Python j=-1. the
in place
number, ython uses j (or /) two complex
numbers in Python:
where a and b are storing
following examples
a =0+3.1j
b 1.5+2j
0 and
The above complex number a has real component
b, the real
as
NOTE
imaginary componernt as 3.1; in complex number Python represents complex
is 2. When you display complex
part is 1.5 and imaginary part numbers in parentheses
numbers as a pair of floating

numbers, Python displays complex point numbers.


as shown in following
a n o n z e r o real part
when they have
examples.
» C=0+4.5j
>> d = 1.1+3.4j
NOTE
used in
Complex numbers are quite commonly
Electrical Engineering. In the field of electricity, 4.5j
used to represent d
however, because the symboliis
current, they use the symbol j for the square root of (1.1+3.4j)
adheres to this convention. See, a complex number with
-1 Python print (c) non-zero real part is displayed with
parentheses around it.
4.5j But no parentheses around compler
> print (d) number with real part as zero(0).

Check P o i n t
(1.1+3.4j)
8.2 Unlike Python's other numeric types, complex numbers are
: the real part
and
1. What are floating point numbers? a composite quantity made of two parts
internaly
When are they prefered over integers? the imaginary part, both of which are represented
are complex numbers? How
as float values (floating point numbers).
2. What attribue
would Python represent a complex
You can retrieve the two components using
number with real part as 3 and
references. For a complex number z:
2.5?
imaginary part as
3. What will be the output of following z.real gives the real part.
a
float, not as
code? Z.imag gives the imaginary part as a

P 3j complex value.
q P+ (1+1.5j) For example,
print (p) >» z = (1+2.56j) + (4-3.56j)
print (9) a
4. What will be the output of following
(-3 -1j) It will display real part of
complex
code ?
>> z.real number z
r 2.5+3.9j
3.0
onpler

of
print (r. real) t will display imaginary part
z.imag number z
print (r.imag)
-1.0
5. Why does Python uses symbol j to
represent imaginary part of a complex
number instead of the conventional i? number
c a n
be

Hint. Refer note above. The real and imaginary parts of a complex andz./
retrieved through the read-onlyattributesz.reu
8 : DATA HAN
HANDLING

207
DATA

Chapter
&:

he range of numbers representea through Python's numeric data types is given below.

Table 8.1 The Range of ython Numbers

Data type
Range
an unlimited range, subject to available
Integers (virtual) memory only
Booleans
two values True (1), False (0)
Floating point numbers an unlimited range, subject to available
machine architecture. (virtual) memory on underlying
Same as
floating point numbers because the real and
Complex
represented as floats
imaginary parts are
numbers

82.2 Strings
You already know about strings (as data) in Python. In this section, we shall be talking about
Python's data type string. 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
character. Or in other words, all strings in Python 3.x are NOTE
sequences of pure Unicode characters. Unicode is a system All Python (3.x) strings store
designed to represent every character from every language. A Unicode characters.
string can hold any type of known characters i.e., letters, numbers,
and special characters, of any known scripted language.
Following are all legal strings in Python:
"29"
"abcd", "1234", '$%^&', '2???', "`ÆËá", "2??2??"', '??2?', "22??", 22?',
String as a Sequence of Characters
and each character can be individually accessed
A Python string is a sequence of characters
using its index. Let us understand this.
it will form the basis
first study the internal structure or composition of Python strings
as
Let us
in Python are stored as
Or all the learning of various string manipulation concepts. Strings
index for each location.
Idlvidual characters in contiguous location, with two-way
ne individual elements of a string are the characters contained in it (stored in contiguous
are given two-way index for
mentioned the characters of string
a
Emory locations) and as
of an illustration as given in Fig. 8.1.
ocation. Let understand this with the help
a us

name[0] 'P = namel-6


name[1]= "Y = namel-5]
Forward indexing 01 2 3 4 5
namel2]=T =name[-4]
name HON Backwardindexing
namel3]= "H' = namel-3]|

-6-5 -4 -3 -2-1 namel4]='0'=namel-21


namel5)= "N° = namel-1]

8.1 Structure of a Python String.


Figure

have -
that can hold a single
ython has no programming languages
which most other
separate character datatype,
s
character. In Python, character.

a character is astringtype only, with single


208 COMPUTER SCIENCE WITH PYTHO
PYTHON-
From Fig. 8.1 you can infer that:
Strings in Python are stored by storing each character separately in contiguous locats.
cations.
The characters of the strings are
given two-way indices:
0 , 1, 2,... in the forward direction and
- 1 , -2, -3, in the backward direction.
. . .

Thus, you can access any character as <stringname>lcindex) eg, to access the first charad
iracter of
string name shown in Fig. 8.1, you'll write name[01, because the index of first character is 0.k
may also write name I5] for the above example i.e., when string name is storing "PYTHONYou
Let us consider another string, say subject ="Computers'. It will be stored as:
2 4 6

subject c m P u t e
r
-
S

1
9 8 7 5 - 5 -4 2

Thus, subjectfe] = 'C subject[2] = 'm subject [6]="e'

subject [-1] = ' s subject[-7]= 'm subject [ -9] = 'C

Since length of string variable can be determined using function len(<string>), we can say that:
first character of the string is at index 0 or -length
second character of the string is at index 1 or -(length-1)

second last character of the string is at index (length -2) or -2


l a s t character of the string is at index (length -1) or -1
In a string, say name, of length in, the valid indices are 0, 1, 2,
... In-1. That means, if you try to give something like: NO
subscript
The index (also called
numbered
name[ln] sometimes) is the
in the string
position of a letter

Python will return an error like In Python, indices begin


direction
onwardsin the forward
name[In] in the backwar0
and-1, -2, . .

IndexError: string index out of range direction.

The reason is obvious that in string there is no index equal to


the length of the string, thus accessing an element like this causes an error.
ofa

Also, another thing that you must know is that you cannot change the individual ie
string in place by assignment because strings are immutable and hence item assignr
supported, i.e.,
name 'hello' individual letter assignment not
name[e] = 'p' allowed in Python

will cause an error like

name[e] ='p
TypeError: 'str object does not support item assignment
HANDLINNG

Chopter
8:
DATA
209
ver, you can assign to a string another string or an
However,

csion that returns a string using assignment, e.g., following


NOTE
express

statementi s valid: Valid string indices are 0, 1,


2. upto length-1 in forward
name = "hello'
Strings can be assigned expressions direction and -1,-2,-3..
name ="new" that give strings. -length in backward direction.

Lists and Tuples


8.2.3
are Python's compound data types. We have taken them together in one
he lists and tuples
section because they are basically the same types with one difference. Lists can be changed
moc
nadified (i.e., mutable) but tuples cannot be changed or modified (i.e., immutable). Let us talk
about these two Python types one by one.
8.2.3A Lists
A List in Python represents a list of comma-separated values of any datatype between square
brackets e.g, tollowing are some lists:
[1, 2, 3, 4, 5]
r'a', 'e', 'i', 'o', 'u']
[Neha', 102, 79.5]
Like any other value, you can assign a list to a variable e.g.,
a = [1, 2, 3, 4, 5] # Statement 1
a
[1, 2, 3, 4, 5]
print (a)
[1, 2, 3, 4, 5]
To change first value in a list namely a (given above), you may write
# change 1st item - consider statement 1 above
a [o]=10
>a

[10, 2, 3, 4, 5]
To change 3rd item, you may write
a [ 2 ] = 30 # change 3rd item

a
[10, 2, 30, 4, 5]
it right; the values internally are numbered (zero) from 0 onwards i.e., first item of
guessed
ne list is internally numbered as 0, second item of the list as 1, 3rd item as 2 and so on.
are not going further in list discussion here. Lists shall be disgussed in details in a later chapter.
W
8.2.3B Tuples
with couple) as those lists which cannot be
cha ink of Tuples (pronounced as tu-pp-le, rhyming values of any
group ot comma-separated
e , are not modifiable. Tuples are represented
as

dateltype within rentheses, e.g., following are some tuples:


NOTE
P (1, 2, 3, 4, 5)
9(2,4, 6, 8) Values of type list are mutable i.e., changeable
(a', 'e', 'i', 'o, 'u) one can change/ add / delete a list's
elements. But the values of type tuple are
h (7, 8, 9, A, 'B, 'C) immutable i.e., non-changeable ;one cannot
l d i l be discussed in details in a later chapter.
make changes to a tuple
COMPUTER SCIENCE WITH PYTHON
210 HON -M

8.2.4 Sets
values same as in mathematical sSekts.
also similar to lists that can
store multiple But
Sets are
lists.
Python sets are little different from
These differences are
values enclosed in curly brackets I 1.
Sets are created by specifying c o m m a separated
lists.
and unindexed unlike
Sets' elements are unordered
entries unlike lists.
Sets do not allow duplicate
elements.
Sets cannot contain mutable
set of values.
given example which is creating
a
Consider below

>> myset =
{1, 2, 3, 4} Set created by specifjying comma separated values
enclosed in curly brackets { }.
» print (myset)
1, 2, 3, 4}
> myset1 { 1, 2, 3, 4, 4}
=

Sets do not allow duplicate


entries. See, it rejected the duplicate
see that 4 appears only once in the set even
print(myset1) entry 4. As you can
while creating.
though you gave 4 twice
(1, 2, 3, 4}
»type(myset)
<class 'set'>

>» set1 - {1, 2, [3, 4]} -


allow mutable elements like
Sets do not

Traceback(most recent call last): lists. See it gave error when we


tried to add
error when
File "<pyshell#68>", line 1, in <module> a list as element, but it gave
no

element, because a
we gave a tuple as an

{1, 2, [3, 4]} +


setl =
tuple is not mutable.
TypeError unhashable type: 'list'
>set1= {1, 2, (3, 4)} NOTE
set itself
A set cannot contain a mutable element in it. However,
a strings
Python data types
dictionary etc
is mutable, i.e., we can add or remove items from it. lists, tuples,
are all iterables.

8.2.5 Dictionary etof


hat. The dictionary is an unordered st
Dictionary data type is another feature in Python's a dictionary,
comma-separated key: value pairs, within {}, with the requirement that within
two keys can be the same (ie., there are unique keys within a dictionary). For insa

following are some dictionaries


fa: 1,'e : 2,'i : 3, 'o : 4, 'u : 5}
ITERABLE Pytho
is any
> vowels ={'a' : 1, 'e' : 2, 'i' : 3,'o': 4, 'U: 5} An iterable
ject that can
return its
time
Here 'a', 'e, 7, 'o' and 'u' are the keys of dictionary at a
>» vowels['a'] members,
one aCcess

vowels; 1, 2, 3, 4, 5 are values for these keys respectively. can

1 Since, you ists


elements of strings

> vowels['u'] Specifying key inside [ Il after dictionary name gives the
tuples and
dictionary on
corresponding value from the key : value pair inside iterables
5 are all
time, these
dictionary.
Dictionaries shall be covered in details in a later chapter.
DATA H
HANDLING
ANDI
DAIA

8:
Chapter 211
ollowing figure summarizes the core data
types of Python.
Core Data Types

Numbers Sets None Sequences Mappings

Integer Floating Complex Strings


point Tuple List Dictionary
Boolean

AND IMMUTABLE TYPES


83 MUTABLE
The Python data objects can be broadly categorized into two - mutable and immutable types, in
simple words changeable or modifiable and non-modifiable types.

1. Immutable types
The immutable types are those that can never change their value in place. In Python, the following
types are immutable:integers, floating point numbers, Booleans, strings, tuples.
Let us understand the concept of immutable types. In
Immutable Types
order to understand this, consider the code below integers
Sample code 8.1
floating point numbers
booleans
P 5
strings
=P tuples
r 5
#will give 5, 5, 5

P 10
r 7

=r
variables p, q, r could be
say that
values of integer
reading the above code, you can
think that integer types can

ged effortlessly. Since p, q, r are integer types, you may


change values.
But hold : It is not the case. Let's see how.
references to value-objects i.e.,
variable-names are just the
y know that in Python,
values themselves i.e., they are not storage
data do not store
ues. The variable-names
cont ainers. talked about it.
Recall section 7.5.1 where we brietly these
how Python processes
above. Internally,
Now consider
Lder the Sample code 8.1 given 8.2 on the next page and then
go through figure
lained in Fig. 8.2. Carefully
gnments is explai
Fead the "in
following lines. values
arenotchanging
So variable p/q/ ris changing; n e w imutable integer
although
place"
it ap
the factaPpears
that the value of
variable-names are
instead made
to reter to
s a m e memory
location.)
1s that the value in
Object. the same

(Changing in place
place
6 8 in
means
modifying
COMPUTER SCIENCE WITH
212 PYTHON-
Initially these three
statements are executed
value
reference the
same
P value
All variables having s a m e
same integer objects
r will all reference
q p object i.e., p, q.
r 5
a count of how
Internally Python keeps value
many
variables are-referring to a

Each integer
value is an
immutable 5 6 8
.256
9 .272
10 288
object .208 .224 .240

Figure 8.2

You can check/confirm it yourself using id(). The id() returns the memory addressto
which a variable is referencing.

p 5
>>q= p
>>>r=5 Notice the id( ) is returning
same memory address for
NOTE
>» id(5) Please note that everything is an object
value 5, p, q,r - which
1457662208 means all these are in Python, be it data items, any literal
data types,
referencing the same value, strings, numbers,
>>»id(p) variables and so forth. This is because

1457662208 Python is an object oriented language


and it creates and treats everything 85
id(9) function when you
an object. The id( )
1457662208 use on any data value or variable,
objec
returns the unique identity of the
>>id(r) which is its assigned memory
address

1457662208

different

Please note, memory addresses depend on your operating system and will varyn
sessions.
When the next set of statements execute, i.e.,
P 10
r 7
To s e e
q =r M u t a b i l i t y / i m m u t a b i l i t y

then these variable names are made to in action


point to different
integer objects. That is, now their memory addresses that
they reference will change. The original memory address of p
that was having value 5 will be the same with the same value
i.e., 5 but p will no longer reference it. Same is for other Scan

variables. QR Code
DATA HANDLING
afer 8:
213
This count reflects
that currently two
identifiers/variables are
referring to this value.
(2)
(4
6 78 8

9 10
..208 224 .240 ..256 272 288

Figure 8.3
Let us check their ids

>> p 10

>>>r=7

q=
r

Notice, this time with change in value


>>id(10) the reference memory address of
1457662288 variables p,g and r
have
changed.
The value 5 is at the same address
> id(p)
(Compare the result of id(5) on the
1457662288
previous page)

id(7)
1457662240

» id(q)
1457662240
NOTE
Mutablity means that in the
same memory address, new
id(r) value can be stored as and when
1457662240 you want. The types that do not
support this property are
>> id(5) immutable types.
1457662208
Now if you assign 5 to any other variable. Let us see what happens.

>t 5 Now variable thas reference memory


address same as initial reference memory
has value 5.
id(t) address of variable p when it
listings given above
1457662208 Compare

Thus stored as references to a value-object. Each time you


clear that variable n a m e s are
s value, the variable's reference memory address changes.
chan the
address
containers i.e., with fixed memory
Variables
whoES (of (of certain types) are NOT LIKE storage
IMMUTABLE.
Changes every time.
Hence they are
COMPUTER SCIENCE WITH PYTHON

214
Mutable Types
2. Mutable types Lists
be changed
those whose values Dictionaries
can
The mutable types are
in Python. These
are:
are mutable Sets
in place. Only three types
lists, dictionaries and sets.
write:
To change a member of a list, you may

Chk [2, 4, 6]
Chk[1] = 40

It will make the list namely Chk as [2, 40, 6].

>Chk =[2, 4, 6]
after changing a value in
id(Chk) See, even

the list Chk, its reference memory


150195536
address has remained same. That
means the change has taken in place
> Chk[1] =40
the lists are mutable

id(Chk)
150195536

Lists and Dictionaries shall be covered later in this book.

8.3.1 Variable Internals


Python is an object oriented language. Python calls every entity that stores any values or any

type of data as an object.


Check Point
An object is an entity that has certain properties and that
exhibit a certain type of behavior, eg., integer values ane
8.3
1. What is String data type in Python ?
objects they hold whole numbers only and they have
infinite precision (properties); they support all arithmenc
2. What are two internal subtypes of
String data in Python ? operations (behavior).
3. How are str type strings different from So all data or values are referred to as object in Pytha
Unicode strings ? Similarly, we can say that a variable is also an object na
4. What are List and luple data types of refers to a value.
Python ?
t
5. How is list type different from
Every Python object has three key attributes associateato
a
tuple
data type of Pythen ?
6. What are Dictionanies in Python () The type of an object canbe
7. Identify the types of data from the The type of an object determines the operations that
following set of data
performed on the object. Built-in function typel) Te
"Roshan', uURoshan', False, the type of an object.
False', [R, 'o, s, h, a', 'n,l
CR, 'o, 's, 'h', 'a, 'n) Consider this:
fR:1,'o':2,'s:3, 'h:4'a > a =4
Type of integer value 4 is
5,'n:6, (2.0-3) >> type (4) * returned int i.e., integer
12, 12.0, 0.0, 0, 3j. 6+2.3, class 'int>
True, "True" int ie.
Type of variable a is also
8. What do you
type (a) * mteger because a is curenily
understand by mutable <class'int> referring to an integer
vaue.
andimmutable objects?
HANDLINNG
8: DATA
Chopter

215
value of an object
tial The Thus internal
change in value of variable b
Itis the
adata-item contained in the object. For a (trom 5 to
4) of sample code 8.2 will be
eral, the value is the literal itself and for a represented as shown in Fig. 8.4.
riable the value is the data-item it
(the 30899132
referencing. Using print
variable) is currently a 4
4
statement you can display value of an object.
For example, b 5

a =4 30899120
value of integer literal b b
» print (4) is 4
1
A
4 Figure 8.4 Memory representation of sample code 8.2.
>>> print (a) value of variable a is 4 as it is Please note that while storing
currently referencing integer
complex numbers,
id's are created differently, so a complex literal
value 4.
say 2.4j and a complex variable say x having
(i) The id of an object value 2.4j may have different id's.
The id of an object is generally the memory
location of the object. Although id is imple- EXAMPLE 1 What is the outputofthefollorwing code?
mentation dependent but in most implemen- nset1 { 11, 12, 13, 13)
tations it returns the memory location of the ? print(nset1)
object. Built-in function id() returns the id of soLUTION {11, 12, 13}
an object, eg,
> id(4) Object 4 is internally stored EXAMPLE 2 the previous example, Why did the
In
30899132 at location 30899132 code not print the output exactly as the input?
>a = 4 SOLUTION This is because the sets ignore the
Variable a is current referencing
» id (a) location 30899132 (Notice same duplicate values. Since the input contained a
as id(4). Recall that variable is duplicate value 13, the set nsetl ignored it and
30899132 not a storage location in Python,
rather a label pointing to a value
hence the output is different from the input.

object). following two variables


EXAMPLE 3 How are

Theid()of avariable is same as the id() ofvalue created using {} diferent from one another ?
itis storing Now consider this V1 = {11, 12, 13, 14}, V2 ={11:12, 13:14}
Variable V1 is a set and V2 is a
Sample code 8.2 SOLUTION
We can
The id's of value 4 and dictionary as it contains key:value pairs.
the types of V1 and V2 as:
id(4) variable a are the same confirm it by checking
since the memory-location
30899132
s a m e as the
is
location »V1 { 11, 12, 13, 14}
a =4 of 4 »V2 {11:12, 13:14}
is
to which variable
a

» id(a) referring to. > type(V1)


class 'set'>
30899132
» type(V2)
>»b 5 Variable b is currently having <class 'dict'>
>» id(5) value 5, ie., referring
to

integer value 5
30899120 DATA TYPES, MUTABILITY

» id(b)
-Progress In Python 8.1
NTERNALS

30899120 Variable b will now refer to


iP
»» b b-1 value 4 IDE of your choice
In the Python
id(b) the id of
30899132. Now notice that
variable
s a m e as
b is
id

of integer 4.
COMPUTER SCIENCE WITH
216 PYTHON -

8.4 OPERATORS
operators. The sunm
out on data, are represented by mbols hat
The operations being carried The operations(specific t
on data, are called operators.
trigger the operation/ action are reterred to as Overand are
and the objects of the operation(s) s.
represented by Operators
these types of
Python's rich set of operators comprises of OPERATORS
Relational operators
operators : (i) Arithmetic operators (ii) The symbols" that trigger
(v) Bitwise
ii) Identity operators (iv) Logical operators operation/ action on
he
data, are
operators (vi) Membership operators. called Operators, and the
later on which operation is
data
Out of these, we shall talk about membership operators being
when we talk about strings, lists, tuples and
dictionaries. carried out, i.e., the objects of
the operation(s) are referred
(Chapter 10 onwards). to
as Operands.
Let us discuss these operators in detail.

8.4.1 Aithmetic Operators


To do arithmetic, Python uses arithmetic operators. Python provides operators for basic
calculations, as given beloww

addition multiplication I floor division exponentiation


subtraction division remainder

Each of these operators is a binary operator i.e., it requires two values (operands) to calculate a
final answer. Apart from these binary operators, Python provides two unary arithmetic
operators (that require one operand) also, which are unary +, and unary -.

UNARY OPERATORS
8.4.1A Unary Operators The operators that act on one
operand are referred to as

Unary + Unary Operators.


Unary
The operators unary + precedes an The operator unary - precedes an operand. iie

operand. The operand (the value on operand of the unary - operator must have
which the operator operates) of the unary arithmetic type and the result is the negation or
+operator must have arithmetic type and
operand's value. For example,
the result is the value of the
argument. if a = 5 then - a means - 5.
For example, if a = 0 then - a means 0
if a 5 then +a means 5. known as -0)
(there is no quantity
if a = 0 then a means 0. if a =- 4 then -a means .
if a =- 4 then + a means -4. This operatorreverses the value
sign ofthe operand's
8.4.1B Binary Operators
Operators that act upon two operands are referred to as Binary BINARY OPERATORS
two

Operators. The operands of a binary operator are distinguished Operators that act
upon

as the left or referred to


right operand. Together, the operator and its operands are

operands constitute an expression. Binary Operators.

4. Sometimes these can be words too, e.g., in


Python is and is not are also
operators.
3 DATA HANDLING

C h o p t e r
217
+
Addition
operator
5. Floor Division operator //
1, binary operator + adds values of :
Python also offers another division
a r i t h m e t i c

The and the : result is the sum of operator //,


sopera
erands the: which performs the floor division. The floor
two operands. For example,
ofits division is the division in which
values

4+ 20
results in 24 only the whole
part of the result is given in the output and the
a =
2) results in 7 fractional part is truncated.
a+5 (where
b (where a = 4, b 6) results in 10
Tounderstand this, consider the third example of
Addition operator+ operands may be of division
For given in division
operator/, i.e.,
mumber types, a
=15.9, b=3,
on also offers + as a concatenation operator
a/b evaluates to 5.3.
when used with strings, lists and tuples. This func-
Now if you change the division
operator /, with
tionality for strings will be covered in Chapter 10 floor division
operator // in above expression, i.e.,
String Manipulation; for lists, it will be covered If a =15.9, b=3,
See, the
in Chapter
12 -

List Manipulation. al/b will evaluate to 5. Fractional part


Consider 0.3 is discarded
operator some more
examples:
-

2. Subtraction from the actual


The operator subtracts the second operand 100//32 evaluates to 3 result 5.3
from the first. For example, 7//3 evaluates to 2
6.5//2 evaluates to 3.0
14-3 evaluates to 11
a-b (where a =7, b=5) evaluates to 2 The operands may be of number types.
x-3 (where x = -1) evaluates to -46. Modulus operator %
The operands may be of number types.
The %operator finds the modulus (i.e.,
3. Multiplication operator remainder but pronounced as mo-du-lo) of its first
The operator multiplies the values of its operands. operand relative to the second. That is, it
produces the remainder of dividing the first
For example,
operand by the second operand. For example,
3 *4 evaluates to 12
19 %6 evaluates to 1, since 6 goes into 19
b*4 (where b =6) evaluates to 24
three times with a remainder 1.
p*2 (where p =
-5) evaluates to -10
a*c (where a =3, C =5) evaluates to 15
Similarly, 7.2%3 will yield 1.2
6 % 2.5 will yield 1.0
Ihe
operands may be of integer or floating point
umber types.
The operands may be of number types.

**

yihon also ofers as a replication operatorwhen:7. Exponentiation operator


with strings. Thisfunctionality will be covered in The exponentiation operator ** performs exponen-

Chapter10-String Manipulation. tiation (power) calculation, i.e., it returns the


result of a number raised to a power (exponent).
4.Division operator/
For example,
neoperator in Python 3.x divides its first
erand by the second operand and always rerurns 4 ** 3 evaluates to 64 (4)
the result a ** b ( a =7, b=4)
as a float
value, e.g
4/2 evaluates to 2.0 evaluates to 2401 (a° i.e., 7*).
108/10 evaluates to 10.0 x ** 0.5 (x=49.0)
7/2.5 evaluates to 2.8 evaluates to 7.0. (x, i.e., Vx, i.e., V49)
100/32 evaluates to 3.125 2 7 . 0 0 9 ** 0 . 3

13.5/1.5 evaluates 9.6 to evaluates to 2.68814413570761. (27.009.3


Please note that
version of Python (2.x),
in olderdifferently. The operands may be of number types.
. Operator worked
For Booleanvalues takes values 1 and o (zero) respectively
True 1 will give so +

you 2 ). True and


and False, recall that Python internally
218 COMPUTER SCIENCE WITH
PYTHON
THON -K
EXAMPLE 4 What will be the output produced EXAMPLE 5 Print the area of a
circle of ra
by the following code ? 3.75 metres. radius
A, B, C, D =9.2, 2.0, 4, 21 SOLUTION
print ( (A/4), (A// 4) ) Radius = 3.75
p r i n t (B ** C)
Area 3.14159 * Radius ** 2

print (D// B)
print (Area, 'sq. metre')
print (A % C)
SOLUTION 2.3 2.0
NOTE
16.0
Floor division truncates
10.0
1.2
fractional remainders and
gives
only the whole part as the resuit.
Table 8.2 Binary Arithmetic Operators

Symbol Name Example | Result Comment


addition 6+5 11 adds values of its two operands.
5+6
subtraction 6-5 subtracts the value of right operand from
5-6 left operand.

multiplication 5 *6 30 multiplies the values of its two operands.


6*5 30
division 60/5 12 divides the value of left operand with the
right operand and returns the result as a float value.
value of
Modulus (pronounced 60%5 divides the two operands and gives the remainder
mo-du-lo) or Remainder 6%5 1
resulting
Floor division 7.2 // 2 3.0 divides and truncates the fractional part from the result
Exponentiation(Power) 2.5 ** 3
15.625 returns base raised to power exponent. (2.5° here)

Negative Number Arithmetic in Python


Arithmetic operations are straightforward even with negative numbers, > 5//-3
especially with non-division operators i.e., -2

5+3 2; -5-3 =-8; -5*3 =-15; -5 **3 =-125 >5//3

But when it comes to division and related operators (, I1, %), mostly people get 2
confused. Let us see how Python evaluates these. To understand this, we >-7/4
recommend that you look at the operation shown in the adjacent screenshot 1.75
and then look for its working explained below, where the result is shown
-71/4
shaded
-2
(a)-3) (-2 6) 3)-5 -2 (c) 4)-7(-1.75
>>>-7%4
-1 +1
1
>» 7%4

4) 4)-7 (2 () 4-7 -2 -4)7-2 (g) -4)77-2 >> 7//-4

-8 -8 8
8: DATA HANDLING
Chopt
219
84.10 Augmented Assignment Operators
learnt that Python
You have lear has
assignment operator =which assigns the value
an

RHS ble/object on the LHS of Python


to the variabl =
also offers specified on
augmented assigngnment arithmetic
.

S, which combine the


impact of an arithmetic
O vou want to add value of b to value of operator with an assignment
operator,
and assign the result
a
to a, then instead of writing
a a+b

you may write

a t= b

Ta add value of a to value of b add


assign the result to b,
you may write
b+= a
#instead of b = b+a
operation Description Comment
+y x =X+y Value of y added to the value of x and then result
assigned to x

XX-y Value of y subtracted from the


value of x and then result
assigned to x
X*=y X =**Y Value of y
multiplied to value of x and then result assigned to x
xl=y x =x/y Value of y divides value of x and then
result assigned to x
xl=y x =x/l y Value ofy does floor division to value
of x and then result assigned to x
X**=y X = X**Y
xcomputed and then result assigned to *
x =* % y Value of y divides value
of x and then remainder
assigned to x

These operators be used


can
anywhere that
assigrnment ordinary Augmented is used.
assignment doesn't violate mutability. Therefore, writing r+ = y creates an entirely new object x
with the value x+ y.
Please note that this expansion such as
'x+=y is same as x =X+y, holds only for immutable types
Such as numbers. For iterable mutables such as lists this is not the
case (i.e., for lists x+= y is not
equal to x =x+y). We shall explain this in the chapter of lists.

8.4.2 Relational Operators


In the term relational operator, relational refers to the relationships that values (or operands) can
nave with another. Thus, the relational
one
operators determine the relation among different
nds. Python provides six relational operators for comparing values (thus also called
a o operaiors). If the comparison is true, the relational expression results into the Boolean
Vdiue True and
to Boolean value False, if the comparison is talse.
Thesix relational operators are:
less than, <= less than or equal to, equal to
greater than, greater than or equal to, = not equal to,
lict operators work with nearly all types of data in Python, such as numbers, strings,
ples etc. Relational operators work on following principles:
o r numeric types, the values are compared after removing trailing zeros after decimal
POint from a floating point number. For example, 4 and 4.0 will be treated as equal (after
emoving trailing zeros from 4.0, it becomes equal to 4 only).
.Please note this
stye o combining assignment with other operator also works with bitwise operators.
220 cOMPUTER SCIENCE WITH
PYTHON-
PYTHON
Strings are compared on the basis of lexicographical ordering (ordering in diction
dictionary).
Capital letters are considered lesser than small letters, e g , 'A' is less than'a :'Pu
not equal to 'python'; book' is not equal to books'.
nan 'a' 'Python' is
Lexicographical ordering is implemented via the corresponding codes or ordinal .
(e.g, ASCI code or Unicode code) of the characters being compared. That is the ea
A' is less than 'a' because ASCII value of letter 'A (65) is less than 'a'(97). You can
for ordinal code of a character yourself using ord(<character>) function (eg, ordeA
F o r the same reason, you need to be careful
).
about nonprinting characters like spaces. >» 'Apple' 'Apple'
Spaces are real characters and they have a True
specific code (ASCII code 32) assigned to
'Apple'== 'Apple
them. If you are comparing two strings that
appear same to you but they might produce True
a different result if they have some spaces
-

Results different from anticipated


in the beginning or end of the string. results because the second string
See screenshot on the right. contains a space in the beginning and
space s ordinal value (32) is less than
Two lists and similarly two tuples are equal if A s ordinal value (65)
they have same elements in the same order.
Boolean True is equivalent to 1 (numeric one) and Boolean False to 0 (numeric zero) for
comparison purposes.
IMPORTANT For instarnce, consider the
following relational operations.
You should not use to compare two
==
floating Given a =3, b = 13, p = 3.0
point values, the reason being that floating
point numbers are stored with some precision C='n, d ='g, e ='N,
limit and which may result in some rounding f =god', g ='God', h = 'god', j = God', k= "Godhous,
off. All this will not yield the correct result.
L =
[1, 2, 31, M =
[2, 4, 6], N =
[1, 2, 31
Thus, it is not recommended to use operator ==

to compare two floating point values. O = (1, 2, 3), P = (2, 4, 6), Q = (1, 2, 3)

C h e c kP o i n t a <b will return True


8.4 <d will return False Both match up to

the letter 'd "but


f<h will return False
1. What is the function of operators ? God is shorter
f= will return True than Godhouse'so
What are arithmetic operators? Give
C=e it jirst in ihe
comes
their examples. will return False dictionary.
2. How is 'unary + operator different 8 j will return True
from+ operator ? How is 'unary "God" "Godhouse" will return True
operator different fromoperator "god" < "Godhouse"
3. What are binary operators ? Give
Will return False
a = p
examples of arithmetic binary operators. will return True the
The length of
4. What does the modulus operator % do? L==M will return False strings does not
m a t t e r here. Louer
What will be the result of 7.2 % 2.1 and L== N will return True
8 % 3? is greater
O== P Caseg G
will return False than upper
cuse

5. What will be the result of 5.0/3 and


will return True
5.0//3? a = True
will return False
6. How will you calculate 4.5° in Python? = False
7. Write an expression that uses a relational will return True
operator to return True if the variable 1==True will return True
total is greater than or equal to variable
final.
8: DATA HANDLING

Chopter
221
Table
a2
cmmarizes the action of these
relational operators.
Relationa/ Operators in Python
Table8.3

P Pq Pq p=q
3.0 False
P>q P 9 pq
3 True True False True False
6 4 True False False True True True
'A 'A False True True False True False
a A False False False True True True

IMPORTANT

While using floatin8-pOint numbers with relational


operators, you should keep in mind that
floating point numbers are approximately presented in
memory in binary form up to the
allowed precision (15 digit precision in case of
Python).
This approximation may yield
unexpected results it you are comparing
floating-point numbers especially for equality (
Numbers such as 1/3 etc., cannot be fully represented as
binary as it yields 0.3333... etc. and to
represent it in binary some approximation is done internally.
Consider the following code for to understand it:

>>» 0.1+0.1+0.1 == 0.3


Notice, Python returns False when you
False compare 0.1+ 0.1 +0.1 with 0.3.

>> print (0.1+0.1+0.1) See, it does not give you 0.3 when you print
the result of expression 0.1+ 0.1 +0.1
0.300000ee000eeoo04 (because of floating pt approximation) and
this is the reason the result is False for
print(e.3) quality
comparison of 0.1+ 0.1 +0.1 and 0.3
.3

Thus, you should avoid floating point equality comparisons as much as you can.

Relational Operators with Arithmetic Operators


The relational operators have a lower precedence than the
arithmetic operators.
Check Point

That means the expression


8.5
a+5 c -2 expression 1
Given that i
=4, j =5, k =4, what will Corresponds to
bethe result of following
0i<k expressions (a+5) (c-2) expression 2
(it) i<j (iüi) i <=k (iv)i==j
i-=k (v) j>k (vi)j>=i and not the following
vii) j=i (ix) j a+(5 c) -2 expression 3
=k
nat will be the order of
evaluation for Expression 1 means the expression 2 and not the expression 3.
following expressions?
) 1+5>=j-6 (ü) s* Though relational operators are easy to work with, yet while
(i)i<j k>1-n 10< p
+
** 2
working with them, sometimes you get unexpected results
How are following two and behaviour from your program. To avoid so, I would
terent ? () expressions
ans 8 like you to know certain tips regarding relational operators.
=
( ans = 8
222 COMPUTER SCIENCE WITH
PYTHONN
A very common mistake is to the assignment operator in
use
place of the relational operator = =. Do not confuse testing the
=

NOTE
operator == with the assignment operator (=). For instance, the In
Python, arithmetic
expression
have operators
higher precedence
relational operators i.e., over
value1 == 3
y+X>y 2 would be
*

internally as (y +x) evaluated


tests whether valuel is equal to 3? The expression has the value >
(y*2
True if the comparison is true otherwise it is False. But the
expression
value1 = 3 TIP
Do not
assigns 3 to valuel; no comparison takes place. confuse the and the
=

=
operators.

8.4.3 ldentity Operators


There are two identity
operators in Python is and is not. The identity operators are
check if both the used to
operands reference the same object memory i.e., the
compare the memory locations of two objects and return True or False identity operators
accordingly.
Operator Usage Description
is a is b returns True if both its
to same
operands are
pointing to same
object (i.e., both referring
memory location), returns False otherwise.
is not is
a
not b returns True if both its
operands
referring to different memory
are
pointing to different objects (i.e., both |
location), returns False otherwise.
Consider the following examples :

A 10
B 10
Ais B will return True because
both are
referencing the memory address of value iu
You can use id() to confirm that both are
referencing same memory address.
> a = 235

b= 240
a is b returns False because a and b are
C= 235 refering to
different objects (235 and
a is
240)
c returns True because
both a and c are
a is b referring to same
object (235)
False

> ais c
True
Theids of a, b and tell thata and
c

>
print(id(a), id(b) , id(c)) are referring to same object (their memoy

492124000 492124080 492124000 addresses are same) but b is referring To


different object as its memory address
-
different from the other two
DATA
HANDLIN ING
ofer 8:
Chapter
223
w if you change the value of b so that it is not
No

e x p r e s s i o n
a s ib
is will return True: referring to same
integer object, then
- - -

> b = b -5
ais b Now b is also
pointing to same integer
True object(235) thus a is b is giving True this time.
Their ids also
reflect the same i.e., all a, b
>> print(id(a), id (b), id(c)). and c are
referring to same memory location
492124000 492124000 492124eee

a is not operator is opposite of the is operator. It returns True when


referring to same memory address. both its operands are not

: 43A Equality (==) and


ldentity (is) Important Relation-

Vou have seen in above given examples that when two


variables are referring to 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. That is,
thata= b will also be True, always. See below: expression a isb as True means

>print (a, b)
235 235

a isb
True

> a == b

True

Dut t is not always true other way round. That means there are some cases where you will find
tnatthe two objects are having just the same value ie,=operator returns True for them but the
Is
operator returns False.
See in the screenshots
shown here.

>> s1 ='abc'

> $2 input ("Enter a string: ")


Enter a
string : abc
>> s1== $2
.The strings s1 and s2 although have the same
value 'abc' in them

True .The operator also returns True for s1 == s2

>» s1 is . But the is operator returns False for s1 is s2


s2
False
>> s3 =
"'abc"
s1is $3
True
COMPUTER SCIENCE WITH PYTHO
224 HON

Similarly,
store the same complex
>>>i=2+3.5j Objects i and j
number value 2+3.5j in them
>j= 2+3.5j returns False for i is j
But is operator

>>>iisjj
False

Also,
> k = 3.5

1 float (input ( "Entera


value: "))
.The variables k and / both store float value 3.5
Enter a value : 3.5
(k assigned 3.5 and I has taken this
has been
>>k === 1 valuethrough input() and float())
True .But k == I returns True and k is I returns False

> > k is 1
False
few cases where Python creates two
there are a
The reason behind this behaviour is that
both store the same value. These are
different objects even though
the console;
input of strings from
writing integers literals with many digits (very big integers);
and complex literals.
writing floating-point screenshots.
illustrates one of the above given
Following figure

>s1= 'abc' m
30456
>>>s2 input("Enter a string: ")
abc

abc
Enter a string:
s3
s 1 == $2
True
abc
s1 is s2
1345724
False

s3 = 'abc'

> s1 is s3
NOTE rue
True returns
is operator
Ifthe the
need to check whether the two then
Most of the times we just for two objects
return True
value or not-in this case the equality must

objects refer to the same


fwo
0perator

objects, ie,
this test. However, in advanced same

operator ( i s sufficient for


the
refer to
the sau
need to check whether references
then te
in your projects, you may
programs or memory
address,

address or not in this case, you


always same
-

they refer to same memory values a r e

can use the is operator.


HANDLING
DATA

ler 8:
Chopler 225
8.4.4 Logical Operators

rlier section.discussed about relational


An
tion talks about logical operators that establish relationships among
values. This sectio
operators, the Boolean logical the
reter to the ways these relationships operators
(among values) can be connected. Python
(or, and, not) that
anerators to combine existing expressions.
logical operat
These are or, and, and not.
provides three
roceed to the discussion of logical operators, it is
DeTesting, because in some cases logical operators baseimportant for you to know about Truth
their results on truth value testing.
Truth Value Testing
84.4A
dhon with every value type, some truth
associates value (the
rizes them as true or false. Any object can be tested fortruthiness), i.e., Python internally
truth value. Python considers
fallowing values false, (i.e., with truth-value as false) and true:
Values with truth value as false Values with truth value as true
None

False (Boolean value False)


Zero of any numeric type, for example, 0, 0.0, 0Oj
All other values are
any empty sequence, for example, ", ( ), [ 1 considered true.
(pleasenote, isempty string; O is empty tuple; and [ ]isemptylist)]
anyempty mapping, for example, { }
The result ofa relational expression can be True or False depending upon the values of its operands and the
comparison taking place.
Do not confuse between Boolean values True, False and truth values (truthiness values) true, false.
Simply put truth-value tests for zero-ness or emptiness of a value. Boolean values belong to just
one data type, i.e., Boolean type, whereas we can test truthiness for every value object in Python. But
to avoid any confusion, we shall be giving truth values true and false in small letters and with a subscript
fonl, 1.e., now on in this chapter true tal and false al Will be referring to truth-values of an object.

The utility of Truth Value testing will be clear to you as we are discussing the functioning of
logical operators.
8.4.4B The or
Operator
The
E
or
operator combines two expressions, which make operands.
its or
Ways: () relational expressions as operands (i) numbers or strings or ists as operands
in
The operator works
) Relational expressions as operands
then the
r operator has its operands as relational expressions (eg, p >g,j=k, etc.)
en or

Perator performs as per following principle :

operator evaluates to True if either of its


Or (relational) operands evaluates to
e
rue; False if both operands evaluate to False.
That is:
x or y
False False False
False True True
True False True
True True True
226 COMPUTER SCIENCE WITH
PYTHC

Following are some examples of this or The or operator will test the second

operation:
only if the first operand is false, otherw operan
ignore it; even if the second operana
(4 4) or (5 == 8) results into True because first
expression (4 ==
4) is True. logically wrong eg, operand is
5 8 or 5<2 results into False because:
20 10 or "a" +1> 1

bothexpressions 5 >8 and will give you result as True


5<2 are False.
without checking the second operand of or ia
i) Numbers/ strings/ lists as operands "a +1>1, which is syntactically wrong-u
cannot add an integer to a string. you
When or operator has its operarnds as
numbers or strings or lists (e.g., 'd or ",3 or 0,
etc.) then the or operator performs as per NOTE
following principle: The or operator will test the second operand only if the
first operand is false, otherwise ignore it.
In an expression x or y, if first operand, (i.e.,
expression x) has false pval then return second8.4.4C The and Operator
operand y as result, otherwise return x.
The and operator combines two expressions
That is which make its operands. The and operator
y XO y works in these ways : (i) relational expressions
false oal false toal as operands (i) numbers or strings or lists as
false oal true toal
operands
true toal false tpal
true toalI true toal Relational expressions as operands
When and operator has its operands as
NOTE
relational expressions (eg.,p > qjl= k, etc)
In general, True and False represent the Boolean
then the and operator performs as per
values and true and false represent truth values.
following principle
Examples The and operator evaluates to True if both of
Results (relational) operands evaluate to True;False
Operation into Reason
either or both operands evaluate to False.
0 or 0 | 1st expression (0) has falseal thus
|2nd expression 0 is returned. That is
X x and y
0 or 8 8 1st expression (0) has false tuoalr thus
2nd expression 8 is returned. False False False
5 or 0.0) 5 1st expression (5) has true pat thus False True False
1st expression 5 is returned. True False False
hello' or"| hello 1st expression ('hello') has true tpale True True True
| thus 1st expression 'hello' is retumed
Following are some examples of the
and
"or 'd 'a 1st expression (") has false poal thus

"
2nd expression 'a' is returned. operation:
or 1st expression (") has false pa thus
2nd expression " is r e t u r n e d .
(4 - 4) and (5 == 8)
(4==49s
'a' or j' a |1st expression ('a') has results into False because first
true,oa xpression
Falke
|thus 1st expression'a' is returned. rue but second expression (5 ==8) evaluates
to
to
rde
How the truth value is determined ? Both operands have to result into True in o
-

refer to
section 8.4.4A above. have the final results as True
7. This type of or functioning applies to any value which is not a relational
determineu

by Python. expression but whose truthness cat be


iess can
HANDLING
8: DATA
Chapter
227
5 8 and 5 < 2

results into False cause first expression : 5>8


IMPORTANT
The and
evaluates to False. operator will test the second operand only if
the first operand is
true, otherwise ignore it ; even if the
2< 5 second operand is
8 5and logically wrong e.g.,
nto True because both operands 8>5 and
result
10 20 and "a" + 10 <5
evaluate to True.
2<5
will give you result as

al Numbers strings/ lists as operands8 False


When and operator has its operands as ignoring the second operand completely, even if it is
numbers or strings or lists (e.g, 'a' or ", 3 or 0, wrong-you cannot add an integer to a string in Python.
etc.) then the and operator performs as per
following principle :
The and operator will test the second
In an expression x and y, f first operand, (i.e., operand only if
the first operand is true, otherwise
expression x) has false tval then return first ignore it.
operand x as Tesult, otherwise return y.
8.4.4D The not Operator
Thatis
X x and y The Boolean/logical not works
operator, on
false toal false toal single expression or
operand i.e., it
is a unary
false roal true toal operator. The logical not operator negates or
reverses the truth value of the
true roal false toal expression
true toal true toal1 following it i.e., if the expression is True or
truetval then not expression is False, and vice
Examples versa. Unlike 'and' and 'or operators that can
OperationResults
return number or a
into Reason string or a list etc. as result,
the 'not' operator returns
0 and 0 0 1st expression (0) has
false,toalr always
a Boolean

thus first expression 0 is returned. value True or False.


0 and 8
1st expression (0) has false Consider some
examples below:
tual
thus 1st expression 0 is returned.
5 and 0.0
not 5 results into False because 5 is
0.0 1st expression (5) has true toal non-zero (i.e., true twal)
thus 2nd expression 0.0 is
returned. not e results into True because 0 is zero
hello and "
1st expression ('hello') has (i.e., false poa)
true
toal thus 2nd expression " is not -4
results into False because -4 is non
returneda zero thus true toal
"and 'a 1st expression (")
thus 1st expression "
has
false toal
is returned. not (5> 2) results into False because the
and" expression 5 >2 is True.
1st expression ("") has
false tpal
thus 1st expression" is not (S> 9) results into True because the
returned. expression 5>9 is False.
'aand 1st expression ('a') has true toal
thus 2nd expression j is NOTE
returned. Operator not has a lower priority than non-Boolean
the truth value is determined operators, so not a ==b is interpreted as not (a == b),
section 8.4.4A. ?-refer to and a not b is a syntax error.

8.
This type of or
by Python OE
functioningaapplies to any value which is not a
Tunctioning relational expression but whose truthness can be determined
228 COMPUTER SCIENCE WITH
PYTHON - X

Following table summarizes the logical operators.


Table 8.4 The Logical Operators

Operation Result Notes


x or if x is false tpul then return y It (or) only evaluates the second argument if the first
as result, else x false toal one
x and y if x is false pul then x as It (and) only evaluates the second argument if the first ona
result, else y true tpal
not if x is false toa then return not has a lower priority than non-Boolean operators,
True as result, else False

Chained Comparison Operators


While discussing Logical operators, Python has something interesting to offer. You can chain
multiple comparisons which are like shortened version of larger Boolean expressions. Let us See
how. Rather than writing 1 < 2 and 2 <3,
you can even write 1<2<3, which the chained version
of earlier Boolean
expression.
The above statement will check if 1 was less than 2 and 2 was less
if than 3.
Let's look at a few examples
of using chains
> 1«2<3 is equivalent to >>>1< 2 and 2 < 3
True True
As per the property of and, the
expression1<3 will be first evaluated and if only it is True, then
only the next chained expression 2 < 3 will be evaluated.
Similarly consider some more examples:
1 1 < 13 >12
True
The above
expression checks if 13 is larger than both the other numbers
; it is the shortened
version of 11 < 13 and 13> 12.

8.4.5 Bitwise Operators


Python also provides another category of operators - bitwise operators, which are similar to tne
logical operators, except that they work on a smaller scale on
Bitwise
operators are used to change individual bits in an binary representations of aa
-

Python provides following Bitwise operators.


operand.
Table 8.5 Bitwise Operators
Operator Operation Use
bitwise and op1 &op2 The AND operator
Description
both bits are 1; compares two bits and generates a resu
bitwise or
otherwise,
it returns 0.
op1 op2 The OR operator compares two bits and generates aresult of1ifthe
bitwise xor
bits are
complementary; otherwise, it returns 0. resuno
op1 op2 The EXCLUSIVE-OR (XOR) operator compares two returns

1 if either of the bits are 1 and it gives bitsarear


0 if both bits 1,
bitwise op1 The COMPLEMENT operator is used to invert all of the Dl
complement operand.
8 DATA HANDLING 229
Chapter 8 .

e x a m i n e
them one by o nne.
us
Let

AND operator &


The
4.5A numbers, the & each
When
its erands are operation performs the bitwise AND function on
its in each operand. The AND function sets the resulting bit to 1 if the
bits
pair of
rallel
TesDonding bit in both operands l, as shown in the following Table 8.6.
is

The Bitwise. AND (&) Operation


ble 8.6

op1 op2 Result


0 For AND operations, 1 AND 1 produces 1.

Any other combination produces 0.


0
1 0

>>> bin(13)
13 & 12 1101
w e r e to AND the values 13 ob1101
Suppose that you 1100
& 12. The result of this
and 12, like this : 13 >bin(12)
operation is 12 because the binary 1100 eb1100
and the binary
representation of 12 is 1100, 1 3 & 12
You can use bin()
representation of 13 is 1101. 12
of a number.
to get binary representation
AND function >> bin(13 & 12)
If both operand bits a r e 1, the
sets the bit to 1 ; otherwise, the
resulting
ob1100
the two
resulting bit is 0. So, when you line up that the two high-order bits (the
two bits
the AND function, you can see
operands and perform a r e 1. Thus, the resulting
bit in the result is
tarthest to the left of each number) of each operand 0.
because either one or both bits in the operands are

also 1. The low-order bits evaluate to 0

8.4.58 The inclusive OR operator|


the inclusive OR operation.
numbers, the | operator performs
both of its operands The following Table 8.7
are
When the two bits is 1, the result is 1.
OR means that if either of
nclusive
shows the results of inclusive OR operations.
able 8.7 The Inclusive OR (|) Operation >bin(13)
13 12 0000 1101 'eb1101'
0e00 1100
op1 op2 Result
>> bin(12)
0
e000 1101 @b1100'
1 1
1 0 1 > bin(13 | 12)
eb1101'
1
1 3 | 12
OR 0.
OT operations, 0 OR 0 produces
Any other combination produces 1. 13
8.4.5C The eXclusive OR (XOR) operator result is 1; otherwise the
different, the
Exclusive OR means that if the
two operand
bits a r e
of an
eXclusive OR operation.
result ne
following Table 8.8
shows the
results
230 COMPUTER SCIENCE WITH
PYTHONN
-
able 8.8 The eXclusive OR () Operation
13 12 ee00 1101
>>> bin(13)
Op1 op2 Result e00e 1100
eb1101
0 0
0 1
>>bin(12)
e00e ee01 eb1100
1 1
> 13 12
1
For XOR operations, 1 XOR 0 produces 1, as does 0 XOR 1. (All these >> bin(13 12)
operations are commutative.) Any other combination produces 0.
i "@b1
8.4.5D The Complement Operator
The complement operator inverts the value of each bit of the
result is 0 and if the
operand: if the operand bit is 1 the
operand
bit is 0 the result is 1.
This is binary code of -15 in »»bin(12)
able 8.9 The Complement (-) Operation 2's complement form. @b1100
12
op1 Result 12 0000 1100
-13
1 -

1111 0011 » bin(13)


0
= -

(0000 1101) ob1101

8.4.6 Operator Precedence bin(-12)


'-@b1101
When an expression or statement involves
multiple operators, Python resolves the order of
execution through Operator Precedence. The chart of
lowest for the operators covered in this operator precedence from highest to
chapter is given below.
Operator
Description
Parentheses (grouping)
** Highest
Exponentiation
X Bitwise nor
+X, -X
Positive, negative (unary +,
*,1,11,%
Multiplication, division, floor division, remainder
Addition, subtraction
Bitwise and
Bitwise XOR
Bitwise OR
>=, <>, l, =5
1s, is not
Comparisons (Relational operators), identity operators
not x Boolean NOT
and Boolean AND
or
Boolean OR Lowest

9. To obtain the number whose 2's


complement is given, you can calculate its 2's complement following this rule
starting from right to left, copy all the bits as it is UNTIL you find first again by followingicrule
complement of 11110011 as 00001101, which is 13. invert all other
we can calculate 2's
1, then bits. As per
DATA
HANDLING

231
Chopter 8:

Operator Associativity

Python allows multiple operators in


single expression as you have learnt above, e.g,
a

b+2<c or p<qretc. Ifthe operators used in an expression have different precedence,


a
here is not any problem as P'ython will evaluate the operator with higher precedence first. BUT
f the expression contains two operators that have the same precedence ?
wh

In
that case, associativity helps determine the order of operations.
Accociativity 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. That means, in case of multiple operators with same
precedence, other than **, in same expression - the operator on the left is evaluated first and
then the operator on its right and so on.

For example, multiplication operator (), division operator () and floor division operator ()
have the same precedence. So, if we have an expression having these operators simultaneously,
then the same-precedence-operators will be evaluated in left-to-right order.

For example,

»» 7*8 /5//2
5.0

» ((7 *8) /5) // 2) This first expression is evaluated in left to


5. right order of operators as evident from the
2md expression's evaluation that clearly marks
this order of evaluation
» 7* ( (8/ 5) // 2))
0.0

> 7 * (8/ (5//2) )


28.0

*CApresSion having multiple ** operators is evaluated from right to left, i.e.,

2*3*4 will be evaluated as 2** (3 *4) and NOT AS (2**3)*4

Consider following example:


See the default order of evaluation (first expression)
» 3 ** ** MATCHES with the second expression where
3 2
added as per right-to-lefi associativity order
parentheses are
19683 and NOT LIKE third expression that has parentheses from
left-to-right order, because exponentiation (**) has
3** (3 **2) right-to-left associativity
19683
»
NOTE
(3 **
3) ** 2 Associativity is the order in which an
729 expression having multiple operators of
same precedence, is evaluated.
All operators are left associative except
exponentiation (right associative).
232 COMPUTER SCIENCE WITH PYTH
PYTHON -
EXAMPLE 6 What will be the output produced by EXAMPLE T1 Why is the following code
code on owing grving error?
the following code ? print (11+3)
X, Z 5 , 10 print ("11' +3)
y X+3 SOLUTION
X =X 1
The problem is with line 2 of
X =X+Z given code
because an integer cannot be added to a
print('x: ', x, 'y: 's y, 'z: ', z) string value, thus Python will give:
SOLUTION TypeError: can only concatenate str (not
"int") to tr
x: 14 y: 8 z: 10

EXAMPLE 12 Which
the following of expresions
EXAMPLE 7 What will be the output produced by; will yield an integer type value as its output ?
the following code ?
(i)5*2(ir) 5 ** 2

print(14//4, 14%4, 14/4) (ii) '5 +2 (iv) '5 *2


(v) 5/2 (vi) 5 // 2
SOLUTION
(vi) 5 % 2 (vii) 5 +2.0
3 2 3.5
(ix) 5.0* 2.0 (x) 5 - 2

EXAMPLE 8 What will be the SOLUTION


output produced by :
the following code? Expressions (i), (i), (vi), (vii) will yield integer
type result.
print (2*'No' +3* !")
print(2 * ( "No' +3** "))
EXAMPLE 13 Considering the expressions given in
SOLUTION the previous example, which expressions will yield a
NONO!!! floating point result
No!!!No!!! SOLUTION
Expressions (o), (vii), (ix) will yield a floating
EXAMPLE 9What uwill be the output produced by; point result.
thefollowing code?
print(type(1+3)) EXAMPLE 14 Considering the expressions given
print(type(1+3.0)) the previous example 12, which expressions will yielda
SOLUTION String result?
<class 'int'> SOLUTION
<class 'float'>
Expressions (ii), (io) will yield a Stringresul
enim
EXAMPLE 10 What will be the output produced EXAMPLE 15 Considering the expressions gioen
the following code ?
Pesult

the previous example 10, which expressions wil r


into an Error and why?
print (11+3)
SOLUTION
print ('11' + '3') the
e

SOLUTION Expression (x) will result into error becaot


minus operator is not a valid operator
14
string and integer values.
113
: DATA HANDLING
Chapter 8 : 233

OPERATORS IN PYTHON

+iP.
Progress In Python 8.2
This actical session aims at strengtherning operators' concepts. It involves both interactive mode and
or
script mode. For better understanding ot the concepts, it would be better if you first perform the
teractive mode practice
questions followed by script mode practice questions.

Please check the practical component-book - Progress in


Computer
Science with Python and till it there in PriP 8.2 under Chapter 8 after
practically doing it on the computer.
>>><<<
Check Point

8.6
LET US REVISE

1. What is the function of logical Immutable Types in Python mean that their values cannot be
operators ?Write an expression changed in place.
involving a logical operator to test if
*Mutable Types Python mean that their values can be changed
marks are 55 and grade is 'B'. in place
Python has only 3 mutable type : lists, dictionaries and sets.
2. What is the order of evaluation in the
Operators are the symbols (or keywords sometimes) that represent
following expressions :
() a b or b <= d ?
specific operations.
Arithmetic operators carry out arithmetic for Python. These are
(7) x= y and y >= m?
c>d
unary +, unary ,+,,*,1,1,% and **.
(t) a>b Unary + gives the value ofits operand, unary changes the sign of
3. What is the result of following its operand's value.
expression : a >= b and (a +b)> a if
Addition operator +gives sum ofis operand's value, - subtracts the
i) a =3, b =0 (i) a =7, b=7? value of second operand from the value of first operand, * gives the
What is the result of following product of its operands' value. The operator/ divides the first operand
expressions (a to e) if by second and returns a float result // performs the floor division, 9%
i) check =3, mate = 0.0 gives the remainder after dtividing first operand by second and** is
i) check =0, mate = -5 the exponentiation operator, i.e., it gives base raised to power.

(ü) check ="', mate = 'e Relational operators compare the values of their operands. These
are, <, = , <=,>= and! =ie., less than, greater than, equal to,
(iv) check ='meera', mate =''
less than or equal to, greater than or equal to and not equal to
(a) check or mate b) mate or check
respectively.
c) check and not mate Bitwise operators are like logical operators but they work on
a) check and mate
(e) mate and check individual bits.
Evaluate each
for
of the above
expressions Identify operators (is, is not) compare the memory two objects are
all four sets of
5. identify the values. referencing.
order of evaluation in the on the basis oftruth-ness of
follow expression: Logical operators perform comparisons
an expression or value. These are 'or', 'and' and 'not'.
45 +7 2 8 % 3+ 4 and *
relational expressions' truth value depends on their
.7 // Boolean or

not 2
2 -1+4 or not 2 == 4
**
and Boolean result True or False.
4 > 6 * 2
6. emptiness
their non-emptiness.
or
a 15.5, b Values' truth value depends
on
=
15.5 then why is a is b is 0, 0.0, 0j etc.) and empty sequences (such
Empty numbers (such
as
ralse while a b is True? None have truth-vaBue as false and all others
==

as", [1, ()) and


have truth-value as true.
(non-empty ones)
234 COMPUTER SCIENCE WITH
PYTH
HON
8.5 EXPRESSIONS
An expression in Python is any valid combination of operators,
ATOM
An atom is
literals and variables. An expression is composed of one or something that
more operations, with operators, literals, and variables as the
value.
Identifiers, has
strings, lists, tuples, literals,
constituents of expressions. dictionaries etc. are all atoms,
Python puts it in this way: a valid combination of atoms and
operators forms a Python expression. In simplest words, an
atom is something that has a value. So all of these are atoms EXPRESSION
in Python: identifiers, literals and values-in-enclosures such as An expression
valid combination
in
Python is any
quotes ("), parentheses, brackets, etc. i.e, strings, tuples, lists, of
dictionaries, sets etc. and atoms. An
operators
expression is
composed of one or
more
The expressions in Python type arithmetic
can be of any operations.
expressions, string expressions, relational expressions, logical
expressions, compound expressions etc.
The types of operators and operands used in an expression determine the
expression type.
An expression can be compound expression too if it involves
multiple of types operators
e.g., a + b> c**d a*b< c*d is
or a
compound expression as it involves arithmetic as well as
relational as well as logical operators.
Let us talk about these one by one.

1. Arithmetic Expressions
Arithmetic expressions involve numbers
(integers, floating-point numbers, complex numbers) and
arithmetic operators.
2. Relational Expressions
An expression having literals and/or variables of any valid type and relational
relational expression. For example, these are valid relational expressions operators 1sa
Xy, y<= Z, Z < X, z
== q, X <y> z, X ==
y <>z

3. Logical Expressions
An expression having literals and/or variables of any valid type and
logical expression. For example, these are valid logical operators i
logical expressions:
a or b, band c, a and not b, not c or notb
4. String expressions
Python also provides two string operators + and *, when combined Is and
integers, form string expressions. with string operarn
With operator +, the concatenation operator, the
With* operator, the replication operator, the
operands should be string type only.
of
operands should be one string and one teger
For instance, following are some legal string
"and" "then"
expressions
# would result into 'andthen' - concatenation
"and" 2 #would result into
String manipulation is being covered in a
'andand replication -

separate chapter chapter 10. -


Chopter 8 :
3 : DATA H A NDLING
ND
235
Evaluating txpressions

8.5.1

section, we shal be
discussing how Python evaluates different pes of expressions
this
ic.,
arithme
relational and logical expressions. String expressions, as mentioned earlier will be
in a separate chapter chapter 10.
-

discusse

Evaluating Arithmetic Expressions


8.5.1A
l are familiar with arithmetic expressions and their basic evaluation rules, right from
rimary and middle-school years. Likewise, Python also has certain set of rules that help it
youl
evalu an expression. Let's see how Python evaluates them.
Fraluating Arithmetic Expressions
Toevaluate an arithmetic expression (with operator and operands), Python follows these rules:
Determines the order of evaluation in an expression considering the operator precedence.
As per the evaluation order, for each of the sub-expression (generally in the form of <value>
<operator<value> e.g., 13% 3)
Evaluate each of its operands or
arguments.
Performs any implicit conversions (e.g., promoting int to float or bool to int for arithmetic
on mixed types). For implicit conversion rules of Python, read the text given after the rules.
Compute its resultbased on the operator.
Replace the subexpression with the computed result and carry on the expression evaluation.
Repeat till the final result is obtained.

Implicit type conversion (Coercion). An implicit type conversion is a conversion performed by


the compiler without
programmer's intervention. An implicit conversion is applied generally
whenever
differing data types are intermixed in an expression (mixed mode expression), so as
not to lose information.
in a mixed arithmetic expression, Python converts all operands up to the type of the largest
operand (type promotion). In
simplest form, an expression is like op1 operator op2 (e.g., x/y
OrPa). Here, if both arguments are standard numeric types, the following coercions are
applied
t h e r argument is a complex number, the other is converted to complex;
rwse, ifeither argument is a floating point number, the other is converted to floating point;
No
conversion if both operands are integers.
To understand this,
consider the
WIng example, which will make it ch 5 #integer
ear how Python i = 2 # integer
internally coerces
promotes) data types in mixed a
fl 4 # integer
ype arithmetic # floating point number
evaluates it. expression and then
db 5.0
fd 36. #floating point number
db # expression 1
A (ch+ i) /
MPLE 16 Conside B fd /db * ch / 2 #expression 2

ontaining mixed
ve the Isider the
following code print (A)
nal result arithmetic exP
and the
xpression. What wil print (B)
final data type ?
236 COMPUTER SCIENCE WITH PYTHON
-

SOLUTION As per operator precedence, expression 1 will be internally evaluated as

A ((ch + i)/db)

int int

Step 1 (no conversion here)


int floating pt
Step 2 (int to floating -pt conversion)
floatingpt
So overall, final datatype for expression 1 will be floating-point number and the expressin
will be evaluated as:
((ch +i)/db)
((5+2))/5.0
((5+2))/5.0
B (((fd/db) * ch)/2)
=(7)/5.0
int to floating point conversion] float float

= 7.0/5.0
no conversion
A 14 float int

integer to floating
As per operator precedence, expression float pt conversion
2 will be internally evaluated as
int

integer to floating
So, final datatype for expression 2 will float pt conversion

be floating point number.

The expression, expression 2 will be evaluated as

(C(fd/db)*ch) /2)
= (36.0/5.0)* 5L/2)
no conversion required]
= ((7.2 5)/2)
int to floating point conversion]
=
((7.2 5.0) /2)
= (36.0/2)
integer to floating point conversion
36.0/2.0
B =18.0
1.4
The output will be 18. 0
e

IMPORTANT In Python, if the operato ways bea

will alway
division operator (/), the result h the
The final Tloating point number, even
datatype of expression
to
l will be floating on

operands are of integer types (an exth


point number and of expression 2, it will be the rule). Consider following exanp
floating-point number. illustrates it.
HANDLING

DATA
dar 8:
Chopter 237
EXAMPLE1 7 Consider Consider below given expressi0ns what.
Will be the final result and
b) a, b = 3, 6 final data type ?
b = 3, 6
(a) a, () a, b 3, 6
c b/a C =b//a C = b% a
n expression

OLUTION ()
C 6/3 b a

C 2.0

int int
Here, the operator is /, which
gives floating pt result. alvays
floating pt
(b) In expression
(c) In expression
C 6//3 b 1/a C 6%3
C2 For other division % a
related operations, C 0
int
int land %, if both
int
operands are integers, int
int result will be integer.
int
You, yourself, can run these expressions in Python shell and then check the type of C
(C) function. using type
8.5.1B Evaluating Relational Expressions (Comparisons)
All comparison operations in Python have the same priority, which is lower than
arithmetic that of any
operations. All relational expressions (comparisons) yield Boolean values
True or False. only i.e.,
Further, chained expressions like a<b<c have the
mathematics i.e., comparisons in interpretation that is conventional in
treated as a< b and b<c Python are chained
arbitrarily, e.g, a< b< c is internally
For chained
comparisons like x<y<=z (which internally equivalent to x< and
is
Common
expression (the middle one, y here) is evaluated only y y<=z), the
z here) is not evaluated once and the third
at all when first expression
comparison (x< y here) is found to be False.
EXAMPLE 18
What will
be output of following statement when the inputs are:
(i) a = 10, b=23, c=23 (it) a =23, b=10, c=10
print (a < b)
print (b = c)
print (a «b <= c)
OLUTION For input combination
the (i), For input combination (ii),
output would be the output would be
True False
True True
True False
XAMPLE 19
would following relational be
expressions internally interpreted by Python ?
SOLUTION () (P> 9)
9p>9)
) p>q<y
and
(i) a= N<=b
(q< y) (i) (a=N) and (N<=b)
238 COMPUTER SCIENCE WITH
PYTHON
X
8.5.1C Evaluating Logical Expressions
Recall that the use of logical operators and, or and not makes a
logical expression
evaluating logical expressions, Python follows these rules ssion. While
(i) The precedence of logical operators is lower than the arithmetic operators, so cont
arithmetic sub-expression (if any) is evaluated first and then nstituent
logical operators
applied, e.g are

25/5 or 2.0 + 20/1e will be first evaluated as: 5 or 4.

So, the overall result will be 5. (For logical operators' functioning, refer to section
843
(ii) The precedence of logical operators among themselves is not, and, or. So, the expressiom
a or b and not c will be evaluated as

(a or (b and (not c) )) Similarly, following expression


((p and q) or (not r))
pand q or not r will be evaluated as:

(ii) Important. While evaluating, Python minimizes internal work by following these rules
(a) In or evaluation, Python only evaluates the second argument if the first one is
false oal
(b) In and evaluation, Python only evaluates the second argument if the first one is
true toal
For instance, consider the following examples:
In expression (3 < 5) or (5<2), since first argument (3<5) is True, simply its (first
argument's) result is returned as overall result; the second argument (5< 2) will not be
evaluated at all.
In expression (5 <3) or (5 < 2), since first argument (5 < 3) is False, it will now evaluate
the second
argument (5 < 2) and its (second argument's) result is returned as overall result.
I n expression (3 < 5) and (5 <2), since first
the second argumernt (5 < 2) and its
argument (3 <5) is True, it will now evaluate
(second argument's) result is returned as overall result
I n expression (5 < 3) and (5 <2), since first
argument (5< 3) is False, simply
argument's) result is returned as overall result; the second argument (5 <2) willitsno
evaluated at all.
Check Point

8.7 EXAMPLE 20 What will be the output of following


expre
ession?

Evaluation of expression and type (S10) and (10 « 5) or (3 < 18) and not 8 <10
conversion
1. What is
SOLUTION False
an expression ? How many
different types of expressions can you
have in Python ?
EXAMPLE 21 Divide zero' is an ividing

2. What is atom in context of expression ? by undefined terh when


by zero causes an error in any
3. From the following expression, identify programming languug t e a
atoms and operators.
follooing expression is evaluated in Python, Python reporte
error and returned the result as True. Could you tell, wny ?
str(a+b >c+d>e+for not g-h)
4. What is type conversion (coercion) ? (5 < 10) or
(50 <100/0)
How does Python perform it ?
C h o p t e r
DATA HANDLING
239
soLUTION

In or evaluatio tion, firstly Python tests the first argument, i.e., 5 10 here, which is True. In or
ation, Python does not evaluate the second argument if the first argument is True and
evaluation,

S the result of first argument as the result of overall expression.


returr

Go, for the given expresSion, the second argument expression (50 < 100/0) is NOT EVALUATED
AT ALL. That is why, Fython reported no error, and simply returned True, the result of first
A argument.

8.5.2 Type Casting


You have learnt in earlier section that in expression with
CPE CASITNG
mixed types, Python internally changes the data type of some The explicit conversion of an
operands so that all operands have same data type. This type operand to a specific type is
of conversion is automatic, 1.e., implicit and hence known as called type casting
implicit type conversion. Python, however, also supports
explicit type conversion.

Explicit Type Conversion


An explicit type conversion is user-defined conversion that
C h e c k P o i n t

8.8 forces an expression to be of specific type. The explicit type


conversion is also known as Type Casting.
1. Are the following expressions equal ?
Why/why not ? Type casting in Python is performed by <type>() function of
xor y and not z appropriate data type, in the following manner:
(x or y) and (not z) ) <datatype> (expression)
(x or (y and (not z) ))
where <datatype> is the data type to which you want to
2. State when would only first argument
be evaluated and when both first and type-cast your expression.
second arguments are evaluated in For example, if we have (a = 3 and b = 5.0), then
following expressions if a =5, b=10,
c-5, d =0. int (b)
() b>c and c>d will cast the data-type of the expression as int.
(i) a <= b or c<=d
(tn) (b+c) <=a and not (c < a)
Similarly,
(iv) b<d and d <a d float (a)
3.
What is Type casting? will assign value 3.0 to d because float(a) cast the
4. How is implicit type conversion different
from explicit type conversion ?
expression's value to float type and then assigned it to d.
. Python offers some conversion functions that you can use
Write conversion function
you would to type cast a value in Python. These are being listed in
use for
following type of conversions. following Table 8.10.
i) Boolean to string
i) integer to float
ii) float to integer EXPRESSION EVALUATION
(iv string to integer Progress In Python 8.3
iP
(stringto float
This is an important practical session to reinforce the concepts of
()string to Boolean evaluation in
vii) integer expression Python.
to complex >>>%<<<
COMPUTER SCIENCE WITH
240 PYTHON -
Table 8.10 Python Data Conversion Functions

ConversSIon Conversion Examples


No To
Function
From
int(7.8) will give 7
1. any number-conver integer int()
(floating point number to integer conversior
tible type e.g., a float, a
int('34)will give 34 (string to integer conversin
string having digits sion)
float(7) will give 7.00
any number-conver- floating float()
(integer to floating point number conversion)
tible type eg, a float, a | point
number float(34) will give 34.0
string having digits
(string to floating point number conversion)

3. numbers complex complex( complex(7) will give 7+0j


number (ONE ARGUMENT- integer to complex number
conversion)
complex(3, 2) will give 3+2j
(TWO ARGUMENTS- integer to complex number
conversion)

str( str(3) will give 3 (integer to string conversion)


number Booleans string
str(5.78) will give '"5.78'
(floating-point number to string conversion)
str(0o17) will give '15
(octal number to string conversion ; string converts
the equivalent decimal number to string: 0o17=15)
str(1 + 2j) will give '(1+2i)
(complex number to string conversion)
str(True) will give "True'
(Boolean to string conversion)

Boolean bool() bool(0) will give False bool(0.0) will give False
5. any type
bool(1) will give True ; bool(3) will give True
True
bool(") will give False ; bool('a') will give
bool(hello) will give True
With bool( ), non-zero, non-empty values o any
s
type will give True and rest (zero, empty va
will give False.

Converted to

10. If a number (in string form) is given in any other base e.g., octal or hexadecimal or binary, it can alsoDeivalent
equiva
integers using int() as int (<number-in-string-form>, base). For example, to convert a string "0011 (octal Dase
of) into integer, you can write int(0010', 8) and it will give 8. respectively

If you want to convert an integer to octal or hexadecimal or binary form then oct(), hex( ) or bin( ) funco isplayed
are there but they produce the equivalent number in string formi.e., hex(10) will give you 'ox A'. This value ca with
int

), abin(
ct( ),
or printed but cannot be used in calculations as it is not number. However, by combining hex( )., oct(
)
(<number string>, base) you can convert to appropriate type.
8: DATA HANDLING

Choprer
241
Type C a s t i n g I s s u e s

a value to a
type with a
greater range (e.g., from short to long) poses no
ASS
however,
assigning value of larger data
a
type to a smaller data type (e.g, from problem
teger)
may result in losing some precision. floating-point to
ing-point type
Floating-point
to integer type conversion results in loss of
fractional Original value
may
out of range for target type, in which case result is undefined. part.
PLE 22 Which of the following expressions wvill yield a Boolean type value its
(i) 2 != 4
as
output ?
) 10>2
ii) (2+5, 6+6) (iv) 5>2 and not (10> 11)
(vi) 4== 2**2
()2 4,13, 4 (vii) 4, 2**2 (vii) 'cat' < 'dog'
(ix)'Cat' 'dog (x) 5>2 and 10 > 11
(xi) 5 > 2 or 10> 11
cOlUTION Expressions (1), (11), t0), (o1), (i) to (xi) will yield a Boolean result.

PVAMPLE 23 Write Boolean expressions in Python for these conditions:


()xis a factor of y (that is, x divides evenly into
(i) age is at least 18 and state equals "Goa
(ii) the string name is not 'Nimra'
SOLUTION
i) x % y =0
(i)age>= 18 and state ="Goa'
(i) name ='Nimra'

8.6 INTRODUCTION TO PYTHON STANDARD LIBRARY MODULES


Other than built-in functions, standard library also provides some modules having functionality
tor 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
nodule functions, variables, constants and other objects irn your program file.
Et
us learn to use some such modules. In the following lines we shall talk about how to use
ndom and statics
modules of standard
Python's library.
.OWorking with math Module of Python
matan the built-in functions, Python makes available many more functions through
d i s i n its standard library. Python's standard library is a collection of many modules for
funest functionalities, eg, module time offers time related functions; module string offers
functions for string manipulation and so on.
with standard library provides a module namely math for math related functions that work
ith
all number types except for complex numbers.
Rivintwork with functions of math module, you need to first import it to your program by
giving statement as follows as the top line ofyour Python script:
import math
hen you can math library's functions math.<function-name>. Conventionally (not a
tical requireuse
Syntachicd as
uirement), you should give import statements at the top of the program code.
COMPUTER SCIENCE WITH PyT
242 PYTHON
useful math functions
that you can u s e
use in
i

Following table (Table


8.11) lists s o m e your programs
Mathematical
Functions in math Module
able 8.11 Some

5. Function
Prototype Description Example
(General Form)
No.
math.ceil(num)
The ceil) function returns the
math.ceil(1.03) gives 2.0
1. ceil smallest integer not less than num.
math.ceil(-103) gives -10
The sqrt() function returns the math.sqrt(81.0) gives 9.0,
math.sqrt (num)
2. sqrt square root of num. If num <0,
domain error occurs.

3. exp math.expfarg)
The exp() function returns the math.exp(2.0) gives the value
natural logarithm e raised to the of e.
arg power.
. fabs math.fabs (num) The fabs() function returns the math.fabs (1.0) gives 1.0
absolute value of num. math.fabs(-10) gives 1.0.
floor math.floor (num) The floor() function returns the math.floor(1.03) gives 1.0
5.
largestinteger not greater than math.floor(-103) gives -2.0.
num.

6. l0g math.log (num, [base] ) The log() function returns the math.log (1.0) gives the natural
natural logarithm for num. A| logarithm for 1.0.
domain error occurs if nun is
math.log(1024, 2) will give
negative and a range error OCculrs| logarithm of 1024 to the base 2.
if the argument num is zero.

7. log10 math.log10 (num) The log10() function returns | math.log10(1.0) gives base 10
the base 10 logarithm for num. logarithm for 1.0.
A domain error ocurs if numn is
negative and a range error
occurs if the argument is zero.

8. pow mathpow (base, exp) The pow( Ofunction returns base math.pow (3.0, 0) gives value ot
raised to exp power i.e,. base exp.
30
A domairn error occurs if base = 0| math.pow (4.0, 2.0) gives value
and exp <=0; also if base <0 and
of 44.
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 a 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 a 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 a number)
must be in radians.
12. degrees math.degrees() The degrees() converts
angle x math.degrees (3.14) would gve
from radians to
degrees. 179.91
13. radians
math.radians(x) The radians() converts angle x | math.radians (179.71)
would

from degrees to radians.


give 3.14
8: DATA HANDLING

Chopter& :D A T A

243
d u l e of Python also makes available two useful constants
The
use as.
namely pi and e, which
can
you
oives the mathematical constant t =3.141592..., to available
math.pi
precision.
math.e
gives the mathematical constant e =2.718281..., to available
precision.
ouarine are
Follo examples of valid arithmetic
expressions (after import math statement):
b=4, c=5, P=70, 9 =93, r=10.51,
Given x
=25.519, y =10-24.113, z =231.05
() math.pow(a / b, 3.5) (i) math.sin(p/9) math.cos(a 9
+

(iüt) x/y + math.floor(p*a /b) (io) (math.sqrt (b)*a) - c


(v) (math.ceil (p) +a) * c
Followingare examples of invalid arithmetic expressions:
two
() X+* operators in continuation.
(i) q(a+b-z/4) operator missing between q and a.
(it) math.pow(0, -1) Domain error because if base =0 then
exp should not be <=0.
(iv) math.log(-3)+ p/q Domain error because
logarithm
of a negative number is not possible.
EXAMPLE 24 Write the corresponding Python expressions for the following mathematical
expressions
)Wa +b+ (i) 2-ye +4y (i) p+
(iv) (cos x/ tan x)+tx
SOLUTION (-
() math.sqrt (a*a +b*b+c*
(ii) 2-y* math.exp(2*y) + 4*y
tii) p+q/math.pow(r+ s), 4)
(iv) (math.cos(x)/ math.tan (x) ) +x
(o) math.fabs (math.exp(2) -x)

CAAMPLE25 The radius of a sphere is 7.5 metres. Write Python script to calculate its area
sphere=ar Volume ofa sphere =4rr°) and volume. (Area
of
SOLUTION
import math
r 7.5

area
math.pi r *r *

volume =4
math.pi* math.pow(r, 3)
print("Radiusof the sphere: ", r, "metres")
print("Area of the sphere: ", area, "units
PPunt("Volume of the sphere: square")
", volume, "units cube"
Output
Kadius of
Area of the sphere 7.5 metres
the
Volume of thesphere 176.71458676442586 units square
sphere
5301.437602932776 units cube
244 OMPUTER:
SCIENCE WITH
8.6.2 Using random Module PYTHON
Python has a module namely random that provides random-number11 11 gener
number in simple words means a
number generated
by chance, i.e., randomlv, generators. A
random
To use random number
generators in your Python program, you first need to ims
random using any import command, eg,
nodule
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 [oa 1a
i.e., 0.0 N< 1.0. Notice that the number generated with L.0),
always be less than 1.0. (only lower random will
is range-limit inclusive).
Remember, it generates a floating point number.
randint(a, b) it returns a random integer N in the range (a, b), ie., a s Nsb
(both range-limits are inclusive). Remember, it
generates an
integer.
randrange it returns random numbers from
range start...stop with step value.
(<start>, <stop>, <step>)
Let consider
us some examples. In the following lines we are
giving some
sample codes along
with their output.
1. To generate random
a
floating-point number between 0.0 to 1.0, simply use random():
import random
>> print(random. random())
The output generated is between range [0.0, 1.0)
0.022353193431
2. To generate a random floating-point number between range lower to upper using random():
(a) multiply random() with difference of upper limit with lower limit, i.e., (upper -lower)
(b) add to it lower limit
For example, to generate between 15 to 35, you may write
import random # need not re-write this command, if random
# module already imported
print (random.random()* (35 -15) +15)
28.3071872734 The output generated is floating point number behveen range 15 to 35

3. To random
gernerate a
integer number in range 15 to 35 using randintl), write
> print(random.randint (15, 35))
16 The output generated is integer between range 15 to 35

Using randrange() function


The function randrange() can be used in following three ways: nge 0 to

(1) random.randrange(<stopvalue>) to generate a random number in tne


45
Stopvalue>, eg, following code will generate a random number from o
>> random. randrange (45)
13 A random number generated in the range 0..45
and hence
and
11. In fact, pseudo-random numbers are generated because it is generated via some algorithm
algorithm Or
or pprocedure

deterministic somewhere.
DATA H A N D L I N G

Chopler& :L 245
am
randrange(<starb, <stop>) to generate a random number in
the range <start> to
(Gi) ra e..,following code will generate a random number in the range 11 to 45
random.randrange (11, 455)
25 A random number generated in the range 11..45

randadom.randrange(<start, <stop>, <step>) to


generate a random number in the range
(1 arf to <stop>, but here, the difference
between two such generated random numbers
1l he a multiple of <step> value. For example, following code will generate a random
number in the range tl to 45, with a step value 4. That means, the possible random
numbers that may be generated will 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)
See each generated random number is
35 one of the above given values
random.randrange(11, 45, 4)
39

So, internally, randarange with a <step> value creates a series from <start> to <stop> with each
value at <step> values apart and randomly picks one from this.

EXAMPLE 26 What could be the minimumn possible: Output can be somewhat like
ad maximum possible numbers by following code ? 77.41547442568118
0.03735925715458066
import random
print(random.randint (3, 10) - 3) Every time the code is run, a different output
will be printed as different random numbers
SOLUTION. minimum possible number = 0
will be generated.
maximum possible number =7
EXAMPLE 28 Write a code fragment to generatea
Because,
random floating number between 45.0 and 95.0. Print
random :
Y
Iandint(3, 10) would generate a
than it.
integer in the range 3 to 10 this number along with its nearest integer greater
SOLUTION
9Subtracting 3 from it would change the range import random
to0to 7 (because if randint(3,10) generates 10 import math
then-3would make it 7; similarly, for lowest *
45)+45
generated value 3, it will make it 0) fnum =random.random() (95
inum = math.ceil( fnum )

AMPLE 27 What will the following code print("Random numbers between 45..95:")
oduce ?
Discuss. print(fnum)

print("Nearest higher integer:", inum


import random
print(random. random() * 100) Output:
print (random.random()) Random numbers
between 45..95

SOLUTION 48.24212504903489

higher integer:
49
he Nearest
code will firstly print a random;
number gen Eenerated in the range 0.0 to 100.0. EXAMPLE 2 9 Write a codefragment to generate two

And the next line, between 450 and 950. Print


these

umber it will print a randonrandom integers


8enerated in the range 0.0 to 1.0. numbers along with theiraverage.
246 cOMPUTER SCIENCE WITH
PTHO N -A
SOLUTION SOLUTION
import random import random
num1
num1
num2
random.randint(450, 950)
random.randint ( 4 5 e , 950) - 450
450
num2
random.randrange
random.
(10, 70, 131
randrange (10, 70, 131
avg (num1+ num2)/2 num3 random. randrange
(10, 70, 131
print("Random integers in the\ set1 {num1, num2, num3}
range 450 to 950:", num1, num2) ("Random integers in the
print("
print("Theiraverage:", avg)
range 10..70,
step-value 13 ", num1, num2, nuna
print("Set created:", set1)
Output:
Random integers in the range 450 to 950: 472 145
Their average: 308.5
Output:
Random integers in the range 10..70,
step-value 13 10 10 62
EXAMPLE 30 Write a code fragment to generate set created : {10, 62}
three random integers in the range 10, 70 with a step of
13. Create a set with these numbers.

8.6.3 Using the statistics Module


The statistics module of the Python Standard Library provides many statistics functions suchas
mean( ), median( ), mode() etc. In order to use these in your program, you need to first
Python statistics module by giving one of the following statements
import the
import statistics
Or Import full statistics module
from statistics import mean, median, mode

Import only three functions from


You can then these functions
use as
given below statistics module
(i) statistics.mean(<seqp) it returns the
average value of the set/sequence of values passe.
(ii) statistics.median(<seq>) it return the middle value of the set/sequence of values passsed.
(iin) statistics.mode (<seqp) it of
returns the most often repeated value of the set/sequence
values passed.
Consider following 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 See, mean, median and mode of above sequence
calculated using statistics module
>>» statistics .mode (seq)
5

Code t o VCulate

EXAMPLE 31 Given a list containing these values


[22, 13, 28, 13, 22, 25, 7, 13, 251. Write
mean, median and mode of this lis.
DATA
HANDLING

247
ter 8:
SOLUTION
s t a t i s t i c s
as stat
:EXAMPLE 32 Have a look at the below given Heron's
:formula to calculate the area of a triangle through its three
import
22, 13,
3 28,13, 22, 25, 7, 13, 23] :
list1= [
=
stat.mean (list1)
sides a, b, and c.
list_mean a+b+C
median stat.median (1ist1) ;Area =s(s-a)(s-b)(s-)
= S=
list_m 2
1ist_mode = s t a t . m o d e ( l i s t 1 )
: Which Python module would you need to import to calculate
print("Given
list : ", list1))
: aren using this formula? Can you use statistics module's
orint ("Mean: ", list_mean) mean() for calculating s in above given formula?
1list_median)
print("Median: ", SOLUTION
print("Mode:", list_mode)
Python's math module should be imported in
Output: order to calculate the square root using sqrt().
Given1ist : [22, 13, 28, 13, 22, 25, 7, 13, 25]
Mean: 18.666666666666668 No, we cannot use mean() function of
Median: 22 statistics module because s is not the mean of
MOde: 13 a, b and c; it is the half of the sides' sum.

8.7 DEBUGGING

in simple English means to remove 'bugs' from a


DEBUGGING
Debugging Debugging refers to the process
program. An error causing disruption in program's running or in of locating the place of error,
producing right output, is a 'program bug'. Debugging involves cause of error, and correcting
rectifying the code so that the reason behind the bug gets the code accordingly.
resolved and thus bug is also removed.
In this section, we shall talk about general debugging techniques and how you can debug code in
Python.
Before we talk about debugging techniques, it is important for you to know the errors, error
types, what causes them etc. So, let us first talk about errors and exceptions.

8.7.1 Errors in a
Program
An error, sometimes called 'a bug', is anything in the code that prevents a program from
catastrophic in their effects, while
compiling and running correctly. Some program bugs are unclear
are comparatively less harmful and still others are so that you will ever dise er
TS
L h e r e are broadly three types of errors:Compile-time errors, run-time errors and logical errors.

8.7.1A Compile-Time Errors


its
t h a t occur during compile-time, are compile-time errors. When a program compiles,
rules or not.
follows the programming language's
rce code is checked for whether it
Twa
y p e s of errors fall into category of compile-time
errors.

. Syntax Erors
are misused i.e., when a
errors when rules of a
occur programming language
two statements:
matical rule of Pvthon is violated. Forexample, observe the following
X<- Y*Z
ifX=(X *Y)
is not an assignment operator in Python
etwo statements will result in svntax errors as '- Also, if is a block statemernt, it
operator, not a relational operator.
tequin ne assignment above.
colon which is missing
the end ofit,
a
(: ) at
248 COMPUTER SCIENCE WITH
wITH PYTHON -
PYTH
will be as follows
Therefore, the correct statements
X = Y *Z SYNTAX
i f X == (X * Y ) : Syntax refers to formal
the first time, as governing the constructionride
rules
One should always try to get the syntax right well
valid statements in a
a syntax error wastes computing time and money, as as
language
programmer's time and it is preventable.

2. Semantics Errors
Semantics Errors occur when statements are not meaningful. For instance, the statement
plays Guitar is syntactically and semantically correct as it has some meaning but the statemSita
ement
Guitar plays Sita' is syntactically correct (as the grammar is correct) but semantically incoro
Similarly, there are semantics rules of a programming language, violation of which result
ults in
semantical errors. For instance, the statement
X*Y Z
SEMANTICS
Semantics refers to the set of
will result in a semantical error as an expression cannot come rules which give the
meaning of
on the left side of an assignment statement. a statement.

8.7.1B Logical Errors


Sometimes, even if you don't encounter any error during compile-time and run-time, your
program does not provide the correct result. This is because of the programmer's nistaken
analysis of the problem he or she is trying to solve. Such errors are logical errors. 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 the hardest to prevent and to locate. These
must be handled carefully. Sometimes logical errors are treated as a subcategory of run-time errors.

8.7.1C Run-Time Errors


Errors that occur during the execution of a program are run-time errors. These are harder to
detect errors. Some run-time errors stop the execution of the program which is then called
program "crashed'" or "abnormally terminated'".
Most run-time
easy to identify because program halts when it encounters them eg»
errors are
an infinite
loop or wrong value (of different data type other than required) is input.
Normally, programming languages incorporate checks for run-time errors, so does thon.

However, Python usually takes care of such errors ry


that crashes whenever it detects by terminating the program, but a
pT
am

an error condition is 8ram


not desirable. Therefore, a
should be robust so as to recover and PTO
continue following an error.
Exceptions
Errors and
exceptions are similar but different terms. While
any DuBg
in the
running of the program or causes improper output,represents,
error
code that
disrupts an Exception
to any
irregular situation occurring during execution/run-time, which you have no rei Errors

in a program can be fixed


by making corrections in the code, fixing contro nle
Let us try to understand the exceptions is
notu
difference between an error and
example. For instance, if you operate an ATM then exception with the heip o
entering wrong account number or wrong
not that much
pin
number is an ERROR.
amount in account' is an EXCEPTION.
ATM machine struck' is also an
EXCEPTION
C h a p r e r
8 DATA HANDLING
249
So you
can thin.
can
think of Exceptions in a program as a situation that NOTE
ccurs during runtime nd you have no control on it e.g., you
oCcu
While Error is a bug in the code
code that opens a data file and displays its contents on that causes irregular output or
write a
screen. This program's code is syntactically correct and logically stops a program from executing
when you rurn this program, the file that you are an Exception is an irregular
correct too. But
does not exist on disk his will cause an EXCEPTION. unexpected situation occurring
onening, -

during execution on which


has no errors but an exception occurred.
So the program programmer has no control.
Some Built-in Exceptions
Table 8.12
Exception Name Description
Raised when one of the built-in functions (input( )) hits an end-of-file condition (EOF)
EOFError
without reading any data.
Raised when an I/O operation (such as a print(), the built-in open( ) function or a
OError method of a file object) fails for an I/O-related reason, e.g., "filenotfound" or "disk full".

Nametrror
Raised when an identifier name is not found.
IndexError Raised when a sequence subscript or index is out of range, e.g., from a string of length 4 if
you try to read a value of index like 4 or more i.e., string[4], string[5], stringl-5] etc. will
raiseexception aslegalindexes for astring oflength 4 are 0, 1,2, 3and -1,-2,-3, 4 only,
Raised when an import statement fails to find the module definition or when a from ...
ImportError
import fails to find a name that is to be imported.
Raised when an operation or function is applied to an object of inappropriate type, eg
TypeError
value.
if you try to compute a square-root of a string
Raised when a built-in operation or function receives an argument with an
VaiueError
ValueError.
inappropriate value e.g., int("z10") willraise
ZeroDivisionError Raised when the second argument of a division or modulo operation is zero.

Raised when the result of an arithmetic operation is too large to be represented.


OverflowError
Raised when a mapping (dictionary) key is not found in the set of existing keys.
KeyError
ror example, following screenshots are showing two different exceptions.

»100/ 0 * int ('11ab') ****


aceback (most reçent call last) Traceback (most recent call last): <module>
ile "<pyshelli30>", line 1, in Pile "<pyshellt431>", line 1, in
<module
int(11gb
for int () with base 10:11ab|
eroDivisiionError division by zero ValueError invalid literal

2 Code Tracing
Debugging using This
to debug an error is to find the point of error and origin of error.
MOst common technique and of all values. For this
intermediate result
often done by printing the values of every
most commonly used technique.
Purpose, code tracing is one

is code tracing. Code tracing executing code


means
Ommon useful technique for debugging
on variables. One way of code tracing is using Dry
One line at a watching its impact
time and also be done by
learnt in an earlier chapter.
Code tracing can

n, which you have already in software form.


ebugging tools or debugg available
250 COMPUTER SCIENCE WITH pYT
HON.
LET Us REVISE
*An expression is composed ofone or more operations. It is a valid combination
ation of
of operators, literale
In Python terms, an expression is a legal combination of atoms and operators.
operators, literals and varick
les.
An atom in Python is something that has value. Examples of atoms are variables,
sets etc.
a
literals, strinas
*Expressions can be arithmetic, relational or logical, compoundetc.
tuples,
Types of operators used in an expression determine its type. For instance, use
of arithmetic
metic operate
operators makes
arithmetic expression.
Arithmetic expressions can either be integer expressions real
or expressions or
complex number.
mixed-mode expressions. number operations or
An arithmetic
expression always results in a number (integer or floating-point number or a
relational expression always results in a Boolean value i.e., either True or Faise compley m
into a number or a string or a Boolean
; and a logical
expression roe
number);
value, depending upon its operands.
I n a mixed-mode
expression, different types of variables/constants are converted to one same
called type conversion. type. This proes
process is
Type conversion can
take place in two forms: implicit (that is performed by compiler
intervention) and explicit (that is defined by the user). without programnerk
I n implicit conversion, all
operands are converted up to the type of the largest operand, which is
promotion or coercion. called tye
The explicit conversion
of an operand to a specific type is called type casting and it is done
functions that is used as using type conversion
<type conversion function> ( <expression>)
e.g., to convert to float, one may write

float (<expression>)
Debugging refers to the process of locating the place of error, cause
of error, and correcting the code accordingly.
Compile-time errors (syntax error and semantics errors)
regulations of a programming language. refer to the errors that violate the
grammatical rules and
Runtime errors occur
during the execution of a program.
Logical errors occur due to mistaken analysis
of problem.
Irregular unexpected situations occurring during theruntime are called
Exceptions may occur even if the program is free Exceptions.
all from types of errors.
bjective Type Questions
Multiple Choice Questions OTQs
1. Which of the
following are valid Python data 3. C o n s i d e r t h e f o l l o w i n g sequence of state
ements:
types?
(a) Numeric (b) None a = 35
() Mappings
(d) list m = a
(e)Sequence () set
g) tuple (h) dictionary Following the execution of these staten
objects and
2. Which of the following are datatypes considered Pyt
ython has created how many
how many references?
as Numbers in Python.
() Two integer objects, two references
(a) Integer (b) Boolean (6) One integer object, two references
) complex (d) floating point
(e) list (C) One integer object, one reference
) None (a) Two integer objects, one referenee
8 : 0DATA HANDLINO
C h o p t e r

251
Dython built-in function returns the 15. What
4 .Whic

number assigned to an object?


will the following code produce?
unique a 8.6
(0)identity() (b). id() b = 2
() refnum( ) (d) ref( )
print ( a//b )
5. The
operator
used <if both the operands
to check
(a) 4.3 (b) 4.0
Treference the same Object memory, is the (c)4 (d) compilation error
operator.
16. In the Python statement
(a) i (b) is (c) id (d)= x =a+5-b: a and b are

A For two objects x and y, the expression x is y


(a) Operands (b) Expression
will True, if and only if
yield
(a) id(x)= id(y) (b) len(x) = len(y)
()operators (d) Equation
17. In the
(d) all of these Python statement x =a+5-b: a+5-bis
(c)xy
7.Which of the following is not an immutable
(a) Operands (b) Expression
type in Python ? (c) operators (d) Equation
() String () Tuples () Set () dictionary 18. What will be the value of after
y following code
8. Python operator always yields the result of fragment is executed?
datatype. X = 10.0

() integer (b) floating point y= (x< 100.0) andx >= 10


()complex (d) all of these (a) 110 (b) True
What is the value of the expression 100/ 25 ? (c) False (d) Error.
(a) 4 (b) 4.0 19. Which of the
(c) 2.5
following literals has True
(d) none of these truth-value?
10. What is the value of the
expression 100 // 25?: (a) 0.000001 (b) None (c)0
(a) 4
C) 2.5
(b) 4.0
(d) none of these
(d)[1
(g) 1
(e) False
(h) 33
True
(i) None () 0.0
I n Python, a variable must be declared before it 20. What will the following code result as ?
is assigned a value. import math
(a) True b) False X = 100

() Only in Functions (d) Only in modules print (x> 0 and math. sqrt( x))
12.
In Python, a variable is assigned
a value of one (a) True (6) 1
type, and then later assigned a value of a (c) 10 (d) 10.0
different type. This will yield
21. Which of the following operators has the lowest
(a) Warning (b) Error precedence ?
(c) None (d) No Error
(a) not (b) %
In Python, a variable may be assigned a value (C) and (d) + (e) **

r one type, and then later assigned a value or a 22. What is the value of the expression 10 +3** 3 *2?
afferent type. This concept is known
asS (a) 28 (b) 739
(c) mutability (b) static typing
C) dynamic (c) 829 (d) 64
14. Is it typing(d) immutability
tsafe
23. To increase the value of x five times using an
o directly use the == operator to deter-
augmented assignment operator, the correct
Whether objects of type float are equal ? expression will be
() Yes (6) No
e) Yes, if the values are <100 (a)x tF5 (b) x *=5
(c)x = x ** 5
(d) none of these
a) Yes, if the values are
>10
252 COMPUTER SCIENCE WITH
PYTHON
ON -
24. What will be the result of the expression 10 or 0D? 2. Two forms of floating-point
form and numbers are
(a) 0 (b) 1 (c) 10 (d) 1.0 notation.
25. What will be the result of the expression 5 or 10? 3. Python's floating point numbers have Dres
5 1 (c) 10 (d) 0
of digits. recision
(a) (b)
4. Three mutable types of Python
26. What will be the result of the expression 5 are
and
and 10 ?
5. The floor division of tw0 integers yields a resd
(a) 5 (b) 1 (c) 10 (d) 0
of type.
27. What will be the result of the expression 15
6. The division ot two integers yields
and 10? a
result of

(a) 5 (b) 1 (c) 10 (d) 0


type
7. The sequence type cannot store
28. What will be the result of the expression 10 or 0? duplicate values.
(a)0 (b)1 (c) 10 (d) 1.0
8. The datatype is like lists but is not
"
29. What will be the result of the expression 'a' or mutable.
(" is an empty string) ?
9. The of an object gives the
(a) a (6)" memory
)1 0 location of the object.
30. What will be the result of the expression 'a' and "; 10. To check if two objects reference the same
("is an empty string) ? memory address, operator is used.
"

(a) 'a' (b) )1 () 0 11. To use function fabs( ), module should


31. What will be the result of the expression 'x be imprted.
and 'a' ?
12. To generate a random floating number in the
'a (b) (c) 'x (d) 1
range 0 to 100, function is used.
32. What will be the result of the expression 'a': 13. To generate a random integer in a rangs
and 'x' ?
function is used.
(a) 'a (b) (c) x (d) 1 14. To generate a random number in a sequence or
a
33. What will be the result of the expression 'a' values where two values have a difference
and 'None' ? step value, function is used.

(a) a (b) module is to be


15. To use mean( ) function,
(c) 'None (d) 1 imported.
34. What will be the result of the expression 'None'
and 'a' ? True/False Questions
(a) 'a' b) 1. List is an immutable data type.
()"None' (d) 1
2. Set is a mutable data type.
35. What will be the result of the
expression 'false' 3. A set can contain duplicate values in l

and False? treated


as an

(a) false (6) False


4. A Boolean value is internally
() false' (d) 'False
integer value.
36. What will be the result of the False.
expression 'false' value as
or False ? . ( a n empty string) has truth

(a) false (b) False (c) false' (d) 'False' . ( a space) has truth value as False
Python.
literal alue in
7. Value false is a legal
Fill in the Blanks In
Python.
8. Value False is a legal literal value
in Pytho
1. Boolean data type is internally treated as
9. Value 'False' is a legal litera
data type.
8 : DATA HANDLIN

Chapter
253
false is a legal literal value in Python.
1 0 .V a l u e

'None are the same.


11. None a n d and
h a s the
truth
truth value as False.
None
12.
13. None' has the truth value as False.

result of bool(0)
is False.
14. The
result of bool('None') is False.
The
15.
two integers results in an integer.
16 Dividing
17 Floor division of two integers results in an integer.

0Twofloating pont numbers should not be compared for equality using =.


19.implicit conversion, all operands data types are converted to the datatype of the largest operand.
n0 Explicit type conversion nvolves the use of a function to convert datatype of a value.

NOTE: Answers for 0TQs are given at the end of the book.

Selved Prohlems

1 What are data types ? What are


Python's built-in
types? core data
olution. The real life data is of many types. So to represent various
types of real-life data,
programming languages provide ways and facilities to handle these, which are known as data types.
Python's built-in core data types belong to:
Numbers (integer, floating-point, complex numbers, Booleans)
String List
Tuple Dictionary
2. Which data types of Python handle Numbers?
Solution. Python provides
following data types to handle numbers
Integers (i) Boolean
(n) Floating-point numbers (io) Complex numbers
3.
Why is Boolean considered
subtype of integers
a

ution. Boolean values True and False internally map to integers 1 and 0. That is, internally True is
e r e d equal to 1 and False equal to 0 (zero). When 1 and 0 are converted to Boolean through
Ofunction, they return True and False. Thatiswhy Booleans are treated as a subtype of integers.
ldentify the data types of the values given below :
3, 3, 13.0, 13', "13", 2 +0j, 13, [3, 13, 21, (3, 13, 2)
Solution.
3 3j complex number
integer
13.0 Floating-point number 13' string
"13 String +0j complex number
13 [3, 13, 2] List
integer
3, 13, 2) Tuple
254 cOMPUTER SCIENCE WITH
PYTHONON
5. What do you understand by term immutable' ?
Solution. Immutable means unchangeable. In Python, immutable types are those whoo.
cannot be changed in place. Whenever one assigns a new value to a variable referring to iValue
type, variable's reference is changed and the previous value is left unchanged. e.
X = 3

X =

3 value 3 is untouched and x is made


to refer to new value.

6. What will be the output of the following ?


print (len (str (17//4)) )
print (len(str(17/4))
Solution. 1

because and

len(str(17//4)) len(str(17/4))
len(str(4)) = len(str(4.0))

len (4) len('4.@)


=
3

7. What will be the output produced by these ?

(a) 12/4 (b) 14//14 (c) 14%4 (d) 14.0/4 ()14.0//4 14.0%4
Solution. (a) 3.0 (6) 1 (c) 2 (d) 3.5 ()3.0 () 2.0
8. Given that variable CK is bound to
string "Raman" (i.e., CK =
"Raman"). What will be the output produced
byfollowing two statements the
if input given in "Raman" ? Why?
DK input("Enter name:")
Enter name Raman
(a) DK == CK
(6) DK is CK
Solution. The output produced will be as (a) True (b) False
The reason being
that both DK and CK variable are out
bound to identical strings 'Raman'. but
strings are always bound to fresh memory even if they have value
string in memory. identical to some other ex
Thus DK CK
==

produces True as strings are identical.


But DK is CK
produces False as they are bound to different memory addresses.
9. What will be the output of
following code ? Explain reason behind output of every line
5 5 or 10
5 10 or 5
5
(10 or 5)
5 (5 or 10)
Solution. 10
True
True
False
8 : DATA HA
HANDLING

8:
Chopter
DATA

255
Explanation

5<5 or 10
Line 1 precedence of < is higher than or
= False or 10

10
because or would evaluate the second if first
argument
argument is False or
falsetwa
Line 2 5 10 or 5
precedence of < is higher than or
= True or 5

True or would return first if it is True


argument or trueoal
Line 3 5 (10 or 5)
= 5 10 10 or 5 returns 10 since 10 is
= True
truetual

Line 4 5 (5 or 10)
=5<5 5 or 10 returns 5 since 5 is
trueval
= False

10. What wil be the output produced by the three expressions of the following code ?
a =5
b=-3
C 25
d=-10
a + b+ Cc a+ c b * d

s t r ( a+ b + c > a +C b * d) == 'true'

len(str(a + b+ c> a + c - b * d)) == l e n (str (bool(1)))

Solution. True
False
True

What would Python produce iffor the following code, the input given is
) 11 (ii) hello iii) just return key pressed, no input given (io) 0 (o) 5-5
Code

bool(input("Input:")) and 10 < 13 2


Solution.
) Input 11 would
:
yield bool ( ' e ' ) and 18 < 11
(iv)
bool (11') and 10 < 11
True and True
True and 10 < 11 = True
= True

i) True For the same reason as in (1)| (Please note 0° is a non-empty


string and hence has truth value
U) False because when just return key 1s
as true tval)
pressed, input is " i.e., empty string, hence

expression becomes (v) bool ('5-5) and 10 < 11


bool( ) and 10 < 11 = True and 10 < 11
False and True = True
= False
COMPUTER SCIENCE WITH
NITH PYTHON-
256
code ? Explain reason(s).
12. What would be the output of the following
a 3+5/8
b int(3 + 5/8)
C 3+ float (5/8)
d 3+float (5)/8
e 3+ 5.0/8
f int(3+ 5/8.0)
print (a, b, c, d, e, f)
Solution. The output would be
3.625 3.625 3.625 3
3.625 3

Explanation
Line 1 a = 3 + 5/8
= 3 +0.625

a = 3.625

Line 2 b int (3+ 5/8)


fractional part)
i n t (3 + 0.625) (int( ) will drop the
= int (3.625)

b= 3

Line 3 C 3+ float (5/8)


C=3 + float(0.625)

= 3+0.625
C = 3.625

Line 4 d = 3+ float(5)/8
= 3 + 5.0/8 5.0/8 0.625 because one operand is floating point, the
converted to floatingpt
= 3 +0.625 integer operand will be internally
d = 3.625

Line 5 e = 3+ 5.0/8

= 3 +0.625 (same reason as above)


e = 3.6255

Line 6 f int(3 5/8.0) (same reason as above)


f =int (3 +0.625)
f= int (3.0) (int() will drop the fractional part)
f =3
13. What will be the output produced by following code statements ?
(a) 87//5 (b) 87 // 5.0
c)(87 //5.0)=(87 //5) d) (87 //5.0)== int (87 / 5.0)
(e) (87 // int (5.0))= (87 I/ 5.0)
Solution. (a) 17 (b) 17.0 (c) True (d) True (e) True

14. What will be the output produced by following code statements ? State reasons(s).
(a) 17 %5 (b) 17 % 5.0
(c) (17 % 5) ==(17 % 5) (d) (17 % 5) is (17 % 5)
(e) (17 % 5.0) == (17 % 5.0)
( (17 % 5.0) is (17 % 5.0)
DAlA
HANDLING
257
hop/er
8:

Solution. (a) 2 ) 2.0 (c) True (d) True (e) True () False
and
and (e) evalu.
(e) evaluate to True because both the operands of == operator are same values (2-=2 in
Both (c)
and 2.0
==
2.0 in (e).
c)
evaluates
True
to T as both the operands of is operator are same integer objects (2).
(d)
Since both operand expressions evaluate to same integer value 2 and 2 is a small integer value, both

are hound to same memory address, hence is operator returns True.


In (. even though both operands evaluate to same floating point value 2.0, the is operator returns
False because Python assigns different memory address to floating point values even if their exists a
same value in the memory.

15. In Python, you can write -5 in following ways. 5*2 and math.pow-5, 2) and 5 *-5
But you execute these, the results vary, i.., 5*2 gives result as -25

But both math.pow(--5, 2) and -5 *-5 gives result as +25.

Why do results vary for these expressions? What changes will you incorporate to get the same result in all
these expressions ?
Solution. The result of 5**2 is -25 because:
E x p o n e n t i a l o p e r a t o r ** h a s h i g h e r p r e c e d e n c e t h a t u n a r y - operator and it (exponentiation operator

**) has right to left a s s o c i a t i v i t y , i.e., the right side operator ** attaches w i t h value 5 before u n a r y

operator
Hence itis internally interpreted as: - ( 5**2)

Andhence we get the result as: -25.


In other two expressions there is only single operator with value 5, hence no need of using
associativity and thus the result as +25.
We can changes the first expression as (-5)**2 to get the correct result.
lb. What will be the output produced by the following code statements ? State reasons.

() bool(0) (b) bool (1) c) bool(0) (d) bool("1') (e)bool( ")


bool(0.0) (g) bool('0.0) () bool(0)) () bool(o)
Solution.
4 ralse. Integer value 0 has false truth value hence bool() converts it to False.
6) True. Integer value 1 has true truth value hence bool( ) converts it to True.
)True. '0 is string value, which is a non-empty string and has a true truth value, hence bool()
converts it to True.
)True. Same reason as above.
ralse. i s an empty string, thus has false truth value, hence bool() converts it to False.

09 False. 00 is zero floating point number and has false truth value, hence bool() converts it to False.
)True. 0,0 is a non-empty string henceithas true truth value and thus bool() converted it to True.
()False. 0)is zero complex number and has false truth value and thus bool() converted it to False.
1rue. '0 is non-empty string, hence it has true truth value and thus boo( ) converted it to True.

b e the output produced by these code statement ?


()bool(int(0') (6) bool(str(0)) c) bool(float('0.0')) (d) boolstr(0.0))
Dolution. (a) False (b) True
(c) False (d) 1rue
COMPUTER SCIENCE WITH PYTH

258
code ? Why?
18. What will be the output of following or 113
len(13)
len(13)
(ii)
() 13 or

Solution. 13s truth value, which is f


evaluates first argument
) 13 because or
13 without evaluating second argument
hence returns
the result as

evaluates fist argument len(13), Python gives ers or as


error because when or

len() works on strings only.


times. What could be
the possible set ofoutud. Dut of
which is repeated four
19. Given the following Python code, combination of digits)?
given four sets (dddd represent any
import random
*
print(15+ random.random() 5)
15.dddd
() 17.dddd, 19.dddd, 20.dddd,
18.dddd
(i) 15.dddd, 17.dddd. 19.dddd,
20.dddd
(ii) 14.dddd, 16.dddd, 18.dddd,
(io) 15.dddd, 15.dddd, 15.dddd, 15.dddd
and (iv) the correct possible outputs because:
Solution. Option (i) are

number N between range 0.0 <= N <1.0.


(a) random( ) generates
becomes 0.0 to < 5
(b) when it is multiplied with 5, the range
(c)when 15 is added to it, the range becomes 15 to 20
<

Only option (i) and (iv) fulfill the condition of range 15 to 20.
<

20. What do you mean by Syntax errors and Semantics errors?


Solution. Syntax errors are the errors that occur when rules of a programming language are violae

Semantics errors occur when statements are not meaningful.

21. Why are logical errors harder to locate ?


Solution. In spite of logical errors' presence, the program executes without any problems but tte
tobe
output produced is not correct. Therefore, each and
every statement of the program needis
scanned and interpreted. Thus the logical errors are harder to locate.
22. What is an Exception ?
Solution. Exception in general refers to some contradictory or unusual situation w
encountered unexpectedly while executing a
program.
23. Write a program to read base/length (), width(w) and
height(h) width (w)
of a parallelogram and calculate its area and perimeter. height (h)
Solution.
base ()
1 float (input ( "Enter base/length of the
W parallelogram:
float (input ("Eter width of the parallelogram: "))
h float (input("Enter height of the parallelogram "))
area 1 * h "))
perimeter 2*1 + 2*w
print("The area of given parallelogram
is: ", area)
print("The perimeter of given parallelogram is :", perimeter)
HANDLING

hopter
8 :DA IA 259
The sample run of the above program is as shown below:

Enter base/length of the parallelogram: 13.5


Enter width of the parallelogram: 7
Enter height of the parallelogram 5
The area of given paral lelogram is : 67.5
The peri meter of given parallelogram is 41.0

aSchool fest, three randonmly chosen students out of 100 students (having roll numbers 1-100) have to
resent bouquets to the guests. Help the school authorities choose three students randomly.
Solution. import random

student1 =random.randint(1, 100)


student2 = random.randint(1, 100)

student3 =random. randint (1, 100)


print("3 chosen students are",)
print (student1, student2, student3)
25 A triangle has three sides a, b, c as 17, 23, 30. Calculate and display its area using Heron's formula as

a+b+C
S Area = /s(s-a)(s-b)(s-c)
2
Solution.
import math
a, b, c 17, 23, 30
S
=(a+ b+c)/2
area
math.sqrt(s *
(s-a) *
(s-b) *
(5-c))
print("Sides of triangle: ", a, b, c)
print("Area: ", area, "units square")
Output:
Sides of triangle: 17 23 30
Area
194.42222095223582 units square

i U1delines to NCERT Questionns NCERT Chapter 5]

lagal expressions corresponding to the following statements in Python and evaluate the expressions
gariables num1, num2, num3, first, midále, last are already having meaningful values):
() The sum of 20 and -10 is less than 12.
() num3 is notmore than 24.
96./5 is between the values of integers num1 and num2.
(d) ne string'middle' is larger than the string 'first' and smaller than the string 'last'.
Ans. (a)
(20+-10) <12 (b) num324 or not (n3 >24)
() num1 =6.75
4. Add a <= num2 (d) 'first' <'middle'< "last'.
parentheses to each expression so that it evaluates to True.
(a =1 == 2 6) 2+3 ==4 +5 == 7
c)1 -1 == 3> 4
COMPUTER SCIENCE WITH PYTHOON
260 -K

Ans. (a) = = (1 == 2)

==7
(6) (2+ (3 -=4) +5)
C)(1-1) == (3 >4)
data values and why ?
Which data will be used to represent the following
6. type Delhi or not
Number of months in a year
(b) Resident of
(a)
(d) Pocket money
(c) Mobile number
( Perimeter of a square
(e)Volume of a sphere
(h) Address of the student
(g) Name of the student
(b) Boolean (c)Integer (d) Integer or Floating point e) Floating point
Ans. (a) Integer
( Floating point (8) String (h) String
num2 =3, num3 = 2
the output of the following when
num1 =
4,
7. Give
(h) num1 = float (10))
num1 += num2 + num3
(a)
**
(num2 + num3) print (num1)
(6) num1 =num1 (i) num1 = int( '3.14')
print(num1)
print(num1")
(c) num1 **= num2 + num3
() print( 'Bye' 'BYE') ==

(d) num1 ='5'+ '5'


print(num1) (k) print(10 != 9 and 20 >= 20)
29/9)
(e) print(4.00/(2.0+2.0)) () print(10 +6 *2** 2 !=9/4-3 and 29 >=
«= 29)
( num1 2+9* (3 12) 8)/10
* -

(m) print(5% 10 + 10 < 50 and 29


print(num1) (n) print((0 < 6) o r (not(10 6) and (10 < 0))) ==

(g) num1 =24//4//2


print(num1)

(b) 1024 (c) 1024 (d) 55 (e) 1.0 () 27.2 g) 3 (h) 10.0
Ans. (a) 9
False () True () False (7) True (n) True
() ValueError (j)
syntax logical error or runtime:
8. Categorise the following as error,

(a) 25/0 (b) num1 = 25; num2 - 0 ; numl/num2

Ans. () Runtime error (exception) (b) runtime error (exception) S i 0 n a l

u
9. A dartboard of radius 10 units and the wall it is hanging on are represented using
coordinate system, with the board's center at coordinate (0, 0). Variables x and y store the x-c0tnlt
y-coordinate of a dart that hits the dartboard. Write a Python expression using variables x an i n
to True if the dart hits (is within) the dartboard, and then evaluate the expressionfor these aure s

() (0, 0) (b) (10, 10) () (6,6) (d) (7, 8)


Ans. Expression to test if the dart hits within the dartboard = (*2+ y)<100
() 0, 0) lies within the dartboard as(0 +0 ) <100 is True.
(b) (10, 10) does not lies within the dartboard as (102 +102)<100 is False.
()(6,6) lies within the dartboard as (6 +62)<100is True.
(4) (7, 8) does not lie within the dartboard as (2 +82) <100 is False. boisat1

10. Write a Python program to convert temperature in degree Celsius to degree Fahrenhet. eezing.
degree C and freezes as 0 degree C, use the program to find out what is the boiling poimr n
water on the Fahrenheit scale. [Hint. T(° F)
=T(° C)x+32))
: DATA HANDLING
261
Chopler

Ans.
bp_C 100 # boiling point in celcius
# freezing point in celcius
fp_C =
degree u'\N{DEGREE SIGN} #it is the literal for degree sign
# Fahrenheit = ( Celsius * 9/5 ) + 32

bp_f (bp_c
*
9/5 ) +32 # bp_f : boiling point in fahrenheit

fp_f ( fp_c
*
9/5 ) +32 #fp_f: freezing poit in fahrenheit
print("Boiling point in", degree+ "C:", bp_c, "and in", degree+"F", bp_f)
print("Freezing point in", degree + "C:", fp_c, "and in", degree+ "F:", fp_f)
Output:
in C100 and in F : 212.0
Boiling point
Freezing point in 'C: 0 and in 'F : 32.0

11. Write a Python program to calculate the amount payable if money has been lent on simple interest.
Principal or money lent = P, Rate of interest = R% per annum and Time = T years.

Then simple interest (SI) = (Px Rx T)/100.

Amount payable = Principal + SI.

P, R and T are given as input to the program.


Ans.
P float( input( "Eter money lent: "))
Rfloat( input("Enter rate of interest: "))
T float( input("Enter time in years: "))
SI=(P* R*T)/100
amount_payable = P+ SI

print("Amount payable is : Rs.", amount _payable)

Sample Run:
Enter money 1ent: 7000
Enter rate of interest: 8.5
Enter time in years: 3.5
Amount payable is : RS. 9082.5
r i t e a program to repeat the string "GOOD MORNING" n time. Here 'n times. Here 'n is an integer
entered by the user.
Ans.
n int( input("How many times ?"))
print ("GOOD MORNING" * n)

Output:
How many times ? 3
GOOD MORNINGGOOD MORNINGGoOD MORNING
262 COMPUTER SCIENCE WITH
20. The formula E =mc states that the equioalent energy (E) can be calculated as the
PYTHON -

the speed of light (c= about 3x 10 m/s) squared. Write a program that accepts the mace int
nass of an
determines its energy.
object ant
Ans.
import math
m float(input( "Enter mass: "))
C 3 * pow (10, 8)

E =m*c *c
print ("Equivalent energy: ", E, "Joule") #unit of energy is Joule

Output:
Enter mass: 8.95
Equivalent energy: 8.055e+17 Joule

21. Presume that a ladder is


put upright against a wall. Let variables length and angle store the length af1.
ladder and the angle that it forms with the ground as it leans against the wall. Write a Python
compute the height reached by the ladder on the wall for the program b
following values or length and
angle:
(a) 16 feet and 75 degrees (b) 20 feet and 0 degrees
(c) 24 feet and 45 degrees (d) 24 feet and 80 degrees
Solution. Since the ladder leaning against the wall will form a
right-angled triangle, the height up to which a ladder reaches can be
calculated as
h=lsin
Thus, our Python program is based on the same.

import math
length float (input ("Enter length of the ladder: "))
angle float ( input("Enter angle of leaning (in degrees)"))
ang_radian math.radians (angle)
=

#Convert degrees to radians


height length math.sin(ang_radian)
= *

print ("Ladder s height on the wall:",


height)
Sample run:
Enter 1ength of the ladder 1 6
Enterangle of 1eaning (in degrees): 75
Ladder's height on the wall
15.45481322062 5093
Enter 1ength of the ladder : 20
Enter angle of 1eaning (in degrees) : 0
Ladder's height on the wall 0.0

Enter 1ength of the ladder: 24


Enter angle of leaning (in
degrees): 45
Ladder's height on
the wall 16.970562748477143
Enter length of the ladder 24
Enter angle of leaning (in degrees) : 80
Ladder's height on
the wall 23.63538607229299
HANDLING
263
DATA

Chopter 8:

G L O S S A R Y

Something that has a value.


Atom

Implicit Type Conversion


Coercion

Valid combination of operators and atoms.


E x p r e s s i o n

Explicit Type C o n v e r s i o n Forced data type conversion by the user.

Immutable Type A type whose value is not changeable in place.


Implicit Type Conversion Automatic lnternal Conversion of dato type (lower to higher type) by Python.
Mutable Type
A type whose value is changeable in place.
Symbol/word that triggers an action or operation.
Operator

Type Casting
Explicit Type Conversion.

For
Solutions for

Assignments Selected Questions

Type A: Short Answer Questions/Conceptual Questions


1. What are data types? How are they important Scan
QR Code
supported by Python ? Name them.
2. How many integer types are

3. How are these numbers different from one another ? 33, 33.0, 33, 33+j
numbers have two real and imaginary. In which data type are real and imaginary
4. The complex parts:
parts represented ?
different from another ?
5. How many string types does Python support ? How are they one

6. What will following code print?


str1 = '' "Hell J

o''

str2'''Hell\

print(len (str1) > len(str2))


7. What are immutable an mutable types ? List immutable and mutable types of Python.
8. What are three internal key-attributes of a value-variable in Python ? Explain with example.

return True for is operator, they will also return True for ==
operator ?
9. Is it true that if two objects
10. Are these values equal ? Why/why not ?
(ii) 20 and int(20) (ii) str(20) and str(20.0) io) 'a' and "a"
() 20 and 20.0
. What is an atom ? What is an expression ?
2. What is the difference between implicit type conversion and explicit type conversion ?
5. Two objects (say a and b) when compared using == , return True. But Python gives False when
b is True but why is a is b False ?)
compared using is operator. Why ? (i.e., a ==

4. Given str1 = "Hello", what will be the values of ?

(a) strl [0] (b) str1 [1] () str -5) (d) str 4] (e)str[5
b. If you give the following for str1 = "Hello", why does Python report error?

str1[2] ="'p
264 COMPUTER SCIENCE WITH
ITH PTH
PTHON-
16. What will the result given by the following?
( ) type (6+3) ( ) type (6-3) ()type (6 * 3) (d) type (6/3) ( ) type (6//3)

17. What are augmented assignment operators ? How are they useful? type (6
18. Differentiate between (555/222)*2 and (555.0/222)**2.
19. Given three Boolean variables a, b, c as : n = False, b = True, c = False,

Evaluate the following Boolean expressions:


(a) b andc (b) bor c (C) not a and b (d) (a and b) or not c
e) not b and not (a or c) () not ((not b or not a) and ) or a

20. What would following code fragments result in ? Given x =3.


(e) "Hello" == "Hello"
(a) 1 <x (b) x >=4 (c)x==3 (d) x ==3.0
) "Hello" > "hello" (g) 4/2 2.0 (h) 4/2 = 2 ) x < 7 and 4 > 5.

21. Write following expressions in Python


() ) tYh h (d) d =(x2-x1)* +(y2 -yly |Hint. tor sqrt( ) use math.sartd

(e) (r -h$ +(y-k? =2 (x =-b+ Nb-4ac (g) a"x a" = a"*


2a

(h) (a"y" =a" () a"=


22. int('ad) produces error. Why ?
23. int('a) produces error but following expression having int('a) in it, does not return error. Why 1
len('a') +2 or int('a')
24. Writeexpression to convert the values 17, len(ab) to ) integer (i) str (i11) Boolean values
25. Evaluate and Justify () 22 /17 =37/47+88/83
(i) len('375*2.
26. Evaluate () 22.0/7.0 22/7 (i) 22.0/7.0 int(22.0/7.0) (ii) 22/7 - int (22.0)/7 and justifv.
27. Evaluate and justify : (i) false and None (ii) 0 and None (ii) True and None (iv) None and None
28. Evaluate and justify:
a) 0 or None and "or" (6) 1 or None and 'a' or 'b' () False and 23
(d) 23 and False ) not (1 -= 1 and 0!= 1)
() "abc" ==
"Abc" and not (2 ==
3 or 3 ==
4)
(g) False and 1 == 1 or not True or 1 1 and
==
False or 0 == 0
29. Evaluate the following for each expression that is successfully evaluated, determine its value anu type
for unsuccessful
expression, state the reason.
(a) len("hello") 25/5 or 20/10
==
(b) 3 <5 or 50/(5 - (3 + 2))
(c)50/(5 (3 +2)) or 3 < 5 (d) 2 * (2* (len("01")))
30. Write an expression that uses 99.
exactly 3 arithmetic operators with integer literals and produces re>
31. Add parentheses to the
following expression to make the order of evaluation more
y %4 == e and y % 100 != 0 or y% 400 == 0
cledr
32. A program runs to ISecdi t?
completion but gives an incorrect results. What type of error would tde
33. In Python, strings are immutable while lists are mutable. What is the
34.
difference
How does the //
operator differ from the / operator ? Give an where /// would
be neeat
35. MidAir Airlines will example of where wo VIde, and

only allow carry-on bags that are no more than 22 inches


9 inches deep.
Assuming that variables named length, width, and long, 1* been signed

depth have alreaay and

values, write an expression combining the three that evaluates to True if


False otherwise. bag fits within u
HANDLING
265
DATA
ter 8:
Which types are most dangerous and why ?
are main error types?
o. statements:
talse

17
Correct any easier to detect and to correct than run-time errors.

Compile-time errors are usually


C
errors can usually be detected by the compiler.
(b) Logically error and a semantics error.
between a syntax
Differentiate
38.
between a syntax error and a logical error in a program. When is each type of error likely
Differentiate

39. found ?
to be
difference etween an error and exception ?
What is the
40.

Based Questions
Tyoe B: Application the outcome.
is the result produced by (i) bool (0) (i) bool (str(0)) ? Justify
1, What
be the output, if input for both
the statements is 5+4/2.
What will
6 input ("Value 1:")
=
6 = int(input ("value 2: "))
is the result in floating point form ?
Following code has
an expression with all integer values. Why
3.
2, 3, 6
a, b, c
=

d a+ b * c/b

print(d)
following code print ?
4. What will
a = va= 3 (b) a =3
(a)
b va 3 b 3.0
print (a == b)
print (a, b)
print (a is b)

5. What will be output produced by following code ? State reason for this output.

a, b, c= 1, 1, 1
a) a, b, c =
1, 1, 2
(b) a = 5 - 4 3 (c)
d a +b b 3**2**3 d 0.3
e = a + b+C - d
e 1.0 print(a)
f a +b+c == d
f 1.0 print(b)
8 2.0 print(e)
h e +f print(f)
print(c == d)

print(c is d)
print(g== h)
print(g is h)
GWhat will be the output of following Python codee?

(a) a 12
b) X, y =4, 8
b 7.4 z x/y*y
C1 print(z)
a- b
print (a, b)
a = 2+C

print(a)
b+ a *c
print(b)
COMPUTER SCIENCE WI
266
Bo that the outpul Drw
of previoUN questikon
Make change in
the expresion for z lint. Use a function around
ound a
(1
7.
cannot change the operators
and order of
variables.
Uub-exprewit
8. Consider the following
expression.
"or" + "4"
X "and" * (3 + 2) >»
this expression ?
of value that is computed
by
What is the data type

9. Consider the following code segment:


a input()
b int(input())
C a + b
print (c) Find the
first enters 10 and
then 5, it gives an error.
the error, its
When the program is run, the
user r
reason
and correct it.
10. Consider the following cocde segment
a input("Enter the value of a:")
b input("Enter the value of b:")
print(a + b)
9 for b then what will the above codedi
IF the the program and enters 11 for a and
user runs blay?
11. Find out the error and the reason for the error in the following code. Also, give the corrected Code

a, b "5.0", "10."
X = float(a/b)

print (x)
Consider the following program for the next two questions. It is supposed to compute the hypoteuse
of a right triangle after the user enters the lengths of the other two sides.

a =float (input ("Enter the length of the first side: "))


b float(input ("Enter the length of the second side: "))
h sqrt(a * a + b * b)

print("The length of the hypotenuse is", h)


12. When this program is run, the following output is generated (note that input entered by the user is
shown in bold):
Enter the length of the first side: 3
Enter the length of the second side: 4
Traceback (most recent cal1 1ast):
h sqrt(a * a + b * b)

NameError: name 'sqrt' is not defined


Why is this error ocurring? How would you resolve it ?
13. After adding inport math to the code given above )
(before question 12), what other change
required in the code to make it fully work ?
14. Which of the following expressions will result in program

containing it is run ?
an error
message being displayed when d
P
a) 2.0/4 (b) "3" +"Hello" (c) 4 % 15
(d) int("5")/float("3") (e) float("6"/"2")
15. Following expression does not report an error evern if it has a lem
3 or 10/0
sub-expression with 'divide by zero P
What changes can you make to above expression so that Python reports this error ?
8: DATA HANDLING
267
C h o p t e r8 :D A T A

byfollowing code?
What is the output produced
15. bool(0), bool (0.0)
a, b
str(®), str(e.0)
C d
print (len(a), len(b))
len(d))
print (len (c),
Can you write an expression that gives sum of all the digits shown inside the
string s "12345".
=

on a
should be able to produce the result as 15 (1+2+3+4+5).
ino S ie., the program
indexes and convert to integer]
Hint. Use
if e is given input as True
17 Predict the output
a True

b <5
print (a == b)

print (a is b)
C str (a)
d str (b)
print (c == d)

print (c is d)
e =input ("Enter:")
print (c = e)

print (c is e)

18. Find the errors(s).

name = "HariT" (b) a = bool (0))

print (name) b bool (1)


print (a == false)
name[2] = 'R'
print (b == true)
print (name)
c) print (type (int("123"))) (d) pi =3.14
print (type (int('"Hello"))) print (type (pi))
print (type (str("123.0"))) print (type ("3.14") )
print (type (float ("3.14")))
print (type (float("three point fourteen") ))

(e) print ("Hello" + 2) ( p r i t ("Hello"/2)


print ("Hello" / 2)
print ("Hello" "2")
p r i n t ("Hello" * 2)

19. What will be the output


produced
'5', 2
) X , y, Z =True, False, False (b) x, y
=

z X +y
a =
x or (y and z)
b = (x or y) and z print(z)
print(a, b)
) s = 'Sipo' (d) w,X, y, z
=True, 4, -6, 2
result - (x + z) < y or x ** z < 10
S1 = s + '2'
s2 = s * 2 print(result)

print(s1)
print(s2)
COMPUTER SCIENCE WITH
268
Correct it so that it Drod
PYTHON-
PyT

20. Program is giving a weird result of "O.50.50.50.50.50.50...


times 150.
uces the correct
result which is the probability value (input
as 0.5)
number between 0
and 1: ")
probability =input ("Type a *
150), "il
print("Out of 150 tries, the
odds are that only", (probability "will succeed."
[Hint. Consider its datatype
21. Consider the code given below:
import random
r= random.randrange (100, 999, 5)
print(r, end = '")
r= random.randrange (100, 999, 5)
print(r, end = " ")

r= random.randrange (100, 999, 5)


print(r)
Which of the following are the possible outcomes of the above code? Also, what can be the maximum
um
and minimum number generated by line 2 ?
(a) 655, 705, 220 (b) 380, 382, 505 c) 100, 500, 999 (d) 345, 650, 110
22. Consider the code given below:
import random
r random.randint (10, 100) - 10

print(r, end ="*)


r=random.randint(10, 100) 10
print(r, end = *)
r= random.randint(10, 100) 10
print(r)
Which of the following are the possible outcomes of the above code ? Also, what can be the maximum
and minimum number generated by line 2?
(a)1245 22 (b) 100 80 84 (c) 101 12 43 (d) 100 12 10
23. Consider the le given low:
import random
r random.random() * 10

print(r, end = '")


r random.random() * 10

print(r, end ='")


r random.random() * 10

print(r)
Which of the following are the
possible outcomes of the above code? Also, what can be the maximult
and minimum number
generated by line 2?
(a) 0.5 1.6 9.8 (b) 10.0 1.0 0.0 (c) 0.0 5.6 8.7 (d) 0.0 7.9 10.0
24. Consider the code
given below:
import statistics as st
v= [7, 8, 8, 11, 7, 71
mi st.mean(v)
m2 st.mode (v)
m3 st.median(v)
print(m1, m2, m3)
Which of the following is the correct of the above code ?
output
(a) 7 8 7.5 (b) 8 7 7 (c)8 7 7.5 (c) 8.5 7 7.5
8 : DATA HANDLING
Chapter8 :DAT

269

C: Programming ractice/Knowledge based Questions


Type
program to obtain prinipal amount, rate of interest and time from user and compute simple

interest.

te a p
program
r o g r a m to obtain temperatures of 7 days (Monday, Tuesday ... Sunday) and then display
2. Write a
average
temperature of the week.,
r i t e a program to obtaln x, y, 2 from user and calculate expression : 4x+3y° +9z+6T.
3.
4. Write a program that reads a number of seconds and prints it in form: mins and seconds, e:g,
200 seconds are printed as 3 mins and 20 seconds
Hint. use // and % to get minutes and seconds]
5. Write a program to take year as input and check if it is a leap year or not.

6. Write a program to take fwo numbers and print if the first number is fully divisible by second number

or not.
7. Write a program to take a 2-digit number and then print the reversed number. That is, if the input given
is 25, the program should print 52.
8. Try writing program (similar to previous one) for three digit number i.e., if you input 123, the program
should print 321.
9. Write a program to take two inputs for day, month and then calculate which day of the year, the given
date is. For simplicity, take 30 days for all months. For example, if you give input as : Day3, Month2
then it should print "Day of the year: 33"
10. Write a program that asks a user for a number of years, and then prints out the number of days, hours,
minutes, and seconds in that number of years.
How many years ? 10
10.0 years is
3650.0 days
87600.0 hours
5256000.e minutes
31536000e.0 seconds
Write a program that inputs an age and print age after 10 years as shown below:

What is your age ? 17


in ten years, you will be 27 years old!
12. runs are shown below
Ee a program whose three sample

Sample Run 1
(A) 2
Random number between 0 and 5
:

(B) :5.
Random number between 0 and 5
A to the power B = 32

Sample Run 2
(A 4
Random number between 0 and 5
:

0 and 5 (B) :3.


Random number between
A to the power B = 64

Sample Run 3
1
Random number between 0 and 5 (A
:

:1.
Random number between 0 and 5 (B)
A to the power B = 1
270 COMPUTER SCIENCE WITH
PYTHO
HON -
13. Write a program that generates six random numbers in a sequence created with (start eha
art, stop,
print the mean, median and mode of the generated numbers. step). Then
14. Write a program to generate 3 random integers between 100 and 999 which is divisihloL
15. Write a program to generate 6 digit random secure OTP between 100000 to by 5
999999.
16. Write a
program to generate 6 random numbers and then their
print and mean, median
right angled triangle whose two sides and an angle is ode.
mod.
17. Write a
program to find a side of a
ois
18. Write a program to calculate the radius of a
sphere whose area (4u) is given.
19. Write a
program that inputs a string and then prints it equal to nunmber of times its
length.eg
Enterstring: "eka"
Result ekaekaeka
20. Find the volume of the
cylinder (trh) as shown:

15 cm

8 cm

21. Write a
program to calculate the area of an 3
equilateral triangle. (area =* side *
side).
2
22. Write a to
program input the radius of a
sphere and calculate its
volume| V
23. Write a
program to calculate amount payable after
24. Write simple interest.
a
program to calculate amount payable after
25. Write a to
compound interest.
program computer (a+ b* using the formula a + b +3a b+3ab3
CHAPTER 8 : DATA HANDLING

Multiple Choice Questions


1. (b), (d), ), (g). (h) 2. (a), (b), (c), (d) 3. (6) 4. (b) 5. (b)
7. (c), d) 8. (b) 9. (b) 10. (a) 11. (b)
6. (a)
13. (c) 14. (b) 15. (b) 16. () 17. (b)
12. ()
18. (b) 19. (), (b), (. (g). (h) 20. (d) 21. (c) 22. (d)
24. (c) 25. (a) 26. (c) 27. (c) 28. (c)
23. (b)
30. b) 31. () 32. (c) 33. (c) 34. (a)
29. (a)
35. (b) 36. (c)

Fill in the Blanks


3. 15 4. lists, dictionaries, sets
1. integer 2. fractional, exponent
9. id 10. is
5. integer 6. floating-point 7. set 8. tuple
11. math random(O or random.random() 13. randint()
12. or random.randint( )
14. randrange( ) or random.randrange() 15. statistics

True/False Questions
3. F 4. T 5. T 6. F
1. F 2. T
9. T 10. T 11. F 12. T
7. F 8. T
15. F 16. F 17. T 18. T
13. F 14. T

19. T 20. T

CHARTER 9 FIOW QE CONTROL

You might also like