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

Data Handling - Ch-8

Uploaded by

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

Data Handling - Ch-8

Uploaded by

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

Data handling

Class-11th

Chapter - 8
CORE DATA TYPES OF PYTHON

Data type

Number None Sequences Mapping

Integer Floating Point Complex String Dictionary

Boolean Tuple

List
Mutable and immutable data types
 The Python data types are broadly classified into two types.
1. Mutable→ value can be changeable or modifiable.
2. Immutable→ value can not be changeable or non-modifiable.
X=5
y=6 Mutable data types immutable data types
if x==y:
Lists Integers
print(“ X value is equal to y”)
Dictionaries Floating point numbers
else: Sets Booleans
print(“ X value is not equal to y”) Strings
tuples
Number data types
 The number data types are used to store numeric values in Python. These number
data types are :
i) Integers
a) Signed integers
b) Booleans
ii) Floating-point Numbers
iii) Complex Numbers
Integers data types
Signed integers Booleans
 Integers are whole numbers . It is the normal integer These represent the truth
 They have no fractional parts. representation of whole values False and True
number. behaves like the values 0
 Integers cab be positive or negative. and 1.
 Integers are immutable types (i.e. the
values cannot be changed or
modified) Python provides single data It is a sub type of the plain
type(int) to store any integer, integers.
 Integers are represented in Python by whether big or small.
numeric values with no decimal point.
 There are two types of integers in
python :
It is signed representation To get the Boolean
a) Signed integers means the integer can be equivalent of 0 or 1, you
b) Booleans positive as well as negative. type bool(0) or bool(1),
python returns False or True
 The str() function converts a Boolean respectively .
value to string as ‘False’ or ‘True’.
String type data
 A python string is a sequence of characters and each character can be individually
accessed using its index or ( also called subscript).
 Strings in python are stored as individual characters in contiguous location, with two-way
index for each location.
 Strings are immutable data type i.e. you can not change the individual letter / character of a
string in place by assignment.
 The individual elements of a string are the characters contained in it those are stored in
contiguous memory locations.
 Length of string can be determined using len( ) function.
String characters internally stored
Syntax : len(string) and addressed by its index.
Example: len(“Carmel”) output : 6
 Two-way index for each location in a string are:
0 1 2 3 4 5
❑ Forward direction : ➔ 0, 1, 2, 3, 4, 5, ……….. ‘C’ ‘a’ ‘r’ ‘m’ ‘e’ ‘l'
❑ Backward direction:  -1, -2, -3 , -4, -5, -6, ……….. -6 -5 -4 -3 -2 -1
Nm=“Banshika Das”
print(len(Nm)) output➔12
LISTS data type
List element Values internally stored
and addressed by its index.
 A List in Python represents a list of comma-separated values of
any data type between square brackets i.e. [ ].
0 1 2 3 4
 The List in Python is a compound data type.
1 2 3 4 5
 A List can be changed/ modified . So it is a mutable. -5 -4 -3 -2 -1
 Like any other value, you can assign a list to a variable.
 When you assign values of a list in a variable, the values internally
are numbered from 0 onwards in memory. That is, 1st item of the 0 1 2 3 4
list is numbered 0, 2nd item of the list as 1, 3rd item of the list as 2, ‘a’ ‘e’ ‘i’ ‘o’ ‘u’
and so on. -5 -4 -3 -2 -1
Example:
>>> a=[1,2,3,4,5]
>>> VL=[‘a’, ’e’, ‘i’, ‘o’, ‘u’] >>>VL[0] ➔a 0 1 2
>>> ST=[‘Nikita’, 102, 78.5] ‘Nikita’ 102 78.5
-3 -2 -1
How to change any value in the LIST data type?
➢ To change first value in the above list namely a.
 A List can be changed/ modified ( i.e.
mutable) Example: -1
 Like any other value, you can assign a list to >>> a[0]=20 # first value is changed
