Iot (Python)
Iot (Python)
Iot (Python)
IoT Systems –
Logical Design using Python
Course Faculty:
Prof. Triveni.C.L
Dept of ECE
MCE Hassan
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.
#Create string #Print string #strip: Returns a copy of the string with the
>>>s="Hello World!" >>>print s Hello #leading and trailing characters removed.
>>>type(s) World!
<type ’str’> >>>s.strip("!")
#Formatting ’Hello World’
#String concatenation output
>>>t="This is sample program." >>>print "The string (The string (Hello World!) has
>>>r = s+t 12 characters
>>>r
’Hello World!This is sample program.’ #Convert to upper/lower case
>>>s.upper() ’HELLO
#Get length of string WORLD!’
>>>len(s) >>>s.lower()
12 ’hello world!’
#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’) True
>>>student [’gender’, ’major’, ’name’, ’id’] >>>student.has_key(’grade’) False
{’major’: ’CS’, ’name’: ’Mary’, ’id’: ’8776’}
>>>type(student) #Get all values in a dictionary
<type ’dict’> >>>student.values() [’female’, ’CS’, ’Mary’, ’8776’]
#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]
Control Flow – break/continue statements
• The break and continue statements in Python are similar to the statements in C.
• Break #Break statement example
>>>y=1
>>>for x in range(4,256,4):
y = y * x if y > 512:
Break statement breaks out of the for/while loop break
print y
4
32
384
• Continue
#Continue statement example
• Continue statement continues with the next iteration. >>>fruits=[’apple’,’orange’,’banana’,’mango’]
>>>for item in fruits:
if item == "banana":
continue
else:
print item
>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 Example of a function in Python
parameters), does some computation, and returns a new piece of
information based on the parameter information. 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},
• A function in Python is a block of code that begins with the keyword '5': {'name': 'Alex', 'grade': 3.8}}
def followed by the function name and parentheses. The function
parameters are enclosed within the parenthesis.
def averageGrade(students):
“This function computes the average grade”
sum = 0.0
• The code block within a function begins after a colon that comes after for key in students:
the parenthesis enclosing the parameters. sum = sum + students[key]['grade']
average = sum/len(students)
return average
>>>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')
• 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 subpackage
init .py
colorconv.py
colorlabel.py
rgb_colors.py
exposure/
exposure subpackage
init .py
_adapthist.py
exposure.py
feature/
feature subpackage
init .py
_brief.py
_daisy.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 file.
• The open(filename, mode) function is used to get a >>>fp.close()
file 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
>>>print "Month: " + now.strftime("%B") Month: July >>>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 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
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
(overridden
function)"
Further Reading
32