Unit-Ii: Iot Systems - Logical Design Using Python

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 79

UNIT-II

IoT Systems –
Logical Design using Python

Mr. Babu Illuri B.Tech, M.Tech, (P.hD.)


Assistant Professor
Department of ECE
Vardhaman College of Engineering
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.

• The main characteristics of Python are:


• Multi-paradigm programming language
• Python supports more than one programming paradigms including object-oriented programming and structured
programming
• 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.
• Interactive Language
• Python provides an interactive mode in which the user can submit commands at the Python prompt and interact
with the interpreter directly.
Python - Benefits
• Easy-to-learn, read and maintain
• Python is a minimalistic language with relatively few keywords, uses English keywords and has fewer syntactical constructions
as compared to other languages. Reading Python programs feels like English with pseudo-code like constructs. Python is easy
to learn yet an extremely powerful language for a wide range of applications.
• Object and Procedure Oriented
• Python supports both procedure-oriented programming and object-oriented programming. Procedure oriented paradigm allows
programs to be written around procedures or functions that allow reuse of code. Procedure oriented paradigm allows programs
to be written around objects that include both data and functionality.
• Extendable
• Python is an extendable language and allows integration of low-level modules written in languages such as C/C++. This is
useful when you want to speed up a critical portion of a program.
• Scalable
• Due to the minimalistic nature of Python, it provides a manageable structure for large programs.
• Portable
• Since Python is an interpreted language, programmers do not have to worry about compilation, linking and loading of
programs. Python programs can be directly executed from source
• Broad Library Support
• Python has a broad library support and works on various platforms such as Windows, Linux, Mac, etc.
Python - Setup

• 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 <typ
n
>>>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.

#Create a Tuple #Get an element from a tuple


>>>fruits=("apple","mango","banana","pineapple") >>>fruits[0
>>>fruits ] ’apple’
(’apple’, ’mango’, ’banana’, ’pineapple’) >>>fruits[:2]
(’apple’,
>>>type(fruits) ’mango’)
<type ’tuple’>
#Combining
#Get length of tuple tuples
>>>len(fruits >>>vegetables=(’
) 4 potato’,’carrot’,’o
nion’,’radish’)
>>>eatables=fruit
s+vegetables
>>>eatables
(’apple’,
’mango’,
’banana’,
’pineapple’,
’potato’, ’carrot’,
’onion’, ’radish’)
Dictionaries

• 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’}

#Get all items in a #A value in a dictionary can


