SlideShare a Scribd company logo
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
Ad

More Related Content

Similar to Introduction to Python Programming – Part I.pptx (20)

Data Structure and Algorithms (DSA) with Python
Data Structure and Algorithms (DSA) with PythonData Structure and Algorithms (DSA) with Python
Data Structure and Algorithms (DSA) with Python
epsilonice
 
Revision of the basics of python1 (1).pdf
Revision of the basics of python1 (1).pdfRevision of the basics of python1 (1).pdf
Revision of the basics of python1 (1).pdf
optimusnotch44
 
Python Course Basic
Python Course BasicPython Course Basic
Python Course Basic
Naiyan Noor
 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
Anonymous9etQKwW
 
unit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptxunit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptx
usvirat1805
 
Python Programming Introduction demo.ppt
Python Programming Introduction demo.pptPython Programming Introduction demo.ppt
Python Programming Introduction demo.ppt
JohariNawab
 
Python knowledge ,......................
Python knowledge ,......................Python knowledge ,......................
Python knowledge ,......................
sabith777a
 
Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1
Abdul Haseeb
 
Python introduction towards data science
Python introduction towards data sciencePython introduction towards data science
Python introduction towards data science
deepak teja
 
python questionsfor class 8 students and
python questionsfor class 8 students andpython questionsfor class 8 students and
python questionsfor class 8 students and
RameshKumarYadav29
 
00 C hello world.pptx
00 C hello world.pptx00 C hello world.pptx
00 C hello world.pptx
Carla227537
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
 
Python basics
Python basicsPython basics
Python basics
Bladimir Eusebio Illanes Quispe
 
UNIT-1 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHON
UNIT-1 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHON UNIT-1 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHON
UNIT-1 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHON
Nandakumar P
 
Introduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIMLIntroduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIML
VijaySharma802
 
C463_02_python.ppt
C463_02_python.pptC463_02_python.ppt
C463_02_python.ppt
KapilMighani
 
kapil presentation.ppt
kapil presentation.pptkapil presentation.ppt
kapil presentation.ppt
KapilMighani
 
Python fundamentals
Python fundamentalsPython fundamentals
Python fundamentals
natnaelmamuye
 
Python Course.docx
Python Course.docxPython Course.docx
Python Course.docx
AdnanAhmad57885
 
Introduction to python & its applications.ppt
Introduction to python & its applications.pptIntroduction to python & its applications.ppt
Introduction to python & its applications.ppt
PradeepNB2
 
Data Structure and Algorithms (DSA) with Python
Data Structure and Algorithms (DSA) with PythonData Structure and Algorithms (DSA) with Python
Data Structure and Algorithms (DSA) with Python
epsilonice
 
Revision of the basics of python1 (1).pdf
Revision of the basics of python1 (1).pdfRevision of the basics of python1 (1).pdf
Revision of the basics of python1 (1).pdf
optimusnotch44
 
Python Course Basic
Python Course BasicPython Course Basic
Python Course Basic
Naiyan Noor
 
unit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptxunit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptx
usvirat1805
 
Python Programming Introduction demo.ppt
Python Programming Introduction demo.pptPython Programming Introduction demo.ppt
Python Programming Introduction demo.ppt
JohariNawab
 
Python knowledge ,......................
Python knowledge ,......................Python knowledge ,......................
Python knowledge ,......................
sabith777a
 
Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1
Abdul Haseeb
 
Python introduction towards data science
Python introduction towards data sciencePython introduction towards data science
Python introduction towards data science
deepak teja
 
python questionsfor class 8 students and
python questionsfor class 8 students andpython questionsfor class 8 students and
python questionsfor class 8 students and
RameshKumarYadav29
 
00 C hello world.pptx
00 C hello world.pptx00 C hello world.pptx
00 C hello world.pptx
Carla227537
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
 
UNIT-1 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHON
UNIT-1 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHON UNIT-1 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHON
UNIT-1 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHON
Nandakumar P
 
Introduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIMLIntroduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIML
VijaySharma802
 
C463_02_python.ppt
C463_02_python.pptC463_02_python.ppt
C463_02_python.ppt
KapilMighani
 
kapil presentation.ppt
kapil presentation.pptkapil presentation.ppt
kapil presentation.ppt
KapilMighani
 
