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

Unit-III Iot Systems- Logical Design Using Python

This document covers the logical design of IoT systems using Python, focusing on various Python data types and structures such as lists, tuples, dictionaries, and sets. It provides an introduction to Python, its features, and detailed explanations of data types, including examples for better understanding. The document also discusses control flow, functions, modules, packages, classes, file handling, and date/time operations.

Uploaded by

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

Unit-III Iot Systems- Logical Design Using Python

This document covers the logical design of IoT systems using Python, focusing on various Python data types and structures such as lists, tuples, dictionaries, and sets. It provides an introduction to Python, its features, and detailed explanations of data types, including examples for better understanding. The document also discusses control flow, functions, modules, packages, classes, file handling, and date/time operations.

Uploaded by

yashasvi khade
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 592

INTERNET OF THINGS (IoT)

UCSE0801

UNIT-III
IoT SYSTEMS – LOGICAL DESIGN USING
PYTHON
POINTS TO BE COVERED
• INTRODUCTION
• PYTHON DATA TYPES & DATA STRUCTURES
• CONTROL FLOW
• FUNCTIONS
• MODULES
• PACAKAGES
• CLASSES
• FILE HANDLING
• DATE/TIME OPERARTIONS

2
INTRODUCTION TO PYTHON

3
INTRODUCTION
• WHAT IS PYTHON LANGUAGE ?
• Python is general purpose interpreted, interactive, object
oriented and high level programming language.

4
FEATURES OF PYTHON
• SIMPLE AND EASY TO LEARN

• INTERPRETED AND INTERACTIVE

• OBJECT-ORIENTED

• PORTABLE

• SCALABLE

• EXTENDABLE

• GUI PROGRAMMING AND DATABASES

• BROAD STANDARD LIBRARY


5
PYTHON DATA TYPES

6
PYTHON DATA TYPES
• Python Data Types are used to define the type of a variable.

• It defines what type of data we are going to store in a


variable.

• The data stored in memory can be of many types.

• For example, a person's age is stored as a numeric value and


his or her address is stored as alphanumeric characters.
7
PYTHON DATA TYPES
• Python has various built-in data types :
• Numeric - int, float, complex
• String - str
• Sequence - list, tuple, range
• Binary - bytes, bytearray, memoryview
• Mapping - dict
• Boolean - bool
• Set - set, frozenset
• None - NoneType
8
PYTHON DATA TYPES
• NUMERIC

• It stores numeric values.

• Number object are created when you assign a value to them.

• a = 1, b = 2

• Python support 4 different numerical types


– int (signed integer)

– float (floating point real value)

– long (long integers both octal and hexadecimal)

– complex (complex numbers)


9
PYTHON DATA TYPES

10
PYTHON DATA TYPES
• EXAMPLE 1 – PRINTING NUMBERS

11
PYTHON DATA TYPES
• EXAMPLE 2 – PRINTING NUMBERS TYPE

12
PYTHON DATA TYPES
• EXAMPLE 3 – CONVERTING & PRINTING NUMBERS TYPE

13
PYTHON DATA TYPES
• STRING
• Strings in python are surrounded by either single quotation
marks (‘A‘), or double quotation marks (“A”).

• 'hello' is the same as "hello".

• You can display a string literal with the print() function

14
PYTHON DATA TYPES
• Subsets of strings can be taken using the slice operator ([] and
[:]) with indexes starting at 0 in the beginning of the string
and ending at -1.

• The plus (+) sign is the string concatenation operator.

• The asterisk (*) is the repetition operator.

15
PYTHON DATA TYPES

16
PYTHON DATA TYPES
• EXAMPLE

17
PYTHON DATA TYPES
• LIST

• Lists are used to store multiple items in a single variable.

• Lists are one of 4 built-in data types in Python used to store


collections of data, the other 3 are Tuple, Set, and Dictionary,
all with different qualities and usage.

• Lists are created using square brackets [].

18
PYTHON DATA TYPES
• EXAMPLE

19
PYTHON DATA TYPES
• LIST ITEMS

• ORDERED
• Ordered means that the items have a defined order, and that
order will not change.

• If you add new items to a list, the new items will be placed at
the end of the list.

20
PYTHON DATA TYPES
• LIST ITEMS

• CHANGEABLE

• The list is changeable, meaning that we can change, add, and


remove items in a list after it has been created.

• ALLOW DUPLICATES

• Since lists are indexed, lists can have items with the same
value.

21
PYTHON DATA TYPES
• EXAMPLE 1 : ADDING MULTIPLE ITEMS TO A LIST

22
PYTHON DATA TYPES
• EXAMPLE 2 : UPDATING ITEMS FROM A LIST

23
PYTHON DATA TYPES
• EXAMPLE 3 : DELETING ITEMS FROM A LIST

24
PYTHON DATA TYPES
• TUPLE
• A tuple is another sequence of data type that is similar to the
list.

• A tuple consists of a number of values separated by commas.


• The main differences between lists and tuples are, lists are
enclosed with brackets ([]) and their elements and size can be
changed, while tuples are enclosed in parentheses [()] and
cannot be updated.

• Tuples can be considered as read-only lists.


25
PYTHON DATA TYPES
• TUPLE

• Tuples are used to store multiple items in a single variable.

• Tuple is one of 4 built-in data types in Python used to store


collections of data, the other 3 are List, Set, and Dictionary,
all with different qualities and usage.

• A tuple is a collection which is ordered and unchangeable.

26
PYTHON DATA TYPES
• EXAMPLE 1 : REPRESENTING TUPLE

27
PYTHON DATA TYPES
• TUPLE ITEMS

• ORDERED
• Ordered means that the items have a defined order, and that
order will not change.

• UNCHANGEABLE

• The tuple is unchangeable, meaning that we cannot change,


add, and remove items in a tuple after it has been created.

28
PYTHON DATA TYPES
• TUPLE ITEMS

• ALLOW DUPLICATES
• Since tuple are indexed, tuple can have items with the same
value.

29
PYTHON DATA TYPES
• EXAMPLE 2 : CREATING TUPLE WITH ONE ITEM

30
PYTHON DATA TYPES
• EXAMPLE 3: TUPLE ITEMS – DATA TYPES

31
PYTHON DATA TYPES
• RANGE
• Python range() is an in-built function in Python which returns
a sequence of numbers starting from 0 and increments to 1
until it reaches a specified number.

32
PYTHON DATA TYPES
• We use range() function with for and while loop to generate a
sequence of numbers.

• Following is the syntax of the function:


• start: Integer number to specify starting position, (Its
optional, Default: 0)

• stop: Integer number to specify starting position (It's


mandatory)

• step: Integer number to specify increment, (Its optional,


Default: 1)
33
PYTHON DATA TYPES
• EXAMPLE 1:

34
PYTHON DATA TYPES
• EXAMPLE 2:

35
PYTHON DATA TYPES
• EXAMPLE 3:

36
PYTHON DATA TYPES
• DICTIONARY

• Dictionary in Python is an unordered collection of data


values.
• It is used to store data values like a map, which, unlike other
data types that hold only a single value as an element.

• Dictionary holds key : value pair.

• Key-value is provided in the dictionary to make it more


optimized.

37
PYTHON DATA TYPES
• In Python, a Dictionary can be created by placing a sequence
of elements within curly {} braces, separated by ‘comma’.

• Dictionary holds pairs of values, one being the Key and the
other corresponding pair element being its key : value.

• Values in a dictionary can be of any data type and can be


duplicated, whereas keys can’t be repeated and must be
immutable.
38
PYTHON DATA TYPES
• EXAMPLE 1 : REPRESENTING DICTIONARY

39
PYTHON DATA TYPES
• DICTIONARY ITEMS
• ORDERED OR UNORDERED ?
• As of Python version 3.7, dictionaries are ordered. In Python
3.6 and earlier, dictionaries are unordered.

• CHANGEABLE
• The dictionary is changeable, meaning that we can change,
add, and remove items in a dictionary after it has been
created.
40
PYTHON DATA TYPES
• DICTIONARY ITEMS

• DUPLICATES NOT ALLOWED

• Dictionary cannot have items with the same value.

41
PYTHON DATA TYPES
• BOOLEAN
• Python boolean type is one of built-in data types which
represents one of the two values either True or False.

• Python bool() function allows you to evaluate the value of any


expression and returns either True or False based on the
expression.

42
PYTHON DATA TYPES
• EXAMPLE 1 :

43
PYTHON DATA TYPES
• EXAMPLE 2 :

44
PYTHON DATA TYPES
• SET

• A set is an unordered collection of unique items.

• It is defined by separated by comma inside braces {}.


• It can have any number of items and they may be of different
types (integer, float, tuple, string etc.)

• Since items in set are unordered, we cannot perform set


operations like union, intersection, difference on two sets
using indexing and slicing.

45
PYTHON DATA TYPES
• EXAMPLE 1 : REPRESENTING SET

46
PYTHON DATA TYPES
• SET ITEMS

• UNORDERED
• Unordered means that the items do not have a defined order,
and that order.