a variable.
>>> print(a) # To see the changed values
Example:
[20,12,13,14,15]
➢ To see and check the values in a list.
Or
>>> a=[1,2,3,4,5] Or
>>>print(a)
>>> a >>>print(a)
[20,12,13,14,15]
[1,2,3,4,5] [1,2,3,4,5]
Example:-2
➢ To see and check individual values in a list.
➢ To change third value in the above list namely a.
>>> a=[10,12,13,14,15]
Example:
>>> a[0] >>>print( a[-3] )
>>> a[2]=30 # third value is changed
10 13
v>>> a[3] >>>print( a[-1] ) >>> a # To see the changed values

14 15 [10,12,30,14,15]
Tuples
 Tuples are represented as a list of comma-separated values of any data type within
parentheses i.e. ( ).
 Tuples are those lists which cannot be changed i.e. are not modifiable.
 A Tuple can’t be changed/ modified . So it is an immutable.
 Like any other value, you can assign a tuple to a variable.
 When you assign values of a tuple in a variable, the values internally are numbered
from 0 onwards in memory. That is, 1st item of the tuple is numbered 0, 2nd item of
the tuple as 1, 3rd item of the tuple as 2, and so on.
Example:
>>> p=(1,2,3,4,5)
>>> Q=(‘a’, ’e’, ‘I’, ‘o’, ‘u’)
>>> S=(‘N’, ‘p’ 12, 7, 5.5)
Dictionary
 The Dictionary is an unordered set of comma-separated key : value pairs, within { } , with the
requirement that within a dictionary.
 No two keys can be the same ( i.e. there are unique keys within a dictionary).
 A Dictionary can be changed/ modified . So it is a mutable.
 Like any other value, you can assign a Dictionary to a variable.
 Each element/ item value in a Dictionary is referred and accessed by its corresponding
key.

Example: To access individual element value of a Dictionary


>>> Vowels={‘a’:1, ‘e’:2, ‘i’:3, ‘o’:4, ‘u’:5}
>>> Vowels[‘a’]
1
>>> Vowels[‘o’]
4
Here, a, e, i, o, u are the keys of the dictionary and 1, 2, 3, 4, 5 are the values for these keys
respectively.
Python’s immutable Variable Names

 Python variable names are just the references to value-objects i.e. data
values.
 The variable-names do not store values themselves i.e. they are not
storage containers.
 Each time when you change the value, the variable’s reference memory
address changes.
 Variables are not like storage containers i.e. with fixed memory address
where value changes every time. Hence, they are immutable.
Variable Internals
❑ Python is an object oriented language.
❑ Python calls every entity that stores any values or any type of data as an
object.
❑ So, all data or values are referred to as object in Python.
❑ An object is an entity that has :
➢ certain properties
➢ and that exhibit a certain type of behavior
❑ Every Python object has three attributes associated to it. These are:
➢ The type of an object
➢ The value of an object
➢ The id of an object
Attributes of every Python object
1. The type of an object 2. The value of an object
The type of an object determines the operations that ➢ It is the data item contained in the object.
can be performed on the object. ➢ For a literal, the value is the literal itself and for a
variable the value is the data-item it is currently
Built-in function type( ) ➔ This function returns the referencing.
type of an object. ➢ Using print() statement you can access and display
Example: value of an object.
Example: >>> a , b=5 , 14.5
>>> a=5
>>> print(a) output: 5
>>> type(5) output: <class ‘int’>
>>> print(b) output: 14.5
>>> type(a) output: <class ‘int’>
3. The id of an object
➢ The id of an object is generally the memory location of the object.
➢ Built-in function id( ) ➔ This function returns the id of an object i.e. the memory location of the object.
➢ The id( ) of a variable is same as the id( ) of value it storing.
➢ Remember that while storing complex numbers, id’s are created differently.
Example: >>> a=5 >>> a=4
>>> id(5) output: 30899132 >>> id(4) output: 30899130
OPERATORS
• Operators are tokens that trigger some computation/ action when applied to variables and other
objects in an expression.
• Operator requires some operands to work upon. Mainly there are types of operators:-

