KEMBAR78
Introduction to Python Programming – Part I.pptx
Introduction to Python
Programming – Part I
Introduction to Internet of Things
1
Why Python?
Introduction to Internet of Things
2
 Python is a versatile language which is easy to script and easy to
read.
 It doesn’t support strict rules for syntax.
 Its installation comes with integrated development environment
for programming.
 It supports interfacing with wide ranging hardware platforms.
 With open-source nature, it forms a strong backbone to build large
applications.
Python IDE
Introduction to Internet of Things
3
 Python IDE is a free and open source software that is used to
write codes, integrate several modules and libraries.
 It is available for installation into PC with Windows, Linux and
Mac.
 Examples: Spyder, PyCharm, etc.
Starting with Python
Introduction to Internet of Things
4
 Simple printing statement at the python interpreter prompt,
>>> print “Hi, Welcome to python!”
Output: Hi, Welcome to python!
 To indicate different blocks of code, it follows rigid indentation.
if True:
print “Correct"
else:
print “Error"
Data-types in
Python
Introduction to Internet of Things
5
 There are 5 data types in Python:
 Numbers
x, y, z = 10, 10.2, " Python "
 String
x = ‘This is Python’
print x
print x[0]
print x[2:4]
>>This is Python
>>T
>>is
Data-types in Python
(contd..)
Introduction to Internet of Things
6
 List
x = [10, 10.2, 'python']
 Tuple
 Dictionary
