0% found this document useful (0 votes)
15 views117 pages

CH 7&8 DataHandling & Module

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views117 pages

CH 7&8 DataHandling & Module

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 117

7.

DATA HANDLING

CLASS: XI CBSE COMPUTER SCIENCE


JINI N K
Jini N K
INTRODUCTION

➢Python provides a PREDEFINED set of


data types for handling the data it uses

➢ Data can be stored in any of these


data types

Jini N K
BUILT-IN CORE DATA TYPES

STRING TUPLE
NUMBERS LIST
DICTIONARY

Jini N K
NUMBERS Used to store numeric values

Floating Point Complex


Integers Numbers Numbers

Fractional Form
Integers

Exponent
Booleans

Jini N K
THE RANGE OF PYTHON NUMBERS
DATA TYPE RANGE

Integers An unlimited range, subject to available (virtual)


memory only
Booleans Two values True (1), False (0)

Floating point numbers An unlimited range, subject to available (virtual)


memory on underlying machine architecture

Complex numbers Same as floating point numbers because the real


imaginary parts are represented as floats

Jini N K
STRINGS
Any number of valid characters into a
set of quotation marks

Jini N K
STRINGS IN PYTHON
Strings in Python are stored as individual
characters in contiguous locations, with
two way index for each location
Forward Indexing
0 1 2 3 4 5
S L E S S O N
-6 -5 -4 -3 -2 -1
Backward Indexing

Jini N K
ACCESSING SINGLE ELEMENT OF A STRING
0 1 2 3 4 5

name L E S S O N
-6 -5 -4 -3 -2 -1

Jini N K
STRINGS ARE IMMUTABLE

Jini N K
LISTS IN PYTHON
• List stores a sequence of values of any data
type

• The lists are depicted through square


brackets

Jini N K
ACCESSING SINGLE ELEMENT OF A LIST
Forward Indexing
0 1 2 3 4 5
L1 C H E R R Y
-6 -5 -4 -3 -2 -1 Backward Indexing

Jini N K
LISTS ARE MUTABLE
Elements of the list can be changed. Can add, change, delete a list’s
elements

Jini N K
TUPLES IN PYTHON
• Tuple stores a sequence of values of any data type
• The tuples are depicted through parentheses

Eg:
T=(‘Q’, ‘h’, ’joy’, ’14’, 30.07)

T=( )

T=(5,10,15,20,25)

T=(‘go’, ‘come’, ’see’, ’let’)


Jini N K
TUPLES ARE IMMUTABLE
Elements of a tuple cannot be
changed.

Jini N K
SETS
• Created by specifying comma separated values
enclosed in curly brackets

• Elements are unordered and unindexed unlike lists

• Do not allow duplicate entries

• Sets cannot contain mutable elements

• Set is mutable
Jini N K
Jini N K
DICTIONARIES IN PYTHON
• Collection of key-value pairs separated by commas
• Mutable, unordered collections that associate keys to
values
• Dictionaries are enclosed within curly brackets

Jini N K
Jini N K
PYTHON DATA OBJECTS

Mutable Immutable
• Values can be changed in place • Values cannot be changed in place
• Lists, Dictionaries, Sets • Integers, Floating point numbers,
Booleans, strings, Tuples

Jini N K
IMMUTABLE

10 15 20 21 40 55
…280 …284 …290 …312
146003692 14003700
8 8

a b c

a=10
b=a
c=15

Jini N K
Jini N K
VARIABLE INTERNALS
• Python is an Object Oriented Language
• Everything is an object in Python
• Data items, literal value, strings, numbers, data types,
variables → Objects
• An object is an entity that has certain properties and
that exhibit a certain type of behavior

Hold whole numbers only and


they have infinite precision Properties
Integers
Supports all arithmetic operations Behavior
Jini N K
Every python object has three key attributes

Jini N K
EXAMPLES
1. What is the output of the following code?

2. Why did the code not print the output exactly as the input?

