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

L4_Data Handling

The document provides an overview of Python's built-in data types, including Numbers, Strings, Lists, Tuples, and Dictionaries, along with their characteristics and operations. It explains mutable and immutable types, the significance of memory locations, and the use of various operators such as arithmetic, relational, and logical operators. Additionally, it covers comparisons between different data types and the behavior of truth values in Python.

Uploaded by

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

L4_Data Handling

The document provides an overview of Python's built-in data types, including Numbers, Strings, Lists, Tuples, and Dictionaries, along with their characteristics and operations. It explains mutable and immutable types, the significance of memory locations, and the use of various operators such as arithmetic, relational, and logical operators. Additionally, it covers comparisons between different data types and the behavior of truth values in Python.

Uploaded by

Arindam Gurung
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 75

Le4 DATA HANDLING

Python provides a predefined set of data types for handling the data it uses.
Data can be stored in any of these data types.
Lets discuss in more details.
Data Types
• Data Types are means to identify the type of data and associated
operations of handling it. Python offers following built-in datatypes:
1. Numbers (int, float, complex)
2. String Click to add text

3. List
4. Tuple
5. Dictionary
1.Number data types are used to store numeric values in python. It is further divided
into :
a) Integer : used to store whole number. Means no decimal. Integer can be
positive or negative Eg: 10, -7 etc. Further Integers are divided into :
-Integers signed or signed Integers: used to store numbers normal integers
i.e. whole nos. Integer can be any length, it is only limited by the memory available. The
integers can be +ve as well as –ve.
- Booleans : represents the truth values True or False. The Boolean type
values False/ True behave like values 0/1 i.e. False=0 and True=1.
To get the Boolean equivalent of 0 or 1 we can type bool(0) or bool(1)
EG:
• Further Boolean values True and False can be converted into string
i.e. ‘True’ and ‘False’. By using str( ) function.
• NOTE: str( ) function converts a value to string.
EG:
Floating Point nos: A number having fractional part is a floating-point
number. For eg: 3.14159 is floating-point number. The no. 12 is integer
but 12.0 is floating-point no.
In python, the floating point no. have precision of 15 digits.
ADVANTAGES: They can represent values between the integers.
They can represent a much greater range of values.

DISADVANTAGES: Floating-point nos are usually slower than integer


operations.
Fractional nos are further divided into two forms:
-Fractional form (normal decimal notation) i.e. 35.0075,3.15159
-Exponent Notation:EG: 3.500075E03, 0.5E-04, 1.456655E02
Complex Numbers: are in the form of A+Bi where i is the imaginary
number, equal to the square root of -1 i.e i2 =-1
BUT in python i is replaced with j or J. So A+Bj ( here j/J is imaginary no)
A and B are float numbers.
2. String data type:
-String can hold any type of character i.e. letters, numbers, special
characters of any known scripted language.
-any valid characters in quotation marks is a string.
-each character store in string is pure Unicode character.
-Unicode is a system designed to represent every character form every
language.
-Every character in string has index no.
Observe the strings carefully:
• Space is also consider as a part of string and has index no.
• Length of string ‘hello’ is 5 and ‘Monty Python’ is 12. Length means
no. of characters in the string including space or any character
• len() function is used to find the length of string.
EG : str1=“Hello”
print(len(str1)) o/p is 5
Str2=“Monty Python”
print (len(Str2)) o/p is 12
• Accessing single character from string
EG : str1=“Hello”
print(str1[0]) o/p is H
print (str1[-1]) o/p is o
print(str1[5]) ERROR index out of range
print(str1[-3]) o/p is l
• Trying to change a single character from string
EG : str1=“Hello”
str1[0] = ‘A’

ERROR ‘str’ object does not support item assignment