• UNCHANGEABLE

• The set is unchangeable, meaning that we cannot change,


add, and remove items in a set after it has been created.

47
PYTHON DATA TYPES
• SET ITEMS

• DUPLICATES NOT ALLOWED

• Set cannot have items with the same value.

48
PYTHON DATA STRUCTURES

49
PYTHON DATA STRUCTURES
• LISTS
• TUPLES
• SETS
• DICTIONARIES

50
LISTS
• DEFINING LISTS

• ACCESSING VALUES IN LISTS

• UDATING LISTS

• BASIC LIST OPERATIONS

• BUILT-IN LIST FUNCTIONS

51
52
LISTS
• LIST

• Lists are used to store multiple items in a single variable.

• Lists are created using square brackets [].

• EXAMPLE

• Mylist = *“John”, ”Alice”, “Bob”, 1, 2, 3]

53
LISTS
• EXAMPLE

54
LISTS
• LIST ITEMS

• ORDERED
• Ordered means that the items have a defined order, and that
order will not change.

• If you add new items to a list, the new items will be placed at
the end of the list.

55
LISTS
• LIST ITEMS

• CHANGEABLE

• The list is changeable, meaning that we can change, add, and


remove items in a list after it has been created.

• ALLOW DUPLICATES

• Since lists are indexed, lists can have items with the same
value.

56
57
LISTS
• EXAMPLE 1 : ADDING MULTIPLE ITEMS TO A LIST

58
59
LISTS
• Lists respond to the + and * operators much like strings; they
mean concatenation and repetition, except that the result is a
new list, not a string.

60
LISTS

61
62
LISTS
• There are total 5 Built-in list functions

• len(list)

• max(list)

• min(list)

• list(seq)

• map(aFunction, aSequence)

63
LISTS
• len(list) – Gives the total length of the list

64
LISTS
• max(list) – Returns item from the list with maximum value

65
LISTS
• min(list) – Returns item from the list with minimum value

66
LISTS
• list(seq) – Returns a tuple into a list

67
LISTS
• map(aFunction, aSequence) – it applies a passed-in function
to each item in an iterable object and returns a list
containing all the function call results.

68
LISTS

69
LISTS

70
71
LISTS
• There are total 8 Built-in list methods (updating) functions
• append()
• count()
• remove()
• extend()
• reverse()
• insert()
• sort()
• pop()
72
LISTS
• append() – it appends an object obj passed to the existing
list.

73
LISTS
• count() – Returns how many times the object obj appears in
the existing list.

74
LISTS
• remove() – removes an object obj from the existing list.

75
LISTS
• extend() – Appends the contents in a sequence seq passed
to the existing list.

76
LISTS
• reverse() – Reverse object in a list

77
LISTS
• insert() – Returns a list with object obj inserted at the given
index

78
LISTS
• sort() – Sorts the item in a list & returns the list. If a function
is provided, it will compare using the function provided.

79
LISTS
• pop() – Removes or returns the last object from the list.

80
LISTS
• EXAMPLES
• Write a python program which accepts a sequence of comma-
separated numbers from user and generate a list and a tuple
with those numbers.

• Write a python program to display the first and last colors


from the input list.

• Write a python program to get a single string from two strings,


separated by a space and swap the first two characters of
each string.
81
LISTS
• EXAMPLES
• Write a python program which accepts a string and prints the
same string for 4 times. Each string should be printed on a
new line.

• Write a python program to accept 3 list as shown below:

• List1 = *‘Hello!’+

• List2 = *‘how are you?’+

• List3 = *‘Have a nice day….’+

82
83
TUPLE
• DEFINING TUPLE

• ACCESSING VALUES IN TUPLE

• BASIC TUPLE OPERATIONS

• BUILT-IN TUPLE FUNCTIONS

84
85
TUPLE
• TUPLE
• A tuple is another sequence of data type that is similar to the
list.

• A tuple consists of a number of values separated by commas.


• The main differences between lists and tuples are, lists are
enclosed with brackets ([]) and their elements and size can be
changed, while tuples are enclosed in parentheses [()] and
cannot be updated.

• Tuples can be considered as read-only lists.


86
TUPLE
• TUPLE

• Tuples are used to store multiple items in a single variable.

• Tuple is one of 4 built-in data types in Python used to store


collections of data, the other 3 are List, Set, and Dictionary,
all with different qualities and usage.

• A tuple is a collection which is ordered and unchangeable,


hence they are immutable.
87
TUPLE
• EXAMPLE 1 : REPRESENTING TUPLE

88
TUPLE
• TUPLE ITEMS

• ORDERED
• Ordered means that the items have a defined order, and that
order will not change.

• UNCHANGEABLE

• The tuple is unchangeable, meaning that we cannot change,


add, and remove items in a tuple after it has been created.

89
TUPLE
• TUPLE ITEMS

• ALLOW DUPLICATES
• Since tuple are indexed, tuple can have items with the same
value.

90
91
TUPLE
• EXAMPLE 2 : CREATING TUPLE WITH ONE ITEM

92
TUPLE
• EXAMPLE 3: TUPLE ITEMS – DATA TYPES

93
94
TUPLE
• Tuples respond to the + and * operators much like strings;
they mean concatenation and repetition here too, except that
the result is a new tuple, not a string.

95
TUPLE

96
97
TUPLE
• There are total 5 Built-in list functions

• len(tuple)

• max(tuple)

• min(tuple)

• tuple(seq)

98
TUPLE
• len(tuple) – Gives the total length of the tuple

99
TUPLE
• max(tuple) – Returns item from the tuple with maximum
value

100
TUPLE
• min(tuple) – Returns item from the tuple with minimum
value

101
TUPLE
• tuple(seq) – Returns a list into a tuple

102
SAMPLE PROGRAMS
• Write a python program to accept a filename from the user
and print its extension.

103
GUESS GAME
• Define the range of the numbers. By default, it’s 1-100 but you can change it as you prefer.
• Generate a random integer from the above range (1-100).
• Start the game by displaying the user a message saying “Guess the number from X to Y”. You may update
the message as you wish.
• Initialize a variable to 0 to count the total number of chances that the user has taken to guess the number
correctly.
• Write an infinite loop.
• Ask the user to guess the number.
• If the current guessed number is equal to the randomly generated number, then congratulate the user
with a message as you like. An example would be “-> Hurray! You got it in 5 steps!”.
• Break the loop after congratulating the user.
• If the current guessed number is less than the randomly generated number, then give a message to the
user saying “-> Your number is less than the random number” or a custom message having the same
meaning.
• If the current guessed number is greater than the randomly generated number, then give a message to the
user saying “-> Your number is greater than the random number” or a custom with the same meaning.
• Finally, increment the chances that the user has taken to guess.

104
105
SET
• DEFINING SET

• ACCESSING VALUES IN SET

• UDATING SET

• BASIC SET OPERATIONS

• BUILT-IN SET FUNCTIONS

106
SET
• SET

• A set is an unordered collection of unique items.

• It is defined by separated by comma inside braces {}.


• It can have any number of items and they may be of different
types (integer, float, tuple, string etc.)

• Since items in set are unordered, we cannot perform set


operations like union, intersection, difference on two sets
using indexing and slicing.

107
SET
• EXAMPLE 1 : REPRESENTING SET

108
SET
• SET ITEMS

• UNORDERED
• Unordered means that the items do not have a defined order,
and that order.

• UNCHANGEABLE

• The set is unchangeable, meaning that we cannot change,


add, and remove items in a set after it has been created.

109
SET
• SET ITEMS

• DUPLICATES NOT ALLOWED

• Set cannot have items with the same value.

110
111
SET

112
113
SET
• SET UNION

• SET INTERSECTION

• SET DIFFERENCE

• SET SYMMETERIC DIFFERENCE

114
SET
• SET UNION –union()
• The union of two sets is the set of all the elements of both the
sets without duplicates.

• We can use union() or | symbol to find the set intersection.

115
SET

116
SET
• SET INTERSECTION – intersection()
• The intersection of two sets is the set of all the common
elements of both the sets.

• We can use intersection() or & symbol to find the set


intersection.

117
SET

118
SET
• SET DIFFERENCE – difference()
• The difference of two sets is the set of all the elements that
are not present in second set.

• We can use difference() or - symbol to find the set difference.

119
SET

120
SET
• SET SYMMETRIC DIFFERENCE – symmetric_difference()
• The symmetric difference of two sets is the set of all the
elements that are either in the first set or second set but
both.

• We can use symmetric_difference() or ^ symbol to find the


set symmetric difference.

121
SET

122
123
SET
• SET BUILT IN FUNCTIONS (8)
• len(set)
• max(set)
• min(set)
• sum(set)
• sorted(set)
• enumerate(set)
• any(set)
• all(set)
124
SET
• len(set) – Returns the length or total number of items in a set

125
SET
• max(set) – Returns item from the set with maximum value.

126
SET
• min(set) – Returns item from the set with minimum value.

127
SET
• sum(set) – Returns the sum of all items in the set.

