Download as pdf or txt
Download as pdf or txt
You are on page 1of 51

Fundamentals Of Internet Of Things

-Md.Umalawara

UNIT III

Introduction to Python programming, Introduction to Raspberry Pi, Interfacing


Raspberry Pi with basic peripherals, Implementation of IOT with Raspberry Pi.

What is python?

Python is a general purpose,dynamic,high-level,interpreted programming language.it supports object


oriented programming approach to develop applications.it is easy to learn and provides lots of high-level data
structures.
python was introduced by “Guido Van Rossum” In 1970s.

Features in Python:
There are many features in Python, some of which are discussed below as follows:
1. Free and Open Source
Python language is freely available at the official website and you can download it from the given download
link below click on the Download Python keyword. Download Python Since it is open-source, this means
that source code is also available to the public. So you can download it, use it as well as share it.
2. Easy to code
Python is a high-level programming language. Python is very easy to learn the language as compared to other
languages like C, C#, Javascript, Java, etc. It is very easy to code in the Python language and anybody can
learn Python basics in a few hours or days. It is also a developer-friendly language.
3. Easy to Read
As you will see, learning Python is quite simple. As was already established, Python‟s syntax is really
straightforward. The code block is defined by the indentations rather than by semicolons or brackets.
4. Object-Oriented Language
One of the key features of Python is Object-Oriented programming. Python supports object-oriented language
and concepts of classes, object encapsulation, etc.
5. GUI Programming Support
Graphical User interfaces can be made using a module such as PyQt5, PyQt4, wxPython, or Tk in python.
PyQt5 is the most popular option for creating graphical apps with Python.
6. High-Level Language
Python is a high-level language. When we write programs in Python, we do not need to remember the system
architecture, nor do we need to manage the memory.
7. Extensible feature
Python is an Extensible language. We can write some Python code into C or C++ language and also we can
compile that code in C/C++ language.
8. Easy to Debug:Excellent information for mistake tracing. You will be able to quickly identify and correct
the majority of your program‟s issues once you understand how to interpret Python‟s error traces. Simply by
glancing at the code, you can determine what it is designed to perform.
9. Python is a Portable language
Python language is also a portable language. For example, if we have Python code for windows and if we
want to run this code on other platforms such as Linux, Unix, and Mac then we do not need to change it, we
can run this code on any platform.
10. Python is an Integrated language
Python is also an Integrated language because we can easily integrate Python with other languages like
C, C++, etc.
11. Interpreted Language:
Python is an Interpreted Language because Python code is executed line by line at a time. like other languages
C, C++, Java, etc. there is no need to compile Python code this makes it easier to debug our code. The source
code of Python is converted into an immediate form called bytecode.
12. Large Standard Library
Python has a large standard library that provides a rich set of modules and functions so you do not have to
write your own code for every single thing. There are many libraries present in Python such as regular
expressions, unit-testing, web browsers, etc.
13. Dynamically Typed Language
Python is a dynamically-typed language. That means the type (for example- int, double, long, etc.) for a
variable is decided at run time not in advance because of this feature we don‟t need to specify the type of
variable.
14. Frontend and backend development
With a new project py script, you can run and write Python codes in HTML with the help of some simple tags
<py-script>, <py-env>, etc. This will help you do frontend development work in Python like javascript.
Backend is the strong forte of Python it‟s extensively used for this work cause of its frameworks
like Django and Flask.

15. Allocating Memory Dynamically

In Python, the variable data type does not need to be specified. The memory is automatically allocated to a
variable at runtime when it is given a value. Developers do not need to write int y = 18 if the integer value 15
is set to y. You may just type y=18.

Python Variables
Variable is a name that is used to refer to memory location .
A python varible is also known as an identifier and used to hold value.

Python Variable declaration


Variablename=value;
Ex:a=5;
Python programs
EX-1
Print(“sritw”);
o/p
sritw
EX-2
a=10;
Print(a);
o/p
10
EX-3
a=10;
b=20;
Print(a+b);
o/p
30
Python datatypes
Data types are the classification or categorization of data items. It represents the kind of value that tells what
operations can be performed on a particular data. Since everything is an object in Python programming, data
types are actually classes and variables are instances (object) of these classes. The following are the standard
or built-in data types in Python:
 Numeric
 Sequence Type
 Boolean
 Set
 Dictionary
 Binary Types( memoryview, bytearray, bytes)

What is Python type() Function?


To define the values of various data types and check their data types we use the type() function. Consider the
following examples.
 Python3

# DataType Output: str


x = "Hello World"

# DataType Output: int


x = 50

# DataType Output: float


x = 60.5

# DataType Output: complex


x = 3j
# DataType Output: list
x = ["geeks", "for", "geeks"]

# DataType Output: tuple


x = ("geeks", "for", "geeks")

# DataType Output: range


x = range(10)

# DataType Output: dict


x = {"name": "Suraj", "age": 24}

# DataType Output: set


x = {"geeks", "for", "geeks"}

# DataType Output: frozenset


x = frozenset({"geeks", "for", "geeks"})

# DataType Output: bool


x = True

# DataType Output: bytes


x = b"Geeks"

# DataType Output: bytearray


x = bytearray(4)

# DataType Output: memoryview


x = memoryview(bytes(6))

# DataType Output: NoneType


x = None

1.Numeric Data Type in Python


The numeric data type in Python represents the data that has a numeric value. A numeric value can be an
integer, a floating number, or even a complex number. These values are defined as Python int, Python float,
and Python complex classes in Python.
 Integers – This value is represented by int class. It contains positive or negative whole numbers
(without fractions or decimals). In Python, there is no limit to how long an integer value can be.
 Float – This value is represented by the float class. It is a real number with a floating-point
representation. It is specified by a decimal point. Optionally, the character e or E followed by a
positive or negative integer may be appended to specify scientific notation.
 Complex Numbers – Complex number is represented by a complex class. It is specified as (real
part) + (imaginary part)j. For example – 2+3j
Note – type() function is used to determine the type of data type.
 Python3

# Python program to
# demonstrate numeric value
a=5
print("Type of a: ", type(a))

b = 5.0
print("\nType of b: ", type(b))

c = 2 + 4j
print("\nType of c: ", type(c))

Output:
Type of a: <class 'int'>

Type of b: <class 'float'>

Type of c: <class 'complex'>

2.Sequence Data Type in Python


The sequence Data Type in Python is the ordered collection of similar or different data types. Sequences allow
storing of multiple values in an organized and efficient fashion. There are several sequence types in Python –
 Python String
 Python List
 Python Tuple

String Data Type

Strings in Python are arrays of bytes representing Unicode characters. A string is a collection of one or more
characters put in a single quote, double-quote, or triple-quote. In python there is no character data type, a
character is a string of length one. It is represented by str class.
Creating String
Strings in Python can be created using single quotes or double quotes or even triple quotes.

 Python3

# Python Program for


# Creation of String

# Creating a String
# with single Quotes
String1 = 'Welcome to the World'
print("String with the use of Single Quotes: ")
print(String1)

# Creating a String
# with double Quotes
String1 = "I'm a aruna"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1)

Output:
String with the use of Single Quotes:
Welcome to the World

String with the use of Double Quotes:


I'm a aruna

List Data Type


Lists are just like arrays, declared in other languages which is an ordered collection of data. It is very flexible
as the items in a list do not need to be of the same type.
Creating List
Lists in Python can be created by just placing the sequence inside the square brackets[].

 Python3

# Creating a List
List = []
print("Initial blank List: ")
print(List)

# Creating a List with


# the use of a String
List = ['GeeksForGeeks']
print("\nList with the use of String: ")
print(List)

# Creating a List with


# the use of multiple values
List = ["Geeks", "For", "Geeks"]
print("\nList containing multiple values: ")
print(List[0])
print(List[2]st)

Output:
Initial blank List:
[]
List with the use of String:
['GeeksForGeeks']
List containing multiple values:
Geeks
Geeks
Python Access List Items
In order to access the list items refer to the index number. Use the index operator [ ] to access an item in a list.
In Python, negative sequence indexes represent positions from the end of the array. Instead of having to
compute the offset as in List[len(List)-3], it is enough to just write List[-3]. Negative indexing means
beginning from the end, -1 refers to the last item, -2 refers to the second-last item, etc.

 Python3

# Python program to demonstrate


# accessing of element from list

# Creating a List with


# the use of multiple values
List = ["Geeks", "For", "Geeks"]

# accessing a element from the


# list using index number
print("Accessing element from the list")
print(List[0])
print(List[2])

# accessing a element using


# negative indexing
print("Accessing element using negative indexing")

# print the last element of list


print(List[-1])

# print the third last element of list


print(List[-3])

Output:
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks
Note – To know more about Lists, refer to Python List.

Tuple Data Type

Just like a list, a tuple is also an ordered collection of Python objects. The only difference between a tuple and
a list is that tuples are immutable i.e. tuples cannot be modified after it is created. It is represented by a tuple
class.
Creating a Tuple
In Python, tuples are created by placing a sequence of values separated by a „comma‟ with or without the use
of parentheses for grouping the data sequence. Tuples can contain any number of elements and of any
datatype (like strings, integers, lists, etc.). Note: Tuples can also be created with a single element, but it is a
bit tricky. Having one element in the parentheses is not sufficient, there must be a trailing „comma‟ to make it
a tuple.
 Python3

# Creating an empty tuple


Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)

# Creating a Tuple with


# the use of Strings
Tuple1 = ('Geeks', 'For')
print("\nTuple with the use of String: ")
print(Tuple1)

# Creating a Tuple with


# the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))

# Creating a Tuple with the


# use of built-in function
Tuple1 = tuple('Geeks')
print("\nTuple with the use of function: ")
print(Tuple1)

# Creating a Tuple
# with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'geek')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)

Output:
Initial empty Tuple:
()

Tuple with the use of String:


('Geeks', 'For')

Tuple using List:


(1, 2, 4, 5, 6)

Tuple with the use of function:


('G', 'e', 'e', 'k', 's')
Tuple with nested tuples:
((0, 1, 2, 3), ('python', 'geek'))
Note – The creation of a Python tuple without the use of parentheses is known as Tuple Packing.
Access Tuple Items
In order to access the tuple items refer to the index number. Use the index operator [ ] to access an item in a
tuple. The index must be an integer. Nested tuples are accessed using nested indexing.

 Python3

# Python program to
# demonstrate accessing tuple

tuple1 = tuple([1, 2, 3, 4, 5])

# Accessing element using indexing


print("First element of tuple")
print(tuple1[0])

# Accessing element from last


# negative indexing
print("\nLast element of tuple")
print(tuple1[-1])

print("\nThird last element of tuple")


print(tuple1[-3])

Output:
First element of tuple
1

Last element of tuple


5

Third last element of tuple


3
Note – To know more about tuples, refer to Python Tuples.
Boolean Data Type in Python
Data type with one of the two built-in values, True or False. Boolean objects that are equal to True are truthy
(true), and those equal to False are falsy (false). But non-Boolean objects can be evaluated in a Boolean
context as well and determined to be true or false. It is denoted by the class bool.
Note – True and False with capital „T‟ and „F‟ are valid booleans otherwise python will throw an error.
 Python3