LISTS
• List is compound datatype.
• List data can be change i.e. mutable (means can add/delete/modify
element(s).
• List data is separated by comma(,)
• List data is represented in square brackets [ ].
• Eg1 a=[1, 2, 3, 4, 5]
b=[‘a’, ‘e’, ‘I’, ‘o’, ‘u’]
c=[‘Donna’, 102, 87.5]
0 1 2 {each item has index no. ,starts with 0}
Printing Lists
Indexes in Lists
Accessing elements of List
Adding an elements of List

Replacing an elements of List


Element 0th was Red and now its
Black

Deleting an elements of List


There are more ways to delete an
element will cover in next chapter
TUPLES
• Tuple is compound datatype.
• In Tuple, data cannot be changed i.e. immutable (means cannot
add/delete/modify element(s)) or NOT modifiable.
• Tuple data is separated by comma(,)
• Tuple data is represented in round brackets ( ).
• Eg1 a=(1, 2, 3, 4, 5)
b=(‘a’, ‘e’, ‘I’, ‘o’, ‘u’)
c=(‘Donna’, 102, 87.5)
0 1 2 {each item has index no. ,starts with 0}
DICTIONARY
• Dictionary is compound datatype.
• It is one of the datatype in python comes with Key:Value pair.
• Dictionary Key is immutable means cannot be modified. But dictionary
Value is mutable means can be modify.
• Dictionary data is separated by comma(,)
• Dictionary data is represented in curly brackets { }.
• Eg1

• Accessing elements from dictionary through key


Summary of core datatypes in
python
Mutable and Immutable types:
• What are Immutable types?
Definition of An immutable object is an object is whose value cannot changed in place
ie with respect to the computer memory.
Most python objects (booleans, integers, floats, strings, and tuples) are immutable.
This means that after you create the object and assign some value to it, you can’t
modify that value.
An object created and given a value is assigned some space in memory. The variable
name bound to the object points to that place in memory. Following figure shows the
memory locations of objects and what happens when you bind the same variable to a
new object using the expressions a=1 and a=2. The object with value 1 still exists in
memory, but you’ve lost the binding to it.
The variable named a is bound to an object
with value 1 in one memory location. When
the variable named a is bound to a
different object with value 2, the original
object with value 1 is still in memory, but
you can’t access it anymore through the
variable ‘a’.
• EG:
P
Q 5 1748891632
Memory ID
R

All variables are pointing to same location. Remember location no. is NOT
fixed.
NOTE: Python is an object oriented language so everything in python is an
object. So all variables are treated as an object.
id() function used on any data value/ variable returns the unique identity of
an object, which is assigned memory address.
• What are Mutable types?
Definition of Mutable object is an object is whose value can be changed in place.
Means in scene of the computer memory.
Lists, Dictionaries and sets are mutable types in python.
EG
Observe the memory location
of list, which remains the
same. Means the change
happens in same location.
Variable Internals
• Python is an Object Oriented Programming Language (OOPs)
• Every data stored in python is in the form of object.
• An object is an entity that has certain properties & that exhibits
a certain behaviour. EG: integer values are objects they hold
whole numbers only & they have infinite properties and
arithmetic behaviour.
• Similarly for all data types.
• Data type/ object has 3 key attributes:
Data type/ object has 3 key attributes:
Explain 3key attributes of variable
internals.
1) Type of an Object 2) Value of an object. 3)id of an object.
EG: EG: EG:
a=4 a=4 a=4
type(a) print(a) id(a)

o/p o/p o/p


<class ‘int’> 4 123456564
type() function is an print() function is used to Object 4 is internally
attribute and returns the print the value of an stored at location
type of an object object 123456564. id() function
returns the id of an object
ie memory location/
memory address
Program on id() function

Same memory location/ address


Operators: Operators are used to perform operations on variables and values. Means operators
are tokens that trigger some computation / action when applied to variable or values. Python
divides the operators in the following groups:
I) Unary Operators: are those operators that require one operand to operate upon. Following are
unary operator: EG +10 , -5
+ Unary Plus
- Unary Minus
II) Binary Operators : are those operators that require two operands to operate upon. Following are
some binary operators: EG: 10+2 , 5-2
• Arithmetic operators
• Assignment operators
• Relational operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
• Shift operators
Program on arithmetic operators
A=21
B=10
C=0
C=A+B
print(“+ operator”, C)
C=A-B
print(“- operator”, C)
C=A*B
print(“* operator”, C)
C=A/B
print(“/ operator”, C)
C=A//B #Floor division operator will display output by eliminating decimal
#values will NOT round up
print(“// operator”, C)
Program on arithmetic operators
A=21
B=10
C=0
C=A//B #Floor division operator will display output by eliminating
# decimal values will NOT round up
print(“// operator”, C)
C=A%B
print(“% operator”,C) #Modulus operator use to store/print remainder
x=2
y=3
z=x**y
print(“** operator”,z) #exponent/raised to operator xy i.e. 23 so O/p is 8
Negative number Arithmetic in
Python

Observe the output in the


rectangular box.
Difference between / and //
PG 92
EG 92
• WAP to input radius of circle and print the area. Use ** operator.
Comparing strings
• Strings are compared lexicographically (i.e. ordering in dictionary)
• Capital letters and small letters are treated differently.
• EG: ‘A’ is not equal to ‘a’
• Capital letters are considered lesser than small letters. Strings are case sensitive.

• ASCII (American Standard Code for Information Interchange)


• A-Z = 65 – 90
• a-z = 97-122
• 0-9 = 48-57
• Space (‘ ‘)= 32

• ord() function is used to find the ascii values of a character.


Program on comparison of Strings
Both Strings are equal so o/p is
True

Comparison is done between ascii


values and both are equal

_ has ascii value 95 and ‘A’ is 65

‘a’ has ascii value 97 and ‘A’ is 65


Comparison of Lists, Tuple and
Boolean

• Two lists and two tuples are equal if they have same elements in the
same order.
• Boolean True is equivalent to 1 and Boolean False is equivalent to 0
for comparison purpose.
Program on comparison of values
#Program
a=3
b=13
p=3.0 True
a<b
True
a==p
False
a==True #checks for truth value i.e. 1
True
0==False #truth values of 0 is False so o/p True

True
1==True
#Program 3
#Program 2 c,e='n','N' NOTE: small letters
x='a' f,g='god','God' are considered bigger
y=97 d,h='g','god' than capital. Length
False
print(c<g) False of string will not
x==y
False
matter here.
print(f<h)
True Here, small letter ‘g’
y==ord('a') True
print(f==h) has bigger ascii value
False than capital ‘G’.
p=5
print(c==e)
False
p==True True
print(g=='God‘)
True
p=1 print('God'<'God house‘)
True False
p==True print('god'<'God house‘)
Comparison of tuple and lists
#program 4 #program 5
L=[1,2,3] L=(1,2,3)
M=[2,4,6] M=(2,4,6)
N=[1,2,3] N=(1,2,3)
L==M False L==M False

True True
L==N L==N
NOTE:
• Floating-point numbers are presented in memory in binary form.
Conversion to binary is done internally. So the comparing floating
numbers may give different result.
• EG: 0.1+0.1+0.1==0.3 o/p is False
• As compiler converts the 0.1+0.1+0.1 into binary and calculated the
answer is also binary. And comparing it with 0.3 but as 0.1+0.1+0.1 is
not equal to 0.3
17digit precision is the result so the
o/p is False
Relational operators with Arithmetic operators
a=10 and c=20 so a+5=15 c-2 = 18
So 15 > 18 is False
And 15 < 18 is True

True results to 1 value


False results to 0 value
a=10 and c=20 so
a+(0)-2 = 8
a+(1)-2 = 9
What is the difference between
= and ==?
• In Python and many other programming languages,
a single equal mark (=) is used to assign a value to
a variable, whereas two consecutive equal marks is
used to check whether two expressions give
the same value.
• = is an assignment operator
• == is an equality operator (mostly used in if
condition)
EG : x=10 here, variable x has value 10
if(x==10) here check will happen whether x is 10
or not
if x=10 then condition is True else False
Identity operators

• There are 2 identity operators is and is not which refers to memory


location of variable or object.
• It is used to compare the memory locations of 2 objects and return
True or False.
• is operator returns true if both operands referring to same memory
location.
• is not operator returns true if both operands are NOT referring to
same memory location.
Observe the id() function of all variables.
Equality operator(==) & Identity operators(is) are different
• If == returns True may not necessary is operator will also return True.
• But if is operator will return True surely == operator will return True.

NOTE: When data


accepted from user
i.e. on console may
do not refer to same
memory location.
Equality operator(==) & Identity operators(is) are different
Logical operators (and, or, not)

• or operator combines two expressions, which make its operands. It


works in following ways: -
I) Relational expression as operands
II) Number/string/lists as operands

Before this we need to understand the truthiness of the value: next


slide
Understanding truth value and testing
• Every value/object in python has truthness.
• Python internally categorizes them as True/False
• Python considers following values False i.e. with truth-value as false
Values with truth value as False Value with truth value as true

1) None

2) False (Boolean value False)


Remaining all values are
3) Zero of any numeric type EG: 0 , 0.0, 0j considered as true

