Iot Unit - III Notes
Iot Unit - III Notes
What is Python?
History of Python
Python was created by Guido van Rossum. In the late 1980s, Guido van Rossum, a
Dutch programmer, began working on Python while at the Centrum Wiskunde & Informatica
(CWI) in the Netherlands. He wanted to create a successor to the ABC programming
language that would be easy to read and efficient.
In February 1991, the first public version of Python, version 0.9.0, was
released. This marked the official birth of Python as an open-source project. The language
was named after the British comedy series "Monty Python's Flying Circus".
VMTW Page | 1
Internet of Things II – I JNTUH-R22
Python development has gone through several stages. In January 1994, Python 1.0 was
released as a usable and stable programming language. This version included many of the
features that are still present in Python today.
From the 1990s to the 2000s, Python gained popularity for its simplicity, readability,
and versatility. In October 2000, Python 2.0 was released. Python 2.0 introduced list
comprehensions, garbage collection, and support for Unicode.
In December 2008, Python 3.0 was released. Python 3.0 introduced several backward-
incompatible changes to improve code readability and maintainability.
The Python Software Foundation (PSF) was established in 2001 to promote, protect,
and advance the Python programming language and its community.
VMTW Page | 2
Internet of Things II – I JNTUH-R22
Python is Easy to Learn and Use: There is no prerequisite to start Python, since it is
Ideal programming language for beginners.
High Level Language: Python don’t let you worry about low-level details, like
memory management, hardware-level operations etc.
Extensive Library is Available: Python has huge set of library and modules, which
can make development lot easier and faster.
Cross Platform: Same Python code can run on Windows, macOS and Linux, without
any modification in code.
Good Career Opportunities: Python is in high demand across industries like Software
development, AI, finance, and cloud computing etc.
VMTW Page | 3
Internet of Things II – I JNTUH-R22
☞ Project Oriented Learning: You can start making simple projects while learning
For Experienced:
☞ Easy Career Transition: If you know any other programming language, moving to
learning Python can help you integrate advanced features like AI in your projects.
Limitation of Python:
Performance Limitations: Python is an interpreted language which makes it slower
than compiled languages like C++ or Java.
Not preferred for Mobile Apps and Front End: Python isn’t preferred for Front End
dev or mobile apps because of slower execution speeds and limited frameworks
compared to JavaScript or Swift.
VMTW Page | 4
Internet of Things II – I JNTUH-R22
Memory Expensive: Python consumes more memory because of its high-level nature
and dynamic typing.
Lack of Strong Typing: Dynamic typing makes Python easy to code, but it can lead to
runtime errors that would be caught at compile time in statically typed languages like
Java or C#.
Not Suitable for Game development: Python lacks the high speed and low-level
hardware control needed for game engines.
Python is an excellent choice for rapid development and scripting tasks. Whereas Java
emphasizes a strong type system and object-oriented programming.
Here are some basic programs that illustrates key differences between them.
Python Code:
print("Hello World!")
Output:
Hello, World!
In Python, it is one line of code. It requires simple syntax to print 'Hello World'
Java Code:
VMTW Page | 5
Internet of Things II – I JNTUH-R22
Output:
Hello, World!
While both programs give the same output, we can notice the syntax difference in the print
statement.
o In Python, it is easy to learn and write code. While in Java, it requires more code to
perform certain tasks.
o Python is dynamically typed, meaning we do not need to declare the variable Whereas
Java is statistically typed, meaning we need to declare the variable type.
o Python is suitable for various domains such as Data Science, Machine Learning, Web
development, and more. Whereas Java is suitable for web development, mobile app
development (Android), and more.
Python print() function is used to display output to the console or terminal. It allows us to
display text, variables and other data in a human readable format.
Syntax:
It takes one or more arguments separated by comma(,) and adds a 'newline' at the end by
default.
Parameters:
o object(s) - As many as you want data to display, will first converted into string and
printed to the console.
o sep - Separates the objects by a separator passed, default value = " ".
VMTW Page | 6
Internet of Things II – I JNTUH-R22
Example:
# Displaying a string
print("Hello, World!")
Hello, World!
Name: Aman Age: 21
X = 5 y = 7 Sum = 12
Score: 85.75%
In this example, the print statement is used to print string, integer, and float values in a human
readable format.
The print statement can be used for debugging, logging and to provide information to the user.
VMTW Page | 7
Internet of Things II – I JNTUH-R22
x = 10
y=5
if x > y:
print("x is greater than y")
else:
print("y is greater than or equal to x")
Output:
x is greater than y
In the above code, we have two variables, x, and y, with 10 and 5, respectively. Then we
used an if..else statement to check if x is greater than y or vice versa. If the first condition is true,
the statement "x is greater than y" is printed. If the first condition is false, the statement "y is
greater than or equal to x" is printed instead.
The if keyword checks the condition is true and executes the code block inside it. The
code inside the else block is executed if the condition is false. This way, the if..else statement
helps us to execute different blocks of code based on a condition.
We will learn about this in more detail in the further article for the Python tutorial.
VMTW Page | 8
Internet of Things II – I JNTUH-R22
Python Loops
Sometimes we may need to alter the flow of the program. The execution of a specific
code may need to be repeated several times. For this purpose, the programming languages
provide various loops capable of repeating some specific code several times. Consider the
following tutorial to understand the statements in detail.
i=1
while i<5:
print(i, end=" ")
i += 1
Output:
1234
In the above example code, we have demonstrated using two types of loops in Python -
For loop and While loop.
The For loop is used to iterate over a sequence of items, such as a list, tuple, or string. In
the example, we defined a list of fruits and used a for loop to print each fruit, but it can also be
used to print a range of numbers.
VMTW Page | 9
Internet of Things II – I JNTUH-R22
The While loop repeats a code block if the specified condition is true. In the example, we
have initialized a variable i to 1 and used a while loop to print the value of i until it becomes
greater than or equal to 6. The i += 1 statement is used to increment the value of i in each
iteration.
Python offers four built-in data structures: lists, tuples, sets, and dictionaries that
allow us to store data in an efficient way. Below are the commonly used data structures in
Python, along with example code:
1. Lists
Example:
# Create a list
fruits = ['apple', 'banana', 'cherry']
print("fuirts[1] =", fruits[1])
# Modify list
fruits.append('orange')
print("fruits =", fruits)
num_list = [1, 2, 3, 4, 5]
# Calculate sum
sum_nums = sum(num_list)
print("sum_nums =", sum_nums)
VMTW Page | 10
Internet of Things II – I JNTUH-R22
Output:
fuirts[1] = banana
fruits = ['apple', 'banana', 'cherry', 'orange']
sum_nums = 15
2. Tuples
o Tuples are also ordered collections of data elements of different data types, similar to
Lists.
o Elements can be accessed using indices.
o Tuples are immutable meaning Tuples can't be modified once created.
o They are defined using open bracket '()'.
Example:
# Create a tuple
point = (3, 4)
x, y = point
print("(x, y) =", x, y)
(x, y) = 3 4
Tuple = ('apple', 'banana', 'cherry', 'orange')
VMTW Page | 11
Internet of Things II – I JNTUH-R22
3. Sets
o Sets are unordered collections of immutable data elements of different data types.
o Sets are mutable.
o Elements can't be accessed using indices.
o Sets do not contain duplicate elements.
o They are defined using curly braces '{}'
Example:
# Create a set
set1 = {1, 2, 2, 1, 3, 4}
print("set1 =", set1)
set1 = {1, 2, 3, 4}
set2 = {'apple', 'cherry', 'orange', 'banana'}
4. Dictionaries
o Dictionaries are key-value pairs that allow you to associate values with unique keys.
o They are defined using curly braces '{}' with key-value pairs separated by colons ':'.
o Dictionaries are mutable.
o Elements can be accessed using keys.
Example:
# Create a dictionary
person = {'name': 'Umesh', 'age': 25, 'city': 'Noida'}
VMTW Page | 12
Internet of Things II – I JNTUH-R22
# Modify Dictionary
person['age'] = 27
print("person =", person)
Output:
These are just a few examples of Python's built-in data structures. Each data structure has
its own characteristics and use cases.
This section of the Python tutorial defines some important tools related to functional
programming, such as lambda and recursive functions. These functions are very efficient in
accomplishing complex tasks. We define a few important functions, such as reduce, map, and
filter. Python provides the functools module that includes various functional programming tools.
Visit the following tutorial to learn more about functional programming.
Recent versions of Python have introduced features that make functional programming
more concise and expressive. For example, the "walrus operator":= allows for inline variable
assignment in expressions, which can be useful when working with nested function calls or list
comprehensions.
VMTW Page | 13
Internet of Things II – I JNTUH-R22
Python Function:
1. Lambda Function - A lambda function is a small, anonymous function that can take
any number of arguments but can only have one expression. Lambda functions are often
used in functional programming to create functions "on the fly" without defining a named
function.
2. Recursive Function - A recursive function is a function that calls itself to solve a
problem. Recursive functions are often used in functional programming to perform
complex computations or to traverse complex data structures.
3. Map Function - The map() function applies a given function to each item of an iterable
and returns a new iterable with the results. The input iterable can be a list, tuple, or other.
4. Filter Function - The filter() function returns an iterator from an iterable for which the
function passed as the first argument returns True. It filters out the items from an iterable
that do not meet the given condition.
5. Reduce Function - The reduce() function applies a function of two arguments
cumulatively to the items of an iterable from left to right to reduce it to a single value.
6. functools Module - The functools module in Python provides higher-order functions that
operate on other functions, such as partial() and reduce().
7. Currying Function - A currying function is a function that takes multiple arguments and
returns a sequence of functions that each take a single argument.
8. Memoization Function - Memoization is a technique used in functional programming to
cache the results of expensive function calls and return the cached Result when the same
inputs occur again.
9. Threading Function - Threading is a technique used in functional programming to run
multiple tasks simultaneously to make the code more efficient and faster.
Python Modules:
Python modules are the program files that contain Python code or functions. Python has
two types of modules - User-defined modules and built-in modules. A module the user defines,
or our Python code saved with .py extension, is treated as a user-define module.
VMTW Page | 14
Internet of Things II – I JNTUH-R22
Built-in modules are predefined modules of Python. To use the functionality of the
modules, we need to import them into our current working program.
Python modules are essential to the language's ecosystem since they offer reusable code
and functionality that can be imported into any Python program. Here are a few examples of
several Python modules, along with a brief description of each:
Math: Gives users access to mathematical constants and pi and trigonometric functions.
Datetime: Provides classes for a simpler way of manipulating dates, times, and periods.
OS: Enables interaction with the base operating system, including administration of processes
and file system activities.
Random: The random function offers tools for generating random integers and picking random
items from a list.
JSON: JSON is a data structure that can be encoded and decoded and is frequently used in
online APIs and data exchange. This module allows dealing with JSON.
Re: Supports regular expressions, a potent text-search and text-manipulation tool.
Collections: Provides alternative data structures such as sorted dictionaries, default dictionaries,
and named tuples.
NumPy: NumPy is a core toolkit for scientific computing that supports numerical operations on
arrays and matrices.
Pandas: It provides high-level data structures and operations for dealing with time series and
other structured data types.
Requests: Offers a simple user interface for web APIs and performs HTTP requests.
VMTW Page | 15
Internet of Things II – I JNTUH-R22
Files are used to store data in a computer disk. In this tutorial, we explain the built-in file
object of Python. We can open a file using Python script and perform various operations such as
writing, reading, and appending. There are various ways of opening a file. We are explained with
the relevant example. We will also learn to perform read/write operations on binary files.
Python's file input/output (I/O) system offers programs to communicate with files stored on a
disc. Python's built-in methods for the file object let us carry out actions like reading, writing,
and adding data to files.
The open() method in Python makes a file object when working with files. The name of the file
to be opened and the mode in which the file is to be opened are the two parameters required by
this function. The mode can be used according to work that needs to be done with the file, such
as "r" for reading, "w" for writing, or "a" for attaching.
After successfully creating an object, different methods can be used according to our
work. If we want to write in the file, we can use the write() functions, and if you want to read and
write both, then we can use the append() function and, in cases where we only want to read the
content of the file we can use read() function. Binary files containing data in a binary rather than
a text format may also be worked with using Python. Binary files are written in a manner that
humans cannot directly understand. The rb and wb modes can read and write binary data in
binary files.
Python Exceptions
Whenever an exception occurs, the program stops the execution, and thus the other code
is not executed. Therefore, an exception is the run-time errors that are unable to handle to Python
script. An exception is a Python object that represents an error.
VMTW Page | 16
Internet of Things II – I JNTUH-R22
Python Exceptions are an important aspect of error handling in Python programming. When a
program encounters an unexpected situation or error, it may raise an exception, which can
interrupt the normal flow of the program.
In Python, exceptions are represented as objects containing information about the error,
including its type and message. The most common type of Exception in Python is the Exception
class, a base class for all other built-in exceptions.
To handle exceptions in Python, we use the try and except statements. The try statement is used
to enclose the code that may raise an exception, while the except statement is used to define a
block of code that should be executed when an exception occurs.
try:
x = int ( input ("Enter a number: "))
y = 10 / x
print ("Result:", y)
except ZeroDivisionError:
print ("Error: Division by zero")
except ValueError:
print ("Error: Invalid input")
Output:
Enter a number: 0
Error: Division by zero
In this code, we use the try statement to attempt to perform a division operation. If either
of these operations raises an exception, the matching except block is executed.
VMTW Page | 17
Internet of Things II – I JNTUH-R22
Python also provides many built-in exceptions that can be raised in similar situations.
Some common built-in exceptions include IndexError, TypeError, and NameError. Also, we
can define our custom exceptions by creating a new class that inherits from the Exception class.
INTRODUCTION:
The Raspberry Pi is a credit card-sized computer with an ARM processor that can run
Linux. This item is the Raspberry Pi 3 Model B+, which has 1 GB of RAM, dual-band Wi-Fi,
Bluetooth 4.2, Bluetooth Low Energy (BLE), an Ethernet port, HDMI output, audio output, RCA
composite video output (through the 3.5 mm jack), four USB ports, and 0.1″-spaced pins that
provide access to general purpose inputs and outputs (GPIO). The Raspberry Pi requires a
microSD card with an operating system on it (not included).
Overview:
VMTW Page | 18
Internet of Things II – I JNTUH-R22
The Raspberry Pi 3 Model B+ has many performance improvements over the Model
B including a faster CPU clock speed (1.4 GHz vs 1.2 GHz), increased Ethernet throughput, and
dual-band WiFi. It also supports Power over Ethernet with a Power over Ethernet HAT (not
included). The MagPi Magazine has a blog post with performance benchmarks comparing various
Raspberry Pi models.
The dual-band wireless LAN comes with modular compliance certification, allowing the
board to be designed into end products with significantly reduced wireless LAN compliance
testing, improving both cost and time to market.
Features:
VMTW Page | 19
Internet of Things II – I JNTUH-R22
1 GB RAM
Ethernet port
dual-band (2.4 GHz and 5 GHz) IEEE 802.11.b/g/n/ac wireless LAN (WiFi)
Bluetooth 4.2
Four-pole 3.5 mm jack with audio output and composite video output
40-pin GPIO header with 0.1″-spaced male pins those are compatible with our 2×20
stackable female headers and the female ends of our premium jumper wires.
Camera interface (CSI)
VMTW Page | 20
Internet of Things II – I JNTUH-R22
The Raspberry Pi has a number of ports which you will use to control the Raspberry Pi, and it
can use to control other devices. Your Raspberry Pi will have the following ports:
USB – USB ports are used to connect a wide variety of components, most commonly a
mouse and keyboard.
HDMI – The HDMI port outputs video and audio to your monitor.
Audio – The audio jack allows you to connect standard headphones and speakers.
Micro USB – The Micro USB port is only for power, do not connect anything else to this
port. Always connect the power after you have already connected everything else.
GPIO – The GPIO ports allow the Raspberry Pi to control and take input from any
electronic component.
SD card slot – The Raspberry Pi uses SD cards the same way a full-size computer uses a
hard drive. The SD card provides the Raspberry Pi with internal memory, and stores the
hard drive.
VMTW Page | 21
Internet of Things II – I JNTUH-R22
RASPBERRY PI PINOUT:
VMTW Page | 22
Internet of Things II – I JNTUH-R22
The following table shows the Raspberry Pi pinout, it shows all GPIOs, their
corresponding physical pin numbers, their Broadcom numbering, and corresponding features.
VMTW Page | 23
Internet of Things II – I JNTUH-R22
GPIO 27 13 14 GND
GPIO 22 15 16 GPIO 23
GPIO 5 29 30 GND
VMTW Page | 24
Internet of Things II – I JNTUH-R22
The Raspberry Pi comes with two 3.3V pins (pins number 1 and 17) and two 5V pins (pins 2 and
4).
Additionally, there are eight GND pins (pins number: 6, 9, 14, 20, 25, 30, 34, and 39).
Out of the 40 Raspberry Pi GPIOs, 11 are power or GND pins. Besides that, there are two
reserved pins (pins 27 and 28) for I2C communication with an EEPROM (learn more about this).
So, this left us with 16 GPIOs that you can use to connect peripherals. These GPIOs can be used
either as inputs or outputs. Additionally, some of them support specific communication
protocols.
SPI stands for Serial Peripheral Interface, and it is a synchronous serial data protocol used by
microcontrollers to communicate with one or more peripherals. This communication protocol
allows you to connect multiple peripherals to the same bus interface, as long as each is connected
to a different chip select pin.
VMTW Page | 25
Internet of Things II – I JNTUH-R22
For example, your Raspberry Pi board can communicate with a sensor that supports SPI, another
Raspberry Pi, or a different microcontroller board. These are the Raspberry Pi SPI pins:
MOSI: GPIO 10
MISO: GPIO 9
CLOCK: GPIO 11
CE0 (chip select): GPIO 8
CE1 (chip select): GPIO 7
The UART pins can be used for Serial communication. The Raspberry Pi Serial (UART) pins
are:
TX: GPIO 14
RX: GPIO 15
PWM stands for Pulse Width Modulation and it is used to control motors, define varying levels
of LED brightness, define the color of RGB LEDs, and much more.
The Raspberry Pi has 4 hardware PWM pins: GPIO 12, GPIO 13, GPIO 18, GPIO 19.
You can have software PWM on all pins.
The Raspberry Pi supports one-wire on all GPIOs, but the default is GPIO4.
VMTW Page | 26
Internet of Things II – I JNTUH-R22
The Raspberry Pi comes with PCM (pulse-code Modulation) pins for digital audio output. These
are the PCM pins:
Din: GPIO 20
Dout: GPIO 21
FS: GPIO 19
CLK: GPIO 18
I2C EEPROM:
Pins 27 and 28 (GPIO 0 and GPIO 1) are reserved for connecting a HAT ID EEPROM.
Do not use these pins unless you’re using an I2C ID EEPROM. Leave unconnected if you’re not
using an I2C EEPROM.
VMTW Page | 27