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

Unit III - 1

Uploaded by

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

Unit III - 1

Uploaded by

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

CORE CONCEPTS OF IOT

Unit - 3
Python:
• Python is a general-purpose high-level programming language suitable for providing a solid
foundation to the reader in the area of cloud computing.
The main characteristics of Python are:
• Multi-paradigm programming language
• Python supports more than one programming paradigm, including object-oriented
programming and structured programming
• Interpreted language
• Python is an interpreted language and does not require an explicit compilation step. The
Python interpreter executes the program source code directly, statement by statement,
as a processor or scripting engine does.
• Interactive language
• Python provides an interactive mode in which the user can submit commands at the
Python prompt and interact with the interpreter directly.
Python – Benefits:
• Easy-to-learn, read and maintain
• Python is a minimalistic* language with relatively few keywords,
• uses English keywords and has fewer syntactical constructions as compared to other languages.
• Reading Python programs feels like reading English with pseudocode-like constructs.
• Python is easy to learn yet an extremely powerful language for a wide range of applications.
• Object and procedure oriented
• Python supports both procedure-oriented programming and object-oriented programming.
• Procedure-oriented paradigm allows programs to be written around procedures or functions
that allow reuse of code.
• Object-oriented paradigm allows programs to be written around objects that include both data
and functionality.
• Extendable
• Python is an extendable language and allows integration of low-level modules written in
languages such as C/C++.
• This is useful when you want to speed up a critical portion of a program.
• Scalable
• Due to the minimalistic nature of Python, it provides a manageable structure for large
programs.

• Portable
• Since Python is an interpreted language, programmers do not have to worry about compilation,
linking and loading of programs.
• Python programs can be directly executed from the source.
• Broad library support
• Python has broad library support and works on various platforms such as Windows, Linux,
Mac, etc.

Language features of Python:


Python is a dynamic, high level, free open source and interpreted programming language. It supports object-
oriented programming as well as procedural oriented programming.
Core Concepts of IoT By Dr. V. Deepika - 1-
In Python, we don’t need to declare the type of variable because it is a dynamically typed language.
For example, x = 10
Here, x can be anything such as String, int, etc.

Features in Python:
There are many features in Python, some of which are discussed below –
1. Easy to code:
Python is a high-level programming language. Python is very easy to learn the language as compared to other
languages like C, C#, Javascript, Java, etc. It is very easy to code in python language and anybody can learn
python basics in a few hours or days. It is also a developer-friendly language.
2. Free and Open Source:
Python language is freely available at the official website and you can download it from the given download
link below click on the Download Python keyword.
Download Python Since it is open-source, this means that source code is also available to the public. So you
can download it as, use it as well as share it.
3. Object-Oriented Language:
One of the key features of python is Object-Oriented programming. Python supports object-oriented language
and concepts of classes, objects encapsulation, etc.
4. GUI Programming Support:
Graphical User interfaces can be made using a module such as PyQt5, PyQt4, wxPython, or Tk in python.
PyQt5 is the most popular option for creating graphical apps with Python.
5. High-Level Language:
Python is a high-level language. When we write programs in python, we do not need to remember the system
architecture, nor do we need to manage the memory.
6. Extensible feature:
Python is a Extensible language. We can write us some Python code into C or C++ language and also we can
compile that code in C/C++ language.

7. Python is Portable language:


Python language is also a portable language. For example, if we have python code for windows and if we want
to run this code on other platforms such as Linux, Unix, and Mac then we do not need to change it, we can
run this code on any platform.
8. Python is Integrated language:
Python is also an Integrated language because we can easily integrated python with other languages like c,
c++, etc.
9. Interpreted Language:
Python is an Interpreted Language because Python code is executed line by line at a time. like other languages
C, C++, Java, etc. there is no need to compile python code this makes it easier to debug our code. The source
code of python is converted into an immediate form called bytecode.
10. Large Standard Library
Python has a large standard library which provides a rich set of module and functions so you do not have to
write your own code for every single thing. There are many libraries present in python for such as regular
expressions, unit-testing, web browsers, etc.
11. Dynamically Typed Language:
Python is a dynamically-typed language. That means the type (for example- int, double, long, etc.) for a
variable is decided at run time not in advance because of this feature we don’t need to specify the type of
variable.

Core Concepts of IoT By Dr. V. Deepika - 2-


Python data types and data structures
Data types:
• Numbers
• Strings
• Lists
• Tuples
• Dictionaries
• Range
• Set
• Type Conversions

Numbers:
• The number data type is used to store numeric values. Numbers are immutable data types, therefore
changing the value of a number data type results in a newly allocated object.

#Integer
>>>a=5
>>>type(a)
< class ’int’>

#Floating Point
>>>b=2.5
>>>type(b)
< class ’float’>

#Complex
>>>y=2+5j
>>>y
(2+5j)
>>>type(y)
< class ’complex’>
>>>y.real
2.0
>>>y.imag
5.0

#bool
>>> bool = a>b
>>> bool
True
>>> type(bool)
<class 'bool’>

#Number Type Conversion


>>> a=int(2.5)
>>> a
2

Core Concepts of IoT By Dr. V. Deepika - 3-


>>> b=3
>>> c=float(b)
>>> c
3.0
>>> c=complex(a,b)
>>> c
(2+3j)

#Addition
>>>c=a+b
>>>c
7.5

#Subtraction
>>>d=a-b
>>>d
2.5

#Multiplication
>>>e=a*b
>>>e
12.5

#Division
>>>f=b/a
>>>f
0.5

#Power
>>>g=a**2
>>>g
25

Strings:
• A string is simply a list of characters in order. There are no limits to the number of characters you can
have in a string.
#Create string
>>> s = 'Hello World'
>>> type(s)
<class 'str’>

#String concatenation
>>> p= 'Python Programming'
>>> x=s+p
>>> x
'Hello WorldPython Programming’

Core Concepts of IoT By Dr. V. Deepika - 4-


#Get length of string
>>> len(p)
18
#Convert string to integer
>>>x="100"
>>>type(s)
< class ’str’>
>>>y=int(x)
>>>y
100

#Print string
>>>print(s)
Hello World!