# Python program to
# demonstrate boolean type

print(type(True))
print(type(False))

print(type(true))

Output:
<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8, in
print(type(true))
NameError: name 'true' is not defined

Set Data Type in Python


In Python, a Set is an unordered collection of data types that is iterable, mutable and has no duplicate
elements. The order of elements in a set is undefined though it may consist of various elements.
Create a Set in Python
Sets can be created by using the built-in set() function with an iterable object or a sequence by placing the
sequence inside curly braces, separated by a „comma‟. The type of elements in a set need not be the same,
various mixed-up data type values can also be passed to the set.

 Python3

# Python program to demonstrate


# Creation of Set in Python

# Creating a Set
set1 = set()
print("Initial blank Set: ")
print(set1)

# Creating a Set with


# the use of a String
set1 = set("GeeksForGeeks")
print("\nSet with the use of String: ")
print(set1)

# Creating a Set with


# the use of a List
set1 = set(["Geeks", "For", "Geeks"])
print("\nSet with the use of List: ")
print(set1)

# Creating a Set with


# a mixed type of values
# (Having numbers and strings)
set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks'])
print("\nSet with the use of Mixed Values")
print(set1)

Output:
Initial blank Set:
set()

Set with the use of String:


{'F', 'o', 'G', 's', 'r', 'k', 'e'}

Set with the use of List:


{'Geeks', 'For'}

Set with the use of Mixed Values


{1, 2, 4, 6, 'Geeks', 'For'}
Access Set Items
Set items cannot be accessed by referring to an index, since sets are unordered the items has no index. But you
can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in
the keyword.

 Python3

# Python program to demonstrate


# Accessing of elements in a set

# Creating a set
set1 = set(["Geeks", "For", "Geeks"])
print("\nInitial set")
print(set1)

# Accessing element using


# for loop
print("\nElements of set: ")
for i in set1:
print(i, end=" ")

# Checking the element


# using in keyword
print("Geeks" in set1)

Output:
Initial set:
{'Geeks', 'For'}
Elements of set:
Geeks For

True
Note – To know more about sets, refer to Python Sets.
Dictionary Data Type in Python
A dictionary in Python is an unordered collection of data values, used to store data values like a map, unlike
other Data Types that hold only a single value as an element, a Dictionary holds a key: value pair. Key-value
is provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary is separated by a
colon : , whereas each key is separated by a „comma‟.
Create a Dictionary
In Python, a Dictionary can be created by placing a sequence of elements within curly {} braces, separated by
„comma‟. Values in a dictionary can be of any datatype and can be duplicated, whereas keys can‟t be repeated
and must be immutable. The dictionary can also be created by the built-in function dict(). An empty dictionary
can be created by just placing it in curly braces{}. Note – Dictionary keys are case sensitive, the same name
but different cases of Key will be treated distinctly.
 Python3

# Creating an empty Dictionary


Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)

# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)

# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)

# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)

Output:
Empty Dictionary:
{}

Dictionary with the use of Integer Keys:


{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with the use of Mixed Keys:


{1: [1, 2, 3, 4], 'Name': 'Geeks'}

Dictionary with the use of dict():


{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with each item as a pair:


{1: 'Geeks', 2: 'For'}
Accessing Key-value in Dictionary
In order to access the items of a dictionary refer to its key name. Key can be used inside square brackets.
There is also a method called get() that will also help in accessing the element from a dictionary.

 Python3

# Python program to demonstrate


# accessing a element from a Dictionary

# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# accessing a element using key


print("Accessing a element using key:")
print(Dict['name'])

# accessing a element using get()


# method
print("Accessing a element using get:")
print(Dict.get(3))

Output:
Accessing a element using key:
For
Accessing a element using get:
Geeks
Python Keywords:
Introduction
Keywords in Python are reserved words that can not be used as a variable name, function name, or any
other identifier.
List of all keywords in Python
and as assert break

class continue def del

elif else except False

finally for from global

if import in is

lambda None nonlocal not

or pass raise return

True try while with

yield

We can also get all the keyword names using the below code.

Example: Python Keywords List

 Python3

# Python code to demonstrate working of iskeyword()

# importing "keyword" for keyword operations


import keyword

# printing all keywords at once using "kwlist()"


print("The list of keywords is : ")
print(keyword.kwlist)

Output
The list of keywords is :
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else' ,
'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise',
'return', 'try', 'while', 'with', 'yield']
Output:
The list of keywords is :
[‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘async’, ‘await’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’,
‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’,
‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]
Control Structures in Python

Control flow refers to the sequence a program will follow during its execution.
Conditions, loops, and calling functions significantly influence how a Python program is controlled.
There are three types of control structures in Python:
1.Sequential - The default working of a program
2.Selection - This structure is used for making decisions by checking conditions and branching
3.Repetition - This structure is used for looping, i.e., repeatedly executing a certain piece of a code
block.
1.Sequential

Sequential statements are a set of statements whose execution process happens in a sequence. The problem
with sequential statements is that if the logic has broken in any one of the lines, then the complete source code
execution will break.
Code
# Python program to show how a sequential control structure works

# We will initialize some variables


# Then operations will be done
# And, at last, results will be printed
# Execution flow will be the same as the code is written, and there is no hidden flow
a = 20
b = 10
c=a-b
d=a+b
e=a*b
print("The result of the subtraction is: ", c)
print("The result of the addition is: ", d)
print("The result of the multiplication is: ", e)
Output:

The result of the subtraction is: 10


The result of the addition is :
30
The result of the multiplication is: 200
2.Selection/Decision Control Statements
The statements used in selection control structures are also referred to as branching statements or, as their
fundamental role is to make decisions, decision control statements.

A program can test many conditions using these selection statements, and depending on whether the given
condition is true or not, it can execute different code blocks.

There can be many forms of decision control structures. Here are some most commonly used control
structures:
1. Only if
2. if-else
3. The nested if
4. The complete if-elif-else
1.Simple if:
If statements in Python are called control flow statements. The selection statements assist us in running a
certain piece of code, but only in certain circumstances. There is only one condition to test in a basic if
statement.
The if statement's fundamental structure is as follows:
Syntax
if <conditional expression> :
The code block to be executed if the condition is True
These statements will always be executed. They are part of the main code.

All the statements written indented after the if statement will run if the condition giver after the if the keyword
is True. Only the code statement that will always be executed regardless of the if the condition is the statement
written aligned to the main code. Python uses these types of indentations to identify a code block of a
particular control flow statement. The specified control structure will alter the flow of only those indented
statements.

Here are a few instances:


Code
# Python program to show how a simple if keyword works

# Initializing some variables


v=5
t=4
print("The initial value of v is", v, "and that of t is ",t)

# Creating a selection control structure


if v > t :
print(v, "is bigger than ", t)
v -= 2

print("The new value of v is", v, "and the t is ",t)

# Creating the second control structure


if v < t :
print(v , "is smaller than ", t)
v += 1

print("the new value of v is ", v)

# Creating the third control structure


if v == t:
print("The value of v, ", v, " and t,", t, ", are equal")
Output:
The initial value of v is 5 and that of t is 4
5 is bigger than 4
The new value of v is 3 and the t is 4
3 is smaller than 4
the new value of v is
4
The value of v,
4 and t, 4, are equal

2.if-else:
If the condition given in if is False, the if-else block will perform the code t=given in the else block.
Code
# Python program to show how to use the if-else control structure

# Initializing two variables


v=4
t=5
print("The value of v is ", v, "and that of t is ", t)

# Checking the condition


if v > t :
print("v is greater than t")
# Giving the instructions to perform if the if condition is not true
else :
print("v is less than t")
Output:

The value of v is 4 and that of t is 5


v is less than t

3.Repetition/Iterative control structure:

To repeat a certain set of statements, we use the repetition structure.

There are generally two loop statements to implement the repetition structure:

1. The for loop


2. The while loop
1.For Loop:
We use a for loop to iterate over an iterable Python sequence. Examples of these data structures are lists,
strings, tuples, dictionaries, etc. Under the for loop code block, we write the commands we want to execute
repeatedly for each sequence item.

Code

# Python program to show how to execute a for loop

# Creating a sequence. In this case, a list


l = [2, 4, 7, 1, 6, 4]

# Executing the for loops


for i in range(len(l)):
print(l[i], end = ", ")
print("\n")
for j in range(0,10):
print(j, end = ", ")
Output:
2, 4, 7, 1, 6, 4,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
2.While Loop:
While loops are also used to execute a certain code block repeatedly, the difference is that loops continue to
work until a given precondition is satisfied. The expression is checked before each execution. Once the
condition results in Boolean False, the loop stops the iteration.

Code
# Python program to show how to execute a while loop
b=9
a=2
# Starting the while loop
# The condition a < b will be checked before each iteration
while a < b:
print(a, end = " ")
a=a+1
print("While loop is completed")
Output:

2 3 4 5 6 7 8 While loop is completed

Python Loop Control Statements:(continue,break,pass)

Loop control statements change execution from their normal sequence. When execution leaves a scope, all
automatic objects that were created in that scope are destroyed. Python supports the following control
statements.
1. Break – Terminates from the loop
2. Continue- It skips the current iteration ececution
3. Pass- Body of the loop is empty

Python Continue
It returns the control to the beginning of the loop.

 Python3

# Prints all letters except 'e' and 's'


for letter in 'geeksforgeeks':
if letter == 'e' or letter == 's':
continue
print('Current Letter :', letter)

Output:
Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k
Python Break
It brings control out of the loop.

 Python3

for letter in 'geeksforgeeks':

# break the loop as soon it sees 'e'


# or 's'
if letter == 'e' or letter == 's':
break
print('Current Letter :', letter)

Output:
Current Letter :

3.Python pass Statement


The pass statement is used as a placeholder for future code. When the pass statement is executed, nothing
happens, but you avoid getting an error when empty code is not allowed. Empty code is not allowed in loops,
function definitions, class definitions, or in if statements.
Example: if(condition): python
Pass

Loops in Python

Python programming language provides the following types of loops to handle looping requirements.
Python While Loop
Until a specified criterion is true, a block of statements will be continuously executed in a Python while loop.
And the line in the program that follows the loop is run when the condition changes to false.

Syntax of Python While

while expression:
statement(s)
In Python, all the statements indented by the same number of character spaces after a programming construct
are considered to be part of a single block of code. Python uses indentation as its method of grouping
statements.

 Python3
# prints Hello Geek 3 Times
count = 0
while (count < 3):
count = count+1
print("Hello")

Output:
Hello
Hello
Hello
See this for an example where a while loop is used for iterators. As mentioned in the article, it is not
recommended to use a while loop for iterators in python.

Python for Loop


In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is a “for in” loop which is similar to for
each loop in other languages.

Syntax of Python for Loop

for iterator_var in sequence:


statements(s)
It can be used to iterate over iterators and a range.

 Python3

# Iterating over a list


print("List Iteration")
l = ["geeks", "for", "geeks"]
for i in l:
print(i)

# Iterating over a tuple (immutable)


print("\nTuple Iteration")
t = ("geeks", "for", "geeks")
for i in t:
print(i)

# Iterating over a String


print("\nString Iteration")
s = "Geeks"
for i in s :
print(i)

# Iterating over dictionary


print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d :
print("%s %d" %(i, d[i]))

Output:
List Iteration
geeks
for
geeks

Tuple Iteration
geeks
for
geeks

String Iteration
G
e
e
k
s

Dictionary Iteration
xyz 123
abc 345
Time complexity: O(n), where n is the number of elements in the iterable (list, tuple, string, or dictionary).
Auxiliary space: O(1), as the space used by the program does not depend on the size of the iterable.
We can use a for-in loop for user-defined iterators. See this for example.

Python Nested Loops

Python programming language allows using one loop inside another loop. The following section shows a few
examples to illustrate the concept.

Syntax of Python Nested for Loop

The syntax for a nested for loop statement in Python programming language is as follows:
for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)
Syntax of Python Nested while Loop