Sl. UnaryOperators Binary Operators


1 Unary Plus (+) Arithmetic operators (7 operators) +, -, *, /, %, **(exponent), // (floor division)

2 Unary minus (-) Bitwise Operators (3 operators) & (bitwise AND) , ^ (bitwise XOR) , | (bitwise OR)

3 Bitwise Complement (~) Shift Operators (2 operators) << (shift left) , >> (shift right)

4 Logical negation (not) Identify Operators (2 operators) is , is not

5 Relational Operators (6 operators) < , > , <= , >= , == , !=

6 Logical Operators (2 operators) and , or

7 Assignment Operators (8 operators) = , /= , += , *= , %= , - = , **= , //=

8 Membership Operators (2 operators) in , not in


Unary Operators
Unary operators ➔ The operators that acts on one operand to operate upon are called
Unary operators.

Operator name Unary Plus (+) Unary minus (-)

Function/operation This operator (+) precedes an This operator (-) precedes an operand
operand which must have arithmetic which must have arithmetic type and
type and the result is the value of the result is the negation of its
the argument. operand’s value.

Example If a=5 then +a means 5 If a=5 then - a means –(5) = - 5


If a=0 then +a means 0 If a=0 then - a means -(0) = 0
If a= - 4 then +a means - 4 If a= - 4 then - a means -(- 4) = 4
Binary Operators
 Binary operators ➔ The operators that acts upon two operands are
called binary operators.

Sl. no Operators
1 Arithmetic operators (7 operators) +, -, *, /, %, **(exponent), // (floor division)
2 Bitwise Operators (3 operators) & (bitwise AND) , ^ (bitwise XOR) , | (bitwise OR)
3 Shift Operators (2 operators) << (shift left) , >> (shift right)
4 Identify Operators (2 operators) is , is not
5 Relational Operators (6 operators) < , > , <= , >= , == , !=
6 Logical Operators (2 operators) and , or
7 Assignment Operators (8 operators) = , /= , += , *= , %= , - = , **= , //=
8 Membership Operators (2 operators) in , not in
1. Addition Operator (+) 3. Multiplication Operator (*)
 This (+)add operator adds values of its operands and This (*) operator multiplies the values of its
the result is the sum of the values of its two operands. operands.
 The operands may be of number types. The operands may be of integer or floating point
number types.
 Python also offers (+) as a concatenation operator
Python also offers (*) as a replication operator
when used with strings, lists and tuples.
when used with strings.
➢ Example: Example:
>>>A , B= 5 , 7 >>>a=57 >>>A,B=5,7 >>>a=7
>>>print(A+B) >>>b=13 >>>print(A*B) >>>b=11
output : 12 >>>a+b output: 70 output : 35 >>>a * b output: 77

2. Subtraction Operator (-) 4. Division Operator ( / )


 This (-) operator subtracts the second operand  This ( / ) operator divides its first operand by the
value from the first operand. second operand and always returns the result as
float value.
 The operands may be of number types.  The operands may be of integer or floating point
number types.
 Example:
Example:
>>>A,B=15,7 >>>a=57
>>>A,B=15,5 >>>a=100
>>>print(A - B) >>>b=13 >>>print(A / B) >>>b=32
output : 8 >>>a - b output: 44 output : 8 >>>a / b output: 3.125
5. Floor Division Operator (//) 7. Exponentiation Operator (**)
 This (//) floor division is the division in which only the whole This (**) exponentiation operator performs
part of the result is given in the output and the fractional exponentiation (power) calculation and returns
part is truncated. the result of a number raised to a power
 The operands may be of number types. (exponent) .
Example :Comparison between division and floor division  The operands may be of number types.
>>> a=18.6 >>>a=18.6 Example:
>>> b=3 >>>b=3 >>>A , B = 5 , 2 >>>a=4
>>> print(a / b) >>> print(a // b) >>>print(A**B) >>>b=3
output : 6.2 output : 6 output: 25 >>>a ** b output : 64

6. Modulus Operator (%)


 This (%) operator finds the modulus (i.e. remainder ) of
its first operand relative to the second.
 That means it produces the remainder of dividing the
first operand by the second operand.
 The operands may be of number types.
 Example:
>>>A , B=7.2 , 3 >>>a=57
>>>print(A % B) >>>b=13
output : 1.2 >>>a % b output: 5
Negative Number Arithmetic in Python

operator Example output

Addition(+) -5 + 3 -2

Subtraction(-) -5 - 3 -8

Multiplication(*) -5 * 3 - 15

Exponentiation(**) -5 ** 3 -125

Division (/) -7 / 4 - 1.75

Floor Division (//) -7 // 4 -2

Modulus (%) -7 % 4 1
Augmented Assignment Operator (=)
Python has an assignment operator (=) which assigns the value specified on RHS ( Right hand Side) to the
variable / object on the LHS ( Left Hand Side) of the assignment operator (=).
 Python also offers Augmented Assignment arithmetic Operators, witch combine the impact of an
arithmetic operator with assignment operator.
These operators can be used any where that ordinary assignment is used.

Operation Description Comment


a+=b a=a+b Value of b added to the value of a and then the result assigned to a.

a-=b a=a-b Value of b subtracted to the value of a and then the result assigned to a.

a*=b a=a*b Value of b multiplied to the value of a and then the result assigned to a.

a/=b a=a/b Value of b divides the value of a and then the result assigned to a.

a // = b a = a // b Value of b does floor division to the value of a and then the result assigned to a.

a ** = b a = a ** b a b (a to the power b) computed first and then the result assigned to a.

a%=b a=a%b Value of b divides the value of a and then the remainder assigned to a.
Relational Operators
Relational refers to the relationships that values or operands can have with one other.
Python has Relational operators which determines the relation among different operands.
Python provides 6 relational operators for comparing values.
It checks / compares the values and returns Boolean value True when it satisfies otherwise; False.

Operation Description Example

a<b Smaller than / less than A, B=5 , 7 A<B → Output : True


a>b Greater than A, B=5 , 7 A>B → Output : False
a <= b Less than or equal to A, B=5 , 7 A<=B → Output : True

a >= b Greater than or equal to A, B=5 , 7 A>=B → Output : False

a==b Equal to A, B=5 , 7 A= =B → Output : False

a!=b Not equal to A, B=5 , 7 A != B → Output : True


Identity Operators
 There are two identity operators in Python is and not is.
 The identity operators are used to check if both the operands reference the same object
memory i.e. the identity operators compare the memory locations of two objects and return True
or False accordingly.

Operator Usage Description


is a is b It returns True if both the operands are pointing to same
object i.e. same memory location.
Is not a is not b It returns True if both the operands are pointing to different
object i.e. different memory location.
Example:→
A=10
B=10
A is B output ➔ It will return True
Logical Operators
Logical Python has Logical operators which determines the relation among different operands.
Python provides 3 Logical operators for comparing values..

Operator Meaning Example

and True if both the operands are true x and y

or True if either of the operands is true x or y

not True if operand is false (complements the operand) not x

Logical operators
Example:→ X Y R=X and Y X Y R=X or Y
x = True T T T T T T
y = False
print('x and y is', x and y) T F F T F T
print('x or y is', x or y) F T F F T T
print('not x is', not x)
Output F F F F F F
( x and y is False )
( x or y is True ) X R = not X
( not x is False )
T F
F T
Bitwise operators
These operators are used to manipulate bit values.
Operator Meaning Example
& Bitwise AND x& y Returns 1 if both the bits are 1 else 0.
| Bitwise OR x|y Returns 1 if either of the bit is 1 else 0.
~ Bitwise NOT ~x Returns one’s complement of the number.

^ Bitwise XOR x^y Returns 1 if one of the bits is 1 and the other is 0 else returns false (0).
Shifts the bits of the number to the right and fills 0 on voids left( fills 1 in the
>> Bitwise right shift x>> 2 case of a negative number) as a result. Similar effect as of dividing the
number with some power of two.
Shifts the bits of the number to the left and fills 0 on voids right as a result.
<< Bitwise left shift x<< 2
Similar effect as of multiplying the number with some power of two.
Bitwise operators continue Bitwise operators continue
>>> a, b, c= 6, 3, 0
>>> c = a ^ b
>>> print ('a=',a,':', bin(a), 'b=',b,':', bin( b) )
>>> print ("result of EXOR is ", c,':', bin(c))
>>> c = a & b
>>> c = ~a
>>> print ("result of AND is ", c,':', bin(c) )
>>> print ("result of COMPLEMENT is ",c,':‘, bin( c ) )
>>> c = a | b
>>> print ("result of OR is ", c,':', bin(c) )
Python Membership Operators
Test for membership in a sequence

Operator Description

in Evaluates to true if it finds a variable in the specified sequence and false otherwise.

not in Evaluates to true if it does not finds a variable in the specified sequence and false otherwise.

a= 5
b = 10
list = [1, 2, 3, 4, 5 ]
output
if ( a in list ):
Line 1 - a is available in the given list
print ("Line 1 - a is available in the given list") Line 2 - b is not available in the given list
else:
print ("Line 1 - a is not available in the given list")
if ( b not in list ):
print ("Line 2 - b is not available in the given list")
else:
print ("Line 2 - b is available in the given list")
Operators Precedence : Highest precedence to lowest precedence table
Operator Description

** Exponentiation (raise to the power)

~+- Complement, unary plus and minus (method names for the last two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction

>> << Right and left bitwise shift

& Bitwise 'AND'td>


^| Bitwise exclusive `OR' and regular `OR'

<= < > >= Comparison operators

<> == != Equality operators

= %= /= //= -= Assignment operators


+= * = **=
is is not Identity operators

in not in Membership operators

not or and Logical operators


Expression
It is a valid combination of operators,literals and variable.
 Arithmetic expression : e.g. c=a+b
 Relational expression : e.g. x>y
 Logical expression : a or b
 String expression : c = “comp” + ”sc”
Type conversion
 The process of converting the value of one data type (integer, string, float, etc.) to another data
type is called type conversion.
 Python has two types of type conversion.
Implicit Type Conversion
Explicit Type Conversion
Implicit Type Conversion:
In Implicit type conversion, Python automatically converts one data type to another data type. This
process doesn't need any user involvement.
Example:
num_int = 12 OUTPUT
num_flo = 10.23 ('datatype of num_int:', <type 'int'>)
num_new = num_int + num_flo ('datatype of num_flo: ', <type 'float' >)
('Value of num_new: ', 22.23)
print("datatype of num_int:",type(num_int))
('datatype of num_new: ', <type 'float' >)
print("datatype of num_flo:",type(num_flo))
print("Value of num_new:",num_new)
print("datatype of num_new:", type(num_new))
Explicit Type Conversion
In Explicit Type Conversion, users convert the data type of an object to required data type. We
use the predefined functions like int(),float(),str() etc.
Example:
num_int = 12 num_str = "45"
print("Data type of num_int:", type(num_int))
print("Data type of num_str before Type Casting:", type(num_str))
num_str = int(num_str)
print("Data type of num_str after Type Casting:", type(num_str))
num_sum = num_int + num_str
print("Sum of num_int and num_str:", num_sum)
print("Data type of the sum:", type(num_sum))
OUTPUT
('Data type of num_int:', <type 'int'>)
('Data type of num_str before Type Casting:', <type 'str'>)
('Data type of num_str after Type Casting:', <type 'int'>)
('Sum of num_int and num_str: ', 57)
('Data type of the sum:', <type 'int'>)
Using Python standard library function and modules
 Python’s standard library is very extensive that offers many built-in functions
that you can use without having to import any library.
 Python’s standard library is by default available, so you do not need to import it
separately.
 Python's standard library also offers, other than the built-in functions , some
modules for specialised type of functionality, such as math module for
mathematical function, random module for pseudo random number
generation, statistics module which provides mathematical statistics functions ,
urllib module for a functionality for adding and using websites’ address from
within program, etc. Python uses different categories of functions.
 Python’s Built-in functions
 Python’s Library Modules functions
 Python’s user defined functions
Importing modules in a Python program
 In Python, if you want to use the definitions inside a module, then you need to
first import the module in your program. Python provides import statement to
import modules in a program. The import statement can be used in three
ways :
1. To import entire module:
Syntax:→ import<module1, module2, …>
Example:→ import math, random
2. To import selected objects from a module:
Syntax:→ from< module> import <object/function name(s)>
Example:→ from math import sqrt, pow
3. Alias name (i.e. assumed name) to imported module
Syntax:→import <module name> as < alias name>
Example:→ import temp random as R
math module
It is a standard module in Python. To use mathematical functions of this module, we have to
import the module using import math.
Function Description Example
ceil(n) It returns the smallest integer greater than or equal to n. math.ceil(4.2) returns 5
factorial(n) It returns the factorial of value n math.factorial(4) returns 24
floor(n) It returns the largest integer less than or equal to n math.floor(4.2) returns 4
fmod(x, y) It returns the remainder when n is divided by y math.fmod(10.5,2) returns 0.5
exp(n) It returns e**n math.exp(1) return 2.718281828459045
log2(n) It returns the base-2 logarithm of n math.log2(4) return 2.0
log10(n) It returns the base-10 logarithm of n math.log10(4) returns 0.6020599913279624
pow(n, y) It returns n raised to the power y math.pow(2,3) returns 8.0
sqrt(n) It returns the square root of n math.sqrt(100) returns 10.0
cos(n) It returns the cosine of n math.cos(100) returns 0.8623188722876839
sin(n) It returns the sine of n math.sin(100) returns -0.5063656411097588
tan(n) It returns the tangent of n math.tan(100) returns -0.5872139151569291
pi It is pi value (3.14159...) It is (3.14159...)
e It is mathematical constant e (2.71828...) It is (2.71828...)
Example of Python expression using math module

1. Write the corresponding Python expressions for the following mathematical expression:
a) 𝒂𝟐 + 𝒃𝟐 + 𝒄𝟐 ➔ math.pow(a,2)+math.pow(b,2)+math.pow(c,2)
𝒑
b) log 𝟏𝟎 + 𝒒 ➔math.log(10)+p/q

c) 𝒂𝟐 + 𝒃 𝟐 ➔
Working with standard Random Module in Python
 Usage of the random module in Python →
 The random module provides access to functions that support many operations.
 Perhaps the most important thing is that it allows you to generate random
numbers.
 A random number in simple words means – a number generated by chance, i.e.
randomly.
 When to use it ?
 We want the computer to pick a random number in a given range.
 Pick a random element from a list, pick a random card from a deck, flip a coin
etc.
 When making your password database more secure or powering a random page
feature of your website.
Random functions from Random Module

 Random functions →The Random module contains some very


useful functions. You first need to import Module random using any
import command to use it’s functions.
1. randint()
2. random()
3. randrange()
4. choice()
Q1. randint() function

This function returns a random integer N in the range ( a, b) , i.e., a <= N <= b
( both range-limits are inclusive). Remember, it generates an integer.
Randint accepts two parameters: → a lowest and a highest number.
Generate integers between 1 , 5. The first value should be less than the second.
Example:- 1 To generate a random integer number in range 0 to 5.
import random
print(random.randint(0, 5))
This will output either 0 or 1 or 2 or 3 or 4 or 5.
Example:- 2 Find a random integer number between 15 to 35.
import random
print("random integer between 15 to 35 = " , random.randint (15 , 35) )
2. random() function
random() ➔ It returns or generates a random floating point number N in the
range (0.0, 1.0) , i.e. 0.0<= N < 1.0 .
 Remember that the number generated with random( ) will always be less
than 1.0 , (only lower range limit is inclusive).
 Note that , If you want a larger floating point number between range lower
to upper using random( ) :
 You multiply random( ) with difference of upper limit with lower limit i.e.
formula : (upper limit – lower limit)
 Then add the result with the lower limit .
Example →1 Find a random floating point number between 0.0 to 1.0 .
Sol n → Here, simply use random( ) to generate random floating point
number be tween 0.0 and 1.0.
import random
print(random.random())
Example: random() function
Example-2 Find a random number between 0 and 100.
import random
print(random.random() * 100)

Example-3 Find a random Floating point number between 15 to 35.


import random
print(‘random floating number between 15 to 35=‘, random.random()*(35-15)+15)
3. randrange() function
randrange() →This function is used to generate a random number in
three different ways:
i) Syntax :→ randrange(<stopvalue>)
 This function is used to generate a random number in the range 0 to
(stopvalue>
Example:
import random
print( random.randrange(15)
NB: It will generate random number in the range 0 to 15 including
lowest limit and highest limit.
Use of randrange() function - 2nd way
ii) Syntax :→ randrange(<start value> , <stop value>)
 This function is used to generate a random number in the range <start
value> to (stopvalue>
Example:
import random
print( random.randrange(5 , 15)
NB: It will generate random number in the range 5 to 15 including
lowest limit and highest limit.
Use of randrange() function - 3rd way
iii) Syntax :→ randrange(<start value> , <stop value> , < step value>)
 This function is used to generate a random number in the range <start
value> to (stop value> and the difference between two such
generated random numbers will be a multiple of <step value>.
Example:
import random
print( random.randrange(5 , 15 , 3)
NB: It will generate random number in the range 5 to 15 including
lowest limit and highest limit . It will generate any one of the following
values 5, 8, 11, 14.
Example : randint()
Q1. What could be the minimum possible and maximum possible
numbers by following code?
import random
Print( random.randint( 5 , 15 ) – 4)
Ans: → here,
minimum possible number =1
maximum possible number =11
statistics Module
 The statistics Module of the python Library provides many statistics
functions such as : mean() , median() , mode() , etc.
In order to use these functions , you need to first import the python
statistics Module .
Syntax:
i) statistics.mean(<seq>)
ii) statistics.median(<seq>)
iii) statistics.mode(<seq>)
Examples of statistics module functions
i) statistics.mean(<seq>) ➔ It returns the average value of the set/sequence
of values passed.
Example:
import statistics
SL=[5,4,3,8,6,5,4,2,4,9,4]
print(statistics.mean(SL))
ii) statistics.median(<seq>) ➔ It returns the middle value of the set/sequence
of values passed.
import statistics
SL=[5,4,3,8,6,5,4,2,4,9,4]
print(statistics.median(SL))
iii) statistics.mode(<seq>) ➔ It returns the most often repeated value of the
set/sequence of values passed.
import statistics
SL=[5,4,3,8,6,5,4,2,4,9,4]
print(statistics.mode(SL))
Bug and Debugging
What is Debugging?
 Debugging refers to the process of locating the place of error. cause of error,
