Se ha denunciado esta presentación.
Se está descargando tu SlideShare. ×
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Próximo SlideShare
Embedded C - Day 1
Embedded C - Day 1
Cargando en…3
×

Eche un vistazo a continuación

1 de 132 Anuncio

Python for IoT

Descargar para leer sin conexión

Python programming concepts for the Internet of things applications development. This PPT contains details about classes, list , tuples, dictionaries, packages like HTTPLib,SMTPLib, etc

Python programming concepts for the Internet of things applications development. This PPT contains details about classes, list , tuples, dictionaries, packages like HTTPLib,SMTPLib, etc

Anuncio
Anuncio

Más Contenido Relacionado

Presentaciones para usted (20)

Similares a Python for IoT (20)

Anuncio

Más de Selvaraj Seerangan (20)

Más reciente (20)

Anuncio

Python for IoT

  1. 1. By Mr.S.Selvaraj Asst. Professor(SRG) / CSE Kongu Engineering College 14ITO01 – Internet of Things Unit III – Python for IoT
  2. 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. 3. Python Conquers the Universe • Most widely used high level programming language across the world 1/7/2021 Python for IoT 3
  4. 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
  5. 5. 1/7/2021 Python for IoT 5
  6. 6. 1/7/2021 Python for IoT 6
  7. 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. 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
  9. 9. Sample Programs • Helloworld.py: print("Hello World!") • Addition.py a=10; b=4; c=a+b; print ("Sum=",c) 1/7/2021 Python for IoT 9
  10. 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. 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
  12. 12. 1/7/2021 Python for IoT 12
  13. 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
  14. 14. 1/7/2021 Python for IoT 14
  15. 15. Keywords 1/7/2021 Python for IoT 15
  16. 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. 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. 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. 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
  20. 20. Thank You 1/7/2021 Python for IoT 20
  21. 21. Unit - III Data Types and Data Structures
  22. 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. 23. Standard Data Types • Numbers • String • List • Tuple • Dictionary 1/7/2021 Python for IoT 23
  24. 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. 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
  26. 26. Indexing and Slicing 1/7/2021 Python for IoT 26
  27. 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
  28. 28. Lists - Example 1/7/2021 Python for IoT 28
  29. 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
  30. 30. Tuples - Example 1/7/2021 Python for IoT 30
  31. 31. Tuples - Output 1/7/2021 Python for IoT 31
  32. 32. Difference – Lists and Tuples 1/7/2021 Python for IoT 32
  33. 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
  34. 34. Example 1/7/2021 Python for IoT 34
  35. 35. Example -Output 1/7/2021 Python for IoT 35
  36. 36. Basic Operators • Arithmetic Operators • Comparison (Relational) Operators • Assignment Operators • Logical Operators • Bitwise Operators • Membership Operators • Identity Operators 1/7/2021 Python for IoT 36
  37. 37. Arithmetic Operators 1/7/2021 Python for IoT 37
  38. 38. Comparison Operators 1/7/2021 Python for IoT 38
  39. 39. 1/7/2021 Python for IoT 39
  40. 40. Bitwise Operators • a = 0011 1100 • b = 0000 1101 • Example: – a&b = 0000 1100 – a|b = 0011 1101 – a^b = 0011 0001 – ~a = 1100 0011 1/7/2021 Python for IoT 40
  41. 41. Logical Operators 1/7/2021 Python for IoT 41
  42. 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
  43. 43. Identity Operators • Identity operators compare the memory locations of two objects 1/7/2021 Python for IoT 43
  44. 44. 1/7/2021 Python for IoT 44
  45. 45. 1/7/2021 Python for IoT 45
  46. 46. 1/7/2021 Python for IoT 46
  47. 47. Thank You 1/7/2021 Python for IoT 47
  48. 48. Unit - III Python for IOT
  49. 49. 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 49
  50. 50. Selection /Conditional Branching Statements • If Statement • If-else Statement • Nested if statements • If-elif-else statements 1/7/2021 Python for IoT 50
  51. 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. 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. 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. 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. 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
  56. 56. while Loop • Syntax: while expression: statement(s) • Example: 1/7/2021 Python for IoT 56 Output:
  57. 57. Using else Statement with Loops • Supports else statement associated with a loop. • Example: 1/7/2021 Python for IoT 57
  58. 58. for Loop • Syntax: for iterating_var in sequence: statements(s) • Example: 1/7/2021 Python for IoT 58 Output:
  59. 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
  60. 60. Example- For loop Prime Numbers b/w 10 and 20 1/7/2021 Python for IoT 60
  61. 61. Nested loops • Syntax: 1/7/2021 Python for IoT 61
  62. 62. Example- Nested Loop 1/7/2021 Python for IoT 62
  63. 63. Mathematical Functions • abs(x) • ceil(x) • cmp(x, y) • floor(x) • log(x) • log10(x) • max(x1, x2,...) • min(x1, x2,...) • pow(x, y) • round(x [,n]) • sqrt(x) 1/7/2021 Python for IoT 63
  64. 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
  65. 65. Function- Syntax • Example: 1/7/2021 Python for IoT 65
  66. 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. 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. 68. Required arguments • Required arguments are the arguments passed to a function in correct positional order 1/7/2021 Python for IoT 68
  69. 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. 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. 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. 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
  73. 73. Thank You 1/7/2021 Python for IoT 73
  74. 74. Python (Modules, Package & Files)
  75. 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. 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. 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
  78. 78. Main Program import sample1 f=sample1.fact(5); print "Factorial is =", f; f=sample1.power(5,3); print "Power is =", f; 1/7/2021 Python for IoT 78
  79. 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. 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. 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. 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
  83. 83. Package Example 1/7/2021 Python for IoT 83
  84. 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. 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. 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. 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
  88. 88. File Positions 1/7/2021 Python for IoT 88
  89. 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
  90. 90. Delete 1/7/2021 Python for IoT 90
  91. 91. Programming in Python : Date Time, Classes and Exception Handling
  92. 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
  93. 93. TimeTuple 1/7/2021 Python for IoT 93
  94. 94. Current time 1/7/2021 Python for IoT 94
  95. 95. Getting formatted time 1/7/2021 Python for IoT 95
  96. 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. 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. 98. Classes • Python is an OOP Language. • Python provides all the standard features of OOP 1/7/2021 Python for IoT 98
  99. 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. 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
  101. 101. Creating Classes • Syntax: • Example: 1/7/2021 Python for IoT 101
  102. 102. Example: 1/7/2021 Python for IoT 102
  103. 103. Creating Objects 1/7/2021 Python for IoT 103
  104. 104. Example 1/7/2021 Python for IoT 104
  105. 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
  106. 106. Example: 1/7/2021 Python for IoT 106
  107. 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. 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
  109. 109. 1/7/2021 Python for IoT 109
  110. 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
  111. 111. Syntax 1/7/2021 Python for IoT 111
  112. 112. Example1 1/7/2021 Python for IoT 112
  113. 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. 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
  115. 115. HTTPLib Example 1/7/2021 Python for IoT 115
  116. 116. HTTP Lib • Resp contains response headers • Content contains the content retrieved from the URL. 1/7/2021 Python for IoT 116
  117. 117. URLLib 1/7/2021 Python for IoT 117
  118. 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
  119. 119. SMTPLib 1/7/2021 Python for IoT 119
  120. 120. SMTPLib (Contd.,) 1/7/2021 Python for IoT 120
  121. 121. Programming in Python: Sample Codes
  122. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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: ?
  132. 132. Thank You 1/7/2021 Python for IoT 132

×