The syntax for a nested while loop statement in Python programming language is as follows:
while expression:
while expression:
statement(s)
statement(s)
A final note on loop nesting is that we can put any type of loop inside of any other type of loop. For example,
a for loop can be inside a while loop or vice versa.

 Python3

from __future__ import print_function


for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()

Output:
1
22
333
4444
Introduction to raspberry pi

What is a Raspberry Pi?

Raspberry pi is the name of the “credit card-sized computer board” developed by the Raspberry pi
foundation, based in the U.K. It gets plugged in a TV or monitor and provides a fully functional computer
capability. It is aimed at imparting knowledge about computing to even younger students at the cheapest
possible price. Although it is aimed at teaching computing to kids, but can be used by everyone willing to
learn programming, the basics of computing, and building different projects by utilizing its versatility.
Raspberry Pi is developed by Raspberry Pi Foundation in the United Kingdom. The Raspberry Pi is a series
of powerful, small single-board computers.
Raspberry Pi is launched in 2012 and there have been several iterations and variations released since then.
Various versions of Raspberry Pi have been out till date. All versions consist of a Broadcom system on a
chip (SoC) with an integrated ARM-compatible CPU and on-chip graphics processing unit (GPU).
The original device had a single-core Processor speed of device ranges from 700 MHz to 1.2 GHz and a
memory range from 256 MB to 1 GB RAM.
To store the operating system and program memory Secure Digital (SD) cards are used. Raspbian OS which
is a Linux operating system is recommended OS by Raspberry Pi Foundation. Some other third party
operating systems like RISC OS Pi. Diet Pi, Kali, Linux can also be run on Raspberry Pi.

Used:
It also provides a set of general purpose input/output pins allowing you to control electronic components for
physical computing and explore the Internet of Things (IOT).
Raspberry pi Diagram :
Raspberry Pi model –

There have been many generations of raspberry Pi from Pi 1 to Pi 4.


There is generally a model A and model B.
Model A is a less expensive variant and it trends to have reduce RAM and dual cores such as
USB and Ethernet.

List of Raspberry pi models and releases year:

1. pi 1 model B – 2012
2. pi 1 model A – 2013
3. pi 1 model B+ -2014
4. pi 1 model A+ – 2014
5. Pi 2 Model B – 2015
6. Pi 3 Model B- 2016
7. Pi 3 Model B+ -2018
8. Pi 3 Model A+ -2019
9. Pi 4 Model A – 2019
10. Pi Model B – 2020
11. Pi 400 – 2021

Specs of the Computer: – The computer has a quad-core ARM processor that doesn‟t support the same
instruction as an X86 desktop CPU. It has 1GB of RAM, One HDMI port, four USB ports, one Ethernet
connection, Micro SD slot for storage, one combined 3.5mm audio/video port, and a Bluetooth connection.
It has got a series of input and output pins that are used for making projects like – home security cameras,
Encrypted Door lock, etc.
Versatility of Raspberry Pi: – It is indeed a versatile computer and can be utilized by people from all age
groups, it can be used for watching videos on YouTube, watching movies, and programming in languages
like Python, Scratch, and many more. As mentioned above it has a series of I/O pins that give this board the
ability to interact with its environment and hence can be utilized to build really cool and interactive
projects.
Examples of projects: – It can be turned into a weather station by connecting some instruments to
it for check the temperature, wind speed, humidity etc… It can be turned into a home surveillance system
due to its small size; by adding some cameras to it the security network will be ready. If you love reading
books it can also become a storage device for storing thousands of eBooks and also you can access them
through the internet by using this device.

Conclusion: Concluding the article it is convenient to assert that it is a small and powerful computer at a
dirt-cheap rate and can handle most of the task as a desktop computer.
1.Computer in your palm.
2.Single-board computer.
3.Low cost.
4.Easy to access.

Specification :
Basic Architecture :

Features of Raspberry Pi:


 Raspberry Pi is a low-cost mini-computer with the physical size of a credit card.
• Raspberry Pi runs various flavors of Linux and can perform almost all tasks that a normal
desktop computer can do.
• Raspberry Pi also allows interfacing sensors and actuators through the general purpose I/O
pins.
• Since Raspberry Pi runs Linux operating system, it supports Python "out of the box".
The Raspberry Pi’s ports
The Raspberry Pi has a range of ports, starting with four Universal Serial Bus (USB) ports
(Figure 2) to the middle and right-hand side of the bottom edge. These ports let you connect
any USB-compatible peripheral, from keyboards and mice to digital cameras and flash drives,
to the Pi. Speaking technically, these are known as USB 2.0 ports, which means they are based
on version two of the Universal Serial Bus standard.