and correcting the code accordingly.
What is Bug?
 An error causing disruption in a program’s running or in producing right output, is
called as program bug.
 Anything in the code that prevents a program from compiling and running
correctly.
 Errors and Exceptions, both disrupt a program and stop its execution. However,
errors and exception are not the same.
 Some program bugs are catastrophic( i.e terrible) in their effects, while others
are comparatively less harmful and still others are so unclear that you will ever
discover them.
 There are three types of errors :
 Compiler-Time Errors
 Run-Time Errors
 Logical errors
Compiler-Time Errors
Errors that occur during compile-time, are compile-time
errors.
when a program compiles, its source code is checked for
whether it follows the programming language’s rules or not.
Two types of errors fall into category of compile-time errors.
1.Syntax errors
2.Semantics errors
syntax errors
 syntax errors occur when rules of programming language are misused
i.e., when a grammatical rule python is violated.
 for example, observe the following two statements:
x<- y*x
if x=(x*y)
 These two statement will result in syntax errors as ‘<-‘ is not an
assignment operator in python ‘=’ is assignment operator, not a
relational operator.
 Also, if is a block statement, it require a colon (:) at the end of it, which
is missing above.
 correct statement is follows:
x = y*x
if x == (x*y):
semantics errors
 Semantics errors occur when statements are not meaningful. for
