SlideShare a Scribd company logo
UNIT-II
IoT Systems โ€“
Logical Design using Python
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
>>>a=5
>>>type(a)
<type โ€™intโ€™>
#Floating
Point
>>>b=2.5
>>>type(b)
<type โ€™floatโ€™>
#Long
>>>x=9898878787676
L
>>>type(x)
<type โ€™longโ€™>
#Complex
>>>y=2+5j
>>>y
(2+5j
)
>>>type(y)
<type
โ€™complexโ€™>
>>>y.rea
l 2
>>>y.ima
g 5
#Addition
>>>c=a+b
>>>
c
7.5
>>>type(c)
<type โ€™floatโ€™>
#Subtraction
>>>d=a-b
>>>
d
2.5
>>>type(d)
<type โ€™floatโ€™>
#Multiplicatio
n
>>>e=a*b
>>>
e
12.5
>>>type(e)
<type โ€™floatโ€™>
#Division
>>>f=b/a
>>>
f
0.5
>>>type(f)
<type floatโ€™>
#Power
>>>g=a**
2
>>>
g 25
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
>>>s="Hello World!"
>>>type(s)
<type โ€™strโ€™>
#String concatenation
>>>t="This is sample program."
>>>r = s+t
>>>r
โ€™Hello World!This is sample program.โ€™
#Get length of string
>>>len(s
) 12
#Convert string to integer
>>>x="100"
>>>type(s)
<type โ€™strโ€™>
>>>y=int(x)
>>>
y
100
#Print string
>>>print s
Hello
World!
#Formatting output
>>>print "The string (The string (Hello
World!) has 12 characters
#Convert to upper/lower case
>>>s.upper()
โ€™HELLO
WORLD!โ€™
>>>s.lower()
โ€™hello
world!โ€™
#Accessing sub-strings
>>>s[0
] โ€™Hโ€™
>>>s[6:]
โ€™World!โ€™
>>>s[6:-1]
โ€™Worldโ€™
#strip: Returns a copy of the string with
the #leading and trailing characters
removed.
>>>s.strip("!"
) โ€™Hello
Worldโ€™
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.
#Create List
>>>fruits=[โ€™appleโ€™,โ€™orangeโ€™,โ€™bananaโ€™,โ€™mangoโ€™]
>>>type(fruits)
<type โ€™listโ€™>
#Get Length of List
>>>len(fruits
) 4
#Access List Elements
>>>fruits[1
] โ€™orangeโ€™
>>>fruits[1:3]
[โ€™orangeโ€™, โ€™bananaโ€™]
>>>fruits[1:]
[โ€™orangeโ€™, โ€™bananaโ€™, โ€™mangoโ€™]
#Appending an item to a list
>>>fruits.append(โ€™pearโ€™)
>>>fruits
[โ€™appleโ€™, โ€™orangeโ€™, โ€™bananaโ€™, โ€™mangoโ€™, โ€™pearโ€™]
#Removing an item from a list
>>>fruits.remove(โ€™mangoโ€™)
>>>fruits
[โ€™appleโ€™, โ€™orangeโ€™, โ€™bananaโ€™, โ€™pearโ€™]
#Inserting an item to a list
>>>fruits.insert(1,โ€™mangoโ€™)
>>>fruits
[โ€™appleโ€™, โ€™mangoโ€™, โ€™orangeโ€™, โ€™bananaโ€™, โ€™pearโ€™]
#Combining lists
>>>vegetables=[โ€™potatoโ€™,โ€™carrotโ€™,โ€™onionโ€™,โ€™beansโ€™,โ€™
r adishโ€™]
>>>vegetables
[โ€™potatoโ€™, โ€™carrotโ€™, โ€™onionโ€™, โ€™beansโ€™, โ€™radishโ€™]
>>>eatables=fruits+vegetables
>>>eatables
[โ€™appl
eโ€™,
โ€™mang
oโ€™,
โ€™orang
eโ€™,
โ€™banan
aโ€™,
โ€™pearโ€™, โ€™potatoโ€™, โ€™carrotโ€™, โ€™onionโ€™, โ€™beansโ€™,
โ€™radishโ€™]
#Mixed data types in a list
>>>mixed=[โ€™dataโ€™,5,100.1,8287398L]
>>>type(mixed)
<type โ€™listโ€™>
>>>type(mixed[0])
<type โ€™strโ€™>
>>>type(mixed[1])
<type โ€™intโ€™>
>>>type(mixed[2])
<type โ€™floatโ€™>
>>>type(mixed[3])
<type โ€™longโ€™>
#Change individual elements of a list
>>>mixed[0]=mixed[0]+" items"
>>>mixed[1]=mixed[1]+1
>>>mixed[2]=mixed[2]+0.05
>>>mixed
[โ€™data itemsโ€™, 6, 100.14999999999999, 8287398L]
#Lists can be nested
>>>nested=[fruits,vegetables]
>>>nested
[[โ€™appleโ€™, โ€™mangoโ€™, โ€™orangeโ€™, โ€™bananaโ€™, โ€™pearโ€™],
[โ€™potatoโ€™, โ€™carrotโ€™, โ€™onionโ€™, โ€™beansโ€™, โ€™radishโ€™]]
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
>>>fruits=("apple","mango","banana","pineapple")
>>>fruits
(โ€™appleโ€™, โ€™mangoโ€™, โ€™bananaโ€™, โ€™pineappleโ€™)
>>>type(fruits)
<type โ€™tupleโ€™>
#Get length of tuple
>>>len(fruits
) 4
#Get an element from a tuple
>>>fruits[0
] โ€™appleโ€™
>>>fruits[:2]
(โ€™appleโ€™,
โ€™mangoโ€™)
#Combining tuples
>>>vegetables=(โ€™potatoโ€™,โ€™carrotโ€™,โ€™onionโ€™,โ€™radishโ€™)
>>>eatables=fruits+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
>>>student={โ€™nameโ€™:โ€™Maryโ€™,โ€™idโ€™:โ€™8776โ€™,โ€™majorโ€™:โ€™CSโ€™}
>>>student
{โ€™majorโ€™: โ€™CSโ€™, โ€™nameโ€™: โ€™Maryโ€™, โ€™idโ€™: โ€™8776โ€™}
>>>type(student)
<type โ€™dictโ€™>
#Get length of a dictionary
>>>len(student)
3
#Get the value of a key in dictionary
>>>student[โ€™nameโ€™]
โ€™Maryโ€™
#Get all items in a dictionary
>>>student.items()
[(โ€™genderโ€™, โ€™femaleโ€™), (โ€™majorโ€™, โ€™CSโ€™), (โ€™nameโ€™,
โ€™Maryโ€™), (โ€™idโ€™, โ€™8776โ€™)]
#Get all keys in a dictionary
>>>student.keys()
[โ€™genderโ€™, โ€™majorโ€™, โ€™nameโ€™, โ€™idโ€™]
#Get all values in a dictionary
>>>student.values()
[โ€™femaleโ€™, โ€™CSโ€™, โ€™Maryโ€™,
โ€™8776โ€™]
#Add new key-value pair
>>>student[โ€™genderโ€™]=โ€™femaleโ€™
>>>student
{โ€™gende
rโ€™: โ€™femaleโ€™, โ€™majorโ€™: โ€™CSโ€™, โ€™nameโ€™: โ€™Maryโ€™, โ€™idโ€™: โ€™8776โ€™}
#A value in a dictionary can be another dictionary
>>>student1={โ€™nameโ€™:โ€™Davidโ€™,โ€™idโ€™:โ€™9876โ€™,โ€™majorโ€™:โ€™ECEโ€™}
>>>students={โ€™1โ€™: student,โ€™2โ€™:student1}
>>>students
{โ€™1โ€™:
{โ€™gende
rโ€™: โ€™femaleโ€™, โ€™majorโ€™: โ€™CSโ€™, โ€™nameโ€™: โ€™Maryโ€™, โ€™idโ€™: โ€™8776โ€™},
โ€™2โ€™:
{
โ€™
majorโ€™: โ€™ECEโ€™, โ€™nameโ€™: โ€™Davidโ€™, โ€™idโ€™:
โ€™9876โ€™}}
#Check if dictionary has a key
>>>student.has_key(โ€™nameโ€™)
True
>>>student.has_key(โ€™gradeโ€™)
False
Type Conversions
#Convert to string
>>>a=10000
>>>str(a
)
โ€™10000โ€™
#Convert to int
>>>b="2013"
>>>int(b
) 2013
#Convert to float
>>>float(b
) 2013.0
#Convert to long
>>>long(b
) 2013L
#Convert to list
>>>s="aeiou"
>>>list(s)
[โ€™aโ€™, โ€™eโ€™, โ€™iโ€™, โ€™oโ€™, โ€™uโ€™]
#Convert to set
>>>x=[โ€™mangoโ€™,โ€™appleโ€™,โ€™bananaโ€™,โ€™mangoโ€™,โ€™bananaโ€™]
>>>set(x)
set([โ€™mangoโ€™, โ€™appleโ€™, โ€™bananaโ€™])
โ€ข Type conversion examples
Control Flow โ€“ if statement
โ€ข The if statement in Python is similar to the if statement in other languages.
>>>a = 25**5
>>>if a>10000:
print "More"
else:
print "Less"
More
>>>s="Hello World"
>>>if "World" in s:
s=s+"!"
print s
Hello World!
>>>if a>10000:
if a<1000000:
print "Between 10k and 100k"
else:
print "More than 100k"
elif a==10000:
print "Equal to 10k"
else:
print "Less than 10k"
More than 100k
>>>student={โ€™nameโ€™:โ€™Maryโ€™,โ€™idโ€™:โ€™8776โ€™}
>>>if not student.has_key(โ€™majorโ€™):
student[โ€™majorโ€™]=โ€™CSโ€™
>>>student
{โ€™majorโ€™: โ€™CSโ€™, โ€™nameโ€™: โ€™Maryโ€™, โ€™idโ€™: โ€™8776โ€™}
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:
printi
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 10 - 100 with
increments of 10
>>>range(10,110,10)
[10, 20, 30, 40, 50, 60, 70, 80, 90,100]
#Generate a list of numbers from 0 โ€“ 9
>>>range (10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Control Flow โ€“ break/continue statements
โ€ข The break and continue statements in Python are similar to the statements in C.
โ€ข Break
โ€ข Break statement breaks out of the for/while loop
โ€ข Continue
โ€ข Continue statement continues with the next iteration.
#Continue statement example
>>>fruits=[โ€™appleโ€™,โ€™orangeโ€™,โ€™bananaโ€™,โ€™mangoโ€™]
>>>for item in fruits:
if item == "banana":
continue
else:
print item
apple
orange
mango
#Break statement example
>>>y=1
>>>for x in range(4,256,4):
y = y * x
if y >
512:
break
print y
4
32
384
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
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 the keyword
def followed by the function name and parentheses. The function
parameters are enclosed within the parenthesis.
โ€ข The code block within a function begins after a colon that comes after
the parenthesis enclosing the parameters.
โ€ข The ๏ฌrst statement of the function body can optionally be a
documentation string or docstring.
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):
โ€œThis function computes the average gradeโ€
sum = 0.0
for key in students:
sum = sum + students[key]['grade']
average = sum/len(students)
return average
avg = averageGrade(students)
print (The average garde is: %0.2f" % (avg)))
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 re๏ฌ‚ected 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
#Adding 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 identi๏ฌes the arguments by the parameter name when the
function is called.
>>>def
printStudentRecords(name,age=20,major=โ€™CSโ€™):
print "Name: " + name
print "Age: " + str(age)
print "Major: " + major
#This will give error as name is required argument
>>>printStudentRecords()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: printStudentRecords() takes at least 1
argument (0 given)
#name is a formal argument.
#**kwargs is a keyword argument that receives
all arguments except the formal argument as a
dictionary.
>>>def student(name, **kwargs):
print "Student Name: " + name
for key in kwargs:
print key + โ€™: โ€™ + kwargs[key]
>>>student(name=โ€™Bobโ€™, age=โ€™20โ€™, major = โ€™CSโ€™)
Student Name: Bob
age: 20
major: CS
#Correct use
>>>printStudentRecords(name=โ€™Alexโ€™
) Name: Alex
Age: 20
Major:
CS
>>>printStudentRecords(name=โ€™Bobโ€™,age=22,major=โ€™E
C Eโ€™)
Name: Bob
Age: 22
Major:
ECE
>>>printStudentRecords(name=โ€™Alanโ€™,major=โ€™ECEโ€™)
Name: Alan
Age: 20
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 pre๏ฌxed 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
โ€ข Python allows organizing the program
code into different modules which
improves the code readability and
management.
โ€ข A module is a Python ๏ฌle that de๏ฌnes
some functionality in the form of functions
or classes.
โ€ข Modules can be imported using the import
keyword.
โ€ข Modules to be imported must be present
in the search path.
#student module - saved as student.py
def averageGrade(students):
sum = 0.0
for key in students:
sum = sum + students[key]['grade']
average = sum/len(students)
return average
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 student module
>>>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
>>>avg = student. averageGrade(students)
>>>print "The average garde is: %0.2f" % (avg)
3.62
# Importing a specific function from a module
>>>from student import averageGrade
# Listing all names de๏ฌnes in a module
>>>dir(student)
Packages
โ€ข Python package is hierarchical ๏ฌle structure that consists of
modules and subpackages.
โ€ข Packages allow better organization of modules related to a single
application environment.
# skimage package
listing
skimage/
init .py
Top level package
Treat directory as a
package
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
_daisy.py
...
File Handling
โ€ข Python allows reading and writing to ๏ฌles using the ๏ฌle
object.
โ€ข The open(๏ฌlename, mode) function is used to get a ๏ฌle
object.
โ€ข The mode can be read (r), write (w), append (a), read and
write (r+ or w+), read-binary (rb), write-binary (wb), etc.
โ€ข After the ๏ฌle contents have been read the close function is
called which closes the ๏ฌle object.
# Example of reading line by line
>>>fp = open('file1.txt','r')
>>>print "Line-1: " + fp.readline()
Line-1: Python supports more than one programming paradigms.
>>>print "Line-2: " + fp.readline()
Line-2: Python is an interpreted language.
>>>fp.close()
# Example of reading an entire file
>>>fp = open('file.txt','r')
>>>content = fp.read()
>>>print content
This is a test file.
>>>fp.close()
# 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 seeking to a certain position
>>>fp = open('file.txt','r')
>>>fp.seek(10,0)
>>>content = fp.read(10)
>>>print content
ports more
>>>fp.close()
# Example of reading a certain number of bytes
>>>fp = open('file.txt','r')
>>>fp.read(10
) 'Python sup'
>>>fp.close()
# Example of getting the current position of read
>>>fp = open('file.txt','r')
>>>fp.read(10
) 'Python sup'
>>>currentpos = fp.tell
>>>print currentpos
<built-in method tell of file object at 0x0000000002391390>
>>>fp.close()
# Example of writing to a file
>>>fo = open('file1.txt','w')
>>>content='This is 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 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 date
>>>from datetime import date
>>>now = date.today()
>>>print "Date: " + now.strftime("%m-%d-
%y") Date: 07-24-13
>>>print "Day of Week: " +
now.strftime("%A") Day of Week: Wednesday
>>>print "Month: " +
now.strftime("%B") Month: July
>>>then = date(2013, 6, 7)
>>>timediff = now - then
>>>timediff.day
s 47
# Examples of manipulating with time
>>>import time
>>>nowtime = time.time()
>>>time.localtime(nowtime)
time.struct_time(tm_year=2013, tm_mon=7, tm_mday=24, tm_ec=51, tm_wday=2, tm_yday=205,
tm_isdst=0)
>>>time.asctime(time.localtime(nowtime))
'Wed Jul 24 16:14:51 2013'
>>>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.'
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
class variable that is shared by
all instances of the class
Student and is accessed by
Student.studentCount.
โ€ข The variables name, id and
grades are instance variables
which are speci๏ฌc to each
instance of the class.
โ€ข There is a special method by
the name init () which is the
class constructor.
โ€ข The class constructor
initializes a new instance
when it is created. The
function del () is the class
destructor
# Examples of a class
class Student:
studentCount = 0
def init (self, name, id):
print "Constructor called"
self.name = name
self.id = id
Student.studentCount = Student.studentCount + 1
self.grades={}
def del (self):
print "Destructor called"
def getStudentCount(self):
return Student.studentCount
def addGrade(self,key,value):
self.grades[key]=value
def getGrade(self,key):
return self.grades[key]
def printGrades(self):
for key in self.grades:
print key + ": " + self.grades[key]
>>>s =
Student(โ€™Steveโ€™,โ€™98928โ€™)
Constructor called
>>>s.addGrade(โ€™Mathโ€™,โ€™90โ€™)
>>>s.addGrade(โ€™Physicsโ€™,โ€™85โ€™)
>>>s.printGrades()
Physics: 85
Math: 90
>>>mathgrade = s.getGrade(โ€™Mathโ€™)
>>>print mathgrade
90
>>>count = s.getStudentCount()
>>>print count
1
>>>del s
Destructor called
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 de๏ฌned in the base class Shape is overridden in child
class Circle).
# Examples of class
inheritance class Shape:
def init (self):
print "Base class constructor"
self.color = โ€™Greenโ€™
self.lineWeight = 10.0
def draw(self):
print "Draw - to be implemented"
def setColor(self, c):
self.color = c
def getColor(self):
return self.color
def setLineWeight(self,lwt):
self.lineWeight = lwt
def getLineWeight(self):
return self.lineWeight
class Circle(Shape):
def init (self, c,r):
print "Child class constructor"
self.center = c
self.radius = r
self.color = โ€™Greenโ€™
self.lineWeight = 10.0
self. label = โ€™Hidden circlelabelโ€™
def setCenter(self,c):
self.center = c
def getCenter(self):
return self.center
def setRadius(self,r):
self.radius = r
def getRadius(self):
return self.radius
def draw(self):
print "Draw Circle (overridden function)"
class Point:
def init (self, x, y):
self.xCoordinate = x
self.yCoordinate = y
def setXCoordinate(self,x):
self.xCoordinate = x
def getXCoordinate(self):
return self.xCoordinate
def setYCoordinate(self,y):
self.yCoordinate = y
def getYCoordinate(self):
return self.yCoordinate
>>>p = Point(2,4)
>>>circ = Circle(p,7)
Child class constructor
>>>circ.getColor()
โ€™Greenโ€™
>>>circ.setColor(โ€™Redโ€™)
>>>circ.getColor()
โ€™Redโ€™
>>>circ.getLineWeight()
10.0
>>>circ.getCenter().getXCoordinate()
2
>>>circ.getCenter().getYCoordinate()
4
>>>circ.draw()
Draw Circle (overridden function)
>>>circ.radius
7
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.
BUILDING IoT WITH ARDUINO & RASPBERRY PI
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.
BUILDING IoT WITH ARDUINO & RASPBERRY PI
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.
BUILDING IoT WITH ARDUINO & RASPBERRY PI
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.
BUILDING IoT WITH ARDUINO & RASPBERRY PI
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.
BUILDING IoT WITH ARDUINO & RASPBERRY PI
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.
BUILDING IoT WITH ARDUINO & RASPBERRY PI
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.)
BUILDING IoT WITH ARDUINO & RASPBERRY PI
BUILDING IoT WITH ARDUINO & RASPBERRY PI
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.
BUILDING IoT WITH ARDUINO & RASPBERRY PI
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.
BUILDING IoT WITH ARDUINO & RASPBERRY PI
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")