To the left of the USB ports is an Ethernet port, also known as a network port (Figure
above).You can use this port to connect the Raspberry Pi to a wired computer network using a
cable with what is known as an RJ45 connector on its end. If you look closely at the Ethernet
port, you„ll see two light-emitting diodes (LEDs) at the bottom; these are status LEDs, and let
you know that the connection is working. Just above the Ethernet port, on the left-hand edge
of the Raspberry Pi, is a 3.5 mm audio-visual (AV) jack (Figure 2). This is also known as the
headphone jack, and it can be used for that exact purpose – though you„ll get better sound
connecting it to amplified speakers rather than headphones. It has a hidden, extra feature,
though: as well as audio, the 3.5 mm AV jack carries a video signal which can be connected
to TVs, projectors, and other displays
-High-Definition Multimedia Interface (HDMI) port:
It is the same type of connector you„ll find on a games console, set-top box, and TV. The
multimedia part of its name tells you that it carries both audio and video signals, while high-
definition tells you that you can expect excellent quality. You„ll use this to connect the
Raspberry Pi to your display device, whether that„s a computer monitor, TV, or projector.

-Micro USB power port : which you„ll use to connect the Raspberry Pi to a power
source. The micro USB port is a common sight on smartphones, tablets, and other portable
devices. So you could use a standard mobile charger to power the Pi, but for best results you
should use the official Raspberry Pi USB Power Supply.
Basic Set up for Raspberry Pi

 HDMI cable
 Monitor.
 Key board
 Mouse
 5volt power adapter for raspberry pi.
 LAN cable
 Min - 2GB micro sd card
Operating System

Official Supported OS :
1. Raspbian
2. NOOBS
Some of the third party OS :
 UBUNTU mate
 Snappy Ubuntu core
 Windows 10 core
 Pinet
 Risc OS
Raspberry Pi Setup
Download Raspbian :
 Download latest Raspbian image from raspberry pi official site
: https://www.raspberrypi.org/downloads/
 Unzip the file and end up with an .img file.
Programming :
Default installed :
 Python
 C
 C++
 Java
 Scratch
 Ruby
Note : Any language that will compile for ARMv6 can be used with raspberry pi.
Applications of Rassberry pi:
1. Media streamer
2. Home automation
3. Controlling BOT
4. VPN
5. Light weight web server for IOT
6. Tablet computer
7. Desktop PC. Using Raspberry Pi, the microSD card, and a power supply, a simple desktop can be
made. ...
8. Wireless print server. ...
9. Media Usage. ...
10. Game Servers. ...
11. Retro Gaming Machine. ...
12. Robot Controller. ...
13. Stop Motion Camera. ...
14. Time-lapse CameraCCombiningge.

-Raspberry Pi‟s peripherals


A Raspberry Pi by itself can„t do very much, just the same as a desktop computer on its own is
little more than a door-stop. To work, the Raspberry Pi needs peripherals: at the minimum,
you„ll need a microSD card for storage; a monitor or TV so you can see what you„re doing; a
keyboard and mouse to tell the Pi what to do; and a 5 volt (5 V) micro USB power supply
rated at 2.5 amps (2.5 A) or better. With those, you„ve got yourself a fully functional
computer.
USB power supply: A power supply rated at 2.5 amps (2.5A) or 12.5 watts (12.5W) and with
a micro USB connector. The Official Raspberry Pi Power Supply is the recommended choice,
as it can cope with the quickly switching power demands of the Raspberry Pi.
Raspberry Pi General purpose Input/Output(GPIO)

The GPIO pins on the Raspberry Pi are divided into the


following groups:

1.Power: Pins that are labeled 5.0v supply 5 volts of power and those labeled 3V3 supply 3.3
volts of power. There are two 5V pins and two 3V3 pins.
2.GND: These are the ground pins. There are eight ground pins.
3.Input/Output pins: These are the pins labelled with the # sign, for example, #17, #27, #22,
etc. These pins can be used for input or output.
4.UART: The Universal Asynchronous Receiver/Transmitter allows your Raspberry Pi to be
connected to serial peripherals. The UART pins are labelled TXD and RXD.
5.SPI: The Serial Peripheral Interface is a synchronous serial communication interface
specification used for short distance communication, primarily in embedded systems. The SPI
pins are labeled MOSI, MISO, SCLK, CE0, and CE1.
 MISO(Master In Slave Out): Master line for sending data to the master.
 MOSI( Master Out Slave In): Slave line for sending data to the Peripherals.
 SCK( Serial Clock): Clock generated by master to synchronize data transmission.
 CE0( chip Enable 0): to enable or disable devices.
 CE1( chip Enable 1): to enable or disable devices.

6.ID EEPROM: Electrically Erasable Programmable Read-Only Memory is a user-


modifiable read-only memory that can be erased and written to repeatedly through the
application of higher than normal electrical voltage. The two EEPROM pins on the Raspberry
Pi (EED and EEC) are also secondary I2C ports that primarily facilitate the identification of
Pi Plates (e.g., Raspberry Pi Shields/Add-On Boards) that are directly attached to the Raspberry
Pi.SPI(Serial peripheral interface)
7.I2C (Inter Integrated chip)
The I2C interface pins on raspberry pi allow you to connect hardware modules. I2C interface
allow synchronous data transfer with two pins -SDA( data line) and SCL(clock line).
8.Serial
The serial interface on Raspberry Pi has receive (Rx) and Transmit (Tx) pins for communication
with serial periperals.

Interfacing Raspberry Pi with basic peripherals:


In this section you will learn how to get started with developing python programs on
Raspberry Pi. Raspberry Pi runs Linux and supports Python out of box. Therefore, you can
run any python program which runs on normal computer. However, it is the general purpose
input/output pins(GPIO) on Raspberry Pi that makes it useful for IoT. We can interface
Raspberry Pi with sensors and actuators with GPIO pins and SPI, I2C and serial interfaces.

1.Controlling LED with Raspberry Pi


Let us start with basic example of controlling an LED from Raspberry Pi. In this example the
LED is connected to GPIO pin 18. We can connect LED to other GPIO pin as well.
The program uses the RPi.GPIO module to control the GPIO on Raspberry Pi. In this
program we set pin 18 direction to output and then True/False alternatively after a delay of
one second.
To begin, we import the GPIO package that we will need so that we can communicate with
the GPIO pins. We also import the time package, so we„re
able to put the script to sleep for when we need to. We then set the GPIO mode to
GPIO.BOARD/GPIO.BCM, and this means all the numbering we use in this script will refer
to the physical numbering of the pins.
Program:
import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library
from timeimport sleep # Import the sleep function from the time module
GPIO.setmode(GPIO.BCM/BOARD) # Use physical pin numbering GPIO.setup(18,
GPIO.OUT) # Set pin 18 to be an output pin
while True: # Run forever
GPIO.output(18, GPIO.HIGH) # Turn on
sleep(1) # Sleep for 1 second
GPIO.output(18, GPIO.LOW) # Turn off
sleep(1) # Sleep for 1 second
2.Interfacing an LED and Switch with Raspberry Pi
In this example the LED is connected to GPIO pin 18 and the switch is connected to pin 13. In
the infinite while loop the value of pin 13 is checked and the state of LED is toggled if the switch
is pressed. This example shows how to get input from GPIO pins and process the input and
take some actions.
Program
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(13,GPIO.IN) #button
GPIO.setup(18,GPIO.OUT) #led
while True:
if (GPIO.input(13)):
print("on")
GPIO.output(18, GPIO.HIGH)
while False:
if (GPIO.input(13)):
print(―off‖)
GPIO.output(18, GPIO.LOW)
3.Interfacing Light Dependent Resistor (LDR) in Raspberry Pi:
This is code for interfacing LDR in Raspberry Pi. First of all, we have to import the Light
Sensor code for LDR from the GPIOZERO library. Assign GPIO pin to variable LDR and
also pass the GPIO pin number as an argument to the Light Sensor method. While loop
print„s value of LDR.
Program:
from gpiozero import LightSensor
LDR = LightSensor (4) # light sensor given to pin 4 while
True:
print(ldr.value)

4.Python program for switching LED based on LDR readings:


Since we only have one input/output pin, we only need to set one variable. Set this variable to
the number of the pin you have acting as the input/output pin. Next, we have a function called
rc_time that requires one parameter, which is the pin number to the circuit. In this function,
we initialize a variable called count, and we will return this value once the pin goes to high.
We then set our pin to act as an output and then set it to low. Next, we have the script sleep for
10ms.After this, we then set the pin to become an input, and then we enter a while loop. We
stay in this loop until the pin goes to high, this is when the capacitor charges to about
3/4.Once the pin goes high, we return the count value to the main function. You can use this
value to turn on and off an LED, activate something else, or log the data and keep statistics on
any variance in light.
Program:
import RPi.GPIO as GPIO import
time import sleep def rc_time
(pin_to_circuit):
count = 0
#Output on the pin for GPIO.setup(pin_to_circuit,
GPIO.OUT) GPIO.output(pin_to_circuit, GPIO.LOW)
sleep(1)
#Change the pin back to input
GPIO.setup(pin_to_circuit, GPIO.IN)
#Count until the pin goes high
while (GPIO.input(pin_to_circuit) == GPIO.LOW): count +=
1
return count

Implementation of IoT with Raspberry Pi

Why it is important for IoT:


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.

IoT has evolved from the meeting of wireless technologies, micro- electromechanical
systems (MEMS) and the internet. The Raspberry Pi is a popular choice when developing IoT
products. It offers a complete Linux server with a tiny platform at an incredibly low price.
Actually, the Raspberry Pi is so well-known to IoT that the company has featured several
Internet of Things projects on their site. Here you will find projects and community support
for a range of IoT activities.

Take for example, the World„s First Cloud Texting Enabled Espresso Machine –
powered by Raspberry Pi.Partnered with the Zipwhip cloud texting application, the Raspberry
Pi connects to an espresso machine and allows people to text a message to it that
automatically turns it on and starts brewing beverages. Raspberry Pi can be plugged into a
TV, computer monitor, and it uses a standard keyboard and mouse. It is user-friendly as it can
be handled by all the age groups.

It does everything you would expect a desktop computer to do like word-processing,


browsing the internet spreadsheets, playing games to playing high definition videos. It is used
in many applications like in a wide array of digital maker projects, music machines, parent
detectors to the weather station and tweeting birdhouses with infrared cameras. All models
feature on a Broadcom system on a chip (SOC), which includes chip graphics processing unit
GPU(a Video Core IV), an ARM-compatible and CPU.

The CPU speed ranges from 700 MHz to 1.2 GHz for the Pi 3 and onboard memory
range from 256 MB to 1 GB RAM. An operating system is stored in the secured digital SD
cards and program memory in either the Micro SDHC or SDHC sizes.

Most boards have one to four USB slots, composite video output, HDMI and a 3.5 mm
phone jack for audio. Some models have WiFi and Bluetooth.
Python program for using PIR sensor:

Connecting to a Sensor to Detect Motion