#Formatting output
>>> print('Hello\n world!')
Hello
world!
>>> print('Hima's book')
SyntaxError: invalid syntax
>>> print("Hima's book")
Hima's book
>>> print('Hima\'s book')
Hima's book

#Convert to upper/lower case


>>>s.upper()
’HELLO WORLD!’
>>>s.lower()
’hello world!’

#Accessing sub-strings

>>>s[0]
’H’
>>>s[6:]
’World!’
>>>s[6:-1]
’World’

#strip: Returns a copy of the string with the #leading and trailing characters removed.
>>>s.strip("!")
’Hello World’
Core Concepts of IoT By Dr. V. Deepika - 5-
Lists:
• A list is a compound/ most versatile data type used to group together other values. List items need not
all be of the same type. A list contains items separated by commas and enclosed within square brackets.

#Create List
>>>fruits=[’apple’,’orange’,’banana’,’mango’]
>>>type(fruits)
<class ’list’>

#Get Length of List


>>>len(fruits)
4

#Access List Elements


>>>fruits[1]
’orange’
>>>fruits[1:3]
[’orange’, ’banana’]
>>>fruits[1:]
[’orange’, ’banana’, ’mango’]

#Appending an item to a list


>>>fruits.append(’pear’)
>>>fruits
[’apple’, ’orange’, ’banana’, ’mango’, ’pear’]

#Removing an item from a list


>>>fruits.remove(’mango’)
>>>fruits
[’apple’, ’orange’, ’banana’, ’pear’]
#Inserting an item to a list
>>>fruits.insert(1,’mango’)
>>>fruits
[’apple’, ’mango’, ’orange’, ’banana’, ’pear’]
#Combining lists
>>>vegetables=[’potato’,’carrot’,’onion’,’beans’,’radish’]
>>>vegetables
[’potato’, ’carrot’, ’onion’, ’beans’, ’radish’]
>>>eatables=fruits+vegetables
>>>eatables
[’apple’, ’mango’, ’orange’, ’banana’, ’pear’, ’potato’, ’carrot’, ’onion’, ’beans’, ’radish’]

#Mixed data types in a list


>>>mixed=[’data’,5,100.1]
>>>type(mixed)
< class ’list’>
>>>type(mixed[0])

Core Concepts of IoT By Dr. V. Deepika - 6-


< class ’str’>
>>>type(mixed[1])
< class ’int’>
>>>type(mixed[2])
< class ’float’>

#Change individual elements of a list


>>>mixed[0]=mixed[0]+" items"
>>>mixed[1]=mixed[1]+1
>>>mixed[2]=mixed[2]+0.05
>>>mixed
[’data items’, 6, 100.14999999999999]

#Lists can be nested


>>>nested=[fruits, vegetables]
>>>nested
[[’apple’, ’mango’, ’orange’, ’banana’, ’pear’], [’potato’, ’carrot’, ’onion’, ’beans’, ’radish’]]

Tuples:
• A tuple is a sequence of immutable Python objects (similar to the list). A tuple consists of a number of
values separated by commas and enclosed within parentheses. Unlike lists, the elements of tuples
cannot be changed, so tuples can be thought of as read-only lists.
#Create a Tuple
>>>fruits=("apple","mango","banana","pineapple")
>>>fruits
(’apple’, ’mango’, ’banana’, ’pineapple’)
>>>type(fruits)
<class ’tuple’>

#Get length of tuple


>>>len(fruits)
4

#Get an element from a tuple


>>>fruits[0]
’apple’
>>>fruits[:2]
(’apple’, ’mango’)

#Combining tuples
>>>vegetables=(’potato’,’carrot’,’onion’,’radish’)
>>>eatables=fruits+vegetables
>>>eatables
(’apple’, ’mango’, ’banana’, ’pineapple’, ’potato’, ’carrot’, ’onion’, ’radish’)

Core Concepts of IoT By Dr. V. Deepika - 7-


Dictionaries:
• Dictionary is a mapping data type or a kind of hash table that maps keys to values. Keys in a dictionary
can be of any data type, though numbers and strings are commonly used. The values in a dictionary
can be any data type or object.

#Create a dictionary
>>>student={’name’:’Mary’,’id’:’8776’,’major’:’CS’}
>>>student
{’major’: ’CS’, ’name’: ’Mary’, ’id’: ’8776’}
>>>type(student)
<class ’dict’>

#Get length of a dictionary


>>>len(student)
3

#Get the value of a key in dictionary


>>>student[’name’]
’Mary’

#Get all items in a dictionary


>>>student.items()
[(’gender’, ’female’), (’major’, ’CS’), (’name’, ’Mary’), (’id’, ’8776’)]

#Get all keys in a dictionary


>>>student.keys()
[’gender’, ’major’, ’name’, ’id’]

#Get all values in a dictionary


>>>student.values()
[’female’, ’CS’, ’Mary’, ’8776’]

#Add new key-value pair


>>>student[’gender’]=’female’
>>>student
{’gender’: ’female’, ’major’: ’CS’, ’name’: ’Mary’, ’id’: ’8776’}

#A value in a dictionary can be another dictionary


>>>student1={’name’:’David’,’id’:’9876’,’major’:’ECE’}
>>>students={’1’: student,’2’:student1}
>>>students
{’1’: {’gender’: ’female’, ’major’: ’CS’, ’name’: ’Mary’, ’id’: ’8776’}, ’2’: {’
major’: ’ECE’, ’name’: ’David’, ’id’: ’9876’}}

Set and Range:


Set:
Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements.

Core Concepts of IoT By Dr. V. Deepika - 8-


Sets can be created by using the built-in set() function with an iterable object or a sequence by placing the
sequence inside curly braces, separated by ‘comma’. Type of elements in a set need not be the same, various
mixed-up data type values can also be passed to the set.
Ex:
>>> s = {20,30,40}
>>> type(s)
<class 'set’>
>>> s
{40, 20, 30}
>>> s1={'abc','def','ghi'}
>>> s1
{'ghi', 'def', 'abc'}

Range:
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by
default), and stops before a specified number.
Syntax:
range(start, stop, step)

Ex:
>>> range(10)
range(0, 10)
>>> list(range(5))
[0, 1, 2, 3, 4, 5]
>>> range
<class 'range'>
>>> list(range(2, 10, 2))
[2, 4, 6, 8]
>>> list(range(2, 15, 3))
[2, 5, 8, 11, 14]

Type Conversions:
Ex:
#Implicit Type Conversion
>>> x=10
<class ‘int’>
>>> y=10.2
>>> x=x+y
>>> x
20.2
>>> type(x)
<class 'float’>

#Explicit Type Conversion


>>> a="1000"
>>> type(a)
<class 'str'>

Core Concepts of IoT By Dr. V. Deepika - 9-


>>> a=int(a)
>>> type(a)
<class 'int'>

#conversions
>>> bin(20)
'0b10100’
>>> 0b0111
7
>>> oct(25)
'0o31’
>>> hex(20)
'0x14’
>>> 0xa
10

Control flow

Python If ... Else


Python Conditions and If statements
Python supports the usual logical conditions from mathematics:
• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements" and loops.
An "if statement" is written by using the if keyword.
Example
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")

In this example we use two variables, a and b, which are used as part of the if statement to test whether b is
greater than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so we print to screen that "b
is greater than a".

Indentation:
Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other
programming languages often use curly-brackets for this purpose.
Example
If statement, without indentation (will raise an error):
a = 33
b = 200

Core Concepts of IoT By Dr. V. Deepika - 10-


if b > a:
print("b is greater than a") # you will get an error

Elif
The elif keyword is pythons way of saying "if the previous conditions were not true, then try this condition".
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")

In this example a is equal to b, so the first condition is not true, but the elif condition is true, so we print to
screen that "a and b are equal".

Else
The else keyword catches anything which isn't caught by the preceding conditions.
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
In this example a is greater than b, so the first condition is not true, also the elif condition is not true, so we
go to the else condition and print to screen that "a is greater than b".
You can also have an else without the elif:
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

Short Hand If
If you have only one statement to execute, you can put it on the same line as the if statement.
Example
One line if statement:
if a > b: print("a is greater than b")

Short Hand If ... Else


If you have only one statement to execute, one for if, and one for else, you can put it all on the same line:
Example

Core Concepts of IoT By Dr. V. Deepika - 11-


One line if else statement:
a=2
b = 330
print("A") if a > b else print("B")

This technique is known as Ternary Operators, or Conditional Expressions.


You can also have multiple else statements on the same line:
Example
One line if else statement, with 3 conditions:
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")

