Unit-4 Python Topic in IoT (1)
Unit-4 Python Topic in IoT (1)
IoT Systems –
Logical Design using Python
Outline
• Introduction to Python
• Installing Python
• Python Data Types & Data Structures
• Control Flow
• Functions
• Modules
• Packages
• File Input/Output
• Date/Time Operations
• Classes
Python
• Python is a general-purpose high level programming language and suitable for providing a solid
foundation to the reader in the area of cloud computing.
• Windows
• Python binaries for Windows can be downloaded from http://www.python.org/getit .
• For the examples and exercise in this book, you would require Python 2.7 which can be directly downloaded from:
http://www.python.org/ftp/python/2.7.5/python-2.7.5.msi
• Once the python binary is installed you can run the python shell at the command prompt using
> python
• Linux
#Install Dependencies
sudo apt-get install build-essential
sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev
#Download Python
wget http://python.org/ftp/python/2.7.5/Python-2.7.5.tgz tar
-xvf Python-2.7.5.tgz
cd Python-2.7.5
#Install Python
./configure
make
sudo make
install
Numbers
• Numbers
• 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 #Addition #Division
>>>a=5 >>>c=a+b >>>f=b/a
>>>type(a) >>> >>>
<type c f
’int’> 7.5 0.5
#Floating >>>t >>>
Point ype( type
>>>b=2.5 c)
#Subtraction (f)
#Power
>>>type(b) <typ
>>>d=a-b <typ
>>>g=a**
<type ’float’> e
>>> e
2
#Long d’floa float
>>>
>>>x=9898878787676 t’>
2.5 ’> 25
g
L >>>t
>>>type(x) ype(
<type ’long’> d)
#Multiplicatio
#Complex n <typ
>>>y=2+5j e
>>>e=a*b
>>>y ’floa
>>>
et’>
(2+5j 12.5
) >>>t
>>>t ype(
ype(y e)
) <typ
<type e
’com ’floa
plex’ t’>
>
Strings
• 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 #Print string #strip: Returns a copy of the string with
>>>s="Hello World!" >>>print s the #leading and trailing characters
>>>type(s) Hello removed.
<type ’str’> World!
>>>s.strip("!"
#String concatenation #Formattin ) ’Hello
>>>t="This is sample program." g output World’
>>>r = s+t >>>print "The string (The string (Hello
>>>r World!) has 12 characters
’Hello World!This is sample program.’
#Convert to upper/lower case
#Get length of string >>>s.upper()
>>>len(s ’HELLO
) 12 WORLD!’
>>>s.lower()
#Conver ’hello
t string world!’
to
integer #Accessing
>>>x="1 sub-strings
00" >>>s[0
>>>type( ] ’H’
s) >>>s[6
<type :]
’str’> ’World
>>>y=int !’
(x) >>>s[6
>>> :-1]
Lists
• Lists
• List a compound data type used to group together other values. List items need not all have the same type. A list contains items
separated by commas and enclosed within square brackets.
#Mixed data types in a list
#Create List #Removing an item from a list >>>mixed=[’data’,5,100.1,8287398L]
>>>fruits=[’apple’,’orange’,’banana’,’mango’] >>>fruits.remove(’mango’) >>>type(mixed)
>>>type(fruits) >>>fruits <type ’list’>
<type ’list’> [’apple’, ’orange’, ’banana’, ’pear’] >>>type(mixed[0])
<type ’str’>
#Get Length of List #Inserting an item to a list >>>type(mixed[1])
>>>len(fruits >>>fruits.insert(1,’mango’) <type ’int’>
) 4 >>>fruits >>>type(mixed[2])
[’apple’, ’mango’, ’orange’, ’banana’, ’pear’] <type ’float’>
#Access List >>>type(mixed[3])
Elements #Combining lists <type ’long’>
>>>fruits[1 >>>vegetables=[’potato’,’carrot’,’onion’,’beans’,’
] ’orange’ r adish’] #Change individual elements of a list
>>>fruits[1:3] >>>vegetables >>>mixed[0]=mixed[0]+" items"
[’orange’, ’banana’] [’potato’, ’carrot’, ’onion’, ’beans’, ’radish’] >>>mixed[1]=mixed[1]+1
>>>fruits[1:] >>>mixed[2]=mixed[2]+0.05
[’orange’, ’banana’, >>>eatables=fruits+vegetables >>>mixed
’mango’] >>>eatables [’data items’, 6, 100.14999999999999, 8287398L]
[’appl
#Appending an e’, #Lists can be nested
item to a list ’mang >>>nested=[fruits,vegetables]
>>>fruits.append(’ o’, >>>nested
pear’) ’orang [[’apple’, ’mango’, ’orange’, ’banana’, ’pear’],
>>>fruits e’, [’potato’, ’carrot’, ’onion’, ’beans’, ’radish’]]
[’apple’, ’orange’, ’banan
’banana’, ’mango’, a’,
’pear’] ’pear’,
’potato
Tuples
• Tuples
• A tuple is a sequence data type that is 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.
• 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 for keys. Values in a dictionary can be any data type or object.
#Create a dictionary #Get all keys in a dictionary #Check if dictionary has a key
>>>student={’name’:’Mary’,’id’:’8776’,’major’:’CS’} >>>student.keys() >>>student.has_key(’name’)
>>>student [’gender’, ’major’, ’name’, ’id’] True
{’major’: ’CS’, ’name’: ’Mary’, ’id’: ’8776’} >>>student.has_key(’grade’)
>>>type(student) #Get all values in a dictionary False
<type ’dict’> >>>student.values()
[’female’, ’CS’, ’Mary’,
#Get length of a dictionary ’8776’]
>>>len(student)
3 #Add new key-value pair
>>>student[’gender’]=’femal
#Get the value e’
of a key in >>>student
dictionary {’gende
>>>student[’name’] r’: ’female’, ’major’: ’CS’,
’Mary’ ’name’: ’Mary’, ’id’: ’8776’}
#Conver #Convert
t to float to set
>>>float(b >>>x=[’m
) 2013.0 ango’,’app
le’,’banana
’,’mango’,
’banana’]
>>>set(x)
set([’mang
o’, ’apple’,
’banana’])
Control Flow – if statement
• The for statement in Python iterates over items of any sequence (list, string, etc.) in the order in which they
appear in the sequence.
• This behavior is different from the for statement in other languages such as C in which an initialization,
incrementing and stopping criteria are provided.
for
Syntax: For iterating_var in sequence:
Execute Statements
Control Flow – while statement
• The while statement in Python executes the statements within the while loop as long as the while condition is
true.
>>> i = 0
>>> while
i<=100: if i%2
== 0:
print i
i = i+1
Control Flow – range statement
#Generate a list of numbers from 0 – 9 #Generate a list of numbers from 10 - 100 with
increments of 10
>>>range (10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>>range(10,110,10)
[10, 20, 30, 40, 50, 60, 70, 80, 90,100]
Control Flow – break/continue statements
• The break and continue statements in Python are similar to the statements in C.
• Break #Break statement example
• Break statement breaks out of the for/while loop >>>y=1
>>>for x in range(4,256,4):
y=y*x
if y >
512:
b
r
e
a
k
print y
• Continue 4
32
#Continue statement example
• Continue statement continues with the next iteration. 384
>>>fruits=[’apple’,’orange’,’banana’,’mango’]
>>>for item in fruits:
if item == "banana":
continue
else:
print item
apple
orange
mango
Control Flow – pass statement
>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 information in (in the form of students = { '1': {'name': 'Bob', 'grade': 2.5},
parameters), does some computation, and returns a new piece of '2': {'name': 'Mary', 'grade': 3.5},
'3': {'name': 'David', 'grade': 4.2},
information based on the parameter information. '4': {'name': 'John', 'grade': 4.1},
'5': {'name': 'Alex', 'grade': 3.8}}
>>>def displayFruits(fruits=[’apple’,’orange’]):
print "There are %d fruits in the list" % (len(fruits))
for item in fruits:
print item
>>>fruits =
[’banana’, ’pear’,
’mango’]
>>>displayFruits(fruits
) banana
pear
mango
Functions-Passing by Reference
>>>def displayFruits(fruits):
print "There are %d fruits in the list" % (len(fruits))
for item in fruits:
print item
print "Adding one more fruit"
fruits.append('mango')
#Add
ing
one
more
fruit
>>>print "There are %d fruits in the list" %
(len(fruits)) There are 4 fruits in the list
Functions - Keyword Arguments
• Functions can also be called using keyword arguments that identifies the arguments by the parameter name when the
function is called.
• Python functions can have variable length arguments. The variable length arguments are passed to as a tuple to the
function with an argument prefixed with asterix (*)
>>>student(’Nav’)
Student Name: Nav
exposure/
exposure
subpackage
init .py
_adapthist.py
exposure.py
feature/
feature subpackage
init .py
_brief.py
File Handling
• Python allows reading and writing to files using the file # Example of reading an entire file
object. >>>fp = open('file.txt','r')
>>>content = fp.read()
>>>print content
This is a test
• The open(filename, mode) function is used to get a file.
file object. >>>fp.close()
# Example of reading line by line
>>>fp = open('file1.txt','r')
• The mode can be read (r), write (w), append (a), read and >>>print "Line-1: " + fp.readline()
write (r+ or w+), read-binary (rb), write-binary (wb), etc. Line-1: Python supports more than one programming paradigms.
>>>print "Line-2: " + fp.readline()
Line-2: Python is an interpreted language.
>>>fp.close()
• After the file contents have been read the close function is
called which closes the file object. # Example of reading lines in a loop
>>>fp = open(’file1.txt’,’r’)
>>>lines = fp.readlines()
>>>for line in lines:
print line
• Python provides several functions for date and time access and conversions.
• The datetime module allows manipulating date and time in several ways.
• The time module in Python provides various time-related functions.
>>>then = date(2013, 6, 7)
>>>timediff = now - then
>>>timediff.day
s 47
Classes
• Python is an Object-Oriented Programming (OOP) language. Python provides all the standard features of Object
Oriented Programming 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 user-defined prototype for an object that is composed of three things: a name,
attributes, and operations/methods.
• Instance/Object
• 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.
Class Example
def draw(self):
print "Draw
Circle
Program execution process using IDLE
Numbers: This data type is used to store numeric values
Strings
Lists
Lists Contd..
Tuples
A tuple is a Sequence data type that is similar to that to the list.
Unlike lists, the elements of tuples cannot be changed, so tuples can be thought of as read-only lists.
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 for keys
Contd..
Control Flow
The if statement in python is similar to the if statement of other languages.
for
Syntax: For iterating_var in sequence:
Execute Statements
While
While(condition is true):
Statements…
range
5. Break/Continue
The Break statement breaks out for/while loop where as continue statement continues with next iteration
Continue
Pass
The pass statement is used when statement is required syntactically but you do not want any command or code to
execute.
Modules
Python allows organizing of the program code into different modules which improves the code readability and
management.
A module in python file defines some functionality in the form of functions or classes.
Modules can be imported using the import keyword.
Package
A Directory that contains __init__.py is a package.
A Package is a Hierarchical file directory structure that defines a single python application environment that consists of
modules and sub packages and sub sub packages and soon.
File Handling
Python allows reading and writing to files using the file object.
The open(filename, mode) function is used to get a file object.
The mode can be read(r),write(w),append(a),read binary(rb),write binary(wb),etc.,
After the file contents have been read the close () is called which closes the file object
Classes
Python is an object-oriented programming (oop) language.
Python provides all the standard features of Object Oriented Programming such as
classes
class variable
class methods
inheritance
originally specified by Douglas Crockford,. The official Internet media type for
The following example shows how to use JSON to store information related to books based on their topic and edition.
"
The process of encoding JSON is usually called serialization. This term
refers to the transformation of data into a series of bytes (hence serial) to
be stored or transmitted across a network. You may also hear the
term marshaling, but that’s a whole other discussion.
Naturally, deserialization is the reciprocal process of decoding data that
has been stored or delivered in the JSON standard.
A Simple Serialization Example
It is critical that you save this information to disk, so your mission is to write it to a file.
Using Python’s context manager, you can create a file called data_file.json and open it in write mode.
(JSON files conveniently end in a .json extension.)
Reading and Writing XML Files in Python
Object Model (DOM). The DOM is an application programming interface that treats XML as a tree
structure, where each node in the tree is an object. Thus, the use of this module requires that we are
The ElementTree module provides a more "Pythonic" interface to handling XMl and is a good option
As you can see, it's a fairly simple XML example, only containing a few nested objects
and one attribute.
Reading XML Documents
Using minidom
In order to parse an XML document using minidom, we must first import it from the xml.dom module. This
module uses the parse function to create a DOM object from our XML file. The parse function has the
following syntax:
xml.dom.minidom.parse (filename_or_file[,parser[, bufsize]])
Here the file name can be a string containing the file path or a file-type object. The function returns a
document, which can be handled as an XML type. Thus, we can use the
function getElementByTagName() to find a specific tag.
If we wanted to use an already-opened file, can just pass our file object to parse like
so:
Using ElementTree
ElementTree presents us with an very simple way to process XML files. As always, in order to use it we must
first import the module. In our code we use the import command with the as keyword, which allows us to
use a simplified name (ET in this case) for the module in the code.
Following the import, we create a tree structure with the parse function, and we obtain its root element.
Once we have access to the root node we can easily traverse around the tree, because a tree is a connected
graph.
Working Code
import xml.etree.ElementTree as xml
def GenerateXML(FileName):
root = xml.Element("Customers")
c1 = xml.Element("Customer type")
c1.text ="Business"
root.append(c1)
type1 = xml.SubElement(c1,"Place")
type1.text = "UK"
amount1 = xml.SubElement(c1,"Amount")
amount1.text = "15000"
tree = xml.ElementTree(root)
with open(FileName,'wb') as files:
tree.write(files)
if __name__=="__main__":
GenerateXML("Customer4.xml")