Iot Unit III

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

Introduction to Python

Python is a general-purpose interpreted, interactive, object-oriented, and high-level


programming language. It was created by Guido van Rossum during 1985- 1990.
Python is designed to be highly readable.
The main characteristics of Python are:
1. Multi-paradigm programming language: Python supports more than one
programming paradigms including object-oriented programming and structured
programming.
2. 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.
3. Interactive Language: Python provides an interactive mode in which the user can
submit commands at the Python prompt and interact with the interpreter directly.
The key benefits of python:

Easy-to-learn,read and maintain: Python is a minimalistic language with relatively few


keywords. Due to its simplicity,programs written in python are generally easy to maintain.

Object and Procedure Oriented: Python supports both Object and Procedure Oriented.

Extendable: Python is an extendable language and allows integration of low-level


modules written in languages such as C,C++.

Scalable: Due to its minimalistic nature of python, it provides a manageable structure for
large programs.

Portable: Python programs can be directly executed from source code and copied from
one machine to other without worrying about portability.

Broad Library Support: Python has a broad library support and works on various
platforms such as windows, Linux, Mac, etc.
Installing python

Windows:

Python for windows can be downloaded from http://www.python.org.ghetit.

For Ex: 2.7 version can be downloaded as- http:www.python.org/ftp/python/2.7.5/python-


2.7.5.msi.

Once the python is installed you can run the python shell at the command prompt using
>python

Linux:

Python Data Types & Data Structures

Numbers

Number data type is used to store numeric values.

Examples:

#Integer

>>>a=5

>>>print(type(a))

o/p: <type ‘int’>

#Float

>>>b=2.5

>>>print(type(b))

o/p: <type ‘float’>


#Long

>>>x=1234987612341L

>>>print(type(x))

o/p: <type ‘long’>

#Complex

>>>y=2+5j

>>>print(type(y))

o/p: <type ‘complex’>

>>>print (y.real)

o/p: 2

>>>print (y.imag)

o/p: 5

#Addition

>>>c=a+b

>>>print(c)

o/p:7.5

#subtraction

>>>d=a-b

>>>print(d)

o/p:7.5

#Multiplication

>>>e=a*b

>>>print(e)

o/p:12.5

#Division

>>>f=b/a
>>>print(f)

o/p:0.5

Strings

A string is list of characters in order.A string that has zero character is called empty string.

Examples:

#creating string

>>>s=”Hello World!”

>>>print(type(s))

o/p:<type ‘str’>

#String concatenation

>>>t=”Welcome to python.”

>>>r=s+t

>>>Print(r)

o/p:Hello World!Welcome to python.

#Length of string

>>>Print (len(s))

o/p:12

#Formatting output

>>>print “the string has (%s) has %d characters” % (s,len(s))