3. How are following two variables created using { }


different from one another?
V1={11,12,13,14} V2={11:12, 13:14}

Jini N K
EXAMPLES - ANSWERS
1. What is the output of the following code?

2. Why did the code not print the output exactly as the input?
Sets ignore duplicate values
3. How are following two variables created using { }
different from one another?
V1={11,12,13,14} V2={11:12, 13:14}

Jini N K
V1 is a set and V2 is a dictionary as it has key : value pairs
& |
^ ~
Jini N K
OPERATORS
The symbols that trigger the operation/action on data

OPERANDS
The data on which operation is being carried out

OPERANDS

OPERATOR
Jini N K
UNARY OPERATORS Operators that act on one operand

+ Unary Plus - Unary Minus


The operator + precedes an operand.

The operand of the unary + operator


must have arithmetic type and the
result is the value of the argument

Jini N K
Binary Operators
Operators that act upon two operands

+ - *
Addition Operator Subtraction Operator
Multiplication
Operator

Jini N K
/ // %
Floor Division
Division Operator Modulus Operator
Operator

Divides and returns the Divides and truncates Divides and gives the
result as a float value the fractional part. remainder
Rounds to the lowest
value if negative
Jini N K
**
Exponentiation Operator

Returns base raised to


power exponent

Jini N K
EXAMPLES

1. What will be the output produced by the following code?

Jini N K
EXAMPLES
1. What will be the output produced by the following code?

Jini N K
EXAMPLES
2. Print the area of a circle of radius 3.75 metres

Jini N K
AUGMENTED ASSIGNMENT OPERATORS

+= a+=1 → a=a+1
//= p//=10 → p=p//10
-= b-=5 → b=b-5
**= x**=5 → x=x**5
*= x*=y → x=x*y
%= m%=5 → m=m%5
/= a/=7 → a=a/7

Holds only for immutable types


Jini N K
RELATIONAL OPERATORS
Also known as Comparison Operators

< Less than >= Greater than or equal to

> Greater than == Equal to

<= Less than or equal to != Not equal to

If the comparison is true, the relational expression


results into the Boolean value True otherwise False
Jini N K
Numeric Types Values are compared after removing trialing
zeros after decimal point

Strings Compared on the basis of lexicographical


ordering

Lists, Tuples Equal if they have same elements in the


same order

True is equivalent to 1
Boolean
False is equivalent to 0
Jini N K
a=9, b=15, p=9.0
c= ‘n’, d=‘g’, e=‘N’
f=‘god’, g=‘God’, h=‘god’, j=‘God’, k=‘Godhouse’
L=[1,2,3], M=[2,4,6], N=[1,2,3]
O=(1,2,3), P=(2,4,6), Q=(1,2,3)

a < b → True f == h → True “God” < “Godhouse” → True

c < d → False c == e → False “god” < “Godhouse” → False

f < h → False g == j → True a == p → True

Jini N K
a=9, b=15, p=9.0
c= ‘n’, d=‘g’, e=‘N’
f=‘god’, g=‘God’, h=‘god’, j=‘God’, k=‘Godhouse’
L=[1,2,3], M=[2,4,6], N=[1,2,3]
O=(1,2,3), P=(2,4,6), Q=(1,2,3)

L == M → False O == Q → True 1 == True → True

L == N → True a == True → False

O == P → False 0 == False → True

Jini N K
It is not recommended to use == operator
to compare two floating point values

• Relational operators have lower precedence than the arithmetic operators


• Do not confuse the = and the == operators.

Jini N K
IDENTITY OPERATORS

Returns True if both


is operands are pointing to
same object(same
memory location), returns
False otherwise

Returns True if both


operands are pointing to
is not different objects(different
memory location),
returns False otherwise
Jini N K
TRUTH VALUES
Any object can be tested for truth values – true and false

Values with truth value as false Values with truth value as false

None

False
All other values are considered
0, 0.0, 0j
true
Empty sequence [],(), ‘’

