Python programming concepts for the Internet of things applications development. This PPT contains details about classes, list , tuples, dictionaries, packages like HTTPLib,SMTPLib, etc
2. Contents
• Language Features of Python
• Data Types
• Data Structures
• Control of Flow
• Functions
• Modules
• Packaging
• File Handling
• Date/Time Operations
• Classes
• Exception Handling
• Python Packages – HTTPLib,URLLib,SMTPLib
1/7/2021 Python for IoT 2
3. Python Conquers the Universe
• Most widely used high level programming language across the world
1/7/2021 Python for IoT 3
4. Introduction
• Python is a general-purpose interpreted,
interactive, object-oriented and high-level
programming language
• It was created by Guido van Rossum during 1985-
1990
• Like Perl, Python source code is also available
under the GNU General Public License (GPL)
• Extension of python program is .py
• Applications:
– Develop simple text processing to www applications,
even games.
1/7/2021 Python for IoT 4
7. Features
• Easy to learn
• Easy to read
• Easy to maintain
• Broad standard library
• Interactive
• Portable (Many hardware platforms)
• Extendable
• Databases
• GUI programming
• Scalable
1/7/2021 Python for IoT 7
8. Modes of Programming
• Interactive Mode Programming
– Invoking the interpreter without passing a script
file as a parameter
• Script Mode Programming
– Invoking the interpreter with a script parameter
begins execution of the script and continues until
the script is finished
1/7/2021 Python for IoT 8
10. Programming Rules
• Quotation
– accepts single (') and double (") quotes to denote string literals
– Example:
• word = 'word‘
• sentence = "This is a sentence."
• Comments
– A hash sign (#) that is not inside a string literal begins a
comment
– Example:
• # First comment
• Multiple Statements on a Single Line
– semicolon ( ; ) allows multiple statements on the single line
1/7/2021 Python for IoT 10
11. Lines and Indentation
• Python provides no braces to indicate blocks
of code for class and function definitions or
flow control
• Example:
1/7/2021 Python for IoT 11
13. Python Identifiers
• Identifier is a name used to identify a variable,
function, class, module or other object
• Case sensitive programming language
• Naming conventions:
– Class names start with an uppercase letter
– All other identifiers start with a lowercase letter
– Starting an identifier with a single leading
underscore indicates that the identifier is private
1/7/2021 Python for IoT 13
16. Variables
• Variables are nothing but reserved memory
locations to store values
• Assigning Values to Variables
– Variables do not need explicit declaration to
reserve memory space
– The declaration happens automatically when you
assign a value to a variable
– The equal sign (=) is used to assign values to
variables.
1/7/2021 Python for IoT 16
17. Multiple Assignment
• Python allows you to assign a single value to
several variables simultaneously
– a = b = c = 1
– a, b, c = 1, 2, "john"
1/7/2021 Python for IoT 17
18. Input Methods
• Two Methods:
– raw_input function:
Syntax:
varname=raw_input(“Prompt”);
– input function:
Syntax:
varname=input(“Prompt”);
– Example:
a=int(raw_input('Enter number 1'))
b=int(raw_input('Enter number 2'))
c=a+b
print "sum=",c
1/7/2021 Python for IoT 18
19. Output statements
• print function:
Syntax:
print(“Message”) // used in python 3.4
print “Message” // used in python 2.7
• Example:
print ("Hello World“)
a=10
print ("The Value of a=",a)
b=20.5
print ("The Value of b = %d" %b)
print ("The Value of b = %f" %b)
print ("The Value of b = %g" %b)
print ("The Value of b = %3.2f" %b)
1/7/2021 Python for IoT 19
22. Contents
• Language Features of Python
• Data Types
• Data Structures
• Control of Flow
• Functions
• Modules
• Packaging
• File Handling
• Date/Time Operations
• Classes
• Exception Handling
• Python Packages – HTTPLib,URLLib,SMTPLib
1/7/2021 Python for IoT 22
23. Standard Data Types
• Numbers
• String
• List
• Tuple
• Dictionary
1/7/2021 Python for IoT 23
24. Numbers
• Number data types store numeric values
• Python supports four different numerical
types −
– int (signed integers)
– long (long integers, they can also be represented
in octal and hexadecimal)
– float (floating point real values)
– complex (complex numbers)
1/7/2021 Python for IoT 24
25. Strings
• Contiguous set of characters represented in
the quotation marks
• Subsets of strings can be taken using the slice
operator ([ ] and [:] )
• Indexing and Slicing ([ ] and [:] )
• The plus (+) sign is the string concatenation
operator and the asterisk (*) is the repetition
operator
1/7/2021 Python for IoT 25
27. Lists
• Compound data type
• A list contains items separated by commas
and enclosed within square brackets
• Lists are similar to arrays in C.
• Difference - a list can be of different data type
• Accessed using the slice operator ([ ] and [:])
with indexes
• (+) sign is the list concatenation operator, (*) is
the repetition operator
1/7/2021 Python for IoT 27
29. Tuples
• A tuple is another sequence data type that is
similar to the list
• A tuple consists of a number of values
separated by commas
• Unlike lists, however, tuples are enclosed
within parentheses
• Tuples can be thought of as read-only lists
1/7/2021 Python for IoT 29
33. Dictionary
• Hash table type
• Work like associative arrays or hashes - consist
of key-value pairs.
• Key - any Python type, but are usually
numbers or strings
• Enclosed by curly braces ({ }) and values can
be assigned and accessed using square braces
([])
1/7/2021 Python for IoT 33
42. Membership Operators
• Python’s membership operators test for
membership in a sequence, such as strings,
lists, or tuples
1/7/2021 Python for IoT 42
51. If Statement
• Syntax of If Statement
– if (test_expression):
Statement 1
..........
Statement n
Statement x
• Example:
x = 10
if(x>0):
x= x+1
Print(x)
1/7/2021 Python for IoT 51
52. If – Else Statement
• Syntax of If-else Statement
– if (test_expression):
Statement Block 1
else:
Statement Block 2
Statement x
• Example:
age = 19
if(age>=18):
print(“You are Eligible to vote”)
else:
print(“Not Eligible”)
1/7/2021 Python for IoT 52
53. Nested if Statement
• To perform more complex checks if statement can be nested.
• If statements can be nested resulting in multi-way selection.
• Example:
avg = 50
If (avg<=100 and avg>90):
print(“Grade S”)
If (avg<=90 and avg>80):
print(“Grade A”)
If (avg<=80 and avg>70):
print(“Grade B”)
If (avg<=70 and avg>60):
print(“Grade C”)
If (avg<=60 and avg>50):
print(“Grade D”)
If (avg<=50):
print(“Grade E”)
Else:
print(“Grade RA”)
1/7/2021 Python for IoT 53
54. If-elif-else Statement
• Python does not have switch statement. You can use an if...elif...else
statement to do the same thing.
• Elif is an short for else if.
• Syntax of If-elif-else Statement
– if (test_expression 1):
Statement Block 1
elif (test_expression 2):
Statement Block 2
.........................
elif (test_expression n):
Statement Block n
Else:
Statement Block x
Statement y
1/7/2021 Python for IoT 54
55. Loops
• A loop statement allows us to execute a
statement or group of statements multiple
times
• Examples:
– While
– for
– nested loops
1/7/2021 Python for IoT 55
57. Using else Statement with Loops
• Supports else statement associated with a
loop.
• Example:
1/7/2021 Python for IoT 57
58. for Loop
• Syntax:
for iterating_var in sequence:
statements(s)
• Example:
1/7/2021 Python for IoT 58
Output:
59. The range() function
• Syntax for range () function
– range(start, stop, step)
• Example 1:
– For i in range(10):
print(i, end=“,”)
– Output: 0,1,2,3,4,5,6,7,8,9,
• Example 2:
– For i in range(1,5):
print(i, end=“,”)
– Output: 1,2,3,4,
• Example 3:
– For i in range(1,10,2):
print(i, end=“,”)
– Output: 1,3,5,7,9,
1/7/2021 Python for IoT 59
64. Functions
• A function is a block of organized and reusable code
• Modularity
• Types:
– Built-in functions
– User defined functions
• Rules:
– first statement of a function can be an optional statement -
the documentation string of the function or docstring.
– statement return [expression] exits a function, optionally
passing back an expression to the caller. A return
statement with no arguments is the same as return None
1/7/2021 Python for IoT 64
66. Calling a Function
• All parameters (arguments) in the Python
language are passed by reference.
• It means if you change what a parameter
refers to within a function, the change also
reflects back in the calling function.
1/7/2021 Python for IoT 66
67. Function Arguments
• Call a function by using the following types of
formal arguments:
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
1/7/2021 Python for IoT 67
68. Required arguments
• Required arguments are the arguments
passed to a function in correct positional
order
1/7/2021 Python for IoT 68
69. Keyword arguments
• The caller identifies the arguments by the
parameter name
• Python interpreter is able to use the keywords
provided to match the values with parameters
1/7/2021 Python for IoT 69
70. Default arguments
• A default argument is an argument that
assumes a default value if a value is not
provided in the function call for that argument
1/7/2021 Python for IoT 70
71. Variable-length arguments
• Call a function with variable number of arguments.
• Example:
def customer_details(cust_name,*var_tuple):
print(“This function prints Customer Names:”)
print(“Customer name:”,cust_name)
for var in var_tuple:
print(var)
return
customer_details (“John”,”Jim”,”Harry”,” Kerber”)
This function prints Customer Names
Customer name:John
Jim
Harry
Kerber
customer_details (“Mary”)
This function prints Customer Names
Customer name: Mary
1/7/2021 Python for IoT 71
72. Global vs. Local variables
• Variables that are defined inside a function
body have a local scope
• Variables defined outside have a global scope.
1/7/2021 Python for IoT 72
75. Python Modules
• Used to logically organize code
• Grouping related code into a module
• Module is a file consisting of Python code
• It can define functions, classes and variables
1/7/2021 Python for IoT 75
76. Example
Save this in sample1.py
import math;
def fact(n):
f=1;
for i in range(1, n+1):
f=f*i;
return f;
def power(a,b):
p=math.pow(a, b)
return p;
1/7/2021 Python for IoT 76
77. The import Statement
• You can use any Python source file as a
module by executing an import statement in
some other Python source file.
• import module1[, module2[,... moduleN]
1/7/2021 Python for IoT 77
79. The from...import Statement
• Python's from statement lets you import specific
attributes from a module into the current
namespace
• Syntax:
from modname import name1[, name2[, ...
nameN]]
Example:
from sample1 import power;
f=power(5,3);
print "Power is =", f;
1/7/2021 Python for IoT 79
80. The from...import * Statement:
• It is also possible to import all names from a
module into the current namespace by using
the following import statement −
from modname import *
1/7/2021 Python for IoT 80
81. Locating Modules
• When you import a module, the Python
interpreter searches for the module in the
following sequences −
– The current directory
– If the module isn't found, Python then searches
each directory in the shell variable PYTHONPATH
– If all else fails, Python checks the default path.
– On UNIX, this default path is normally
/usr/local/lib/python/.
1/7/2021 Python for IoT 81
82. Packages
• Package is a hierarchical file structure that consists of
modules and subpackages.
• Packages allow better organization of modules related
to a single application environment.
• Each package in python is a directory which must have
a special file called _init_.py
• This file may not even have a single line of code.
• It is simply added to indicate that this directory is not
an ordinary directory and contains a python package.
1/7/2021 Python for IoT 82
84. Files I/O
• Opening and Closing Files
– Syntax:
– file object = open(file_name [, access_mode][, buffering])
– access_mode - read, write, append, read and write(r+ or w+), read-binary(rb),
write-binary(wb), etc.
– If the buffering value is set to 0, no buffering takes place.
– If the buffering value is 1, line buffering is performed while accessing a file.
– If the buffering value is an integer greater than 1, then buffering is performed
with the indicated buffer size
– Example:
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
1/7/2021 Python for IoT 84
85. The close() Method
• close() method of a file object flushes any
unwritten information an
• Syntax
– fileObject.close();
1/7/2021 Python for IoT 85
86. Reading and Writing Files
• write() method writes any string to an open
file
• Example:
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.nYeah its
great!!n");
fo.close()
1/7/2021 Python for IoT 86
87. The read() Method
• The read()
• Syntax
– fileObject.read([count]);
Example:
– fo = open("foo.txt", "r+")
– str = fo.read(10);
– print "Read String is : ", str
– fo.close()
1/7/2021 Python for IoT 87
89. Renaming and Deleting Files
• Python os module provides methods that help
you perform file-processing operations, such
as renaming and deleting files.
1/7/2021 Python for IoT 89
92. Date & Time
• Python's time and calendar modules help track dates
and times
• time module provides functions for working with times
and for converting between representations
• Function time.time() returns the current system time in
ticks since 12:00am, January 1, 1970
1/7/2021 Python for IoT 92
96. Getting calendar for a month
• The calendar module gives a wide range of methods to
manipulate with yearly and monthly calendars
1/7/2021 Python for IoT 96
97. Time -clock() Method
• clock() returns the current processor time
as a floating point number expressed in
seconds
• Example:
import time;
print (time.clock())
time.sleep(20.5)
print (time.clock())
1/7/2021 Python for IoT 97
98. Classes
• Python is an OOP Language.
• Python provides all the standard features of
OOP
1/7/2021 Python for IoT 98
99. OOP Concepts:
• Class
• Object
• Class variable
• Data member
• Method
• Instance variable
• Inheritance
• Instantiation
• Function overloading
• Operator overloading
1/7/2021 Python for IoT 99
100. Class and Instance/Object
• Class is simply a representation of type of
object and user-defined prototype for an
object that is composed of three things:
– Name
– Attributes
– Operations/Methods
• Object is an instance of the data structure
defined by a class.
1/7/2021 Python for IoT 100
105. Class Inheritance
• It is the process of forming a new class from
an existing class or base class.
• Instead of starting from scratch, you can
create a class by deriving it from a preexisting
class
• The child class inherits the attributes of its
parent class
• Syntax:
1/7/2021 Python for IoT 105
107. Function Overloading and Operator
Overloading
• Function overloading is a form of
polymorphism that allows a function to have
different meaning, depending on its context.
• Operator overloading is form of polymorphism
that allows assignment of more than one
function to a particular operator.
1/7/2021 Python for IoT 107
108. Overriding Methods
• Function overriding allows a child class to provide a specific
implementation of a function that is already provided by the base
class.
• It has the same name, parameters and return type as the function
in the base class.
• Override parent class methods.
• Reason – To give special or different functionality in subclass
1/7/2021 Python for IoT 108
110. Exceptions Handling
• Errors detected during execution are
called exceptions
• The try block lets you test a block of code for
errors.
• The except block lets you handle the error.
• The finally block lets you execute code,
regardless of the result of the try- and except
blocks.
1/7/2021 Python for IoT 110
113. Exceptions- Example2
while True:
try:
x = int(raw_input("Please enter a number:
"))
break
except ValueError:
print "That was not valid number. Try
again..."
print "Number is correct!"
1/7/2021 Python for IoT 113
114. Python Packages – HTTPLib,URLLib,SMPTLib
• HTTPLib2 and URLLib2 are python libraries
used in network/internet programming.
• HTTPLib2 is an HTTP client library
• URLLib2 is a library for fetching URLs.
1/7/2021 Python for IoT 114
118. SMTPLib
• Simple Mail Transfer Protocol (SMTP) is a
protocol which handles sending email and
routing e-mail between mail server.
• Python smtplib module provides an SMTP
client session object that can be used to send
email.
• ‘message’ contains the email message to be
sent.
1/7/2021 Python for IoT 118
122. Sample Code 1
def myfunc(a):
a = a + 2
a = a * 2
return a
print myfunc(2)
1/7/2021 Python for IoT 122
a) 8
b) 16
c) Indentation Error
d) Runtime Error
Ans: ?
123. Sample Code 2
What is the output of the expression : 3*1**3
1/7/2021 Python for IoT 123
a) 27
b) 9
c) 3
d) 1
Ans: ?
124. Sample Code 3
i = 0
while i < 3:
print i
i += 1
else:
print 0
1/7/2021 Python for IoT 124
a) 0 1 2 3 0
b) 0 1 2 0
c) 0 1 2
d) Error
Ans: ?
125. Sample Code 4
1/7/2021 Python for IoT 125
a) 12
b) 24
c) 48
d) Error
Ans: ?
r = lambda q: q * 2
s = lambda q: q * 3
x = 2
x = r(x)
x = s(x)
x = r(x)
print x
126. Sample Code 5
a = 4.5
b = 2
c = a/b
d = a//b
a = d
print (a,b,c,d)
1/7/2021 Python for IoT 126
a) 4.5 2 2.25 2.0
b) 4.5 2 2.0 2.25
c) 2.0 2 2.25 2.0
d) 2 2 2.25 2.0
Ans: ?
127. Sample Code 6
list = [1,2,3,4,5,6,7,8]
print (list[1:5])
print (list[-2])
1/7/2021 Python for IoT 127
a) 1,2,3,4,5 7
b) 2,3,4,5,6 7
c) 2,3,4,5 7
d) 2,3,4,5 6
e) 1,2,3,4,5 6
f) 2,3,4,5,6 6
Ans: ?
128. Sample Code 7
class A(object):
val = 1
class B(A):
pass
class C(A):
pass
print A.val, B.val, C.val
B.val = 2
print A.val, B.val, C.val
A.val = 3
print A.val, B.val, C.val
1/7/2021 Python for IoT 128
a) 1 1 1
1 2 1
3 3 3
b) 1 1 1
1 2 1
3 2 3
c) 1 1 1
2 2 2
3 2 3
d) 1 1 1
2 2 2
3 3 3
Ans: ?
129. Sample Code 8
nameList = ['Harsh', 'Pratik', 'Bob', 'Dhruv']
print nameList[1][-1]
1/7/2021 Python for IoT 129
a) Dhruv
b) Bob
c) v
d) Pratik
e) k
f) b
Ans: ?
130. Sample Code 9
data = 50
try:
data = data/10
except ZeroDivisionError:
print('Cannot divide by 0 ', end = '')
finally:
print('GeeksforGeeks ', end = '')
else:
print('Division successful ', end = '')
1/7/2021 Python for IoT 130
a) Runtime error
b) Cannot divide by 0 GeeksforGeeks
c) GeeksforGeeks Division successful
d) GeeksforGeeks
Ans: ?
131. Sample Code 10
• data = 50
• try:
• data = data/0
• except ZeroDivisionError:
• print('Cannot divide by 0 ', end = '')
• else:
• print('Division successful ', end = '')
•
• try:
• data = data/5
• except:
• print('Inside except block ', end = '')
• else:
• print('GFG', end = '')
1/7/2021 Python for IoT 131
a) Cannot divide by 0 GFG
b) Cannot divide by 0
c) Cannot divide by 0 Inside except block GFG
d) Cannot divide by 0 Inside except block
Ans: ?