Unit III Iiot
Unit III Iiot
Introduction to
Python
What is Computer Program?
Java Mostly used for developing Android apps, web apps, and Big data.
Javascript JavaScript usage include web/mobile app development, game development, and desktop app
development.
C++ C++ is widely used in Game Development, Advance Computations, and Graphics Compilers
Python is a high-level
It is a language that enables a programmer to
write programs that are more or less independent of a particular
type of computer. Such languages are considered as closer to
human languages and further from machine languages.
Python is Interpreted
Python is processed at runtime by the interpreter. We do not need to
compile our program before executing it. This is similar to PERL and
PHP.
Python is Interactive
You can actually sit at a Python prompt and
interact with the interpreter directly to write your
programs.
Python is Object-Oriented
Python is an object-oriented language .It allows
us to develop applications using an Object-
Oriented approach. In Python, we can easily
create and use classes and objects.
Python is scripting language:
A scripting language is used to write scripts. These contain a series of commands that are
interpreted one by one at runtime unlike programming languages that are compiled first
before running
Programming languages based applications are run by compiler
Programming languages based applications are required explicit compilation
Programming languages based applications can’t run directly without
compilation.
Ex: C,C++,JAVA .NET
These languages are run by compiler
Python is said to have succeeded is ABC Programming Language, which had the interfacing
with the Amoeba Operating System.
Python is derived from many other languages, including ABC, Modula-3, C, C++,Algol-68,
SmallTalk, and Unix shell and other scripting languages
Here interesting fact is- Python is named after the BBC TV comedy show Monty
5. Interpreted
6. Object-Oriented
7. Embeddable
– Python is very easy to code. Compared to other popular languages like Java
and C++ . Anyone can learn python syntax in just a few hours.
b. Easy to read:
– Being a high-level language, Python code is quite like English. Looking at it, you
can tell what the code is supposed to do.
Firstly, Python is freely available. You can download it from the following link
https://www.python.org/downloads/.
Secondly, it is open-source. This means that its source code is available to the
public. You can download it, change it, use it, and distribute it. This is called
FLOSS(Free/Libre and Open Source Software).
3. High- Level
4. Portable
We can take one code and run it on any machine, there is no
need to write different code for different machines. This
makes Python a portable language. However, you must avoid
any system-dependent features in this case.
5. Interpreted:
If you’re any familiar with languages like C++ or Java, you must first
compile it, and then run it. But in Python, there is no need to
compile it. Internally, its source code is converted into an
immediate form called byte code.
So, all you need to do is to run your Python code without worrying
about linking to libraries, and a few other things.
Object-oriented programming (OOP) is nothing but that which allows the writing of programs
with the help of certain classes and real-time objects.
We can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
CPython is a python integrated with C/C++ language.
Similarly JPython is a purely integrated language.
4) Business Applications
7) 3D CAD Applications
8) Enterprise Applications
9) Image applications
1) Web Applications
We can use Python to develop web applications. It provides libraries to
handle internet protocols such as HTML and XML, JSON, Email processing etc.
It also provides Frameworks such as Django, Pyramid, Flask etc to design and
develop web based applications. Some important developments are:
PythonWikiEngines, Pocoo, PythonBlogSoftware etc.
Some other useful toolkits wxWidgets, Kivy, pyqt that are useable on several
platforms. The Kivy is popular for writing multitouch applications.
3) Software Development
Python is helpful for software development process. It works as a support language and
can be used for build control and management, testing etc.
5) Business Applications
Python is used to build Business applications like ERP and e-commerce systems.
Tryton is a high level application platform.
8) 3D CAD Applications
To create CAD application Fandango is a real application which provides full features of
CAD.
9) Enterprise Applications
Python can be used to create applications which can be used within an Enterprise or an
Organization.
Some real time applications are: OpenErp, Tryton, Picalo etc.
2. Less Coding: The syntax written in python is very simple and use common English
language which makes it more user-friendly.
3. Efficient: Python relies on indentation, using white space, to define scope; such as
the scope of loops, functions, and classes. Other Programming Languages use curly-
brackets for this purpose.
4. Portability: Python can run any operating system. Also, we use the Python Code
written on one system onto another system without making any changes to the code.
Existing Programming Vs Python Programming:
C, c++ ,java , python program to find addition of two numbers
scanf("%d %d", &a, &b); cout << "Enter two integers: ";
cin >> firstNumber >> secondNumber;
sum = a + b;
sumOfTwoNumbers = firstNumber + secondNumber;
printf("Sum : %d", sum);
cout << firstNumber << " + " << secondNumber << " = " << sumOfTwoNumbers;
return(0);
return 0;
}
}
--------java program--------
--------python program--------
public class AddTwoNumbers {
num1 = 1.5; num2 = 6.3
public static void main(String[] args) {
sum = num1 + num2
int num1 = 5, num2 = 15, sum;
print('The sum of two numbers”, sum))
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}
1. Data Types in Python
Data Structures in Python
• What is a Data Structure?
• Organizing, managing and storing data is
important as it enables easier access and
efficient modifications.
1) Lists:
• Lists are used to store data of different data types in a
sequential manner.
Output:
[]
[1, 2, 3, ‘example’, 3.132]
Adding Elements
my_list = [1, 2, 3]
print(my_list)
my_list.append([555, 12]) #add as a single element
print(my_list)
my_list.extend([234, 'more_example']) #add as different elements
print(my_list)
my_list.insert(1, 'insert_example') #add element i
print(my_list)
Output:
[1, 2, 3]
[1, 2, 3, [555, 12]]
[1, 2, 3, [555, 12], 234, ‘more_example’]
[1, ‘insert_example’, 2, 3, [555, 12], 234, ‘more_example’]
Deleting Elements
Output:
Output:
1
2
3
example
3.132
10
30
[1, 2, 3, ‘example’, 3.132, 10, 30]
example
[1, 2]
[30, 10, 3.132, ‘example’, 3, 2, 1]
Other Functions
Output:
6
3
2
[1, 2, 3, 10, 10, 30]
[30, 10, 10, 3, 2, 1]
Dictionary
― Now the constant values here are Name and the Phone Numbers which are
called as the keys.
― And the various names and phone numbers are the values that have been fed to
the keys.
― If you access the values of the keys, you will obtain all the names and phone
numbers.
― So that is what a key-value pair is. And in Python, this structure is stored using
Dictionaries.
Creating a Dictionary
Output:
{}
{1: ‘Python’, 2: ‘Java’}
Changing and Adding key, value pairs
• To change the values of the dictionary, you need to do that using the
keys. So, you firstly access the key and then change the value
accordingly. To add values, you simply just add another key-value pair as
shown below.
Output:
{‘First’: ‘Python’, ‘Second’: ‘Java’}
{‘First’: ‘Python’, ‘Second’: ‘C++’}
{‘First’: ‘Python’, ‘Second’: ‘C++’, ‘Third’: ‘Ruby’}
Deleting key, value pairs
• To delete the values, you use the pop() function which returns the value that has been deleted.
• To retrieve the key-value pair, you use the popitem() function which returns a tuple of the key and
value.
• To clear the entire dictionary, you use the clear() function.
Output:
Value: Ruby
Dictionary: {‘First’: ‘Python’, ‘Second’: ‘Java’}
Key, value pair: (‘Second’, ‘Java’)
Dictionary {‘First’: ‘Python’}
{}
Accessing Elements
Output:
Python
Java
Other Functions
Output:
dict_keys([‘First’, ‘Second’, ‘Third’])
dict_values([‘Python’, ‘Java’, ‘Ruby’])
dict_items([(‘First’, ‘Python’), (‘Second’, ‘Java’), (‘Third’, ‘Ruby’)])
Python
Tuple
• Tuple are the same as lists are with the exception that the data
once entered into the tuple cannot be changed no matter what.
• The only exception is when the data inside the tuple is mutable,
only then the tuple data can be changed.
Creating a Tuple:
Output:
(1, 2, 3)
Accessing Elements
Output:
1
2
3
Bharath
(1, 2, 3, ‘Bharath’)
1
(1, 2, 3, ‘Bharath’)
a
Appending Elements
my_tuple = (1, 2, 3)
my_tuple = my_tuple + (4, 5, 6) #add elements
print(my_tuple)
• Output:
(1, 2, 3, 4, 5, 6)
Other Functions
• Output:
(1, 2, 3, [‘english’, ‘python’])
1
3
Sets
• Output:
{1, 2, 3, 4, 5}
Adding elements
my_set = {1, 2, 3}
my_set.add(4) #add element to set
print(my_set)
• Output:
{1, 2, 3, 4}
Operations in sets
my_set = {1, 2, 3, 4}
my_set_2 = {3, 4, 5, 6}
print(my_set.union(my_set_2), '----------', my_set |
my_set_2)
print(my_set.intersection(my_set_2), '----------', my_set &
my_set_2)
print(my_set.difference(my_set_2), '----------', my_set -
my_set_2)
print(my_set.symmetric_difference(my_set_2), '----------',
my_set ^ my_set_2)
my_set.clear()
print(my_set)
• Output:
{1, 2, 3, 4, 5, 6} ———- {1, 2, 3, 4, 5, 6}
{3, 4} ———- {3, 4}
{1, 2} ———- {1, 2}
{1, 2, 5, 6} ———- {1, 2, 5, 6}
set()
• The intersection() function finds the data present in both sets only.
1) Arrays:
• The root is the node from where the data originates and
the nodes are the other data points that are available to
us.
• The node that precedes is the parent and the node after is
called the child.
• Many applications such as Google Maps, Uber, and many more use
Graphs to find the least distance and increase profits in the best
ways.
HashMaps
• Syntax of the if statement:
if condition:
statement 1
statement 2
statement n
Example:
number = 6
if number > 5:
print(number * number) # Calculate square
print('Next lines of code')
Output
36
Next lines of code
2) If – else statement
Syntax of the if-else statement:
if condition:
statement 1
else:
statement 2
Flow chart of if-else statement
Example:
password = input('Enter password ')
if password == “Mrecw@123":
print("Correct password")
else:
print("Incorrect Password")
Output 1:
Enter password Mrecw@123
Correct password
Output 2:
Enter password Mrecw@12
Incorrect Password
3) if-elif-else statement
• Syntax of the if-elif-else statement:
if condition-1:
statement 1
elif condition-2:
stetement 2
elif condition-3:
stetement 3
...
else: statement
Example:
def user_check(choice):
if choice == 1: Output:
print("Admin") Admin
elif choice == 2: Editor
print("Editor") Guest
elif choice == 3: Wrong entry
print("Guest")
else: print("Wrong entry")
user_check(1)
user_check(2)
user_check(3)
user_check(4)
4) Nested if-else statement
if conditon_outer:
if condition_inner:
statement of inner if
else:
statement of inner else:
statement of outer if
else:
Outer else
statement outside if block
Example: Find a greater number between two
numbers
Output 2:
Enter first number 29
Enter second number 78
29 is smaller than 78
Single statement suites
Example: Example:
x=1
number = 56 while x <= 5:
if number > 0: print(x,end=" ");
print("positive") x = x+1
else:
print("negative") Output
12345
Iterative statements
num = 10
sum = 0
i=1
while i <= num:
sum = sum + I
i=i+1
print("Sum of first 10 number is:", sum)
Output
Sum of first 10 number is: 55
Transfer statements
• break statement
• continue statement
• pass statements
1) Break Statement
Example of a continue statement:
for num in range(3, 8):
Output:
if num == 5: 3
continue 4
6
else:
7
print(num)
3) Pass statement
Output:
['January', 'June', 'March', 'April']
Python Functions
• Arguments are the values passed inside the parenthesis of the function.
• A function can have any number of arguments separated by a comma.
Python supports various types of arguments that can be passed at the time of
the function call.
1) Default arguments:
# A simple module
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)
Import Module in Python – Import statement
Syntax:
import module
• When the interpreter encounters an import statement, it imports
the module if the module is present in the search path.
Output:
12
Python Packages
Creating Package:
• Let’s create a package named mypckg that will contain two
modules mod1 and mod2. To create this module follow the
below steps –
– Create a folder named mypckg.
– Inside this folder create an empty Python file i.e. __init__.py
– Then create two modules mod1 and mod2 in this folder.
Mod1.py
def gfg():
print("Welcome to MRECW")
Mod2.py
def sum(a, b):
return a+b
Output:
Welcome to MRECW
3
File Handling in Python
• Python too supports file handling and allows users to handle files
i.e., to read and write files, along with many other file handling
options, to operate on files.
• It ends the current line and tells the interpreter a new one has
begun.
Opening of a File
• Before performing any operation on the file like read or write, first we have
to open that file. For this, we should use Python’s inbuilt function open().
• But at the time of opening, we have to specify the mode, which represents
the purpose of the opening file.
• f = open(filename, mode)
Output:
Exceptions: Exceptions are raised when the program is syntactically
correct, but the code resulted in an error. This error does not stop the
execution of the program, however, it changes the normal flow of the
program.
Example:
# initialize the amount variable
marks = 10000
# perform division with 0
a = marks / 0
print(a)
Output:
Try and Except Statement – Catching Exceptions
Try and except statements are used to catch and handle exceptions in Python.
Statements that can raise exceptions are kept inside the try clause and the
statements that handle the exception are written inside except clause.
Example: Let us try to access the array element whose index is out of bound and handle
the corresponding exception.
# Python program to handle simple runtime error
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
# Throws error since there are only 3 elements in array
print ("Fourth element = %d" %(a[3]))
except:
print ("An error occurred")
Output:
Second element = 2
An error occurred
Python Packages
Python Packages of Interest for IoT are
1) JSON
2) XML
3) HTTPLib
4) URLLib
5) SMTPLib
1) JSON:
• JavaScript Object Notation (JSON) is an easy to read and write data-
interchange format.
2) XML :
• XML (Extensible Markup Language) is a data format for structured
document interchange.
4) SMTPLib:
• Simple Mail Transfer Protocol (SMTP) is a protocol
which handles sending email and routing email
between mail servers.