4) Any empty sequence:EG


‘ ‘ empty string i.e. nothing in string is empty not even space)
( ) empty tuple
[] empty list
5) Any empty mapping EG
{ } empty dictionary
Logical operators (or)
I) Relational expression as operands
The ‘or’ operator evaluates to True if either of its relational operands
evaluates to True; and False if both operands to False.
EG: Condition1 Condition2 Result
False False False

False True True

True False True

True True True

Eg: (4==4) or (5==8) results to True, as one condition is evaluates to true


(5>8) or (5<2) results to False, as both conditions is evaluates to false
Logical operators (or)
II) Number/string/lists as operands
In an expression x or y , if the 1st operand has falsetval , then return 2nd
operand y as the result, otherwise return x
X Y Result (X or Y)
false truth value false truth value Y

false truth value true truth value Y

true truth value false truth value X

true truth value true truth value X


Logical operators (or)
Means : lets 1st expression 0 returns false hence 2nd expression is
returned.
Operation Result

0 or 0 0 Here checks for xth operation as its 0 then yth value


is printed.
0 or 8 8 Remember 0th truth val is False

5 or 0.0 5

‘hello’ or ‘ ‘ hello

‘ ‘ or ‘Xyz’ Xyz

‘ ‘ or ‘ ‘ ‘‘ If 1st expression is false then goes to 2nd one


‘a’ or ‘b’ a
Logical operators (or)

NOTE:
1) ‘or’ operator checks for 1st operand and then 2nd operand.
2) If 1st operand is true then will NOT check for 2nd operand.
3) Will return result immediately if 1st operand is True.
Logical operators (and)

• and operator combines two expressions, which make its operands. It


works in following ways: -
I) Relational expression as operands
II) Number/string/lists as operands

Before this we need to understand the truthiness of the value: next


slide
Logical operators (and)
I) Relational expression as operands
The ‘and’ operator evaluates to True if both of its relational operands
evaluates to True; and False if either or both operands evaluates to False.
EG: Condition1 Condition2 Result
False False False

False True False

True False False

True True True

Eg: (4==4) and (5==5) results to True (4>3) and (5<8) results True
(4==8) and (5==5) results to False
Logical operators (and)
II) Number/string/lists as operands
In an expression x and y , if the 1st operand has falsetval , then return 1st
operand x as the result, otherwise return y
X Y Result (X and Y)
false truth value false truth value X

false truth value true truth value X

true truth value false truth value Y

true truth value true truth value Y


Logical operators (and)
Means : lets 1st expression is false then it will NOT go to 2nd expression.
Operation Result

0 and 0 0 1st expression is false it 0th truth value is False and


