Unit-Ii-Introduction To Python

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

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 is a high-level general-purpose programming language that is used in a wide variety of


application domains. Python has the right combination of performance and features that
demystify program writing. Some of the features of Python are listed below:

 It is simple and easy to learn.


 Python implementation is under an open-source license that makes it freely usable and
distributable, even for commercial use.
 It works on many platforms such as Windows, Linux, etc.
 It is an interpreted language.
 It is an object-oriented language.
 Embeddable within applications as a scripting interface.
Python has a comprehensive set of packages to accomplish various tasks. Python is an
interpreted language, as opposed to a compiled one, though the distinction is blurry because of
the presence of the bytecode compiler (beyond the scope of this book). Python source code is
compiled into bytecode so that executing the same file is faster the second time (recompilation
from source to bytecode can be avoided). Interpreted languages typically have a shorter
development/debug cycle than compiled ones, and also their programs generally also run slowly.
Please note that Python uses a 7-bit ASCII character set for program text.
The latest stable releases can always be found on Python‟s website (http://www.python.org/).
There are two recommended production-ready Python versions at this point in time because at
the moment there are two branches of stable releases: 2.x and 3.x. Python 3.x may be less useful
than 2.x since currently there is more third-party software available for Python 2 than for Python
3. Python 2 code will generally not run unchanged in Python 3. This book focuses on Python
version 2.7.6.

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.

Python is a general-purpose high level programming language


The main characteristics of Python are:
 Multi-paradigm programming language: Supports more than one Programming including
object-oriented programming and Structured programming.
 Interpreted Language: It does not require an explicit compilation step.Phyton Interpreter
executes the program source code directly
 Interactive Language: It provides an interactive mode in which user can submit the
commands
 Easy to Learn, read and maintain
 Supports both object and procedure oriented programming. procedure oriented
programming allows programs to be written around procedures or functions that allow
reuse of code.
 Extendable: It is an extendable language that allows integration of low level modules
written in C/C++
 Portable: Python programs can be copied from one machine to another without worrying
about portability.
Introduction to Python – Integrated Development Environment

Introduction to Python – Integrated development environment

An Integrated Development Environment (IDE) is an application that provides comprehensive


facilities for software development. An IDE normally consists of a source code editor, compiler
and/or interpreter, and a debugger.

Introduction to Python – IDLE

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:

 Coded in Python, using the Tkinter GUI toolkit.


 Cross-platform i.e. works on Windows and Unix.
 Has source code editor with multiple undo, text highlighting, smart indent, call tips, and
many other features (shown in figure 1-2).
 Has Python shell window, also known as “interactive interpreter”
Basics of Python – Variable, Identifier and Literal

Variable, identifier, and literal


A variable is a storage location that has an associated symbolic name (called “identifier”), which contains
some value (can be literal or other data) that can change. An identifier is a name used to identify a
variable, function, class, module, or another object. Literal is a notation for constant values of some built-
in type. Literal can be string, plain integer, long integer, floating-point number, imaginary number. For
e.g., in the expressions

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.

Basics of Python – String

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.

Types of Data Structures in Python


Python has implicit support for Data Structures which enable you to store and access data. These
structures are called List, Dictionary, Tuple and Set.

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

Python Programming – Set


A set is an unordered collection with no duplicate elements. Basic uses include membership
testing, eliminating duplicate entries from sequence, mathematical operations like union,
intersection, difference, symmetric difference etc. As mentioned in chapter 2, sets are of two
types: set (mutable set) and frozenset (immutable set).
>>> a=set ( [ ‟ spam ‟ , ' eggs ' , 100 , 1234 ] )
>>> a
set ( [ ' eggs ' , 100 , 1234 , ' spam ' ] )
>>> a=set ( ' abracadabra ' )
>>> a
set ( [ ' a ' , ' r ' , ' b ' , ' c ' , ' d ' ] )
>>> a-frozenset ( [ ' spain ' , ' eggs ' , 100 , 1234 ] )
>>> a
frozenset ( [ ' eggs ' , 100 , 1234 , ' spam ' ] )
Using curly braces
Non-empty set (not frozenset) can be created by placing a comma-separated list of elements
within braces. Curly braces cannot be used to create an empty set, because it will create an empty
dictionary that will be discussed in the next section.
>>> { ' spam ' , ' eggs ' , 100 , 1234 }
set ( [ 1234 , 100 , ' eggs ' , ' spam ' ] )

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.

The if…elif…else statement is used in Python for decision making.

Python if Statement Syntax


if test expression: statement(s)

Here, the program evaluates the test expression and will execute statement(s) only if the text
expression is True.
If the text expression is False, the statement(s) is not executed. In Python, the body of the
if statement is indicated by the indentation. Body starts with an indentation and the first
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

Python for Loop


The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable
objects. Iterating over a sequence is called traversal.
Syntax of for Loop for val in sequence:
Body of for
Here, val is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated
from the rest of the code using indentation.
Flowchart of for Loop

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

# iterate over the list for val in numbers:


sum = sum+val # Output: The sum is 48 print("The sum is", sum)

When you run the program, the output will be:


The sum is 48

The range() function


We can generate a sequence of numbers using range() function. range(10) will generate numbers
from 0 to 9 (10 numbers). We can also define the start, stop and step size as range(start,stop,step
size). step size defaults to 1 if not provided. This function does not store all the values in emory,
it would be inefficient. So it remembers the start, stop, step size and generates the next number
on thego.
To force this function to output all the items, we can use the function list(). The following
example will clarify this.
# Output: range(0, 10) print (range(10))
# Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print (list(range(10)))

# 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])

When you run the program, the output will be:


I like pop I like rock I like jazz

Python Programming – Dictionary


Another useful mutable built-in type is “dictionary”. A dictionary is an unordered group of
comma-separated “key: value” pairs enclosed within braces, with the requirement that the keys
are unique within a dictionary. The main operation of a dictionary is storing a value
corresponding to a given key and extracting the value for that given key. Unlike sequences,
which are indexed by a range of numbers, the dictionary is indexed by key (key should be of an
immutable type, strings and numbers can always be keys).

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

def fib ( n ) : # write Fibonacci series up to n


a , b=0 , 1
while b<n :
print b ,
a, b=b , a+b

def fib2 ( n ) : # return Fibonacci series up to n


result= [ ]
a,b=0,1
while b<n:
result . append ( b )
a , b=b , a+b
return result

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.

Syntax : def function name(Function parameters)


statements……….

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

Create a Child Class


To create a class that inherits the functionality from another class, send the parent class as a
parameter when creating the child class:

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 JSON format was originally specified by Douglas Crockford,.

 The official Internet media type for JSON is application/json. The JSON filename extension
is .json.

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

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

Characteristics of JSON

• JSON is easy to read and write.

• It is a lightweight text-based interchange format.

• JSON is language independent.

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

 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":
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.

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy