0% found this document useful (0 votes)
29 views

Iot Unit 3

This document provides an overview of the Python programming language. It discusses that Python is an easy to learn, high-level, interpreted, dynamic programming language that supports object-oriented, imperative, and functional programming styles. It also summarizes some of Python's main features like being an interpreted language, having a large standard library, supporting multiple programming paradigms, and being portable across different platforms. Finally, it briefly describes some common Python data types and structures like lists, tuples, dictionaries, modules, and file handling capabilities in Python.

Uploaded by

208r1a05n0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Iot Unit 3

This document provides an overview of the Python programming language. It discusses that Python is an easy to learn, high-level, interpreted, dynamic programming language that supports object-oriented, imperative, and functional programming styles. It also summarizes some of Python's main features like being an interpreted language, having a large standard library, supporting multiple programming paradigms, and being portable across different platforms. Finally, it briefly describes some common Python data types and structures like lists, tuples, dictionaries, modules, and file handling capabilities in Python.

Uploaded by

208r1a05n0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

IOT UNIT 3

Introduction to python:

 Python is a general-purpose, dynamic, high-level, and interpreted


programming language.

 It supports Object Oriented programming approach to develop


applications.

 It is simple and easy to learn and provides lots of high-level data


structures.

 Python is an easy-to-learn yet powerful scripting language, which makes it


attractive for Application Development.

 Python's syntax and dynamic typing make it an ideal language for


scripting and rapid application development.

 Python supports multiple programming patterns, including object-


oriented,functional or procedural programming styles.

Python Features

Python provides many useful features which make it popular and valuable
from the other programming languages. It supports object-oriented
programming, procedural programming approaches and provides dynamic
memory allocation. few essential features.

1) Easy to Learn and Use

Python is easy to learn as compared to other programming languages. Its


syntax is straightforward and much the same as the English language. There is
no use of the semicolon or curly-bracket, the indentation defines the code
block.

2) Expressive Language

Python can perform complex tasks using a few lines of code. A simple
example, the hello world program you simply type print("Hello World"). It
will take only one line to execute, while Java or C takes multiple lines.

3) Interpreted Language
Python is an interpreted language; it means the Python program is executed
one line at a time. It makes debugging easy and portable.

4) Portable Language

Python can run equally on different platforms such as Windows, Linux, UNIX,
and Macintosh, etc. So, we can say that Python is a portable language.once
written can run anywhere.

5) Object-Oriented Language

Python supports object-oriented language and concepts of classes and


objects . It supports inheritance, polymorphism, and encapsulation, etc.

6) Extensible

It converts the program into byte code, and any platform can use that byte
code.

7) Large Standard Library

It provides a vast range of libraries for the various fields such as machine
learning, web developer, and also for the scripting. Ex: Pandas,
Numpy,matplotlib etc. Django, flask are the popular framework for Python
web development.

8) Integrated

Python runs code line by line like C,C++ Java. It makes easy to debug the
code.

9) Dynamic Memory Allocation

In Python, we don't need to specify the data-type of the variable. When we


assign some value to the variable, it automatically allocates the memory to the
variable at run time. Suppose we are assigned integer value 15 to x, then we
don't need to write int x = 15. Just write x = 15.

Data types
Data structures

Built in:
List:
A list is a data structure in Python that is a mutable, or changeable, ordered
sequence of elements.
Ex:same from datatypes
Sets:
Dose not maintain insertion order,immutable(cant modify),dose not allow
duplicates
Ex: same from datatypes
Tuples:
Maintains insertion order,immutable(cant modify),allows duplicates
Ex: same from datatypes
Dictionary:
Unordered,unique,mutable(can modify)
Ex: same from datatypes
User defined:
1. Array:
An array is a special variable, which can hold more than one value at a time.
Array Methods

Python has a set of built-in methods that you can use on lists/arrays.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

2. Stack:
 A stack is a linear data structure where data is arranged objects on over
another.
 It stores the data in LIFO (Last in First Out) manner.
 We can perform the two operations in the stack - PUSH and POP.
 The PUSH operation is when we add an element
 POP operation is when we remove an element from the stack.
Methods of Stack
1. empty() - It returns true, it the stack is empty. The time complexity is O(1).
2. size() - It returns the length of the stack. The time complexity is O(1).
3. top() - This method returns an address of the last element of the stack.
The time complexity is O(1).
4. push(g) - This method adds the element 'g' at the end of the stack - The
time complexity is O(1).
5. pop() - This method removes the topmost element of the stack. The time
complexity is O(1).
3.Queue:
 A queue is a linear type of data structure used to store the data in a
sequentially.
 The concept of queue is based on the FIFO, which means "First in First
Out".
 It is also known as "first come first severed".
 The queue has the two ends front and rear.
 The next element is inserted from the rear end and removed from
the front end.

We can perform the following operations in the Queue.

o Enqueue - The enqueue is an operation where we add items to the


queue. time complexity of enqueue is O(1).
o Dequeue - The dequeue is an operation where we remove an element
from the queue.The time complexity of dequeue is O(1).
o Front - An element is inserted in the front end. The time complexity of
front is O(1).
o Rear - An element is removed from the rear end.. The time complexity
of the rear is O(1).
4. Linked List in Python
 A linked list is a type of linear data structure similar to arrays.
 It is a collection of nodes that are linked with each other.
 A node contains two things first is data and second is a link that
connects it with another node.
5.Tree
 A Python tree is a data structure in which data items are connected
using references in a hierarchical manner in the form of edges and
nodes.
 Each tree consists of a root node from which we can access the elements
of the tree.
 Starting from the root node, each node contains zero or more nodes
connected to it as children.
6. Graphs

A graph is a pictorial representation of a set of objects where some pairs of