128
SET
• sorted(set) – Returns a new sorted set.

129
SET
• enumerate(set) – Returns an enumerate object. It contains
the index and value of all the items of set as a pair.

130
SET
• any(set) – Returns True, if the set contains at least one item,
false otherwise.

131
SET
• all(set) – Returns True, if all the elements are true or the set is
empty.

132
133
SET
• SET BUILT IN METHODS (11)
• set.add(obj)
• set.remove(obj)
• set.discard(obj)
• set.pop()
• set1.update(set2)
• set1.intersection_update(set2)
• set1. difference_update(set2)
• set1. symmetric_difference_update(set2)
134
SET
• SET BUILT IN METHODS (11)

• set1.isdisjoint(set2)

• set1.issubset(set2)

• set1.issuperset(set2)

135
SET
• set.add(obj) – Adds a element to a set

136
SET
• set.remove(obj) – Removes a element from the set

137
SET
• set.discard(obj) – Discards a element from the set

138
SET
• set.pop(obj) – Removes and returns an arbitrary set element.

139
SET
• set1.update(set2) – Update a set with the union of itself and
others.

140
SET
• set1.intersection_update(set2) – Update a set with the
intersection of itself and other.

141
SET
• set1.difference_update(set2) – Removes all elements of
another set (set2) from current set (set3) and the result is
strode in current set (set1)

142
SET
• set1.symmetric_difference_update(set2) – Update a set with
symmetric difference of itself and another.

143
SET
• set1.isdisjoint(set2) – Returns True if two sets have a null
intersection.

144
SET
• set1.issubset(set2) – Returns True if set1 is subset of set2.

145
SET
• set1.issuperset(set2) – Returns True if set1 is superset of set2.

146
147
DICTIONARY
• DEFINING DICTIONARY

• ACCESSING VALUES IN DICTIONARY

• UDATING DICTIONARY

• BASIC DICTIONARY OPERATIONS

• BUILT-IN DICTIONARY FUNCTIONS

148
DICTIONARY
• DICTIONARY
• Dictionary in Python is an unordered collection of data
values.

• It is used to store data values like a map, which, unlike other


data types that hold only a single value as an element.

• Dictionary holds key : value pair.

• Key-value is provided in the dictionary to make it more


optimized.

149
DICTIONARY
• DICTIONARY
• In Python, a Dictionary can be created by placing a sequence
of elements within curly {} braces, separated by ‘comma’.

• Dictionary holds pairs of values, one being the Key and the
other corresponding pair element being its key : value.

• Values in a dictionary can be of any data type and can be


duplicated, whereas keys can’t be repeated and must be
immutable.

150
DICTIONARY
• EXAMPLE 1 : REPRESENTING DICTIONARY

151
DICTIONARY
• DICTIONARY ITEMS
• ORDERED OR UNORDERED ?
• As of Python version 3.7, dictionaries are ordered. In Python
3.6 and earlier, dictionaries are unordered.

• CHANGEABLE
• The dictionary is changeable, meaning that we can change,
add, and remove items in a dictionary after it has been
created.
152
DICTIONARY
• DICTIONARY ITEMS

• DUPLICATES NOT ALLOWED

• Dictionary cannot have items with the same value.

153
154
DICTIONARY
• DICTIONARY OPERATIONS • DICTIONARY OPERATIONS

• Definition Operations • Immutable Operations

– Empty dictionary {} • These operations allow us to


work with dictionaries without
altering or modifying their
• Mutable Operations previous definition.
• These operations allow us to – len
work with dictionaries, but – keys
altering or modifying their – values
previous definition. – items
– [] – in
– del – get
– update – set default
155
DICTIONARY
• DEFINITION OPERATIONS
• Empty dictionary {} - Creates an empty dictionary or a
dictionary with some initial values.

156
DICTIONARY
• MUTABLE OPERATIONS
• [ ] - Adds a new pair of key and value to the dictionary, but in case that
the key already exists in the dictionary, we can update the value.

157
DICTIONARY
• MUTABLE OPERATIONS
• del - Del statement can be used to remove an entry (key-value pair) from
a dictionary.

158
DICTIONARY
• MUTABLE OPERATIONS
• update - This method updates a first dictionary with all the key-value
pairs of a second dictionary.

159
DICTIONARY
• IMMUTABLE OPERATIONS

• len - Returns the number of entries (key-value pairs) in a dictionary.

160
DICTIONARY
• IMMUTABLE OPERATIONS

• keys - This method allows you to get all the keys in the dictionary.

161
DICTIONARY
• IMMUTABLE OPERATIONS
• values - This method allows you to obtain all the values stored in a
dictionary.

162
DICTIONARY
• IMMUTABLE OPERATIONS
• items - Returns all the keys and their associated values as a sequence of
tuples.

163
DICTIONARY
• IMMUTABLE OPERATIONS
• in - We can use the in method that test whether a key exists in a
dictionary, returns True if a dictionary has a value stored under the given
key and False otherwise.

164
DICTIONARY
• IMMUTABLE OPERATIONS
• get - Returns the value associated with a key if the dictionary contains
that key, in case that the dictionary does not contain the key, you can
specified a second optional argument to return a default value, if the
argument is not included get method will return None.

165
DICTIONARY
• IMMUTABLE OPERATIONS
• setdefault - This method is similar to get method, it returns the value
associated with a key if the dictionary contains that key, but in case that
the dictionary does not contain the key, this method will create a new
element in the dictionary (key-value pair), where the first argument in this
method is the key, and the second argument is the value. The second
argument is optional, but if this is not included, the value will be None.

166
DICTIONARY
• IMMUTABLE OPERATIONS

167
168
DICTIONARY
• BUILT-IN FUNCTIONS

• len(dict)

• str(dict)

• type(variable)

169
DICTIONARY
• BUILT-IN FUNCTIONS
• str(dict) – Produce a printable string representation of the
dictionary.

170
DICTIONARY
• BUILT-IN FUNCTIONS

• type(variable) – It returns the type of the passed variable.

171
172
DICTIONARY
• dict.clear()

• dict.copy()

• dict.keys()

• dict.values()

• dict.items()

• dict1.update(dict2)

• dict.has_key(key)

• dict.get(key,default=None)

• dict.setdefault(key,default=None)

• dict.fromkeys(seq,[val])
173
DICTIONARY
• BUILT-IN METHODS

• dict.clear() – Remove all elements of dictionary.

174
DICTIONARY
• BUILT-IN METHODS

• dict.copy() – Returns a copy of dictionary.

175
DICTIONARY
• BUILT-IN METHODS

• dict.has_key(key) – Returns True if key is present, else False.

176
DICTIONARY
• BUILT-IN METHODS
• dict.fromkeys(seq,[val]) – Creates a new dictionary from
sequence and values.

177
178
INTRODUCTION
• WHAT ARE OPERATORS ?
• Operators are the constructs which can manipulate the value
of operands.

• Consider the expression a = b + c

• Here a, b and c are called as operands and ‘+’, ‘=‘ is called as


operators.

179
180
TYPES OF OPERATORS
• ARITHMETIC OPERATORS

• COMPARISION (RELATIONAL) OPERATORS

• ASSIGNMENT OPERATORS

• LOGICAL OPERATORS

• BITWISE OPERATORS

• MEMBERSHIP OPERATORS

• IDENTITY OPERATORS

