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

7.data Handling Notes

Uploaded by

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

7.data Handling Notes

Uploaded by

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

3.

1 Data Types in Python: Ch 03 – Data Handling

Data Handling: Python has Two data types:


1. Primitive Data Type (Numbers, String)
2. Collection Data Type (List, Tuple, Set, Dictionary)

1. Primitive Data Types:


a. Numbers: Number data types store numeric values.
There are three numeric types in Python:
 int
 float
 complex
Example:
w=1 # int
y = 2.8 # float
z = 1j # complex
integer: There are two types of integers in python:
 int
 Boolean
• int: int or integer, is a whole number, positive or negative, without decimals.
Example:
x=1
y = 35656222554887711
z = -3255522
Boolean: It has two values: True and False. True has the value 1 and False has the value 0.
Example:
>>> bool(0)
False
>>> bool(1)
True
>>> bool(‘ ‘)
False
>>> bool(-34)
True
>>> bool(34)
True
float: float or “floating point number” is a number, positive or negative, containing one or more
decimals. Float can also be scientific numbers with an “e” to indicate the power of 10.

Example:

x = 1.10
y = 1.0
z = -35.59

a = 35e3
b = 12E4
c = -87.7e100

complex: Complex numbers are written with a “j” as the imaginary part.

Example:

>>>x = 3+5j
>>>y = 2+4j
>>>z=x+y
>>>print(z)
5+9j
>>>z.real
5.0
>>>z.imag
9.0

Real and imaginary part of a number can be accessed through the attributes real and imag.

b. String: Sequence of characters represented in the quotation marks.

 Python allows for either pairs of single or double quotes. Example: ‘hello’ is the same as “hello” .
 Python does not have a character data type, a single character is simply a string with a length of 1.
 The python string store Unicode characters.
 Each character in a string has its own index.
 String is immutable data type means it can never change its value in place

3. Collection Data Type:

 List
 Tuple
 Set
 Dictionary
3.2 Mutable & Immutable Data Type: Ch 03 – Data Handling

 Mutable Data Type:


These are changeable. In the same memory address, new value can be stored.
Example: List, Set, Dictionary
 Immutable Data Type:
These are unchangeable. In the same memory address new value cannot be stored.
Example: integer, float, Boolean, string and tuple
3.3 Basic Operators in Python: Ch 03 – Data Handling

1. Arithmetic Operators
2. Relational Operator
3. Logical Operators
4. Bitwise operators
5. Assignment Operators
6. Other Special Operators
o Identity Operators
o Membership operators

i. Arithmetic Operators: To perform mathematical operations.

Example:
>>>x= -5
>>>x**2
>>> -25

ii. Relational Operators: Relational operators compare the values. It either returns True or False
according to the condition.
iii. Logical operators: Logical operators perform Logical AND, Logical OR and Logical NOT operations.

OPERATOR DESCRIPTION SYNTAX


and Logical AND: True if both the operands are true x and y
or Logical OR: True if either of the operands is true x or y
not Logical NOT: True if operand is false not x
Examples of Logical Operator:

The and operator: The and operator works in two ways:


a. Relational expressions as operands
b. numbers or strings or lists as operands

a. Relational expressions as operands:


X Y X and Y
False False False
False True False
True False False
True True True

>> 5 > 8 and 7 > 3


False
>>> (4==4) and (7==7)
True

b. numbers or strings or lists as operands:


In an expression X and Y, if first operand has false value, then return first operand X as a result, otherwise
returns Y.
X Y X and Y
False False X
False True X
True False Y
True True Y

0 and 0
0
>>> 0 and 6
0
>>> ‘a’ and ‘n’
’n’
>>> 6>9 and ‘c’+9>5 # and operator will test the second operand only if the first operand
False # is true, otherwise ignores it, even if the second operand is wrongThe or
operator: The or operator works in two ways:

a. Relational expressions as operands


b. numbers or strings or lists as operands

a. Relational expressions as operands:

X Y X or Y
False False False
False True True
True False True
True True True

>> 5>8 or 7>3


True
>>> (4==4) or (7==7)
True

b. numbers or strings or lists as operands:

In an expression X or Y, if first operand has true value, then return first operand X as a
result, otherwise returns Y.

X Y X or Y
False False Y
False True Y
True False X
True True X
>>>0 or 0 0
>>>0 or 6 6
>>>‘a’ or ‘n’ ’a’
>>>6<9 or ‘c’+9>5
# or operator will test the second operand only if the first operand
True

