Iot (Mod 3)
Iot (Mod 3)
Python
Python is a general-purpose high level programming language and suitable for providing a solid
foundation to the reader in the area of cloud computing.
The main characteristics of Python are:
1) Multi-paradigm programminglanguage.
2) Python supports more than one programming paradigms including object- oriented programming
and structured programming.
3) InterpretedLanguage.
5) The Python interpreter executes the program source code directly, statement by statement, as a
processor or scripting engine does.
6) Interactive Language
7) Python provides an interactive mode in which the user can submit commands at the Python
prompt and interact with the interpreterdirectly.
Python Benefits
Python – Setup
Datatypes
Every value in Python has a datatype. Since everything is an object in Python programming, data
types are actually classes and variables are instance (object) of these classes.
There are various data types in Python. Some of the important types are listed below.
Python Numbers
Integers, floating point numbers and complex numbers falls under Python numbers category. They
are defined as int, float and complex class in Python. We can use the type() function to know which
class a variable or a value belongs to and the isinstance() function to check if an object belongs to a
particular class.
Script.py
1. a = 5
2. print(a, "is of type", type(a)) 3. a = 2.0
4. print(a, "is of type", type(a)) 5. a = 1+2j
6. print(a, "is complex number?", isinstance(1+2j,complex))
Integers can be of any length, it is only limited by the memory available. A floating point number is
accurate up to 15 decimal places. Integer and floating points are separated by decimal points. 1 is
integer, 1.0 is floating point number. Complex numbers are written in the form, x + yj, where x is the
real part and y is the imaginary part. Here are someexamples.
>>> a = 1234567890123456789
>>> a 1234567890123456789
>>> b = 0.1234567890123456789
>>> b 0.12345678901234568
>>> c = 1+2j
>>> c (1+2j)
List is an ordered sequence of items. It is one of the most used datatype in Python and is very
flexible. All the items in a list do not need to be of the same type. Declaring a list is pretty straight
forward. Items separated by commas are enclosed within brackets [].
>>> a = [1, 2.2, 'python']
We can use the slicing operator [ ] to extract an item or a range of items from a list. Index starts
form 0 in Python.
Script.py
1. a = [5,10,15,20,25,30,35,40]
2. # a[2] = 15
3. print("a[2] = ", a[2])
4. # a[0:3] = [5, 10, 15]
5. print("a[0:3] = ", a[0:3])
6. # a[5:] = [30, 35, 40]
7. print("a[5:] = ", a[5:])
Lists are mutable, meaning; value of elements of a list can be altered.
>>> a = [1,2,3]
>>> a[2]=4
>>> a [1, 2, 4]
Python Tuple
Tuple is an ordered sequences of items same as list. The only difference is that tuples are immutable.
Tuples once created cannot be modified. Tuples are used to write-protect data and are usually faster
than list as it cannot change dynamically. It is defined within parentheses () where items are
separated bycommas.
>>> t = (5,'program', 1+3j)
Script.py
Python Strings
String is sequence of Unicode characters. We can use single quotes or double quotes to represent
strings. Multi-line strings can be denoted using triple quotes, ''' or """.
>>> s = "This is a string"
>>> s = '''a multiline
Like list and tuple, slicing operator [ ] can be used with string. Strings are immutable.
Script.py
a ={5,2,3,1,4}
# printing setvariable print("a = ", a)
# data type of variable a print(type(a))
We can perform set operations like union, intersection on two sets. Set have unique values. They
eliminate duplicates. Since, set are unordered collection, indexing has no meaning. Hence the
slicing operator [] does not work. It is generally used when we have a huge amount of data.
Dictionaries are optimized for retrieving data. We must know the key to retrieve the value. In
Python, dictionaries are defined within braces {} with each item being a pair in the form key:value.
Key and value can be of anytype.
>>> d = {1:'value','key':2}
>>> type(d)
<class 'dict'>
We use key to retrieve the respective value. But not the other way around.
Script.py
else:
Body of else
The if..else statement evaluates test expression and will execute body of if only when test condition
is True.
If the condition is False, body of else is executed. Indentation is used to separate the blocks.
Python if..else Flowchart
Example of
Example of if...else
# Program checks if the number is positive or negative # And displays an appropriate message
num = 3
# Try these two variations as well. # num = -5
# num = 0
if num >= 0: print("Positive or Zero")
else:
print("Negative number")
In the above example, when num is equal to 3, the test expression is true and body of if is executed
and body of else is skipped.
If num is equal to -5, the test expression is false and body of else is executed and body of if is
skipped.
If num is equal to 0, the test expression is true and body of if is executed and body of else is
skipped.
Flowchart of if...elif...else
Example of if...elif...else
# In this program,
# we check if the number is positive or # negative or zero and
# display an appropriate message num = 3.4
# Try these two variations as well: # num = 0
# num = -4.5 if num > 0:
print("Positive number") elif num == 0:
print("Zero") else:
print("Negative number")
When variable num is positive, Positive number is printed. If num is equal to 0, Zero is printed.
If num is negative, Negative number is printed
Python Nested if statements
We can have a if...elif...else statement inside another if...elif...else statement. This is called nesting
in computer programming. Any number of these statements can be nested inside one another.
Indentation is the only way to figure out the level of nesting. This can get confusing, so must be
avoided if we can.
# Output: [2, 3, 4, 5, 6, 7]
print(list(range(2, 8)))
# Output: [2, 5, 8, 11, 14, 17]
print(list(range(2, 20, 3)))
We can use the range() function in for loops to iterate through a sequence of numbers. It can be
combined with the len() function to iterate though a sequence using indexing. Here is an example.
# Program to iterate through a list using indexing genre = ['pop', 'rock', 'jazz']
# iterate over the list using index for i in range(len(genre)):
print("I like", genre[i])
When you run the program, the output will be: I likepop
I likerock I likejazz
What is while loop in Python?
The while loop in Python is used to iterate over a block of code as long as the test expression (condition)
is true. We generally use this loop when we don't know beforehand, the number of times to iterate.
Syntax of while Loop in Python
while test_expression: Body of while
In while loop, test expression is checked first. The body of the loop is entered only if the test_expression
evaluates to True. After one iteration, the test expression is checked again. This process continues until
the test_expression evaluates to False. In Python, the body of the while loop is determined through
indentation. Body starts with indentation and the first unindented line marks the end. Python interprets
any non-zero value as True. None and 0 are interpreted asFalse.
Flowchart of while Loop
# Program to add natural # numbers upto
# sum = 1+2+3+...+n
# To take input from the user, # n = int(input("Enter n: "))
n = 10
# initialize sum and counter sum = 0
i=1
while i <= n: sum = sum + i
x = dir(platform) print(x)
Note: The dir() function can be used on all modules, also the ones you create yourself.
Import from Module
You can choose to import only parts from a module, by using the from keyword.
Example
The module named mymodule has one function and one dictionary: def greeting(name):
print("Hello, " + name)
person1 = {"name": "John", "age": 36, "country": "Norway"}
Example
Import only the person1 dictionary from the module: from mymodule import person1
print (person1["age"])
Note: When importing using the from keyword, do not use the module name when referring to
elements in the module. Example: person1["age"], not mymodule.person1["age"].
Packages
We don't usually store all of our files in our computer in the same location. We use a well- organized
hierarchy of directories for easier access. Similar files are kept in the same directory, for example, we
may keep all the songs in the "music" directory. Analogous to this, Python has packages for
directories and modules for files. As our application program grows larger in size with a lot of
modules, we place similar modules in one package and different modules in different packages. This
makes a project (program) easy to manage and conceptuallyclear.
Similar, as a directory can contain sub-directories and files, a Python package can have sub-
packages and modules. A directory must contain a file namedinit.py in order for Python to consider it
as a package. This file can be left empty but we generally place the initialization code for that
package in this file. Here is an example. Suppose we are developing a game, one possible
organization of packages and modules could be as shown in the figure below.
Package Module Structure in Python Programming Importing module from a package
We can import modules from packages using the dot (.) operator. For example, if want to import
the start module in the above example, it is done as follows.
import Game.Level.start
Now if this module contains a function named select_difficulty(), we must use the full name to
reference it.
Game.Level.start.select_difficulty(2)
If this construct seems lengthy, we can import the module without the package prefix as follows.
from Game.Level import start
We can now call the function simply as follows. start.select_difficulty(2)
Yet another way of importing just the required function (or class or variable) form a module within a
package would be as follows.
from Game.Level.start import select_difficulty Now we can directly call this function.
select_difficulty(2)
Although easier, this method is not recommended. Using the full namespace avoids confusion and
prevents two same identifier names from colliding. While importing packages, Python looks in the
list of directories defined in sys.path, similar as for module search path.
Files
File is a named location on disk to store related information. It is used to permanently store data in a
non-volatile memory (e.g. hard disk). Since, random access memory (RAM) is volatile which loses
its data when computer is turned off, we use files for future use of the data. When we want to read
from or write to a file we need to open it first. When we are done, it needs to be closed, so that
resources that are tied with the file are freed. Hence, in Python, a file operation takes place in the
followingorder.
1. Open afile
'This'
>>>f.read(4) # read the next 4 data ' is'
>>>f.read() # read in the rest till end of file 'my first file\nThis file\ncontains threelines\n'
>>> f.read() # further reading returns empty sting ''
We can see that, the read() method returns newline as '\n'. Once the end of file is reached, we get
empty string on further reading. We can change our current file cursor (position) using the seek()
method. Similarly, the tell() method returns our current position (in number of bytes).
>>>f.tell() # get the current file position 56
>>> f.seek(0) # bring file cursor to initial position 0
>>> print(f.read()) # read the entire file This is my first file
This file
contains three lines
We can read a file line-by-line using a for loop. This is both efficient and fast.
>>> for line in f:
... print(line, end = '')
...
This is my first file This file
contains three lines
The lines in file itself has a newline character '\n'.
Moreover, the print() end parameter to avoid two newlines when printing. Alternately, we can use
readline() method to read individual lines of a file. This method reads a file till the newline, including
the newlinecharacter.
>>> f.readline()
'This is my first file\n'
>>> f.readline() 'This file\n'