Empty mapping {}

Jini N K
LOGICAL OPERATORS
Used to combine expressions

or

and

not

Jini N K
THE or OPERATOR
• Combines two expressions
• Works in two ways

• The or operator evaluates to True if either of its operands evaluate to True


• False if both operands evaluate to False

(i) Relational expressions as operands

p q p or q
False False False
False True True
True False True
Jini N K
True True True
Jini N K
(ii) Numbers / Strings / Lists as operands

In an expression x or y, if first operand has truth value as false,


then return second operand y as result, otherwise return x.

x Y x or y
false false y
false true y
true false x
true true x
Jini N K
Operation Result
0 or 0 0
0 or 4 4
6 or 0.0 6
‘hello’ or ‘’ ‘hello’
‘’ or ‘g’ ‘g’
‘’ or ‘’ ‘’
‘s’ or ‘j’ ‘s’
Jini N K
THE and OPERATOR
• The or operator evaluates to True if both of its operands evaluate to True
• False if either or both operands evaluate to False

(i) Relational expressions as operands

p q p and q
False False False
False True False
True False False
True True True
Jini N K
Jini N K
Jini N K
(ii) Numbers / Strings / Lists as operands

In an expression x and y, if first operand has truth value as


false, then return first operand x as result, otherwise return y.

x Y x and y
false false x
false true x
true false y
true true y
Jini N K
Operation Result
0 and 0 0
0 and 4 4
6 and 0.0 0.0
‘hello’ and ‘’ ‘’
‘’ and ‘g’ ‘’
‘’ and ‘’ ‘’
‘s’ and ‘j’ ‘j’
Jini N K
THE not OPERATOR

The not operator


negates or reverses
the truth value of the
expression.

Jini N K
BITWISE OPERATORS
Used to change individual bits in an operand

&

^
~
Jini N K
Operato
Operation Use Description
r
Results 1 if both bits are
& bitwise and op1 & op2
1; otherwise returns 0
Results 1 if either of the
| bitwise or op1 | op2 bits are 1; results 0 if both
bits are 0 or 1
Results 1 if the bits are
^ bitwise xor op1 ^ op2 complementary;
otherwise returns 0
bitwise Inverts all of the bits of
Jini N K
~ complement
~op1
the operand
THE AND OPERATOR &

For AND operations, op1 op2 Result


1 AND 1 produces I. 0 0 0
Any other 0 1 0
combination
1 0 0
produces 0
1 1 1

Jini N K
THE INCLUSIVE OR OPERATOR |

op1 op2 Result


For inclusive OR
operations, 0 OR 0 0 0 0
produces 0. Any other 0 1 1
combination produces 1. 1 0 1
1 1 1

Jini N K
THE EXCLUSIVE OR OPERATOR ^

op1 op2 Result


For XOR operations, 1 0 0 0
XOR 0 produces 1 and 0 0 1 1
XOR 1 produces 1. Any 1 0 1
other combination 1 1 0
produces 0.
Jini N K
THE COMPLEMENT OPERATOR ~

For complement
operations, if the operand op1 Result
bit is 1 the result is 0 and 0 1
if the operand bit is 0 the 1 0
result is 1.

Jini N K
OPERATOR PRECEDENCE
Operator Description

() Parantheses

** Exponentiation

+x, -x Positive, Negative

* , / , //, % Multiplication, Division, Floor Division, Remainder

+, - Addition, Subtraction

<, <=, >, >=, !=, == Comparison Operators


is, is not Identity Operators

not Logical NOT

and Logical AND

or
Jini N K
Logical OR
Operator Description
() Parantheses

8*7/4//3 **
+x, -x
Exponentiation
Positive, Negative
* , / , //, Multiplication,

56/4//
56/4//3 % Division, Floor
Division, Remainder
+, - Addition, Subtraction

14.0//3 <, <=, >,


>=, !=, ==
Comparison Operators
Identity Operators