objects are connected by links. Following are the basic operations we perform
on graphs.

 Display graph vertices


 Display graph edges
 Add a vertex
 Add an edge
 Creating a graph
7. Hashmaps
The hash map design will include the following functions:
 set_val(key, value): Inserts a key-value pair into the hash map. If the
value already exists in the hash map, update the value.
 get_val(key): Returns the value to which the specified key is mapped, or
“No record found” if this map contains no mapping for the key.
 delete_val(key): Removes the mapping for the specific key if the hash
map contains the mapping for the key.
Control flow:
Functions in python

https://www.scaler.com/topics/types-of-functions-in-python/

Modules:
 Modules work like code library
 It is file containing set of functions you want to include in your application
 A module allows you to logically organize your code
 A module can define functions ,classes and variables
 A module can also include a runnable code
Ex:
//ex1.py
def sample(name):
print(“welcome”+name)
import ex1
ex1.sample(“to home”)
Variables module:
# This is variables module
## this is a function in module
def factorial(n):
if n == 1 || n == 0:
return 1
else:
return n * factorial(n-1)

## this is dictionary in module


power = {
1 : 1,
2 : 4,
3 : 9,
4 : 16,
5 : 25,
6 : 36,
7 : 49,
8 : 64,
9 : 81,
10 : 100
}

## This is a list in the module


alphabets = [a,b,c,d,e,f,g,h]
--
import variables

fact_of_6 = variables.factorial(6)
power_of_6 = variables.power[6]

alphabet_2 = variables.alphabets[1]

print(f"The factorial of 6 is : {fact_of_6}")


print(f"Power of 6 is : {power_of_6}")
print(f"Second Alphabet is : {alphabet_2}")
Output:
The factorial of 6 is 720
Power of 6 is 36
The second alphabet is b

Built in modules available are:


 Sys module
 Os module
 Math module
 Rand module
 Statistics module
 Collections module

Renaming a Module

Python provides an easy and flexible way to rename our module with a
specific name and then use that name to call our module resources. For
renaming a module, we use the as keyword. The syntax is as follows:

Code:

import math as m
import numpy as np
import random as r
print(m.pi)
print(r.randint(0,10))
print(np.__version__)

Output:

3.141592653589793
10
1.22.0
File handling:
A file is a container in computer storage devices used for storing
data.

Hence, in Python, a file operation takes place in the following order:

1. Open a file
2. Read or write (perform operation)
3. Close the file
Date time operations:

There are six main object classes with their respective components in the
datetime module mentioned below:
1. datetime.date
2. datetime.time
3. datetime.datetime
4. datetime.tzinfo
5. datetime.timedelta
6. datetime.timezone
1.datetime.date
from datetime import date
current = date.today()
print("Current Day is :", current.day)
print("Current Month is :", current.month)
print("Current Year is :", current.year)

2.datetime.time:
from datetime import time
defaultTime = time(9,14,59,12)
print("default_hour =", defaultTime.hour)
print("default_minute =", defaultTime.minute)
print("default_second =", defaultTime.second)
print("default_microsecond =", defaultTime.microsecond)

3.datetime.datetime:
from datetime import datetime
current = datetime.now()
date_time = current.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:", date_time)
manual = datetime(2021, 3, 28, 23, 55, 59, 342380)
print("year =", manual.year)
print("month =", manual.month)
print("day =", manual.day)
print("hour =", manual.hour)
print("minute =", manual.minute)
print("sec =", manual.second)
Exception handling:

Exception handling is the process of responding to unwanted or unexpected


events when a computer program runs.
Classes in python:

 In Python, a class is a user-defined data type that contains both the data
itself and the methods that may be used to manipulate it.

 classes serve as a template to create objects.

 They provide the characteristics and operations that the objects will
employ.

 Suppose a class is a prototype of a building. A building contains all the


details about the floor, rooms, doors, windows, etc. we can make as many
buildings as we want, based on these details. Hence, the building can be
seen as a class, and we can create as many objects of this class.

Syntax

class ClassName:
Example:
Code:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print("Hello, my name is " + self.name)

Name and age are the two properties of the Person class. Additionally, it has a
function called greet that prints a greeting.

Packages:

JSON:

 JSON (JavaScript Object Notation) is the most widely used data format
for data interchange on the web.
 JSON is a lightweight text-based, data-interchange format and it is
completely language-independent.
 It is based on a subset of the JavaScript programming language and it is
easy to understand and generate.
JSON supports mainly 6 data types:
1. String
2. Number
3. Boolean
4. Null
5. Object
6. Array
Note: string, number, boolean, null are simple data types or
primitives data types whereas object and array are referred as
complex data types.

HTTP lib:

The Hypertext Transfer Protocol (HTTP) is application-level protocol. It is the


data communication protocol used to establish communication between
client and server.
HTTP is used to deliver the data like image files, query results, HTML files etc
on the World Wide Web (WWW) .It provides the standardized way for
computers to communicate with each other.

The Basic Features of HTTP:

o HTTP is media independent


o HTTP is connectionless
o HTTP is stateless

SMTP lib:
Simple Mail Transfer Protocol (SMTP) is used as a protocol to handle the email
transfer using Python. It is an application layer protocol which allows to users
to send mail to another. The receiver retrieves email using the
protocols POP(Post Office Protocol) and IMAP(Internet Message Access
Protocol).

The SMTP object is used for the email transfer. The following syntax is used to
create the smtplib object.

Syntax:

import smtplib
smtpObj = smtplib.SMTP(host, port, local_hostname)

It accepts the following parameters.

o host: It is the hostname of the machine which is running your SMTP


server.
o port: It is the port number on which the host machine is listening to
the SMTP connections
o local_hostname: If the SMTP server is running on your local machine,
we can mention the hostname of the local machine.

You might also like