Unit III - 1
Unit III - 1
Unit - 3
Python:
• Python is a general-purpose high-level programming language 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 paradigm, 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 reading English with pseudocode-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.
• Object-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 the source.
• Broad library support
• Python has broad library support and works on various platforms such as Windows, Linux,
Mac, etc.
Features in Python:
There are many features in Python, some of which are discussed below –
1. Easy to code:
Python is a high-level programming language. Python is very easy to learn the language as compared to other
languages like C, C#, Javascript, Java, etc. It is very easy to code in python language and anybody can learn
python basics in a few hours or days. It is also a developer-friendly language.
2. Free and Open Source:
Python language is freely available at the official website and you can download it from the given download
link below click on the Download Python keyword.
Download Python Since it is open-source, this means that source code is also available to the public. So you
can download it as, use it as well as share it.
3. Object-Oriented Language:
One of the key features of python is Object-Oriented programming. Python supports object-oriented language
and concepts of classes, objects encapsulation, etc.
4. GUI Programming Support:
Graphical User interfaces can be made using a module such as PyQt5, PyQt4, wxPython, or Tk in python.
PyQt5 is the most popular option for creating graphical apps with Python.
5. High-Level Language:
Python is a high-level language. When we write programs in python, we do not need to remember the system
architecture, nor do we need to manage the memory.
6. Extensible feature:
Python is a Extensible language. We can write us some Python code into C or C++ language and also we can
compile that code in C/C++ language.
Numbers:
• The 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)
< class ’int’>
#Floating Point
>>>b=2.5
>>>type(b)
< class ’float’>
#Complex
>>>y=2+5j
>>>y
(2+5j)
>>>type(y)
< class ’complex’>
>>>y.real
2.0
>>>y.imag
5.0
#bool
>>> bool = a>b
>>> bool
True
>>> type(bool)
<class 'bool’>
#Addition
>>>c=a+b
>>>c
7.5
#Subtraction
>>>d=a-b
>>>d
2.5
#Multiplication
>>>e=a*b
>>>e
12.5
#Division
>>>f=b/a
>>>f
0.5
#Power
>>>g=a**2
>>>g
25
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)
<class 'str’>
#String concatenation
>>> p= 'Python Programming'
>>> x=s+p
>>> x
'Hello WorldPython Programming’
#Print string
>>>print(s)
Hello World!
#Formatting output
>>> print('Hello\n world!')
Hello
world!
>>> print('Hima's book')
SyntaxError: invalid syntax
>>> print("Hima's book")
Hima's book
>>> print('Hima\'s book')
Hima's book
#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’
Core Concepts of IoT By Dr. V. Deepika - 5-
Lists:
• A list is a compound/ most versatile data type used to group together other values. List items need not
all be of the same type. A list contains items separated by commas and enclosed within square brackets.
#Create List
>>>fruits=[’apple’,’orange’,’banana’,’mango’]
>>>type(fruits)
<class ’list’>
Tuples:
• A tuple is a sequence of immutable Python objects (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)
<class ’tuple’>
#Combining tuples
>>>vegetables=(’potato’,’carrot’,’onion’,’radish’)
>>>eatables=fruits+vegetables
>>>eatables
(’apple’, ’mango’, ’banana’, ’pineapple’, ’potato’, ’carrot’, ’onion’, ’radish’)
#Create a dictionary
>>>student={’name’:’Mary’,’id’:’8776’,’major’:’CS’}
>>>student
{’major’: ’CS’, ’name’: ’Mary’, ’id’: ’8776’}
>>>type(student)
<class ’dict’>
Range:
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by
default), and stops before a specified number.
Syntax:
range(start, stop, step)
Ex:
>>> range(10)
range(0, 10)
>>> list(range(5))
[0, 1, 2, 3, 4, 5]
>>> range
<class 'range'>
>>> list(range(2, 10, 2))
[2, 4, 6, 8]
>>> list(range(2, 15, 3))
[2, 5, 8, 11, 14]
Type Conversions:
Ex:
#Implicit Type Conversion
>>> x=10
<class ‘int’>
>>> y=10.2
>>> x=x+y
>>> x
20.2
>>> type(x)
<class 'float’>
#conversions
>>> bin(20)
'0b10100’
>>> 0b0111
7
>>> oct(25)
'0o31’
>>> hex(20)
'0x14’
>>> 0xa
10
Control flow
In this example we use two variables, a and b, which are used as part of the if statement to test whether b is
greater than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so we print to screen that "b
is greater than a".
Indentation:
Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other
programming languages often use curly-brackets for this purpose.
Example
If statement, without indentation (will raise an error):
a = 33
b = 200
Elif
The elif keyword is pythons way of saying "if the previous conditions were not true, then try this condition".
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
In this example a is equal to b, so the first condition is not true, but the elif condition is true, so we print to
screen that "a and b are equal".
Else
The else keyword catches anything which isn't caught by the preceding conditions.
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
In this example a is greater than b, so the first condition is not true, also the elif condition is not true, so we
go to the else condition and print to screen that "a is greater than b".
You can also have an else without the elif:
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Short Hand If
If you have only one statement to execute, you can put it on the same line as the if statement.
Example
One line if statement:
if a > b: print("a is greater than b")
And
The and keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Or
The or keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, OR if a is greater than c:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
Nested If
You can have if statements inside if statements, this is called nested if statements.
Example
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
if b > a:
pass
The for loop does not require an indexing variable to set beforehand.
Note: The else block will NOT be executed if the loop is stopped by a break statement.
Example
Break the loop when x is 3, and see what happens with the else block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
The break Statement
With the break statement we can stop the loop before it has looped through all the items:
Example
Exit the loop when x is "banana":
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
Example
Exit the loop when i is 3:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
Functions:
• A function is a block of code that takes in information (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 first statement of the function body can optionally be a documentation string or docstring.
Ex:
#This function computes the average grade
students = {'1': {'name': 'Bob', 'grade': 2.5},
'2': {'name': 'Mary', 'grade': 3.5},
'3': {'name': 'David', 'grade': 4.2},
'4': {'name': 'John', 'grade': 4.1},
'5': {'name': 'Alex', 'grade': 3.8}}
def averageGrade(students):
sum = 0.0
for key in students:
sum = sum + students[key]['grade']
average = sum / len(students)
return average
avg = averageGrade(students)
print("The average garde is: %0.2f" % (avg))
o/p:
There are 3 fruits in the list
banana
pear
mango
o/p:
There are 3 fruits in the list
banana
pear
apple
o/p:
There are 4 fruits in the list
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.
Example:
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
o/p:
The youngest child is Linus
• If you do not know how many keyword arguments that will be passed into your function, add two
asterisk: ** before the parameter name in the function definition.
• This way the function will receive a dictionary of arguments, and can access the items accordingly:
Ex:
If the number of keyword arguments is unknown, add a double ** before the parameter name:
def my_function(**kid):
print("His last name is " + kid["lname"])
o/p:
His last name is Refsnes
o/p:
Error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: printStudentRecords() takes at least 1 argument (0 given)
#Correct use
>>>printStudentRecords(name='Alex')
o/p:
Name: Alex
Age: 20
Major: CS
>>> printStudentRecords(name='Bob',age=22,major='ECE')
o/p:
Name: Bob
Age: 22
Major: ECE
>>> printStudentRecords(name='Alan',major='ECE')
o/p:
Name: Alan
Age: 20
Major: ECE
student('Nav')
O/P:
Student Name: Nav
O/P:
Student Name: Amy
Age: 24
Create a Module:
To create a module just save the code you want in a file with the file extension .py:
Use a Module:
Now we can use the module we just created, by using the import statement:
Ex:
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Jonathan")
Note: When using a function from a module, use the syntax: module_name.function_name.
Variables in Module
The module can contain functions, as already described, but also variables of all types(arrays,
dictionaries, objects etc):
Example
Save this code in the file mymodule.py
Example
Import the module named mymodule, and access the person1 dictionary:
import mymodule
a = mymodule.person1["age"]
print(a)
o/p:
36
Naming a Module
You can name the module file whatever you like, but it must have the file extension .py
Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
Example
Create an alias for mymodule called mx:
import mymodule as mx
a = mx.person1["age"]
print(a)
o/p:
36
Built-in Modules
There are several built-in modules in Python, which you can import whenever you like.
Example
Import and use the platform module:
import platform
x = platform.system()
O/p:
Windows
Example
List all the defined names belonging to the platform module:
import platform
x = dir(platform)
print(x)
O/p:
F:\pythonProject\venv\Scripts\python.exe F:/pythonProject/main.py
['_Processor', '_WIN32_CLIENT_RELEASES', '_WIN32_SERVER_RELEASES', '__builtins__',
'__cached__', '__copyright__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__',
'__version__', '_comparable_version', '_component_re', '_default_architecture', '_follow_symlinks',
'_get_machine_win32', '_ironpython26_sys_version_parser', '_ironpython_sys_version_parser',
'_java_getprop', '_libc_search', '_mac_ver_xml', '_node', '_norm_version', '_platform', '_platform_cache',
'_pypy_sys_version_parser', '_sys_version', '_sys_version_cache', '_sys_version_parser', '_syscmd_file',
'_syscmd_ver', '_uname_cache', '_unknown_as_blank', '_ver_output', '_ver_stages', 'architecture',
'collections', 'functools', 'itertools', 'java_ver', 'libc_ver', 'mac_ver', 'machine', 'node', 'os', 'platform',
'processor', 'python_branch', 'python_build', 'python_compiler', 'python_implementation', 'python_revision',
'python_version', 'python_version_tuple', 're', 'release', 'subprocess', 'sys', 'system', 'system_alias', 'uname',
'uname_result', 'version', 'win32_edition', 'win32_is_iot', 'win32_ver']
Note: The dir() function can be used on all modules, also the ones you create yourself.
def greeting(name):
print("Hello, " + name)
person1 = {"name": "John", "age": 36, "country": "Norway"}
Example
Import only the person1 dictionary from the module:
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
student.printRecords(students)
o/p:
There are 5 students
Student-1:
Name: Bob
Grade: 2.5
Student-2:
Name: Mary
Grade: 3.5
Student-3:
Name: David
Grade: 4.2
Student-4:
Name: John
Grade: 4.1
Student-5:
Name: Alex
Grade: 3.8
o/p:
The average garde is: 3.62
====================================================================
Packages:
We don't usually store all of our files on our computer in the same location. We use a well-organized hierarchy
of directories for easier access.
Similar files are kept in the same directory, for example, we may keep all the songs in the "music" directory.
Analogous to this, Python has packages for directories and modules for files.
As our application program grows larger in size with a lot of modules, we place similar modules in one
package and different modules in different packages. This makes a project (program) easy to manage and
conceptually clear.
Similarly, as a directory can contain subdirectories and files, a Python package can have sub-packages and
modules.
A directory must contain a file named __init__.py in order for Python to consider it as a package. This file can
be left empty but we generally place the initialization code for that package in this file.
Here is an example. Suppose we are developing a game. One possible organization of packages and modules
could be as shown in the figure below.
import Game.Level.start
Now, if this module contains a function named select_difficulty(), we must use the full name to reference it.
Game.Level.start.select_difficulty(2)
If this construct seems lengthy, we can import the module without the package prefix as follows:
start.select_difficulty(2)
Another way of importing just the required function (or class or variable) from a module within a package
would be as follows:
select_difficulty(2)
Although easier, this method is not recommended. Using the full namespace avoids confusion and prevents
two same identifier names from colliding.
While importing packages, Python looks in the list of directories defined in sys.path, similar as for module
search path.
Ex:
Let's create a package named mypackage, using the following steps:
• Create a package named 'mypackage'.
• create modules greet.py and functions.py with the following code:
greet.py
def SayHello(name):
print("Hello ", name)
functions.py
def sum(x,y):
print(x+y)
def average(x,y):
print((x+y)/2)
def power(x,y):
print(x**y)
That's it. We have created our package called mypackage. The following is a folder structure:
Syntax
file object = open(file_name [, access_mode][, buffering])
1 r
Opens a file for reading only. The file pointer is placed at the beginning of the file. This is
the default mode.
2 rb
Opens a file for reading only in binary format. The file pointer is placed at the beginning of
the file. This is the default mode.
4 rb+
Opens a file for both reading and writing in binary format. The file pointer placed at the
beginning of the file.
5 w
Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist,
creates a new file for writing.
6 wb
Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file
does not exist, creates a new file for writing.
7 w+
Opens a file for both writing and reading. Overwrites the existing file if the file exists. If
the file does not exist, creates a new file for reading and writing.
8 wb+
Opens a file for both writing and reading in binary format. Overwrites the existing file if
the file exists. If the file does not exist, creates a new file for reading and writing.
9 a
Opens a file for appending. The file pointer is at the end of the file if the file exists. That is,
the file is in the append mode. If the file does not exist, it creates a new file for writing.
10 ab
Opens a file for appending in binary format. The file pointer is at the end of the file if the
file exists. That is, the file is in the append mode. If the file does not exist, it creates a new
file for writing.
11 a+
Opens a file for both appending and reading. The file pointer is at the end of the file if the
file exists. The file opens in the append mode. If the file does not exist, it creates a new file
for reading and writing.
12 ab+
Opens a file for both appending and reading in binary format. The file pointer is at the end
of the file if the file exists. The file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.
1 file.closed
Returns true if file is closed, false otherwise.
2 file.mode
Returns access mode with which file was opened.
3 file.name
Returns name of the file.
Note − softspace attribute is not supported in Python 3.x
Example
#!/usr/bin/python3
# Open a file
fo = open("a.txt", "wb")
print ("Name of the file: ", fo.name)
print ("Closed or not : ", fo.closed)
print ("Opening mode : ", fo.mode)
fo.close()
This produces the following result −
Name of the file: a.txt
Closed or not : False
Opening mode : wb
Syntax
fileObject.close();
Example
#!/usr/bin/python3
# Open a file
fo = open("a.txt", "wb")
print ("Name of the file: ", fo.name)
Syntax
fileObject.write(string);
Here, passed parameter is the content to be written into the opened file.
Example
#!/usr/bin/python3
# Open a file
fo = open("a.txt", "w")
fo.write( "Python is a great language.\nYeah its great!!\n")
Syntax
fileObject.read([count]);
Here, passed parameter is the number of bytes to be read from the opened file. This method starts reading
from the beginning of the file and if count is missing, then it tries to read as much as possible, maybe until
the end of file.
Example
Let us take a file foo.txt, which we created above.
#!/usr/bin/python3
# Open a file
fo = open(“a.txt”, “r+”)
str = fo.read(10)
print (“Read String is : “, str)
File Positions
The tell() method tells you the current position within the file; in other words, the next read or write will
occur at that many bytes from the beginning of the file.
The seek(offset[, from]) method changes the current file position. The offset argument indicates the number
of bytes to be moved. The from argument specifies the reference position from where the bytes are to be
moved.
If from is set to 0, the beginning of the file is used as the reference position. If it is set to 1, the current position
is used as the reference position. If it is set to 2 then the end of the file would be taken as the reference
position.
Example
Let us take a file foo.txt, which we created above.
#!/usr/bin/python3
# Open a file
fo = open("a.txt", "r+")
str = fo.read(10)
print ("Read String is : ", str)
Example
Following is an example to rename an existing file test1.txt −
#!/usr/bin/python3
import os
Example
Following is an example to delete an existing file test2.txt −
#!/usr/bin/python3
import os
main.py
fp = open('file.txt','r')
content = fp.read()
print(content)
fp.close()
o/p:
This is a test file.
# Example of reading line by line
file1.txt
Python supports more than one programming paradigms.
Python is an interpreted language.
main.py
fp = open('file1.txt','r')
print("Line-1: " + fp.readline())
print("Line-2: " + fp.readline())
fp.close()
o/p:
Python supports more than one programming paradigms.
Python is an interpreted language.
===================================================================
Date/Time Operations:
we can import a module named datetime to work with dates as date objects.
Example
Import the datetime module and display the current date:
import datetime
x = datetime.datetime.now()
print(x)
O/p:
2021-06-06 23:14:25.497227
The date contains year, month, day, hour, minute, second, and microsecond.
The datetime module has many methods to return information about the date object.
Here are a few examples, you will learn more about them later in this chapter:
Ex:
Return the year and name of weekday:
import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
O/p:
2021
Sunday
x = datetime.datetime(2020, 5, 17)
print(x)
O/p:
2020-05-17 00:00:00
The datetime() class also takes parameters for time and timezone (hour, minute, second, microsecond,
tzone), but they are optional, and has a default value of 0, (None for timezone).
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))
O/p:
June
%H Hour 00-23 17
%I Hour 00-12 05
%p AM/PM PM
%S Second 00-59 08
%Z Timezone CST
%% A % character %
now = date.today()
print("Day of Week: " + now.strftime("%A"))
Day of Week: Wednesday
now = date.today()
print( "Month: " + now.strftime("%B"))
Month: July
now = date.today()
then = date(2013, 6, 7)
timediff = now - then
print(timediff.days)
47
import time
print(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 05-06-21. Today is a Saturday. It is 12 hours, 41 minutes and 09 seconds now.
====================================================================
Classes:
• Python is an Object-Oriented Programming (OOP) language. Python provides all the standard
features of OOP 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 a user-defined prototype for an
object that is composed of three things: a name, attributes and operations/methods.
• Instance/Object
• An 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.
Ex: 1
My name is Tom
My name is Jerry
def introduce_self(self):
print("My name is " + self.name)
# r1 = Robot()
# r1.name = "Tom"
# r1.color = "red"
# r1.weight = 30
#
# r2 = Robot()
# r2.name = "Jerry"
# r2.color = "blue"
# r2.weight = 40
r1.introduce_self()
r2.introduce_self()
o/p:
My name is Tom
My name is Jerry
Core Concepts of IoT By Dr. V. Deepika - 36-
Ex: 2
• 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 specific 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
mathgrade = s.getGrade('Math')
print(mathgrade)
count = s.getStudentCount()
print(count)
del s
O/p:
Constructor called
Math: 90
Physics: 85
90
1
Destructor called
Example
Create a class named Person, with firstname and lastname properties, and a printname method:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
O/p: John Doe
Example
Create a class named Student, which will inherit the properties and methods from the Person class:
class Student(Person):
pass
Note: Use the pass keyword when you do not want to add any other properties or methods to the class.
Now the Student class has the same properties and methods as the Person class.
Example
Use the Student class to create an object, and then execute the printname method:
x = Student("Mike", "Olsen")
x.printname()
Handling an exception:
Syntax:
Here is simple syntax of try....except...else blocks −
try:
You do your operations here
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Exception handling:
Standard Exceptions
Here is a list of Standard Exceptions available in Python. −
Sr.No. Exception Name & Description
1 Exception
Base class for all exceptions
2 StopIteration
Raised when the next() method of an iterator does not point to any object.
3 SystemExit
Raised by the sys.exit() function.
4 StandardError
Base class for all built-in exceptions except StopIteration and SystemExit.
5 ArithmeticError
Base class for all errors that occur for numeric calculation.
6 OverflowError
Raised when a calculation exceeds maximum limit for a numeric type.
7 FloatingPointError
Raised when a floating point calculation fails.
8 ZeroDivisonError
Raised when division or modulo by zero takes place for all numeric types.
9 AssertionError
Raised in case of failure of the Assert statement.
11 EOFError
Raised when there is no input from either the raw_input() or input() function and the end of
file is reached.
12 ImportError
Raised when an import statement fails.
13 KeyboardInterrupt
Raised when the user interrupts program execution, usually by pressing Ctrl+c.
14 LookupError
Base class for all lookup errors.
15 IndexError
Raised when an index is not found in a sequence.
16 KeyError
Raised when the specified key is not found in the dictionary.
17 NameError
Raised when an identifier is not found in the local or global namespace.
18 UnboundLocalError
Raised when trying to access a local variable in a function or method but no value has been
assigned to it.
19 EnvironmentError
Base class for all exceptions that occur outside the Python environment.
20 IOError
Raised when an input/ output operation fails, such as the print statement or the open()
function when trying to open a file that does not exist.
21 OSError
Raised for operating system-related errors.
22 SyntaxError
Raised when there is an error in Python syntax.
23 IndentationError
Raised when indentation is not specified properly.
24 SystemError
Raised when the interpreter finds an internal problem, but when this error is encountered
the Python interpreter does not exit.
26 TypeError
Raised when an operation or function is attempted that is invalid for the specified data type.
27 ValueError
Raised when the built-in function for a data type has the valid type of arguments, but the
arguments have invalid values specified.
28 RuntimeError
Raised when a generated error does not fall into any category.
29 NotImplementedError
Raised when an abstract method that needs to be implemented in an inherited class is not
actually implemented.
Example
This example opens a file, writes content in the, file and comes out gracefully because there is no problem at
all −
#!/usr/bin/python3
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
fh.close()
This produces the following result −
Written content in the file successfully
Example
This example tries to open a file where you do not have the write permission, so it raises an exception −
#!/usr/bin/python3
try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
This produces the following result −
Error: can't find file or read data
JSON:
• JavaScript Object Notation (JSON) is an easy to read and write data-interchange format.
• JSON is used as an alternative to XML and is easy for machines to parse and generate.
• JSON is built on two structures:
• a collection of name–value pairs (e.g., a Python dictionary)
• ordered lists of values (e.g., a Python list).
JSON in Python
Python has a built-in package called json, which can be used to work with JSON data.
Example
Import the json module:
import json
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
Example
Convert from Python to JSON:
import json
O/p:
{
"name": "John",
"age": 30,
"city": "New York"
}
You can convert Python objects of the following types, into JSON strings:
• dict
• list
• tuple
• string
• int
• float
• True
• False
• None
Example
Convert Python objects into JSON strings, and print the values:
import json
O/p:
{"name": "John", "age": 30}
["apple", "bananas"]
When you convert from Python to JSON, Python objects are converted into the JSON (JavaScript)
equivalent:
Python JSON
dict Object
list Array
tuple Array
str String
int Number
float Number
True true
False false
None null
Example
Convert a Python object containing all the legal data types:
import json
x={
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}
O/P:
{"name": "John", "age": 30, "married": true, "divorced": false, "children": ["Ann", "Billy"], "pets": null,
"cars": [{"model": "BMW 230", "mpg": 27.5}, {"model": "Ford Edge", "mpg": 24.1}]}
Example
Use the indent parameter to define the numbers of indents:
print(json.dumps(x, indent=4))
O/P:
{
"name": "John",
"age": 30,
"married": true,
"divorced": false,
"children": [
"Ann",
"Billy"
],
"pets": null,
"cars": [
{
"model": "BMW 230",
"mpg": 27.5
},
{
"model": "Ford Edge",
"mpg": 24.1
}
]
}
You can also define the separators, default value is (", ", ": "), which means using a comma and a space to
separate each object, and a colon and a space to separate keys from values:
Example
Use the separators parameter to change the default separator:
Example
Use the sort_keys parameter to specify if the result should be sorted or not:
O/P:
{
"age": 30,
"cars": [
{
"model": "BMW 230",
"mpg": 27.5
},
{
"model": "Ford Edge",
"mpg": 24.1
}
],
"children": [
"Ann",
"Billy"
XML:
• XML (Extensible Markup Language) is a data format for structured document interchange.
• The Python minidom library provides a minimal implementation of the Document Object
Model interface.
• It has an API similar to that in other languages.
What is XML?
The Extensible Markup Language (XML) is a markup language much like HTML or SGML. This is
recommended by the World Wide Web Consortium and available as an open standard.
XML is extremely useful for keeping track of small to medium amounts of data without requiring an SQL-
based backbone.
Example: main.py
#!/usr/bin/python3
import xml.sax
if ( __name__ == "__main__"):
# create an XMLReader
parser = xml.sax.make_parser()
# turn off namepsaces
parser.setFeature(xml.sax.handler.feature_namespaces, 0)
Output
This would produce the following result −
*****Movie*****
Title: Enemy Behind
Type: War, Thriller
Format: DVD
Year: 2003
Rating: PG
Stars: 10
Description: Talk about a US-Japan war
*****Movie*****
Title: Transformers
Type: Anime, Science Fiction
Format: DVD
Year: 1989
Rating: R
Stars: 8
Description: A scientific fiction
*****Movie*****
Title: Trigun
Type: Anime, Action
Format: DVD
Rating: PG
Stars: 10
Description: Vash the Stampede!
*****Movie*****
Title: Ishtar
Type: Comedy
Format: VHS
Rating: PG
Stars: 2
Description: Viewable boredom