4 is, is not
not Logical NOT
and Logical AND
or Logical OR
Jini N K
Operator Description
() Parantheses
** Exponentiation
len(“Explore”)==49/7 or 50/10 Positive, Negative
+x, -x
* , / , //, Multiplication,
7 == 49/7 or % Division, Floor
Division, Remainder
50/10 +, - Addition, Subtraction
<, <=, >, Comparison Operators
7 == 7.0 or 50/10 >=, !=, == Identity Operators
is, is not
7 == 7.0 or 5.0 Logical NOT
not
True or 5.0 and Logical AND
or Logical OR
Jini N K
Operator Description
() Parantheses
len(“Explore”)==49/7 or 50/10 ** Exponentiation
+x, -x Positive, Negative

7 == 49/7 or * , / , //, Multiplication,


Division, Floor
%
50/10 Division, Remainder

7 == 7.0 or 50/10 +, - Addition, Subtraction


<, <=, >, Comparison Operators
7 == 7.0 or 5.0 >=, !=, == Identity Operators
is, is not
True or 5.0 not Logical NOT

True and Logical AND


or Logical OR
Jini N K
Operator Description
() Parantheses

8*2+5**2//5-8 **
+x, -x
Exponentiation
Positive, Negative
* , / , //, Multiplication,
8*2+25//5-8 % Division, Floor
Division, Remainder
16+25//5-8 +, - Addition, Subtraction
<, <=, >, Comparison Operators
16+5-8 >=, !=, == Identity Operators
is, is not
21-8 not Logical NOT
13 and Logical AND
or Logical OR
Jini N K
Operator Description
() Parantheses

7>2 and 8>9 or not 11>1 ** Exponentiation


+x, -x Positive, Negative
* , / , //, Multiplication,
True and 8>9 or not 11>1 % Division, Floor
Division, Remainder
True and False or not 11>1 +, - Addition, Subtraction

True and False or not True <, <=, >, Comparison Operators
Identity Operators
>=, !=, ==
True and False or False is, is not
False or False not Logical NOT
and Logical AND
False Logical OR
Jini N K
or
Operator Description
() Parantheses
** Exponentiation
5<7 or 50 / (10 – (8+2) ) +x, -x Positive, Negative
* , / , //, Multiplication,
5<7 or 50/(10-10) % Division, Floor
Division, Remainder
5<7 or 50/0 +, - Addition, Subtraction
<, <=, >, Comparison Operators
5<7 or DivisionByZeroError >=, !=, == Identity Operators
is, is not
True or DivisionByZeroError Logical NOT
not
True and Logical AND
or Logical OR
Jini N K
Operator Description
() Parantheses
“xyz”==“Xyz” and not ** Exponentiation

(5==3 or 3==4) +x, -x Positive, Negative


* , / , //, Multiplication,
“xyz”==“Xyz” and not % Division, Floor
Division, Remainder
(False or False) +, - Addition, Subtraction
“xyz”==“Xyz” and not False <, <=, >, Comparison Operators
>=, !=, == Identity Operators
False and not False is, is not
False and True not Logical NOT
and Logical AND
False or Logical OR
Jini N K
Operator Description
() Parantheses
** Exponentiation
10>80 and not 10>80 Positive, Negative
+x, -x
* , / , //, Multiplication,
% Division, Floor
False and not False Division, Remainder
+, - Addition, Subtraction
False and True <, <=, >, Comparison Operators
>=, !=, == Identity Operators
False is, is not
not Logical NOT
and Logical AND
or Logical OR
Jini N K
Operator Description
() Parantheses
-3 * -2**4+len(str(10)) ** Exponentiation
+x, -x Positive, Negative

-3*-2**4+len(‘10’) * , / , //, Multiplication,


Division, Floor
%
-3*-2**4+2 Division, Remainder
Addition, Subtraction
+, -
-3*-16+2 <, <=, >, Comparison Operators
>=, !=, == Identity Operators
48+2 is, is not
not Logical NOT
50 Logical AND
and
or Logical OR
Jini N K
EXAMPLES
1. What will be the output produced by the following code?

Jini N K
EXAMPLES
1. What will be the output produced by the following code?

Jini N K
2. What will be the output produced by the following code?

Jini N K
2. What will be the output produced by the following code?

Jini N K
3. What will be the output produced by the following code?

Jini N K
3. What will be the output produced by the following code?

Jini N K
4. What will be the output produced by the following code?

Jini N K
4. What will be the output produced by the following code?

Jini N K
5. What will be the output produced by the following code?

Jini N K
5. What will be the output produced by the following code?

Jini N K
6. Why is the following code giving error?

Jini N K
7. Which of the following expressions will yield an integer type
value as its output

(i) 5 * 2 → 10
(ii) 5**2 → 25
(iii) ‘5’+’2’ → ‘52’
(iv) ‘5’*2 → ‘55’
(v) 5/2 → 2.5
(vi) 5//2 →2
(vii) 5%2 →1
(viii) 5+2.0 → 7.0
(ix) 5.0*2.0 → 10.0
(x) ‘5’-2 → Type Error

Jini N K
EXPRESSIONS Any valid combination of operators,
literals and variables

ATOM An atom is something that has a value. Identifiers, strings, lists,


tuples, sets, dictionaries, sets are all atoms

Arithmetic Relational Logical String Compound

Combination Combination Combination of String Combination


of numbers of literals, literals, operators ‘+’ of any of the
and variables and variables and and ‘*’ when above type of
arithmetic relational logical combined with expressions
operators operators operators string operands
and integers
+ Concatenation
* Replication

Jini N K
Jini N K
Jini N K
Jini N K
int()
str()

float()

bool()
complex()

Jini N K
Which of the following expressions will yield a Boolean type
value as its output?

Jini N K
Write Boolean expressions in Python for these conditions.

(i) x is a factor of y (that is, x divides evenly into y)

(ii) age is at least 18 and state equals ‘Goa’

(iii) the string name is not ‘Nimra’

Jini N K
Write Boolean expressions in Python for these conditions.

(i) x is a factor of y (that is, x divides evenly into y)

(ii) age is at least 18 and state equals ‘Goa’

(iii) the string name is not ‘Nimra’

(i) x % y == 0

(ii) age >= 18 and state ==‘Goa’

(iii) name != ‘Nimra’


Jini N K
PYTHON STANDARD LIBRARY MODULES

▪ Standard library provides some modules having functionality for


specialized actions

▪ A Python module is a file which contains some variables,


constants, functions , objects defined in it which can be used in
other Python programs

▪ In order to use the module functions, import the module in a


program

Jini N K
WORKING WITH math MODULE OF PYTHON
import math

ceil math.ceil(num) Returns the smallest integer not less than num

Returns the square root of num.


sqrt math.sqrt(num) If num<0, error occurs

Jini N K
exp math.exp(arg) Returns the natural logarithm e raised to the arg power

Gives the value of e2

fabs math.fabs(num) Returns the absolute value of num.

floor math.floor(num) Returns the largest integer not greater than num

Jini N K
log math.log(num,[base]) Returns the natural logarithm for num

log 10 math.log10(num) Returns the base 10 logarithm for num

pow math.pow(base,exp) Returns base raised to exp power

Jini N K
Returns the sine of arg. The value of
sin math.sin(arg) arg must be in radians.

cos math.cos(arg) Returns the cosine of arg. The value


of arg must be in radians.

Returns the tangent of arg. The


tan math.tan(arg)
value of arg must be in radians.

Jini N K
The degrees() converts angle x from
degrees math.degrees(x) radians to degrees

radians The radians() converts angle x from


math.radians(x)
degrees to radians

Jini N K
Constants ⫪ and e

math.pi Gives the mathematical constant ⫪=3.141152…

math.e Gives the mathematical constant e=2.718281…