More Related Content

Similar to BUILDING IoT WITH ARDUINO & RASPBERRY PI (20)

PPTX
Python_IoT.pptx
SwatiChoudhary95
ย 
PPTX
python presntation 2.pptx
Arpittripathi45
ย 
PPT
Python lab basics
Abi_Kasi
ย 
PPTX
Python Programming.pptx
DineshThakur911173
ย 
PPTX
Python.pptx
SajjadAbdullah4
ย 
PPTX
All_About_Python_and_more+Cambridge.pptx
nadaragnesrani
ย 
PPTX
python_module_.................................................................
VaibhavSrivastav52
ย 
PPT
1B-Introduction_to_python.ppt
AmritMarwaha1
ย 
PDF
Programming in python Unit-1 Part-1
Vikram Nandini
ย 
PPTX
Python_Introduction_Good_PPT.pptx
lemonchoos
ย 
PPTX
ITC 110 Week 10 Introdution to Python .pptx
aaaaaannnnn6
ย 
PDF
The Ring programming language version 1.10 book - Part 7 of 212
Mahmoud Samir Fayed
ย 
PPT
Introduction to python
Syed Zaid Irshad
ย 
PPTX
python_class.pptx
chandankumar943868
ย 
PPTX
intro to python.pptx
UpasnaSharma37
ย 
PDF
Python Programming
Saravanan T.M
ย 
PPTX
Getting Started with R
Sankhya_Analytics
ย 
PPTX
Machine learning session3(intro to python)
Abhimanyu Dwivedi
ย 
PPTX
modul-python-part1.pptx
Yusuf Ayuba
ย 
PPTX
Pf cs102 programming-8 [file handling] (1)
Abdullah khawar
ย 
Python_IoT.pptx
SwatiChoudhary95
ย 
python presntation 2.pptx
Arpittripathi45
ย 
Python lab basics
Abi_Kasi
ย 
Python Programming.pptx
DineshThakur911173
ย 
Python.pptx
SajjadAbdullah4
ย 
All_About_Python_and_more+Cambridge.pptx
nadaragnesrani
ย 
python_module_.................................................................
VaibhavSrivastav52
ย 
1B-Introduction_to_python.ppt
AmritMarwaha1
ย 
Programming in python Unit-1 Part-1
Vikram Nandini
ย 
Python_Introduction_Good_PPT.pptx
lemonchoos
ย 
ITC 110 Week 10 Introdution to Python .pptx
aaaaaannnnn6
ย 
The Ring programming language version 1.10 book - Part 7 of 212
Mahmoud Samir Fayed
ย 
Introduction to python
Syed Zaid Irshad
ย 
python_class.pptx
chandankumar943868
ย 
intro to python.pptx
UpasnaSharma37
ย 
Python Programming
Saravanan T.M
ย 
Getting Started with R
Sankhya_Analytics
ย 
Machine learning session3(intro to python)
Abhimanyu Dwivedi
ย 
modul-python-part1.pptx
Yusuf Ayuba
ย 
Pf cs102 programming-8 [file handling] (1)
Abdullah khawar
ย 

Recently uploaded (20)

PDF
Automated Test Case Repair Using Language Models
Lionel Briand
ย 
PDF
Code Once; Run Everywhere - A Beginnerโ€™s Journey with React Native
Hasitha Walpola
ย 
PDF
Best Software Development at Best Prices
softechies7
ย 
PDF
From Data Preparation to Inference: How Alluxio Speeds Up AI
Alluxio, Inc.
ย 
PPTX
Iobit Driver Booster Pro 12 Crack Free Download
chaudhryakashoo065
ย 
PDF
What Is an Internal Quality Audit and Why It Matters for Your QMS
BizPortals365
ย 
PDF
capitulando la keynote de GrafanaCON 2025 - Madrid
Imma Valls Bernaus
ย 
PDF
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
ย 
PPTX
IDM Crack with Internet Download Manager 6.42 [Latest 2025]
HyperPc soft
ย 
PDF
Which Hiring Management Tools Offer the Best ROI?
HireME
ย 
PPTX
IObit Driver Booster Pro 12.4-12.5 license keys 2025-2026
chaudhryakashoo065
ย 
PPTX
IObit Driver Booster Pro 12 Crack Latest Version Download
pcprocore
ย 
PPTX
Introduction to web development | MERN Stack
JosephLiyon
ย 
PDF
OpenChain Webinar - AboutCode - Practical Compliance in One Stack โ€“ Licensing...
Shane Coughlan
ย 
PPTX
IObit Uninstaller Pro 14.3.1.8 Crack Free Download 2025
sdfger qwerty
ย 
PPTX
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
ย 
PPTX
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
dheeodoo
ย 
PPTX
IObit Driver Booster Pro Crack Download Latest Version
chaudhryakashoo065
ย 
PPTX
Agentforce โ€“ TDX 2025 Hackathon Achievement
GetOnCRM Solutions
ย 
PDF
Alur Perkembangan Software dan Jaringan Komputer
ssuser754303
ย 
Automated Test Case Repair Using Language Models
Lionel Briand
ย 
Code Once; Run Everywhere - A Beginnerโ€™s Journey with React Native
Hasitha Walpola
ย 
Best Software Development at Best Prices
softechies7
ย 
From Data Preparation to Inference: How Alluxio Speeds Up AI
Alluxio, Inc.
ย 
Iobit Driver Booster Pro 12 Crack Free Download
chaudhryakashoo065
ย 
What Is an Internal Quality Audit and Why It Matters for Your QMS
BizPortals365
ย 
capitulando la keynote de GrafanaCON 2025 - Madrid
Imma Valls Bernaus
ย 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
ย 
IDM Crack with Internet Download Manager 6.42 [Latest 2025]
HyperPc soft
ย 
Which Hiring Management Tools Offer the Best ROI?
HireME
ย 
IObit Driver Booster Pro 12.4-12.5 license keys 2025-2026
chaudhryakashoo065
ย 
IObit Driver Booster Pro 12 Crack Latest Version Download
pcprocore
ย 
Introduction to web development | MERN Stack
JosephLiyon
ย 
OpenChain Webinar - AboutCode - Practical Compliance in One Stack โ€“ Licensing...
Shane Coughlan
ย 
IObit Uninstaller Pro 14.3.1.8 Crack Free Download 2025
sdfger qwerty
ย 
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
ย 
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
dheeodoo
ย 
IObit Driver Booster Pro Crack Download Latest Version
chaudhryakashoo065
ย 
Agentforce โ€“ TDX 2025 Hackathon Achievement
GetOnCRM Solutions
ย 
Alur Perkembangan Software dan Jaringan Komputer
ssuser754303
ย 
Ad