• OPERATOR PRECEDENCE
181
TYPES OF OPERATORS
• ARITHMETIC OPERATORS
• Arithmetic operators are used for performing mathematical
operations like
• Addition ( + )
• Subtraction ( - )
• Multiplication ( * )
• Division ( / )
• Modulus ( % )
• Exponent ( ** )
• Floor Division ( // )
182
TYPES OF OPERATORS
• ARITHMETIC OPERATORS

183
TYPES OF OPERATORS
• REPRESENTING ARITHMETIC OPERATORS

184
TYPES OF OPERATORS
• COMPARISION (RELATIONAL) OPERATORS

• Comparison of Relational operators compares the values.

• It either returns True or False according to the condition.

185
TYPES OF OPERATORS
• COMPARISION (RELATIONAL) OPERATORS

186
TYPES OF OPERATORS
• REPRESENTING COMPARISION OPERATORS

187
TYPES OF OPERATORS
• ASSIGNMENT OPERATORS
• Assignment operators are used to assigning values to the
variables.

188
TYPES OF OPERATORS
• ASSIGMENT OPERATORS

189
TYPES OF OPERATORS
• REPRESENTING ASSIGNMENT OPERATORS

190
TYPES OF OPERATORS
• LOGICAL OPERATORS

• Logical operators perform

– Logical AND,

– Logical OR,

– Logical NOT operations.

• It is used to combine conditional statements.

191
TYPES OF OPERATORS
• LOGICAL OPERATORS

192
TYPES OF OPERATORS
• REPRESENTING LOGICAL OPERATORS

193
TYPES OF OPERATORS
• BITWISE OPERATORS
• Bitwise operators act on bits and perform the bit-by-bit
operations.

• These are used to operate on binary numbers (0 AND 1).

194
TYPES OF OPERATORS
• BITWISE OPERATORS

195
TYPES OF OPERATORS
• REPRESENTING BITWISE OPERATORS

196
TYPES OF OPERATORS
• MEMBERSHIP OPERATORS
• Membership operators are in and not in, which are used to
test whether a value or variable is in a sequence.

197
TYPES OF OPERATORS
• MEMBERSHIP OPERATORS

198
TYPES OF OPERATORS
• REPRESENTING MEMBERSHIP OPERATORS

199
TYPES OF OPERATORS
• 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 do not imply that they are
identical.

200
TYPES OF OPERATORS
• IDENTITY OPERATORS

201
TYPES OF OPERATORS
• REPRESENTING IDENTITY OPERATORS

202
TYPES OF OPERATORS
• OPERATOR PRECEDENCE
• Operator Precedence is used in an expression with more than
one operator with different precedence to determine which
operation to perform first.

• Operator Precedence determines the priorities of the


operator.

203
TYPES OF OPERATORS

10 + 20 * 30 is calculated as 10 + (20 * 30)


and not as (10 + 20) * 30 204
TYPES OF OPERATORS
• REPRESENTING OPERATOR PRESEDENCE

205
206
FLOW CONTROL
• A program’s control flow is the order in which the program’s
code executes.

• The control flow of a Python program is regulated by


conditional statements, loops, and function calls.

• Python has three types of control structures:

• Sequential - default mode

• Selection - used for decisions and branching


• Repetition - used for looping, i.e., repeating a piece of code
multiple times.
207
FLOW CONTROL
• 1. SEQUENTIAL

• Sequential statements are a set of statements whose


execution process happens in a sequence.

• The problem with sequential statements is that if the logic has


broken in any one of the lines, then the complete source code
execution will break.

208
FLOW CONTROL
• REPRESENTING SEQUENTIAL FLOW

209
FLOW CONTROL
• 2. SELECTION / DECISION CONTROL STATEMENTS

• In Python, the selection statements are also known as


Decision control statements or branching statements.

• The selection statement allows a program to test several


conditions and execute instructions based on which
condition is true.

210
FLOW CONTROL
• 2. SELECTION / DECISION CONTROL STATEMENTS

• Some Decision Control Statements are:

• Simple if

• if-else

• nested if

• if-elif-else

211
FLOW CONTROL
• SIMPLE IF
• If statements are control flow statements that help us to run a particular
code, but only when a certain condition is met or satisfied. A simple if only
has one condition to check.

Syntax

If test expression:
statement(s)

212
FLOW CONTROL
• REPRESENTING SIMPLE IF

213
FLOW CONTROL
• EXAMPLE
• Write a program using if condition to check password is 123456789. if
password is 123456789, then print “Access Granted”.

• TAKE INPUT FROM USER

214
FLOW CONTROL
• IF-ELSE
• The if-else statement evaluates the condition and will execute the body of
if, if the test condition is True, but if the condition is False, then the body
of else is executed.

Syntax

if test expression:
Body of if
else:
Body of else

215
FLOW CONTROL
• REPRESENTING IF-ELSE

216
FLOW CONTROL
• EXAMPLE
• Write a program using if-else condition to check password is 123456789. if
password is 123456789, then print “Access Granted” else print “Access
Denied”

• TAKE INPUT FROM USER

217
FLOW CONTROL
• NESTED IF
• Nested if statements are an if statement inside another if statement.

218
FLOW CONTROL
• REPRESENTING NESTED-IF

219
FLOW CONTROL
• IF-ELIF-ELSE
• The if-elif-else statement is used to conditionally execute a statement or a
block of statements.

Syntax

if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else

220
FLOW CONTROL
• REPRESENTING IF-ELIF-ELSE

221
FLOW CONTROL
• EXAMPLE
• Write a program using if-elif-else condition to check the number is +ve, -ve
or zero

• TAKE INPUT FROM USER

222
FLOW CONTROL
• 3. REPETATION
• A repetition statement is used to repeat a group(block) of
programming instructions.

• In Python, we generally have two loops/repetitive statements:

• for loop

• while loop

223
FLOW CONTROL
• FOR LOOP
• A for loop is used to iterate over a sequence that is either a list, tuple,
dictionary, or a set. We can execute a set of statements once for each item
in a list, tuple, or dictionary.

Syntax

for item in sequence:


Body of for

224
FLOW CONTROL
• REPRESENTING FOR LOOP

225
FLOW CONTROL
• REPRESENTING FOR LOOP USING range() FUNCTION

226
FLOW CONTROL
• REPRESENTING FOR LOOP WITH ELSE

227
FLOW CONTROL
• EXAMPLES
• Write a program using for loop to display all letters from the
word ‘Program’

• Write a program using for loop and range() function to display


all flowers from a list.

• Write a program using for loop and if-else, to find the location
of the fruit (apple, mango, banana, cherry)
228
FLOW CONTROL
• WHILE LOOP
• In Python, while loops are used to execute a block of
statements repeatedly until a given condition is satisfied.

• Then, the expression is checked again and, if it is still true, the


body is executed again.

• This continues until the expression becomes false.

229
FLOW CONTROL
• WHILE LOOP

Syntax

while test expression:


Body of while

230
FLOW CONTROL
• REPRESENTING WHILE LOOP

231
FLOW CONTROL
• REPRESENTING WHILE LOOP USING ELSE

232
FLOW CONTROL
• EXAMPLES
• Write a program using while loop to find the sum of first 5
natural numbers.

• Write a program using while loop and if-else to display a string


on screen for only one time.

233
FLOW CONTROL
• NESTED LOOPS

• Placing a loop inside another loop is called as nested loop.

• Nested loops can be used for both while and for loop.

Syntax for nested for loop Syntax for nested while loop

for iterating_variable in sequence: while expression:


for iterating_variable in sequence: while expression:
statements(s) statements(s)
statements(s) statements(s)
234
FLOW CONTROL
• REPRESENTING NESTED LOOP USING FOR LOOP

235
FLOW CONTROL
• REPRESENTING NESTED LOOP USING WHILE LOOP

236
FLOW CONTROL
• REPRESENTING NESTED LOOP USING WHILE LOOP

237
238
LOOP MANIPULATION
• CONTROL STATEMENTS
• Control statements change the execution from normal
sequence.

• These are used to terminate the current iteration or even the


whole loop without checking test expression.

239
LOOP MANIPULATION
• CONTROL STATEMENTS

• Python supports 3 control statements

• break

• continue

• pass

240
LOOP MANIPULATION
• BREAK CONTROL STATEMENTS

• The break statement terminates the loop containing it.

• Control of the program flows to the statement immediately


after the body of the loop.

• If the break statement is inside a nested loop (loop inside


another loop), the break statement will terminate the
innermost loop.
241
LOOP MANIPULATION

242
FLOW CONTROL
• REPRESENTING BREAK CONTROL STATEMENT

243
LOOP MANIPULATION

244
FLOW CONTROL
• EXAMPLES

• Write a program for displaying a particular letter from word


‘Python’ using break statement.

245
LOOP MANIPULATION
• CONTINUE CONTROL STATEMENTS
• The continue statement is used to skip the rest of the code
inside a loop for the current iteration only.

• Loop does not terminate but continues on with the next


iteration.

246
LOOP MANIPULATION

247
FLOW CONTROL
• REPRESENTING CONTINUE CONTROL STATEMENT

248
LOOP MANIPULATION

249
FLOW CONTROL
• EXAMPLES

• Write a program for displaying a letters from word ‘Python’


using continue statement.

250
LOOP MANIPULATION
• PASS CONTROL STATEMENTS

• Pass statement is used to write empty loops.

• Pass is also used for empty control statement, function and


classes.

251
FLOW CONTROL
• REPRESENTING PASS CONTROL STATEMENT

252
253
254
PYTHON BUILT-IN FUNCTIONS
• Functions like input(), print() etc. are examples of built-in
functions.

• The code of these functions are already defined.

• These are called as built-in functions.

255
256
PYTHON BUILT-IN FUNCTIONS
• Python defines type conversion functions to directly convert
one data type to another.

• There are two types of Type Conversion in Python:

• Implicit Type Conversion

• Explicit Type Conversion

257
PYTHON BUILT-IN FUNCTIONS
• IMPLICIT TYPE CONVERSION
• In this conversion, the Python interpreter automatically
converts one data type to another without any user
involvement.

258
PYTHON BUILT-IN FUNCTIONS
• EXAMPLE

259
PYTHON BUILT-IN FUNCTIONS
• EXPLICIT TYPE CONVERSION
• In this conversion, the data type is manually changed by the
user as per their requirement.

• Various forms of explicit type conversion are explained below:


• int(a, base): This function converts any data type to integer.
‘Base’ specifies the base in which string is if the data type is a
string.

• float(): This function is used to convert any data type to a


floating-point number
260
PYTHON BUILT-IN FUNCTIONS
• EXAMPLE

261
PYTHON BUILT-IN FUNCTIONS
• EXPLICIT TYPE CONVERSION

• ord() : This function is used to convert a character to integer.

• hex() : This function is to convert integer to hexadecimal


string.

• oct() : This function is to convert integer to octal string

262
PYTHON BUILT-IN FUNCTIONS
• EXAMPLE

263
PYTHON BUILT-IN FUNCTIONS
• EXAMPLE

264
PYTHON BUILT-IN FUNCTIONS
• EXPLICIT TYPE CONVERSION
• complex(real,imag) : This function converts real numbers to
complex(real,imag) number.

• chr(number): This function converts number to its


corresponding ASCII character.

265
PYTHON BUILT-IN FUNCTIONS
• EXAMPLE

266
PYTHON BUILT-IN FUNCTIONS
• EXAMPLE

267
268
PYTHON BUILT-IN FUNCTIONS

269
270
USER DEFINED FUNCTIONS
• INTRODUCTION
• FUNCTION DEFINING
• FUNCTION CALLING
• FUNCTION ARGUMENTS
• SCOPE OF VARIABLES

271
272
USER DEFINED FUNCTIONS
• INTRODUCTION

• When we create our own functions to perform a particular


task are called as user defined functions.

273
274
USER DEFINED FUNCTIONS
• RULES FOR DEFINING USER DEFINED FUNCTIONS

• Function block or Function header begins with the keyword


def followed by the function name and parentheses (()).

• Any input parameter or arguments should be placed within


these parentheses. We can also define parameters inside
these parameters.

275
USER DEFINED FUNCTIONS
• RULES FOR DEFINING USER DEFINED FUNCTIONS
• The first string after the function header is called the
doctstring and is short for documentation string. It is used to
explain in brief, what a function does.

• The code block within every function starts with a colon (:)
and is intended.

276
USER DEFINED FUNCTIONS
• RULES FOR DEFINING USER DEFINED FUNCTIONS
• The return statement [expression] exits a function, optionally
passing back an expression to the caller.

• A return statement with no arguments is the same as return


none.

277
USER DEFINED FUNCTIONS
• SYNTAX

def functionname ( parameters ):

“function_doctstring”

function_suite

return [expression]

278
USER DEFINED FUNCTIONS
• EXAMPLE

279
280
USER DEFINED FUNCTIONS
• After defining a function, we call the function from another
function or directly from the python prompt.

• The order of parameters specified in the function definition


should be preserved in function call also.

281
USER DEFINED FUNCTIONS
• EXAMPLE - 1

282
USER DEFINED FUNCTIONS
• EXAMPLE - 2

283
284
USER DEFINED FUNCTIONS
• ARGUMENTS

• Information can be passed into functions as arguments.

• Arguments are specified after the function name, inside the


parentheses.

• You can add as many arguments as you want, just separate


them with a comma.

285
USER DEFINED FUNCTIONS
• We can call the function by any 4 arguments.

• Required Arguments

• Keyword Arguments

• Default Arguments

• Variable-Length Arguments

286
USER DEFINED FUNCTIONS
• REQUIRED ARGUMENTS
• These arguments are passed to a function in correct positional
order.

• Here, the number of arguments in the function call should


match exactly with the functional definition.

287
USER DEFINED FUNCTIONS
• EXAMPLE

288
USER DEFINED FUNCTIONS
• KEYWORD ARGUMENTS
• By using these arguments in a function call, the caller
identifies the arguments by the parameter name.

• This allows us to skip arguments or place them out of order


because the Python interpreter is able to use the keywords
provided to match the values with parameters.

289
USER DEFINED FUNCTIONS
• EXAMPLE

290
USER DEFINED FUNCTIONS
• DEFAULT ARGUMENTS
• A default argument is an argument that assumes a default
value if a value is not provided in function call for that
argument.

291
USER DEFINED FUNCTIONS
• EXAMPLE

292
USER DEFINED FUNCTIONS
• VARIABLE-LENGTH ARGUMENTS
• In some cases we may need to process a function for more
arguments than specified while defining the function.

• These arguments are called as variable-length arguments and


are not named in function definition.

• An asterisk (*) is placed before the variable name that holds


the values of all non-keyword variable arguments.

• This tuple remains empty if no additional arguments are


specified during the function call.
293
USER DEFINED FUNCTIONS
• EXAMPLE

294
USER DEFINED FUNCTIONS

295
296
USER DEFINED FUNCTIONS
• SCOPE OF VARIABLES
• In programming languages, variables need to be defined
before using them.

• These variables can only be accessed in the area where they


are defined, this is called scope.

• You can think of this as a block where you can access


variables.
297
USER DEFINED FUNCTIONS
• TYPES PYTHON VARIABLES SCOPE

• There are four types of variable scope in Python

• LOCAL SCOPE

• GLOBAL SCOPE

• ENCLOSING SCOPE

• BUILT-IN SCOPE

298
USER DEFINED FUNCTIONS
• LOCAL SCOPE

• Local scope variables can only be accessed within its block.

299
USER DEFINED FUNCTIONS
• LOCAL SCOPE

300
USER DEFINED FUNCTIONS
• GLOBAL SCOPE
• The variables that are declared in the global scope can be
accessed from anywhere in the program.

• Global variables can be used inside any functions.

• We can also change the global variable value.

301
USER DEFINED FUNCTIONS
• GLOBAL SCOPE

302
USER DEFINED FUNCTIONS
• GLOBAL SCOPE
• What would happen if you declare a local variable with the same name as
a global variable inside a function?

303
USER DEFINED FUNCTIONS
• ENCLOSING SCOPE

• A scope that isn’t local or global comes under enclosing scope

304
USER DEFINED FUNCTIONS
• BUILT-IN SCOPE

• All the reserved names in Python built-in modules have a


built-in scope.

305
306
307
MODULES
• INTRODUCTION

• PYTHON BUILT-IN MODULES

• CREATING MODULES

• IMPORTING OBJECTS FROM MODULES

• CREATING CUSTOM MODULES

308
MODULES
• INTRODUCTION

• A module a file that contains a Python code that we can use in


our program

309
MODULES
• PYTHON BUILT-IN MODULES

• All Built-in modules can be accessed using following command

help(‘modules’)

• All modules are placed in an alphabetic order (a to z)

310
311
MODULES
• CREATING MODULES
• For creating any module, we choose the module name and
import it using import statement

import module

• For example

import math

312
313
MODULES
• IMPORTING MODULES

314
315
MODULES
• IMPORTING MODULES – CONSTANT VALUES

316
MODULES
• IMPORTING MODULES – RENAMING

317
MODULES
• IMPORTING MODULES – from…….import statement

318
MODULES
• IMPORTING MODULES – from…….import statement

319
MODULES
• IMPORTING MODULES – all names *

320
MODULES
• IMPORTING MODULES – dir() function

321
322
MODULES
• CUSTOM MODULE

• In python we can create custom modules as per our need.

• This helps us to keep our code organized.

323
MODULES
• CUSTOM MODULE - CALCULATOR

• To perform ARITHMETIC CALCULATIONS

324
MODULES
• CUSTOM MODULE - CALCULATOR

• To perform ARITHMETIC CALCULATIONS

325
MODULES
• CUSTOM MODULE - CALCULATOR

326
327
PACKAGES
• INTRODUCTION

• CREATING PYTHON PACKAGE

• STANDARD PACKAGES

• USER DEFINED PACKAGES

328
PACKAGES
• INTRODUCTION
• We usually organize our files in different folders and
subfolders based on some criteria, so that they can be
managed easily and efficiently.

• For example, we keep all our games in a Games folder and we


can even subcategorize according to the genre of the game or
something like this.

• The same analogy is followed by the Python package.

329
PACKAGES
• INTRODUCTION
• A Python module may contain several classes, functions,
variables, etc. whereas a Python package can contains several
module.

• In simpler terms a package is folder that contains various


modules as files.

• A package is directory containing modules or subpackages.

330
331
332
PACKAGES
• EXAMPLE 1

• Let’s create a package named mypckg that will contain two


modules mod1 and mod2.

• To create this module follow the below steps –

– Create a folder named mypckg.

– Inside this folder create an empty Python file i.e.


init .py (for considering as package)

– Then create two modules mod1 and mod2 in this folder.

333
334
335
336
337
PACKAGES
• EXAMPLE 2

• Let’s create a package named game that will contain two


subpackages characters and weapons.

• To create this module follow the below steps –

– Create a folder named game.

– Inside this folder create an empty Python file i.e.


init .py (for considering as package)
– Then create two subpackages characters and weapons in
this folder.
338
PACKAGES
– Inside each subpackage create an empty Python file i.e.
init .py (for considering as package)

– Create two python files named player.py and boss.py in


characters package.

– Create one python file named category.py in weapons


package.

– Finally create main.py python file outside the game


package to import and call all packages.

339
340
341
342
343
PACKAGES
• DATE AND TIME MODULES

• The Time Module

• It contains a lot of functions to process time.

• Time intervals are represented as floating point numbers


in seconds.

344
EPOCH
345
ctime() – Current Time
346
PACKAGES
• DATE AND TIME MODULES

• The datetime Module – TIME CLASS


• It contains functions and classes for doing date and time
parsing, formatting and arithmetic.

• It contains functions and classes for working with dates


and times, separately and together.

347
Time class 348
PACKAGES
• DATE AND TIME MODULES

• The datetime Module – DATE CLASS


• Calendar date values are represented with the date class.

• Instances have attributes for year, month, and day.

• It is easy to create a date representing today’s date using


the today() class method.
349
Date class 350
PACKAGES
• CALENDAR MODULES

• The datetime Module – DATE CLASS


• It has many built-in functions for printing and formatting
the output.

• By default calendar takes Monday as the first day of the


week and Sunday as the last.

351
352
353
354
355
PACKAGES
• STANDARD PACKAGE

• Numpy

• NumPy is a Python library used for working with arrays.


• It also has functions for working in domain of linear
algebra, fourier transform, and matrices.

• NumPy was created in 2005 by Travis Oliphant. It is an


open source project and you can use it freely.

• NumPy stands for Numerical Python.

356
PACKAGES
• Why to use Numpy?

• In Python we have lists that serve the purpose of arrays, but


they are slow to process.

• NumPy aims to provide an array object that is up to 50x faster


than traditional Python lists.
• The array object in NumPy is called ndarray, it provides a lot of
supporting functions that make working with ndarray very easy.

• Arrays are very frequently used in data science, where speed


and resources are very important.

357
py –m pip install numpy

358
PACKAGES
• STANDARD PACKAGE

• Pandas

• Pandas is a Python library.

• Pandas is used to analyze data.


• Pandas is a Python package providing fast, flexible, and
expressive data structures designed to make working with
“relational” or “labeled” data both easy and intuitive.

• It aims to be the fundamental high-level building block for


doing practical, real-world data analysis in Python.
359
PACKAGES
• Pandas
• Pandas makes it simple to do many of the time consuming, repetitive
tasks associated with working with data, including:

• Data cleansing
• Data fill
• Data normalization
• Merges and joins
• Data visualization
• Statistical analysis
• Data inspection
• Loading and saving data
360
py –m pip install pandas

361
POINTS TO BE COVERED
• CREATING CLASSES AND OBJECTS
• METHOD OVERLOADING AND OVERWRITING
• DATA HIDING
• DATA ABSTRACTION
• INHERITANCE AND Child CLASSES
• CUSTOMIZATION VIA INHERITANCE SPECIALIZING
INHERITED METHOD

362
363
POINTS TO BE COVERED
• INTRODUCTION
• CLASS
• OBJECTS

364
365
CLASSES & OBJECTS

• Python is an object oriented programming language.

• Almost everything in Python is an object, with its properties


and methods.

• A Class is like an object constructor, or a "blueprint" for


creating objects.

366
CLASSES & OBJECTS
Think of a class as a blueprint of a house. It
contains all the details about floors, doors,
windows etc. Based on this description we
build the house. House is an object

367
CLASSES & OBJECTS
• CLASS
• A class is a user-defined blueprint or prototype from which objects
are created.
• Classes provide a means of bundling data and functionality
together.
• Creating a new class creates a new type of object, allowing new
instances of that type to be made.
• Each class instance can have attributes attached to it for
maintaining its state.
• Class instances can also have methods (defined by their class) for
modifying their state.
368
CLASSES & OBJECTS
• IMPORTANT POINTS FOR CLASS

• Classes are created by keyword class.

• Variables are called as attributes.

• Attributes are the variables that belong to a class.

• Attributes are always public and can be accessed using the


dot (.) operator.

• Eg.:- Myclass.Myattribute

• Functions are called as methods.

369
CLASSES & OBJECTS

370
CLASSES & OBJECTS
• OBJECT

• An Object is an instance of a Class.

• A class is like a blueprint while an instance is a copy of the


class with actual values.

371
CLASSES & OBJECTS
• An object consists of :
• State: It is represented by the attributes of an object. It also
reflects the properties of an object.

• Behavior: It is represented by the methods of an object. It


also reflects the response of an object to other objects.

• Identity: It gives a unique name to an object and enables one


object to interact with other objects.
372
CLASSES & OBJECTS

373
CLASSES & OBJECTS

374
CLASSES & OBJECTS
• THE self METHOD
• Class methods must have an extra first parameter in the method
definition.
• We do not give a value for this parameter when we call the
method, Python provides it.
• If we have a method that takes no arguments, then we still have to
have one argument.
• When we call a method of this object as myobject.method(arg1,
arg2), this is automatically converted by Python into
MyClass.method(myobject, arg1, arg2) – this is all the special self
is about.
375
376
CLASSES & OBJECTS

377
CLASSES & OBJECTS

378
CLASSES & OBJECTS
• THE init METHOD
• It is a special method that automatically gets called every time
objects are created.

• The init method is similar to constructors in C++ and Java.

• Constructors are used to initializing the object’s state

379
CLASSES & OBJECTS

380
381
382
383
384
385
386
INHERITANCE
• DEFINITION

Inheritance allows us to inherit attributes and


methods from a parent class to child classes.

387
INHERITANCE
• PROPERTIES OF INHERITANCE

• It allows to derive a new class from old class.

• The old class is called as base class or parent class.

• The new class is called as derived class/subclass or child class.

• Inheritance allows subclasses to inherit all the variables and


methods to their parent class.

• Reusability of code is best advantage of inheritance.

388
INHERITANCE
• TYPES OF INHERITANCE

• SINGLE INHERITANCE

• MULTIPLE INHERITANCE

• MULTILEVEL INHERITANCE

• HIERARCHICAL INHERITANCE

• HYBRID INHERITANCE

389
INHERITANCE
• SINGLE INHERITANCE

• It includes only one parent class and one child class.

PARENT CLASS

CHILD CLASS
390
INHERITANCE
• SYNTAX

• SINGLE INHERITANCE

class SubClassName (ParentClass1*,ParentClass2,….,+)

‘Optional class documentation string’

class_suite

391
INHERITANCE
• WRITE A PROGRAM
• Create two classes named Student() and Test() and student
information and marks. You can take input from user.

392
393
394
INHERITANCE
• MULTIPLE INHERITANCE
• It includes more than one parent class and the child class
inherits all properties of both parent class.

PARENT CLASS-1 PARENT CLASS-2

CHILD CLASS
395
INHERITANCE
• MULTIPLE INHERITANCE
• When a class is derived from more than one base class it is called
multiple Inheritance. The derived class inherits all the features of
the base case.

Class Base1:
Body of the class
Class Base2

Body of the class


Class Derived(Base1, Base2):
Body of the class
396
397
398
399
INHERITANCE
• MULTILEVEL INHERITANCE
• In this inheritance a child class can act as parent class for
another child class

PARENT CLASS

CHILD CLASS-1

CHILD CLASS-2 400


401
402
403
404
INHERITANCE
• WRITE A PROGRAM
• Create three classes named Student(), Test() and Result() and
student information and marks. You can take input from user.

405
406
407
408
INHERITANCE
• HIERARCHICAL INHERITANCE

• It includes multiple inheritance from same parent class.

PARENT CLASS-1 PARENT CLASS-2

CHILD CLASS 1 CHILD CLASS 2


409
410
411
INHERITANCE
• HYBRID INHERITANCE
• If multiple inheritance occurs in a program then it is called
hybrid inheritance.

PARENT CLASS-1 PARENT CLASS-2

CHILD CLASS 1 CHILD CLASS 2


412
413
414
415
INHERITANCE
• SUPER FUNCTION IN INHERITANCE

• It directly calls the parent class method.

416
417
418
COMPOSITION CLASSES
• COMPOSITION CLASSES

• In this concept, a class has references to one or more objects of


other classes as an Instance variable.

• Here, by using the class name or by creating the object we can


access the members of one class inside another class.
• It enables creating complex types by combining objects of different
classes.

• It means that a class Child can contain an object of another class


Parent.

• This type of relationship is known as Has-A Relation. 419


COMPOSITION CLASSES
• The class name Child and Parent represents Has-A relation
between both of them.

CHILD CLASS

HAS A

PARENT CLASS
420
421
422
423
COMPOSITION CLASSES
• In the above example, we created two classes Parent and Child to show the
Has-A Relation among them.

• In the Parent class, we have one constructor and an instance method m1().
• Similarly, in Child class, we have one constructor in which we created an object
of Parent Class. Whenever we create an object of Child Class, the object of the
Parent class is automatically created.

• Now in m2() method of Child class we are calling m1() method of Parent Class
using instance variable obj1 in which reference of Parent Class is stored.

• Now, whenever we call m2() method of Child Class, automatically m1()


method of Parent Class will be called.

424
COMPOSITION CLASSES
• COMPOSITION CLASSES VS INHERITANCE

What should be used more INHERITANCE or


COMPOSITION ?

425
426
427
428
METHOD OVERLOADING
• Methods in Python can be called with zero, one, or more
parameters.

• This process of calling the same method in different ways is


called method overloading.

• Two methods cannot have the same name in Python; hence


method overloading is a feature that allows the same
operator to have different meanings.
429
430
431
432
METHOD OVERLOADING
• Now in above example, consider if you have to take any one
of following choice
– Only 1 input value

– Only 2 input values

– All 3 input values

• Then the program should give output in any choice and


should not give a traceback error.

• Reuse same code and modify necessary things to get desired


output.
433
434
435
436
437
METHOD OVERLOADING
• Example:
• Write a python program using Method Overloading Method to find
– Area of Rectangle

– Area of Square

• Create only one class and define only one method in that class and
generate output in following manner.

– Nothing to Print – if no arguments are passed

– Area of Square: - if only one argument is passed

– Area of Rectangle: - if two arguments are passed

438
439
440
441
METHOD OVERRIDING
• Method overriding is an ability of any object-oriented
programming language that allows a subclass or child class to
provide a specific implementation of a method that is already
provided by one of its super-class(s) or parent class(s).

• When a method in a subclass has the same name, same


parameters or signature and same return type(or sub-type) as
a method in its super-class, then the method in the subclass
is said to override the method in the super-class.
442
443
444
445
446
447
448
449
450
451
452
DATA HIDING
• Data hiding is a concept which underlines the hiding of data or
information from the user.

• Data hiding is also known as information hiding.

• It includes object details such as data members, internal work.

• Data hiding excludes full data entry to class members and defends
object integrity by preventing unintended changes.

• Data hiding also minimizes system complexity for increase robustness


by limiting interdependencies between software requirements.
• In class, if we declare the data members as private so that no other
class can access the data members, then it is a process of hiding data.
453
454
455
456
457
DATA HIDING
• ADVANTAGES OF DATA HIDING:
• It helps to prevent damage or misuse of volatile data by hiding
it from the public.

• The class objects are disconnected from the irrelevant data.

• It isolates objects as the basic concept of OOP.


• It increases the security against hackers that are unable to
access important data.

458
DATA HIDING
• DISADVANTAGES OF DATA HIDING:
• It enables programmers to write lengthy code to hide
important data from common clients.

• The linkage between the visible and invisible data makes the
objects work faster, but data hiding prevents this linkage.

459
460
DATA ABSTRACTION
• The process by which data and functions are defined in such a
way that only essential details can be seen and unnecessary
implementations are hidden is called Data Abstraction.

• The main focus of data abstraction is to separate the interface


and the implementation of the program.

461
DATA ABSTRACTION
• In Python, abstraction can be achieved by using abstract
classes and interfaces.

• A class that consists of one or more abstract method is called


the abstract class.

• Abstract methods do not contain their implementation.


• Abstract class can be inherited by the subclass and abstract
method gets its definition in the subclass.

• Abstraction classes are meant to be the blueprint of the other


class.
462
DATA ABSTRACTION
• An abstract class can be useful when we are designing large
functions.

• An abstract class is also helpful to provide the standard


interface for different implementations of components.

463
DATA ABSTRACTION
• SYNTAX

We import the ABC class from the abc module.

464
DATA ABSTRACTION
• ABSTRACT BASE CLASSES
• An abstract base class is the common application program of
the interface for a set of subclasses.

• It can be used by the third-party, which will provide the


implementations such as with plugins.

• It is also beneficial when we work with the large code-base


hard to remember all the classes.
465
DATA ABSTRACTION
• WORKING OF THE ABSTRACT CLASSES
• Unlike the other high-level language, Python doesn't provide
the abstract class itself.

• We need to import the abc module, which provides the base


for defining Abstract Base classes (ABC).

• The ABC works by decorating methods of the base class as


abstract.
466
DATA ABSTRACTION
• WORKING OF THE ABSTRACT CLASSES
• It registers concrete classes as the implementation of the
abstract base.

• We use the @abstractmethod decorator to define an abstract


method or if we don't provide the definition to the method, it
automatically becomes the abstract method

467
468
469
DATA ABSTRACTION
• EXPLANATION OF CODE
• In the above code, we have imported the abc module to
create the abstract base class.

• We created the Car class that inherited the ABC class and
defined an abstract method named mileage().

• We have then inherited the base class from the three


different subclasses and implemented the abstract method
differently.

• We created the objects to call the abstract method.


470
DATA ABSTRACTION
• TRY YOURSELF

• Write a python program to display sides of following polygons

• Triangle, Pentagon, Hexagon, Square


• Simply display message of sides for each polygon e.g. for
triangle – “Triangle has 3 sides”

471
472
473
DATA ABSTRACTION
• EXPLANATION OF CODE
• In the above code, we have defined the abstract base class named Polygon
and we also defined the abstract method.

• This base class inherited by the various subclasses.

• We implemented the abstract method in each subclass.

• We created the object of the subclasses and invoke the sides() method.

• The hidden implementations for the sides() method inside the each
subclass comes into play.
• The abstract method sides() method, defined in the abstract class, is never
invoked.
474
POINTS TO BE COVERED
• INTRODUCTION TO FILES
• I/O OPERATIONS
• FILE HANDLING
• EXCEPTION HANDLING

475
476
POINTS TO BE COVERED
• INTRODUCTION
• READING KEYBOARD INPUT
• PRINTING ON SCREEN

477
478
INTRODUCTION
What is a file?
• It is a kind of permanent storage consuming less memory but
satisfies the user basic needs.

• A file can be of any type


– Audio

– Video

– Text

– Image

479
480
I/O OPERATIONS ON FILE
• The key function for working with files in Python is the open()
function.

• The open() function takes two parameters; filename, and


mode.

open (filename, mode)

481
I/O OPERATIONS ON FILE
• There are four different methods (modes) for opening a file:

482
I/O OPERATIONS ON FILE
open (filename, r)

open (filename, w)

open (filename, a)

open (filename, x)

483
I/O OPERATIONS ON FILE
• In addition you can specify if the file should be handled as
binary or text mode

484
I/O OPERATIONS ON FILE

open (filename, t)

open (filename, b)

485
I/O OPERATIONS ON FILE
• Hence, in Python, a file operation takes place in the following
order:

• Open a file

• Read or write (perform operation)

• Close the file

486
487
I/O OPERATIONS ON FILE
• WORKING OF OPEN() FUNCTION
• Before performing any operation on the file like read or write,
first we have to open that file.

• For this, we should use Python’s inbuilt function open()

• But at the time of opening, we have to specify the mode,


which represents the purpose of the opening file.

488
I/O OPERATIONS ON FILE

489
I/O OPERATIONS ON FILE

490
491
I/O OPERATIONS ON FILE
• WORKING OF READ() MODE

• There is more than one way to read a file in Python.

• If you need to extract a string that contains all characters in


the file then we can use file.read()

492
I/O OPERATIONS ON FILE

493
I/O OPERATIONS ON FILE
• WORKING OF READ() MODE
• Another way to read a file is to call a certain number of
characters.

• The interpreter will read the certain number of characters of


stored data and return it as a string.

494
I/O OPERATIONS ON FILE

495
496
I/O OPERATIONS ON FILE
• WORKING OF WRITE() MODE
• It is used for manipulating contents in a file.

• If the file that we are trying to open is not present in pwd,


then a new file is created.

• The write() mode over writes the contents in a file.

• It does not preserve integrity of a file.


497
I/O OPERATIONS ON FILE

498
I/O OPERATIONS ON FILE

499
500
I/O OPERATIONS ON FILE
• WORKING OF APPEND() MODE

• It is used for manipulating contents in a file.

• It does not over writes the new content over the old contents
like write() mode.

• Executing append() mode for multiple time, appends same


statement for n number of times.

501
I/O OPERATIONS ON FILE

502
I/O OPERATIONS ON FILE

503
504
I/O OPERATIONS ON FILE
• WORKING OF X() MODE

• It is creating a file.

• If the file that we are trying to open is not present in pwd,


then a new file is created.

• But if the file exist, then an error message is shown.

505
I/O OPERATIONS ON FILE

BEFORE EXECUTION

AFTER EXECUTION

506
507
I/O OPERATIONS ON FILE
• WORKING OF T() & B() MODE

• The t() mode is default mode for text.

• The b() mode is used for images.

• The b() mode reads and writes in binary mode

508
I/O OPERATIONS ON FILE

509
510
I/O OPERATIONS ON FILE
• ATTRIBUTES OF FILE
• Once a file is opened, we have one file object. To get various
information related to that file using following attributes.

• 1. file.closed – Returns True if file is closed, false otherwise.


• 2. file.mode – Returns access mode with which file was
opened.

• 3. file.name – Returns name of the file.


• 4. file.softspace – Returns 0 is space is explicitly required with
print, or 1 otherwise.
511
I/O OPERATIONS ON FILE

512
I/O OPERATIONS ON FILE

513
514
I/O OPERATIONS ON FILE

515
I/O OPERATIONS ON FILE
• TRY IT YOURSELF

• Consider you have created a file named ‘demo.txt’. Write a python


program to take input as name of file from user.

• If the user types the file name correct (‘demo.txt’), then print “File
Exist” and read the file contents and print each line one by one.

• If the user types the file name incorrect, then print “File does not
exist” and print “End of Program”

516
I/O OPERATIONS ON FILE

517
I/O OPERATIONS ON FILE

518
519
I/O OPERATIONS ON FILE
• FILE METHODS

• file.no()

• file.seek()

• file.tell()

• file.truncate()

• file.readlines()

520
I/O OPERATIONS ON FILE

521
522
523
524
525
526
527
528
I/O OPERATIONS ON FILE
• RENAMING A FILE
• To rename a file, we must use os module.

• It provides methods to perform file operations.

• To rename an existing file, we can use rename() method.

• This method takes two arguments , current filename and new


file name.
529
I/O OPERATIONS ON FILE

os.rename (current_filename, new_filename)

530
BEFORE EXECUTION AFTER EXECUTION

531
I/O OPERATIONS ON FILE
• DELETING A FILE

• To deleting a file, we must use os module.

• It provides methods to perform file operations.

• To delete an existing file, we can use remove() method.

• This method takes one argument , filename


532
I/O OPERATIONS ON FILE

os.remove(filename)

533
BEFORE EXECUTION AFTER EXECUTION

534
535
DIRECTORIES

WHAT IS A DIRECTORY?
• A directory or folder is a collection of files and subdirectories.

• Python has the os module that provides us with many useful


methods to work with directories (and files as well).

536
DIRECTORIES
WHAT IS A DIRECTORY?
• Directories are a way of storing, organizing, and separating
the files on a computer.
• The directory that does not have a parent is called a root
directory.

• The way to reach the file is called the path.


• The path contains a combination of directory names, folder
names separated by slashes and colon and this gives the route
to a file in the system.
537
538
DIRECTORIES
• DIRECTORY MANAGEMENT
• Python contains several modules that has a number of built-in
functions to manipulate and process data.

• Python has also provided modules that help us to interact


with the operating system and the files.

• These kinds of modules can be used for directory


management also.
539
DIRECTORIES
• DIRECTORY MANAGEMENT

• The modules that provide the functionalities are listed below:

• os and os.path

• filecmp

• tempfile

• shutil

540
541
DIRECTORIES
• 1. OS AND OS.PATH MODULES
• The os module is used to handle files and directories in various
ways.

• It provides provisions to create/rename/delete directories.

• This allows even to know the current working directory (CWD) and
change it to another.

• It also allows one to copy files from one directory to another.


542
DIRECTORIES
• There are different methods for directory management
– Creating New Directory

– Getting Current Working Directory (CWD)

– Changing Current Working Directory (CWD)

– Renaming a Directory

– Listing files in a Directory

– Removing a Directory

– Checking Directory (It is / It is not)

– Size of Directory

– Getting access and modification times

543
DIRECTORIES
• OS AND OS.PATH MODULES

• A. CREATING NEW DIRECTORY:

• os.mkdir (name) method to create a new directory.

• The desired name for the new directory is passed as the parameter.
• By default it creates the new directory in the current working
directory.

• If the new directory has to be created somewhere else then that


path has to be specified and the path should contain forward
slashes instead of backward ones.

544
DIRECTORIES

os.mkdir(Drive name/directoryname)

545
546
BEFORE EXECUTION

547
AFTER EXECUTION

548
DIRECTORIES
• OS AND OS.PATH MODULES

• B. GETTING CURRENT WORKING DIRECTORY (CWD):

• os.getcwd() can be used.


• It returns a string that represents the path of the current
working directory.

• os.getcwdb() can also be used but it returns a byte string that


represents the current working directory.

• Both methods do not require any parameters to be passed.

549
550
DIRECTORIES
• OS AND OS.PATH MODULES

• C. CHANGING CURRENT WORKING DIRECTORY (CWD):


• Every process in the computer system will have a directory
associated with it, which is known as Current Working
Directory(CWD).

• os.chdir() method is used to change it.

• The parameter passed is the path/name of the desired


directory to which one wish to shift.

551
DIRECTORIES

os.chdir(path/name)

552
553
DIRECTORIES
• OS AND OS.PATH MODULES

• D. RENAMING A DIRECTORY:

• os.rename() method is used to rename the directory.

• The parameters passed are old_name followed by new_name.


• If a directory already exists with the new_name passed,
OSError will be raised.

• os.renames(‘old_name’,’dest_dir:/new_name’) method
works similar to os.rename() but it moves the renamed file to
the specified destination directory(dest_dir).
554
DIRECTORIES

os.rename(old_name,new_name)

555
BEFORE EXECUTION AFTER EXECUTION

556
DIRECTORIES
• OS AND OS.PATH MODULES

• E. LISTING THE FILES IN A DIRECTORY:


• A directory may contain sub-directories and a number of files in it.
To list them, os.listdir() method is used.

• It either takes no parameter or one parameter.


• If no parameter is passed, then the files and sub-directories of the
CWD is listed.

• If files of any other directory other than the CWD is required to be


listed, then that directory’s name/path is passed as parameter.

557
DIRECTORIES

os.listdir()

os.listdir(os.getcwd())

558
559
DIRECTORIES
• OS AND OS.PATH MODULES

• F. REMOVING A DIRECTORY:

• os.rmdir() method is used to remove/delete a directory.

• The parameter passed is the path to that directory.

• It deletes the directory if and only if it is empty, otherwise


raises an OSError.

560
561
DIRECTORIES
• OS AND OS.PATH MODULES

• G. TO CHECK WHETHER IT IS A DIRECTORY:


• Given a directory name or Path, os.path.isdir(path) is used to
validate whether the path is a valid directory or not.

• It returns Boolean values only.


• Returns true if the given path is a valid directory otherwise
false.

562
563
564
DIRECTORIES
• OS AND OS.PATH MODULES

• G. TO GET SIZE OF THE DIRECTORY:


• os.path.getsize(path_name) gives the size of the directory in
bytes.

• OSError is raised if, invalid path is passed as parameter.

565
DIRECTORIES

os.path.getsize(path_name)

566
567
DIRECTORIES
• OS AND OS.PATH MODULES

• G. GETTING ACCESS AND MODIFICATION TIMES:


• To get the last accessed time of a directory : os.path.getatime
(path)

• To get the last modified time of the directory :


os.path.getmtime (path)
• These methods return the number of seconds since the
epoch. To format it, datetime module’s strftime( ) function
can be used.
568
DIRECTORIES

os.path.getatime (path)

os.path.getmtime (path)

569
570
DIRECTORIES
• 2. FILECMP MODULE
• This module provides various functions to perform
comparison between files and directories.

• To compare the directories, an object has to be created for


the class filecmp.dircmp that describes which files to ignore
and which files to hide from the functions of this class.

• The constructor has to be invoked before calling any of the


functions of this class.

571
DIRECTORIES
• 3. TEMPFILE MODULE

• This module is used to create temporary files and directories.

• This creates the temporary files and directories in the temp


directories created by the Operating systems.

572
DIRECTORIES
• 3. SHUTIL MODULE
• This module is concerned with number of high-level
operations on files and directories.

• It allows copying/moving directories from a source to


destination.

573
574
EXCEPTION HANDLING
• INTRODUCTION
• Error in Python can be of two types i.e. Syntax errors and
Exceptions.

• Errors are the problems in a program due to which the


program will stop the execution.

• On the other hand, exceptions are raised when some internal


events occur which changes the normal flow of the program.
575
EXCEPTION HANDLING
• DIFFERENCE BETWEEN SYNTAX ERROR AND EXCEPTIONS
• Syntax Error: As the name suggests this error is caused by the
wrong syntax in the code. It leads to the termination of the
program.

• Exceptions: Exceptions are raised when the program is


syntactically correct, but the code resulted in an error. This
error does not stop the execution of the program, however, it
changes the normal flow of the program.
576
577
578
579
EXCEPTION HANDLING
• TRY AND EXCEPT STATEMENT – CATCHING EXCEPTIONS
• Try and except statements are used to catch and handle
exceptions in Python.

• Statements that can raise exceptions are kept inside the try
clause and the statements that handle the exception are
written inside except clause.

580
581
EXCEPTION HANDLING
• CATCHING SPECIFIC EXCEPTION
• A try statement can have more than one except clause, to
specify handlers for different exceptions.

• The general syntax for adding specific exceptions are –

582
583
584
585
EXCEPTION HANDLING
• RAISE STATEMENT
• The raise statement allows the programmer to force a specific
exception to occur.

• The sole argument in raise indicates the exception to be


raised.

• This must be either an exception instance or an exception


class (a class that derives from Exception).
586
587
588
EXCEPTION HANDLING
• CREATING USER-DEFINED EXCEPTION

• Programmers may name their own exceptions by creating a new


exception class.

• Exceptions need to be derived from the Exception class, either


directly or indirectly.

• Although not mandatory, most of the exceptions are named as


names that end in “Error” similar to the naming of the standard

exceptions in python. 589


590
591
592

You might also like