Iot Unit3
Iot Unit3
Python is a general-purpose high level programming language. It was created by Guido van Rossum, and
released in 1991.
Python provides lots of features that are listed below.
1) Easy to Learn and Use
Python is easy to learn and use. It is developer-friendly and high level programming language.
2) Expressive Language
Python language is more expressive means that it is more understandable and readable.
3) Interpreted Language
Python is an interpreted language i.e. interpreter executes the code line by line at a time. This makes
debugging easy and thus suitable for beginners.
4) Cross-platform 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.
5) Free and Open Source
Python language is freely available.The source-code is also available. Therefore it is open source.
6) Object-Oriented Language
Python supports object oriented language and concepts of classes and objects come into existence.
7) Extensible
Python is a Extensible language.we can write our some python code into c or c++ language and also we can
compile that code in c/c++ language.
8) Large Standard Library
Python has a large and broad library and provides rich set of module and functions for rapid application
development.
9) GUI Programming Support
Graphical user interfaces can be developed using Python.
10) Integrated
It can be easily integrated with languages like C, C++, JAVA etc.
Python provides various standard data types that define the storage method on each of them. The data
types defined in Python are given below.
1. Numbers
2. String
3. List
4. Tuple
5. Dictionary
Numbers
Number stores numeric values. Python creates Number objects when a number is assigned to a variable.
For example;
1. a = 3 , b = 5 #a and b are number objects
Python supports 4 types of numeric data.
1. int (signed integers like 10, 2, 29, etc.)
2. long (long integers used for a higher range of values like 908090800L, -0x1929292L, etc.)
3. float (float is used to store floating point numbers like 1.9, 9.902, 15.2, etc.)
4. complex (complex numbers like 2.14j, 2.0 + 2.3j, etc.)
String
The string can be defined as the sequence of characters represented in the quotation marks. In python, we
can use single, double, or triple quotes to define a string.
String handling in python is a straightforward task since there are various inbuilt functions and operators
provided.
In the case of string handling, the operator + is used to concatenate two strings as the operation "hello"+"
python" returns "hello python".
The operator * is known as repetition operator as the operation "Python " *2 returns "Python Python ".
str1 = 'hello javatpoint' #string str1
str2 = ' how are you' #string str2
print (str1[0:2]) #printing first two character using slice operator
print (str1[4]) #printing 4th character of the string
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2
Output:
he
o
hello javatpointhello javatpoint
hello javatpoint how are you
List
Lists are similar to arrays in C. However; the list can contain data of different types. The items stored in the
list are separated with a comma (,) and enclosed within square brackets [].
We can use slice [:] operators to access the data of the list. The concatenation operator (+) and repetition
operator (*) works with the list in the same way as they were working with the strings.
l = [1, "hi", "python", 2]
print (l[3:])
print (l[0:2])
print (l)
print (l + l)
print (l * 3)
Output:
[2]
[1, 'hi']
[1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the items of
different data types. The items of the tuple are separated with a comma (,) and enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.
t = ("hi", "python", 2)
print (t[1:])
print (t[0:1])
print (t)
print (t + t)
print (t * 3)
print (type(t))
t[2] = "hi";
Output:
('python', 2)
('hi',)
('hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2, 'hi', 'python', 2)
<type 'tuple'>
Traceback (most recent call last):
File "main.py", line 8, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment
Dictionary
Dictionary is an ordered set of a key-value pair of items. It is like an associative array or a hash table where
each key stores a specific value. Key can hold any primitive data type whereas value is an arbitrary Python
object.
The items in the dictionary are separated with the comma and enclosed in the curly braces {}.
d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}
print("1st name is "+d[1])
print("2nd name is "+ d[4])
print (d)
print (d.keys())
print (d.values())
Output:
Sets are a collection of unordered elements that are unique. Meaning that even if the data is repeated
more than one time, it would be entered into the set only once.
Creating a set
Sets are created using the flower braces but instead of adding key-value pairs, you just pass values to it.
1 my_set = {1, 2, 3, 4, 5, 5, 5} #create set
2 print(my_set)
Output:
{1, 2, 3, 4, 5}
Adding elements
To add elements, you use the add() function and pass the value to it.
1 my_set = {1, 2, 3}
2 my_set.add(4) #add element to set
3 print(my_set)
Output:
{1, 2, 3, 4}
Arrays vs. Lists
Arrays and lists are the same structure with one difference. Lists allow heterogeneous data element
storage whereas Arrays allow only homogenous elements to be stored within them.
Stack
Stacks are linear Data Structures which are based on the principle of Last-In-First-Out (LIFO) where data
which is entered last will be the first to get accessed. It is built using the array structure and has operations
namely, pushing (adding) elements, popping (deleting) elements and accessing elements only from one
point in the stack called as the TOP.
A queue is also a linear data structure which is based on the principle of First-In-First-Out (FIFO) where the
data entered first will be accessed first.
Trees are non-linear Data Structures which have root and nodes.
Linked lists are linear Data Structures which are not stored consequently but are linked with each other
using pointers.
Graphs are used to store data collection of points called vertices (nodes) and edges (edges). Graphs can be
called as the most accurate representation of a real-world map.
HashMaps are the same as what dictionaries are in Python. They can be used to implement applications
such as phonebooks, populate data according to the lists and much more.
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.
Advantage of functions in python
There are the following advantages of C functions.
o By using functions, we can avoid rewriting same logic/code again and again in a program.
o We can call python functions any number of times in a program and from any place in a program.
o We can track a large python program easily when it is divided into multiple functions.
o Reusability is the main achievement of python functions.
o However, Function calling is always overhead in a python program.
Calling a Function
To call a function, use the function name followed by parenthesis:
def my_function():
print("Hello from a function")
my_function()
Parameters
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.
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Deafult parameter value
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Return
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Python Modules
A python module can be defined as a python program file which contains a python code including python
functions, class, or variables. In other words, we can say that our python code file saved with the extension
(.py) is treated as the module. We may have a runnable code inside the python module.
Loading the module in our python code
We need to load the module in our python code to use its functionality. Python provides two types of
statements as defined below.
1. The import statement
2. The from-import statement
The import statement
The import statement is used to import all the functionality of one module into another. Here, we must
notice that we can use the functionality of any python source file by importing that file as the module into
another python source file.
def greeting(name):
print("Hello, " + name)
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Jonathan")
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Python Exceptions
An exception can be defined as an abnormal condition in a program resulting in the disruption in the flow
of the program.
Whenever an exception occurs, the program halts the execution, and thus the further code is not
executed. Therefore, an exception is the error which python script is unable to tackle with.
Python provides us with the way to handle the Exception so that the other part of the code can be
executed without any disruption. However, if we do not handle the exception, the interpreter doesn't
execute all the code that exists after the that.
Common Exceptions
A list of common exceptions that can be thrown from a normal python program is given below.
1. ZeroDivisionError: Occurs when a number is divided by zero.
2. NameError: It occurs when a name is not found. It may be local or global.
3. IndentationError: If incorrect indentation is given.
4. IOError: It occurs when Input Output operation fails.
5. EOFError: It occurs when the end of the file is reached, and yet operations are being performed.
Python Packages
1. JSON: JavaScript Object Notation (JSON) is an easy to read and write data-interchange format. JSON is
used as an alternative to XML and is is easy for machines to parse and generate. JSON is built on two
structures - a collection of name-value pairs (e.g. a Python dictionary) and ordered lists of values (e.g..
a Python list).
2. XML: XML (Extensible Markup Language) is a data format for structured document interchange. The
Python minidom library provides a minimal implementation of the Document Object Model interface
and has an API similar to that in other languages.
3. HTTPLib & URLLib: HTTPLib2 and URLLib2 are Python libraries used in network/internet programming
4. SMTPLib: Simple Mail Transfer Protocol (SMTP) is a protocol which handles sending email and routing
e-mail between mail servers. The Python smtplib module provides an SMTP client session object that
can be used to send email.
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except:
print("can't divide by zero")
else:
print("Hi I am else block")
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
Create a class named MyClass, with a property named x
class MyClass:
x = 5
Create an object named p1, and print the value of x
p1 = MyClass()
print(p1.x)
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
File Handling
The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode.
There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
The open() function returns a file object, which has a read() method for reading the content of the file:
Example
f = open("demofile.txt", "r")
print(f.read())
Return the 5 first characters of the file:
f = open("demofile.txt", "r")
print(f.read(5))
Open the file "demofile2.txt" and append content to the file:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()