And
The and keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")

Or
The or keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, OR if a is greater than c:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")

Nested If
You can have if statements inside if statements, this is called nested if statements.
Example
x = 41

if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")

Core Concepts of IoT By Dr. V. Deepika - 12-


The pass Statement
if statements cannot be empty, but if you for some reason have an if statement with no content, put in
the pass statement to avoid getting an error.
Example
a = 33
b = 200

if b > a:
pass

Python For Loops


A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
This is less like the for keyword in other programming languages, and works more like an iterator method as
found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
Example
Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)

The for loop does not require an indexing variable to set beforehand.

Looping Through a String


Even strings are iterable objects, they contain a sequence of characters:
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)

The range() Function


To loop through a set of code a specified number of times, we can use the range() function,
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by
default), and ends at a specified number.
Example
Using the range() function:
for x in range(6):
print(x)

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.


The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by
adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):
Example
Using the start parameter:
for x in range(2, 6):
print(x)

Core Concepts of IoT By Dr. V. Deepika - 13-


The range() function defaults to increment the sequence by 1, however it is possible to specify the increment
value by adding a third parameter: range(2, 30, 3):
Example
Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)

Else in For Loop


The else keyword in a for loop specifies a block of code to be executed when the loop is finished:
Example
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")

Note: The else block will NOT be executed if the loop is stopped by a break statement.
Example
Break the loop when x is 3, and see what happens with the else block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")

Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
for y in fruits:
print(x, y)
The break Statement
With the break statement we can stop the loop before it has looped through all the items:
Example
Exit the loop when x is "banana":
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break

Core Concepts of IoT By Dr. V. Deepika - 14-


Example
Exit the loop when x is "banana", but this time the break comes before the print:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)

The continue Statement


With the continue statement we can stop the current iteration of the loop, and continue with the next:
Example
Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)

Python While Loops


Python Loops
Python has two primitive loop commands:
• while loops
• for loops
The while Loop
With the while loop we can execute a set of statements as long as a condition is true.
Example
Print i as long as i is less than 6:
i=1
while i < 6:
print(i)
i += 1

Note: remember to increment i, or else the loop will continue forever.


The while loop requires relevant variables to be ready, in this example we need to define an indexing
variable, i, which we set to 1.

The break Statement


With the break statement we can stop the loop even if the while condition is true:

Example
Exit the loop when i is 3:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1

Core Concepts of IoT By Dr. V. Deepika - 15-


The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example
Continue to the next iteration if i is 3:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)

The else Statement


With the else statement we can run a block of code once when the condition no longer is true:
Example
Print a message once the condition is false:
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

Control Flow – pass Statement


• The pass statement in Python is a null operation.
• The pass statement is used when a statement is required syntactically but you do not want any
command or code to execute.
fruits=['apple','orange','banana','mango']
for item in fruits:
if item == "banana":
pass
else:
print(item)
apple
orange
mango

Functions:
• A function is a block of code that takes in information (in the form of parameters), does some
computation and returns a new piece of information based on the parameter information.
• A function in Python is a block of code that begins with the keyword def followed by the function
name and parentheses. The function parameters are enclosed within the parenthesis.
• The code block within a function begins after a colon that comes after the parenthesis enclosing the
parameters.
• The first statement of the function body can optionally be a documentation string or docstring.

Core Concepts of IoT By Dr. V. Deepika - 16-


Syntax:
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]

Ex:
#This function computes the average grade
students = {'1': {'name': 'Bob', 'grade': 2.5},
'2': {'name': 'Mary', 'grade': 3.5},
'3': {'name': 'David', 'grade': 4.2},
'4': {'name': 'John', 'grade': 4.1},
'5': {'name': 'Alex', 'grade': 3.8}}

def averageGrade(students):
sum = 0.0
for key in students:
sum = sum + students[key]['grade']
average = sum / len(students)
return average

avg = averageGrade(students)
print("The average garde is: %0.2f" % (avg))

Functions – Default Arguments


def displayFruits(fruits=['apple', 'orange']):
print("There are %d fruits in the list" % (len(fruits)))
for item in fruits:
print(item)
# Using default arguments
displayFruits()
o/p: There are 2 fruits in the list
apple
orange
fruits = ['banana', 'pear', 'mango']
displayFruits(fruits)

o/p:
There are 3 fruits in the list
banana
pear
mango

Functions – Passing by Reference


def displayFruits(fruits):
print("There are %d fruits in the list" % (len(fruits)))
for item in fruits:

Core Concepts of IoT By Dr. V. Deepika - 17-


print(item)
#Adding one more fruit
fruits.append('mango')

fruits = ['banana', 'pear', 'apple']


displayFruits(fruits)

o/p:
There are 3 fruits in the list
banana
pear
apple

print("There are %d fruits in the list" % (len(fruits)))

o/p:
There are 4 fruits in the list

Functions – Keyword Arguments

You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.

Example:
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

o/p:
The youngest child is Linus

Arbitrary Keyword Arguments, **kwargs

• If you do not know how many keyword arguments that will be passed into your function, add two
asterisk: ** before the parameter name in the function definition.
• This way the function will receive a dictionary of arguments, and can access the items accordingly:

Ex:
If the number of keyword arguments is unknown, add a double ** before the parameter name:
def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")

o/p:
His last name is Refsnes

Core Concepts of IoT By Dr. V. Deepika - 18-


>>> def printStudentRecords(name,age=20,major='CS'):
print("Name: " + name)
print("Age: " + str(age))
print("Major: " + major)

#This will give error as name is required argument


>>>printStudentRecords()

o/p:
Error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: printStudentRecords() takes at least 1 argument (0 given)

#Correct use
>>>printStudentRecords(name='Alex')

o/p:
Name: Alex
Age: 20
Major: CS

>>> printStudentRecords(name='Bob',age=22,major='ECE')
o/p:
Name: Bob
Age: 22
Major: ECE

>>> printStudentRecords(name='Alan',major='ECE')
o/p:
Name: Alan
Age: 20
Major: ECE

#name is a formal argument.


#**kwargs is a keyword argument that receives all arguments except the formal argument as a
dictionary.

def student(name, **kwargs):


# print("Student Name: " + name)
for key in kwargs:
print(key + ':' + kwargs[key])

student(name='Bob', age ='20', major = 'CS')


o/p:
Student Name: Bob

Core Concepts of IoT By Dr. V. Deepika - 19-


age: 20
major: CS

Functions – Variable Length Arguments

def student(name, *varargs):


print("Student Name: " + name)
for item in varargs:
print(item)

student('Nav')

O/P:
Student Name: Nav

student('Amy', 'Age: 24')

O/P:
Student Name: Amy
Age: 24

student('Bob', 'Age: 20', 'Major: CS')


O/P:
Student Name: Bob
Age: 20
Major: CS
================================================================
Modules:

Consider a module to be the same as a code library.


A file containing a set of functions you want to include in your application.

Create a Module:
To create a module just save the code you want in a file with the file extension .py:

Ex: Save this code in a file named mymodule.py


def greeting(name):
print("Hello, " + name)

Use a Module:
Now we can use the module we just created, by using the import statement:
Ex:
Import the module named mymodule, and call the greeting function:
import mymodule

mymodule.greeting("Jonathan")

Core Concepts of IoT By Dr. V. Deepika - 20-


o/p:
Hello, Jonathan

Note: When using a function from a module, use the syntax: module_name.function_name.

Variables in Module
The module can contain functions, as already described, but also variables of all types(arrays,
dictionaries, objects etc):

Example
Save this code in the file mymodule.py

person1 = {"name": "John","age": 36,"country": "Norway"}

Example
Import the module named mymodule, and access the person1 dictionary:

import mymodule
a = mymodule.person1["age"]
print(a)

o/p:
36

Naming a Module
You can name the module file whatever you like, but it must have the file extension .py

Re-naming a Module
You can create an alias when you import a module, by using the as keyword:

Example
Create an alias for mymodule called mx:

import mymodule as mx
a = mx.person1["age"]
print(a)
o/p:
36

Built-in Modules
There are several built-in modules in Python, which you can import whenever you like.

Example
Import and use the platform module:

import platform
x = platform.system()

Core Concepts of IoT By Dr. V. Deepika - 21-


print(x)

O/p:
Windows

Using the dir() Function


There is a built-in function to list all the function names (or variable names) in a module. The
dir() function:

Example
List all the defined names belonging to the platform module:

import platform
x = dir(platform)
print(x)
O/p:
F:\pythonProject\venv\Scripts\python.exe F:/pythonProject/main.py
['_Processor', '_WIN32_CLIENT_RELEASES', '_WIN32_SERVER_RELEASES', '__builtins__',
'__cached__', '__copyright__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__',
'__version__', '_comparable_version', '_component_re', '_default_architecture', '_follow_symlinks',
'_get_machine_win32', '_ironpython26_sys_version_parser', '_ironpython_sys_version_parser',
'_java_getprop', '_libc_search', '_mac_ver_xml', '_node', '_norm_version', '_platform', '_platform_cache',
'_pypy_sys_version_parser', '_sys_version', '_sys_version_cache', '_sys_version_parser', '_syscmd_file',
'_syscmd_ver', '_uname_cache', '_unknown_as_blank', '_ver_output', '_ver_stages', 'architecture',
'collections', 'functools', 'itertools', 'java_ver', 'libc_ver', 'mac_ver', 'machine', 'node', 'os', 'platform',
'processor', 'python_branch', 'python_build', 'python_compiler', 'python_implementation', 'python_revision',
'python_version', 'python_version_tuple', 're', 'release', 'subprocess', 'sys', 'system', 'system_alias', 'uname',
'uname_result', 'version', 'win32_edition', 'win32_is_iot', 'win32_ver']

Note: The dir() function can be used on all modules, also the ones you create yourself.

Import from Module


You can choose to import only parts from a module, by using the from keyword.
Example
The module named mymodule has one function and one dictionary:

def greeting(name):
print("Hello, " + name)
person1 = {"name": "John", "age": 36, "country": "Norway"}

Example
Import only the person1 dictionary from the module:

from mymodule import person1


print (person1["age"])
o/p:
36

Core Concepts of IoT By Dr. V. Deepika - 22-


Note: When importing using the from keyword, do not use the module name when referring to
elements in the module. Example: person1["age"], not mymodule.person1["age"].

#student module - saved as student.py


def averageGrade(students):
sum = 0.0
for key in students:
sum = sum + students[key]['grade']
average = sum/len(students)
return average

def printRecords(students):
print("There are %d students" %(len(students)))
i=1
for key in students:
print("Student-%d: " % (i))
print("Name: " + students[key]['name'])
print("Grade: " + str(students[key]['grade']))
i = i+1

#Using student module in main.py


import student

students = {'1': {'name': 'Bob', 'grade': 2.5},


'2': {'name': 'Mary', 'grade': 3.5},
'3': {'name': 'David', 'grade': 4.2},
'4': {'name': 'John', 'grade': 4.1},
'5': {'name': 'Alex', 'grade': 3.8}}

student.printRecords(students)
o/p:
There are 5 students
Student-1:
Name: Bob
Grade: 2.5
Student-2:
Name: Mary
Grade: 3.5
Student-3:
Name: David
Grade: 4.2
Student-4:
Name: John
Grade: 4.1
Student-5:
Name: Alex
Grade: 3.8

Core Concepts of IoT By Dr. V. Deepika - 23-


avg = student. averageGrade(students)
print("The average garde is: %0.2f" % (avg))

o/p:
The average garde is: 3.62
====================================================================
Packages:
We don't usually store all of our files on our computer in the same location. We use a well-organized hierarchy
of directories for easier access.
Similar files are kept in the same directory, for example, we may keep all the songs in the "music" directory.
Analogous to this, Python has packages for directories and modules for files.
As our application program grows larger in size with a lot of modules, we place similar modules in one
package and different modules in different packages. This makes a project (program) easy to manage and
conceptually clear.
Similarly, as a directory can contain subdirectories and files, a Python package can have sub-packages and
modules.
A directory must contain a file named __init__.py in order for Python to consider it as a package. This file can
be left empty but we generally place the initialization code for that package in this file.
Here is an example. Suppose we are developing a game. One possible organization of packages and modules
could be as shown in the figure below.

Package Module Structure in Python Programming


Importing module from a package
We can import modules from packages using the dot (.) operator.
For example, if we want to import the start module in the above example, it can be done as follows:

import Game.Level.start

Now, if this module contains a function named select_difficulty(), we must use the full name to reference it.

Game.Level.start.select_difficulty(2)

If this construct seems lengthy, we can import the module without the package prefix as follows:

Core Concepts of IoT By Dr. V. Deepika - 24-


from Game.Level import start

We can now call the function simply as follows:

start.select_difficulty(2)

Another way of importing just the required function (or class or variable) from a module within a package
would be as follows:

from Game.Level.start import select_difficulty

Now we can directly call this function.

select_difficulty(2)

Although easier, this method is not recommended. Using the full namespace avoids confusion and prevents
two same identifier names from colliding.
While importing packages, Python looks in the list of directories defined in sys.path, similar as for module
search path.
Ex:
Let's create a package named mypackage, using the following steps:
• Create a package named 'mypackage'.
• create modules greet.py and functions.py with the following code:
greet.py
def SayHello(name):
print("Hello ", name)

functions.py
def sum(x,y):
print(x+y)
def average(x,y):
print((x+y)/2)
def power(x,y):
print(x**y)

That's it. We have created our package called mypackage. The following is a folder structure:

Package Folder Structure


Importing a Module from a Package:
Import the functions module from the mypackage package and call its power() function.
main.py

Core Concepts of IoT By Dr. V. Deepika - 25-


from mypackage import functions
functions.power(3,2)
o/p: 9

It is also possible to import specific functions from a module in the package.


main.py
from mypackage.functions import sum
sum(10,20)
o/p: 30
==================================================================
File Handling:

Opening and Closing Files


Until now, you have been reading and writing to the standard input and output. Now, we will see how to use
actual data files.
Python provides basic functions and methods necessary to manipulate files by default. You can do most of
the file manipulation using a file object.

The open Function


Before you can read or write a file, you have to open it using Python's built-in open() function. This function
creates a file object, which would be utilized to call other support methods associated with it.

Syntax
file object = open(file_name [, access_mode][, buffering])

Here are parameter details −


• file_name − The file_name argument is a string value that contains the name of the file that you want
to access.
• access_mode − The access_mode determines the mode in which the file has to be opened, i.e., read,
write, append, etc. A complete list of possible values is given below in the table. This is an optional
parameter and the default file access mode is read (r).
• buffering − If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line
buffering is performed while accessing a file. If you specify the buffering value as an integer greater
than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size
is the system default(default behavior).

Here is a list of the different modes of opening a file −


Sr.No. Mode & Description

1 r
Opens a file for reading only. The file pointer is placed at the beginning of the file. This is
the default mode.

2 rb
Opens a file for reading only in binary format. The file pointer is placed at the beginning of
the file. This is the default mode.

Core Concepts of IoT By Dr. V. Deepika - 26-


3 r+
Opens a file for both reading and writing. The file pointer placed at the beginning of the
file.

4 rb+
Opens a file for both reading and writing in binary format. The file pointer placed at the
beginning of the file.

5 w
Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist,
creates a new file for writing.

6 wb
Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file
does not exist, creates a new file for writing.

7 w+
Opens a file for both writing and reading. Overwrites the existing file if the file exists. If
the file does not exist, creates a new file for reading and writing.

8 wb+
Opens a file for both writing and reading in binary format. Overwrites the existing file if
the file exists. If the file does not exist, creates a new file for reading and writing.

9 a
Opens a file for appending. The file pointer is at the end of the file if the file exists. That is,
the file is in the append mode. If the file does not exist, it creates a new file for writing.

10 ab
Opens a file for appending in binary format. The file pointer is at the end of the file if the
file exists. That is, the file is in the append mode. If the file does not exist, it creates a new
file for writing.

11 a+
Opens a file for both appending and reading. The file pointer is at the end of the file if the
file exists. The file opens in the append mode. If the file does not exist, it creates a new file
for reading and writing.

12 ab+
Opens a file for both appending and reading in binary format. The file pointer is at the end
of the file if the file exists. The file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.

The file Object Attributes


Once a file is opened and you have one file object, you can get various information related to that file.
Here is a list of all the attributes related to a file object −

Core Concepts of IoT By Dr. V. Deepika - 27-


Sr.No. Attribute & Description

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.
Note − softspace attribute is not supported in Python 3.x

Example
#!/usr/bin/python3

# Open a file
fo = open("a.txt", "wb")
print ("Name of the file: ", fo.name)
print ("Closed or not : ", fo.closed)
print ("Opening mode : ", fo.mode)
fo.close()
This produces the following result −
Name of the file: a.txt
Closed or not : False
Opening mode : wb

The close() Method


The close() method of a file object flushes any unwritten information and closes the file object, after which
no more writing can be done.
Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good
practice to use the close() method to close a file.

Syntax
fileObject.close();

Example
#!/usr/bin/python3

# Open a file
fo = open("a.txt", "wb")
print ("Name of the file: ", fo.name)

# Close opened file


fo.close()
This produces the following result −
Name of the file: a.txt

Core Concepts of IoT By Dr. V. Deepika - 28-


Reading and Writing Files
The file object provides a set of access methods to make our lives easier. We would see how to
use read() and write() methods to read and write files.
The write() Method
The write() method writes any string to an open file. It is important to note that Python strings can have
binary data and not just text.
The write() method does not add a newline character ('\n') to the end of the string −

Syntax
fileObject.write(string);

Here, passed parameter is the content to be written into the opened file.

Example
#!/usr/bin/python3

# Open a file
fo = open("a.txt", "w")
fo.write( "Python is a great language.\nYeah its great!!\n")

# Close opend file


fo.close()
The above method would create foo.txt file and would write given content in that file and finally it would
close that file. If you would open this file, it would have the following content −
Python is a great language.
Yeah its great!!

The read() Method


The read() method reads a string from an open file. It is important to note that Python strings can have binary
data. apart from text data.

Syntax
fileObject.read([count]);

Here, passed parameter is the number of bytes to be read from the opened file. This method starts reading
from the beginning of the file and if count is missing, then it tries to read as much as possible, maybe until
the end of file.
Example
Let us take a file foo.txt, which we created above.
#!/usr/bin/python3

# Open a file
fo = open(“a.txt”, “r+”)
str = fo.read(10)
print (“Read String is : “, str)

Core Concepts of IoT By Dr. V. Deepika - 29-


# Close opened file
fo.close()
This produces the following result –
Read String is : Python is

File Positions
The tell() method tells you the current position within the file; in other words, the next read or write will
occur at that many bytes from the beginning of the file.
The seek(offset[, from]) method changes the current file position. The offset argument indicates the number
of bytes to be moved. The from argument specifies the reference position from where the bytes are to be
moved.
If from is set to 0, the beginning of the file is used as the reference position. If it is set to 1, the current position
is used as the reference position. If it is set to 2 then the end of the file would be taken as the reference
position.
Example
Let us take a file foo.txt, which we created above.
#!/usr/bin/python3

# Open a file
fo = open("a.txt", "r+")
str = fo.read(10)
print ("Read String is : ", str)

# Check current position


position = fo.tell()
print ("Current file position : ", position)

# Reposition pointer at the beginning once again


position = fo.seek(0, 0) #from = 0,1,2
str = fo.read(10)
print ("Again read String is : ", str)

# Close opened file


fo.close()
This produces the following result −
Read String is : Python is
Current file position : 10
Again read String is : Python is

Renaming and Deleting Files


Python os module provides methods that help you perform file-processing operations, such as renaming and
deleting files.
To use this module, you need to import it first and then you can call any related functions.
The rename() Method
The rename() method takes two arguments, the current filename and the new filename.

Core Concepts of IoT By Dr. V. Deepika - 30-


Syntax
os.rename(current_file_name, new_file_name)

Example
Following is an example to rename an existing file test1.txt −
#!/usr/bin/python3
import os

# Rename a file from test1.txt to test2.txt


os.rename( "test1.txt", "test2.txt" )

The remove() Method


You can use the remove() method to delete files by supplying the name of the file to be deleted as the
argument.
Syntax
os.remove(file_name)

Example
Following is an example to delete an existing file test2.txt −
#!/usr/bin/python3
import os

# Delete file test2.txt


os.remove("text2.txt")
# Example of reading an entire file
file.txt
This is a test file.

main.py
fp = open('file.txt','r')
content = fp.read()
print(content)
fp.close()

o/p:
This is a test file.
# Example of reading line by line
file1.txt
Python supports more than one programming paradigms.
Python is an interpreted language.

main.py
fp = open('file1.txt','r')
print("Line-1: " + fp.readline())
print("Line-2: " + fp.readline())
fp.close()

Core Concepts of IoT By Dr. V. Deepika - 31-


o/p:
Line-1: Python supports more than one programming paradigms.
Line-2: Python is an interpreted language.

# Example of reading lines in a loop


fp = open('file.txt','r')
lines = fp.readlines()
for line in lines:
print(line)

o/p:
Python supports more than one programming paradigms.
Python is an interpreted language.
===================================================================
Date/Time Operations:
we can import a module named datetime to work with dates as date objects.
Example
Import the datetime module and display the current date:
import datetime

x = datetime.datetime.now()
print(x)
O/p:
2021-06-06 23:14:25.497227

The date contains year, month, day, hour, minute, second, and microsecond.
The datetime module has many methods to return information about the date object.
Here are a few examples, you will learn more about them later in this chapter:

Ex:
Return the year and name of weekday:
import datetime

x = datetime.datetime.now()

print(x.year)
print(x.strftime("%A"))
O/p:
2021
Sunday

Creating Date Objects


To create a date, we can use the datetime() class (constructor) of the datetime module.
The datetime() class requires three parameters to create a date: year, month, day.
Example
Create a date object:

Core Concepts of IoT By Dr. V. Deepika - 32-


import datetime

x = datetime.datetime(2020, 5, 17)
print(x)
O/p:
2020-05-17 00:00:00

The datetime() class also takes parameters for time and timezone (hour, minute, second, microsecond,
tzone), but they are optional, and has a default value of 0, (None for timezone).

The strftime() Method


The datetime object has a method for formatting date objects into readable strings.
The method is called strftime(), and takes one parameter, format, to specify the format of the returned string:
Example
Display the name of the month:
import datetime

x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))
O/p:
June

A reference of all the legal format codes:


Directive Description Example

%a Weekday, short version Wed

%A Weekday, full version Wednesday

%w Weekday as a number 0-6, 0 is Sunday 3

%d Day of month 01-31 31

%b Month name, short version Dec

%B Month name, full version December

%m Month as a number 01-12 12

%y Year, short version, without century 18

%Y Year, full version 2018

%H Hour 00-23 17

%I Hour 00-12 05

%p AM/PM PM

Core Concepts of IoT By Dr. V. Deepika - 33-


%M Minute 00-59 41

%S Second 00-59 08

%f Microsecond 000000-999999 548513

%z UTC offset +0100

%Z Timezone CST

%j Day number of year 001-366 365

%U Week number of year, Sunday as the first day of week, 00-53 52

%W Week number of year, Monday as the first day of week, 00-53 52

%c Local version of date and time Mon Dec 31 17:41:00 2018

%x Local version of date 12/31/18

%X Local version of time 17:41:00

%% A % character %

%G ISO 8601 year 2018

%u ISO 8601 weekday (1-7) 1

%V ISO 8601 weeknumber (01-53) 01

# Examples of manipulating with date


from datetime import date
now = date.today()
print("Date: " + now.strftime("%m-%d-%y"))
Date: 07-24-13

now = date.today()
print("Day of Week: " + now.strftime("%A"))
Day of Week: Wednesday

now = date.today()
print( "Month: " + now.strftime("%B"))
Month: July
now = date.today()
then = date(2013, 6, 7)
timediff = now - then
print(timediff.days)
47

Core Concepts of IoT By Dr. V. Deepika - 34-


# Examples of manipulating with time
import time
nowtime = time.time()
print(time.asctime(time.localtime(nowtime)))
Sat Jun 5 12:41:09 2021

import time
print(time.strftime("The date is %d-%m-%y. Today is a %A. It is %H hours, %M minutes and %S
seconds now."))
The date is 05-06-21. Today is a Saturday. It is 12 hours, 41 minutes and 09 seconds now.
====================================================================
Classes:
• Python is an Object-Oriented Programming (OOP) language. Python provides all the standard
features of OOP such as classes, class variables, class methods, inheritance, function overloading and
operator overloading.
• Class
• A class is simply a representation of a type of object and a user-defined prototype for an
object that is composed of three things: a name, attributes and operations/methods.
• Instance/Object
• An object is an instance of the data structure defined by a class.
• Inheritance
• Inheritance is the process of forming a new class from an existing class or base class.
• Function overloading
• Function overloading is a form of polymorphism that allows a function to have different
meanings, depending on its context.
• Operator overloading
• Operator overloading is a form of polymorphism that allows assignment of more than one
function to a particular operator.
• Function overriding
• Function overriding allows a child class to provide a specific implementation of a function
that is already provided by the base class. Child class implementation of the overridden
function has the same name, parameters and return type as the function in the base class.
Ex: 1

Core Concepts of IoT By Dr. V. Deepika - 35-


class Robot:
def introduce_self(self):
print("My name is " + self.name)
r1 = Robot()
r1.name = "Tom"
r1.color = "red"
r1.weight = 30
r2 = Robot()
r2.name = "Jerry"
r2.color = "blue"
r2.weight = 40
r1.introduce_self()
r2.introduce_self()

My name is Tom
My name is Jerry

Ex: same example using constructor


class Robot:
def __init__(self, name, color, weight):
self.name = name
self.color = color
self.weight = weight

def introduce_self(self):
print("My name is " + self.name)

# r1 = Robot()
# r1.name = "Tom"
# r1.color = "red"
# r1.weight = 30
#
# r2 = Robot()
# r2.name = "Jerry"
# r2.color = "blue"
# r2.weight = 40

r1 = Robot("Tom", "red", 30)


r2 = Robot("Jerry", "blue", 40)

r1.introduce_self()
r2.introduce_self()
o/p:
My name is Tom
My name is Jerry
Core Concepts of IoT By Dr. V. Deepika - 36-
Ex: 2
• The variable studentCount is a class variable that is shared by all instances of the class Student and is
accessed by Student.studentCount.
• The variables name, id and grades are instance variables which are specific to each instance of the
class.
• There is a special method by the name __init__() which is the class constructor.
• The class constructor initializes a new instance when it is created.
• The function __del__() is the class destructor.

# Examples of a class
class Student:
studentCount = 0

def __init__(self, name, id):


print("Constructor called")
self.name = name
self.id = id
Student.studentCount = Student.studentCount + 1
self.grades={}
def __del__(self):
print("Destructor called")
def getStudentCount(self):
return Student.studentCount
def addGrade(self,key,value):
self.grades[key]=value
def getGrade(self,key):
return self.grades[key]
def printGrades(self):
for key in self.grades:
print(key + ": " + self.grades[key])
s = Student('Steve','98928')
s.addGrade('Math','90')
s.addGrade('Physics','85')
s.printGrades()

mathgrade = s.getGrade('Math')
print(mathgrade)
count = s.getStudentCount()
print(count)
del s
O/p:
Constructor called
Math: 90
Physics: 85
90
1
Destructor called

Core Concepts of IoT By Dr. V. Deepika - 37-


Class Inheritance:
Inheritance allows us to define a class that inherits all the methods and properties from another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
Create a Parent Class
Any class can be a parent class, so the syntax is the same as creating any other class:

Example
Create a class named Person, with firstname and lastname properties, and a printname method:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname

def printname(self):
print(self.firstname, self.lastname)

#Use the Person class to create an object, and then execute the printname method:

x = Person("John", "Doe")
x.printname()
O/p: John Doe

Create a Child Class


To create a class that inherits the functionality from another class, send the parent class as a parameter when
creating the child class:

Example
Create a class named Student, which will inherit the properties and methods from the Person class:
class Student(Person):
pass

Note: Use the pass keyword when you do not want to add any other properties or methods to the class.
Now the Student class has the same properties and methods as the Person class.

Example
Use the Student class to create an object, and then execute the printname method:

x = Student("Mike", "Olsen")
x.printname()

O/p: Mike Olsen


====================================================================
Exception:
An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the
program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it
raises an exception. An exception is a Python object that represents an error.

Core Concepts of IoT By Dr. V. Deepika - 38-


When a Python script raises an exception, it must either handle the exception immediately otherwise it
terminates and quits.

Handling an exception:
Syntax:
Here is simple syntax of try....except...else blocks −
try:
You do your operations here
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.

Exception handling:
Standard Exceptions
Here is a list of Standard Exceptions available in Python. −
Sr.No. Exception Name & Description

1 Exception
Base class for all exceptions

2 StopIteration
Raised when the next() method of an iterator does not point to any object.

3 SystemExit
Raised by the sys.exit() function.

4 StandardError
Base class for all built-in exceptions except StopIteration and SystemExit.

5 ArithmeticError
Base class for all errors that occur for numeric calculation.

6 OverflowError
Raised when a calculation exceeds maximum limit for a numeric type.

7 FloatingPointError
Raised when a floating point calculation fails.

8 ZeroDivisonError
Raised when division or modulo by zero takes place for all numeric types.

9 AssertionError
Raised in case of failure of the Assert statement.

Core Concepts of IoT By Dr. V. Deepika - 39-


10 AttributeError
Raised in case of failure of attribute reference or assignment.

11 EOFError
Raised when there is no input from either the raw_input() or input() function and the end of
file is reached.

12 ImportError
Raised when an import statement fails.

13 KeyboardInterrupt
Raised when the user interrupts program execution, usually by pressing Ctrl+c.

14 LookupError
Base class for all lookup errors.

15 IndexError
Raised when an index is not found in a sequence.

16 KeyError
Raised when the specified key is not found in the dictionary.

17 NameError
Raised when an identifier is not found in the local or global namespace.

18 UnboundLocalError
Raised when trying to access a local variable in a function or method but no value has been
assigned to it.

19 EnvironmentError
Base class for all exceptions that occur outside the Python environment.

20 IOError
Raised when an input/ output operation fails, such as the print statement or the open()
function when trying to open a file that does not exist.

21 OSError
Raised for operating system-related errors.

22 SyntaxError
Raised when there is an error in Python syntax.

23 IndentationError
Raised when indentation is not specified properly.

24 SystemError
Raised when the interpreter finds an internal problem, but when this error is encountered
the Python interpreter does not exit.

Core Concepts of IoT By Dr. V. Deepika - 40-


25 SystemExit
Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the
code, causes the interpreter to exit.

26 TypeError
Raised when an operation or function is attempted that is invalid for the specified data type.

27 ValueError
Raised when the built-in function for a data type has the valid type of arguments, but the
arguments have invalid values specified.

28 RuntimeError
Raised when a generated error does not fall into any category.

29 NotImplementedError
Raised when an abstract method that needs to be implemented in an inherited class is not
actually implemented.

Example
This example opens a file, writes content in the, file and comes out gracefully because there is no problem at
all −
#!/usr/bin/python3

try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
fh.close()
This produces the following result −
Written content in the file successfully

Example
This example tries to open a file where you do not have the write permission, so it raises an exception −
#!/usr/bin/python3
try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
This produces the following result −
Error: can't find file or read data

Core Concepts of IoT By Dr. V. Deepika - 41-


Python packages – JSON, XML, HTTPLib, URLLib, SMTPLib

JSON:
• JavaScript Object Notation (JSON) is an easy to read and write data-interchange format.
• JSON is used as an alternative to XML and is easy for machines to parse and generate.
• JSON is built on two structures:
• a collection of name–value pairs (e.g., a Python dictionary)
• ordered lists of values (e.g., a Python list).

JSON is a syntax for storing and exchanging data.


JSON is text, written with JavaScript object notation.

JSON in Python
Python has a built-in package called json, which can be used to work with JSON data.

Example
Import the json module:
import json

Parse JSON - Convert from JSON to Python


If you have a JSON string, you can parse it by using the json.loads() method.
The result will be a Python dictionary.
Example
Convert from JSON to Python:
import json

# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'

# parse x:
y = json.loads(x)

# the result is a Python dictionary:


print(y["age"])
O/p: 30

Convert from Python to JSON:


If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.

Example
Convert from Python to JSON:
import json

# a Python object (dict):


x={
"name": "John",
"age": 30,
Core Concepts of IoT By Dr. V. Deepika - 42-
"city": "New York"
}

# convert into JSON:


y = json.dumps(x)
# y = json.dumps(x, indent=4)

# the result is a JSON string:


print(y)
O/p:
{"name": "John", "age": 30, "city": "New York"}

O/p:
{
"name": "John",
"age": 30,
"city": "New York"
}

You can convert Python objects of the following types, into JSON strings:
• dict
• list
• tuple
• string
• int
• float
• True
• False
• None

Example
Convert Python objects into JSON strings, and print the values:
import json

print(json.dumps({"name": "John", "age": 30}))


print(json.dumps(["apple", "bananas"]))
print(json.dumps(("apple", "bananas")))
print(json.dumps("hello"))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))

O/p:
{"name": "John", "age": 30}
["apple", "bananas"]

Core Concepts of IoT By Dr. V. Deepika - 43-


["apple", "bananas"]
"hello"
42
31.76
true
false
null

When you convert from Python to JSON, Python objects are converted into the JSON (JavaScript)
equivalent:
Python JSON

dict Object

list Array

tuple Array

str String

int Number

float Number

True true

False false

None null

Example
Convert a Python object containing all the legal data types:
import json

x={
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}

Core Concepts of IoT By Dr. V. Deepika - 44-


print(json.dumps(x))

O/P:
{"name": "John", "age": 30, "married": true, "divorced": false, "children": ["Ann", "Billy"], "pets": null,
"cars": [{"model": "BMW 230", "mpg": 27.5}, {"model": "Ford Edge", "mpg": 24.1}]}

Format the Result


The example above prints a JSON string, but it is not very easy to read, with no indentations and line breaks.
The json.dumps() method has parameters to make it easier to read the result:

Example
Use the indent parameter to define the numbers of indents:

print(json.dumps(x, indent=4))

O/P:
{
"name": "John",
"age": 30,
"married": true,
"divorced": false,
"children": [
"Ann",
"Billy"
],
"pets": null,
"cars": [
{
"model": "BMW 230",
"mpg": 27.5
},
{
"model": "Ford Edge",
"mpg": 24.1
}
]
}

You can also define the separators, default value is (", ", ": "), which means using a comma and a space to
separate each object, and a colon and a space to separate keys from values:

Example
Use the separators parameter to change the default separator:

print(json.dumps(x, indent=4, separators=(". ", " = ")))

Core Concepts of IoT By Dr. V. Deepika - 45-


O/P:
{
"name" = "John".
"age" = 30.
"married" = true.
"divorced" = false.
"children" = [
"Ann".
"Billy"
].
"pets" = null.
"cars" = [
{
"model" = "BMW 230".
"mpg" = 27.5
}.
{
"model" = "Ford Edge".
"mpg" = 24.1
}
]
}

Order the Result


The json.dumps() method has parameters to order the keys in the result:

Example
Use the sort_keys parameter to specify if the result should be sorted or not:

print(json.dumps(x, indent=4, sort_keys=True))

O/P:
{
"age": 30,
"cars": [
{
"model": "BMW 230",
"mpg": 27.5
},
{
"model": "Ford Edge",
"mpg": 24.1
}
],
"children": [
"Ann",
"Billy"

Core Concepts of IoT By Dr. V. Deepika - 46-


],
"divorced": false,
"married": true,
"name": "John",
"pets": null
}

Core Concepts of IoT By Dr. V. Deepika - 47-


====================================================================

XML:
• XML (Extensible Markup Language) is a data format for structured document interchange.
• The Python minidom library provides a minimal implementation of the Document Object
Model interface.
• It has an API similar to that in other languages.