dictionary be another dictionary
>>>student.items() >>>student1={’name’:’David
[(’gender’, ’female’), (’major’, ’CS’), (’name’, ’,’id’:’9876’,’major’:’ECE’}
’Mary’), (’id’, ’8776’)] {>>>students={’1’:
student,’2’:student1}
’m ajor’: ’ECE’, ’name’: ’David’, ’id’:
>>>students
’9876’}}
{’1’:
{’gende
Type Conversions

• Type conversion examples

#Convert to string #Convert to long


>>>a=10000 >>>long(b
>>>str(a ) 2013L
)
’10000’ #Convert
to list
#Conver >>>s="aei
t to int ou"
>>>b="2 >>>list(s)
013" [’a’, ’e’,
>>>int(b ’i’, ’o’,
) 2013 ’u’]

#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 if statement in Python is similar to the if statement in other languages.

>>>a = 25**5 >>>if a>10000: >>>s="Hello World" >>>student={’name’:’Mary’,’id’:’8776’}


>>>if a>10000: if a<1000000: >>>if "World" in s: >>>if not student.has_key(’major’):
print "More" print "Between 10k and 100k" s=s+"!" student[’major’]=’CS’
else: else: print s
print "Less" print "More than 100k" >>>student
elif a==10000: Hello World! {’major’: ’CS’, ’name’: ’Mary’, ’id’:
More print "Equal to ’8776’}
10k"
else:
print "Less
than 10k"

More than 100k


Control Flow – for 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.

#Prints even numbers upto 100

>>> i = 0

>>> while
i<=100: if i%2
== 0:
print i
i = i+1
Control Flow – range statement

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

#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

• The pass statement in Python is a null operation.


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

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

• A function in Python is a block of code that begins with the keyword


def averageGrade(students):
def followed by the function name and parentheses. The function “This function computes the average grade”
parameters are enclosed within the parenthesis. sum = 0.0
for key in students:
sum = sum + students[key]['grade']
average = sum/len(students)
• The code block within a function begins after a colon that comes after return average
the parenthesis enclosing the parameters.
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.
Functions-Default Arguments

• Functions can have default values of the parameters.


• If a function with default values is called with fewer parameters or without any parameter, the default values of the
parameters are used

>>>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(
) apple
orange

>>>fruits =
[’banana’, ’pear’,
’mango’]
>>>displayFruits(fruits
) banana
pear
mango
Functions-Passing by Reference

• All parameters in the Python functions are passed by reference.


• If a parameter is changed within a function the change also reflected back in the calling function.

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

>>>fruits = ['banana', 'pear', 'apple']


>>>displayFruits(fruits)
There are 3 fruits in the list
banana
pear
apple

#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.

>>>def #Correct use #name is a formal argument.


printStudentRecords(name,age=20,major=’CS’): >>>printStudentRecords(name=’Alex’ #**kwargs is a keyword argument that receives
print "Name: " + name ) Name: Alex all arguments except the formal argument as a
print "Age: " + str(age) Age: 20 dictionary.
print "Major: " + Major:
major CS >>>def student(name, **kwargs):
>>>printStudentRecords(name=’Bob’,age=22,major=’E print "Student Name: " + name
#This will give error as name C E’) for key in kwargs:
is required argument Name: Bob print key + ’: ’ + kwargs[key]
>>>printStudentRecords() Age: 22
Traceback (most recent call last): Major: >>>student(name=’Bob’, age=’20’,
File "<stdin>",
argument line 1, in
(0 given) ECE major = ’CS’)
<module> >>>printStudentRecords(name=’Alan’,major=’ECE’) Student Name: Bob
TypeError: Name: Alan age: 20
printStudentRecords() takes at Age: 20 major: CS
least 1 Major:
ECE
Functions - Variable Length Arguments

• 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 (*)

>>>def student(name, *varargs):


print "Student Name: " + name
for item in varargs:
print item

>>>student(’Nav’)
Student Name: Nav

>>>student(’Amy’, ’Age: 24’)


Student Name: Amy
Age: 24

>>>student(’Bob’, ’Age: 20’, ’Major:


CS’) Student Name: Bob
Age: 20
Major:
CS
Modules
#Using student module
• Python allows organizing the program #student module - saved as student.py >>>import student
def averageGrade(students): >>>students = '1': 'name': 'Bob', 'grade': 2.5,
code into different modules which sum = 0.0 '2': 'name': 'Mary', 'grade': 3.5,
improves the code readability and for key in students: '3': 'name': 'David', 'grade': 4.2,
management. sum = sum + students[key]['grade'] '4': 'name': 'John', 'grade': 4.1,
average = sum/len(students) '5': 'name': 'Alex', 'grade': 3.8
• A module is a Python file that defines return average
>>>student.printRecords(students) There
some functionality in the form of functions def printRecords(students): are 5 students
or classes. print "There are %d students" %(len(students)) Student-1:
i=1 Name: Bob
• Modules can be imported using the import for key in students: Grade: 2.5
keyword. print "Student-%d: " % (i) Student-2:
print "Name: " + students[key]['name'] Name: David
• Modules to be imported must be present print "Grade: " + str(students[key]['grade']) Grade: 4.2 Student-
i = i+1 3:
in the search path. Name: Mary
Grade: 3.5 Student-
# Importing a specific function from a module 4:
>>>from student import averageGrade Name: Alex
Grade: 3.8
# Listing all names defines in a module Student-5:
>>>dir(student) Name: John
Grade: 4.1
>>>avg = student.
averageGrade(stude
nts)
>>>print "The
3.62 garde is:
average
Packages

• 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
• Packages allow better organization of modules related to a single package
application environment. color/ color color
subpackage
init .py
colorconv.py
colorlabel.py
rgb_colors.py
draw/ draw draw
subpackage
init .py
draw.py
setup.py

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 supports more than one programming paradigms.


Python is an interpreted language.
File Handling

# Example of reading a certain number of bytes # Example of seeking to a certain position

>>>fp = open('file.txt','r') >>>fp = open('file.txt','r')


>>>fp.read(10 >>>fp.seek(10,0)
) 'Python sup' >>>content = fp.read(10)
>>>fp.close() >>>print content
ports more
>>>fp.close()

# Example of getting the current position of read # Example of writing to a file

>>>fp = open('file.txt','r') >>>fo = open('file1.txt','w')


>>>fp.read(10 >>>content='This is an example of writing to a file
) 'Python sup' in Python.'
>>>currentpos >>>fo.write(content)
= fp.tell >>>fo.close()
>>>print
currentpos
<built-in
method tell of
file object at
0x0000000002
391390>
>>>fp.close()
Date/Time Operations

• 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.

# Examples of manipulating with time


# Examples of manipulating with date
>>>import time
>>>from datetime import date
>>>nowtime = time.time()
>>>time.localtime(nowtime)
>>>now = date.today()
time.struct_time(tm_year=2013, tm_mon=7, tm_mday=24, tm_ec=51, tm_wday=2, tm_yday=205,
>>>print "Date: " + now.strftime("%m-%d-
tm_isdst=0)
%y") Date: 07-24-13
>>>time.asctime(time.localtime(nowtime))
>>>print "Day of Week: " +
'Wed Jul 24 16:14:51 2013'
now.strftime("%A") Day of Week: Wednesday
>>>time.strftime("The date is %d-%m-%y. Today is a %A. It is %H hours, %M minutes and %S seconds
>>>print "Month: " +
now.") 'The date is 24-07-13. Today is a Wednesday. It is 16 hours, 15 minutes and 14 seconds now.'
now.strftime("%B") Month: July

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

• The variable studentCount is a # Examples of a class >>>s =


class Student: Student(’Steve’,’98928’)
class variable that is shared by studentCount = 0 Constructor called
all instances of the class
Student and is accessed by def init (self, name, id): >>>s.addGrade(’Math’,’90’)
print "Constructor called" >>>s.addGrade(’Physics’,’85’)
Student.studentCount. self.name = name >>>s.printGrades(
self.id = id ) Physics: 85
• The variables name, id and Student.studentCount = Student.studentCount + 1 Math: 90
grades are instance variables self.grades={}
which are specific to each >>>mathgrade =
def del (self): s.getGrade(’Math’
instance of the class. print "Destructor called" )
>>>print mathgrade
• There is a special method by def getStudentCount(self): 90
the name init () which is return Student.studentCount
the class constructor. >>>count =
def addGrade(self,key,value): s.getStudentCount()
• The class constructor self.grades[key]=value >>>print count
def getGrade(self,key): 1
initializes a new instance return self.grades[key]
when it is created. The >>>del s
function del () is the def printGrades(self): Destructor called
for key in self.grades:
class destructor print key + ": " +
self.grades[key
]
Class Inheritance
• In this example Shape is the base class and Circle is the derived class. The class Circle inherits the attributes of the Shape class.
• The child class Circle overrides the methods and attributes of the base class (eg. draw() function defined in the base class Shape is overridden in child
class Circle).

# Examples of class class Circle(Shape): class Point: >>>p = Point(2,4)


inheritance class Shape: def init (self, c,r): def init (self, x, y): >>>circ = Circle(p,7)
def init (self): print "Child class constructor" self.xCoordinate = Child class constructor
print "Base class constructor" self.center = c x self.yCoordinate >>>circ.getColor()
self.color = ’Green’ self.radius = r =y ’Green’
self.lineWeight = 10.0 self.color = ’Green’ >>>circ.setColor(’
self.lineWeight = 10.0 def setXCoordinate(self,x): Red’)
def draw(self): self. label = ’Hidden self.xCoordinate = >>>circ.getColor()
print "Draw - to be implemented" circle label’ x ’Red’
def setColor(self, c): >>>circ.getLineWeight()
self.color = c def setCenter(self,c): def getXCoordinate(self): 10.0
def self.center = c return >>>circ.getCenter().getXCoordinate()
getColor(self): def getCenter(self): self.xCoordinate 2
return self.color return self.center >>>circ.getCenter().getYCoordinate()
def setYCoordinate(self,y): 4
def setLineWeight(self,lwt): def setRadius(self,r): self.yCoordinate = >>>circ.draw()
self.lineWeight = lwt self.radius = r y Draw Circle (overridden function)
>>>circ.radius
def getLineWeight(self): def getRadius(self): def getYCoordinate(self): 7
return self.lineWeight return return
self.radius self.yCoordinate

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

function overloading and operator overloading


The simplest form of class definition looks like this:
Class Objects
Inheritance
JSON

JSON or JavaScript Object Notation is a lightweight text-based open standard

designed for human-readable data interchange. The JSON format was

originally specified by Douglas Crockford,. The official Internet media type for

JSON is application/json. The JSON filename extension is .json.


JSON stands for JavaScript Object Notation.
The format was specified by Douglas Crockford.
It was designed for human-readable data interchange.
It has been extended from the JavaScript scripting language.
The filename extension is .json.
JSON Internet Media type is application/json.
The Uniform Type Identifier is public.json.
Uses of JSON

It is used while writing JavaScript based applications that includes


browser extensions and websites.
JSON format is used for serializing and transmitting structured data
over network connection.
It is primarily used to transmit data between a server and web
applications.
Web services and APIs use JSON format to provide public data.
It can be used with modern programming languages.
Simple Example in JSON

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

XML, or Extensible Markup Language, is a markup-language that is commonly used


to structure, store, and transfer data between systems.
With Python being a popular language for the web and data analysis, it's likely you'll
need to read or write XML data at some point.
Throughout this Class look at the ElementTree module for reading, writing, and
modifying XML data. We'll also compare it with the older minidom module in the
first few sections so you can get a good comparison of the two.
The XML Modules

The minidom, or Minimal DOM Implementation, is a simplified implementation of the Document

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

familiar with its functionality.

The ElementTree module provides a more "Pythonic" interface to handling XMl and is a good option

for those not familiar with the DOM.


XML File Example
In the examples below, we will be using the following XML file, which we will save as "items.xml":

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

You might also like