Unit III Iot
Unit III Iot
UNIT III
IOT PHYSICAL DEVICES AND ENDPOINTS
Introduction to Arduino and Raspberry Pi- Installation, Interfaces (serial, SPI, I2C), Programming –
Python program with Raspberry PI with focus on interfacing external gadgets, controlling output, and
reading input from pins.
INTRODUCTION TO ARDUINO AND RASPBERRY PI
Arduino and Raspberry Pi are used as a tool for creating electronic projects.
ARDUINO
Arduino is a software as well as hardware platform that helps in making electronic projects. It is
an open source platform and has a variety of controllers and microprocessors. There are various types of
Arduino boards used for various purposes.
The Arduino is a single circuit board, which consists of different interfaces or parts. The board consists of
the set of digital and analog pins that are used to connect various devices and components, which we want
to use for the functioning of the electronic devices.
The analog pins in Arduino are mostly useful for fine-grained control. The pins in the Arduino board are
arranged in a specific pattern. The other devices on the Arduino board are USB port, small components
(voltage regulator or oscillator), microcontroller, power connector, etc.
❖ Arduino programming is a simplified version of C++, which makes the learning process easy.
❖ The Arduino IDE is used to control the functions of boards. It further sends the set of
specifications to the microcontroller.
❖ Arduino does not need an extra board or piece to load new code.
MICROCONTROLLER
The most essential part of the Arduino is the Microcontroller, which is shown below:
Microcontroller is small and low power computer. Most of the microcontrollers have a RAM (Random
Access Memory), CPU (Central Processing Unit), and memory storage like other computer systems.
It has very small memory of 2KB (two Kilobytes). Due to less memory, some microcontrollers are
capable of running only one program at a time.
It is a single chip that includes memory, Input/Output (I/O) peripherals, and a processor.
The GPIO (General Purpose Input Output) pins present on the chip help us to control other electronics or
circuitry from the program.
Downloaded by Yara Varshini (varshiniyara785@gmail.com)
lOMoARcPSD|57264712
ARDUINO KITS
We can easily start with our electronics projects using the complete kit. It also helps us to create hand-on
and engaging projects.
The IDE makes the traditional projects even easier and simpler. The USB cable is used to load the
program or sketch on the specific Arduino board.
ARDUINO DOWNLOAD
The Arduino software (IDE) is open-source software. We are required to write the code and upload the
code to the board to perform some task.
The Arduino IDE software can be used with any type of Arduino boards. The software is available for
various operating system such as, Windows, Linux, and Mac OS X.
The steps to download the Arduino software are listed below:
1. Go to the official website of Arduino (https://www.arduino.cc/) > Click on SOFTWARE < click on
DOWNLOADS, as shown below:
4. Click on the 'Windows Installer' as we are operating with the Windows. We can select the
Linux or Mac OS X, accordingly.
5. A contribution window will appear. We can contribute according to our choice and click on
the 'CONTRIBUTE &DOWNLOAD' option. Otherwise, click on the 'JUST DOWNLOAD'
option, as shown below:
6. The downloading process will start. The downloading file will look like the below image:
10. Accept the license by clicking on 'I Agree' button, as shown below:
12. The window specifying the location of the installed folder will appear. Click on the 'Install'
button. It is shown below:
14. Now, we have to accept the security for the installation. We are required to accept the
security Installation three times.
17. The installation process is now completed. The window will now appear as:
The Arduino IDE software will appear on your desktop, as shown below:
20. The Arduino IDE environment is written in the programming language named as Java. So,
we need to allow access to the Java Platform.
As soon we open the Arduino software, a license window will appear, as shown below:
Let's discuss each section of the Arduino IDE display in detail. Toolbar Button
The icons displayed on the toolbar are New, Open, Save, Upload, and Verify.
It is shown below:
Upload
The Upload button compiles and runs our code written on the screen. It further uploads the code to the
connected board. Before uploading the sketch, we need to make sure that the correct board and ports are
selected.
We also need a USB connection to connect the board and the computer. Once all the above measures are
done, click on the Upload button present on the toolbar.
The latest Arduino boards can be reset automatically before beginning with Upload. In the older boards,
we need to press the Reset button present on it. As soon as the uploading is done successfully, we can
notice the blink of the Tx and Rx LED.
Downloaded by Yara Varshini (varshiniyara785@gmail.com)
lOMoARcPSD|57264712
If the uploading is failed, it will display the message in the error window.
We do not require any additional hardware to upload our sketch using the Arduino Bootloader. A
Bootloader is defined as a small program, which is loaded in the microcontroller present on the board.
The LED will blink on PIN 13.
Open
The Open button is used to open the already created file. The selected file will be opened in the current
window.
Save
The save button is used to save the current sketch or code.
New
It is used to create a new sketch or opens a new window.
Verify
The Verify button is used to check the compilation error of the sketch or the written code.
Serial Monitor
The serial monitor button is present on the right corner of the toolbar. It opens the serial monitor.
Close
The Close button closes the window from which the button is clicked.
Save
The save button is used to save the current sketch. It also saves the changes made to the current sketch. If
we have not specified the name of the file, it will open the 'Save As...' window.
Downloaded by Yara Varshini (varshiniyara785@gmail.com)
lOMoARcPSD|57264712
Save As...
We can save the sketch with a different name using the 'Save As...' button. We can also change the name
accordingly.
Page Setup
It allows setting the page margins, orientation, and size for printing. The 'Page Setup' window will appear
as:
Internet of Things
The Internet of Things (IoT) is a scenario in which objects, animals or people are provided
with single identifiers and the capability to automatically transfer and the capability to
automatically transfer data more to a network without requiring human-to-human or human-
to-computer communication.
Arduino Board:
An Arduino is actually a microcontroller based kit.
It is basically used in communications and in controlling or operating many devices.
Arduino UNO board is the most popular board in the Arduino board family.
In addition, it is the best board to get started with electronics and coding.
Some boards look a bit different from the one given below, but most Arduino’s
have majority of these components in common.
It consists of two memories- Program memory and the data memory.
The code is stored in the flash program memory, whereas the data is stored in the data
memory.
Arduino Uno consists of 14 digital input/output pins (of which 6 can be used as PWM
outputs), 6 analog inputs, a 16 MHz crystal oscillator, a USB connection, a power
jack, an ICSP header, and a reset button
16.ARE
17.Arduino 15.Digital I/O
F
Reset
14.TX and RX
LEDs
1.Power
USB 4.Crystal Oscillator
3.Powe
r LED
1 indicator
12.ICSP pin
3.Voltage
Regulator
11.Main
microcontroll
2.Power er
(Barrel Jack)
5.Arduino
Reset
6,7,8,9.Pins 10.Analog pins
(3.3,
5, GND, Vin)
III Unit
1. Power USB
Arduino board can be powered by using the USB cable from your computer. All you
need to do is connect the USB cable to the USB connection (1).
2. Power (Barrel Jack)
Arduino boards can be powered directly from the AC mains power supply by connecting
it to the Barrel Jack (2).
3. Voltage Regulator
The function of the voltage regulator is to control the voltage given to the Arduino board
and stabilize the DC voltages used by the processor and other elements.
4. Crystal Oscillator
The crystal oscillator helps Arduino in dealing with time issues. How does Arduino
calculate time? The answer is, by using the crystal oscillator. The number printed on top of the
Arduino crystal is 16.000H9H. It tells us that the frequency is 16,000,000 Hertz or 16 MHz.
5,17.Arduino Reset
You can reset your Arduino board, i.e., start your program from the beginning. You can
reset the UNO board in two ways. First, by using the reset button (17) on the board. Second, you
can connect an external reset button to the Arduino pin labelled RESET (5).
6,7,8,9.Pins (3.3, 5, GND, Vin)
• 3.3V (6) − Supply 3.3 output volt
• 5V (7) − Supply 5 output volt
• Most of the components used with Arduino board works fine with 3.3 volt and 5 volt.
• GND (8)(Ground) − There are several GND pins on the Arduino, any of which can be
used to ground your circuit.
• Vin (9) − This pin also can be used to power the Arduino board from an external power
source, like AC mains power supply.
13
III Unit
The Arduino UNO board has six analog input pins A0 through A5. These pins can read
the signal from an analog sensor like the humidity sensor or temperature sensor and
convert it into a digital value that can be read by the microprocessor.
Each Arduino board has its own microcontroller (11). You can assume it as the brain of
your board. The main IC (integrated circuit) on the Arduino is slightly different from board to
board. The microcontrollers are usually of the ATMEL Company. You must know what IC your
board has before loading up a new program from the Arduino IDE. This information is available
on the top of the IC. For more details about the IC construction and functions, you can refer to
the data sheet.
Mostly, ICSP (12) is an AVR, a tiny programming header for the Arduino consisting of
MOSI, MISO, SCK, RESET, VCC, and GND. It is often referred to as an SPI (Serial
Peripheral Interface), which could be considered as an "expansion" of the output.
Actually, you are slaving the output device to the master of the SPI bus.
This LED should light up when you plug your Arduino into a power source to indicate
that your board is powered up correctly. If this light does not turn on, then there is
something wrong with the connection.
On your board, you will find two labels: TX (transmit) and RX (receive). They appear in
two places on the Arduino UNO board. First, at the digital pins 0 and 1, to indicate the
pins responsible for serial communication. Second, the TX and RX led (13). The TX led
flashes with different speed while sending the serial data. The speed of flashing depends
on the baud rate used by the board. RX flashes during the receiving process.
• The Arduino UNO board has 14 digital I/O pins (15) (of which 6 provide PWM (Pulse
Width Modulation) output. These pins can be configured to work as input digital pins to
read logic values (0 or 1) or as digital output pins to drive different modules like LEDs,
relays, etc. The pins labeled “~” can be used to generate PWM.
16. AREF
14
III Unit
• AREF stands for Analog Reference. It is sometimes, used to set an external reference
voltage (between 0 and 5 Volts) as the upper limit for the analog input pins.
Program an Arduino
The most important advantage with Arduino is the programs can be directly loaded to the
device without requiring any hardware programmer to burn the program.
This is done because of the presence of the 0.5KB of Bootloader which allows the
program to be burned into the circuit.
All we have to do is to download the Arduino software and writing the code.
The Arduino tool window consists of the toolbar with the buttons like verify, upload,
new, open, save, serial monitor.
It also consists of a text editor to write the code, a message area which displays the
feedback like showing the errors, the text console which displays the output and a series
of menus like the File, Edit, Tools menu.
1. Declaration of Variables
2. Initialization: It is written in the setup () function.
3. Control code: It is written in the loop () function.
The sketch is saved with .ino extension. Any operations like verifying, opening a sketch,
saving a sketch can be done using the buttons on the toolbar or using the tool menu.
Chose the proper board from the tools menu and the serial port numbers.
Click on the upload button or chose upload from the tools menu. Thus the code is
uploaded by the bootloader onto the microcontroller.
15
III Unit
serial.begin(baud rate): Sets the beginning of serial communication by setting the bit
rate.
The IC socket and the power jack are mounted on the board.
Add the 5v and 3.3v regulator circuits using the combinations of regulators
and capacitors.
Mount the female headers onto the board and connect them to the respective
pins on the chip.
1. It is inexpensive
2. It comes with an open source hardware feature which enables users to develop their own
kit using already available one as a reference source.
3. The Arduino software is compatible with all types of operating systems like Windows,
Linux, and Macintosh etc.
4. It also comes with open source software feature which enables experienced software
developers to use the Arduino code to merge with the existing programming language
libraries and can be extended and modified.
16
III Unit
6. We can develop an Arduino based project which can be completely stand alone or
projects which involve direct communication with the software loaded in the computer.
7. It comes with an easy provision of connecting with the CPU of the computer using serial
communication over USB as it contains built in power and reset circuitry.
Interfaces
UART Peripheral:
A UART (Universal Asynchronous Receiver/Transmitter) is a serial interface.
It has only one UART module.
The pins (RX, TX) of the UART are connected to a USB-to-UART converter circuit and
also connected to pin0 and pin1 in the digital header.
SPI Peripheral:
The SPI (Serial Peripheral Interface) is another serial interface. It has only one SPI
module.
TWI:
The I2C or Two Wire Interface is an interface consisting of only two wires, serial data,
and a serial clock: SDA, SCL.
You can reach these pins from the last two pins in the digital header or pin4 and pin5 in
the analog header.
The Internet of Things (IoT) is a scenario in which objects, animals or people are provided with
single identifiers and the capability to automatically transfer and the capability to automatically
transfer data more to a network without requiring human-to-human or human-to-computer
communication.
Raspberry Pi
The Raspberry Pi is a very cheap computer that runs Linux, but it also provides a set of
GPIO (general purpose input/output) pins that allow you to control electronic
components for physical computing and explore the Internet of Things (IoT).
Raspberry Pi was basically introduced in 2006.
It is particularly designed for educational use and intended for Python.
A Raspberry Pi is of small size i.e., of a credit card sized single board computer, which is
developed in the United Kingdom(U.K) by a foundation called Raspberry Pi.
17
III Unit
18
III Unit
Voltages: Two 5V pins and two 3V3 pins are present on the board, as well as a number
of ground pins (0V). The remaining pins are all general purpose 3V3 pins
A GPIO pin designated as an output pin can be set to high (3V3) or low (0V). A GPIO
pin designated as an input pin can be read as high (3V3) or low (0V).
Processor & RAM: Raspberry based on ARM11 processor. Latest version supports
700MHz processor and 512MB SDRAM. The Central processing unit is the brain of the
raspberry pi board and that is responsible for carrying out the instructions of the computer
through logical and mathematical operations.
Ethernet: The Ethernet port of the raspberry pi is the main gateway for communicating
with additional devices. The raspberry pi Ethernet port is used to plug your home router
to access the internet.
19
III Unit
USB Ports: It has 2 USB ports. USB port provide current upto 100mA. For connecting
devices that draw current more than 100mA, an external USB powered hub is required.
Ethernet Port: It has standard RJ45 Ethernet port. Connect Ethernet cable or USB wifi
adapter to provide internet connectivity.
HDMI Output: It supports both audio and video output. Connect raspberry Pi to monitor
using HDMI cable.
Composite video Output: Raspberry comes with a composite video output with an RCA
jack that supports both PAL and NTSC video output.
Audio Output: It has 3.5mm audio output jack. This audio jack is used for providing
audio output to old television along with RCA jack for video.
GPIO Pins: It has a number of general purpose input/output pins. These pins are used to
connect other electronic components. For example, you can connect it to the temperature
sensor to transmit digital data.
Display Serial Interface (DSI): DSI interface are used to connect an LCD panel to
Raspberry PI.
Cameral Serial Interface(CSI): CSI interface are used to connect a camera module to
Raspberry PI.
SD Card slot: Raspberry does not have built in OS and storage. Plug in an SD card
loaded with Linux to SD card slot.
Power Input: Raspberry has a micro USP connector for power input.
Memory: The raspberry pi model A board is designed with 256MB of SDRAM and
model B is designed with 51MB.Raspberry pi is a small size PC compare with other PCs.
The normal PCs RAM memory is available in gigabytes. But in raspberry pi board, the
RAM memory is available more than 256MB or 512MB
Status LEDs: Raspberry has 5 status LEDs.
Raspberry PI Interfaces:
20
III Unit
1. Where the system processing is huge. They can process high end programs for applications
like Weather Station, Cloud server, gaming console etc. With 1.2GHz clock speed and 1 GB
RAM RASPBERRY PI can perform all those advanced functions.
2. RASPBERRY PI 3 has wireless LAN and Bluetooth facility by which you can setup WIFI
HOTSPOT for internet connectivity.
3. RASPBERRY PI had dedicated port for connecting touch LCD display which is a feature that
completely omits the need of monitor.
4. RASPBERRY PI also has dedicated camera port so one can connect camera without any
hassle to the PI board.
6. It supports HD steaming
Applications
Hobby projects.
Low cost PC/tablet/laptop
IoT applications
Media center
Robotics
Industrial/Home automation
Server/cloud server
Print server
Security monitoring
Web camera
Gaming
Wireless access point
21
III Unit
22
III Unit
23
III Unit
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
print("Real Part is :", x.real)
print("Imaginary Part is :",x.imag)
Output
<class 'complex'>
<class 'complex'>
<class 'complex'>
Real Part is : 3.0
Imaginary Part is : 5.0
5.3.3.2 Strings
String literals in python are surrounded by either single quotation marks, or double
quotation marks.
'hello' is the same as "hello".
One or more character is called string
A string with zero character is called empty string.
Example:
a="Hello"
b="World!"
print(type(a))
print(b)
#String concatination
print(a+b)
#String Length
print(len(a))
#Convert to upper and lower
print(a.lower())
print(a.upper())
# Substring 4th character not included
print(a[1])
print(a[1:4])
print(a[1:])
#strip() method removes any whitespace or characters
print(b.strip("Wor"))
print(b.strip("!"))
#The replace() method replaces a string with another string
24
III Unit
print(a.replace("H","J"))
#Format Method
age = 36
txt = "My age is {}"
print(txt.format(age))
Output
<class 'str'>
World!
HelloWorld!
5
hello
HELLO
e
ell
ello
ld!
World
Jello
My age is 36
5.3.3.3 List
It is a Compound data type used to group together other values.
List items need not have the same data type.
List is a collection which is ordered and changeable. It allows duplicate members.
To add an item to the end of the list, use the append() method
To add an item at the specified index, use the insert() method
The remove() method removes the specified item
List items are separated by commas and enclosed with in square brackets.
To access the list items by referring to the index number.
To change the value of a specific item, refer to the index number
Program
li=['apple','orange','mango','banana']
print(type(li))
#print all item in a list
print(li)
#print items in a list based on index start is 0
print(li[0])
print(li[1:])
#append() add an item in end of the list
li.append("Berry")
print(li)
#remove() delete an item
li.remove("apple")
print(li)
#Insert an item based on index
li.insert(2,"apple")
25
III Unit
print(li)
#Crate mixed list
mi=['Hai',2,5.999]
print(mi)
print(li+mi)
5.3.3.4 Tuple
Tuple is a collection which is ordered and unchangeable. It allows duplicate members.
In Python tuples are written with round brackets.
You can access tuple items by referring to the index number, inside square brackets.
Once a tuple is created, you cannot change its values. Tuples are unchangeable.
To determine how many items a tuple has, use the len() method
You cannot add items to a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can delete the
tuple completely
Example:
tu=('apple','orange','mango','banana')
print(type(tu))
#print all item in a list
print(tu)
#print items in a tuple based on index start at 0
print(tu[0])
print(tu[1:3])
print(tu[:2])
#len() length of the tuple
print(len(tu))
26
III Unit
"model": "Mustang",
"year": 1964
}
print(type(dict))
print(dict)
#len() to determine length of dictionary
print(len(dict))
#print model value
x = dict["model"]
print(x)
# print all items
print(dict.items())
# get keys
print(dict.keys())
#get values
print(dict.values())
#add new key & value
dict["color"] = "red"
print(dict)
# last item deleted
dict.popitem()
print(dict)
del dict["model"]
print(dict)
Output
<class 'dict'>
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
3
Mustang
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
dict_keys(['brand', 'model', 'year'])
dict_values(['Ford', 'Mustang', 1964])
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
{'brand': 'Ford', 'year': 1964}
5.3.3.6 Type Conversion
convert from one type to another with the int(), float(), and complex() methods:
Example
x =1# int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
27
III Unit
c = complex(x)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
s="aeiou"
print(list(s))
Output
1.0
2
(1+0j)
<class 'float'>
<class 'int'>
<class 'complex'>
['a', 'e', 'i', 'o', 'u']
28
III Unit
Example
syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Example:
a=int(input('Enter a Number'))
if a>0:
print(a," is Positive Number")
elif a<0:
print(a," is Negative Number")
else:
print(a," is Zero")
Output
Enter a Number-67
-67 is Negative Number
Nested if
In a nested if construct, you can have an if...elif...else construct inside
another if...elif...else construct.
Syntax
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
elif expression4:
statement(s)
else:
statement(s)
else:
statement(s)
Example
var = 100
if var < 200:
29
III Unit
if var == 150:
print ("Which is 150")
elif var == 100:
print ("Which is 100")
elif var == 50:
print ("Which is 50")
elif var < 50:
print ("Value is less than 50")
else:
print ("Values more than 200..")
For
The for loop in Python is used to iterate the statements or a part of the program several
times.
It is frequently used to traverse the data structures like list, tuple, or dictionary.
syntax
for iterating_var in sequence:
statement(s)
Example
#print natural numbers
i=1
n=int(input("Enter the number up to print the natural numbers : "))
for i in range(0,n):
print(i,end=' ')
#print String
s="Hello World"
print("\n")
for c in s:
print(c,end=' ')
#Multiplication Table
i=1;
print("\n")
num = int(input("Enter a number:"));
for i in range(1,11):
print("%d X %d = %d"%(num,i,num*i));
Output
Enter the number up to print the natural numbers : 2
01
30
III Unit
HelloWorld
Enter a number:4
4X1=4
4X2=8
4 X 3 = 12
4 X 4 = 16
4 X 5 = 20
4 X 6 = 24
4 X 7 = 28
4 X 8 = 32
4 X 9 = 36
4 X 10 = 40
while
With the while loop we can execute a set of statements as long as a condition is true.
Syntax
while expression:
statement(s)
statement(s) may be a single statement or a block of statements.
The condition may be any expression, and true is any non-zero value.
The loop iterates while the condition is true.
Program
#print 1 to 5
i=1
while i < 6:
print(i)
i=i+1
31
III Unit
for x in a:
if x==3:
break
32
III Unit
print(x)
Output
13412
Pass
It is null operation
It is used when a statement is required syntactically but not execute any code.
Program
for x in a:
if x==1:
pass
else:
print(x)
Output
234
5.3.5 Python Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
Creating a Function
In Python a function is defined using the def keyword.
Function begins with def keyword followed by function name and parenthesis.
Function parameters are enclosed within the parenthesis.
Calling a Function
To call a function, use the function name followed by parenthesis:
Information can be passed to functions as parameter.
Parameters are specified after the function name, inside the parentheses. You can add as
many parameters as you want, just separate them with a comma.
Program
#function1
def fun1():
print("Hello from a
function") fun1()
#function2
def fun2(fname):
print("Hello "+ fname)
fun2("Cathy")
fun2("Raju")
#function3
def fun3(country = "Norway"):
print("I am from " + country)
fun3("Sweden")
33
III Unit
fun3("India")
fun3()
fun3("Brazil")
#function4
def fun4(food):
for x in food:
print(x)
fruits = ["apple", "banana",
"cherry"] fun4(fruits)
#function5
def fun5(x):
return 5 * x
print(fun5(3))
print(fun5(5))
print(fun5(9))
Output
Hello from a function
Hello Cathy
Hello Raju
I am from Sweden
I am from India
I am from Norway
I am from Brazil
apple
banana
cherry
15
25
45
5.3.6 Modules
Consider a module to be the same as a code library.
A file containing a set of functions you want to include in your application.
It allows organizing of the program code into different modules which improves the code
readability and management.
A module is a python file that defines some functionality in the form of function or
classes.
Create a Module : To create a module just save the code you want in a file with the file
extension .py:
filename: module1.py
def f1(name):
34
III Unit
2. module4.py
import module3
module3.add(10,5)
print("Subtraction is :",module3.sub(100,50))
5.3.7 Packages
Python package is hierarchical file structure that consists of modules and sub packages.
Packages are organized into root directory with sub directories
Each directory contains a special file named __init .py which tells python to treat
directory as packages.
Packages are a way of structuring many packages and modules which helps in a well-
organized hierarchy of data set, making the directories and modules easy to access.
To tell Python that a particular directory is a package, we create a file named init .py
inside it and then it is considered as a package.
We may create other modules and sub-packages within it.
This init .py file can be left blank or can be coded with the initialization code for the
package.
To create a package in Python, we need to follow these three simple steps:
First, we create a directory and give it a package name, preferably related to its operation.
Then we put the classes and the required functions in it.
Finally we create an init .py file inside the directory, to let Python know that the
directory is a package.
35
III Unit
We can import modules from packages using the dot (.) operator.
Example: import Game.Level.start
36
III Unit
Java Programming
C Programming
C++ Programming
Python Programming
PHP Programming
HTML Programming
Java Programming
C Programming
Java Programming
C Programming
C++ Programming
Python Programming
PHP Programming
HTML Programming
Example2:
#create new file
f = open("myfile.txt", "x")
#write data into file
f = open("myfile.txt", "a")
f.write("Now the file has more content!")
f.close()
#read data from file
f = open("myfile.txt", "r")
print(f.read())
f.close()
Output:
Now the file has more content!
37
III Unit
5.3.10 Classes
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.
To create a class, use the keyword class:
Python supports classes, class variables, class methods, inheritance, function overloading,
operator overloading.
Class: A class is simply a representation of a type of object and user defined prototype
for an object that is composed of three things like name, attribute and
operations/methods.
Object: Object is an instance of the data structure defined by a class.
Inheritance: It is the process of forming a new class from an existing class or base class.
Function overloading: It is a form of polymorphism that allows a function to have
different meanings, depending on its context.
Operator overloading: It is a form of polymorphism that allows assignment of more
than one function to a particular operator.
Function overriding: It allows a child class to provide a specific implementation of a
function that is already provided by the base class. Child class implementation of the
overridden function has the same name, parameters and return type as the function in the
base class.
All classes have a function called init (), which is always executed when the class is
being initiated.
Use the init () function to assign values to object properties, or other operations that
are necessary to do when the object is being created:
The init () function is called automatically every time the class is being used to create
a new object.
38
III Unit
The self parameter is a reference to the current instance of the class, and is used
to access variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to be
the first parameter of any function in the class:
You can delete properties on objects by using the del keyword.
Example1:
class Person:
def init (self, name, age):
print("Constructor Called..")
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
p1.myfunc()
Output1:
Constructor Called..
John
36
Hello my name is John
Example2:
#Inhertitance Program
class Person:
def init (self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def init (self, fname, lname, year):
super(). init (fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of",
self.graduationyear)
39
III Unit
5.3.11.1 JSON
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
40
III Unit
It was designed to store and transport small to medium amounts of data and is widely
used for sharing structured information.
In order to parse an XML document using minidom, we must first import it from
the xml.dom module. This module uses the parse function to create a DOM object from
our XML file.
getElementByTagName() to find a specific tag.
Example:
from xml.dom import minidom
items = mydoc.getElementsByTagName('item')
Item #2 data:
Mango
41
III Unit
Example1:
import http.client
conn = http.client.HTTPSConnection("www.python.org")
conn.request("GET", "/")
r1 = conn.getresponse()
print(r1.status, r1.reason)
data1 = r1.read() # This will return entire content.
# The following example demonstrates reading data in chunks.
conn.request("GET", "/")
r1 = conn.getresponse()
while not r1.closed:
print(r1.read(200))
Example2:
import urllib.request
x = urllib.request.urlopen('https://www.gmail.com/')
print(x.read())
5.11.3.4 SMTPLib
Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending an e-mail
and routing e-mail between mail servers.
Python provides smtplib module, which defines an SMTP client session object that can
be used to send mails to any Internet machine with an SMTP or ESMTP.
Syntax:
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
Here is the detail of the parameters −
host − This is the host running your SMTP server. You can specifiy IP address of the
host or a domain name like tutorialspoint.com. This is an optional argument.
port − If you are providing host argument, then you need to specify a port, where SMTP
server is listening. Usually this port would be 25.
local_hostname − If your SMTP server is running on your local machine, then you can
specify just localhost the option.
An SMTP object has an instance method called sendmail, which is typically used to do
the work of mailing a message. It takes three parameters −
The sender − A string with the address of the sender.
The receivers − A list of strings, one for each recipient.
The message − A message as a string formatted as specified in the various RFCs.
Example:
import smtplib
sender = 'from@fromdomain.com' receivers =
['to@todomain.com']
message = """From: From Person <from@fromdomain.com>
42
III Unit
43
III Unit
44
III Unit
45
III Unit
46
III Unit
47
III Unit
48
III Unit
49
III Unit
50
III Unit
51