d = {1:‘item','k':2}
Controlling
Statements
Introduction to Internet of Things
7
 if (cond.):
statement 1
statement 2
elif (cond.):
statement 1
statement 2
else:
statement 1
statement 2
 while (cond.):
statement 1
statement 2
 x = [1,2,3,4]
for i in x:
statement 1
statement 2
Controlling Statements
(contd..)
Introduction to Internet of Things
8
 Break
for s in "string":
if s == ‘n':
break
print (s)
print
“End”
 Continue
for s in "string":
if s == ‘y':
continue
print (s)
print “End”
Functions in Python
Introduction to Internet of Things
9
# Defining the function
 Defining a function
 Without return value
def funct_name(arg1, arg2, arg3):
statement 1
statement 2
 With return value
def funct_name(arg1, arg2, arg3):
# Defining the function
statement 1
statement 2
return x
# Returning the value
Functions in
Python
Introduction to Internet of Things 10
 Calling a function
def example (str):
print (str + “!”)
example (“Hi”) # Calling the function
Output:: Hi!
Functions in Python
(contd..)
Introduction to Internet of Things 11
 Example showing function returning multiple values
def greater(x, y):
if x > y:
return x, y
else:
return
y, x
val = greater(10,
100) print(val)
Output:: (100,10)
Functions as Objects
Introduction to Internet of Things 12
 Functions can also be assigned and reassigned to the variables.
 Example:
def add (a,b)
return a+b
print (add(4,6))
c = add(4,6)
print c
Output:: 10 10
Variable Scope in
Python
Introduction to Internet of Things 13
Global variables:
These are the variables declared out of any function , but can be
accessed inside as well as outside the function.
Local variables:
These are the ones that are declared inside a function.
Example showing Global
Variable
Introduction to Internet of Things 14
g_var = 10
def example():
l_var = 100
print(g_var)
example() # calling the function
Output:: 10
Example showing
Variable Scope
var = 10
Introduction to Internet of Things 15
def example():
var = 100
print(var)
# calling the function
example()
print(var)
Output:: 100
10
Modules in Python
Introduction to Internet of Things 16
 Any segment of code fulfilling a particular task that can be
used commonly by everyone is termed as a module.
 Syntax:
import module_name #At the top of the code
using module_name.var #To access functions and values
with ‘var’ in the module
Modules in Python
(contd..)
Introduction to Internet of Things 17
 Example:
import random
for i in range(1,10):
val = random.randint(1,10)
print (val)
Output:: varies with each execution
Modules in Python
(contd..)
Introduction to Internet of Things 18
 We can also access only a particular function from a module.
 Example:
from math import pi
print (pi)
Output:: 3.14159
Exception Handling in
Python
Introduction to Internet of Things 19
 An error that is generated during execution of a program, is
termed as exception.
 Syntax:
try:
statements
except _Exception_:
statement
s else:
statemen
ts
Exception Handling in Python
(contd..)
Introduction to Internet of Things 20
 Example:
while True:
try:
n = input ("Please enter an integer: ")
n = int (n)
break
except ValueError:
print
"No valid
integer! "
print “It is an
integer!"
Example Code: to check number is prime or not
Introduction to Internet of Things 21
x = int (input("Enter a number: "))
def prime (num):
if num > 1:
for i in
range(2,num):
if (num % i)
== 0:
print (num,"is not a prime number")
print (i,“is a factor of”,num)
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
prime (x)
Introduction to Python
Programming – Part II
Introduction to Internet of Things
1
File Read Write
Operations
Introduction to Internet of Things
2
 Python allows you to read and write files
 No separate module or library required
 Three basic steps
 Open a file
 Read/Write
 Close the file
File Read Write Operations
(contd..)
Introduction to Internet of Things
3
Opening a File:
 Open() function is used to open a file, returns a file object
open(file_name, mode)
 Mode: Four basic modes to open a file
r: read mode
w: write mode
a: append mode
r+: both read
and write mode
File Read Write Operations
(contd..)
Introduction to Internet of Things
4
Read from a file:
 read(): Reads from a file
file=open(‘data.txt’, ‘r’)
file.read()
Write to a file:
 Write(): Writes to a file
file=open(‘data.txt’, ‘w’)
file.write(‘writing to the file’)
File Read Write Operations
(contd..)
Introduction to Internet of Things
5
Closing a file:
 Close(): This is done to ensure that the file is free to use for other resources
file.close()
Using WITH to open a file:
 Good practice to handle exception while file read/write operation
 Ensures the file is closed after the operation is completed, even if an exception is
encountered
with open(“data.txt","w") as file:
file.write(“writing to the text file”)
file.close()
File Read Write Operations code +
image
Introduction to Internet of Things
6
with open("PythonProgram.txt","w") as file:
file.write("Writing data")
file.close()
with open("PythonProgram.txt","r") as file:
f=file.read()
print('Reading from the filen')
print (f)
file.close()
File Read Write Operations
(contd..)
Introduction to Internet of Things
7
Comma Separated Values Files
 CSV module supported for CSV files
Read:
with open(file, "r") as csv_file:
reader = csv.reader(csv_file)
print("Reading from the CSV Filen")
for row in reader:
print(" ".join(row))
csv_file.close()
Write:
data = ["1,2,3,4,5,6,7,8,9".split(",")]
file = "output.csv"
with open(file, "w") as csv_file:
writer = csv.writer(csv_file, delimiter=',')
print("Writing CSV")
for line in data:
writer.writerow(line)
csv_file.close()
File Read Write Operations
(contd..)
Introduction to Internet of Things
8
Image Read/Write
Operations
Introduction to Internet of Things
9
 Python supports PIL library for image related operations
 Install PIL through PIP
sudo pip install pillow
PIL is supported till python version 2.7. Pillow supports the 3x version of
python.
Image Read/Write
Operations
Introduction to Internet of Things 10
Reading Image in Python:
 PIL: Python Image Library is used to work with image files
from PIL import Image
 Open an image file
image=Image.open(image_name)
 Display the image
image.show()
Image Read/Write
Operations (contd..)
Introduction to Internet of Things 11
Resize(): Resizes the image to the specified size
image.resize(255,255)
Rotate(): Rotates the image to the specified degrees, counter clockwise
image.rotate(90)
Format:
Size:
Mode:
Gives the format of the image
Gives a tuple with 2 values as width and height of the image, in pixels
Gives the band of the image, ‘L’ for grey scale, ‘RGB’ for true colour image
print(image.format, image.size, image.mode)
Image Read/Write Operations
(contd..)
Introduction to Internet of Things 12
Convert image to different mode:
 Any image can be converted from one mode to ‘L’ or ‘RGB’
mode
conv_image=image.convert(‘L’)
 Conversion between modes other that ‘L’ and ‘RGB’ needs
conversion into any of these 2 intermediate mode
Output
Converting a sample image to Grey Scale
Introduction to Internet of Things 13
Output
Introduction to Internet of Things 14
Networking in Python
Introduction to Internet of Things 15
 Python provides network services for client server model.
 Socket support in the operating system allows to implement clients
and servers for both connection-oriented and connectionless
protocols.
 Python has libraries that provide higher-level access to specific
application-level network protocols.
Networking in Python
(contd..)
Introduction to Internet of Things 16
 Syntax for creating a socket:
s = socket.socket (socket_family, socket_type, protocol=0)
socket_family − AF_UNIX or AF_INET
socket_type − SOCK_STREAM or SOCK_DGRAM
protocol − default ‘0’.
Example - simple server
Introduction to Internet of Things 17
 The socket waits until a client connects to the port, and then returns a
connection object that represents the connection to that client.
import socket
import sys
# Create a
TCP/IP socket
sock =
socket.socket(
socket.AF_IN
ET,
socket.SOCK_
STREAM)
# Bind the socket to the port
server_address = ('10.14.88.82', 2017)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
Example - simple server
(contd..)
Introduction to Internet of Things 18
# Listen for incoming connections
sock.listen(1)
connection, client_address = sock.accept()
#Receive command
data = connection.recv(1024)
print(data)
sock.close()
Example - simple client
Introduction to Internet of Things 19
import socket
import sys
# Create a
TCP/IP socket
client_socket
=
socket.socket(
socket.AF_IN
ET,
socket.SOCK_
STREAM)
#Connect to Listener socket
client_socket.connect(("10.14.88.82", 2017))
print>>sys.stderr,'Connection Established'
#Send command
client_socket.send('Message to the server')
print('Data sent successfully')
Code Snapshot
Introduction to Internet of Things 20
Output
Introduction to Internet of Things 21

Introduction to Python Programming – Part I.pptx

  • 1.
    Introduction to Python Programming– Part I Introduction to Internet of Things 1
  • 2.
    Why Python? Introduction toInternet of Things 2  Python is a versatile language which is easy to script and easy to read.  It doesn’t support strict rules for syntax.  Its installation comes with integrated development environment for programming.  It supports interfacing with wide ranging hardware platforms.  With open-source nature, it forms a strong backbone to build large applications.
  • 3.
    Python IDE Introduction toInternet of Things 3  Python IDE is a free and open source software that is used to write codes, integrate several modules and libraries.  It is available for installation into PC with Windows, Linux and Mac.  Examples: Spyder, PyCharm, etc.
  • 4.
    Starting with Python Introductionto Internet of Things 4  Simple printing statement at the python interpreter prompt, >>> print “Hi, Welcome to python!” Output: Hi, Welcome to python!  To indicate different blocks of code, it follows rigid indentation. if True: print “Correct" else: print “Error"
  • 5.
    Data-types in Python Introduction toInternet of Things 5  There are 5 data types in Python:  Numbers x, y, z = 10, 10.2, " Python "  String x = ‘This is Python’ print x print x[0] print x[2:4] >>This is Python >>T >>is
  • 6.
    Data-types in Python (contd..) Introductionto Internet of Things 6  List x = [10, 10.2, 'python']  Tuple  Dictionary d = {1:‘item','k':2}
  • 7.
    Controlling Statements Introduction to Internetof Things 7  if (cond.): statement 1 statement 2 elif (cond.): statement 1 statement 2 else: statement 1 statement 2  while (cond.): statement 1 statement 2  x = [1,2,3,4] for i in x: statement 1 statement 2
  • 8.
    Controlling Statements (contd..) Introduction toInternet of Things 8  Break for s in "string": if s == ‘n': break print (s) print “End”  Continue for s in "string": if s == ‘y': continue print (s) print “End”
  • 9.
    Functions in Python Introductionto Internet of Things 9 # Defining the function  Defining a function  Without return value def funct_name(arg1, arg2, arg3): statement 1 statement 2  With return value def funct_name(arg1, arg2, arg3): # Defining the function statement 1 statement 2 return x # Returning the value
  • 10.
    Functions in Python Introduction toInternet of Things 10  Calling a function def example (str): print (str + “!”) example (“Hi”) # Calling the function Output:: Hi!
  • 11.
    Functions in Python (contd..) Introductionto Internet of Things 11  Example showing function returning multiple values def greater(x, y): if x > y: return x, y else: return y, x val = greater(10, 100) print(val) Output:: (100,10)
  • 12.
    Functions as Objects Introductionto Internet of Things 12  Functions can also be assigned and reassigned to the variables.  Example: def add (a,b) return a+b print (add(4,6)) c = add(4,6) print c Output:: 10 10
  • 13.
    Variable Scope in Python Introductionto Internet of Things 13 Global variables: These are the variables declared out of any function , but can be accessed inside as well as outside the function. Local variables: These are the ones that are declared inside a function.
  • 14.
    Example showing Global Variable Introductionto Internet of Things 14 g_var = 10 def example(): l_var = 100 print(g_var) example() # calling the function Output:: 10
  • 15.
    Example showing Variable Scope var= 10 Introduction to Internet of Things 15 def example(): var = 100 print(var) # calling the function example() print(var) Output:: 100 10
  • 16.
    Modules in Python Introductionto Internet of Things 16  Any segment of code fulfilling a particular task that can be used commonly by everyone is termed as a module.  Syntax: import module_name #At the top of the code using module_name.var #To access functions and values with ‘var’ in the module
  • 17.
    Modules in Python (contd..) Introductionto Internet of Things 17  Example: import random for i in range(1,10): val = random.randint(1,10) print (val) Output:: varies with each execution
  • 18.
    Modules in Python (contd..) Introductionto Internet of Things 18  We can also access only a particular function from a module.  Example: from math import pi print (pi) Output:: 3.14159
  • 19.
    Exception Handling in Python Introductionto Internet of Things 19  An error that is generated during execution of a program, is termed as exception.  Syntax: try: statements except _Exception_: statement s else: statemen ts
  • 20.
    Exception Handling inPython (contd..) Introduction to Internet of Things 20  Example: while True: try: n = input ("Please enter an integer: ") n = int (n) break except ValueError: print "No valid integer! " print “It is an integer!"
  • 21.
    Example Code: tocheck number is prime or not Introduction to Internet of Things 21 x = int (input("Enter a number: ")) def prime (num): if num > 1: for i in range(2,num): if (num % i) == 0: print (num,"is not a prime number") print (i,“is a factor of”,num) break else: print(num,"is a prime number") else: print(num,"is not a prime number") prime (x)
  • 22.
    Introduction to Python Programming– Part II Introduction to Internet of Things 1
  • 23.
    File Read Write Operations Introductionto Internet of Things 2  Python allows you to read and write files  No separate module or library required  Three basic steps  Open a file  Read/Write  Close the file
  • 24.
    File Read WriteOperations (contd..) Introduction to Internet of Things 3 Opening a File:  Open() function is used to open a file, returns a file object open(file_name, mode)  Mode: Four basic modes to open a file r: read mode w: write mode a: append mode r+: both read and write mode
  • 25.
    File Read WriteOperations (contd..) Introduction to Internet of Things 4 Read from a file:  read(): Reads from a file file=open(‘data.txt’, ‘r’) file.read() Write to a file:  Write(): Writes to a file file=open(‘data.txt’, ‘w’) file.write(‘writing to the file’)
  • 26.
    File Read WriteOperations (contd..) Introduction to Internet of Things 5 Closing a file:  Close(): This is done to ensure that the file is free to use for other resources file.close() Using WITH to open a file:  Good practice to handle exception while file read/write operation  Ensures the file is closed after the operation is completed, even if an exception is encountered with open(“data.txt","w") as file: file.write(“writing to the text file”) file.close()
  • 27.
    File Read WriteOperations code + image Introduction to Internet of Things 6 with open("PythonProgram.txt","w") as file: file.write("Writing data") file.close() with open("PythonProgram.txt","r") as file: f=file.read() print('Reading from the filen') print (f) file.close()
  • 28.
    File Read WriteOperations (contd..) Introduction to Internet of Things 7 Comma Separated Values Files  CSV module supported for CSV files Read: with open(file, "r") as csv_file: reader = csv.reader(csv_file) print("Reading from the CSV Filen") for row in reader: print(" ".join(row)) csv_file.close() Write: data = ["1,2,3,4,5,6,7,8,9".split(",")] file = "output.csv" with open(file, "w") as csv_file: writer = csv.writer(csv_file, delimiter=',') print("Writing CSV") for line in data: writer.writerow(line) csv_file.close()
  • 29.
    File Read WriteOperations (contd..) Introduction to Internet of Things 8
  • 30.
    Image Read/Write Operations Introduction toInternet of Things 9  Python supports PIL library for image related operations  Install PIL through PIP sudo pip install pillow PIL is supported till python version 2.7. Pillow supports the 3x version of python.
  • 31.
    Image Read/Write Operations Introduction toInternet of Things 10 Reading Image in Python:  PIL: Python Image Library is used to work with image files from PIL import Image  Open an image file image=Image.open(image_name)  Display the image image.show()
  • 32.
    Image Read/Write Operations (contd..) Introductionto Internet of Things 11 Resize(): Resizes the image to the specified size image.resize(255,255) Rotate(): Rotates the image to the specified degrees, counter clockwise image.rotate(90) Format: Size: Mode: Gives the format of the image Gives a tuple with 2 values as width and height of the image, in pixels Gives the band of the image, ‘L’ for grey scale, ‘RGB’ for true colour image print(image.format, image.size, image.mode)
  • 33.
    Image Read/Write Operations (contd..) Introductionto Internet of Things 12 Convert image to different mode:  Any image can be converted from one mode to ‘L’ or ‘RGB’ mode conv_image=image.convert(‘L’)  Conversion between modes other that ‘L’ and ‘RGB’ needs conversion into any of these 2 intermediate mode
  • 34.
    Output Converting a sampleimage to Grey Scale Introduction to Internet of Things 13
  • 35.
  • 36.
    Networking in Python Introductionto Internet of Things 15  Python provides network services for client server model.  Socket support in the operating system allows to implement clients and servers for both connection-oriented and connectionless protocols.  Python has libraries that provide higher-level access to specific application-level network protocols.
  • 37.
    Networking in Python (contd..) Introductionto Internet of Things 16  Syntax for creating a socket: s = socket.socket (socket_family, socket_type, protocol=0) socket_family − AF_UNIX or AF_INET socket_type − SOCK_STREAM or SOCK_DGRAM protocol − default ‘0’.
  • 38.
    Example - simpleserver Introduction to Internet of Things 17  The socket waits until a client connects to the port, and then returns a connection object that represents the connection to that client. import socket import sys # Create a TCP/IP socket sock = socket.socket( socket.AF_IN ET, socket.SOCK_ STREAM) # Bind the socket to the port server_address = ('10.14.88.82', 2017) print >>sys.stderr, 'starting up on %s port %s' % server_address sock.bind(server_address)
  • 39.
    Example - simpleserver (contd..) Introduction to Internet of Things 18 # Listen for incoming connections sock.listen(1) connection, client_address = sock.accept() #Receive command data = connection.recv(1024) print(data) sock.close()
  • 40.
    Example - simpleclient Introduction to Internet of Things 19 import socket import sys # Create a TCP/IP socket client_socket = socket.socket( socket.AF_IN ET, socket.SOCK_ STREAM) #Connect to Listener socket client_socket.connect(("10.14.88.82", 2017)) print>>sys.stderr,'Connection Established' #Send command client_socket.send('Message to the server') print('Data sent successfully')
  • 41.
    Code Snapshot Introduction toInternet of Things 20
  • 42.