Unit 3
Introduction to Python
-GVNSK Sravya
5/10/2022
Unit 3
1
Outline
• Language features of Python,
• Data types, Data structures,
• Control of flow,
• Functions,
• Modules,
• Packaging,
• File handling,
• Data/time operations,
• Classes,
• Exception handling Python packages - JSON, XML, HTTPLib,
URLLib, SMTPLib.
Unit 3
5/10/2022 2
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.
Unit 3
5/10/2022 3
Characteristics of Python
• The main characteristics of Python are
Multi-paradigm programming language
• Python supports more than one programming paradigms including
object-oriented programming and structured programming
Unit 3
5/10/2022 4
Characteristics of Python
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.
Unit 3
5/10/2022 5
Characteristics of Python
Interactive Language
• Python provides an interactive mode in which the user can submit
commands at the Python prompt and interact with the interpreter
directly.
Unit 3
5/10/2022 6
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.
Unit 3
5/10/2022 7
Python - Benefits
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.
Unit 3
5/10/2022 8
Python - Benefits
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.
Unit 3
5/10/2022 9
Python - Benefits
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
Unit 3
5/10/2022 10
Python - Benefits
Broad Library Support
• Python has a broad library support and works on various platforms such
as Windows, Linux, Mac, etc.
Unit 3
5/10/2022 11
Python Data Types and Data Structures
Data Types
• Every value in Python has a data type.
• Since everything is an object in Python programming, data types are actually
classes and variables are instance (object) of these classes.
Unit 3
5/10/2022 12
Python Data Types and Data Structures
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.
Unit 3
5/10/2022 13
Python Data Types and Data Structures
Unit 3
5/10/2022 14
Python Data Types and Data Structures
Unit 3
5/10/2022 15
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.
Unit 3
5/10/2022 16
Strings
Unit 3
5/10/2022 17
Strings
Unit 3
5/10/2022 18
Strings
# formatting output
>>>print “ The string (%s) has %d characters” % (s, len(s))
The string (Hello World!) has 12 characters
Unit 3
5/10/2022 19
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.
5/10/2022 20
Lists
5/10/2022 21
Lists
5/10/2022 22
Lists
5/10/2022 23
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.
Unit 3
5/10/2022 24
Tuples
Unit 3
5/10/2022 25
Tuples
Unit 3
5/10/2022 26
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.
Unit 3
5/10/2022 27
Dictionaries
Unit 3
5/10/2022 28
Dictionaries
Unit 3
5/10/2022 29
Dictionaries
Unit 3
5/10/2022 30
Type Conversions
Unit 3
Type conversion examples
5/10/2022 31
Type Conversions
Unit 3
Type conversion examples
5/10/2022 32
Control Flow – if statement
• The if statement in Python is similar to the if statement in other languages.
Unit 3
5/10/2022 33
Control Flow – if statement
Unit 3
5/10/2022 34
Control Flow – if statement
Unit 3
5/10/2022 35
Control Flow – if statement
Unit 3
5/10/2022 36
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.
Unit 3
5/10/2022 37
Control Flow – for statement
Unit 3
5/10/2022 38
Control Flow – for statement
Unit 3
5/10/2022 39
Control Flow – for statement
Unit 3
5/10/2022 40
Control Flow – while statement
• The while statement in Python executes the statements within the while
loop as long as the while condition is true.
Unit 3
5/10/2022 41
Control Flow – while statement
Unit 3
5/10/2022 42
Control Flow – range statement
• The range statement in Python generates a list of numbers in arithmetic
progression.
Unit 3
5/10/2022 43
Control Flow – range statement
• The range statement in Python generates a list of numbers in arithmetic
progression.
Unit 3
5/10/2022 44
Control Flow – range statement
Unit 3
5/10/2022 45
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
Unit 3
5/10/2022 46
Control Flow – break/continue statements
Continue
• Continue statement
continues with the next iteration
Unit 3
5/10/2022 47
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.
Unit 3
5/10/2022 48
Control Flow – pass statement
Unit 3
5/10/2022 49
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.
Unit 3
5/10/2022 50
Functions
• 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.
Unit 3
5/10/2022 51
Functions
Unit 3
5/10/2022 52
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
Unit 3
5/10/2022 53
Functions - Default Arguments
Unit 3
5/10/2022 54
Functions - Passing by Reference
• All parameters in the Python functions are passed by reference.
• If a parameter is changed within a function the change also reflected back in
the calling function.
Unit 3
5/10/2022 55
Functions - Passing by Reference
Unit 3
5/10/2022 56
Functions - Keyword Arguments
• Functions can also be called using keyword arguments that identifies the
arguments by the parameter name when the function is called.
Unit 3
5/10/2022 57
Functions - Keyword Arguments
Unit 3
5/10/2022 58
Functions - Keyword Arguments
Unit 3
5/10/2022 59
Functions - Variable Length Arguments
• Python functions can have variable length arguments.
• The variable length arguments are passed to as a tuple to the function with
an argument prefixed with asterix (*)
Unit 3
5/10/2022 60
Functions - Variable Length Arguments
Unit 3
5/10/2022 61
Modules
• Python allows organizing the program code into different modules which
improves the code readability and management.
• A module is a Python file that defines 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.
5/10/2022 62
Modules
5/10/2022 63
Modules
5/10/2022 64
Modules
5/10/2022 65
Modules
5/10/2022 66
Modules
5/10/2022 67
>>>avg = student. averageGrade(students)
>>>print "The average garde is: %0.2f" % (avg) 3.62
Packages
• Python package is hierarchical file structure that consists of
modules and subpackages.
• Packages allow better organization of modules related to a
single application environment.
Unit 3
5/10/2022 68
Packages
Unit 3
5/10/2022 69
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 and write
(r+ or w+), read-binary (rb), write-binary (wb), etc.
• After the file contents have been read the close function is called
which closes the file object.
Unit 3
5/10/2022 70
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()
Unit 3
# Example of reading a certain number of bytes
>>>fp = open('file.txt','r')
>>>fp.read(1
0) 'Python
sup'
>>>fp.close()
# Example of getting the current position of read
>>>fp = open('file.txt','r')
>>>fp.read(1
0) '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()
5/10/2022 71
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.
Unit 3
5/10/2022 72
Date/Time Operations
Unit 3
5/10/2022 73
Date/Time Operations
Unit 3
5/10/2022 74
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.
Unit 3
5/10/2022 75
Classes
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.
Unit 3
5/10/2022 76
Classes
Function overloading
• Function overloading is a form of polymorphism that allows a
function to have different meanings, depending on its
context.
Unit 3
5/10/2022 77
Classes
Operator overloading
• Operator overloading is a form of polymorphism that allows
assignment of more than one function to a particular
operator.
Unit 3
5/10/2022 78
Classes
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.
Unit 3
5/10/2022 79
Classes
Function overloading
• Function overloading is a form of polymorphism that allows a
function to have different meanings, depending on its
context.
Unit 3
5/10/2022 80
Classes
Operator overloading
• Operator overloading is a form of polymorphism that allows
assignment of more than one function to a particular
operator.
Unit 3
5/10/2022 81
Classes
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.
Unit 3
5/10/2022 82
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 specific to each instance of the class.
Unit 3
5/10/2022 83
Class Example
• 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
Unit 3
5/10/2022 84
Class Example
Unit 3
5/10/2022 85
Class Example
Unit 3
5/10/2022 86
Class Inheritance
• In this example Shape is the base class and Circle is the derived
class. The class Circle inherits the attributes of the Shape class.
• The child class Circle overrides the methods and attributes of the
base class (eg. draw() function defined in the base class Shape is
overridden in child class Circle).
Unit 3
5/10/2022 87
Class Inheritance
Unit 3
5/10/2022 88
Class Inheritance
Unit 3
5/10/2022 89
Class Inheritance
Unit 3
5/10/2022 90
Class Inheritance
Unit 3
5/10/2022 91
Exception Handling Python Packages
Python Packages of Interest for IoT
❖ JSON
❖ XML
❖ HTTPLib & URLLib
❖ SMTPLib
Unit 3
5/10/2022 92
Exception Handling Python Packages
JSON(Java Script Object Notation)
• Easy to read and write data – interchange format
• JSON is used as an alternative to XML
• Easy for machines to parse and generate
Unit 3
5/10/2022 93
Exception Handling Python Packages
• JSON is built on two structures
i) Collection of name – value pairs ( Dictionaries in Python)
ii) Ordered list of values (List in Python)
• JSON format is used for serializing and transmitting structured
data over a N/W connection
• Example, transmitting data b/w server and web application.
Unit 3
5/10/2022 94
JSON
Unit 3
5/10/2022 95
JSON
Unit 3
5/10/2022 96
JSON
Unit 3
5/10/2022 97
JSON
• Exchange of information
encoded as JSON involves
encoding and decoding steps.
• The python JSON package
provides functions for
encoding and decoding JSON
Unit 3
5/10/2022 98
JSON
Unit 3
5/10/2022 99
XML (Extensible Markup Language)
• XML is a data format for structured document interchange.
• The python minidom library provides a minimal implementation
of the document object model interface and has an API similar
to that in other languages
Unit 3
5/10/2022 100
Example of an XML file
Unit 3
5/10/2022 101
Python Program for Parsing an XML file
Unit 3
5/10/2022 102
Python Program for Creating an XML file
Unit 3
5/10/2022 103
Python Program for Creating an XML file
Unit 3
5/10/2022 104
Python Program for Parsing an XML file
Unit 3
5/10/2022 105
HTTPLib & URLLib
• HTTPLib2 & URLLib2 are python libraries used in network/internet
programming.
• HTTPLib2 is an HTTP client library and URLLib2 is a library for
fetching URLs.
• Example of an HTTP GET request using HTTPLib is shown in box
6.40.
• The variable resp contains the response headers and content contains
the content retrieved from the URL
Unit 3
5/10/2022 106
HTTPLib & URLLib
Unit 3
5/10/2022 107
HTTPLib & URLLib
• Box 6.41 shows an HTTP request example using URLLib2.
• A request object is created by calling URLLib2.
• Request with the URL to fetch as input parameter.
• Then URLLib2 urlopen is called with the request object which returns
the response object for the request URL.
• The response object is read by calling read function.
Unit 3
5/10/2022 108
HTTPLib & URLLib
Unit 3
5/10/2022 109
HTTPLib & URLLib
• Box 6.42 shows an example of an HTTP POST request.
• The data in the POST body is encoded using the urlencode
function from urllib.
Unit 3
5/10/2022 110
HTTPLib & URLLib
Unit 3
5/10/2022 111
HTTPLib & URLLib
• Box 6.43 shows an example of sending data to a URL using
URLLib2 (e.g an HTML form submission).
• This example is similar to the HTTP POST example in box 6.42
and uses URLLib2 request object instead of HTTPLib2.
Unit 3
5/10/2022 112
HTTPLib & URLLib
Unit 3
5/10/2022 113
SMTPLib
• Simple Mail Transfer Protocol is a protocol which handles sending
email and routing email between mail servers.
• The python SMTPLib module provides an SMTP client session
object that can be used to send email.
• Box 6.44 shows a python example of sending email from a Gmail
account.
• The string message contains the email message to be sent.
Unit 3
5/10/2022 114
SMTPLib
• To send email from a Gmail account the Gmail SMTP server is
specified in the server string.
• To send an email, first a connection is established with the SMTP
server by calling smtplib.SMTP with the SMTP server name and
port.
• The username and password provided are then used to login into
the server.
Unit 3
5/10/2022 115
SMTPLib
• The email is then sent by calling server.sendmail function with the
from address, to address list and message as input parameters.
Unit 3
5/10/2022 116
SMTPLib
Unit 3
5/10/2022 117