What is XML?
The Extensible Markup Language (XML) is a markup language much like HTML or SGML. This is
recommended by the World Wide Web Consortium and available as an open standard.
XML is extremely useful for keeping track of small to medium amounts of data without requiring an SQL-
based backbone.

XML Parser Architectures and APIs


The Python standard library provides a minimal but useful set of interfaces to work with XML.
The two most basic and broadly used APIs to XML data are the SAX and DOM interfaces.
• Simple API for XML (SAX) − Here, you register callbacks for events of interest and then let the
parser proceed through the document. This is useful when your documents are large or you have
memory limitations, it parses the file as it reads it from the disk and the entire file is never stored in
the memory.
• Document Object Model (DOM) API − This is a World Wide Web Consortium recommendation
wherein the entire file is read into the memory and stored in a hierarchical (tree-based) form to
represent all the features of an XML document.
SAX obviously cannot process information as fast as DOM, when working with large files. On the other
hand, using DOM exclusively can really kill your resources, especially if used on many small files.
SAX is read-only, while DOM allows changes to the XML file. Since these two different APIs literally
complement each other, there is no reason why you cannot use them both for large projects.

Core Concepts of IoT By Dr. V. Deepika - 48-


For all our XML code examples, let us use a simple XML file movies.xml as an input −
#movies.xml
<collection shelf = "New Arrivals">
<movie title = "Enemy Behind">
<type>War, Thriller</type>
<format>DVD</format>
<year>2003</year>
<rating>PG</rating>
<stars>10</stars>
<description>Talk about a US-Japan war</description>
</movie>
<movie title = "Transformers">
<type>Anime, Science Fiction</type>
<format>DVD</format>
<year>1989</year>
<rating>R</rating>
<stars>8</stars>
<description>A schientific fiction</description>
</movie>
<movie title = "Trigun">
<type>Anime, Action</type>
<format>DVD</format>
<episodes>4</episodes>
<rating>PG</rating>
<stars>10</stars>
<description>Vash the Stampede!</description>
</movie>
<movie title = "Ishtar">
<type>Comedy</type>
<format>VHS</format>
<rating>PG</rating>
<stars>2</stars>
<description>Viewable boredom</description>
</movie>
</collection>

Parsing XML with SAX APIs


SAX is a standard interface for event-driven XML parsing. Parsing XML with SAX generally requires you
to create your own ContentHandler by subclassing xml.sax.ContentHandler.
Your ContentHandler handles the particular tags and attributes of your flavor(s) of XML. A ContentHandler
object provides methods to handle various parsing events. Its owning parser calls ContentHandler methods
as it parses the XML file.
The methods startDocument and endDocument are called at the start and the end of the XML file. The
method characters(text) is passed the character data of the XML file via the parameter text.
The ContentHandler is called at the start and end of each element. If the parser is not in namespace mode,
the methods startElement(tag, attributes) and endElement(tag) are called; otherwise, the corresponding

Core Concepts of IoT By Dr. V. Deepika - 49-


methods startElementNS and endElementNS are called. Here, tag is the element tag, and attributes is an
Attributes object.
Here are other important methods to understand before proceeding −

The make_parser Method


The following method creates a new parser object and returns it. The parser object created will be of the first
parser type, the system finds.
xml.sax.make_parser( [parser_list] )
Here are the details of the parameters −
• parser_list − The optional argument consisting of a list of parsers to use which must all implement
the make_parser method.

The parse Method


The following method creates a SAX parser and uses it to parse a document.
xml.sax.parse( xmlfile, contenthandler[, errorhandler])
Here are the details of the parameters −
• xmlfile − This is the name of the XML file to read from.
• contenthandler − This must be a ContentHandler object.
• errorhandler − If specified, errorhandler must be a SAX ErrorHandler object.

The parseString Method


There is one more method to create a SAX parser and to parse the specified XML string.
xml.sax.parseString(xmlstring, contenthandler[, errorhandler])
Here are the details of the parameters −
• xmlstring − This is the name of the XML string to read from.
• contenthandler − This must be a ContentHandler object.
• errorhandler − If specified, errorhandler must be a SAX ErrorHandler object.

Example: main.py
#!/usr/bin/python3

import xml.sax

class MovieHandler( xml.sax.ContentHandler ):


def __init__(self):
self.CurrentData = ""
self.type = ""
self.format = ""
self.year = ""
self.rating = ""
self.stars = ""
self.description = ""

# Call when an element starts


def startElement(self, tag, attributes):
self.CurrentData = tag
Core Concepts of IoT By Dr. V. Deepika - 50-
if tag == "movie":
print ("*****Movie*****")
title = attributes["title"]
print ("Title:", title)

# Call when an elements ends


def endElement(self, tag):
if self.CurrentData == "type":
print ("Type:", self.type)
elif self.CurrentData == "format":
print ("Format:", self.format)
elif self.CurrentData == "year":
print ("Year:", self.year)
elif self.CurrentData == "rating":
print ("Rating:", self.rating)
elif self.CurrentData == "stars":
print ("Stars:", self.stars)
elif self.CurrentData == "description":
print ("Description:", self.description)
self.CurrentData = ""

# Call when a character is read


def characters(self, content):
if self.CurrentData == "type":
self.type = content
elif self.CurrentData == "format":
self.format = content
elif self.CurrentData == "year":
self.year = content
elif self.CurrentData == "rating":
self.rating = content
elif self.CurrentData == "stars":
self.stars = content
elif self.CurrentData == "description":
self.description = content

if ( __name__ == "__main__"):

# create an XMLReader
parser = xml.sax.make_parser()
# turn off namepsaces
parser.setFeature(xml.sax.handler.feature_namespaces, 0)

# override the default ContextHandler


Handler = MovieHandler()
parser.setContentHandler( Handler )

Core Concepts of IoT By Dr. V. Deepika - 51-


parser.parse("movies.xml")

Output
This would produce the following result −
*****Movie*****
Title: Enemy Behind
Type: War, Thriller
Format: DVD
Year: 2003
Rating: PG
Stars: 10
Description: Talk about a US-Japan war
*****Movie*****
Title: Transformers
Type: Anime, Science Fiction
Format: DVD
Year: 1989
Rating: R
Stars: 8
Description: A scientific fiction
*****Movie*****
Title: Trigun
Type: Anime, Action
Format: DVD
Rating: PG
Stars: 10
Description: Vash the Stampede!
*****Movie*****
Title: Ishtar
Type: Comedy
Format: VHS
Rating: PG
Stars: 2
Description: Viewable boredom

Core Concepts of IoT By Dr. V. Deepika - 52-


Core Concepts of IoT By Dr. V. Deepika - 53-
====================================================================

HTTPLib & URLLib


• HTTPLib2 and URLLib2 are Python libraries used in network/internet programming.

Core Concepts of IoT By Dr. V. Deepika - 54-


Core Concepts of IoT By Dr. V. Deepika - 55-
==================================================================================
SMTPLib
• Simple Mail Transfer Protocol (SMTP) is a protocol which handles sending email and
routing email between mail servers.
• The Python SMTPLib module provides an SMTP client session object that can be used to
send email.

Core Concepts of IoT By Dr. V. Deepika - 56-


Core Concepts of IoT By Dr. V. Deepika - 57-

You might also like