Iot Unit III
Iot Unit III
Iot Unit III
Object and Procedure Oriented: Python supports both Object and Procedure Oriented.
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:
Once the python is installed you can run the python shell at the command prompt using
>python
Linux:
Numbers
Examples:
#Integer
>>>a=5
>>>print(type(a))
#Float
>>>b=2.5
>>>print(type(b))
>>>x=1234987612341L
>>>print(type(x))
#Complex
>>>y=2+5j
>>>print(type(y))
>>>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)
#Length of string
>>>Print (len(s))
o/p:12
#Formatting output
>>>print s.upper()
#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’
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.
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’]
>>>fruits.append(‘pear’)
>>>print fruits
o/p: [‘apple’,’orange’,’banana’,’mango’,’pear’]
>>>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’,5,100.1’65782345L]
>>>print type(mixed)
>>>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
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.
Examples:
>>>fruits=(“apple”,”mango”,”banana”)
>>>print len(fruits)
o/p: 3
>>>print type(fruits)
o/p:<type ‘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.
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)
>>>print student[‘name’]
o/p: ‘mary’
>>>print (student.keys())
o/p:[‘id’,’name’,’dept’]
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:
elif a==b:
else:
>>>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")
print (fruits)
while
The while statement in python executes the statements within while loop as long as the while
condition is true.
Example:
>>> i=0
>>>while i<=100:
if i%2 == 0:
print i
i=i+1
range
Example:
o/p:[0,1,2,3,4,5,6,7,8,9]
>>>print range(10,100,20)
o/p:[10,30,50,70,90]
break/continue
Example:
>>>y=1
>>>for x in range(4,256,4):
y=y*x
if y > 512:
break
print y
o/p:
32
384
Example:
>>>fruits=[‘apple’,’orange’,’banana’,’mango’]
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’]
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:
‘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
average = sum/len(students)
return average
avg = averageGrade(students)
Functions can have default values of the parameters. If a function with default values is called with
fewer parameters or without any parameter.
>>>def displayFruits(fruits=[`apple’,’orange’]):
print item
>>> displayFruits ()
>>>def displayFruits(fruits):
print item
fruits.append(‘mango’)
>>>fruirts = [‘bababa’,’pear’,’apple’]
>>>displayFruits(fruits)
banana
pear
apple
>>>def printStudentRecords(name,age=20,dept=’IT’):
>>>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
avg = sum/len(students)
return avg
def printRecords(students):
i=1
i = i+1
>>>import student
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
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.
>>>fp = open(‘file.txt’,’r’)
>>>content = fp.read()
>>>print content
Welcome to python
Welcome to IoT
>>>fp.close()
>>>fp.close()
>>>fp = open(‘file.txt’,’r’)
>>>fp.close()
>>>fp = open(‘file.txt’,’r’)
>>>Lines = fp.readLines()
print line
Welcome to python
Welcome to IoT
>>>fp = open(‘file.txt’,’r’)
>>>fp.read(10)
‘Welcome to ‘
>>>fp.close()
>>>fp = open(‘file.txt’,r’)
>>>fp.read(10)
‘Welcome to ‘
>>>curpos = fp.tell
>>>print curpos
>>>fp.close()
>>>fo = open(‘file1.txt’,’w’)
>>>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.
>>>now = date.today()
Date: 01-05-22
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
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
self.name = name
self.idnumber = idnumber
def display(self):
print(self.name)
print(self.idnumber)
# child class
self.salary = salary
self.post = post
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)
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")
<user>
<firstName>Jason</firstName>
<middleName>Alexander</middleName>
<lastName>Smith</lastName>
<address>
<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",
"city" : "Anytown",
"state" : "NY",
"postalCode" : "12345",
"country" : "US"
Loads()
import json
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
Dumps()
import json
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.