Iot Systems - Logical Design Using Python: Bahga & Madisetti, © 2015
Iot Systems - Logical Design Using Python: Bahga & Madisetti, © 2015
Iot Systems - Logical Design Using Python: Bahga & Madisetti, © 2015
IoT Systems –
Logical Design using Python
• Introduction to Python
• Installing Python
• Python Data Types & Data Structures
• Control Flow
• Functions
• Modules
• Packages
• File Input/Output
• Date/Time Operations
• Classes
• 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
• 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 the
>>>s="Hello World!" >>>print s #leading and trailing characters removed.
>>>type(s) Hello World!
<type ’str’> >>>s.strip("!")
#Formatting output ’Hello World’
#String concatenation >>>print "The string (The string (Hello World!)
>>>t="This is sample program." has 12 characters
>>>r = s+t
>>>r #Convert to upper/lower case
’Hello World!This is sample program.’ >>>s.upper()
’HELLO WORLD!’
#Get length of string >>>s.lower()
>>>len(s) ’hello world!’
12
#Accessing sub-strings
#Convert string to integer >>>s[0]
>>>x="100" ’H’
>>>type(s) >>>s[6:]
<type ’str’> ’World!’
>>>y=int(x) >>>s[6:-1]
>>>y ’World’
100
• 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’, ’8776’]
#Get length of a dictionary
>>>len(student) #Add new key-value pair
3 >>>student[’gender’]=’female’
>>>student
#Get the value of a key in dictionary {’gende
>>>student[’name’] r’: ’female’, ’major’: ’CS’, ’name’: ’Mary’, ’id’: ’8776’}
’Mary’
#A value in a dictionary can be another dictionary
#Get all items in a dictionary >>>student1={’name’:’David’,’id’:’9876’,’major’:’ECE’}
>>>student.items() >>>students={’1’: student,’2’:student1}
[(’gender’, ’female’), (’major’, ’CS’), (’name’, ’Mary’), >>>students
(’id’, ’8776’)] {’1’:
{’gende
r’: ’female’, ’major’: ’CS’, ’name’: ’Mary’, ’id’: ’8776’}, ’2’:
{’
major’: ’ECE’, ’name’: ’David’, ’id’: ’9876’}}
• 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.
#Looping over characters in a string #Looping over items in a list #Looping over keys in a dictionary
• The while statement in Python executes the statements within the while loop as long as the while condition is
true.
>>> i = 0
#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]
• 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:
break
print y
4
32
384
apple
orange
mango
>fruits=[’apple’,’orange’,’banana’,’mango’]
>for item in fruits:
if item == "banana":
pass
else:
print item
apple
orange
mango
• 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}}
avg = averageGrade(students)
print "The average garde is: %0.2f" % (avg)
• The first statement of the function body can optionally be a
documentation string or docstring.
>>>def displayFruits(fruits=[’apple’,’orange’]):
print "There are %d fruits in the list" % (len(fruits))
for item in fruits:
print item
>>>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')
• 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
• Python package is hierarchical file structure that consists of # skimage package listing
modules and subpackages. skimage/ Top level package
__init__.py Treat directory as a package
• Packages allow better organization of modules related to a single
application environment. color/ color color subpackage
__init__.py
colorconv.py
colorlabel.py
rgb_colors.py
• 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 file.
• The open(filename, mode) function is used to get a file >>>fp.close()
object.
# 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.
>>>print "Month: " + now.strftime("%B") >>>time.strftime("The date is %d-%m-%y. Today is a %A. It is %H hours, %M minutes and %S seconds now.")
Month: July 'The date is 24-07-13. Today is a Wednesday. It is 16 hours, 15 minutes and 14 seconds now.'
>>>then = date(2013, 6, 7)
>>>timediff = now - then
>>>timediff.days
47
• 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.
def draw(self):
print "Draw Circle (overridden function)"