Iot Unit Iii R22.
Iot Unit Iii R22.
Iot Unit Iii R22.
if else statement.
If True:
Print(“Correct”)
Else
Print(“Error”)
if true then colon you have an indentation print ‘correct’ else then again you go back
else colon again indent print ‘error’.
So, this indentation policy has to be followed whenever you enter into a loop. So,
after one statement or this colon you have to give one tab space indentation.
In Python programming, the “else if” statement, often called “elif,” is a conditional
statement that allows you to specify multiple conditions to be evaluated sequentially.
It provides a way to execute different code blocks based on various conditions. The
“else if” statement is used when you have multiple mutually exclusive requirements
and want to perform other actions depending on the valid state.
1. Numbers
2. String
3. List
4. Tuple
5. Dictionary
1. Numbers
Numbers in Python refer to the numeric data types in Python programming.
Python supports three kinds of numeric data types: int, float, and complex.
Integers are numbers without decimal points.
num=5
type(num)
num=23475891
type(num)
num=5.4
type(num)
Complex numbers have real parts and imaginary parts.
num=2+5j
type(num)
Complex numbers store the real and imaginary parts as a float by default.
num=-423.31
print(num)
2. Strings
A string is a sequence of characters that can be a combination of letters,
numbers, and special characters. It can be declared in python by using single
quotes, double quotes, or even triple quotes.
a = 'This is a string'
print (a)
b = "This is a string"
print (b)
c= '''This is a string'''
print (c)
3. List
Lists are one of the most powerful data structures in python. Lists are
sequenced data types. In Python, an empty list is created using list()
function. They are just like the arrays declared in other languages. But the
most powerful thing is that list need not be always homogeneous. A single
list can contain strings, integers, as well as other objects.
# Declaring a list
L = [1, "a" , "string" , 1+2]
print L
#Adding an element in the list
L.append(6)
print L
#Deleting last element from a list
L.pop()
print (L)
#Displaying Second element of the list
print (L[1])
4. Tuples
A tuple is a sequence of immutable Python objects. Tuples are just like lists
with the exception that tuples cannot be changed once declared. Tuples are
usually faster than lists.
print(tup[1])
5. Dictionary:
A dictionary in Python is a data structure that stores the value in value:key pairs.
Example:
As you can see from the example, data is stored in key:value pairs in dictionaries,
which makes it easier to find values.
Python3
Controlling Statements
Control statements in Python are a powerful tool for managing the flow of
execution. They allow developers to make decisions based on specific
conditions and modify the normal sequential flow of a program. By using
control statements effectively, developers can write more efficient and
effective code.
The break statement is used to terminate a loop, i.e., for loop, while loop, or nested
loop. When a break statement executes inside a loop, it immediately terminates the
loop and transfers control to the statement following the loop.
while condition:
# statements
if condition:
break
In this syntax, the break statement is used inside a loop (while loop or for
loop). When the condition specified in the if statement is true, the break
statement is executed, and the control is transferred to the next statement
after the loop. This means that the loop is terminated, and the code
execution continues from the statement after the loop.
Python
Output:
Explanation:
In this example, we have a list called list_of_numbers. We want to find the
first even number in this list. We use a for loop to iterate over the list, and
inside the loop, we use an if statement to check if the current number is
even. If the current number is even, we print it as the first even number, and
we use the break statement to exit the loop.
The continue statement is used to skip a particular iteration of a loop when a specific
condition is met. When a continue statement is executed inside a loop, it skips the
current iteration of the loop and jumps to the next iteration.
while condition:
# statements before the continue statement
if condition:
continue
# statements after the continue statement
In this syntax, when the condition specified in the if statement is true, the
continue statement is executed, and the control is transferred to the next
iteration of the loop. This means that the current iteration is skipped, and the
loop continues with the next iteration.
Python
Output:
1
3
7
9
11
15
Explanation: We have a list of integers called numbers. Only the odd
numbers from this list should be printed. We use a for loop to traverse
through the list, and an if statement inside the loop checks if the current
number is even. If the current number is an even integer, we apply the
continue statement to skip the current iteration and proceed to the next. We
print the current number if it is odd.
while condition:
# statements before the pass statement
if condition:
pass
In this syntax, the pass statement is used inside a loop (while loop or for
loop) and inside an if statement. When the pass statement is executed, it
does nothing, and the control is transferred to the next statement after the
loop or the if statement.
Python Functions
Python Functions is a block of statements that return the specific task. The idea is to
put some commonly or repeatedly done tasks together and make a function so that
instead of writing the same code again and again for different inputs, we can do the
function calls to reuse code contained in it over and over again.
def function_name(parameters):
function body
Example
def hello_world_func():
print("hello world")
Function blocks begin with the keyword def followed by the function
name and parentheses ( ( ) ).
Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform
them in the same order that they were defined.
Once the function is defined, you can execute it by calling it from another
function or directly from the Python prompt.
Example
The following example shows how to define a function greetings(). The
bracket is empty so there aren't any parameters.
The first line is the docstring. Function block ends with return statement.
when this function is called, Hello world message will be printed.
def greetings():
"This is docstring of greetings function"
print ("Hello World")
return
greetings()
Function Arguments
The process of a function often depends on certain data provided to it while
calling it. While defining a function, you must give a list of variables in
which the data passed to it is collected. The variables in the parentheses are
called formal arguments.
When the function is called, value to each of the formal arguments must be
provided. Those are called actual arguments.
Example
Let's modify greetings function and have name an argument. A string passed
to the function as actual argument becomes name variable inside the
function.
def greetings(name):
"This is docstring of greetings function"
print ("Hello {}".format(name))
return
greetings("Samay")
greetings("Pratima")
greetings("Steven")
It will produce the following output −
Hello Samay
Hello Pratima
Hello Steven
Example
Let us define the add() function. It adds the two values passed to it and
returns the addition. The returned value is stored in a variable called result.
def add(x,y):
z=x+y
return z
a=10
b=20
result = add(a,b)print ("a = {} b = {} a+b = {}".format(a, b, result))
It will produce the following output −
a = 10 b = 20 a+b = 30
A variable is only available from inside the region it is created. This is called scope.
Local Scope
A variable created inside a function belongs to the local scope of that function, and can only
be used inside that function.
def myfunc():
x = 300
print(x)
myfunc()
Example
The local variable can be accessed from a function within the function:
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
Global Scope
A variable created in the main body of the Python code is a global variable and belongs to the
global scope.
Global variables are available from within any scope, global and local.
Example
x = 300
def myfunc():
print(x)
myfunc()
print(x)
Naming Variables
If you operate with the same variable name inside and outside of a function, Python will treat
them as two separate variables, one available in the global scope (outside the function) and
one available in the local scope (inside the function):
Example
The function will print the local x, and then the code will print the global x:
x = 300
def myfunc():
x = 200
print(x)
myfunc()
print(x)
Python Modules
Python Module is a file that contains built-in functions, classes,its and variables.
There are many Python modules, each with its specific work.
In this article, we will cover all about Python modules, such as How to create our own
simple module, Import Python modules, From statements in Python, we can use the
alias to rename the module, etc.
To create a Python module, write the desired code and save that in a file with .py
extension. Let’s understand it better with an example:
Example:
Let’s create a simple calc.py in which we define two functions, one add and another
subtract.
When the interpreter encounters an import statement, it imports the module if the
module is present in the search path.
Note: A search path is a list of directories that the interpreter searches for importing a
module.
For example, to import the module calc.py, we need to put the following command at
the top of the script.
Now, we are importing the calc that we created earlier to perform add operation.
print(calc.add(10, 2))
Output:
12
try:
Here, we have placed the code that might generate an exception inside
the try block. Every try block is followed by an except block.
When an exception occurs, it is caught by the except block. The except block
cannot be used without the try block.
numerator = 10
denominator = 0
result = numerator/denominator
print(result)except:
Run Code
numerator/denominator inside the try block. Now when an exception occurs, the
rest of the code inside the try block is skipped.
The except block catches the exception and statements inside the except block
are executed.
For each try block, there can be zero or more except blocks.
Multiple except blocks allow us to handle each exception differently.
The argument type of each except block indicates the type of exception that
can be handled by it. For example,
try:
even_numbers = [2,4,6,8]
print(even_numbers[5])
except ZeroDivisionError:
except IndexError:
Run Code
Since the list index starts from 0, the last element of the list is at index 3.
Notice the statement,
print(even_numbers[5])
Files
A file object is created using open function and here is a list of functions which
can be called on this object −
file.close()
1
Close the file. A closed file cannot be read or written any more.
file.flush()
2 Flush the internal buffer, like stdio's fflush. This may be a no-op on some
file-like objects.
file.fileno()
3 Returns the integer file descriptor that is used by the underlying
implementation to request I/O operations from the operating system.
file.isatty()
4
Returns True if the file is connected to a tty(-like) device, else False.
file.next()
5
Returns the next line from the file each time it is being called.
file.read([size])
6 Reads at most size bytes from the file (less if the read hits EOF before
obtaining size bytes).
file.readline([size])
7 Reads one entire line from the file. A trailing newline character is kept in
the string.
file.readlines([sizehint])
Reads until EOF using readline() and return a list containing the lines. If
8 the optional sizehint argument is present, instead of reading up to EOF,
whole lines totalling approximately sizehint bytes (possibly after
rounding up to an internal buffer size) are read.
file.seek(offset[, whence])
9
Sets the file's current position
file.tell()
10
Returns the file's current position
Here is a list of the different modes of opening a file −
Sr.No. Modes & Description
r
1 Opens a file for reading only. The file pointer is placed at the beginning of the
file. This is the default mode.
2 rb
Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file. This is the default mode.
r+
3 Opens a file for both reading and writing. The file pointer placed at the
beginning of the file.
rb+
4 Opens a file for both reading and writing in binary format. The file pointer
placed at the beginning of the file.
w
5 Opens a file for writing only. Overwrites the file if the file exists. If the file
does not exist, creates a new file for writing.
wb
6 Opens a file for writing only in binary format. Overwrites the file if the file
exists. If the file does not exist, creates a new file for writing.
w+
7 Opens a file for both writing and reading. Overwrites the existing file if the
file exists. If the file does not exist, creates a new file for reading and writing.
wb+
Opens a file for both writing and reading in binary format. Overwrites the
8
existing file if the file exists. If the file does not exist, creates a new file for
reading and writing.
a
Opens a file for appending. The file pointer is at the end of the file if the file
9
exists. That is, the file is in the append mode. If the file does not exist, it
creates a new file for writing.
ab
Opens a file for appending in binary format. The file pointer is at the end of
10
the file if the file exists. That is, the file is in the append mode. If the file does
not exist, it creates a new file for writing.
a+
Opens a file for both appending and reading. The file pointer is at the end of
11
the file if the file exists. The file opens in the append mode. If the file does not
exist, it creates a new file for reading and writing.
ab+
Opens a file for both appending and reading in binary format. The file pointer
12
is at the end of the file if the file exists. The file opens in the append mode. If
the file does not exist, it creates a new file for reading and writing.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")print "Name of the file: ", fo.nameprint "Closed or
not : ", fo.closedprint "Opening mode : ", fo.modeprint "Softspace flag : ",
fo.softspace
This produces the following result −
Name of the file: foo.txt
Closed or not : False
Opening mode : wb
Softspace flag : 0
Networking in Python
What are Sockets?
Consider a bidirectional communication channel, the sockets are the endpoints of this
communication channel. These sockets (endpoints) can communicate within a
process, between processes on the same machine, or between processes on different
machines. Sockets use different protocols for determining the connection type for
port-to-port communication between clients and servers.
Socket Programming
Socket programming is a way of connecting two nodes on a network to communicate
with each other. One socket(node) listens on a particular port at an IP, while the other
socket reaches out to the other to form a connection. The server forms the listener
socket while the client reaches out to the server. They are the real backbones behind
web browsing. In simpler terms, there is a server and a client. We can use the socket
module for socket programming. For this, we have to include the socket module –
import socket
to create a socket we have to use the socket.socket() method.
Syntax:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print(s)
Output:
Raspberry Pi Foundation officially provides Debian based Raspbian OS. Also, they
provide NOOBS OS for Raspberry Pi. We can install several Third-Party versions of
OS like Ubuntu, Archlinux, RISC OS, Windows 10 IOT Core, etc.
Raspbian OS is official Operating System available for free to use. This OS is
efficiently optimized to use with Raspberry Pi. Raspbian have GUI which includes
tools for Browsing, Python programming, office, games, etc.
Raspberry Pi is more than computer as it provides access to the on-chip hardware i.e.
GPIOs for developing an application. By accessing GPIO, we can connect devices
like LED, motors, sensors, etc and can control them too.
Raspberry Pi processor
It has ARM based Broadcom Processor SoC along with on-chip GPU (Graphics
Processing Unit).
The CPU speed of Raspberry Pi varies from 700 MHz to 1.2 GHz. Also, it has on-
board SDRAM that ranges from 256 MB to 1 GB.
Raspberry Pi also provides on-chip SPI, I2C, I2S and UART modules.
1. Raspberry Pi 1 Model A
2. Raspberry Pi 1 Model A+
3. Raspberry Pi 1 Model B
4. Raspberry Pi 1 Model B+
5. Raspberry Pi 2 Model B
6. Raspberry Pi 3 Model B
7. Raspberry Pi Zero
Out of the above versions of Raspberry Pi, more prominently use Raspberry Pi and
their features are as follows:
Raspberry Pi 2 Raspberry Pi 3
Raspberry Pi Raspberry Pi
Features
Model B+ Model B Model B zero
Operating
700 MHz 900 MHz 1.2 GHz 1 GHz
Freq.
Raspberry Pi Zero
Raspberry Pi Board
Available from the official Raspberry Pi website, Raspberry Pi Imager is a utility that
writes an operating system to your Pi's SD card. A list of operating systems is
included in the app, such as Raspberry Pi OS and other desktops, media players, and
emulation and gaming OSs.
Raspberry Pi Imager is available for Windows, macOS, and Ubuntu. Once installed
on your computer, the process is simple:
To use Etcher, you'll need to download the chosen operating system image to your PC
in advance. This provides you with the flexibility to install any suitable OS without
being restricted to a curated list. (While Raspberry Pi Imager permits the use of a
downloaded image file, it is not the default option.)
Once you've downloaded your preferred disk image, download Etcher. This is a tool
for writing disk images from your computer to flash storage, whether an SD card or a
USB thumb drive. It's a simple mouse-driven app, available for Windows, Linux, and
macOS.
With Etcher installed and running, you'll notice three buttons: Select Image, Select
Drive, and Flash. To flash an image with Etcher:
Serial : The Serial interface on Raspberry Pi has receive (Rx) and transmit (Tx) pins
for communication with serial peripherals.
SPI : Serial Peripheral Interface (SPI) is a synchronous serial data protocol used for
communicating with one or more peripheral devices. in an SPI connection, there are
five pins on Raspberry Pi for SPI interface :
MISO (Master in slave out) – Master line for sending data to the peripherals.
MOSI (Master out slave in) – Slave line for sending data to the master.
SCK (Serial Clock) – Clock generated by master to synchronize data transmission
CE0 (Chip Enable 0) – To enable or disable devices
CE0 (Chip Enable 1) – To enable or disable devices
I2C :
The I2C interface pins on Raspberry Pi allow you to connect hardware modules. I2C
interface allows synchronous data transfer with just two pins – SDA (data line) an
SCL (Clock Line).
In the world of electrical engineering, there are two type of input and output (I/O):
analogue and digital. Digital I/O is fairly easy to understand; it’s
either on or off, 1 or 0.
When talking about voltages and the Raspberry Pi, any input that is approximately
below 1.8V is considered off and anything above 1.8V is considered on. For output,
0V is off and 3.3V is on.
Analogue I/O is a little trickier. With an analogue input, we can have a range of
voltages from 0V up to 3.3V, and the Raspberry Pi is unable to detect exactly what
that voltage is.
How, then, can we use a Raspberry Pi to determine the value of an analogue input, if
it can only tell when the voltage to a GPIO pin goes above 1.8V?
When current is fed into a capacitor, it will begin to store charge. The voltage across
the capacitor will start off low, and increase as the charge builds up.
By putting a resistor in series with the capacitor, you can slow the speed at which it
charges. With a high resistance, the capacitor will charge slowly, whereas a low
resistance will let it charge quickly.
If you time how long it takes the capacitor’s voltage to get over 1.8V (or be on), you
can work out the resistance of the component in series with it.
Luckily, most of the complicated code you would have to write to detect the light
levels received by the LDR has been abstracted away by the gpiozero library. This
library will handle the timing of the capacitor’s charging and discharging for you.
Many, but not all, capacitors are polarised which means they have a positive and a
negative leg. In this case, the negative leg is shorter and should be marked with a ‘-‘
symbol.
Light-dependent resistors
When light hits the LDR, its resistance is very low, but when it’s in the dark its
resistance is very high.
By placing a capacitor in series with an LDR, the capacitor will charge at different
speeds depending on whether it’s light or dark.