Chapter-8 Data Handling
Chapter-8 Data Handling
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.
203
204 cOMPUTER SCIENCE WITH
PYTHON. X
) 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).
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
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
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
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.
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
have -
that can hold a single
ython has no programming languages
which most other
separate character datatype,
s
character. In Python, character.
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
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)
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
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,
[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
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}
=
element, because a
we gave a tuple as an
> 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
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
(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
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
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
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.
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
>Chk =[2, 4, 6]
after changing a value in
id(Chk) See, even
id(Chk)
150195536
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.
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
integer value 5
30899120 DATA TYPES, MUTABILITY
» id(b)
-Progress In Python 8.1
NTERNALS
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.
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
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
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
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 -
**
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
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
-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
a t= b
to compare two floating point values. O = (1, 2, 3), P = (2, 4, 6), Q = (1, 2, 3)
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
>> 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.
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
*
=
operators.
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
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
>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'
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
> > 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, ie,
this test. However, in advanced same
ler 8:
Chopler 225
8.4.4 Logical Operators
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
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
"
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
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
e x a m i n e
them one by o nne.
us
Let
>>> 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
231
Chopter 8:
Operator Associativity
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
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
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.
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
==
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 -
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
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
-
A ((ch + i)/db)
int int
= 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
(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
will alway
division operator (/), the result h the
The final Tloating point number, even
datatype of expression
to
l will be floating on
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
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
(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
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
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,
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.
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.
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
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
+
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
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
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)
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
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
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
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.
. 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.
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.
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
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
() 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) 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
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.
NOTE: Answers for 0TQs are given at the end of the book.
Selved Prohlems
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 =
because and
len(str(17//4)) len(str(17/4))
len(str(4)) = len(str(4.0))
(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
==
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
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'
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
Explanation
Line 1 a = 3 + 5/8
= 3 +0.625
a = 3.625
b= 3
= 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
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
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
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)
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.
258
code ? Why?
18. What will be the output of following or 113
len(13)
len(13)
(ii)
() 13 or
Only option (i) and (iv) fulfill the condition of range 15 to 20.
<
hopter
8 :DA IA 259
The sample run of the above program is as shown below:
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
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
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') ==
(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,
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
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.
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
import math
length float (input ("Enter length of the ladder: "))
angle float ( input("Enter angle of leaning (in degrees)"))
ang_radian math.radians (angle)
=
Chopter 8:
G L O S S A R Y
Type Casting
Explicit Type Conversion.
For
Solutions for
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
o''
str2'''Hell\
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 ==
(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,
17
Correct any easier to detect and to correct than run-time errors.
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
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.
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)
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
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
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:
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
:
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
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