# is false, otherwise ignores it, even if the second operand is wrong


The not operator:
>>>not 6
False
>>>not 0
True
>>>not -7
False
Chained Comparison Operators:

>>> 4<5>3 is equivalent to >>> 4<5 and 5>3

True True

iv. Bitwise operators: Bitwise operators acts on bits and performs bit by bit operation

OPERATOR DESCRIPTION SYNTAX


& Bitwise AND x&y
| Bitwise OR x|y
~ Bitwise NOT x~y
^ Bitwise XOR x|y
>> Bitwise Right Shift x>>
<< Bitwise Left Shift x<<

Examples:

Let
a = 10
b=4
print(a & b)
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
print(a << 2)

Output:

0
14
-11
14
2
40
v. Assignment operators: Assignment operators are used to assign values to the variables.

OPERATOR DESCRIPTION SYNTAX


Assign value of right side of expression to
= x=y+z
left side operand
Add AND: Add right side operand with
a+=b
+= left side operand and
a=a+b
then assign to left operand
Add AND: Add right side operand with a-=b
-= left side operand and
then assign to left operand a=a-b
Multiply AND: Multiply right operand
a*=b
*= with left operand and then
a=a*b
assign to left operand
Divide AND: Divide left operand with
a/=b
/= right operand and then
a=a/b
assign to left operand
Modulus AND: Takes modulus using left
a%=b
%= and right operands and
a=a%b
assign result to left operand
Modulus AND: Takes modulus using left
a//=b
//= and right operands and
a=a//b
assign result to left operand
Exponent AND: Calculate exponent(raise
a**=b
**= power) value using
a=a**b
operands and assign value to left operand
Performs Bitwise AND on operands and
a&=b
&= assign value to left
a=a&b
operand
Performs Bitwise OR on operands and
a|=b
|= assign value to left
a=a|b
operand
Performs Bitwise xOR on operands and
a^=b
^= assign value to left
a=a^b
operand
Performs Bitwise right shift on operands
a>>=b
>>= and assign value to left
a=a>>b
operand
Performs Bitwise left shift on operands and a <<=b
<<= assign value to left
operand a=a << b

vi. Other Special operators: There are some special type of operators like-
a. Identity operators– is and is not are the identity operators both are used to check if
two values are located on the same part of the memory. Two variables that are equal
does not imply that they are identical.

is True if the operands are identical

is not True if the operands are not identical

Example:

Let
a1 = 3
b1 = 3
a2 = ‘PythonProgramming’
b2 = ‘PythonProgramming’
a3 = [1,2,3] b3 = [1,2,3] print(a1 is not b1)
print(a2 is b2) # Output is False, since lists are mutable.
print(a3 is b3)

Output:

False
True
False

Example:

>>>str1= “Hello”
>>>str2=input(“Enter a String :”)
Enter a String : Hello
>>>str1==str2 # compares values of string
True
>>>str1 is str2 # checks if two address refer to the same memory address
False

b. Membership operator – in and not in are the membership operators; used to test whether a value or variable
is in a sequence.

in True if value is found in the sequence


not in True if value is not found in the sequence

Example:
Let
x = ‘Digital India’
y = {3:’a’,4:’b’}
print(‘D’ in x)
print(‘digital’ not in x)
print(‘Digital’ not in x)
print(3 in y)
print(‘b’ in y)
Output:
True
True
False
True
False

3.4 Operator Precedence and Associativity:

Operator Precedence: It describes the order in which operations are performed when an
expression is evaluated. Operators with higher precedence perform the operation first.

Operator Associativity: whenever two or more operators have the same precedence, then
associativity defines the order of operations.

Core data types


• Numbers
• Strings
• Lists
• Dictionaries
• Tuples
• Files
• Sets
Numbers

• Can be integers, decimals (fixed precision), floating


points (variable precision), complex numbers etc.
• Simple assignment creates an object of number
type
such as:
•a=3
• b = 4.56
• Supports simple to complex arithmetic operators.
• Assignment via numeric operator also creates a
number object:
•c=a/b
• a, b and c are numeric objects.
• Try dir(a) and dir(b) . This command lists the
functions
available for these objects.
Strings

• A string object is a ‘sequence’, i.e., it’s a list of


items
where each item has a defined position.
• Each character in the string can be referred,
retrieved
and modified by using its position.
• This order id called the ‘index’ and always starts
with 0.

Strings … continued

• String objects support concatenation and repetition


operations.