To demonstrate how to use the GPIO to connect to an external sensor, we'll now use a PIR
motion sensor to detect motion. For this, I used the Parallax PIR Motion Sensor (see fig). The
PIR Sensor detects motion by measuring changes in the infrared (heat) levels emitted by
surrounding objects of up to three meters.
The Parallax Motion sensor has three pins (see Figure ):

GND: The Ground pin. Connect this pin to the GND on the GPIO.
VCC: The voltage pin. Connect this pin to one of the 5V pins on the GPIO.
OUT: The output pin. Connect this to one of the Input/Output pins on the GPIO.

import RPi.GPIO as GPIO #1


import time #2
pirsensor = 4 #3
GPIO.setmode(GPIO.BCM) #4
GPIO.setup(pirsensor, GPIO.IN) #5

previous_state = False #6

current_state = False
while True: #7
time.sleep(0.1) #8
previous_state = current_state #9
current_state = GPIO.input(pirsensor) #10
if current_state != previous_state: #11
if current_state: #12
print("Motion not Detected!") #13

#1: The latest version of Raspbian includes the RPI.GPIO Python library pre- installed, so you
can simply import that into your Python code. The RPI.GPIO is a library that allows your
Python application to easily access the GPIO pins on your Raspberry Pi. The as keyword in
Python allows you to refer to the RPI.GPIO library using the shorter name of GPIO.

#2: The application is going to insert some delays in the execution, so you need to import the
time module.

#3: You declare a variable named pirsensor to indicate the pin number for which the Output
pin on the PIR sensor is connected to the GPIO pin. In this example, it's GPIO pin #4.

#4: There are two ways to refer to the pins on the GPIO: either by physical pin numbers
(starting from pin 1 to 40 on the Raspberry Pi 2/3), or Broadcom GPIO numbers (BCM).
Using BCM is very useful with a ribbon cable (such as the Adafruit T-Cobbler Plus) to
connect the Raspberry Pi to the breadboard. The BCM numbers refer to the labels printed on
the T- Cobbler Plus (see Figure 8). For this example, we're using the BCM numbering
scheme. That means that when we say we're getting the input from pin 4, we're referring to the
pin printed as #4 on the T-Cobbler Plus.

#5: Initialize the pin represented by the variable pin sensor as an input pin. Also, we use a pull-
down resistor (GPIO.PUD_DOWN) for this pin.

#6: There are two variables to keep track of the state of the sensor. #7: We use an infinite
loop to check the state of the sensor repeatedly. #8: Inserts a slight delay of 1 second to the
execution of the program #9: Save the current state of the sensor.

#10: The GPIO.input() function reads the value of the GPIO pin (#4 in this case). When
motion is detected, it returns a value of true.

#11: Compare the previous state and the current state to see if the motion sensor has a change
in state. If there's a change, it means that either the
sensor has just detected motion (when the state changes from false to true), or that the sensor is
resetting itself (when the state changes from true to false) a few seconds after motion has been
detected.

#12: If the current state is true, it means that motion has been detected. #13: Print out the
string ―Motion Detected!‖

DHT11 Temperature and Humidity Sensor and the Raspberry Pi


The DHT11 requires a specific protocol to be applied to the data pin. In order to save time
trying to implement this yourself it„s far easier to use the Adafruit DHT library. The library
deals with the data that needs to be exchanged with the sensor but it is sensitive to timing
issues. The Pi„s operating system may get in the way while performing other tasks so to
compensate for this the library requests a number of readings from the device until it gets one
that is valid.
program:
import RPi.GPIO as GPIO
import Adafruit_DHT

# Set sensor type : Options are DHT11,DHT22 or AM2302


sensor=Adafruit_DHT.DHT11
gpio=17
# Use read_retry method. This will retry up to 15 times to get a sensor reading (waiting 2
seconds between each retry).
humidity, temperature = Adafruit_DHT.read_retry(sensor, gpio)

# Reading the DHT11 is very sensitive to timings and occasionally the Pi might fail to get a
valid reading. So check if readings are valid.

if humidity is not None and temperature is not None:


print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity)) else:
print('Failed to get reading. Try again!')

The DHT11 is probably best suited for projects where rapid data readings are not required and
the environment is not expected to see sudden changes
in temperature or humidity. A
weather station would be an idea
project but a central heating controller may
require something different.
Motors programming:
Import RPi.GPIO
as GPIO from
gpiozero import
Motor
motor1 = Motor(4, 14) # to make it easier to see which pin is
which, you can use Motor(forward=4, backward=14) .
motor2 = Motor(17, 27) # forward=17,
backward =27 motor1.forward()
motor2.for
ward()
motor1.bac
kward()
motor2.bac
kward()
while True: # The Motor class also allows you to reverse the motor„s
direction.
sleep(5
)
motor1.r
everse()
motor2.r
everse()
motor1.stop() # Now stop the
motors motor2.stop()
Buzzer program:
from gpiozero import Button, Lights, buzzer.
buzzer = Buzzer(15)
while True: lights.on()
buzzer.on()
button.wait_for_press()
lights.off()
buzzer.off()
button.wait_for_release()

Traffic lights program:


from gpiozero import, Button,
TrafficLights from time import sleep
while True:
lights.green.on()
sleep(1)
lights.orange.on()
sleep(1)
lights.red.on()
sleep(1)
lights.off()
Add a wait_for_press so that pressing the button initiates the
sequence:
Try adding the button for a pedestrian crossing. The button should move the lights
to red (not immediately), and give the pedestrians time to cross before moving back
to green until the button is pressed again.

Program:
while True:
button.wait_for_press()
lights.green.on()
sleep(1)
lights.amber.on( )
sleep(1)
lights.red.on()
sleep(1)
lights.off()

You might also like