Introduction to python & its applications.ppt
Introduction to python & its applications.pptIntroduction to python & its applications.ppt
Introduction to python & its applications.ppt
PradeepNB2
 

Recently uploaded (20)

IBAAS 2023 Series_Lecture 8- Dr. Nandi.pdf
IBAAS 2023 Series_Lecture 8- Dr. Nandi.pdfIBAAS 2023 Series_Lecture 8- Dr. Nandi.pdf
IBAAS 2023 Series_Lecture 8- Dr. Nandi.pdf
VigneshPalaniappanM
 
David Boutry - Specializes In AWS, Microservices And Python
David Boutry - Specializes In AWS, Microservices And PythonDavid Boutry - Specializes In AWS, Microservices And Python
David Boutry - Specializes In AWS, Microservices And Python
David Boutry
 
Optimizing Reinforced Concrete Cantilever Retaining Walls Using Gases Brownia...
Optimizing Reinforced Concrete Cantilever Retaining Walls Using Gases Brownia...Optimizing Reinforced Concrete Cantilever Retaining Walls Using Gases Brownia...
Optimizing Reinforced Concrete Cantilever Retaining Walls Using Gases Brownia...
Journal of Soft Computing in Civil Engineering
 
Design of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdfDesign of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdf
Kamel Farid
 
Generative AI & Large Language Models Agents
Generative AI & Large Language Models AgentsGenerative AI & Large Language Models Agents
Generative AI & Large Language Models Agents
aasgharbee22seecs
 
vtc2018fall_otfs_tutorial_presentation_1.pdf
vtc2018fall_otfs_tutorial_presentation_1.pdfvtc2018fall_otfs_tutorial_presentation_1.pdf
vtc2018fall_otfs_tutorial_presentation_1.pdf
RaghavaGD1
 
Physical and Physic-Chemical Based Optimization Methods: A Review
Physical and Physic-Chemical Based Optimization Methods: A ReviewPhysical and Physic-Chemical Based Optimization Methods: A Review
Physical and Physic-Chemical Based Optimization Methods: A Review
Journal of Soft Computing in Civil Engineering
 
AI-Powered Data Management and Governance in Retail
AI-Powered Data Management and Governance in RetailAI-Powered Data Management and Governance in Retail
AI-Powered Data Management and Governance in Retail
IJDKP
 
Artificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptxArtificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptx
rakshanatarajan005
 
OPTIMIZING DATA INTEROPERABILITY IN AGILE ORGANIZATIONS: INTEGRATING NONAKA’S...
OPTIMIZING DATA INTEROPERABILITY IN AGILE ORGANIZATIONS: INTEGRATING NONAKA’S...OPTIMIZING DATA INTEROPERABILITY IN AGILE ORGANIZATIONS: INTEGRATING NONAKA’S...
OPTIMIZING DATA INTEROPERABILITY IN AGILE ORGANIZATIONS: INTEGRATING NONAKA’S...
ijdmsjournal
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
Using the Artificial Neural Network to Predict the Axial Strength and Strain ...
Using the Artificial Neural Network to Predict the Axial Strength and Strain ...Using the Artificial Neural Network to Predict the Axial Strength and Strain ...
Using the Artificial Neural Network to Predict the Axial Strength and Strain ...
Journal of Soft Computing in Civil Engineering
 
Slide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptxSlide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptx
vvsasane
 
Lecture - 7 Canals of the topic of the civil engineering
Lecture - 7  Canals of the topic of the civil engineeringLecture - 7  Canals of the topic of the civil engineering
Lecture - 7 Canals of the topic of the civil engineering
MJawadkhan1
 
Machine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATIONMachine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATION
DarrinBright1
 
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdfLittle Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
gori42199
 
Environment .................................
Environment .................................Environment .................................
Environment .................................
shadyozq9
 
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic AlgorithmDesign Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Journal of Soft Computing in Civil Engineering
 
introduction technology technology tec.pptx
introduction technology technology tec.pptxintroduction technology technology tec.pptx
introduction technology technology tec.pptx
Iftikhar70
 
AI Chatbots & Software Development Teams
AI Chatbots & Software Development TeamsAI Chatbots & Software Development Teams
AI Chatbots & Software Development Teams
Joe Krall
 