returns the xth value.
0 and 8 0

5 and 0.0 0.0

‘hello’ and ‘ ‘ ‘‘

‘ ‘ and ‘Xyz’ ‘‘

‘ ‘ and ‘ ‘ ‘‘ If 1st expression’s truth val is True the will returns Yth
val.
‘a’ and ‘b’ b
Logical operators (and)

NOTE:
1) ‘and’ operator checks for 1st operand and then 2nd operand.
2) If 1st operand is false then will NOT check for 2nd operand.
3) ‘and’ operator will test 2nd operand only if the 1st operand is True.
4) Will return result immediately if 1st operand is False.
Logical operators (not)
• The Boolean/logical not operator, works on single expression or
operand means it is a unary operator.
• The logical not operator negates or reverses the truth value of the
expression following it means if the expression is True or the truth
value, then not expression is False, and vice versa.
• It has lower priority than non-boolean operator, so not a==b is
interpreted as not(a==b), where as, a==not b is an syntax error.
Logical not operator can be represented using != operator
EG:
A=C=10
B=20
if(A!=B):
print(“A is not equal to B”)

o/p A is not equal to B


EGs
Chained comparison operators
• We can chain multiple comparison using shortened version of larger
boolean expression.
EG : 1<2 and 2<3 can be written as

EG: 11 <13 and 13>12 this statement is equivalent to the given below
Operator precedence
Like which operator will execute first like bodmas rule maths.
Refer to PG 104 (4.4.5)

Operator associativity means is the way python is going to calculate


nos.
All operators work left-to-right except exponentiation (* *) works right-
to-left.
Programs
(* *) operator works right-to-left BUT
if brackets are put then it works left-
to-right

right-to-left left-to-right

In short brackets are solved first


Expressions..atoms… read from TB
108
• EG 11 , 12, 13 from page 108,109

• String expressions are divided into two:


1) replication operator (* ) i.e. ‘hello’ * 2 o/p hellohello
s=‘Tea’
print(s*2) o/p TeaTea
This operator requires one string operand and one int operand

2) concatenation operator(+) i.e. ‘hello’ + ‘world’ o/p helloworld


print(s+s) o/pTeaTea
Type casting: changing the DT of some operand to
another operand.
• Type casting is divided into 2:
1) Implicit type casting(coercion) which is performed by the complier without
programmer’s intervention.
2) Explicit type conversion is user-defined conversion that forces an expression
to be of specific type. Type casting can done in following way
Click to add text
String converted to int and vice-versa.

Here int is explicitly converted to float.


i.e. x is and converted to float and vice-versa
• String cannot be converted into int here. Check the error.
Implicit type casting(PG110)
• EG 19, 20, 21 from PAGE 114,115
Working with math Module of python
• Some of the most popular mathematical functions are defined in
math module. These include trigonometric, logarithmic functions etc.
• math is python’s built-in library for math related functions that work
with all number types except for complex nos.
• Statement is used to import the math library is:
import math
• math.<function_name> statement helps to call function from math
module.
• In addition 2 mathematical constants are also defined in this module:

Will print constant pie value

Will print Euler’s no. & it is base of natural logarithm i.e.


constant e
1)math.ceil() return the integer by
rounding upto the next int
#Program on math module.

import math
print(math.ceil(100.1))
print(math.ceil(100.5))
print(math.ceil(47.5))
print(math.ceil(-45.17))
1)math.floor() return the integer by
eliminating the decimal part.
#Program on math module.

import math
print(math.floor(100.1))
print(math.floor(100.78))
print(math.floor(-100.1)) #goes back
print(math.pow(2,3)) #returns the 2 raised to 3 i.e. 8.0
print(math.sqrt(4)) #returns the sqrt of 4 i.e. 2.0

Read EGS from pg 117


EG22, 23

math.sqrt(math.pow(a,2)+math.pow(b,2)+math.pow(c,2))

You might also like