instance, the statement ‘Sita plays Guitar’ is syntactically correct (as
the grammar is correct) but semantically incorrect. similarly, there
are semantics rules of a programming language, violation of which
results in semantically errors.
 for instance, the statement
 x*y=z
 will result in a semantically error as an expression cannot come on
the left side of an assignment statement.
Run-Time Errors

 Errors that occur during the execution of a program are run-time


errors. these harder to detect.
 Some run-time errors stop the execution of the program which is
then called program “crashed” or “abnormally terminated”.
 Most run-time errors are easy to identify because program halts
when it encounter them e.g.,
 An infinite loop or wrong value (of different data type other than
required) is input.
Logical errors

 It occur when desired output not produced by program due to


incorrect implementation of logic or logarithm.
 Sometimes logical errors are treated as a subcategory of run-time
errors.
Exception
Exception:-
 an exception is an irregular unexpected situation which occur
during execution of program on which program has no control.
 let us try to understand the difference between an error and
exception with the help of real life example.
For instance, if you operate an ATM then
 entering wrong account number or wrong pin number is an ERROR.
 ‘not that much amount in account’ is an EXCEPTION.
 ‘ATM machine struck’ is also EXCEPTION.
How to DEBUG a program ?
Debugging techniques
 Debugging a program is a skill. there are many traditional debugging techniques
that you can follow to debug your code. these are :
(1) carefully spot the origin of error.
(2) print variable’s intermediate values.
(3) code tracing and stepping.
Using Debugging tool

Using Debugging tool:-


 debugging tool or debugger is specialized software that can be
used to test debug program. it can be integrated with IDE
(integrated development Environment) like sublime.
 python also provide a debugger program called as pdb(python
debugger).
Break points:-
 break point are temporary fault point or markers in program that
stop the debugger at marked point.
pdb:-
 pdb is a python debugger which can be used to trace or debug a
python program with help of its commands.
Q.1 Write a python program to read principal amount, rate of interest and time
from user and calculate the Simple interest
Hint : SI=(P x T x R)/100
P = float(input("Enter the Principal value: "))
T = float(input("Enter time period: "))
R = float(input("Enter Rate of interest: "))
SI = (P * T * R)/100
print(" The Simple interest = " , SI)

OUTPUT
Enter the Principal value: 2000
Enter time period: 5
Enter Rate of interest: 10
The Simple interest = 1000.0
Q.1 Write a python program to read length (L) , Width (W) and Height (H) of a parallelogram and
calculate its area and perimeter.
Hint : Area= Length x Height
Perimeter =2 x Length + 2x Width

L = float(input("Enter base/length of the parallelogram : "))


W = float(input("Enter width of the parallelogram : "))
H = float(input("Enter height of the parallelogram : "))
Area= L * H
Perimeter =2 * L + 2 * W
print(" The Area of the parallelogram = " , Area)
print(" The Perimeter of the parallelogram = " , Perimeter)

OUTPUT
Enter base/length of the parallelogram : 5
Enter width of the parallelogram : 4
Enter height of the parallelogram : 5
The Area of the parallelogram = 25.0
The Perimeter of the parallelogram = 18.0

You might also like