Lists
• List is a more general sequence object that
allows the individual items to be of different
types.
• Equivalent to arrays in other languages.
• Lists have no fixed size and can be expanded
or contracted as needed.
• Items in list can be retrieved using the index.
• Lists can be nested just like arrays, i.e., you
can have a list of lists.
Lists
• Simple list:

• Nested list:

Dictionaries
• Dictionaries are unordered mappings of ’Name
: Value’ associations.
• Comparable to hashes and associative arrays
in other languages.
• Intended to approximate how humans
remember associations.
Files
• File objects are built for interacting with files on the
system.
• Same object used for any file type.
• User has to interpret file content and maintain
integrity.

Mutable vs. Immutable


• Numbers, strings and tuples are immutable i.,e
cannot be directly changed.
• Lists, dictionaries and sets can be changed in
place.

Tuples
• Tuples are immutable lists.
• Maintain integrity of data during program
execution.

Sets
• Special data type introduced since Python 2.4
onwards to support mathematical set theory
operations.
• Unordered collection of unique items.
• Set itself is mutable, BUT every item in the set
has to be an immutable type.
• So, sets can have numbers, strings and tuples
as items but cannot have lists or dictionaries as
items.
Expressions
• Python has following types of expression –

• Arithmetic Expressions like a+b, 5-4 etc.


• Relational Expressions like a>b, a==b etc.
• Logical Expressions like a>b and a>c , a or b etc.
• String Expressions like “Pankaj” + “Kumar” etc.
Type Casting

• As we know, in Python, an expression may be consists of


mixed datatypes. In such cases, python changes data types
of operands internally. This process of internal data type
conversion is called implicit type conversion.
• One other option is explicit type conversion which is like-
<datatype> (identifier)
For ex-
a=“4”
b=int(a)
Another ex-
If a=5 and b=10.5 then we can convert a to float.
Like d=float(a)
In python, following are the data conversion functions-
(1) int ( ) (2) float( ) (3) complex( ) (4) str( ) (5) bool( )

Working with math Module of Python

• Python provides math module to work for all mathematical


works. We need to write following statement in our program-
import math
output of this program will be 5.0
Taking Input in Python

• In Python, input () function is used to take input which takes input in the
form of string. Then it will be type casted as per requirement. For ex- to
calculate volume of a cylinder, program will be as-
DEBUGGING PROGRAMS
11.1 INTRODUCTION:
Errors in a program are known as ‘bugs’.
To remove the errors from a program, known as debugging.

11.2 TYPES OF ERRORS:

1. Compile Time Error

a. Syntax Error

b. Semantics Error

2. Run Time Error

3. Logical Error

1. Compile Time Error: Compile time errors are those errors that occur at the time
of compilation of the program.
There are two types of compile time errors:

a. Syntax Error: These errors occur due to violation of grammatical rules of


aprogramming language.

for example:

a=10

b=20

if a>b #Syntax error, : is missing

Print(“a is greater than b”) # Syntax error, P is capital in Print statement

b. Semantics Error: Semantic errors occur when the statements written in


the program are not meaningful.

Example:

a+b = c # expression cannot come on the left side of the assignment operator.

2. Run Time Error: Errors that occur during the execution or running the program
are known as run time errors. When a program “crashed” or “abnormally
terminated” during the execution, then this type errors are run time errors.

Example: When a loop executes infinite time.

a=1
while a<5: # value of a is always less than 5, infinite loop
print(a)

a=a-1

3. Logical Error: These types of errors occur due to wrong logic. When a program
successfully executes but giving wrong output, then it is known as logical error.

Example:
a=10
b=20
c=30
average=a+b+c/3 #wrong logic to find the average
print(average)

OUTPUT:
40.0

Exception handling in python:

Exception: The unusual and unexpected condition other than syntax or logical
errors,encountered by a program at the time of execution, is called exception.

The purpose of exception handling mechanism is to provide means to detect and


report an exceptional circumstance, so that appropriate action can be taken.

Exception handling in python can be done using try and except blocks.

Syntax:
try:
# Code that may generate an exception
except:
# Code for handling the exception
Example:
num1=int(input("Enter first number :"))
num2=int(input("Enter second number: "))
try:
r=num1/num2
print("Result is :", r)
except:
print("Divided by zero")

OUTPUT:

Enter first number :30


Enter second number: 0
Divided by zero

Steps to debug a program:

a. Carefully follow the syntax of a language


b. Spot the origin of error
c. Read the type of error and understand it well
d. Use intermediate print statements to know the value and type of a
variable
e. Trace the code carefully

END…..

You might also like