IBAAS 2023 Series_Lecture 8- Dr. Nandi.pdf
IBAAS 2023 Series_Lecture 8- Dr. Nandi.pdfIBAAS 2023 Series_Lecture 8- Dr. Nandi.pdf
IBAAS 2023 Series_Lecture 8- Dr. Nandi.pdf
VigneshPalaniappanM
 
David Boutry - Specializes In AWS, Microservices And Python
David Boutry - Specializes In AWS, Microservices And PythonDavid Boutry - Specializes In AWS, Microservices And Python
David Boutry - Specializes In AWS, Microservices And Python
David Boutry
 
Design of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdfDesign of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdf
Kamel Farid
 
Generative AI & Large Language Models Agents
Generative AI & Large Language Models AgentsGenerative AI & Large Language Models Agents
Generative AI & Large Language Models Agents
aasgharbee22seecs
 
vtc2018fall_otfs_tutorial_presentation_1.pdf
vtc2018fall_otfs_tutorial_presentation_1.pdfvtc2018fall_otfs_tutorial_presentation_1.pdf
vtc2018fall_otfs_tutorial_presentation_1.pdf
RaghavaGD1
 
AI-Powered Data Management and Governance in Retail
AI-Powered Data Management and Governance in RetailAI-Powered Data Management and Governance in Retail
AI-Powered Data Management and Governance in Retail
IJDKP
 
Artificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptxArtificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptx
rakshanatarajan005
 
OPTIMIZING DATA INTEROPERABILITY IN AGILE ORGANIZATIONS: INTEGRATING NONAKA’S...
OPTIMIZING DATA INTEROPERABILITY IN AGILE ORGANIZATIONS: INTEGRATING NONAKA’S...OPTIMIZING DATA INTEROPERABILITY IN AGILE ORGANIZATIONS: INTEGRATING NONAKA’S...
OPTIMIZING DATA INTEROPERABILITY IN AGILE ORGANIZATIONS: INTEGRATING NONAKA’S...
ijdmsjournal
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
Slide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptxSlide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptx
vvsasane
 
Lecture - 7 Canals of the topic of the civil engineering
Lecture - 7  Canals of the topic of the civil engineeringLecture - 7  Canals of the topic of the civil engineering
Lecture - 7 Canals of the topic of the civil engineering
MJawadkhan1
 
Machine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATIONMachine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATION
DarrinBright1
 
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdfLittle Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
gori42199
 
Environment .................................
Environment .................................Environment .................................
Environment .................................
shadyozq9
 
introduction technology technology tec.pptx
introduction technology technology tec.pptxintroduction technology technology tec.pptx
introduction technology technology tec.pptx
Iftikhar70
 
AI Chatbots & Software Development Teams
AI Chatbots & Software Development TeamsAI Chatbots & Software Development Teams
AI Chatbots & Software Development Teams
Joe Krall
 
Ad

Introduction to Python Programming – Part I.pptx

  • 1. Introduction to Python Programming – Part I Introduction to Internet of Things 1
  • 2. 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.
  • 3. 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.
  • 4. 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"
  • 5. 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
  • 6. Data-types in Python (contd..) Introduction to Internet of Things 6  List x = [10, 10.2, 'python']  Tuple  Dictionary d = {1:‘item','k':2}
  • 7. 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
  • 8. 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”
  • 9. 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
  • 10. Functions in Python Introduction to Internet of Things 10  Calling a function def example (str): print (str + “!”) example (“Hi”) # Calling the function Output:: Hi!
  • 11. 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)
  • 12. 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
  • 13. 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.
  • 14. 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
  • 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 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
  • 17. 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
  • 18. 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
  • 19. 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
  • 20. 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!"
  • 21. 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)
  • 22. Introduction to Python Programming – Part II Introduction to Internet of Things 1
  • 23. 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
  • 24. 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
  • 25. 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’)
  • 26. 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()
  • 27. 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()
  • 28. 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()
  • 29. File Read Write Operations (contd..) Introduction to Internet of Things 8
  • 30. 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.
  • 31. 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()
  • 32. 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)
  • 33. 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
  • 34. Output Converting a sample image to Grey Scale Introduction to Internet of Things 13
  • 36. 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.
  • 37. 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’.
  • 38. 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)
  • 39. 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()
  • 40. 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')
  • 41. Code Snapshot Introduction to Internet of Things 20
  翻译: