Unit-Ii-Introduction To Python
Unit-Ii-Introduction To Python
Unit-Ii-Introduction To Python
Language features of Python, Data types& data structures, Control flow Functions, Modules
Packages, File Handling, Data/Time operations, Classes, Python packages of interest for
IoT(JSON,XML)
Introduction:
Before stepping into the world of programming using open source tools, one should try to
understand the definition of open-source software given by “Open Source Initiative”
(abbreviated as OSI). OSI is a non-profit corporation with global scope, formed to educate about
and advocate the benefits of open source software, and to build bridges among different
constituencies in the open-source community.
Open-source software is a defined as software whose source code is made available under a
license that allows modification and re-distribution of the software at will. Sometimes a
distinction is made between open source software and free software as given by GNU
{http://www.gnu.org/). The detailed distribution terms of open-source software given by OSI are
given on the website link: http://opensource. org/.
Introduction to Python – History, Documentation Python
Python follows a modular programming approach, which is a software design technique that
emphasizes separating the functionality of a program into independent, interchangeable modules,
such that each contains everything necessary to execute only one aspect of the desired
functionality. Conceptually, modules represent a separation of concerns and improve
maintainability by enforcing logical boundaries between components.
More information on the module is provided in chapter 5. Python versions are numbered in the
format A.B.C or A.B, where A is the major version number, and it is only incremented for major
changes in the language; B is the minor version number, and incremented for relatively lesser
changes; C is the micro-level, and it is incremented for bug-fixed release.
IDLE is an IDE, and it is the basic editor and interpreter environment which ships with the
standard distribution of Python. IDLE is the built using “Tkinter” GUI toolkit, and has the
following features:
var1=5
var2= 'Tom'
var1 and var2 are identifiers, while 5 and „ Tom‟ are integer and string literals, respectively.
Consider a scenario where a variable is referenced by the identifier a and the variable contains a
list. If the same variable is referenced by the identifier b as well, and if an element in the list is
changed, the change will be reflected in both identifiers of the same variable.
>>> a = [1, 2, 3]
>>> b =a
>>> b
[1, 2, 3]
>> a [ 1 ] =10
>>> a
[1, 10, 3]
>>> b
[1, 10, 3]
There are some rules that need to be followed for valid identifier naming:
The first character of the identifier must be a letter of the alphabet (uppercase or lowercase) or an
underscore („_‟).
The rest of the identifier name can consist of letters (uppercase or lowercase character),
underscores („_‟), or digits (0-9).
Identifier names are case-sensitive. For example, myname and myName are not the same.
Identifiers can be of unlimited length.
String
Python can manipulate string, which can be expressed in several ways. String literals can be
enclosed in matching single quotes („) or double quotes (“); e.g. „hello‟, “hello” etc. They can
also be enclosed in matching groups of three single or double quotes (these are generally referred
to as triple- quoted strings), e.g. „ hello „, “hello”. A string is enclosed in double-quotes if the
string contains a single quote (and no double quotes), else it is enclosed in single quotes.
>>> "doesnt"
'doesnt'
>>> "doesn't"
"doesn't"
>>> '"Yes," he said.'
' "Yes., " he said. '
The above statements can also be written in some other interesting way using escape sequences.
>>> "doesn\' t" ;
"doesn ' t”
„>>> '\"Yes,\" he said.'
' "Yes," he said.'
Python Programming – Data Structures
A data structure is a group of data elements grouped together under one name. Python‟s data
structures are very intuitive from a syntax point of view, and they offer a large choice of
operations. This chapter tries to put together the most common and useful information about
various data structures. Some of the Python‟s data structures that are discussed in this book are
list, tuple, set, and dictionary.
Python allows its users to create their own Data Structures enabling them to have full control
over their functionality. The most prominent Data Structures are Stack, Queue, Tree, Linked List
and so on which are also available to you in other programming languages. So now that you
know what are the types available to you, why don‟t we move ahead to the Data Structures and
implement them using Python.
Python Programming – Tuple
Tuple
There is also another sequence type- tuple. Tuples is a sequence just like list. The differences are
that tuple cannot be changed i.e. tuple is immutable, while list is mutable, and tuple use
parentheses, while list use square brackets. Tuple items need not to be of same data type. Also,
as mentioned previously, Python allow adding a trailing comma after last item of tuple.
>>> a= ( ' spam ' , ' eggs ' , 100 , 1234 )
>>> a
( ' spam ' , ' eggs ' , 100 , 1234 )
>>> a= ( ' spam ' , ' eggs ' , 100 , 1234 , )
>>> a
( ' spam ' , ' eggs ' , 100 , 1234 )
The above expressions are examples of a “tuple packing” operation i.e. the values „ spam „, „
eggs „, 10 0, and 123 4 are packed together in a tuple. The reverse operation is also possible, for
example:
>>> a1 , a2 , a3 , a4=a
>>> a1
' spam '
>>> a2 ' eggs '
>>> a3 100
>>> a4 1234
This is called “sequence unpacking”, and works for any sequence on the right-hand side.
Sequence unpacking requires the group of variables on the left to have the same number of
elements as the length of the sequence. Note that multiple assignments are really just a
combination of tuple packing and sequence unpacking.
>>> a , b=10 , 20
>>> a
10
>>> b
20
Control Flow
if:
The if statement in python is similar to the if statement of other languages.
Python if...else Statement
Every value in Python has a datatype. Since everything is an object in Python programming, data
types are actually classes and variables are instance (object) of these classes. Decision making is
required when we want to execute a code only if a certain condition is satisfied.
Here, the program evaluates the test expression and will execute statement(s) only if the text
expression is True.
If the text expression is False, the statement(s) is not executed. In Python, the body of the
if statement is indicated by the indentation. Body starts with an indentation and the first
unindicted line marks the end. Python interprets non-zero values as True. None and 0 are
interpreted as False.
Python if Statement Flowchart
Example: Python if Statement
# If the number is positive, we print an appropriate message num = 3
if num > 0:
print (num, "is a positive number.") print("This is always printed.")
num = -1
if num >0:
print (num, "is a positive number.") print("This is also always printed.")
When you run the program, the output will be:
3 is a positive number this is always printed
This is also always printed.
In the above example, num > 0 is the test expression. The body of if is executed only if this
evaluates to True.
When variable num is equal to 3, test expression is true and body inside body of if is executed. If
variable num is equal to -1, test expression is false and body inside body of it is skipped. The
print () statement falls outside of the if block (unindicted). Hence, it is executed regardless of the
test expression.
Python if...else Statement Syntax
if test expression: Body of if
else:
Body of else
The if..else statement evaluates test expression and will execute body of if only when test
condition is True.
If the condition is False, body of else is executed. Indentation is used to separate the blocks.
Python if..else Flowchart
Example of if...else
# Program checks if the number is positive or negative # And displays an appropriate message
num = 3
# Try these two variations as well. # num = -5
# num = 0
if num >= 0: print("Positive or Zero")
else:
print("Negative number")
In the above example, when num is equal to 3, the test expression is true and body of if is
executed and body of else is skipped. If num is equal to -5, the test expression is false and body
of else is executed and body of if is skipped. If num is equal to 0, the test expression is true and
body of if is executed and body of else is skipped.
Python if...elif...else Statement Syntax
if test expression:
Body of if
elif test expression:
Body of elif else:
Body of else
The elif is short for else if. It allows us to check for multiple expressions. If the condition for if
is False, it checks the condition of the next elif block and so on. If all the conditions are
False, body of else is executed. Only one block among the several if...elif...else blocks is
executed according to the condition. The if block can have only one else block. But it can have
multiple elif blocks.
Flowchart of if...elif...else
Syntax
# Program to find the sum of all numbers stored in a list # List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum sum = 0
# Output: [2, 3, 4, 5, 6, 7]
print (list(range(2, 8)))
# Output: [2, 5, 8, 11, 14, 17]
print(list(range(2, 20, 3)))
We can use the range() function in for loops to iterate through a sequence of numbers. It can be
combined with the len() function to iterate though a sequence using indexing. Here is an
example.
# Program to iterate through a list using indexing genre = ['pop', 'rock', 'jazz']
# iterate over the list using index for i in range(len(genre)):
print("I like", genre[i])
Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains
any mutable object either directly or indirectly, it cannot be used as a key. The list cannot be
used as keys, since lists are of mutable type. Also, as mentioned previously, Python allows
adding a trailing comma after the last item of the dictionary.
>>> a= { ' sape ' : 4139 , ' guido ' : 4127 , ' jack ' : 4098 }
>>> a
{ ' sape ' : 4139 , ' jack ' : 4098 , ' guido ' : 4127 }
>>> a [ ' jack ' ]
4098
>>> a= { ' sape ' : 4139, ' guido ' : 4127, ' jack ' : 4098 , }
>>> a
{ ' sape ' : 4139 , ' jack ' : 4098 , ' guido ' : 4127 }
Python Programming – Modules and Packages
As the program gets longer, it is a good option to split it into several files for easier maintenance.
There might also be a situation when the programmer wants to use a handy function that is used
in several programs without copying its definition into each program. To support such scenarios,
Python has a way to put definitions in a file and use them in a script or in an interactive instance
of the interpreter.
Module
A module is a file containing Python definitions and statements. The file name is the module
name with the suffix .py appended. Definitions from a module can be imported into other
modules. For instance, consider a script file called “fibo.py” in the current directory with the
following code.
# Fibonacci numbers module
Functions
A Function is a block of code that takes 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
function name and parenthesis. The function parameters are enclosed with this
parenthesis.
Package
A Directory that contains __init__.py is a package.
A Package is a Hierarchical file directory structure that defines a single python
application environment that consists of modules and sub packages and sub sub packages
and soon.
File Handling
Python allows reading and writing to files using the file object.
The open(filename, mode) function is used to get a file object.
The mode can be read(r),write(w),append(a),read binary(rb),write binary(wb),etc.,
After the file contents have been read the close () is called which closes the file
object
Class
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:
Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from another
class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class .
Create a Parent Class
Any class can be a parent class, so the syntax is the same as creating any other class:
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()
Example
Create a class named Student, which will inherit the properties and methods from the Person class:
class Student(Person):
pass
JSON
JSON or JavaScript Object Notation is a lightweight text-based open standard designed for
human-readable data interchange.
The official Internet media type for JSON is application/json. The JSON filename extension
is .json.
JSON or JavaScript Object Notation is a lightweight text-based open standard designed for
human-readable data interchange. Conventions used by JSON are known to programmers, which
include C, C++, Java, Python, Perl, etc.
• 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.
• Web services and APIs use JSON format to provide public data.
Characteristics of JSON
After understanding the above program, we will try another example. Let's save the below code
as json.htm:
Reading and Writing XML Files in Python
import xml.dom.minidom
def main():
# use the parse() function to load and parse an XML file
doc = xml.dom.minidom.parse("Myxml.xml");
# print out the document node and the name of the first child tag
print doc.nodeName
print doc.firstChild.tagName
# get a list of XML tags from the document and print each one
expertise = doc.getElementsByTagName("expertise")
print "%d expertise:" % expertise.length
for skill in expertise:
print skill.getAttribute("name")
# create a new XML tag and add it into the document
newexpertise = doc.createElement("expertise")
newexpertise.setAttribute("name", "BigData")
doc.firstChild.appendChild(newexpertise)
print " "
expertise = doc.getElementsByTagName("expertise")
print "%d expertise:" % expertise.length
for skill in expertise:
print skill.getAttribute("name")
if name == "__main__":
main();
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.