Python.pdf

  • 1.
    Unit 3 Introduction toPython -GVNSK Sravya 5/10/2022 Unit 3 1
  • 2.
    Outline • Language featuresof Python, • Data types, Data structures, • Control of flow, • Functions, • Modules, • Packaging, • File handling, • Data/time operations, • Classes, • Exception handling Python packages - JSON, XML, HTTPLib, URLLib, SMTPLib. Unit 3 5/10/2022 2
  • 3.
    Python • Python isa general-purpose high level programming language and suitable for providing a solid foundation to the reader in the area of cloud computing. Unit 3 5/10/2022 3
  • 4.
    Characteristics of Python •The main characteristics of Python are Multi-paradigm programming language • Python supports more than one programming paradigms including object-oriented programming and structured programming Unit 3 5/10/2022 4
  • 5.
    Characteristics of Python InterpretedLanguage • 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. Unit 3 5/10/2022 5
  • 6.
    Characteristics of Python InteractiveLanguage • Python provides an interactive mode in which the user can submit commands at the Python prompt and interact with the interpreter directly. Unit 3 5/10/2022 6
  • 7.
    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. Unit 3 5/10/2022 7
  • 8.
    Python - Benefits Objectand 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. Unit 3 5/10/2022 8
  • 9.
    Python - Benefits 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. Unit 3 5/10/2022 9
  • 10.
    Python - Benefits 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 Unit 3 5/10/2022 10
  • 11.
    Python - Benefits BroadLibrary Support • Python has a broad library support and works on various platforms such as Windows, Linux, Mac, etc. Unit 3 5/10/2022 11
  • 12.
    Python Data Typesand Data Structures Data Types • Every value in Python has a data type. • Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes. Unit 3 5/10/2022 12
  • 13.
    Python Data Typesand Data Structures 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. Unit 3 5/10/2022 13
  • 14.
    Python Data Typesand Data Structures Unit 3 5/10/2022 14
  • 15.
    Python Data Typesand Data Structures Unit 3 5/10/2022 15
  • 16.
    Strings Strings • A stringis simply a list of characters in order. • There are no limits to the number of characters you can have in a string. Unit 3 5/10/2022 16
  • 17.
  • 18.
  • 19.
    Strings # formatting output >>>print“ The string (%s) has %d characters” % (s, len(s)) The string (Hello World!) has 12 characters Unit 3 5/10/2022 19
  • 20.
    Lists Lists • List acompound 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. 5/10/2022 20
  • 21.
  • 22.
  • 23.
  • 24.
    Tuples Tuples • A tupleis 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. Unit 3 5/10/2022 24
  • 25.
  • 26.
  • 27.
    Dictionaries Dictionaries • Dictionary isa 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. Unit 3 5/10/2022 27
  • 28.
  • 29.
  • 30.
  • 31.
    Type Conversions Unit 3 Typeconversion examples 5/10/2022 31
  • 32.
    Type Conversions Unit 3 Typeconversion examples 5/10/2022 32
  • 33.
    Control Flow –if statement • The if statement in Python is similar to the if statement in other languages. Unit 3 5/10/2022 33
  • 34.
    Control Flow –if statement Unit 3 5/10/2022 34
  • 35.
    Control Flow –if statement Unit 3 5/10/2022 35
  • 36.
    Control Flow –if statement Unit 3 5/10/2022 36
  • 37.
    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. Unit 3 5/10/2022 37
  • 38.
    Control Flow –for statement Unit 3 5/10/2022 38
  • 39.
    Control Flow –for statement Unit 3 5/10/2022 39
  • 40.
    Control Flow –for statement Unit 3 5/10/2022 40
  • 41.
    Control Flow –while statement • The while statement in Python executes the statements within the while loop as long as the while condition is true. Unit 3 5/10/2022 41
  • 42.
    Control Flow –while statement Unit 3 5/10/2022 42
  • 43.
    Control Flow –range statement • The range statement in Python generates a list of numbers in arithmetic progression. Unit 3 5/10/2022 43
  • 44.
    Control Flow –range statement • The range statement in Python generates a list of numbers in arithmetic progression. Unit 3 5/10/2022 44
  • 45.
    Control Flow –range statement Unit 3 5/10/2022 45
  • 46.
    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 Unit 3 5/10/2022 46
  • 47.
    Control Flow –break/continue statements Continue • Continue statement continues with the next iteration Unit 3 5/10/2022 47
  • 48.
    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. Unit 3 5/10/2022 48
  • 49.
    Control Flow –pass statement Unit 3 5/10/2022 49
  • 50.
    Functions • A functionis 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. Unit 3 5/10/2022 50
  • 51.
    Functions • The codeblock 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. Unit 3 5/10/2022 51
  • 52.
  • 53.
    Functions - DefaultArguments • 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 Unit 3 5/10/2022 53
  • 54.
    Functions - DefaultArguments Unit 3 5/10/2022 54
  • 55.
    Functions - Passingby Reference • All parameters in the Python functions are passed by reference. • If a parameter is changed within a function the change also reflected back in the calling function. Unit 3 5/10/2022 55
  • 56.
    Functions - Passingby Reference Unit 3 5/10/2022 56
  • 57.
    Functions - KeywordArguments • Functions can also be called using keyword arguments that identifies the arguments by the parameter name when the function is called. Unit 3 5/10/2022 57
  • 58.
    Functions - KeywordArguments Unit 3 5/10/2022 58
  • 59.
    Functions - KeywordArguments Unit 3 5/10/2022 59
  • 60.
    Functions - VariableLength Arguments • Python functions can have variable length arguments. • The variable length arguments are passed to as a tuple to the function with an argument prefixed with asterix (*) Unit 3 5/10/2022 60
  • 61.
    Functions - VariableLength Arguments Unit 3 5/10/2022 61
  • 62.
    Modules • Python allowsorganizing the program code into different modules which improves the code readability and management. • A module is a Python file that defines 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. 5/10/2022 62
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
    Modules 5/10/2022 67 >>>avg =student. averageGrade(students) >>>print "The average garde is: %0.2f" % (avg) 3.62
  • 68.
    Packages • Python packageis hierarchical file structure that consists of modules and subpackages. • Packages allow better organization of modules related to a single application environment. Unit 3 5/10/2022 68
  • 69.
  • 70.
    File Handling • Pythonallows 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 and write (r+ or w+), read-binary (rb), write-binary (wb), etc. • After the file contents have been read the close function is called which closes the file object. Unit 3 5/10/2022 70
  • 71.
    File Handling # Exampleof seeking to a certain position >>>fp = open('file.txt','r') >>>fp.seek(10,0) >>>content = fp.read(10) >>>print content ports more >>>fp.close() Unit 3 # Example of reading a certain number of bytes >>>fp = open('file.txt','r') >>>fp.read(1 0) 'Python sup' >>>fp.close() # Example of getting the current position of read >>>fp = open('file.txt','r') >>>fp.read(1 0) '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() 5/10/2022 71
  • 72.
    Date/Time Operations • Pythonprovides 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. Unit 3 5/10/2022 72
  • 73.
  • 74.
  • 75.
    Classes • Python isan 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. Unit 3 5/10/2022 75
  • 76.
    Classes Class • A classis 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. Unit 3 5/10/2022 76
  • 77.
    Classes Function overloading • Functionoverloading is a form of polymorphism that allows a function to have different meanings, depending on its context. Unit 3 5/10/2022 77
  • 78.
    Classes Operator overloading • Operatoroverloading is a form of polymorphism that allows assignment of more than one function to a particular operator. Unit 3 5/10/2022 78
  • 79.
    Classes Function overriding • Functionoverriding 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. Unit 3 5/10/2022 79
  • 80.
    Classes Function overloading • Functionoverloading is a form of polymorphism that allows a function to have different meanings, depending on its context. Unit 3 5/10/2022 80
  • 81.
    Classes Operator overloading • Operatoroverloading is a form of polymorphism that allows assignment of more than one function to a particular operator. Unit 3 5/10/2022 81
  • 82.
    Classes Function overriding • Functionoverriding 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. Unit 3 5/10/2022 82
  • 83.
    Class Example • Thevariable 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. Unit 3 5/10/2022 83
  • 84.
    Class Example • Thereis 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 Unit 3 5/10/2022 84
  • 85.
  • 86.
  • 87.
    Class Inheritance • Inthis example Shape is the base class and Circle is the derived class. The class Circle inherits the attributes of the Shape class. • The child class Circle overrides the methods and attributes of the base class (eg. draw() function defined in the base class Shape is overridden in child class Circle). Unit 3 5/10/2022 87
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
    Exception Handling PythonPackages Python Packages of Interest for IoT ❖ JSON ❖ XML ❖ HTTPLib & URLLib ❖ SMTPLib Unit 3 5/10/2022 92
  • 93.
    Exception Handling PythonPackages JSON(Java Script Object Notation) • Easy to read and write data – interchange format • JSON is used as an alternative to XML • Easy for machines to parse and generate Unit 3 5/10/2022 93
  • 94.
    Exception Handling PythonPackages • JSON is built on two structures i) Collection of name – value pairs ( Dictionaries in Python) ii) Ordered list of values (List in Python) • JSON format is used for serializing and transmitting structured data over a N/W connection • Example, transmitting data b/w server and web application. Unit 3 5/10/2022 94
  • 95.
  • 96.
  • 97.
  • 98.
    JSON • Exchange ofinformation encoded as JSON involves encoding and decoding steps. • The python JSON package provides functions for encoding and decoding JSON Unit 3 5/10/2022 98
  • 99.
  • 100.
    XML (Extensible MarkupLanguage) • XML is a data format for structured document interchange. • The python minidom library provides a minimal implementation of the document object model interface and has an API similar to that in other languages Unit 3 5/10/2022 100
  • 101.
    Example of anXML file Unit 3 5/10/2022 101
  • 102.
    Python Program forParsing an XML file Unit 3 5/10/2022 102
  • 103.
    Python Program forCreating an XML file Unit 3 5/10/2022 103
  • 104.
    Python Program forCreating an XML file Unit 3 5/10/2022 104
  • 105.
    Python Program forParsing an XML file Unit 3 5/10/2022 105
  • 106.
    HTTPLib & URLLib •HTTPLib2 & URLLib2 are python libraries used in network/internet programming. • HTTPLib2 is an HTTP client library and URLLib2 is a library for fetching URLs. • Example of an HTTP GET request using HTTPLib is shown in box 6.40. • The variable resp contains the response headers and content contains the content retrieved from the URL Unit 3 5/10/2022 106
  • 107.
    HTTPLib & URLLib Unit3 5/10/2022 107
  • 108.
    HTTPLib & URLLib •Box 6.41 shows an HTTP request example using URLLib2. • A request object is created by calling URLLib2. • Request with the URL to fetch as input parameter. • Then URLLib2 urlopen is called with the request object which returns the response object for the request URL. • The response object is read by calling read function. Unit 3 5/10/2022 108
  • 109.
    HTTPLib & URLLib Unit3 5/10/2022 109
  • 110.
    HTTPLib & URLLib •Box 6.42 shows an example of an HTTP POST request. • The data in the POST body is encoded using the urlencode function from urllib. Unit 3 5/10/2022 110
  • 111.
    HTTPLib & URLLib Unit3 5/10/2022 111
  • 112.
    HTTPLib & URLLib •Box 6.43 shows an example of sending data to a URL using URLLib2 (e.g an HTML form submission). • This example is similar to the HTTP POST example in box 6.42 and uses URLLib2 request object instead of HTTPLib2. Unit 3 5/10/2022 112
  • 113.
    HTTPLib & URLLib Unit3 5/10/2022 113
  • 114.
    SMTPLib • Simple MailTransfer Protocol is a protocol which handles sending email and routing email between mail servers. • The python SMTPLib module provides an SMTP client session object that can be used to send email. • Box 6.44 shows a python example of sending email from a Gmail account. • The string message contains the email message to be sent. Unit 3 5/10/2022 114
  • 115.
    SMTPLib • To sendemail from a Gmail account the Gmail SMTP server is specified in the server string. • To send an email, first a connection is established with the SMTP server by calling smtplib.SMTP with the SMTP server name and port. • The username and password provided are then used to login into the server. Unit 3 5/10/2022 115
  • 116.
    SMTPLib • The emailis then sent by calling server.sendmail function with the from address, to address list and message as input parameters. Unit 3 5/10/2022 116
  • 117.