BUILDING IoT WITH ARDUINO & RASPBERRY PI

  • 2. Outline โ€ข Introduction to Python โ€ข Installing Python โ€ข Python Data Types & Data Structures โ€ข Control Flow โ€ข Functions โ€ข Modules โ€ข Packages โ€ข File Input/Output โ€ข Date/Time Operations โ€ข Classes
  • 3. 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.
  • 4. 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.
  • 5. 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
  • 6. 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 >>>a=5 >>>type(a) <type โ€™intโ€™> #Floating Point >>>b=2.5 >>>type(b) <type โ€™floatโ€™> #Long >>>x=9898878787676 L >>>type(x) <type โ€™longโ€™> #Complex >>>y=2+5j >>>y (2+5j ) >>>type(y) <type โ€™complexโ€™> >>>y.rea l 2 >>>y.ima g 5 #Addition >>>c=a+b >>> c 7.5 >>>type(c) <type โ€™floatโ€™> #Subtraction >>>d=a-b >>> d 2.5 >>>type(d) <type โ€™floatโ€™> #Multiplicatio n >>>e=a*b >>> e 12.5 >>>type(e) <type โ€™floatโ€™> #Division >>>f=b/a >>> f 0.5 >>>type(f) <type floatโ€™> #Power >>>g=a** 2 >>> g 25
  • 7. 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 >>>s="Hello World!" >>>type(s) <type โ€™strโ€™> #String concatenation >>>t="This is sample program." >>>r = s+t >>>r โ€™Hello World!This is sample program.โ€™ #Get length of string >>>len(s ) 12 #Convert string to integer >>>x="100" >>>type(s) <type โ€™strโ€™> >>>y=int(x) >>> y 100 #Print string >>>print s Hello World! #Formatting output >>>print "The string (The string (Hello World!) has 12 characters #Convert to upper/lower case >>>s.upper() โ€™HELLO WORLD!โ€™ >>>s.lower() โ€™hello world!โ€™ #Accessing sub-strings >>>s[0 ] โ€™Hโ€™ >>>s[6:] โ€™World!โ€™ >>>s[6:-1] โ€™Worldโ€™ #strip: Returns a copy of the string with the #leading and trailing characters removed. >>>s.strip("!" ) โ€™Hello Worldโ€™
  • 8. 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. #Create List >>>fruits=[โ€™appleโ€™,โ€™orangeโ€™,โ€™bananaโ€™,โ€™mangoโ€™] >>>type(fruits) <type โ€™listโ€™> #Get Length of List >>>len(fruits ) 4 #Access List Elements >>>fruits[1 ] โ€™orangeโ€™ >>>fruits[1:3] [โ€™orangeโ€™, โ€™bananaโ€™] >>>fruits[1:] [โ€™orangeโ€™, โ€™bananaโ€™, โ€™mangoโ€™] #Appending an item to a list >>>fruits.append(โ€™pearโ€™) >>>fruits [โ€™appleโ€™, โ€™orangeโ€™, โ€™bananaโ€™, โ€™mangoโ€™, โ€™pearโ€™] #Removing an item from a list >>>fruits.remove(โ€™mangoโ€™) >>>fruits [โ€™appleโ€™, โ€™orangeโ€™, โ€™bananaโ€™, โ€™pearโ€™] #Inserting an item to a list >>>fruits.insert(1,โ€™mangoโ€™) >>>fruits [โ€™appleโ€™, โ€™mangoโ€™, โ€™orangeโ€™, โ€™bananaโ€™, โ€™pearโ€™] #Combining lists >>>vegetables=[โ€™potatoโ€™,โ€™carrotโ€™,โ€™onionโ€™,โ€™beansโ€™,โ€™ r adishโ€™] >>>vegetables [โ€™potatoโ€™, โ€™carrotโ€™, โ€™onionโ€™, โ€™beansโ€™, โ€™radishโ€™] >>>eatables=fruits+vegetables >>>eatables [โ€™appl eโ€™, โ€™mang oโ€™, โ€™orang eโ€™, โ€™banan aโ€™, โ€™pearโ€™, โ€™potatoโ€™, โ€™carrotโ€™, โ€™onionโ€™, โ€™beansโ€™, โ€™radishโ€™] #Mixed data types in a list >>>mixed=[โ€™dataโ€™,5,100.1,8287398L] >>>type(mixed) <type โ€™listโ€™> >>>type(mixed[0]) <type โ€™strโ€™> >>>type(mixed[1]) <type โ€™intโ€™> >>>type(mixed[2]) <type โ€™floatโ€™> >>>type(mixed[3]) <type โ€™longโ€™> #Change individual elements of a list >>>mixed[0]=mixed[0]+" items" >>>mixed[1]=mixed[1]+1 >>>mixed[2]=mixed[2]+0.05 >>>mixed [โ€™data itemsโ€™, 6, 100.14999999999999, 8287398L] #Lists can be nested >>>nested=[fruits,vegetables] >>>nested [[โ€™appleโ€™, โ€™mangoโ€™, โ€™orangeโ€™, โ€™bananaโ€™, โ€™pearโ€™], [โ€™potatoโ€™, โ€™carrotโ€™, โ€™onionโ€™, โ€™beansโ€™, โ€™radishโ€™]]
  • 9. 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 >>>fruits=("apple","mango","banana","pineapple") >>>fruits (โ€™appleโ€™, โ€™mangoโ€™, โ€™bananaโ€™, โ€™pineappleโ€™) >>>type(fruits) <type โ€™tupleโ€™> #Get length of tuple >>>len(fruits ) 4 #Get an element from a tuple >>>fruits[0 ] โ€™appleโ€™ >>>fruits[:2] (โ€™appleโ€™, โ€™mangoโ€™) #Combining tuples >>>vegetables=(โ€™potatoโ€™,โ€™carrotโ€™,โ€™onionโ€™,โ€™radishโ€™) >>>eatables=fruits+vegetables >>>eatables (โ€™appleโ€™, โ€™mangoโ€™, โ€™bananaโ€™, โ€™pineappleโ€™, โ€™potatoโ€™, โ€™carrotโ€™, โ€™onionโ€™, โ€™radishโ€™)
  • 10. 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 >>>student={โ€™nameโ€™:โ€™Maryโ€™,โ€™idโ€™:โ€™8776โ€™,โ€™majorโ€™:โ€™CSโ€™} >>>student {โ€™majorโ€™: โ€™CSโ€™, โ€™nameโ€™: โ€™Maryโ€™, โ€™idโ€™: โ€™8776โ€™} >>>type(student) <type โ€™dictโ€™> #Get length of a dictionary >>>len(student) 3 #Get the value of a key in dictionary >>>student[โ€™nameโ€™] โ€™Maryโ€™ #Get all items in a dictionary >>>student.items() [(โ€™genderโ€™, โ€™femaleโ€™), (โ€™majorโ€™, โ€™CSโ€™), (โ€™nameโ€™, โ€™Maryโ€™), (โ€™idโ€™, โ€™8776โ€™)] #Get all keys in a dictionary >>>student.keys() [โ€™genderโ€™, โ€™majorโ€™, โ€™nameโ€™, โ€™idโ€™] #Get all values in a dictionary >>>student.values() [โ€™femaleโ€™, โ€™CSโ€™, โ€™Maryโ€™, โ€™8776โ€™] #Add new key-value pair >>>student[โ€™genderโ€™]=โ€™femaleโ€™ >>>student {โ€™gende rโ€™: โ€™femaleโ€™, โ€™majorโ€™: โ€™CSโ€™, โ€™nameโ€™: โ€™Maryโ€™, โ€™idโ€™: โ€™8776โ€™} #A value in a dictionary can be another dictionary >>>student1={โ€™nameโ€™:โ€™Davidโ€™,โ€™idโ€™:โ€™9876โ€™,โ€™majorโ€™:โ€™ECEโ€™} >>>students={โ€™1โ€™: student,โ€™2โ€™:student1} >>>students {โ€™1โ€™: {โ€™gende rโ€™: โ€™femaleโ€™, โ€™majorโ€™: โ€™CSโ€™, โ€™nameโ€™: โ€™Maryโ€™, โ€™idโ€™: โ€™8776โ€™}, โ€™2โ€™: { โ€™ majorโ€™: โ€™ECEโ€™, โ€™nameโ€™: โ€™Davidโ€™, โ€™idโ€™: โ€™9876โ€™}} #Check if dictionary has a key >>>student.has_key(โ€™nameโ€™) True >>>student.has_key(โ€™gradeโ€™) False
  • 11. Type Conversions #Convert to string >>>a=10000 >>>str(a ) โ€™10000โ€™ #Convert to int >>>b="2013" >>>int(b ) 2013 #Convert to float >>>float(b ) 2013.0 #Convert to long >>>long(b ) 2013L #Convert to list >>>s="aeiou" >>>list(s) [โ€™aโ€™, โ€™eโ€™, โ€™iโ€™, โ€™oโ€™, โ€™uโ€™] #Convert to set >>>x=[โ€™mangoโ€™,โ€™appleโ€™,โ€™bananaโ€™,โ€™mangoโ€™,โ€™bananaโ€™] >>>set(x) set([โ€™mangoโ€™, โ€™appleโ€™, โ€™bananaโ€™]) โ€ข Type conversion examples
  • 12. Control Flow โ€“ if statement โ€ข The if statement in Python is similar to the if statement in other languages. >>>a = 25**5 >>>if a>10000: print "More" else: print "Less" More >>>s="Hello World" >>>if "World" in s: s=s+"!" print s Hello World! >>>if a>10000: if a<1000000: print "Between 10k and 100k" else: print "More than 100k" elif a==10000: print "Equal to 10k" else: print "Less than 10k" More than 100k >>>student={โ€™nameโ€™:โ€™Maryโ€™,โ€™idโ€™:โ€™8776โ€™} >>>if not student.has_key(โ€™majorโ€™): student[โ€™majorโ€™]=โ€™CSโ€™ >>>student {โ€™majorโ€™: โ€™CSโ€™, โ€™nameโ€™: โ€™Maryโ€™, โ€™idโ€™: โ€™8776โ€™}
  • 13. 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.
  • 14. for Syntax: For iterating_var in sequence: Execute Statements
  • 15. 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: printi i = i+1
  • 16. Control Flow โ€“ range statement โ€ข The range statement in Python generates a list of numbers in arithmetic progression. #Generate a list of numbers from 10 - 100 with increments of 10 >>>range(10,110,10) [10, 20, 30, 40, 50, 60, 70, 80, 90,100] #Generate a list of numbers from 0 โ€“ 9 >>>range (10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  • 17. Control Flow โ€“ break/continue statements โ€ข The break and continue statements in Python are similar to the statements in C. โ€ข Break โ€ข Break statement breaks out of the for/while loop โ€ข Continue โ€ข Continue statement continues with the next iteration. #Continue statement example >>>fruits=[โ€™appleโ€™,โ€™orangeโ€™,โ€™bananaโ€™,โ€™mangoโ€™] >>>for item in fruits: if item == "banana": continue else: print item apple orange mango #Break statement example >>>y=1 >>>for x in range(4,256,4): y = y * x if y > 512: break print y 4 32 384
  • 18. 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
  • 19. 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 the keyword def followed by the function name and parentheses. The function parameters are enclosed within the parenthesis. โ€ข The code block within a function begins after a colon that comes after the parenthesis enclosing the parameters. โ€ข The ๏ฌrst statement of the function body can optionally be a documentation string or docstring. 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): โ€œThis function computes the average gradeโ€ sum = 0.0 for key in students: sum = sum + students[key]['grade'] average = sum/len(students) return average avg = averageGrade(students) print (The average garde is: %0.2f" % (avg)))
  • 20. 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
  • 21. 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 re๏ฌ‚ected 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 #Adding one more fruit >>>print "There are %d fruits in the list" % (len(fruits)) There are 4 fruits in the list
  • 22. Functions - Keyword Arguments โ€ข Functions can also be called using keyword arguments that identi๏ฌes the arguments by the parameter name when the function is called. >>>def printStudentRecords(name,age=20,major=โ€™CSโ€™): print "Name: " + name print "Age: " + str(age) print "Major: " + major #This will give error as name is required argument >>>printStudentRecords() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: printStudentRecords() takes at least 1 argument (0 given) #name is a formal argument. #**kwargs is a keyword argument that receives all arguments except the formal argument as a dictionary. >>>def student(name, **kwargs): print "Student Name: " + name for key in kwargs: print key + โ€™: โ€™ + kwargs[key] >>>student(name=โ€™Bobโ€™, age=โ€™20โ€™, major = โ€™CSโ€™) Student Name: Bob age: 20 major: CS #Correct use >>>printStudentRecords(name=โ€™Alexโ€™ ) Name: Alex Age: 20 Major: CS >>>printStudentRecords(name=โ€™Bobโ€™,age=22,major=โ€™E C Eโ€™) Name: Bob Age: 22 Major: ECE >>>printStudentRecords(name=โ€™Alanโ€™,major=โ€™ECEโ€™) Name: Alan Age: 20 Major: ECE
  • 23. 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 pre๏ฌxed 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
  • 24. Modules โ€ข Python allows organizing the program code into different modules which improves the code readability and management. โ€ข A module is a Python ๏ฌle that de๏ฌnes some functionality in the form of functions or classes. โ€ข Modules can be imported using the import keyword. โ€ข Modules to be imported must be present in the search path. #student module - saved as student.py def averageGrade(students): sum = 0.0 for key in students: sum = sum + students[key]['grade'] average = sum/len(students) return average 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 student module >>>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 >>>avg = student. averageGrade(students) >>>print "The average garde is: %0.2f" % (avg) 3.62 # Importing a specific function from a module >>>from student import averageGrade # Listing all names de๏ฌnes in a module >>>dir(student)
  • 25. Packages โ€ข Python package is hierarchical ๏ฌle structure that consists of modules and subpackages. โ€ข Packages allow better organization of modules related to a single application environment. # skimage package listing skimage/ init .py Top level package Treat directory as a package 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 _daisy.py ...
  • 26. File Handling โ€ข Python allows reading and writing to ๏ฌles using the ๏ฌle object. โ€ข The open(๏ฌlename, mode) function is used to get a ๏ฌle object. โ€ข The mode can be read (r), write (w), append (a), read and write (r+ or w+), read-binary (rb), write-binary (wb), etc. โ€ข After the ๏ฌle contents have been read the close function is called which closes the ๏ฌle object. # Example of reading line by line >>>fp = open('file1.txt','r') >>>print "Line-1: " + fp.readline() Line-1: Python supports more than one programming paradigms. >>>print "Line-2: " + fp.readline() Line-2: Python is an interpreted language. >>>fp.close() # Example of reading an entire file >>>fp = open('file.txt','r') >>>content = fp.read() >>>print content This is a test file. >>>fp.close() # 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.
  • 27. File Handling # Example of seeking to a certain position >>>fp = open('file.txt','r') >>>fp.seek(10,0) >>>content = fp.read(10) >>>print content ports more >>>fp.close() # Example of reading a certain number of bytes >>>fp = open('file.txt','r') >>>fp.read(10 ) 'Python sup' >>>fp.close() # Example of getting the current position of read >>>fp = open('file.txt','r') >>>fp.read(10 ) 'Python sup' >>>currentpos = fp.tell >>>print currentpos <built-in method tell of file object at 0x0000000002391390> >>>fp.close() # Example of writing to a file >>>fo = open('file1.txt','w') >>>content='This is an example of writing to a file in Python.' >>>fo.write(content) >>>fo.close()
  • 28. 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 date >>>from datetime import date >>>now = date.today() >>>print "Date: " + now.strftime("%m-%d- %y") Date: 07-24-13 >>>print "Day of Week: " + now.strftime("%A") Day of Week: Wednesday >>>print "Month: " + now.strftime("%B") Month: July >>>then = date(2013, 6, 7) >>>timediff = now - then >>>timediff.day s 47 # Examples of manipulating with time >>>import time >>>nowtime = time.time() >>>time.localtime(nowtime) time.struct_time(tm_year=2013, tm_mon=7, tm_mday=24, tm_ec=51, tm_wday=2, tm_yday=205, tm_isdst=0) >>>time.asctime(time.localtime(nowtime)) 'Wed Jul 24 16:14:51 2013' >>>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.'
  • 29. 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.
  • 30. Class Example โ€ข The variable studentCount is a class variable that is shared by all instances of the class Student and is accessed by Student.studentCount. โ€ข The variables name, id and grades are instance variables which are speci๏ฌc to each instance of the class. โ€ข There is a special method by the name init () which is the class constructor. โ€ข The class constructor initializes a new instance when it is created. The function del () is the class destructor # Examples of a class class Student: studentCount = 0 def init (self, name, id): print "Constructor called" self.name = name self.id = id Student.studentCount = Student.studentCount + 1 self.grades={} def del (self): print "Destructor called" def getStudentCount(self): return Student.studentCount def addGrade(self,key,value): self.grades[key]=value def getGrade(self,key): return self.grades[key] def printGrades(self): for key in self.grades: print key + ": " + self.grades[key] >>>s = Student(โ€™Steveโ€™,โ€™98928โ€™) Constructor called >>>s.addGrade(โ€™Mathโ€™,โ€™90โ€™) >>>s.addGrade(โ€™Physicsโ€™,โ€™85โ€™) >>>s.printGrades() Physics: 85 Math: 90 >>>mathgrade = s.getGrade(โ€™Mathโ€™) >>>print mathgrade 90 >>>count = s.getStudentCount() >>>print count 1 >>>del s Destructor called
  • 31. 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 de๏ฌned in the base class Shape is overridden in child class Circle). # Examples of class inheritance class Shape: def init (self): print "Base class constructor" self.color = โ€™Greenโ€™ self.lineWeight = 10.0 def draw(self): print "Draw - to be implemented" def setColor(self, c): self.color = c def getColor(self): return self.color def setLineWeight(self,lwt): self.lineWeight = lwt def getLineWeight(self): return self.lineWeight class Circle(Shape): def init (self, c,r): print "Child class constructor" self.center = c self.radius = r self.color = โ€™Greenโ€™ self.lineWeight = 10.0 self. label = โ€™Hidden circlelabelโ€™ def setCenter(self,c): self.center = c def getCenter(self): return self.center def setRadius(self,r): self.radius = r def getRadius(self): return self.radius def draw(self): print "Draw Circle (overridden function)" class Point: def init (self, x, y): self.xCoordinate = x self.yCoordinate = y def setXCoordinate(self,x): self.xCoordinate = x def getXCoordinate(self): return self.xCoordinate def setYCoordinate(self,y): self.yCoordinate = y def getYCoordinate(self): return self.yCoordinate >>>p = Point(2,4) >>>circ = Circle(p,7) Child class constructor >>>circ.getColor() โ€™Greenโ€™ >>>circ.setColor(โ€™Redโ€™) >>>circ.getColor() โ€™Redโ€™ >>>circ.getLineWeight() 10.0 >>>circ.getCenter().getXCoordinate() 2 >>>circ.getCenter().getYCoordinate() 4 >>>circ.draw() Draw Circle (overridden function) >>>circ.radius 7
  • 33. Numbers: This data type is used to store numeric values
  • 35. Lists
  • 37. 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.
  • 39. 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
  • 41. Control Flow The if statement in python is similar to the if statement of other languages.
  • 42. for Syntax: For iterating_var in sequence: Execute Statements
  • 44. range
  • 45. 5. Break/Continue The Break statement breaks out for/while loop where as continue statement continues with next iteration
  • 47. Pass The pass statement is used when statement is required syntactically but you do not want any command or code to execute.
  • 49. 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.
  • 51. 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.
  • 53. 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
  • 54. 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
  • 55. The simplest form of class definition looks like this:
  • 58. 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.
  • 60. 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.
  • 61. 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.
  • 62. Simple Example in JSON The following example shows how to use JSON to store information related to books based on their topic and edition. "
  • 63. 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.
  • 66. 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.)
  • 69. 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.
  • 70. 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.
  • 72. 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.
  • 73. 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]])
  • 74. 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.
  • 76. If we wanted to use an already-opened file, can just pass our file object to parse like so:
  • 77. 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.
  • 79. 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")