o/p: the string (Hello World! has 12 characters

#Converting string to Upper case

>>>print s.upper()

o/p: HELLO WORLD!

#Converting string to Lower case

>>> print s.lower()


o/p:hello world!

#Accessing sub-strings

>>>print s[0] ---- Returns the first character from the string

o/p:’H’

>>>print s[6:] --- Returns the string starting from 6 th index to the end of the string.

o/p:’World!’

>>>print s[6:-1] ---Returns the string starting from 6 th and excluding last(-1) index.

o/p:’World’

Note: In python,Forward indexing starts from 0

Backward indexing starts from -1

Lenght of the string = No.of characters in string

Lists

List is a compound data type used to group together other values. List items need not all have
same type. A list contains items separated by commas and enclosed within square brackets.

*** Lists are mutable ***

Examples:

>>>fruits=[‘apple’,’orange’,’banana’,’mango’]

>>>print len(fruits)

o/p: 4

>>>print (type(fruits))

o/p:<type ‘list’>

>>>print fruits[1]
o/p: ‘orange’

>>>print fruits[1:3]

o/p:[‘orange’,’banana’,’mango’]

#Appending an item to a list

>>>fruits.append(‘pear’)

>>>print fruits

o/p: [‘apple’,’orange’,’banana’,’mango’,’pear’]

#Inserting an item into list

>>>fruits.insert(1,’mango’)

>>>print fruits

o/p: [‘apple’,’mango’,’orange’,’banana’,’mango’,’pear’]

#combinng lists

>>>veg=[‘patato’,’carrot’,’beans’]

>>>eatables=fruits+veg

>>>print eatables

o/p: [‘apple’,’mango’,’orange’,’banana’,’mango’,’pear’,‘patato’,’carrot’,’beans’]

#Mixed data types in a list

>>>mixed=[‘data’,5,100.1’65782345L]

>>>print type(mixed)

o/p: <type ‘list>

>>>print type(mixed[0])

o/p:<type ‘str’>

>>>print type(mixed[1])

o/p:<type ‘int’>

>>>print type(mixed[2])

o/p:<type ‘float’>
#Changing individual elements of list

>>>mixed[0]=mixed[0]+”items”

>>>mixed[1]=mixed[1]+”1”

>>>print mixed

o/p: [‘data items’,6,100.1, 65782345L]

Tuples

A tuple is a sequence sequence data type that is similar to list. A tuple consists of a number of
values separated by commas and enclosed within parentheses. Unlike lists, elements of tuples
cannot be changed, so tuples can be thought of as read-only lists.

*** Tuples are immutable ***

Examples:

>>>fruits=(“apple”,”mango”,”banana”)

>>>print len(fruits)

o/p: 3

>>>print type(fruits)

o/p:<type ‘tuple’>

#Accessing elements from tuple

>>>print fruits[0]

o/p:’apple’

>>>print fruits[:2]

o/p: (‘apple’,’mango’)

Set

A Python set is the collection of the unordered items. Each element in the set must be unique,
immutable, and the sets remove the duplicate elements. Sets are mutable which means we can
modify it after its creation.

*** Sets are immutable***

Example:

>>>fruits={“apple”,”orange”,”banana”,”mango”}
>>>print type(fruits)

o/p:<type ‘set’>

Dictionaries

Dictionary is mapping data type or a kind of hash table that maps keys to values.Keys in a
dictionary can be of any type,though numbers and strigs are commonly used for keys. Values in a
dictionary can be any data type or object.

Example:

>>>student={’id’:’1’,‘name’:’mary’,’dept’:’IT’}

>>>print type(student)

o/p: <type ‘dict’>

>>>print student[‘name’]

o/p: ‘mary’

>>>print (student.keys())

o/p:[‘id’,’name’,’dept’]

>>> print (student.values())

o/p: [’1’,’mary’,’IT’]

>>>student.has_key(‘name’)

o/p: True

>>> student.has_key(‘grade’)

o/p: False

Type conversions

#convert to string

>>>a=10000

>>>print str(a)

o/p:’1000’

#convert to float
>>>print float(a)

o/p:10000.0

#convert to list

>>>s=”aeiou”

>>>print(list(s))

o/p:[‘a’,’e’,’i’,’o’,’u’]

Control Flow

if

if test_expression:

statement(s)

Here, the program evaluates the test expression and will execute statement(s) only if the text
expression is True.
If the text expression is False, the statement(s) is not executed. In Python, the body of the if
statement is indicated by the indentation. Body starts with an indentation and the first unindented
line marks the end.

Example:

>>>a=25**5

>>>if a>10000:

Print “More”

if..else

>>>a=100

>>>b=50

>>>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”)


Example:

>>>s=”Hello world”

>>>if “world” in s:

s=s+”!”

>>>print(s)

o/p:Hello world!

for

The for statement in python iterates over items of any sequence (list,strings,etc.) in the order in
which they appear in sequence.

Example:

>>>fruits=("apple","orange","banana")

>>>for item in fruits:

print (fruits)

while

The while statement in python executes the statements within while loop as long as the while
condition is true.

Example:

#print even numbers upto 100

>>> i=0

>>>while i<=100:

if i%2 == 0:

print i

i=i+1

range

The range statement in python generates a list of numbers in arithmetic progression.

Example:

#Generate a list list of numbers from 0-9


>>>print range(10)

o/p:[0,1,2,3,4,5,6,7,8,9]

#Generate a list of numbers from 10-100 with increment of 20

>>>print range(10,100,20)

o/p:[10,30,50,70,90]

break/continue

break:The break statement breaks out of the for/while loop.

Example:

>>>y=1

>>>for x in range(4,256,4):

y=y*x

if y > 512:

break

print y

o/p:

32

384

continue: The continue statement continues with next iteration.

Example:

>>>fruits=[‘apple’,’orange’,’banana’,’mango’]

>>>for item in fruits:

>>>if item == “banana”:

continue

else:

print item
o/p:

apple

orange

mango

pass

The pass statement in python is null operation. The pass statement is used when a statement is
required syntactically but you do not want any command or code to execute.

Example:

>>>fruits=[‘apple’,’orange’,’banana’,’mango’]

>>>for item in fruits:

>>>if item == “banana”:

pass

else:

print item

o/p:

apple

orange

mango

Functions

A function is a block of code that takes information in(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 keyword def followed by function name and
parentheses.

Example:

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 grade is: %0.2f” % (avg)

Functions can have default values of the parameters. If a function with default values is called with
fewer parameters or without any parameter.

Example of function with 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 ()

Example of 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’)
>>>fruirts = [‘bababa’,’pear’,’apple’]

>>>displayFruits(fruits)

o/p: There are 3 fruits in the list

banana

pear

apple

Adding one more fruit

>>> print “There are %d fruits in the list” % (len(fruits))

o/p: There are 4 fruits in the list

Examples of keyword arguments

>>>def printStudentRecords(name,age=20,dept=’IT’):

print “Name: “+name

print “Age: “+str(age)

print “dept: “+major

>>>printStudentRecords(name=’Alex’)

name: Alex

age: 20

dept: IT

>>>printStudentRecords(name=’Bob’,age=22,dept=’IT’)

name: Bob

age: 22

dept: IT

>>>printStudentRecords(name=’Alan’,dept=’CSE’)

name: Alan

age: 20

dept: CSE
Modules

Python allows organizing of the program code into different modules which improves the code
readability and management. A module is a python file that defines some functionality in the form
of functions or classes.Modules are imported using keyword import.

Module student

def avgGrade(students):

sum = 0.0

for key in students:

sum = sum + students[key][‘grade’]

avg = sum/len(students)

return avg

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 module student

>>>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)

There are 5 students

Student-1:

Name: Bob

Grade: 2.5

Student-2:

Name: David

Grade: 4.2

Student-3:

Name: Mary

Grade: 3.5

Student-4:

Name: Alex

Grade: 3.8

Student-5:

Name: John

Grade: 4.1

>>>average = student. avgGrade(students)

>>>print “The average grade is: %0.2f” % (avg)

3.62

Packages

Python package is a hierarchical file structure that consists of modules and sub packages.
Packages allow better organization of modules related to a single application environment.
Skimage package listing

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 and write (r+),
read and write(r+ or w+),read-binary(rb),write-binary(wb),etc.

Example of reading an entire file

>>>fp = open(‘file.txt’,’r’)

>>>content = fp.read()

>>>print content

Welcome to python

Welcome to IoT

>>>fp.close()

Example of reading line by line

>>>fp.close()

>>>fp = open(‘file.txt’,’r’)

>>>print “Line-1: “+fp.readLine()

Line-1: Welcome to python


>>>print “Line-2: “+fp.readLine()

Line2: Welcome to IoT

>>>fp.close()

Example of reading lines in a loop

>>>fp = open(‘file.txt’,’r’)

>>>Lines = fp.readLines()

>>>for line in lines:

print line

Welcome to python

Welcome to IoT

Example of reading certain no.of bytes

>>>fp = open(‘file.txt’,’r’)

>>>fp.read(10)

‘Welcome to ‘

>>>fp.close()

Example of getting the current position of read

>>>fp = open(‘file.txt’,r’)

>>>fp.read(10)

‘Welcome to ‘

>>>curpos = fp.tell

>>>print curpos

<built-in method of file object at 0x0000000002391390>

>>>fp.close()

Example of writing to a file

>>>fo = open(‘file1.txt’,’w’)

>>>content = ‘This ia an example of writing to a file in python.’


>>>fo.write(content)

>>>fo.close()

Date/Time operations

Python provides several functions for date and time access and conversation. The datetime
module allows manipulating date and time in several ways.

Example of manipulating with date

>>>from datetime import date

>>>now = date.today()

>>>print “Date: “+ now.strftime(“%m-%d-%y)

Date: 01-05-22

>>>print “Day of week: “+ now.strftime(“%A)

Day of week: Sunday

.>>>print “Month: “+now.strftime(“%B”)

Month: May

Classes

Python is Object-Oriented Programming (OOP) language. Python provides all the standard
features of OOP such as classes, class variables, class methods, function overloading, operating
overloading.

Class

A class is a user-defined blueprint or prototype from which objects are created. Classes provide
a means of bundling data and functionality together.

Instance/Object

Object is an instance of data structure defined by 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.

In class,

There is a special method by the name __init__() which is the class constructor.

There is a special method by the name __del__() which is the class destructor.

Example of class
Inheritance Example

#parent class

class Person( object ):

#__init__ is known as the constructor

def __init__(self, name, idnumber):

self.name = name

self.idnumber = idnumber

def display(self):

print(self.name)

print(self.idnumber)

# child class

class Employee( Person ):

def __init__(self, name, idnumber, salary, post):

self.salary = salary

self.post = post

# invoking the __init__ of the parent class

Person.__init__(self, name, idnumber)


# creation of an object variable or an instance

a = Employee('Rahul', 886012, 200000, "Intern")

# calling a function of the class Person using its instance

a.display()

Output:
Rahul
886012
Exception Handling
Try and except statements are used to catch and handle exceptions in Python.
Statements that can raise exceptions are kept inside the try clause and the
statements that handle the exception are written inside except clause.
Example:1

try:
k = 5//0 # raises divide by zero exception.
print(k)

# handles zerodivision exception


except ZeroDivisionError:
print("Can't divide by zero")

finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
Exapmle:2

x = -1

if x < 0:
raise Exception("Sorry, no numbers below zero")

Python packages of interest for IoT


JSON(JavaScript Object Notation)
JSON is an easy to read and write data-inetrchange format. JSON is buit on two
structures-dictionaries, list.
XML file;
<?xml version=”1.0”?>

<user>

<firstName>Jason</firstName>

<middleName>Alexander</middleName>

<lastName>Smith</lastName>

<address>

<street1>1234 Someplace Avenue</street1>

<street2>Apt. 302</street2>

<city>Anytown</city>

<state>NY</state>

<postalCode>12345</postalCode>

<country>US</country>

</address>

</user>

</xml>

JSON file:

"firstName" : "Jason",

"middleName" : "Alexander",

"lastName" : "Smith",

"address" : {
"street1" : "1234 Someplace Avenue",

"street2" : "Apt. 302",

"city" : "Anytown",

"state" : "NY",

"postalCode" : "12345",

"country" : "US"

Dumps() and loads() in JSON:

Loads()

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"])

Dumps()

import json

# a Python object (dict):


x = {
"name": "John",
"age": 30,
"city": "New York"
}

# convert into JSON:


y = json.dumps(x)

# the result is a JSON string:


print(y)

Extensible Markup Language(XML)

XML is a data format for structured document interchange. The python minidom library provides a
minimal implementation of Document Model Interface.
HTTPLib & URLLib

HTTPLib2 and URLLib2 are python libraries used in network/internet programming. HTTPLib2 is
an HTTP client library and URLLib2 is a library for fetching URL’s.
SMTPLib

Simple Mail Transfer Protocol(SMTP) is a protocol for sending and routing e-mail between mail
servers.

To send an email, first a connection is established with SMTP server by calling smtplib.SMTP with
SMTP server and port. The email is sent by calling server.sendmail() with from address,to address
list and message as input parameters.

You might also like