Unit-III Iot Systems- Logical Design Using Python
Unit-III Iot Systems- Logical Design Using Python
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
• OBJECT-ORIENTED
• PORTABLE
• SCALABLE
• EXTENDABLE
6
PYTHON DATA TYPES
• Python Data Types are used to define the type of a variable.
• a = 1, b = 2
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”).
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.
15
PYTHON DATA TYPES
16
PYTHON DATA TYPES
• EXAMPLE
17
PYTHON DATA TYPES
• LIST
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
• 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.
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
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.
34
PYTHON DATA TYPES
• EXAMPLE 2:
35
PYTHON DATA TYPES
• EXAMPLE 3:
36
PYTHON DATA TYPES
• DICTIONARY
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.
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
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.
42
PYTHON DATA TYPES
• EXAMPLE 1 :
43
PYTHON DATA TYPES
• EXAMPLE 2 :
44
PYTHON DATA TYPES
• SET
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
47
PYTHON DATA TYPES
• SET ITEMS
48
PYTHON DATA STRUCTURES
49
PYTHON DATA STRUCTURES
• LISTS
• TUPLES
• SETS
• DICTIONARIES
50
LISTS
• DEFINING LISTS
• UDATING LISTS
51
52
LISTS
• LIST
• EXAMPLE
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
• 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.
• List1 = *‘Hello!’+
82
83
TUPLE
• DEFINING TUPLE
84
85
TUPLE
• TUPLE
• A tuple is another sequence of data type that is similar to the
list.
88
TUPLE
• TUPLE ITEMS
• ORDERED
• Ordered means that the items have a defined order, and that
order will not change.
• UNCHANGEABLE
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
• UDATING SET
106
SET
• SET
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
109
SET
• SET ITEMS
110
111
SET
112
113
SET
• SET UNION
• SET INTERSECTION
• SET DIFFERENCE
114
SET
• SET UNION –union()
• The union of two sets is the set of all the elements of both the
sets without duplicates.
115
SET
116
SET
• SET INTERSECTION – intersection()
• The intersection of two sets is the set of all the common
elements of both the sets.
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.
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.
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
• UDATING DICTIONARY
148
DICTIONARY
• DICTIONARY
• Dictionary in Python is an unordered collection of data
values.
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.
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
153
154
DICTIONARY
• DICTIONARY OPERATIONS • DICTIONARY OPERATIONS
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
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
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
174
DICTIONARY
• BUILT-IN METHODS
175
DICTIONARY
• BUILT-IN METHODS
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.
179
180
TYPES OF OPERATORS
• ARITHMETIC 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
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 AND,
– Logical OR,
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.
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.
203
TYPES OF OPERATORS
205
206
FLOW CONTROL
• A program’s control flow is the order in which the program’s
code executes.
208
FLOW CONTROL
• REPRESENTING SEQUENTIAL FLOW
209
FLOW CONTROL
• 2. SELECTION / DECISION CONTROL STATEMENTS
210
FLOW CONTROL
• 2. SELECTION / DECISION CONTROL STATEMENTS
• 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”.
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”
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
222
FLOW CONTROL
• 3. REPETATION
• A repetition statement is used to repeat a group(block) of
programming instructions.
• 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
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 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.
229
FLOW CONTROL
• WHILE LOOP
Syntax
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.
233
FLOW CONTROL
• NESTED LOOPS
• Nested loops can be used for both while and for loop.
Syntax for nested for loop Syntax for nested while 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.
239
LOOP MANIPULATION
• CONTROL STATEMENTS
• break
• continue
• pass
240
LOOP MANIPULATION
• BREAK CONTROL STATEMENTS
242
FLOW CONTROL
• REPRESENTING BREAK CONTROL STATEMENT
243
LOOP MANIPULATION
244
FLOW CONTROL
• EXAMPLES
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.
246
LOOP MANIPULATION
247
FLOW CONTROL
• REPRESENTING CONTINUE CONTROL STATEMENT
248
LOOP MANIPULATION
249
FLOW CONTROL
• EXAMPLES
250
LOOP MANIPULATION
• PASS CONTROL STATEMENTS
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.
255
256
PYTHON BUILT-IN FUNCTIONS
• Python defines type conversion functions to directly convert
one data type to another.
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.
261
PYTHON BUILT-IN FUNCTIONS
• EXPLICIT TYPE CONVERSION
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.
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
273
274
USER DEFINED FUNCTIONS
• RULES FOR DEFINING USER DEFINED FUNCTIONS
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.
277
USER DEFINED FUNCTIONS
• SYNTAX
“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.
281
USER DEFINED FUNCTIONS
• EXAMPLE - 1
282
USER DEFINED FUNCTIONS
• EXAMPLE - 2
283
284
USER DEFINED FUNCTIONS
• ARGUMENTS
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.
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.
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.
294
USER DEFINED FUNCTIONS
295
296
USER DEFINED FUNCTIONS
• SCOPE OF VARIABLES
• In programming languages, variables need to be defined
before using them.
• LOCAL SCOPE
• GLOBAL SCOPE
• ENCLOSING SCOPE
• BUILT-IN SCOPE
298
USER DEFINED FUNCTIONS
• LOCAL SCOPE
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.
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
304
USER DEFINED FUNCTIONS
• BUILT-IN SCOPE
305
306
307
MODULES
• INTRODUCTION
• CREATING MODULES
308
MODULES
• INTRODUCTION
309
MODULES
• PYTHON BUILT-IN MODULES
help(‘modules’)
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
323
MODULES
• CUSTOM MODULE - CALCULATOR
324
MODULES
• CUSTOM MODULE - CALCULATOR
325
MODULES
• CUSTOM MODULE - CALCULATOR
326
327
PACKAGES
• INTRODUCTION
• STANDARD 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.
329
PACKAGES
• INTRODUCTION
• A Python module may contain several classes, functions,
variables, etc. whereas a Python package can contains several
module.
330
331
332
PACKAGES
• EXAMPLE 1
333
334
335
336
337
PACKAGES
• EXAMPLE 2
339
340
341
342
343
PACKAGES
• DATE AND TIME MODULES
344
EPOCH
345
ctime() – Current Time
346
PACKAGES
• DATE AND TIME MODULES
347
Time class 348
PACKAGES
• DATE AND TIME MODULES
351
352
353
354
355
PACKAGES
• STANDARD PACKAGE
• Numpy
356
PACKAGES
• Why to use Numpy?
357
py –m pip install numpy
358
PACKAGES
• STANDARD PACKAGE
• Pandas
• 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
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
• Eg.:- Myclass.Myattribute
369
CLASSES & OBJECTS
370
CLASSES & OBJECTS
• OBJECT
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.
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.
379
CLASSES & OBJECTS
380
381
382
383
384
385
386
INHERITANCE
• DEFINITION
387
INHERITANCE
• PROPERTIES OF INHERITANCE
388
INHERITANCE
• TYPES OF INHERITANCE
• SINGLE INHERITANCE
• MULTIPLE INHERITANCE
• MULTILEVEL INHERITANCE
• HIERARCHICAL INHERITANCE
• HYBRID INHERITANCE
389
INHERITANCE
• SINGLE INHERITANCE
PARENT CLASS
CHILD CLASS
390
INHERITANCE
• SYNTAX
• SINGLE INHERITANCE
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.
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
PARENT CLASS
CHILD CLASS-1
405
406
407
408
INHERITANCE
• HIERARCHICAL INHERITANCE
416
417
418
COMPOSITION CLASSES
• COMPOSITION CLASSES
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.
424
COMPOSITION CLASSES
• COMPOSITION CLASSES VS INHERITANCE
425
426
427
428
METHOD OVERLOADING
• Methods in Python can be called with zero, one, or more
parameters.
– Area of Square
• Create only one class and define only one method in that class and
generate output in following manner.
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).
• Data hiding excludes full data entry to class members and defends
object integrity by preventing unintended changes.
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.
461
DATA ABSTRACTION
• In Python, abstraction can be achieved by using abstract
classes and interfaces.
463
DATA ABSTRACTION
• SYNTAX
464
DATA ABSTRACTION
• ABSTRACT BASE CLASSES
• An abstract base class is the common application program of
the interface for a set of subclasses.
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().
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.
• 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.
– Video
– Text
– Image
479
480
I/O OPERATIONS ON FILE
• The key function for working with files in Python is the open()
function.
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
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.
488
I/O OPERATIONS ON FILE
489
I/O OPERATIONS ON FILE
490
491
I/O OPERATIONS ON FILE
• WORKING OF READ() MODE
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.
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.
498
I/O OPERATIONS ON FILE
499
500
I/O OPERATIONS ON FILE
• WORKING OF APPEND() MODE
• It does not over writes the new content over the old contents
like write() mode.
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.
505
I/O OPERATIONS ON FILE
BEFORE EXECUTION
AFTER EXECUTION
506
507
I/O OPERATIONS ON FILE
• WORKING OF T() & B() 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.
512
I/O OPERATIONS ON FILE
513
514
I/O OPERATIONS ON FILE
515
I/O OPERATIONS ON FILE
• TRY IT YOURSELF
• 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.
530
BEFORE EXECUTION AFTER EXECUTION
531
I/O OPERATIONS ON FILE
• DELETING A 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.
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.
• 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.
• This allows even to know the current working directory (CWD) and
change it to another.
– Renaming a Directory
– Removing a Directory
– Size of Directory
543
DIRECTORIES
• OS AND OS.PATH MODULES
• The desired name for the new directory is passed as the parameter.
• By default it creates the new directory in the current working
directory.
544
DIRECTORIES
os.mkdir(Drive name/directoryname)
545
546
BEFORE EXECUTION
547
AFTER EXECUTION
548
DIRECTORIES
• OS AND OS.PATH MODULES
549
550
DIRECTORIES
• OS AND OS.PATH MODULES
551
DIRECTORIES
os.chdir(path/name)
552
553
DIRECTORIES
• OS AND OS.PATH MODULES
• D. RENAMING A DIRECTORY:
• 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
557
DIRECTORIES
os.listdir()
os.listdir(os.getcwd())
558
559
DIRECTORIES
• OS AND OS.PATH MODULES
• F. REMOVING A DIRECTORY:
560
561
DIRECTORIES
• OS AND OS.PATH MODULES
562
563
564
DIRECTORIES
• OS AND OS.PATH MODULES
565
DIRECTORIES
os.path.getsize(path_name)
566
567
DIRECTORIES
• OS AND OS.PATH MODULES
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.
571
DIRECTORIES
• 3. TEMPFILE MODULE
572
DIRECTORIES
• 3. SHUTIL MODULE
• This module is concerned with number of high-level
operations on files and directories.
573
574
EXCEPTION HANDLING
• INTRODUCTION
• Error in Python can be of two types i.e. Syntax errors and
Exceptions.
• 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.
582
583
584
585
EXCEPTION HANDLING
• RAISE STATEMENT
• The raise statement allows the programmer to force a specific
exception to occur.