Jini N K
Write the corresponding Python expressions for the
following mathematical expressions.

(v) |e2 – x|

Jini N K
(i) math.sqrt(a*a + b*b + c*c)

(ii) 2 - y * math.exp(2 * y) + 4 * y

(iii) p + q / math.pow((r + s),4)


(v) |e2 – x|
(iv) (math.cos(x) / math.tan(x)) + x

(v) math.fabs(math.exp(2) – x)

Jini N K
The value of a sphere is 7.5 metres.
Write Python script to calculate its area and volume.
(Area of a sphere = 4⫪r2; Volume of a sphere= 4/3⫪r3)

Jini N K
USING RANDOM MODULE
import random

random() Returns a random floating point number N


on the range [0.0, 1.0) → 0.0 <= N < 1.0

Jini N K
randint(a,b)
Returns a random integer N in the range (a,b)
→ a <= N <= b

Jini N K
randrange
(<start>,<stop>,<step>)

Returns random numbers from range start…stop with step value


→ start <= N <= stop

Jini N K
What could be the minimum possible and maximum possible
numbers by following code?

Minimum possible number → 3 – 3 = 0

Maximum possible number → 10 – 3 = 7

Jini N K
What will the following code produce?

Jini N K
Write a code fragment to generate a random floating number
between 45.0 and 95.0. Print these numbers along with their
average.

Jini N K
Write a code fragment to generate two random integers between 450
and 950. Print these numbers along with their average.

Jini N K
Write a code fragment to generate three random integers in the range
10,70 with a step of 13. Create a set with these numbers

Jini N K
statistics MODULE OF PYTHON

import statistics

Import full statistics module

from statistics import mean, median, mode

Import only three functions from statistics module

Jini N K
statistics. mean(seq) Returns the average value of the set/sequence

statistics. median(seq) Returns the middle value of the set/sequence

statistics. mode(seq) Returns the most often repeated value of the set/sequence

Jini N K
Given a list containing these values [22, 13, 28, 13, 22, 25, 7, 13, 25].
Write code to calculate mean, median and mode of the list.

Jini N K
DEBUGGING
Debugging refers to the process
of locating the place of error, and
correcting the code accordingly

PROGRAM BUG
Error in a program.

Jini N K
An error or bug is anything in

ERRORS IN A PROGRAM the code that prevents a


program from compiling and
running correctly

COMPILE-TIME ERRORS LOGICAL ERRORS RUN-TIME ERRORS


Errors that occur during compile-time Errors that occur due to Errors that occur
mistaken analysis of the during the execution
problem of the program

SYNTAX ERRORS SEMANTICS ERRORS


Syntax errors occur when Semantics error occurs
rules of a programming when statements are not
language are misused or meaningful
when a grammatical rule
of Python is violated

Jini N K
EXCEPTIONS

Exception refers to any


irregular situation occurring
during execution / runtime,
which you have no control on.

Jini N K
ERRORS EXCEPTIONS

• Error represents any bug • Exception refersto any


in the code that disrupts irregular situation occurring
running of the program or during execution/runtime,
causes improper output which you have no control on it.

• Can be fixed by making • Fixing exceptions is not that


corrections in the code simple

Jini N K
BUILT-IN EXCEPTIONS
Hits an end-of-file (EOF)
EOFError When a mapping key is not
without reading any data KeyError found in the set of existing keys

When fails for an I/O related When a function receives an argument


IOError reason – file not found, disk full ValueError with an inappropriate value

When an identifier name When a function or operation is applied


NameError is not found TypeError to an object of inappropriate type

When a sequence index When an import statement fails to


IndexError out of range ImportError find the module function

When the result of an When the second argument


OverflowError arithmetic expression is ZeroDivisionError if a division or modulo
too large to be expression is zero
represented
Jini N K
DEBUGGING USING CODE TRACING
Executing code one line at a
Code Tracing time and watching its impact
on variables.

Jini N K
JINI N K
Jini N K

You might also like